1use std::path::{Path, PathBuf};
4use std::process::{Command, Stdio};
5
6#[derive(Debug, PartialEq, Eq, Clone, Copy)]
8pub enum GitStatus {
9 NotGitRepo,
11 GitRepoIgnored,
13 GitRepoNotIgnored,
15 Unavailable,
17}
18
19pub fn find_git_repo_root(start_dir: &Path) -> Option<PathBuf> {
21 let output = Command::new("git")
22 .arg("-C")
23 .arg(start_dir)
24 .args(["rev-parse", "--show-toplevel"])
25 .stderr(Stdio::null())
26 .output()
27 .ok()?;
28 if !output.status.success() {
29 return None;
30 }
31 Some(
32 PathBuf::from(String::from_utf8(output.stdout).ok()?.trim())
33 .canonicalize()
34 .unwrap(),
35 )
36}
37
38pub fn check_git_status(dir: &Path) -> GitStatus {
40 let repo = match Command::new("git")
41 .arg("-C")
42 .arg(dir)
43 .args(["rev-parse", "--show-toplevel"])
44 .stdout(Stdio::null())
45 .stderr(Stdio::null())
46 .status()
47 {
48 Ok(status) if status.success() => true,
49 Ok(status) if status.code() == Some(128) => false,
50 _ => return GitStatus::Unavailable,
51 };
52 if !repo {
53 return GitStatus::NotGitRepo;
54 }
55
56 let tracked = Command::new("git")
57 .arg("-C")
58 .arg(dir)
59 .args(["ls-files", "--error-unmatch", "--", ".npmrc"])
60 .stdout(Stdio::null())
61 .stderr(Stdio::null())
62 .status();
63 match tracked {
64 Ok(status) if status.success() => return GitStatus::GitRepoNotIgnored,
65 Ok(status) if status.code() == Some(1) => {}
66 _ => return GitStatus::Unavailable,
67 }
68
69 match Command::new("git")
70 .arg("-C")
71 .arg(dir)
72 .args(["check-ignore", "-q", "--", ".npmrc"])
73 .stdout(Stdio::null())
74 .stderr(Stdio::null())
75 .status()
76 {
77 Ok(status) if status.success() => GitStatus::GitRepoIgnored,
78 Ok(status) if status.code() == Some(1) => GitStatus::GitRepoNotIgnored,
79 _ => GitStatus::Unavailable,
80 }
81}
82
83pub fn check_local_credential_safety(dir: &Path) -> GitStatus {
85 check_git_status(dir)
86}
87
88#[cfg(test)]
89mod tests {
90 use super::*;
91 use std::fs;
92 use tempfile::tempdir;
93
94 #[test]
95 fn git_determines_ignore_status() {
96 let dir = tempdir().unwrap();
97 assert_eq!(check_git_status(dir.path()), GitStatus::NotGitRepo);
98 let status = Command::new("git")
99 .arg("-C")
100 .arg(dir.path())
101 .args(["init", "-q"])
102 .status()
103 .unwrap();
104 assert!(status.success());
105 assert_eq!(check_git_status(dir.path()), GitStatus::GitRepoNotIgnored);
106 fs::write(dir.path().join(".gitignore"), ".npmrc\n").unwrap();
107 assert_eq!(check_git_status(dir.path()), GitStatus::GitRepoIgnored);
108 assert_eq!(
109 find_git_repo_root(dir.path()).unwrap(),
110 dir.path().canonicalize().unwrap()
111 );
112 }
113}