aboutsummaryrefslogtreecommitdiff
path: root/src/cliargs.rs
blob: 26a07af45b97a300e64f1bbb3f6fe8ae50b467f1 (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
// bibiman - a TUI for managing BibLaTeX databases
// Copyright (C) 2024  lukeflo
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
/////

use dirs::{config_dir, home_dir};
use lexopt::prelude::*;
use owo_colors::OwoColorize;
use owo_colors::colors::css::LightGreen;
use owo_colors::colors::*;
use std::env;
use std::path::PathBuf;
use walkdir::WalkDir;

use crate::app;
use crate::config::BibiConfig;

// struct for CLIArgs
#[derive(Debug, Default, Clone)]
pub struct CLIArgs {
    pub pos_args: Vec<PathBuf>,
    pub cfg_path: Option<PathBuf>,
    pub light_theme: bool,
    pub pdf_path: Option<PathBuf>,
}

impl CLIArgs {
    pub fn parse_args() -> color_eyre::Result<(CLIArgs, BibiConfig)> {
        let mut args = CLIArgs::default();
        let mut parser = lexopt::Parser::from_env();
        let mut subcommand = None;

        // Default config
        args.cfg_path = if config_dir().is_some() {
            Some(config_dir().unwrap().join("bibiman/bibiman.toml"))
        } else if home_dir().is_some() {
            Some(home_dir().unwrap().join(".config/bibiman/bibiman.toml"))
        } else {
            None
        };

        // if parser
        //     .raw_args()
        //     .is_ok_and(|mut arg| arg.next_if(|a| a == "format-citekeys").is_some())
        // {
        //     todo!("Format citekeys options");
        // }

        while let Some(arg) = parser.next()? {
            match arg {
                Short('h') | Long("help") => {
                    println!("{}", help_func());
                    std::process::exit(0);
                }
                Short('v') | Long("version") => {
                    println!("{}", version_func());
                    std::process::exit(0);
                }
                Short('c') | Long("config-file") => args.cfg_path = Some(parser.value()?.parse()?),
                Long("light-terminal") => args.light_theme = true,
                Long("pdf-path") => {
                    args.pdf_path = Some(parser.value()?.parse()?);
                }
                Value(pos_arg) => {
                    if args.pos_args.is_empty() {
                        let value = pos_arg
                            .into_string()
                            .unwrap_or_else(|os| os.to_string_lossy().to_string());
                        match value.as_str() {
                            "format-citekeys" => {
                                subcommand = Some(value);
                                break;
                            }
                            _ => {
                                args.pos_args.push(value.into());
                            }
                        }
                    } else {
                        args.pos_args.push(pos_arg.into());
                    }
                }
                _ => return Err(arg.unexpected().into()),
            }
        }

        if args
            .cfg_path
            .as_ref()
            .is_some_and(|f| f.try_exists().is_err() || !f.is_file())
        {
            BibiConfig::create_default_config(&args);
        }

        let mut cfg = if args.cfg_path.is_some() {
            BibiConfig::parse_config(&args)?
        } else {
            BibiConfig::new(&args)
        };

        if let Some(cmd) = subcommand {
            match cmd.as_str() {
                "format-citekeys" => todo!("write citekey formatting"),
                _ => {}
            }
        }

        cfg.cli_overwrite(&args);

        Ok((args, cfg))
    }
}

/// This function maps a vector containing paths to another vector containing paths.
/// But it will walk all entries of the first vec which are directories
/// and put only valid file paths with `.bib` ending to the resulting vec.
pub fn parse_files(args: Vec<PathBuf>) -> Vec<PathBuf> {
    let mut files: Vec<PathBuf> = Vec::new();
    // If pos arg is file, just push it to path vec
    for i in args {
        // Expand tilde to /home/user
        let i = if i.starts_with("~") {
            app::expand_home(&i)
        } else {
            i
        };
        if i.is_file() {
            files.push(i);
        // If pos arg is dir, walk dir and collect bibfiles
        } else if i.is_dir() {
            for file in WalkDir::new(i) {
                let f = file.unwrap().into_path();
                if f.is_file()
                    && f.extension().is_some()
                    && f.extension().unwrap_or_default() == "bib"
                {
                    files.push(f)
                }
            }
        } else {
            println!(
                "{}\n{}",
                "The positional argument is neither a valid file, nor a directory:"
                    .red()
                    .bold(),
                i.as_os_str().to_string_lossy().bright_red().italic()
            );
            println!();
            println!("{}", help_func());
            std::process::exit(1)
        }
    }
    files
}

pub fn help_func() -> String {
    let help = vec![
        format!(
            "{} {}\n",
            env!("CARGO_PKG_NAME").fg::<Green>().bold(),
            env!("CARGO_PKG_VERSION").fg::<LightGreen>(),
        ),
        format!(
            "{}:\n\t{} [Flags] [files/dirs]\n",
            "USAGE".bold(),
            "bibiman".bold()
        ),
        format!(
            "{}:\n\t{}\t\tPath to {} file",
            "POSITIONAL ARGUMENTS".bold(),
            "<file>".fg::<BrightMagenta>().bold(),
            ".bib".fg::<BrightBlack>().bold()
        ),
        format!(
            "\t{}\tPath to directory containing {} files",
            "<directory>".fg::<BrightBlue>().bold(),
            ".bib".fg::<BrightBlack>().bold()
        ),
        format!("\n\t{}", "Both can be passed multiple times".italic()),
        format!("\n{}:", "FLAGS".bold()),
        format!("\t{}", "-h, --help".bold().fg::<BrightCyan>()),
        format!("\t\t{}", "Show this help and exit"),
        format!("\t{}", "-v, --version".bold().fg::<BrightCyan>()),
        format!("\t\t{}", "Show the version and exit"),
        format!("\t{}", "--light-terminal".bold().fg::<BrightCyan>()),
        format!(
            "\t\t{}",
            "Enable default colors for light terminal background"
        ),
        format!(
            "\t{}{}",
            "-c, --config-file=".bold().fg::<BrightCyan>(),
            "<value>".bold().italic().fg::<BrightCyan>()
        ),
        format!("\t\t{}", "Path to config file used for current session."),
        format!("\t\t{}", "Takes precedence over standard config file."),
        format!(
            "\t{}{}",
            "--pdf-path=".bold().fg::<BrightCyan>(),
            "<value>".bold().italic().fg::<BrightCyan>()
        ),
        format!("\t\t{}", "Path to directory containing PDF files."),
        format!(
            "\t\t{}",
            "If the pdf files basename matches an entrys citekey,"
        ),
        format!(
            "\t\t{}",
            "its attached as connected PDF file for the current session."
        ),
        format!("\t\t{}", "Does not edit the bibfile itself!"),
    ];
    let help = help.join("\n");
    help
}

pub fn version_func() -> String {
    let version: Vec<String> = vec![
        format!(
            "{} {}",
            env!("CARGO_PKG_NAME").fg::<Green>().bold(),
            env!("CARGO_PKG_VERSION").fg::<LightGreen>()
        ),
        format!("{}", env!("CARGO_PKG_AUTHORS").bold()),
        format!("{}", env!("CARGO_PKG_LICENSE")),
        format!("\n"),
        format!(
            "{} {}",
            "Target Triple:".bold(),
            env!("TARGET").fg::<BrightRed>()
        ),
    ];
    let version = version.join("\n");
    version
}