add a CLI flag for specifying config file location (#2666)

This commit is contained in:
Michael Davis 2022-08-03 23:05:52 -05:00 committed by GitHub
parent 219d2c2515
commit 5d33dbacac
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 48 additions and 16 deletions

View File

@ -25,6 +25,9 @@ # Configuration
hidden = false hidden = false
``` ```
You may also specify a file to use for configuration with the `-c` or
`--config` CLI argument: `hx -c path/to/custom-config.toml`.
## Editor ## Editor
### `[editor]` Section ### `[editor]` Section

View File

@ -16,7 +16,7 @@ _hx() {
COMPREPLY=($(compgen -W "$languages" -- $2)) COMPREPLY=($(compgen -W "$languages" -- $2))
;; ;;
*) *)
COMPREPLY=($(compgen -fd -W "-h --help --tutor -V --version -v -vv -vvv --health -g --grammar --vsplit --hsplit" -- $2)) COMPREPLY=($(compgen -fd -W "-h --help --tutor -V --version -v -vv -vvv --health -g --grammar --vsplit --hsplit -c --config" -- $2))
;; ;;
esac esac
} && complete -F _hx hx } && complete -F _hx hx

View File

@ -11,3 +11,4 @@ complete -c hx -s v -o vv -o vvv -d "Increases logging verbosity"
complete -c hx -s V -l version -d "Prints version information" complete -c hx -s V -l version -d "Prints version information"
complete -c hx -l vsplit -d "Splits all given files vertically into different windows" complete -c hx -l vsplit -d "Splits all given files vertically into different windows"
complete -c hx -l hsplit -d "Splits all given files horizontally into different windows" complete -c hx -l hsplit -d "Splits all given files horizontally into different windows"
complete -c hx -s c -l config -d "Specifies a file to use for completion"

View File

@ -16,6 +16,8 @@ _hx() {
"--grammar[Fetches or builds tree-sitter grammars]:action:->grammar" \ "--grammar[Fetches or builds tree-sitter grammars]:action:->grammar" \
"--vsplit[Splits all given files vertically into different windows]" \ "--vsplit[Splits all given files vertically into different windows]" \
"--hsplit[Splits all given files horizontally into different windows]" \ "--hsplit[Splits all given files horizontally into different windows]" \
"-c[Specifies a file to use for configuration]" \
"--config[Specifies a file to use for configuration]" \
"*:file:_files" "*:file:_files"
case "$state" in case "$state" in

View File

@ -2,11 +2,28 @@
pub mod grammar; pub mod grammar;
use etcetera::base_strategy::{choose_base_strategy, BaseStrategy}; use etcetera::base_strategy::{choose_base_strategy, BaseStrategy};
use std::path::PathBuf;
pub static RUNTIME_DIR: once_cell::sync::Lazy<std::path::PathBuf> = pub static RUNTIME_DIR: once_cell::sync::Lazy<PathBuf> = once_cell::sync::Lazy::new(runtime_dir);
once_cell::sync::Lazy::new(runtime_dir);
pub fn runtime_dir() -> std::path::PathBuf { static CONFIG_FILE: once_cell::sync::OnceCell<PathBuf> = once_cell::sync::OnceCell::new();
pub fn initialize_config_file(specified_file: Option<PathBuf>) {
let config_file = specified_file.unwrap_or_else(|| {
let config_dir = config_dir();
if !config_dir.exists() {
std::fs::create_dir_all(&config_dir).ok();
}
config_dir.join("config.toml")
});
// We should only initialize this value once.
CONFIG_FILE.set(config_file).ok();
}
pub fn runtime_dir() -> PathBuf {
if let Ok(dir) = std::env::var("HELIX_RUNTIME") { if let Ok(dir) = std::env::var("HELIX_RUNTIME") {
return dir.into(); return dir.into();
} }
@ -31,7 +48,7 @@ pub fn runtime_dir() -> std::path::PathBuf {
.unwrap() .unwrap()
} }
pub fn config_dir() -> std::path::PathBuf { pub fn config_dir() -> PathBuf {
// TODO: allow env var override // TODO: allow env var override
let strategy = choose_base_strategy().expect("Unable to find the config directory!"); let strategy = choose_base_strategy().expect("Unable to find the config directory!");
let mut path = strategy.config_dir(); let mut path = strategy.config_dir();
@ -39,7 +56,7 @@ pub fn config_dir() -> std::path::PathBuf {
path path
} }
pub fn local_config_dirs() -> Vec<std::path::PathBuf> { pub fn local_config_dirs() -> Vec<PathBuf> {
let directories = find_root_impl(None, &[".helix".to_string()]) let directories = find_root_impl(None, &[".helix".to_string()])
.into_iter() .into_iter()
.map(|path| path.join(".helix")) .map(|path| path.join(".helix"))
@ -48,7 +65,7 @@ pub fn local_config_dirs() -> Vec<std::path::PathBuf> {
directories directories
} }
pub fn cache_dir() -> std::path::PathBuf { pub fn cache_dir() -> PathBuf {
// TODO: allow env var override // TODO: allow env var override
let strategy = choose_base_strategy().expect("Unable to find the config directory!"); let strategy = choose_base_strategy().expect("Unable to find the config directory!");
let mut path = strategy.cache_dir(); let mut path = strategy.cache_dir();
@ -56,19 +73,22 @@ pub fn cache_dir() -> std::path::PathBuf {
path path
} }
pub fn config_file() -> std::path::PathBuf { pub fn config_file() -> PathBuf {
config_dir().join("config.toml") CONFIG_FILE
.get()
.map(|path| path.to_path_buf())
.unwrap_or_else(|| config_dir().join("config.toml"))
} }
pub fn lang_config_file() -> std::path::PathBuf { pub fn lang_config_file() -> PathBuf {
config_dir().join("languages.toml") config_dir().join("languages.toml")
} }
pub fn log_file() -> std::path::PathBuf { pub fn log_file() -> PathBuf {
cache_dir().join("helix.log") cache_dir().join("helix.log")
} }
pub fn find_root_impl(root: Option<&str>, root_markers: &[String]) -> Vec<std::path::PathBuf> { pub fn find_root_impl(root: Option<&str>, root_markers: &[String]) -> Vec<PathBuf> {
let current_dir = std::env::current_dir().expect("unable to determine current directory"); let current_dir = std::env::current_dir().expect("unable to determine current directory");
let mut directories = Vec::new(); let mut directories = Vec::new();

View File

@ -89,9 +89,8 @@ pub fn new(args: Args, config: Config) -> Result<Self, Error> {
use helix_view::editor::Action; use helix_view::editor::Action;
let config_dir = helix_loader::config_dir();
let theme_loader = std::sync::Arc::new(theme::Loader::new( let theme_loader = std::sync::Arc::new(theme::Loader::new(
&config_dir, &helix_loader::config_dir(),
&helix_loader::runtime_dir(), &helix_loader::runtime_dir(),
)); ));

View File

@ -14,6 +14,7 @@ pub struct Args {
pub build_grammars: bool, pub build_grammars: bool,
pub split: Option<Layout>, pub split: Option<Layout>,
pub verbosity: u64, pub verbosity: u64,
pub config_file: Option<PathBuf>,
pub files: Vec<(PathBuf, Position)>, pub files: Vec<(PathBuf, Position)>,
} }
@ -43,6 +44,10 @@ pub fn parse_args() -> Result<Args> {
anyhow::bail!("--grammar must be followed by either 'fetch' or 'build'") anyhow::bail!("--grammar must be followed by either 'fetch' or 'build'")
} }
}, },
"-c" | "--config" => match argv.next().as_deref() {
Some(path) => args.config_file = Some(path.into()),
None => anyhow::bail!("--config must specify a path to read"),
},
arg if arg.starts_with("--") => { arg if arg.starts_with("--") => {
anyhow::bail!("unexpected double dash argument: {}", arg) anyhow::bail!("unexpected double dash argument: {}", arg)
} }

View File

@ -64,6 +64,7 @@ async fn main_impl() -> Result<i32> {
--health [LANG] Checks for potential errors in editor setup --health [LANG] Checks for potential errors in editor setup
If given, checks for config errors in language LANG If given, checks for config errors in language LANG
-g, --grammar {{fetch|build}} Fetches or builds tree-sitter grammars listed in languages.toml -g, --grammar {{fetch|build}} Fetches or builds tree-sitter grammars listed in languages.toml
-c, --config <file> Specifies a file to use for configuration
-v Increases logging verbosity each use for up to 3 times -v Increases logging verbosity each use for up to 3 times
(default file: {}) (default file: {})
-V, --version Prints version information -V, --version Prints version information
@ -119,14 +120,15 @@ async fn main_impl() -> Result<i32> {
std::fs::create_dir_all(&config_dir).ok(); std::fs::create_dir_all(&config_dir).ok();
} }
let config = match std::fs::read_to_string(config_dir.join("config.toml")) { helix_loader::initialize_config_file(args.config_file.clone());
let config = match std::fs::read_to_string(helix_loader::config_file()) {
Ok(config) => toml::from_str(&config) Ok(config) => toml::from_str(&config)
.map(helix_term::keymap::merge_keys) .map(helix_term::keymap::merge_keys)
.unwrap_or_else(|err| { .unwrap_or_else(|err| {
eprintln!("Bad config: {}", err); eprintln!("Bad config: {}", err);
eprintln!("Press <ENTER> to continue with default config"); eprintln!("Press <ENTER> to continue with default config");
use std::io::Read; use std::io::Read;
// This waits for an enter press.
let _ = std::io::stdin().read(&mut []); let _ = std::io::stdin().read(&mut []);
Config::default() Config::default()
}), }),