mars/src/client.rs

108 lines
2.9 KiB
Rust
Raw Normal View History

2019-02-27 11:09:38 +01:00
#[macro_use]
extern crate log;
2018-09-24 15:45:32 +02:00
2018-09-25 11:27:28 +02:00
use std::env;
2018-09-24 15:45:32 +02:00
use std::process::exit;
use percent_encoding::{percent_decode, percent_encode, DEFAULT_ENCODE_SET};
2018-09-25 11:27:28 +02:00
use hyper::Client;
use hyper::rt::{self, Future};
2018-09-24 15:45:32 +02:00
use mars::{GeneralBuilder, builder_arguments_from_string};
2018-09-25 14:58:01 +02:00
2018-09-24 13:52:45 +02:00
fn main() {
2018-09-24 15:45:32 +02:00
2019-02-27 11:09:38 +01:00
beautylog::init(log::LevelFilter::Info).ok();
let mut args = vec![];
let mut iter = env::args().skip(1);
let current_dir = {
let mut current_dir = None;
loop {
match iter.next() {
Some(ref x) if (x == "-p" || x == "--path") && current_dir.is_some() => {
error!("path is specified multiple times");
exit(1);
},
Some(ref x) if x == "-p" || x == "--path" => {
match iter.next() {
Some(v) => current_dir = Some(v.clone()),
None => {
error!("expecting a path after -p");
exit(1);
}
}
},
Some(ref x) => {
args.push(x.clone());
},
None => break current_dir,
}
}
};
let current_dir = current_dir.map(|x| {
if ! x.starts_with("/") {
let current_dir = match env::current_dir() {
Err(e) => {
error!("couldn't find current directory: {}", e);
exit(1);
},
Ok(path) => {
let p = path.to_str();
p.unwrap().to_owned()
},
};
format!("{}/{}", current_dir, x)
} else {
x
}
});
let current_dir = current_dir.unwrap_or_else(|| match env::current_dir() {
2018-09-25 11:27:28 +02:00
Err(e) => {
2019-02-27 11:09:38 +01:00
error!("couldn't find current directory: {}", e);
2018-09-25 11:27:28 +02:00
exit(1);
},
Ok(path) => {
let p = path.to_str();
p.unwrap().to_owned()
},
});
2018-09-24 15:45:32 +02:00
let args = args.join("&");
2018-09-25 15:42:41 +02:00
let url = if args.is_empty() {
format!("http://localhost:1500{}", current_dir)
} else {
format!("http://localhost:1500{}?{}", current_dir, args)
};
let url = percent_encode(url.as_bytes(), DEFAULT_ENCODE_SET).to_string();
2018-09-25 11:27:28 +02:00
let url = url.parse::<hyper::Uri>().unwrap();
rt::run(fetch_url(url));
}
fn fetch_url(uri: hyper::Uri) -> impl Future<Item=(), Error=()> {
2018-09-25 11:27:28 +02:00
let client = Client::new();
client.get(uri.clone())
2018-09-25 11:27:28 +02:00
.map(|_| ())
2018-09-25 14:58:01 +02:00
// If there was an error, build in client
.map_err(move |_| {
2019-02-27 11:09:38 +01:00
warn!("{}", "server not listening, building in client...");
let mut builder = GeneralBuilder::new();
let uri = percent_decode(uri.path().as_bytes()).decode_utf8().unwrap();
let (path, args) = builder_arguments_from_string(&*uri);
let _ = builder.build(&path, &args);
2018-09-25 11:27:28 +02:00
})
2018-09-24 13:52:45 +02:00
}