1use crate::clipboard;
2use nils_common::process;
3use nils_common::shell::quote_posix_single;
4use std::io::{self, Write};
5use std::process::Output;
6
7pub fn dispatch(cmd: &str, args: &[String]) -> Option<i32> {
8 match cmd {
9 "zip" => Some(zip(args)),
10 "copy-staged" | "copy" => Some(copy_staged(args)),
11 "root" => Some(root(args)),
12 "commit-hash" | "hash" => Some(commit_hash(args)),
13 _ => None,
14 }
15}
16
17fn zip(args: &[String]) -> i32 {
18 if args
19 .iter()
20 .any(|arg| matches!(arg.as_str(), "-h" | "--help" | "help"))
21 {
22 print_zip_help();
23 return 0;
24 }
25
26 if let Some(arg) = args.first() {
27 eprintln!("❗ Unknown argument: {arg}");
28 eprintln!("Usage: git-cli utils zip");
29 return 1;
30 }
31
32 let short = match git_stdout_trimmed(&["rev-parse", "--short", "HEAD"]) {
33 Ok(value) => value,
34 Err(code) => return code,
35 };
36 let filename = format!("backup-{short}.zip");
37 let output = match run_git_output(&["archive", "--format", "zip", "HEAD", "-o", &filename]) {
38 Some(output) => output,
39 None => return 1,
40 };
41 if output.status.success() {
42 0
43 } else {
44 emit_output(&output);
45 exit_code(&output)
46 }
47}
48
49fn print_zip_help() {
50 println!("Usage: git-cli utils zip");
51 println!("Create backup-<short-sha>.zip from HEAD in the current directory.");
52}
53
54fn copy_staged(args: &[String]) -> i32 {
55 let mut mode = CopyMode::Clipboard;
56 let mut mode_flags = 0usize;
57 let mut unknown_arg: Option<String> = None;
58
59 for arg in args {
60 match arg.as_str() {
61 "--stdout" | "-p" | "--print" => {
62 mode = CopyMode::Stdout;
63 mode_flags += 1;
64 }
65 "--both" => {
66 mode = CopyMode::Both;
67 mode_flags += 1;
68 }
69 "--help" | "-h" => {
70 print_copy_staged_help();
71 return 0;
72 }
73 _ => {
74 if unknown_arg.is_none() {
75 unknown_arg = Some(arg.to_string());
76 }
77 }
78 }
79 }
80
81 if mode_flags > 1 {
82 eprintln!("❗ Only one output mode is allowed: --stdout or --both");
83 return 1;
84 }
85
86 if let Some(arg) = unknown_arg {
87 eprintln!("❗ Unknown argument: {arg}");
88 eprintln!("Usage: git-cli utils copy-staged [-p|--stdout|--both]");
89 return 1;
90 }
91
92 let output = match run_git_output(&["diff", "--cached", "--no-color"]) {
93 Some(output) => output,
94 None => return 1,
95 };
96 if !output.status.success() {
97 emit_output(&output);
98 return exit_code(&output);
99 }
100
101 let diff = trim_trailing_newlines(&String::from_utf8_lossy(&output.stdout)).to_string();
102 if diff.is_empty() {
103 println!("⚠️ No staged changes to copy");
104 return 1;
105 }
106
107 match mode {
108 CopyMode::Stdout => {
109 println!("{diff}");
110 0
111 }
112 CopyMode::Clipboard => {
113 let _ = clipboard::set_clipboard_best_effort(&diff);
114 println!("✅ Staged diff copied to clipboard");
115 0
116 }
117 CopyMode::Both => {
118 let _ = clipboard::set_clipboard_best_effort(&diff);
119 println!("{diff}");
120 println!("✅ Staged diff copied to clipboard");
121 0
122 }
123 }
124}
125
126fn root(args: &[String]) -> i32 {
127 let shell_mode = args.iter().any(|arg| arg == "--shell");
128 let output = match run_git_output(&["rev-parse", "--show-toplevel"]) {
129 Some(output) => output,
130 None => return 1,
131 };
132
133 if !output.status.success() {
134 eprintln!("❌ Not in a git repository");
135 return 1;
136 }
137
138 let root = trim_trailing_newlines(&String::from_utf8_lossy(&output.stdout)).to_string();
139 if shell_mode {
140 println!("cd -- {}", shell_escape(&root));
141 eprintln!("📁 Jumped to Git root: {root}");
142 } else {
143 println!();
144 println!("📁 Jumped to Git root: {root}");
145 }
146 0
147}
148
149fn commit_hash(args: &[String]) -> i32 {
150 let Some(ref_arg) = args.first() else {
151 eprintln!("❌ Missing git ref");
152 return 1;
153 };
154
155 let ref_commit = format!("{ref_arg}^{{commit}}");
156 let output = match run_git_output(&["rev-parse", "--verify", "--quiet", &ref_commit]) {
157 Some(output) => output,
158 None => return 1,
159 };
160 if !output.status.success() {
161 emit_output(&output);
162 return exit_code(&output);
163 }
164
165 let _ = io::stdout().write_all(&output.stdout);
166 0
167}
168
169fn run_git_output(args: &[&str]) -> Option<Output> {
170 match run_output("git", args) {
171 Ok(output) => Some(output),
172 Err(err) => {
173 eprintln!("{err}");
174 None
175 }
176 }
177}
178
179fn run_output(cmd: &str, args: &[&str]) -> Result<Output, String> {
180 process::run_output(cmd, args)
181 .map(|output| output.into_std_output())
182 .map_err(|err| format!("spawn {cmd}: {err}"))
183}
184
185fn git_stdout_trimmed(args: &[&str]) -> Result<String, i32> {
186 let output = run_git_output(args).ok_or(1)?;
187 if !output.status.success() {
188 emit_output(&output);
189 return Err(exit_code(&output));
190 }
191 Ok(trim_trailing_newlines(&String::from_utf8_lossy(&output.stdout)).to_string())
192}
193
194fn exit_code(output: &Output) -> i32 {
195 output.status.code().unwrap_or(1)
196}
197
198fn emit_output(output: &Output) {
199 let _ = io::stdout().write_all(&output.stdout);
200 let _ = io::stderr().write_all(&output.stderr);
201}
202
203fn trim_trailing_newlines(input: &str) -> &str {
204 input.trim_end_matches(['\n', '\r'])
205}
206
207fn shell_escape(value: &str) -> String {
208 quote_posix_single(value)
209}
210
211fn print_copy_staged_help() {
212 print!(
213 "Usage: git-cli utils copy-staged [-p|--stdout|--both]\n -p, --stdout, --print Print staged diff to stdout (no status message)\n --both Print to stdout and copy to clipboard\n"
214 );
215}
216
217enum CopyMode {
218 Clipboard,
219 Stdout,
220 Both,
221}