diff options
author | Qingping Hou <dave2008713@gmail.com> | 2019-12-06 08:57:42 -0800 |
---|---|---|
committer | Matan Kushner <hello@matchai.me> | 2019-12-06 11:57:42 -0500 |
commit | c5a206e3cf5ea01eed98c3c7f79089a450d60b33 (patch) | |
tree | 38abdd7f7522210edac3471a2b9426e0493b9eaf /src/modules | |
parent | 5b440c0bb01b35eff1ebd92af1a2c013668fed04 (diff) |
feat: Add git_commit module (#673)
Diffstat (limited to 'src/modules')
-rw-r--r-- | src/modules/git_commit.rs | 54 | ||||
-rw-r--r-- | src/modules/mod.rs | 2 |
2 files changed, 56 insertions, 0 deletions
diff --git a/src/modules/git_commit.rs b/src/modules/git_commit.rs new file mode 100644 index 000000000..cacfa3982 --- /dev/null +++ b/src/modules/git_commit.rs @@ -0,0 +1,54 @@ +use super::{Context, Module, RootModuleConfig}; +use git2::Repository; + +use crate::configs::git_commit::GitCommitConfig; + +/// Creates a module with the Git commit in the current directory +/// +/// Will display the commit hash if the current directory is a git repo +pub fn module<'a>(context: &'a Context) -> Option<Module<'a>> { + let mut module = context.new_module("git_commit"); + let config = GitCommitConfig::try_load(module.config); + if config.disabled { + return None; + }; + + module + .get_prefix() + .set_value(config.prefix) + .set_style(config.style); + module + .get_suffix() + .set_value(config.suffix) + .set_style(config.style); + module.set_style(config.style); + + let repo = context.get_repo().ok()?; + let repo_root = repo.root.as_ref()?; + let git_repo = Repository::open(repo_root).ok()?; + + let git_head = git_repo.head().ok()?; + let head_commit = git_head.peel_to_commit().ok()?; + let commit_oid = head_commit.id(); + module.create_segment( + "hash", + &config.hash.with_value(&id_to_hex_abbrev( + commit_oid.as_bytes(), + config.commit_hash_length, + )), + ); + + Some(module) +} + +/// len specifies length of hex encoded string +pub fn id_to_hex_abbrev(bytes: &[u8], len: usize) -> String { + bytes + .iter() + .map(|b| format!("{:02x}", b)) + .collect::<Vec<String>>() + .join("") + .chars() + .take(len) + .collect() +} diff --git a/src/modules/mod.rs b/src/modules/mod.rs index f69c94653..42951324b 100644 --- a/src/modules/mod.rs +++ b/src/modules/mod.rs @@ -7,6 +7,7 @@ mod directory; mod dotnet; mod env_var; mod git_branch; +mod git_commit; mod git_state; mod git_status; mod golang; @@ -49,6 +50,7 @@ pub fn handle<'a>(module: &str, context: &'a Context) -> Option<Module<'a>> { "dotnet" => dotnet::module(context), "env_var" => env_var::module(context), "git_branch" => git_branch::module(context), + "git_commit" => git_commit::module(context), "git_state" => git_state::module(context), "git_status" => git_status::module(context), "golang" => golang::module(context), |