on 01984e1 help sign in
bat/src/config.rs
101 lines 2.2 kB history raw
1use std::env;
2use std::ffi::OsString;
3use std::fs;
4use std::path::PathBuf;
6use shell_words;
8use dirs::PROJECT_DIRS;
9use util::transpose;
11pub fn config_file() -> PathBuf {
12 PROJECT_DIRS.config_dir().join("config")
15pub fn get_args_from_config_file() -> Result<Vec<OsString>, shell_words::ParseError> {
16 Ok(transpose(
17 fs::read_to_string(config_file())
18 .ok()
19 .map(|content| get_args_from_str(&content)),
20 )?
21 .unwrap_or(vec![]))
24pub fn get_args_from_env_var() -> Option<Result<Vec<OsString>, shell_words::ParseError>> {
25 env::var("BAT_OPTS").ok().map(|s| get_args_from_str(&s))
28fn get_args_from_str<'a>(content: &'a str) -> Result<Vec<OsString>, shell_words::ParseError> {
29 let args_per_line = content
30 .split('\n')
31 .map(|line| line.trim())
32 .filter(|line| !line.is_empty())
33 .filter(|line| !line.starts_with("#"))
34 .map(|line| shell_words::split(line))
35 .collect::<Result<Vec<_>, _>>()?;
37 Ok(args_per_line
38 .iter()
39 .flatten()
40 .map(|line| line.into())
41 .collect())
44#[test]
45fn empty() {
46 let args = get_args_from_str("").unwrap();
47 assert!(args.is_empty());
50#[test]
51fn single() {
52 assert_eq!(vec!["--plain"], get_args_from_str("--plain").unwrap());
55#[test]
56fn multiple() {
57 assert_eq!(
58 vec!["--plain", "--language=cpp"],
59 get_args_from_str("--plain --language=cpp").unwrap()
60 );
63#[test]
64fn quotes() {
65 assert_eq!(
66 vec!["--theme", "Sublime Snazzy"],
67 get_args_from_str("--theme \"Sublime Snazzy\"").unwrap()
68 );
71#[test]
72fn multi_line() {
73 let config = "
74 -p
75 --style numbers,changes
77 --color=always
78 ";
79 assert_eq!(
80 vec!["-p", "--style", "numbers,changes", "--color=always"],
81 get_args_from_str(config).unwrap()
82 );
85#[test]
86fn comments() {
87 let config = "
88 # plain style
89 -p
91 # show line numbers and Git modifications
92 --style numbers,changes
94 # Always show ANSI colors
95 --color=always
96 ";
97 assert_eq!(
98 vec!["-p", "--style", "numbers,changes", "--color=always"],
99 get_args_from_str(config).unwrap()
100 );