diff --git a/src/cli.rs b/src/cli.rs index e6715075f..dc9233211 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -32,6 +32,14 @@ pub(crate) struct Cli { #[arg(short = 'l', long = "list")] pub list: bool, + /// Edit custom patch with `EDITOR` + #[arg(long = "edit-patch")] + pub edit_patch: bool, + + /// Edit custom page with `EDITOR` + #[arg(long = "edit-page")] + pub edit_page: bool, + /// Render a specific markdown file #[arg( short = 'f', diff --git a/src/main.rs b/src/main.rs index 9dede44dc..b38205bc0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -32,10 +32,12 @@ compile_error!( use std::{ env, + fs::create_dir_all, io::{self, IsTerminal}, process, }; +use anyhow::{anyhow, Context}; use app_dirs::AppInfo; use clap::Parser; @@ -276,6 +278,68 @@ fn main() { } }; + if args.edit_page && args.edit_patch { + print_error( + enable_styles, + &anyhow!("Don't edit-patch and edit-page at the same time"), + ); + process::exit(1); + } + + if args.edit_patch || args.edit_page { + if args.command.is_empty() { + if args.edit_patch { + print_error( + enable_styles, + &anyhow!( + " +No command given + +Sample usage : + tldr --edit-patch ", + ), + ); + } + if args.edit_page { + print_error( + enable_styles, + &anyhow!( + " +No command given + +Sample usage : + tldr --edit-page ", + ), + ); + } + process::exit(1); + } + let command = args.command.join("-").to_lowercase(); + let custom_page_dir = config + .directories + .custom_pages_dir + .as_ref() + .map(PathWithSource::path); + if let Some(custom_page_dir) = custom_page_dir { + let _ = create_dir_all(custom_page_dir); + + let file_name = if args.edit_patch { + format!("{command}.patch.md") + } else { + format!("{command}.page.md") + }; + let custom_page_path = custom_page_dir.join(file_name); + println!("Editing {custom_page_path:?}"); + let editor = env::var("EDITOR").context("env `EDITOR` not set").unwrap(); + let _ = std::process::Command::new(editor) + .arg(custom_page_path.to_str().unwrap()) + .status(); + } else { + print_error(enable_styles, &anyhow!("Fail to get custom page dir")); + process::exit(1); + } + } + // Show various paths if args.show_paths { show_paths(&config);