summaryrefslogtreecommitdiffstats
path: root/src/main.rs
blob: c24398156b79f87c28ced9506d17c98fb6dce33a (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
#[global_allocator]
static ALLOC: jemallocator::Jemalloc = jemallocator::Jemalloc;

#[macro_use]
extern crate lazy_static;
#[macro_use]
extern crate log;

mod app;
mod app_context;
mod browser_states;
mod commands;
mod conf;
mod errors;
mod external;
mod file_sizes;
mod flat_tree;
mod fuzzy_patterns;
mod regex_patterns;
mod git_ignore;
mod help_states;
mod input;
mod patterns;
mod screen_text;
mod screens;
mod spinner;
mod status;
mod task_sync;
mod tree_build;
mod tree_options;
mod tree_views;
mod verbs;

use clap;
use log::LevelFilter;
use simplelog;
use std::env;
use std::fs::File;
use std::path::PathBuf;
use std::result::Result;
use std::str::FromStr;

use crate::app::App;
use crate::app_context::AppContext;
use crate::commands::Command;
use crate::conf::Conf;
use crate::errors::ProgramError;
use crate::external::Launchable;
use crate::tree_options::TreeOptions;
use crate::verbs::VerbStore;

const VERSION: &str = "0.5.1";

// declare the possible CLI arguments, and gets the values
fn get_cli_args<'a>() -> clap::ArgMatches<'a> {
    clap::App::new("broot")
        .version(VERSION)
        .author("dystroy <denys.seguret@gmail.com>")
        .about("Balanced tree view + fuzzy search + BFS + customizable launcher")
        .arg(
            clap::Arg::with_name("root")
            .help("sets the root directory")
        )
        .arg(
            clap::Arg::with_name("commands")
                .short("c")
                .long("cmd")
                .takes_value(true)
                .help("commands to execute (space separated, experimental)")
        )
        .arg(
            clap::Arg::with_name("only-folders")
                .short("f")
                .long("only-folders")
                .help("only show folders")
        )
        .arg(
            clap::Arg::with_name("hidden")
                .short("h")
                .long("hidden")
                .help("show hidden files")
        )
        .arg(
            clap::Arg::with_name("sizes")
                .short("s")
                .long("sizes")
                .help("show the size of files and directories")
        )
        .arg(
            clap::Arg::with_name("permissions")
                .short("p")
                .long("permissions")
                .help("show permissions, with owner and group")
        )
        .arg(
            clap::Arg::with_name("output_path")
                .short("o")
                .long("out")
                .takes_value(true)
                .help("where to write the outputted path (if any)")
        )
        .arg(
            clap::Arg::with_name("gitignore")
                .short("g")
                .long("gitignore")
                .takes_value(true)
                .help("respect .gitignore rules (yes, no, auto)")
        )
        .get_matches()
}

// There's no log unless the BROOT_LOG environment variable is set to
//  a valid log level (trace, debug, info, warn, error, off)
// Example:
//      BROOT_LOG=info broot
// As broot is a terminal application, we only log to a file (dev.log)
fn configure_log() {
    let level = env::var("BROOT_LOG").unwrap_or_else(|_| "off".to_string());
    if level == "off" {
        return;
    }
    if let Ok(level) = LevelFilter::from_str(&level) {
        simplelog::WriteLogger::init(
            level,
            simplelog::Config::default(),
            File::create("dev.log").expect("Log file can't be created"),
        )
        .expect("log initialization failed");
        info!("Starting B-Root v{} with log level {}", VERSION, level);
    }
}

// run the application, and maybe return a launchable
// which must be run after broot
fn run() -> Result<Option<Launchable>, ProgramError> {
    configure_log();

    let config = Conf::from_default_location()?;

    let mut verb_store = VerbStore::new();
    verb_store.init(&config);

    let cli_args = get_cli_args();
    let path = match cli_args.value_of("root") {
        Some(path) => PathBuf::from(path),
        None => env::current_dir()?,
    };
    let path = path.canonicalize()?;
    let mut tree_options = TreeOptions::new();
    if cli_args.is_present("only-folders") {
        debug!("show only folders arg set");
        tree_options.only_folders = true;
    }
    if cli_args.is_present("hidden") {
        debug!("show hidden files arg set");
        tree_options.show_hidden = true;
    }
    if cli_args.is_present("sizes") {
        debug!("show sizes arg set");
        tree_options.show_sizes = true;
    }
    if cli_args.is_present("permissions") {
        debug!("show permissions arg set");
        tree_options.show_permissions = true;
    }
    if let Some(respect_ignore) = cli_args.value_of("gitignore") {
        tree_options.respect_git_ignore = respect_ignore.parse()?;
        debug!("respect_git_itnore = {:?}", tree_options.respect_git_ignore);
    }

    let con = AppContext {
        verb_store,
        output_path: cli_args
            .value_of("output_path")
            .and_then(|s| Some(s.to_owned())),
    };
    debug!("output path: {:?}", &con.output_path);

    let input_commands: Vec<Command> = match cli_args.value_of("commands") {
        Some(str) => str
            .split(' ')
            .map(|s| Command::from(s.to_string()))
            .collect(),
        None => Vec::new(),
    };

    App::new().run(
        &con,
        path,
        tree_options,
        input_commands,
    )
}

fn main() {
    let res = run().unwrap();
    if let Some(launchable) = res {
        info!("launching {:?}", &launchable);
        if let Err(e) = launchable.execute() {
            warn!("Failed to launch {:?}", &launchable);
            warn!("Error: {:?}", e);
            println!("Failed to lauch executable: {:?}", e);
        }
    }
    info!("bye");
}