From 05018a3a771826848464a14207b7b23453005bbd Mon Sep 17 00:00:00 2001 From: Olle Wreede Date: Sun, 3 Jul 2022 16:28:27 +0200 Subject: [PATCH] Add option to override language detection --- README.md | 1 + src/main.rs | 16 +++++++++++++--- 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 1f6f4c1..50c76ed 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,7 @@ OPTIONS: -c, --code Code to display, overrides both `filename` and `gist` -f, --filename Path to sourcecode file to display [default: assets/helloworld.rs] -g, --gist Gist id to display, if set, will override `filename` option + -l, --language Language of the code, if empty defaults to file extension -t, --theme Path to theme.json file [default: assets/theme.json] ``` diff --git a/src/main.rs b/src/main.rs index 7e90d1b..09bcda0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -67,6 +67,10 @@ async fn load_sourcecode( }; } +fn language_from_extension(filename: String) -> Option { + detect_lang::from_path(filename).map(|lang| lang.id().to_string()) +} + async fn build_codebox(opt: &CliOptions, theme: &Theme) -> TextBox { let font_bold = load_ttf_font(&theme.font_bold) .await @@ -82,7 +86,10 @@ async fn build_codebox(opt: &CliOptions, theme: &Theme) -> TextBox { load_sourcecode(opt.gist.clone(), opt.filename.clone(), opt.code.clone()) .await .expect("Couldn't load sourcecode!"); - let language = detect_lang::from_path(filename.clone()).map(|lang| lang.id().to_string()); + let language = opt + .language + .clone() + .or_else(|| language_from_extension(filename)); let code_box_builder = CodeBoxBuilder::new(theme.clone(), font_code, font_bold, font_italic); @@ -95,15 +102,18 @@ async fn build_codebox(opt: &CliOptions, theme: &Theme) -> TextBox { about = "A small tool to display sourcecode files" )] struct CliOptions { + /// Code to display, overrides both `filename` and `gist` + #[structopt(short, long)] + pub code: Option, /// Path to sourcecode file to display [default: assets/helloworld.rs] #[structopt(short, long, parse(from_os_str))] pub filename: Option, /// Gist id to display, if set, will override `filename` option #[structopt(short, long)] pub gist: Option, - /// Code to display, overrides both `filename` and `gist` + /// Language of the code, if empty defaults to file extension. #[structopt(short, long)] - pub code: Option, + pub language: Option, /// Path to theme.json file #[structopt(short, long, parse(from_os_str), default_value = "assets/theme.json")] pub theme: PathBuf,