JAD3N / browsers

MIT License
1 stars 0 forks source link

Sample Code #3

Open felipetesc opened 1 year ago

felipetesc commented 1 year ago

Not-a-bug. Simple example to open a browser passing args from the cmd. I post here so, if you want, you can add as an example. I'm using to call from vs code to open a svelte project. Thanks !

use std::vec;
use std::env;

// search browsers at the path
fn opt_find_browsers()->Option<Vec<Browser>>{

    let browsers: Vec<Browser> = get_browsers();
    // find a specific browser installation path
    if browsers.len() > 0{

        Some(browsers)
    }else{
        None
    }
}

// run exe
fn run_exe(exe_name : String, args: Option<Vec<String>> ){

    use std::process::Command;

    let _browser_runner: std::process::Output ;

    if args.is_some(){
        let buf_args = args.clone().unwrap();
        let buf_args : Vec<&str> = buf_args.iter().map(|s| &**s).collect();
        _browser_runner =  Command::new(exe_name).args(buf_args).output().unwrap();
    }else {

        _browser_runner =  Command::new(exe_name).output().unwrap();
    }
}

fn get_cli_args() -> Option<Vec<String>>{

    let args: Vec<String> = env::args().collect();
    Some(args)
}

fn main() {

    // store cli input inside string
    let args_vec = get_cli_args().unwrap();

    // get a opt list of browsers
    let opt_find_browser = opt_find_browsers();

    // if a browser value was found
    if opt_find_browser.is_some(){

        //get the first browser which is safe
        let browser_path = opt_find_browser.unwrap()[0].path.clone().into_os_string().into_string().unwrap();
        let browser_path = String::from(browser_path);

        // case no cli args where found
        // use default
        if args_vec.len() <= 1 {
            let args = vec![
                String::from("--app=https://github.com/JAD3N/browsers"),
                String::from("--window-size=480,800")
            ];

            run_exe(browser_path, Some(args));

        }else{

            //let args : Vec<String> = input_string.clone().chars().map(|s|s.into()).collect();
            run_exe(browser_path, Some(args_vec));
        }

    }else{
        println!("error can't find a valid browser");
    }

}
JAD3N commented 1 year ago

This crate would be quite easy to further document, I'll make some time to go through and add some examples and inline documentation using a simplified version of the example provided.

felipetesc commented 1 year ago

Should we close this ?

JAD3N commented 1 year ago

Should be fine to leave it for now, I'll close once I get around to this.