Skip to main content

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