Skip to content

parse GIT_CONFIG_PARAMETERS #979

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 49 additions & 35 deletions src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub(crate) use crate::application::app_data::AppData;
use crate::{
Args,
Exit,
config::{Config, ConfigLoader, DiffIgnoreWhitespaceSetting},
config::{Config, ConfigError, ConfigErrorCause, ConfigLoader, DiffIgnoreWhitespaceSetting},
diff::{self, CommitDiffLoader, CommitDiffLoaderOptions},
display::Display,
git::open_repository_from_env,
Expand All @@ -34,15 +34,16 @@ where ModuleProvider: module::ModuleProvider + Send + 'static
impl<ModuleProvider> Application<ModuleProvider>
where ModuleProvider: module::ModuleProvider + Send + 'static
{
pub(crate) fn new<EventProvider, Tui>(args: &Args, event_provider: EventProvider, tui: Tui) -> Result<Self, Exit>
pub(crate) fn new<EventProvider, Tui>(args: Args, git_config_parameters: Vec<(String, String)>, event_provider: EventProvider, tui: Tui) -> Result<Self, Exit>
where
EventProvider: EventReaderFn,
Tui: crate::display::Tui + Send + 'static,
{
let filepath = Self::filepath_from_args(args)?;
let repository = Self::open_repository()?;
let config_loader = ConfigLoader::from(repository);
let config = Self::load_config(&config_loader)?;
let config_loader = ConfigLoader::with_overrides(repository, git_config_parameters);
let config = Self::load_config(&config_loader)
.map_err(|err| Exit::new(ExitStatus::ConfigError, format!("{err:#}").as_str()))?;
let todo_file = Arc::new(Mutex::new(Self::load_todo_file(filepath.as_str(), &config)?));

let display = Display::new(tui, &config.theme);
Expand Down Expand Up @@ -144,7 +145,7 @@ where ModuleProvider: module::ModuleProvider + Send + 'static
Ok(())
}

fn filepath_from_args(args: &Args) -> Result<String, Exit> {
fn filepath_from_args(args: Args) -> Result<String, Exit> {
args.todo_file_path().map(String::from).ok_or_else(|| {
Exit::new(
ExitStatus::StateError,
Expand All @@ -162,8 +163,11 @@ where ModuleProvider: module::ModuleProvider + Send + 'static
})
}

fn load_config(config_loader: &ConfigLoader) -> Result<Config, Exit> {
Config::try_from(config_loader).map_err(|err| Exit::new(ExitStatus::ConfigError, format!("{err:#}").as_str()))
fn load_config(config_loader: &ConfigLoader) -> Result<Config, ConfigError> {
let config = config_loader
.load_config()
.map_err(|e| ConfigError::new_read_error("", ConfigErrorCause::GitError(e)))?;
Config::new_with_config(Some(&config))
}

fn todo_file_options(config: &Config) -> TodoFileOptions {
Expand Down Expand Up @@ -208,8 +212,6 @@ where ModuleProvider: module::ModuleProvider + Send + 'static

#[cfg(all(unix, test))]
mod tests {
use std::ffi::OsString;

use claims::assert_ok;

use super::*;
Expand All @@ -219,19 +221,10 @@ mod tests {
module::Modules,
runtime::{Installer, RuntimeError},
test_helpers::{
DefaultTestModule,
TestModuleProvider,
create_config,
create_event_reader,
mocks,
with_git_directory,
DefaultTestModule, TestModuleProvider, create_config, create_event_reader, mocks, with_git_directory,
},
};

fn args(args: &[&str]) -> Args {
Args::try_from(args.iter().map(OsString::from).collect::<Vec<OsString>>()).unwrap()
}

fn create_mocked_crossterm() -> mocks::CrossTerm {
let mut crossterm = mocks::CrossTerm::new();
crossterm.set_size(Size::new(300, 120));
Expand All @@ -242,8 +235,7 @@ mod tests {
($app:expr) => {
if let Err(e) = $app {
e
}
else {
} else {
panic!("Application is not in an error state");
}
};
Expand All @@ -253,8 +245,12 @@ mod tests {
#[serial_test::serial]
fn load_filepath_from_args_failure() {
let event_provider = create_event_reader(|| Ok(None));
let application: Result<Application<TestModuleProvider<DefaultTestModule>>, Exit> =
Application::new(&args(&[]), event_provider, create_mocked_crossterm());
let application: Result<Application<TestModuleProvider<DefaultTestModule>>, Exit> = Application::new(
Args::from_os_strings(Vec::new()).unwrap(),
Vec::new(),
event_provider,
create_mocked_crossterm(),
);
let exit = application_error!(application);
assert_eq!(exit.get_status(), &ExitStatus::StateError);
assert!(
Expand All @@ -268,8 +264,12 @@ mod tests {
fn load_repository_failure() {
with_git_directory("fixtures/not-a-repository", |_| {
let event_provider = create_event_reader(|| Ok(None));
let application: Result<Application<TestModuleProvider<DefaultTestModule>>, Exit> =
Application::new(&args(&["todofile"]), event_provider, create_mocked_crossterm());
let application: Result<Application<TestModuleProvider<DefaultTestModule>>, Exit> = Application::new(
Args::from_strs(["todofile"]).unwrap(),
Vec::new(),
event_provider,
create_mocked_crossterm(),
);
let exit = application_error!(application);
assert_eq!(exit.get_status(), &ExitStatus::StateError);
assert!(exit.get_message().unwrap().contains("Unable to load Git repository: "));
Expand All @@ -280,8 +280,12 @@ mod tests {
fn load_config_failure() {
with_git_directory("fixtures/invalid-config", |_| {
let event_provider = create_event_reader(|| Ok(None));
let application: Result<Application<TestModuleProvider<DefaultTestModule>>, Exit> =
Application::new(&args(&["rebase-todo"]), event_provider, create_mocked_crossterm());
let application: Result<Application<TestModuleProvider<DefaultTestModule>>, Exit> = Application::new(
Args::from_strs(["rebase-todo"]).unwrap(),
Vec::new(),
event_provider,
create_mocked_crossterm(),
);
let exit = application_error!(application);
assert_eq!(exit.get_status(), &ExitStatus::ConfigError);
});
Expand Down Expand Up @@ -321,8 +325,12 @@ mod tests {
fn load_todo_file_load_error() {
with_git_directory("fixtures/simple", |_| {
let event_provider = create_event_reader(|| Ok(None));
let application: Result<Application<TestModuleProvider<DefaultTestModule>>, Exit> =
Application::new(&args(&["does-not-exist"]), event_provider, create_mocked_crossterm());
let application: Result<Application<TestModuleProvider<DefaultTestModule>>, Exit> = Application::new(
Args::from_strs(["does-not-exist"]).unwrap(),
Vec::new(),
event_provider,
create_mocked_crossterm(),
);
let exit = application_error!(application);
assert_eq!(exit.get_status(), &ExitStatus::FileReadError);
});
Expand All @@ -334,7 +342,8 @@ mod tests {
let rebase_todo = format!("{git_dir}/rebase-todo-noop");
let event_provider = create_event_reader(|| Ok(None));
let application: Result<Application<TestModuleProvider<DefaultTestModule>>, Exit> = Application::new(
&args(&[rebase_todo.as_str()]),
Args::from_strs([rebase_todo]).unwrap(),
Vec::new(),
event_provider,
create_mocked_crossterm(),
);
Expand All @@ -349,7 +358,8 @@ mod tests {
let rebase_todo = format!("{git_dir}/rebase-todo-empty");
let event_provider = create_event_reader(|| Ok(None));
let application: Result<Application<TestModuleProvider<DefaultTestModule>>, Exit> = Application::new(
&args(&[rebase_todo.as_str()]),
Args::from_strs([rebase_todo]).unwrap(),
Vec::new(),
event_provider,
create_mocked_crossterm(),
);
Expand Down Expand Up @@ -382,7 +392,8 @@ mod tests {
let rebase_todo = format!("{git_dir}/rebase-todo");
let event_provider = create_event_reader(|| Ok(Some(Event::Key(KeyEvent::from(KeyCode::Char('W'))))));
let mut application: Application<Modules> = Application::new(
&args(&[rebase_todo.as_str()]),
Args::from_strs([rebase_todo]).unwrap(),
Vec::new(),
event_provider,
create_mocked_crossterm(),
)
Expand All @@ -408,7 +419,8 @@ mod tests {
let rebase_todo = format!("{git_dir}/rebase-todo");
let event_provider = create_event_reader(|| Ok(Some(Event::Key(KeyEvent::from(KeyCode::Char('W'))))));
let mut application: Application<Modules> = Application::new(
&args(&[rebase_todo.as_str()]),
Args::from_strs([rebase_todo]).unwrap(),
Vec::new(),
event_provider,
create_mocked_crossterm(),
)
Expand All @@ -433,7 +445,8 @@ mod tests {
))))
});
let mut application: Application<Modules> = Application::new(
&args(&[rebase_todo.as_str()]),
Args::from_strs([rebase_todo]).unwrap(),
Vec::new(),
event_provider,
create_mocked_crossterm(),
)
Expand All @@ -449,7 +462,8 @@ mod tests {
let rebase_todo = format!("{git_dir}/rebase-todo");
let event_provider = create_event_reader(|| Ok(Some(Event::Key(KeyEvent::from(KeyCode::Char('W'))))));
let mut application: Application<Modules> = Application::new(
&args(&[rebase_todo.as_str()]),
Args::from_strs([rebase_todo]).unwrap(),
Vec::new(),
event_provider,
create_mocked_crossterm(),
)
Expand Down
30 changes: 14 additions & 16 deletions src/arguments.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@ impl Args {
pub(crate) fn todo_file_path(&self) -> Option<&str> {
self.todo_file_path.as_deref()
}
}

impl TryFrom<Vec<OsString>> for Args {
type Error = Exit;
#[cfg(test)]
pub(crate) fn from_strs(args: impl IntoIterator<Item: AsRef<str>>) -> Result<Self, Exit> {
let args = args.into_iter().map(|it| OsString::from(it.as_ref())).collect();
Self::from_os_strings(args)
}

fn try_from(args: Vec<OsString>) -> Result<Self, Self::Error> {
pub(crate) fn from_os_strings(args: Vec<OsString>) -> Result<Self, Exit> {
let mut pargs = Arguments::from_vec(args);

let mode = if pargs.contains(["-h", "--help"]) {
Expand Down Expand Up @@ -59,43 +61,39 @@ impl TryFrom<Vec<OsString>> for Args {
mod tests {
use super::*;

fn create_args(args: &[&str]) -> Vec<OsString> {
args.iter().map(OsString::from).collect()
}

#[test]
fn mode_help() {
assert_eq!(Args::try_from(create_args(&["-h"])).unwrap().mode(), &Mode::Help);
assert_eq!(Args::try_from(create_args(&["--help"])).unwrap().mode(), &Mode::Help);
assert_eq!(Args::from_strs(["-h"]).unwrap().mode(), &Mode::Help);
assert_eq!(Args::from_strs(["--help"]).unwrap().mode(), &Mode::Help);
}

#[test]
fn mode_version() {
assert_eq!(Args::try_from(create_args(&["-v"])).unwrap().mode(), &Mode::Version);
assert_eq!(Args::from_strs(["-v"]).unwrap().mode(), &Mode::Version);
assert_eq!(
Args::try_from(create_args(&["--version"])).unwrap().mode(),
Args::from_strs(["--version"]).unwrap().mode(),
&Mode::Version
);
}

#[test]
fn mode_license() {
assert_eq!(
Args::try_from(create_args(&["--license"])).unwrap().mode(),
Args::from_strs(["--license"]).unwrap().mode(),
&Mode::License
);
}

#[test]
fn todo_file_ok() {
let args = Args::try_from(create_args(&["todofile"])).unwrap();
let args = Args::from_strs(["todofile"]).unwrap();
assert_eq!(args.mode(), &Mode::Editor);
assert_eq!(args.todo_file_path(), Some("todofile"));
}

#[test]
fn todo_file_missing() {
let args = Args::try_from(create_args(&[])).unwrap();
let args = Args::from_os_strings(Vec::new()).unwrap();
assert_eq!(args.mode(), &Mode::Editor);
assert!(args.todo_file_path().is_none());
}
Expand All @@ -105,6 +103,6 @@ mod tests {
#[expect(unsafe_code)]
fn todo_file_invalid() {
let args = unsafe { vec![OsString::from(String::from_utf8_unchecked(vec![0xC3, 0x28]))] };
_ = Args::try_from(args).unwrap_err();
_ = Args::from_os_strings(args).unwrap_err();
}
}
27 changes: 5 additions & 22 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,12 @@ pub(crate) use self::{
config_loader::ConfigLoader,
diff_ignore_whitespace_setting::DiffIgnoreWhitespaceSetting,
diff_show_whitespace_setting::DiffShowWhitespaceSetting,
errors::{ConfigError, ConfigErrorCause, InvalidColorError},
git_config::GitConfig,
key_bindings::KeyBindings,
theme::Theme,
};
use crate::config::{
errors::{ConfigError, ConfigErrorCause, InvalidColorError},
utils::get_optional_string,
};
use crate::config::utils::get_optional_string;

const DEFAULT_SPACE_SYMBOL: &str = "\u{b7}"; // ·
const DEFAULT_TAB_SYMBOL: &str = "\u{2192}"; // →
Expand Down Expand Up @@ -94,22 +92,6 @@ impl Config {
}
}

impl TryFrom<&ConfigLoader> for Config {
type Error = ConfigError;

/// Creates a new Config instance loading the Git Config.
///
/// # Errors
///
/// Will return an `Err` if there is a problem loading the configuration.
fn try_from(config_loader: &ConfigLoader) -> Result<Self, Self::Error> {
let config = config_loader
.load_config()
.map_err(|e| ConfigError::new_read_error("", ConfigErrorCause::GitError(e)))?;
Self::new_with_config(Some(&config))
}
}

impl TryFrom<&crate::git::Config> for Config {
type Error = ConfigError;

Expand All @@ -131,8 +113,9 @@ mod tests {
#[test]
fn try_from_config_loader() {
with_temp_bare_repository(|repository| {
let loader = ConfigLoader::from(repository);
assert_ok!(Config::try_from(&loader));
let loader = ConfigLoader::new(repository);
let config = assert_ok!(loader.load_config());
assert_ok!(Config::try_from(&config));
});
}

Expand Down
Loading