-
-
Notifications
You must be signed in to change notification settings - Fork 714
Expand file tree
/
Copy pathargs.rs
More file actions
290 lines (259 loc) · 6.97 KB
/
args.rs
File metadata and controls
290 lines (259 loc) · 6.97 KB
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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
use crate::bug_report;
use anyhow::{anyhow, Context, Result};
use asyncgit::sync::RepoPath;
use clap::{
builder::ArgPredicate, crate_authors, crate_description,
crate_name, Arg, Command as ClapApp,
};
use simplelog::{Config, LevelFilter, WriteLogger};
use std::{
env,
fs::{self, File},
path::PathBuf,
};
const BUG_REPORT_FLAG_ID: &str = "bugreport";
const LOG_FILE_FLAG_ID: &str = "logfile";
const LOGGING_FLAG_ID: &str = "logging";
const THEME_FLAG_ID: &str = "theme";
const WORKDIR_FLAG_ID: &str = "workdir";
const FILE_FLAG_ID: &str = "file";
const GIT_DIR_FLAG_ID: &str = "directory";
const WATCHER_FLAG_ID: &str = "watcher";
const KEY_BINDINGS_FLAG_ID: &str = "key_bindings";
const KEY_SYMBOLS_FLAG_ID: &str = "key_symbols";
const CONFIG_DIR_FLAG_ID: &str = "config_dir";
const DEFAULT_THEME: &str = "theme.ron";
const DEFAULT_GIT_DIR: &str = ".";
#[derive(Clone)]
pub struct CliArgs {
pub theme: PathBuf,
pub select_file: Option<PathBuf>,
pub repo_path: RepoPath,
pub notify_watcher: bool,
pub key_bindings_path: Option<PathBuf>,
pub key_symbols_path: Option<PathBuf>,
}
pub fn process_cmdline() -> Result<CliArgs> {
let app = app();
let arg_matches = app.get_matches();
if arg_matches.get_flag(BUG_REPORT_FLAG_ID) {
bug_report::generate_bugreport();
std::process::exit(0);
}
if arg_matches.get_flag(LOGGING_FLAG_ID) {
let logfile = arg_matches.get_one::<String>(LOG_FILE_FLAG_ID);
setup_logging(logfile.map(PathBuf::from))?;
}
let workdir = arg_matches
.get_one::<String>(WORKDIR_FLAG_ID)
.map(PathBuf::from);
let gitdir =
arg_matches.get_one::<String>(GIT_DIR_FLAG_ID).map_or_else(
|| PathBuf::from(DEFAULT_GIT_DIR),
PathBuf::from,
);
let select_file = arg_matches
.get_one::<String>(FILE_FLAG_ID)
.map(PathBuf::from);
let repo_path = if let Some(w) = workdir {
RepoPath::Workdir { gitdir, workdir: w }
} else {
RepoPath::Path(gitdir)
};
// Set GITUI_CONFIG_DIR env var early so get_app_config_path() picks it up
if let Some(config_dir) =
arg_matches.get_one::<String>(CONFIG_DIR_FLAG_ID)
{
env::set_var("GITUI_CONFIG_DIR", config_dir);
}
let arg_theme = arg_matches
.get_one::<String>(THEME_FLAG_ID)
.map_or_else(|| PathBuf::from(DEFAULT_THEME), PathBuf::from);
let confpath = get_app_config_path()?;
fs::create_dir_all(&confpath).with_context(|| {
format!(
"failed to create config directory: {}",
confpath.display()
)
})?;
let theme = confpath.join(arg_theme);
let notify_watcher: bool =
*arg_matches.get_one(WATCHER_FLAG_ID).unwrap_or(&false);
let key_bindings_path = arg_matches
.get_one::<String>(KEY_BINDINGS_FLAG_ID)
.map(PathBuf::from);
let key_symbols_path = arg_matches
.get_one::<String>(KEY_SYMBOLS_FLAG_ID)
.map(PathBuf::from);
Ok(CliArgs {
theme,
select_file,
repo_path,
notify_watcher,
key_bindings_path,
key_symbols_path,
})
}
fn app() -> ClapApp {
ClapApp::new(crate_name!())
.author(crate_authors!())
.version(env!("GITUI_BUILD_NAME"))
.about(crate_description!())
.help_template(
"\
{before-help}gitui {version}
{author}
{about}
{usage-heading} {usage}
{all-args}{after-help}
",
)
.arg(
Arg::new(KEY_BINDINGS_FLAG_ID)
.help("Use a custom keybindings file")
.short('k')
.long("key-bindings")
.value_name("KEY_LIST_FILENAME")
.num_args(1),
)
.arg(
Arg::new(KEY_SYMBOLS_FLAG_ID)
.help("Use a custom symbols file")
.short('s')
.long("key-symbols")
.value_name("KEY_SYMBOLS_FILENAME")
.num_args(1),
)
.arg(
Arg::new(CONFIG_DIR_FLAG_ID)
.help("Use a custom config directory")
.short('c')
.long("config-dir")
.env("GITUI_CONFIG_DIR")
.value_name("CONFIG_DIR")
.num_args(1),
)
.arg(
Arg::new(THEME_FLAG_ID)
.help("Set color theme filename loaded from config directory")
.short('t')
.long("theme")
.value_name("THEME_FILE")
.default_value(DEFAULT_THEME)
.num_args(1),
)
.arg(
Arg::new(LOGGING_FLAG_ID)
.help("Store logging output into a file (in the cache directory by default)")
.short('l')
.long("logging")
.default_value_if("logfile", ArgPredicate::IsPresent, "true")
.action(clap::ArgAction::SetTrue),
)
.arg(Arg::new(LOG_FILE_FLAG_ID)
.help("Store logging output into the specified file (implies --logging)")
.long("logfile")
.value_name("LOG_FILE"))
.arg(
Arg::new(WATCHER_FLAG_ID)
.help("Use notify-based file system watcher instead of tick-based update. This is more performant, but can cause issues on some platforms. See https://github.com/gitui-org/gitui/blob/master/FAQ.md#watcher for details.")
.long("watcher")
.action(clap::ArgAction::SetTrue),
)
.arg(
Arg::new(BUG_REPORT_FLAG_ID)
.help("Generate a bug report")
.long("bugreport")
.action(clap::ArgAction::SetTrue),
)
.arg(
Arg::new(FILE_FLAG_ID)
.help("Select the file in the file tab")
.short('f')
.long("file")
.num_args(1),
)
.arg(
Arg::new(GIT_DIR_FLAG_ID)
.help("Set the git directory")
.short('d')
.long("directory")
.env("GIT_DIR")
.num_args(1),
)
.arg(
Arg::new(WORKDIR_FLAG_ID)
.help("Set the working directory")
.short('w')
.long("workdir")
.env("GIT_WORK_TREE")
.num_args(1),
)
}
fn setup_logging(path_override: Option<PathBuf>) -> Result<()> {
let path = if let Some(path) = path_override {
path
} else {
let mut path = get_app_cache_path()?;
path.push("gitui.log");
path
};
println!("Logging enabled. Log written to: {}", path.display());
WriteLogger::init(
LevelFilter::Trace,
Config::default(),
File::create(path)?,
)?;
Ok(())
}
fn get_app_cache_path() -> Result<PathBuf> {
let mut path = dirs::cache_dir()
.ok_or_else(|| anyhow!("failed to find os cache dir."))?;
path.push("gitui");
fs::create_dir_all(&path).with_context(|| {
format!(
"failed to create cache directory: {}",
path.display()
)
})?;
Ok(path)
}
pub fn get_app_config_path() -> Result<PathBuf> {
// Check GITUI_CONFIG_DIR first, then fall back to default
if let Ok(config_dir) = env::var("GITUI_CONFIG_DIR") {
return Ok(PathBuf::from(config_dir));
}
let mut path = if cfg!(target_os = "macos") {
dirs::home_dir().map(|h| h.join(".config"))
} else {
dirs::config_dir()
}
.ok_or_else(|| anyhow!("failed to find os config dir."))?;
path.push("gitui");
Ok(path)
}
#[cfg(test)]
mod tests {
use super::*;
use std::env;
#[test]
fn verify_app() {
app().debug_assert();
}
// env var tests must be serial since they mutate process state
#[test]
fn config_path_env_var_and_fallback() {
// with env var set, should return the custom path
let custom = "/tmp/gitui-test-config";
env::set_var("GITUI_CONFIG_DIR", custom);
let path = get_app_config_path().unwrap();
assert_eq!(path, PathBuf::from(custom));
// without env var, should fall back to default
env::remove_var("GITUI_CONFIG_DIR");
let path = get_app_config_path().unwrap();
assert!(
path.ends_with("gitui"),
"expected path ending in 'gitui', got: {path:?}"
);
}
}