diff options
author | Teddy Wing | 2017-05-07 15:00:19 +0200 |
---|---|---|
committer | Teddy Wing | 2017-05-07 15:00:19 +0200 |
commit | 3408f710221daece5d170dbd6a0dbfde64af8c39 (patch) | |
tree | cc0c54a1ff4632ccaa4ee2b86b8932d1533a27b9 /src/main.rs | |
parent | fd3bf8eb6ebd588850df17c243aae07fdd0259f6 (diff) | |
parent | 69dd2a7a23d1d71c50a91f5779db6f0480106cd8 (diff) | |
download | HearURL-3408f710221daece5d170dbd6a0dbfde64af8c39.tar.bz2 |
Merge branch 'command-line-arguments'
Diffstat (limited to 'src/main.rs')
-rw-r--r-- | src/main.rs | 52 |
1 files changed, 48 insertions, 4 deletions
diff --git a/src/main.rs b/src/main.rs index b4c7781..60780fc 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,10 +1,19 @@ +extern crate getopts; + +use getopts::Options; + +use std::env; use std::io::{self, Write}; use std::io::prelude::*; use std::net::TcpListener; use std::process::Command; -fn open_stream() -> io::Result<()> { - let listener = TcpListener::bind("127.0.0.1:34254")?; +const DEFAULT_PORT: u16 = 37705; + +fn open_stream(browser: String, port: u16) -> io::Result<()> { + let listener = TcpListener::bind( + format!("127.0.0.1:{}", port) + )?; for stream in listener.incoming() { match stream { @@ -14,7 +23,7 @@ fn open_stream() -> io::Result<()> { Command::new("open") .arg("-a") - .arg("Opera") + .arg(&browser) // Trim the trailing newline, otherwise this doesn't // work @@ -30,8 +39,43 @@ fn open_stream() -> io::Result<()> { Ok(()) } +fn print_usage(opts: Options) { + let brief = "Usage: hearurl -b BROWSER"; + print!("{}", opts.usage(&brief)); +} + fn main() { - open_stream().unwrap_or_else(|e| { + let args: Vec<String> = env::args().collect(); + + let mut opts = Options::new(); + opts.optopt("b", "browser", "set browser", "BROWSER"); + opts.optopt("p", "port", "set port number", "PORT"); + opts.optflag("h", "help", "print this help menu"); + + let opt_matches = match opts.parse(&args[1..]) { + Ok(m) => m, + Err(e) => panic!(e.to_string()), + }; + + if opt_matches.opt_present("h") { + print_usage(opts); + return + } + + let browser = match opt_matches.opt_str("b") { + Some(b) => b, + None => { + print_usage(opts); + return + }, + }; + + let port: u16 = match opt_matches.opt_str("p") { + Some(p) => p.parse().unwrap(), + None => DEFAULT_PORT, + }; + + open_stream(browser, port).unwrap_or_else(|e| { writeln!(io::stderr(), "{}", e) .expect("Failed printing to stderr"); }); |