fancy_tree/
cli.rs

1//! CLI utilities.
2use crate::color::ColorChoice;
3use crate::config::{self, ConfigDir, ConfigFile as _};
4use crate::git::Git;
5use crate::lua;
6use crate::tree;
7use clap::{Parser, ValueEnum};
8use std::fs;
9use std::path::PathBuf;
10
11/// Lists files in a directory.
12#[derive(Parser)]
13#[deny(missing_docs)]
14pub struct Cli {
15    /// The path to search in.
16    #[arg(default_value = ".")]
17    pub path: PathBuf,
18
19    /// Controls colorization.
20    #[arg(long = "color")]
21    pub color_choice: Option<ColorChoice>,
22
23    /// Go only this many levels deep.
24    #[arg(short = 'L', long)]
25    pub level: Option<usize>,
26
27    /// Edit the main configuration file and exit.
28    #[arg(long, num_args = 0..=1, default_missing_value = "config")]
29    pub edit_config: Option<EditConfig>,
30}
31
32/// Choices for which config file to edit.
33#[derive(ValueEnum, Clone, Copy)]
34pub enum EditConfig {
35    /// The main configuration file.
36    Config,
37    /// The custom icon configuration.
38    Icons,
39    /// The custom colors configuration.
40    Colors,
41}
42
43impl Cli {
44    /// An environment variable the user can set to specify which editor to use.
45    const EDITOR_ENV_VAR: &str = "FANCY_TREE_EDITOR";
46
47    /// Runs the CLI.
48    pub fn run(&self) -> crate::Result {
49        // NOTE Early return for edit mode
50        if let Some(edit_config) = self.edit_config {
51            return self.edit_file(edit_config);
52        }
53
54        self.run_tree()
55    }
56
57    /// Runs the main tree functionality.
58    fn run_tree(&self) -> crate::Result {
59        let git = Git::new(&self.path).expect("Should be able to read the git repository");
60
61        // NOTE The Lua state must live as long as the configuration values.
62        let lua_state = {
63            let mut builder = lua::state::Builder::new();
64            if let Some(ref git) = git {
65                builder = builder.with_git(git);
66            }
67            builder.build().expect("The lua state should be valid")
68        };
69
70        // TODO Skip loading the config instead of panicking.
71        let config_dir = ConfigDir::new().expect("A config dir should be available");
72
73        let lua_inner = lua_state.to_inner();
74        let config = config_dir
75            .load_main(lua_inner)
76            .expect("The configuration should be valid");
77        let icons = config_dir
78            .load_icons(lua_inner)
79            .expect("The icon configuration should be valid");
80        let colors = config_dir
81            .load_colors(lua_inner)
82            .expect("The color configuration should be valid");
83
84        let mut builder = tree::Builder::new(&self.path);
85
86        // NOTE Apply configuration overrides from CLI.
87        if let Some(color_choice) = self.color_choice {
88            builder = builder.color_choice(color_choice);
89        }
90
91        // NOTE Apply configurations if they exist
92        if let Some(config) = config {
93            builder = builder.config(config);
94        }
95        if let Some(icons) = icons {
96            builder = builder.icons(icons);
97        }
98        if let Some(colors) = colors {
99            builder = builder.colors(colors);
100        }
101
102        if let Some(ref git) = git {
103            builder = builder.git(git);
104        }
105
106        if let Some(level) = self.level {
107            builder = builder.max_level(level);
108        }
109
110        let tree = builder.build();
111
112        lua_state.in_git_scope(|| tree.write_to_stdout().map_err(mlua::Error::external))?;
113
114        Ok(())
115    }
116
117    /// Opens an editor for the file the user specified, creating the config directory
118    /// if needed.
119    fn edit_file(&self, edit_config: EditConfig) -> crate::Result {
120        let config_dir = ConfigDir::new()?;
121        fs::create_dir_all(config_dir.path())?;
122
123        let (file_path, default_contents) = match edit_config {
124            EditConfig::Config => (config_dir.main_path(), config::Main::DEFAULT_MODULE),
125            EditConfig::Icons => (config_dir.icons_path(), config::Icons::DEFAULT_MODULE),
126            EditConfig::Colors => (config_dir.colors_path(), config::Colors::DEFAULT_MODULE),
127        };
128
129        // NOTE If we can't check if it exists, we'll be safe and skip overwriting it.
130        if !file_path.try_exists().unwrap_or(false) {
131            // NOTE Ignore error, because editing the file is a higher priority than
132            //      writing to it.
133            let _ = fs::write(&file_path, default_contents);
134        }
135
136        println!("Opening `{}`", file_path.display());
137
138        let finder = find_editor::Finder::with_extra_environment_variables([Self::EDITOR_ENV_VAR]);
139        /// Should the program wait for the editor to close before continuing?
140        const WAIT: bool = true;
141        finder.open_editor(file_path, WAIT)?;
142
143        Ok(())
144    }
145}
146
147// Runs the CLI. Can exit early without returning an error. For example, this will exit
148// early if the user passes `-h` as CLI argument.
149pub fn run() -> crate::Result {
150    Cli::parse().run()
151}