1use anyhow::anyhow;
2use std::path::Path;
3use std::process::{Command, Stdio};
4
5pub fn init(store: &Path) -> anyhow::Result<()> {
6 run_command(
7 git().args(["init", "--initial-branch", "main"]),
8 store,
9 true,
10 )?;
11 run_command(git().args(["add", "*"]), store, true)?;
12 run_command(
13 git().args(["commit", "--message", "initialize rp password store repo"]),
14 store,
15 true,
16 )?;
17 Ok(())
18}
19
20pub fn add(store: &Path, key: &str) -> anyhow::Result<()> {
21 if has_repository(store) {
22 run_command(
23 git().arg("add").arg(store.join(key).as_os_str()),
24 store,
25 true,
26 )?;
27 run_command(
28 git().args(["commit", "--message", &format!("add {key}")]),
29 store,
30 true,
31 )?;
32 }
33 Ok(())
34}
35
36pub fn edit(store: &Path, key: &str) -> anyhow::Result<()> {
37 if has_repository(store) && is_file_tracked(store, key) {
38 run_command(
39 git().arg("add").arg(store.join(key).as_os_str()),
40 store,
41 true,
42 )?;
43 run_command(
44 git().args(["commit", "--message", &format!("edit {}", key)]),
45 store,
46 true,
47 )?;
48 }
49 Ok(())
50}
51
52pub fn r#move(store: &Path, from_key: &str, to_key: &str) -> anyhow::Result<bool> {
53 if has_repository(store) && is_file_tracked(store, from_key) {
54 run_command(
55 git()
56 .arg("mv")
57 .arg(store.join(from_key).as_os_str())
58 .arg(store.join(to_key).as_os_str()),
59 store,
60 true,
61 )?;
62 run_command(
63 git().args([
64 "commit",
65 "--message",
66 &format!("move {} to {}", from_key, to_key),
67 ]),
68 store,
69 true,
70 )?;
71 Ok(true)
72 } else {
73 Ok(false)
74 }
75}
76
77pub fn remove(store: &Path, key: &str) -> anyhow::Result<()> {
78 if has_repository(store) && is_file_tracked(store, key) {
79 run_command(
80 git().arg("rm").arg(store.join(key).as_os_str()),
81 store,
82 true,
83 )?;
84 run_command(
85 Command::new("git").args(["commit", "--message", &format!("remove {}", key)]),
86 store,
87 true,
88 )?;
89 }
90 Ok(())
91}
92
93fn run_command(command: &mut Command, store: &Path, inherit_io: bool) -> anyhow::Result<()> {
94 let stdio = || match inherit_io {
95 true => Stdio::inherit(),
96 false => Stdio::null(),
97 };
98 let result = command
99 .current_dir(store)
100 .stdin(stdio())
101 .stdout(stdio())
102 .stderr(stdio())
103 .status();
104 match result {
105 Ok(status) if status.success() => Ok(()),
106 Ok(status) => Err(anyhow!(
107 "git failed with status {}",
108 status
109 .code()
110 .map(|c| c.to_string())
111 .unwrap_or("unknown".to_string())
112 )),
113 Err(err) => Err(err.into()),
114 }
115}
116
117fn has_repository(store: &Path) -> bool {
118 store.join(".git").is_dir()
119}
120
121fn is_file_tracked(store: &Path, key: &str) -> bool {
122 run_command(
123 git()
124 .arg("ls-files")
125 .arg("--error-unmatch")
126 .arg(store.join(key).as_os_str()),
127 store,
128 false,
129 )
130 .is_ok()
131}
132
133fn git() -> Command {
134 Command::new("git")
135}