on a7e2bb8 help sign in
bat/src/config.rs
105 lines 2.4 kB history raw
1use std::env;
2use std::ffi::OsString;
3use std::fs;
4use std::path::PathBuf;
6use shell_words;
8use crate::dirs::PROJECT_DIRS;
9use crate::util::transpose;
11pub fn config_file() -> PathBuf {
12 env::var("BAT_CONFIG_PATH")
13 .ok()
14 .map(PathBuf::from)
15 .filter(|config_path| config_path.is_file())
16 .unwrap_or_else(|| PROJECT_DIRS.config_dir().join("config"))
19pub fn get_args_from_config_file() -> Result<Vec<OsString>, shell_words::ParseError> {
20 Ok(transpose(
21 fs::read_to_string(config_file())
22 .ok()
23 .map(|content| get_args_from_str(&content)),
24 )?
25 .unwrap_or_else(|| vec![]))
28pub fn get_args_from_env_var() -> Option<Result<Vec<OsString>, shell_words::ParseError>> {
29 env::var("BAT_OPTS").ok().map(|s| get_args_from_str(&s))
32fn get_args_from_str(content: &str) -> Result<Vec<OsString>, shell_words::ParseError> {
33 let args_per_line = content
34 .split('\n')
35 .map(|line| line.trim())
36 .filter(|line| !line.is_empty())
37 .filter(|line| !line.starts_with('#'))
38 .map(|line| shell_words::split(line))
39 .collect::<Result<Vec<_>, _>>()?;
41 Ok(args_per_line
42 .iter()
43 .flatten()
44 .map(|line| line.into())
45 .collect())
48#[test]
49fn empty() {
50 let args = get_args_from_str("").unwrap();
51 assert!(args.is_empty());
54#[test]
55fn single() {
56 assert_eq!(vec!["--plain"], get_args_from_str("--plain").unwrap());
59#[test]
60fn multiple() {
61 assert_eq!(
62 vec!["--plain", "--language=cpp"],
63 get_args_from_str("--plain --language=cpp").unwrap()
64 );
67#[test]
68fn quotes() {
69 assert_eq!(
70 vec!["--theme", "Sublime Snazzy"],
71 get_args_from_str("--theme \"Sublime Snazzy\"").unwrap()
72 );
75#[test]
76fn multi_line() {
77 let config = "
78 -p
79 --style numbers,changes
81 --color=always
82 ";
83 assert_eq!(
84 vec!["-p", "--style", "numbers,changes", "--color=always"],
85 get_args_from_str(config).unwrap()
86 );
89#[test]
90fn comments() {
91 let config = "
92 # plain style
93 -p
95 # show line numbers and Git modifications
96 --style numbers,changes
98 # Always show ANSI colors
99 --color=always
100 ";
101 assert_eq!(
102 vec!["-p", "--style", "numbers,changes", "--color=always"],
103 get_args_from_str(config).unwrap()
104 );