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_path_status(dir: &Path, path: &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", "--"])
60 .arg(path)
61 .stdout(Stdio::null())
62 .stderr(Stdio::null())
63 .status();
64 match tracked {
65 Ok(status) if status.success() => return GitStatus::GitRepoNotIgnored,
66 Ok(status) if status.code() == Some(1) => {}
67 _ => return GitStatus::Unavailable,
68 }
69
70 match Command::new("git")
71 .arg("-C")
72 .arg(dir)
73 .args(["check-ignore", "-q", "--"])
74 .arg(path)
75 .stdout(Stdio::null())
76 .stderr(Stdio::null())
77 .status()
78 {
79 Ok(status) if status.success() => GitStatus::GitRepoIgnored,
80 Ok(status) if status.code() == Some(1) => GitStatus::GitRepoNotIgnored,
81 _ => GitStatus::Unavailable,
82 }
83}
84
85pub fn check_git_status(dir: &Path) -> GitStatus {
87 check_path_status(dir, Path::new(".npmrc"))
88}
89
90pub fn check_local_credential_safety(dir: &Path) -> GitStatus {
92 check_git_status(dir)
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98 use std::fs;
99 use tempfile::tempdir;
100
101 #[test]
102 fn git_determines_ignore_status() {
103 let dir = tempdir().unwrap();
104 assert_eq!(check_git_status(dir.path()), GitStatus::NotGitRepo);
105 let status = Command::new("git")
106 .arg("-C")
107 .arg(dir.path())
108 .args(["init", "-q"])
109 .status()
110 .unwrap();
111 assert!(status.success());
112 assert_eq!(check_git_status(dir.path()), GitStatus::GitRepoNotIgnored);
113 fs::write(dir.path().join(".gitignore"), ".npmrc\n").unwrap();
114 assert_eq!(check_git_status(dir.path()), GitStatus::GitRepoIgnored);
115 assert_eq!(
116 find_git_repo_root(dir.path()).unwrap(),
117 dir.path().canonicalize().unwrap()
118 );
119
120 assert_eq!(
121 check_path_status(dir.path(), Path::new(".env.local")),
122 GitStatus::GitRepoNotIgnored
123 );
124 }
125}