Skip to content

Commit

Permalink
feat: command line argument to provide path to config file
Browse files Browse the repository at this point in the history
  • Loading branch information
Piturnah committed Jul 7, 2023
1 parent a9f1aba commit be85b54
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 36 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- Config file to configure certain options
- `auto_expand_files`
- `auto_expand_hunks`
- Command line argument to provide alternative config file to use
- Use <kbd>Space</kbd> to toggle expansion of items
### Fixed
- Minibuffer can obscure the available subcommands ([#33](https://github.com/Piturnah/gex/issues/33))
Expand Down
20 changes: 20 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,14 @@ strip = true

[dependencies]
anyhow = "1.0.68"
clap = { version = "4.3.11", features = ["cargo"] }
clap = { version = "4.3.11", features = [ "cargo", "derive" ] }
crossterm = "0.26.0"
dirs = "5.0.1"
git2 = { version = "0.17.1", default-features = false }
itertools = "0.11.0"
nom = "7.1.1"
paste = "1.0.12"
serde = { version = "1.0.167", features = ["derive"] }
serde = { version = "1.0.167", features = [ "derive" ] }
serde_ignored = "0.1.8"
toml = "0.7.6"

Expand Down
18 changes: 18 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,24 @@ To enter gex simply type `gex` in console, optionally providing a path.
$ gex
```

Full usage:

```console
$ gex --help

Git workflow improvement CLI tool inspired by Magit

Usage: gex [OPTIONS] [PATH]

Arguments:
[PATH] The path to the repository [default: .]

Options:
-c, --config-file <PATH> Path to a config file to use
-h, --help Print help
-V, --version Print version
```

### Navigation

| Key | Action |
Expand Down
31 changes: 26 additions & 5 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,24 @@
//! Gex configuration.
#![allow(clippy::derivable_impls)]
use std::fs;
use std::{fs, path::PathBuf};

use clap::Parser;
use serde::Deserialize;

/// Command line args.
#[derive(Parser)]
#[command(version = env!("GEX_VERSION"), about)]
pub struct Clargs {
/// The path to the repository.
#[clap(default_value = ".")]
pub path: String,

/// Path to a config file to use.
#[clap(short, long, name = "PATH")]
pub config_file: Option<String>,
}

/// The top-level of the config parsed from the config file.
#[derive(Deserialize, Default)]
#[serde(default)]
pub struct Config {
Expand All @@ -29,10 +44,16 @@ impl Default for Options {
impl Config {
/// Reads the config from the config file (usually `~/.config/gex/config.toml` on Linux) and
/// returns it along with a Vec of unrecognised keys.
pub fn read_from_file() -> Option<(Self, Vec<String>)> {
let mut config_path = dirs::config_dir()?;
config_path.push("gex");
config_path.push("config.toml");
pub fn read_from_file(path: &Option<String>) -> Option<(Self, Vec<String>)> {
let mut config_path;
if let Some(path) = path {
config_path = PathBuf::from(path);
} else {
config_path = dirs::config_dir()?;
config_path.push("gex");
config_path.push("config.toml");
}

fs::read_to_string(config_path)
.map(|conf| {
let de = toml::Deserializer::new(&conf);
Expand Down
48 changes: 19 additions & 29 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ use std::{
cmp, env,
io::{stdin, stdout, BufRead, Write},
panic,
path::Path,
process::{self, Command, Output},
};

use anyhow::{Context, Result};
use clap::Arg;
use clap::Parser;
use config::Clargs;
use crossterm::{
cursor,
event::{self, Event, KeyCode, KeyEventKind},
Expand Down Expand Up @@ -70,9 +70,9 @@ pub fn git_process(args: &[&str]) -> Result<Output> {
})
}

fn run(path: &Path) -> Result<()> {
fn run(clargs: &Clargs) -> Result<()> {
// Attempt to find a git repository at or above current path
let repo = if let Ok(repo) = Repository::discover(path) {
let repo = if let Ok(repo) = Repository::discover(&clargs.path) {
repo
} else {
print!("Not a git repository. Initialise one? [y/N]");
Expand All @@ -87,7 +87,7 @@ fn run(path: &Path) -> Result<()> {
process::exit(0);
}

Repository::init(path).context("failed to initialise git repository")?
Repository::init(&clargs.path).context("failed to initialise git repository")?
};

// Set working directory in case the repository is not the current directory
Expand All @@ -96,17 +96,20 @@ fn run(path: &Path) -> Result<()> {

let mut minibuffer = MiniBuffer::new();

let config = Config::read_from_file().map_or_else(Config::default, |(config, unused_keys)| {
if !unused_keys.is_empty() {
let mut warning = String::from("Unknown keys in config file:");
for key in unused_keys {
warning.push_str("\n ");
warning.push_str(&key);
let config = Config::read_from_file(&clargs.config_file).map_or_else(
Config::default,
|(config, unused_keys)| {
if !unused_keys.is_empty() {
let mut warning = String::from("Unknown keys in config file:");
for key in unused_keys {
warning.push_str("\n ");
warning.push_str(&key);
}
minibuffer.push(&warning, MessageType::Error);
}
minibuffer.push(&warning, MessageType::Error);
}
config
});
config
},
);

let status = Status::new(&repo, &config.options)?;
let branch_list = BranchList::new()?;
Expand Down Expand Up @@ -342,20 +345,7 @@ fn restore_terminal() {
}

fn main() -> Result<()> {
let matches = clap::command!()
.version(env!("GEX_VERSION"))
.arg(
Arg::new("path")
.default_value(".")
.value_name("PATH")
.help("The path to the repository"),
)
.get_matches();
let path = matches
.get_one::<String>("path")
.expect("default value provided");

run(Path::new(path)).map_err(|e| {
run(&Clargs::parse()).map_err(|e| {
restore_terminal();
e
})
Expand Down

0 comments on commit be85b54

Please sign in to comment.