Add CLI
This commit is contained in:
parent
a5385612e1
commit
fcf0cd2d96
5 changed files with 146 additions and 56 deletions
31
src/main.rs
31
src/main.rs
|
@ -1,4 +1,5 @@
|
|||
extern crate anyhow;
|
||||
extern crate clap;
|
||||
|
||||
pub mod price_result;
|
||||
pub mod parser;
|
||||
|
@ -7,13 +8,33 @@ pub mod price_checker;
|
|||
use price_result::PriceResult;
|
||||
use price_checker::PriceChecker;
|
||||
use url::Url;
|
||||
use anyhow::{Context, Result};
|
||||
use anyhow::Result;
|
||||
use clap::{Arg, App, SubCommand};
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let price_checker = PriceChecker::new().context("Cannot create price checker")?;
|
||||
|
||||
let price_result = price_checker.get_price(Url::parse("https://www.darty.com/nav/achat/gros_electromenager/refrigerateur-congelateur-refrigerateur-cong/refrigerateur-congelateur_bas/samsung_rb33n300nsa_ef.html")?)?;
|
||||
println!("{}", price_result);
|
||||
let matches = App::new("Price checker")
|
||||
.version("0.1")
|
||||
.author("Rémi BERTHO <remi.bertho@dalan.fr>")
|
||||
.about("Check price")
|
||||
.subcommand(SubCommand::with_name("check")
|
||||
.about("Check from an URL")
|
||||
.arg(Arg::with_name("URL")
|
||||
.required(true)
|
||||
.multiple(true)
|
||||
.help("The URL to get price")))
|
||||
.get_matches();
|
||||
match matches.subcommand() {
|
||||
("check", Some(check_matches)) => {
|
||||
let price_checker = PriceChecker::new().unwrap();
|
||||
for url_str in check_matches.values_of("URL").unwrap() {
|
||||
let url = Url::parse(url_str)?;
|
||||
println!("{}", price_checker.get_price(url)?) ;
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
println!("{}", matches.usage());
|
||||
},
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
|
@ -28,10 +28,10 @@ impl PriceChecker {
|
|||
|
||||
/// Get a price from an URL
|
||||
pub fn get_price(&self, url : Url) -> Result<PriceResult> {
|
||||
let parser = *self.parser_list.get_price().iter().find(|p| p.can_parse(&url)).ok_or(anyhow!("No parser can parse {}", url))?;
|
||||
let response = self.client.get(url.clone()).send()?;
|
||||
let text = response.text()?;
|
||||
let document = Html::parse_document(&text);
|
||||
let parser = *self.parser_list.get_price().iter().find(|p| p.can_parse(&url)).ok_or(anyhow!("No parser can parse {}", url))?;
|
||||
Ok(parser.parse(&document)?)
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue