This repository has been archived on 2024-09-15. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
rust-script-tool/src/git.rs
2020-08-02 01:26:29 +08:00

88 lines
2.6 KiB
Rust

use std::path::PathBuf;
use std::process::Command;
trait RunCommandAsEnUs {
fn en_us(&mut self) -> &mut Self;
}
impl RunCommandAsEnUs for Command {
fn en_us(&mut self) -> &mut Self {
self.env("LANG", "en_US")
}
}
pub fn get_git_base_path() -> Option<PathBuf> {
match PathBuf::from(".").canonicalize() {
Err(e) => {
warn!("Get current path failed: {}", e);
None
},
Ok(mut path) => loop {
if path.join(".git").is_dir() {
debug!("Found git base dir: {:?}", path);
return Some(path);
}
if !path.pop() {
return None;
}
}
}
}
pub fn check_git_status() -> bool {
trace!("Run: git fetch --dry-run");
match Command::new("git").en_us().args(&["fetch", "--dry-run"]).output() {
Err(e) => {
warn!("Error in run git fetch --dry-run: {}", e);
return false;
},
Ok(o) => match String::from_utf8(o.stdout) {
Err(e) => {
warn!("Error in get utf8 git fetch --dry-run stdout: {}", e);
return false;
},
Ok(stdout) => if !stdout.trim().is_empty() {
warn!("Std out is not empty git fetch --dry-run: {}", stdout);
return false;
},
},
}
trace!("Run: git status");
match Command::new("git").en_us().args(&["status"]).output() {
Err(e) => {
warn!("Error in run git status: {}", e);
return false;
},
Ok(o) => match String::from_utf8(o.stdout) {
Err(e) => {
warn!("Error in get utf8 git status: {}", e);
return false;
},
Ok(stdout) => if [
"Changes not staged for commit",
"Your branch is ahead of",
"Untracked files" ].iter().any(|s| stdout.contains(s)) {
warn!("Std out check failed git status: {}", stdout);
return false;
}
}
}
true
}
pub fn get_git_hash() -> Option<String> {
trace!("Run: git rev-parse HEAD");
match Command::new("git").en_us().args(&["rev-parse", "HEAD"]).output(){
Err(e) => {
warn!("Error in run git rev-parse HEAD: {}", e);
None
},
Ok(o) => match String::from_utf8(o.stdout) {
Err(e) => {
warn!("Error in get utf8 git rev-parse HEAD: {}", e);
None
},
Ok(stdout) => Some(stdout.trim().into()),
}
}
}