summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: cae9c552a55853c32e2e957656b68fc5f032a8b1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
mod commands;
mod config;
mod context;
mod error;
mod event;
mod fs;
mod history;
mod io;
mod key_command;
mod preview;
mod run;
mod shadow;
mod tab;
mod traits;
mod ui;
mod util;

use std::fs::File;
use std::io::prelude::*;
use std::path::PathBuf;
use std::process;
use std::sync::Mutex;

use clap::{CommandFactory, Parser, Subcommand};
use config::clean::app::AppConfig;
use config::clean::icon::Icons;
use config::clean::keymap::AppKeyMapping;
use config::clean::preview::FileEntryPreview;
use lazy_static::lazy_static;

use config::clean::bookmarks::Bookmarks;
use config::clean::mimetype::AppProgramRegistry;
use config::clean::theme::AppTheme;
use config::{ConfigType, TomlConfigFile};
use util::cwd;

use crate::commands::quit::QuitAction;

use crate::context::AppContext;
use crate::error::AppError;

const PROGRAM_NAME: &str = "joshuto";
const CONFIG_HOME: &str = "JOSHUTO_CONFIG_HOME";

lazy_static! {
    // dynamically builds the config hierarchy
    static ref CONFIG_HIERARCHY: Vec<PathBuf> = {
        let mut config_dirs = vec![];

        if let Ok(p) = std::env::var(CONFIG_HOME) {
            let p = PathBuf::from(p);
            if p.is_dir() {
                config_dirs.push(p);
            }
        }

        if let Ok(dirs) = xdg::BaseDirectories::with_prefix(PROGRAM_NAME) {
            config_dirs.push(dirs.get_config_home());
        }

        if let Ok(p) = std::env::var("HOME") {
            let mut p = PathBuf::from(p);
            p.push(format!(".config/{}", PROGRAM_NAME));
            if p.is_dir() {
                config_dirs.push(p);
            }
        }

        config_dirs
    };
    static ref THEME_T: AppTheme = AppTheme::get_config();
    static ref MIMETYPE_T: AppProgramRegistry = AppProgramRegistry::get_config();
    static ref PREVIEW_T: FileEntryPreview = FileEntryPreview::get_config();
    static ref BOOKMARKS_T: Mutex<Bookmarks> = Mutex::new(Bookmarks::get_config());
    static ref ICONS_T: Icons = Icons::get_config();

    static ref HOME_DIR: Option<PathBuf> = dirs_next::home_dir();
    static ref USERNAME: String = whoami::username();
    static ref HOSTNAME: String = whoami::hostname();

    static ref TIMEZONE_STR: String = {
        let offset = chrono::Local::now().offset().local_minus_utc() / 3600;
        if offset.is_positive() {
            format!(" UTC+{} ", offset.abs())
        } else {
            format!(" UTC-{} ", offset.abs())
        }
    };
}

#[derive(Clone, Debug, Parser)]
#[command(author, about)]
pub struct Args {
    #[command(subcommand)]
    commands: Option<Commands>,

    #[arg(short = 'v', long = "version")]
    version: bool,

    #[arg(long = "change-directory")]
    change_directory: bool,

    #[arg(long = "file-chooser")]
    file_chooser: bool,

    #[arg(long = "output-file")]
    output_file: Option<PathBuf>,

    #[arg(name = "ARGUMENTS")]
    rest: Vec<PathBuf>,
}

#[derive(Clone, Debug, Subcommand)]
pub enum Commands {
    /// Print completions for a given shell.
    Completions { shell: clap_complete::Shell },

    /// Print embedded toml configuration for a given config type.
    Config {
        /// Filename of the given config without '.toml' extension.
        config_type: ConfigType,
    },

    /// Print 'joshuto' build version.
    Version,
}

fn run_main(args: Args) -> Result<i32, AppError> {
    if let Some(command) = args.commands {
        let result = match command {
            Commands::Completions { shell } => {
                let mut app = Args::command();
                let bin_name = app.get_name().to_string();
                clap_complete::generate(shell, &mut app, bin_name, &mut std::io::stdout());
                Ok(0)
            }
            Commands::Config { config_type } => match config_type.embedded_config() {
                None => AppError::fail("no default config"),
                Some(config) => {
                    println!("{config}");
                    Ok(0)
                }
            },
            Commands::Version => print_version(),
        };
        return result;
    }

    if args.version {
        return print_version();
    }

    if let Some(path) = args.rest.first() {
        cwd::set_current_dir(path)?;
    }

    // make sure all configs have been loaded before starting
    let config = AppConfig::get_config();
    let keymap = AppKeyMapping::get_config();

    lazy_static::initialize(&THEME_T);
    lazy_static::initialize(&MIMETYPE_T);
    lazy_static::initialize(&PREVIEW_T);
    lazy_static::initialize(&BOOKMARKS_T);
    lazy_static::initialize(&ICONS_T);

    lazy_static::initialize(&HOME_DIR);
    lazy_static::initialize(&USERNAME);
    lazy_static::initialize(&HOSTNAME);

    let mouse_support = config.mouse_support;
    let mut context = AppContext::new(config, args.clone());
    {
        let mut backend: ui::AppBackend = ui::AppBackend::new(mouse_support)?;
        run::run_loop(&mut backend, &mut context, keymap)?;
    }
    run_quit(&args, &context)?;
    Ok(context.quit.exit_code())
}

fn run_quit(args: &Args, context: &AppContext) -> Result<(), AppError> {
    match &args.output_file {
        Some(output_path) => match context.quit {
            QuitAction::OutputCurrentDirectory => {
                let curr_path = context.tab_context_ref().curr_tab_ref().cwd();
                let mut file = File::create(output_path)?;
                file.write_all(curr_path.as_os_str().to_string_lossy().as_bytes())?;
                file.write_all("\n".as_bytes())?;
            }
            QuitAction::OutputSelectedFiles => {
                let curr_tab = context.tab_context_ref().curr_tab_ref();
                let selected_files = curr_tab
                    .curr_list_ref()
                    .into_iter()
                    .flat_map(|s| s.get_selected_paths());
                let mut f = File::create(output_path)?;
                for file in selected_files {
                    writeln!(f, "{}", file.display())?;
                }
            }
            _ => {}
        },
        None => match context.quit {
            QuitAction::OutputCurrentDirectory => {
                let curr_path = std::env::current_dir()?;
                eprintln!(
                    "{}",
                    curr_path.into_os_string().as_os_str().to_string_lossy()
                );
            }
            QuitAction::OutputSelectedFiles => {
                let curr_tab = context.tab_context_ref().curr_tab_ref();
                let selected_files = curr_tab
                    .curr_list_ref()
                    .into_iter()
                    .flat_map(|s| s.get_selected_paths());
                for file in selected_files {
                    eprintln!("{}", file.display());
                }
            }
            _ => {}
        },
    }
    Ok(())
}

fn print_version() -> Result<i32, AppError> {
    writeln!(
        &mut std::io::stdout(),
        "{PROGRAM_NAME}-{}",
        shadow::CLAP_LONG_VERSION
    )?;
    Ok(0)
}

fn main() {
    let args = Args::parse();

    match run_main(args) {
        Ok(exit_code) => process::exit(exit_code),
        Err(e) => {
            eprintln!("{}", e);
            process::exit(1);
        }
    }
}

#[cfg(test)]
mod tests {
    use clap::Parser;

    use crate::{Args, Commands};

    #[test]
    fn test_command_new() {
        Args::parse_from(["program_name"]);
    }

    #[test]
    fn test_command_version() {
        match Args::parse_from(["program_name", "version"]).commands {
            Some(Commands::Version) => (),
            _ => panic!(),
        }
    }

    #[test]
    fn test_command_completions() {
        for shell in ["bash", "zsh", "fish", "elvish", "powershell"] {
            match Args::parse_from(["program_name", "completions", shell]).commands {
                Some(Commands::Completions { shell: _ }) => {}
                _ => panic!(),
            }
        }
    }
}