Skip to content

Commit

Permalink
feat: support include git config
Browse files Browse the repository at this point in the history
  • Loading branch information
luhc228 committed Jun 15, 2024
1 parent e50e6f7 commit 207b413
Show file tree
Hide file tree
Showing 8 changed files with 125 additions and 52 deletions.
1 change: 0 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
mod commands;
mod process;
mod prompts;
mod utils;

pub use commands::*;
Expand Down
6 changes: 3 additions & 3 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use clap::Parser;
use gitez::{
add_git_user_config, apply_git_user_config, clone_repo, get_git_user_config_id, list_git_user_config,
remove_git_user_config, set_base_dir, Cli, Commands, GlobalConfig, UserConfigSubCommands,
add_git_user_config, apply_git_user_config, clone_repo, get_git_user_config_id, include_git_config,
list_git_user_config, remove_git_user_config, set_base_dir, Cli, Commands, GlobalConfig, UserConfigSubCommands,
};

fn main() -> anyhow::Result<()> {
Expand Down Expand Up @@ -35,7 +35,7 @@ fn main() -> anyhow::Result<()> {
remove_git_user_config(config_id)?;
}
UserConfigSubCommands::AddInclude => {
println!("Adding include.");
include_git_config()?;
}
},
}
Expand Down
48 changes: 47 additions & 1 deletion src/process/git_user_config/include.rs
Original file line number Diff line number Diff line change
@@ -1 +1,47 @@
pub fn include() {}
use std::{fs, path::PathBuf};

use anyhow::{Ok, Result};
use dialoguer::Input;
use ini::Ini;

use crate::{run_piped_command, select_git_user_config, GitUserConfig, GlobalDir};

const GIT_CONFIG_DIR: &str = "git-configs";

pub fn include() -> Result<()> {
// input the folder path
let folder_path: String = Input::new().with_prompt("Enter the folder path").interact()?;
// Select the git user config
let git_user_config = select_git_user_config()?;

let git_config_file = create_git_config_file(&git_user_config)?;

add_include_git_config_to_global(&folder_path, git_config_file)?;

println!("Git user config included successfully!");

Ok(())
}

fn create_git_config_file(git_user_config: &GitUserConfig) -> Result<PathBuf> {
let global_dir = GlobalDir::new();

let git_config_path = global_dir
.0
.join(GIT_CONFIG_DIR)
.join(format!("{}-config", git_user_config.config_id));
fs::create_dir_all(git_config_path.parent().expect("failed to get the parent path"))?;
let mut config = Ini::new();
config
.with_section(Some("user"))
.set("name", &git_user_config.name)
.set("email", &git_user_config.email);
config.write_to_file(&git_config_path)?;
Ok(git_config_path)
}

fn add_include_git_config_to_global(folder_path: &str, git_config_path: PathBuf) -> Result<()> {
let config_key = format!("includeIf.\"gitdir:{}\".path", git_config_path.display());
run_piped_command(vec!["git", "config", "--global", &config_key, folder_path])?;
Ok(())
}
1 change: 0 additions & 1 deletion src/prompts/mod.rs

This file was deleted.

33 changes: 3 additions & 30 deletions src/utils/get_git_user_config_id.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,13 @@
use anyhow::Ok;
use console::style;
use dialoguer::Select;

use crate::GitUserConfig;
use super::select_git_user_config;

pub fn get_git_user_config_id(raw_config_id: Option<String>) -> anyhow::Result<String> {
let config_id: String = match raw_config_id {
Some(config_id) => config_id,
None => {
let git_user_configs = GitUserConfig::get_all()?;
let items = git_user_configs
.iter()
.map(|config| {
format!(
"{}: {}<{}>",
style(&config.config_id).bold(),
&config.name,
&config.email
)
})
.collect::<Vec<String>>();

if items.is_empty() {
return Err(anyhow::anyhow!(
"No git user config found. Please add one by running `gitez user-config add`"
));
}

let selection = Select::new()
.with_prompt("choose the user config you want to remove")
.items(&items)
.default(0)
.interact()?;
let selected_config_id = &git_user_configs[selection].config_id;

selected_config_id.to_owned()
let git_user_config = select_git_user_config()?;
git_user_config.config_id
}
};

Expand Down
52 changes: 37 additions & 15 deletions src/utils/global_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,36 @@ use std::path::PathBuf;

use crate::GitUserConfig;

pub const DIR: &str = ".gitez";
const DIR: &str = ".gitez";
const CONFIG_FILENAME: &str = "config.json";

pub struct GlobalDir(pub PathBuf);

impl GlobalDir {
pub fn new() -> Self {
let global_dir = Self::global_dir();
if !global_dir.exists() {
fs::create_dir(&global_dir)
.map_err(|err| anyhow::anyhow!("Unable to create {}. Reason: {}", global_dir.display(), err))
.expect("Unable to create global directory");
}
Self(global_dir)
}
fn global_dir() -> PathBuf {
match dirs::home_dir() {
// The path is ~/.gitez
Some(home_dir) => home_dir.join(DIR),
None => PathBuf::from(DIR),
}
}
}

impl Default for GlobalDir {
fn default() -> Self {
Self::new()
}
}

#[derive(Debug, Serialize, Deserialize)]
pub struct GlobalConfig {
pub base_dir: Option<String>,
Expand All @@ -16,29 +43,24 @@ pub struct GlobalConfig {

impl GlobalConfig {
pub fn init() -> Result<()> {
Self::init_config()?;
Ok(())
}

fn init_config() -> Result<()> {
let config_path = GlobalConfig::config_path();
Self::init_dir()?;
if !config_path.exists() {
fs::write(&config_path, "{ \"git_user_configs\": [] }")
.map_err(|err| anyhow::anyhow!("Unable to create {}. Reason: {}", config_path.display(), err))?;
}
Ok(())
}
fn init_dir() -> Result<()> {
let config_path = GlobalConfig::config_path();
let dir = config_path.parent().unwrap();
if !dir.exists() {
fs::create_dir(dir).map_err(|err| anyhow::anyhow!("Unable to create {}. Reason: {}", dir.display(), err))?;
}
Ok(())
}

pub fn config_path() -> PathBuf {
match dirs::home_dir() {
// The path is ~/.gitez/config.json
Some(home_dir) => home_dir.join(DIR).join(CONFIG_FILENAME),
None => PathBuf::from(DIR).join(CONFIG_FILENAME),
}
let global_dir = GlobalDir::new();
global_dir.0.join(CONFIG_FILENAME)
}

pub fn new() -> Result<Self> {
let config_path = GlobalConfig::config_path();
let config_str = fs::read_to_string(&config_path)
Expand Down
4 changes: 3 additions & 1 deletion src/utils/mod.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
mod get_git_user_config_id;
mod git_url;
mod global_config;
mod select_git_user_config;
mod shell;

pub use get_git_user_config_id::get_git_user_config_id;
pub use git_url::GitUrl;
pub use global_config::GlobalConfig;
pub use global_config::{GlobalConfig, GlobalDir};
pub use select_git_user_config::select_git_user_config;
pub use shell::run_piped_command;
32 changes: 32 additions & 0 deletions src/utils/select_git_user_config.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
use crate::GitUserConfig;
use anyhow::{Ok, Result};
use console::style;
use dialoguer::Select;

pub fn select_git_user_config() -> Result<GitUserConfig> {
let git_user_configs = GitUserConfig::get_all()?;
let items = git_user_configs
.iter()
.map(|config| {
format!(
"{}: {}<{}>",
style(&config.config_id).bold(),
&config.name,
&config.email
)
})
.collect::<Vec<String>>();

if items.is_empty() {
return Err(anyhow::anyhow!(
"No git user config found. Please add one by running `gitez user-config add`"
));
}

let selection = Select::new()
.with_prompt("choose one of your git user config")
.items(&items)
.default(0)
.interact()?;
Ok(git_user_configs[selection].to_owned())
}

0 comments on commit 207b413

Please sign in to comment.