Debian Codegraph @

examples/status.rs

raw
1 /*
2 * libgit2 "status" example - shows how to use the status APIs
3 *
4 * Written by the libgit2 contributors
5 *
6 * To the extent possible under law, the author(s) have dedicated all copyright
7 * and related and neighboring rights to this software to the public domain
8 * worldwide. This software is distributed without any warranty.
9 *
10 * You should have received a copy of the CC0 Public Domain Dedication along
11 * with this software. If not, see
12 * <http://creativecommons.org/publicdomain/zero/1.0/>.
13 */
14
15 #![deny(warnings)]
16
17 use clap::Parser;
18 use git2::{Error, ErrorCode, Repository, StatusOptions, SubmoduleIgnore};
19 use std::str;
20 use std::time::Duration;
21
22 #[derive(Parser)]
23 struct Args {
24 arg_spec: Vec<String>,
25 #[structopt(name = "long", long)]
26 /// show longer statuses (default)
27 _flag_long: bool,
28 /// show short statuses
29 #[structopt(name = "short", long)]
30 flag_short: bool,
31 #[structopt(name = "porcelain", long)]
32 /// ??
33 flag_porcelain: bool,
34 #[structopt(name = "branch", short, long)]
35 /// show branch information
36 flag_branch: bool,
37 #[structopt(name = "z", short)]
38 /// ??
39 flag_z: bool,
40 #[structopt(name = "ignored", long)]
41 /// show ignored files as well
42 flag_ignored: bool,
43 #[structopt(name = "opt-modules", long = "untracked-files")]
44 /// setting for showing untracked files [no|normal|all]
45 flag_untracked_files: Option<String>,
46 #[structopt(name = "opt-files", long = "ignore-submodules")]
47 /// setting for ignoring submodules [all]
48 flag_ignore_submodules: Option<String>,
49 #[structopt(name = "dir", long = "git-dir")]
50 /// git directory to analyze
51 flag_git_dir: Option<String>,
52 #[structopt(name = "repeat", long)]
53 /// repeatedly show status, sleeping inbetween
54 flag_repeat: bool,
55 #[structopt(name = "list-submodules", long)]
56 /// show submodules
57 flag_list_submodules: bool,
58 }
59
60 #[derive(Eq, PartialEq)]
61 enum Format {
62 Long,
63 Short,
64 Porcelain,
65 }
66
67 fn run(args: &Args) -> Result<(), Error> {
68 let path = args.flag_git_dir.clone().unwrap_or_else(|| ".".to_string());
69 let repo = Repository::open(&path)?;
70 if repo.is_bare() {
71 return Err(Error::from_str("cannot report status on bare repository"));
72 }
73
74 let mut opts = StatusOptions::new();
75 opts.include_ignored(args.flag_ignored);
76 match args.flag_untracked_files.as_ref().map(|s| &s[..]) {
77 Some("no") => {
78 opts.include_untracked(false);
79 }
80 Some("normal") => {
81 opts.include_untracked(true);
82 }
83 Some("all") => {
84 opts.include_untracked(true).recurse_untracked_dirs(true);
85 }
86 Some(_) => return Err(Error::from_str("invalid untracked-files value")),
87 None => {}
88 }
89 match args.flag_ignore_submodules.as_ref().map(|s| &s[..]) {
90 Some("all") => {
91 opts.exclude_submodules(true);
92 }
93 Some(_) => return Err(Error::from_str("invalid ignore-submodules value")),
94 None => {}
95 }
96 opts.include_untracked(!args.flag_ignored);
97 for spec in &args.arg_spec {
98 opts.pathspec(spec);
99 }
100
101 loop {
102 if args.flag_repeat {
103 println!("\u{1b}[H\u{1b}[2J");
104 }
105
106 let statuses = repo.statuses(Some(&mut opts))?;
107
108 if args.flag_branch {
109 show_branch(&repo, &args.format())?;
110 }
111 if args.flag_list_submodules {
112 print_submodules(&repo)?;
113 }
114
115 if args.format() == Format::Long {
116 print_long(&statuses);
117 } else {
118 print_short(&repo, &statuses);
119 }
120
121 if args.flag_repeat {
122 std::thread::sleep(Duration::new(10, 0));
123 } else {
124 return Ok(());
125 }
126 }
127 }
128
129 fn show_branch(repo: &Repository, format: &Format) -> Result<(), Error> {
130 let head = match repo.head() {
131 Ok(head) => Some(head),
132 Err(ref e) if e.code() == ErrorCode::UnbornBranch || e.code() == ErrorCode::NotFound => {
133 None
134 }
135 Err(e) => return Err(e),
136 };
137 let head = head.as_ref().and_then(|h| h.shorthand().ok());
138
139 if format == &Format::Long {
140 println!(
141 "# On branch {}",
142 head.unwrap_or("Not currently on any branch")
143 );
144 } else {
145 println!("## {}", head.unwrap_or("HEAD (no branch)"));
146 }
147 Ok(())
148 }
149
150 fn print_submodules(repo: &Repository) -> Result<(), Error> {
151 let modules = repo.submodules()?;
152 println!("# Submodules");
153 for sm in &modules {
154 println!(
155 "# - submodule '{}' at {}",
156 sm.name().unwrap(),
157 sm.path().display()
158 );
159 }
160 Ok(())
161 }
162
163 // This function print out an output similar to git's status command in long
164 // form, including the command-line hints.
165 fn print_long(statuses: &git2::Statuses) {
166 let mut header = false;
167 let mut rm_in_workdir = false;
168 let mut changes_in_index = false;
169 let mut changed_in_workdir = false;
170
171 // Print index changes
172 for entry in statuses
173 .iter()
174 .filter(|e| e.status() != git2::Status::CURRENT)
175 {
176 if entry.status().contains(git2::Status::WT_DELETED) {
177 rm_in_workdir = true;
178 }
179 let istatus = match entry.status() {
180 s if s.contains(git2::Status::INDEX_NEW) => "new file: ",
181 s if s.contains(git2::Status::INDEX_MODIFIED) => "modified: ",
182 s if s.contains(git2::Status::INDEX_DELETED) => "deleted: ",
183 s if s.contains(git2::Status::INDEX_RENAMED) => "renamed: ",
184 s if s.contains(git2::Status::INDEX_TYPECHANGE) => "typechange:",
185 _ => continue,
186 };
187 if !header {
188 println!(
189 "\
190 # Changes to be committed:
191 # (use \"git reset HEAD <file>...\" to unstage)
192 #"
193 );
194 header = true;
195 }
196
197 let old_path = entry.head_to_index().unwrap().old_file().path();
198 let new_path = entry.head_to_index().unwrap().new_file().path();
199 match (old_path, new_path) {
200 (Some(old), Some(new)) if old != new => {
201 println!("#\t{} {} -> {}", istatus, old.display(), new.display());
202 }
203 (old, new) => {
204 println!("#\t{} {}", istatus, old.or(new).unwrap().display());
205 }
206 }
207 }
208
209 if header {
210 changes_in_index = true;
211 println!("#");
212 }
213 header = false;
214
215 // Print workdir changes to tracked files
216 for entry in statuses.iter() {
217 // With `Status::OPT_INCLUDE_UNMODIFIED` (not used in this example)
218 // `index_to_workdir` may not be `None` even if there are no differences,
219 // in which case it will be a `Delta::Unmodified`.
220 if entry.status() == git2::Status::CURRENT || entry.index_to_workdir().is_none() {
221 continue;
222 }
223
224 let istatus = match entry.status() {
225 s if s.contains(git2::Status::WT_MODIFIED) => "modified: ",
226 s if s.contains(git2::Status::WT_DELETED) => "deleted: ",
227 s if s.contains(git2::Status::WT_RENAMED) => "renamed: ",
228 s if s.contains(git2::Status::WT_TYPECHANGE) => "typechange:",
229 _ => continue,
230 };
231
232 if !header {
233 println!(
234 "\
235 # Changes not staged for commit:
236 # (use \"git add{} <file>...\" to update what will be committed)
237 # (use \"git checkout -- <file>...\" to discard changes in working directory)
238 #\
239 ",
240 if rm_in_workdir { "/rm" } else { "" }
241 );
242 header = true;
243 }
244
245 let old_path = entry.index_to_workdir().unwrap().old_file().path();
246 let new_path = entry.index_to_workdir().unwrap().new_file().path();
247 match (old_path, new_path) {
248 (Some(old), Some(new)) if old != new => {
249 println!("#\t{} {} -> {}", istatus, old.display(), new.display());
250 }
251 (old, new) => {
252 println!("#\t{} {}", istatus, old.or(new).unwrap().display());
253 }
254 }
255 }
256
257 if header {
258 changed_in_workdir = true;
259 println!("#");
260 }
261 header = false;
262
263 // Print untracked files
264 for entry in statuses
265 .iter()
266 .filter(|e| e.status() == git2::Status::WT_NEW)
267 {
268 if !header {
269 println!(
270 "\
271 # Untracked files
272 # (use \"git add <file>...\" to include in what will be committed)
273 #"
274 );
275 header = true;
276 }
277 let file = entry.index_to_workdir().unwrap().old_file().path().unwrap();
278 println!("#\t{}", file.display());
279 }
280 header = false;
281
282 // Print ignored files
283 for entry in statuses
284 .iter()
285 .filter(|e| e.status() == git2::Status::IGNORED)
286 {
287 if !header {
288 println!(
289 "\
290 # Ignored files
291 # (use \"git add -f <file>...\" to include in what will be committed)
292 #"
293 );
294 header = true;
295 }
296 let file = entry.index_to_workdir().unwrap().old_file().path().unwrap();
297 println!("#\t{}", file.display());
298 }
299
300 if !changes_in_index && changed_in_workdir {
301 println!(
302 "no changes added to commit (use \"git add\" and/or \
303 \"git commit -a\")"
304 );
305 }
306 }
307
308 // This version of the output prefixes each path with two status columns and
309 // shows submodule status information.
310 fn print_short(repo: &Repository, statuses: &git2::Statuses) {
311 for entry in statuses
312 .iter()
313 .filter(|e| e.status() != git2::Status::CURRENT)
314 {
315 let mut istatus = match entry.status() {
316 s if s.contains(git2::Status::INDEX_NEW) => 'A',
317 s if s.contains(git2::Status::INDEX_MODIFIED) => 'M',
318 s if s.contains(git2::Status::INDEX_DELETED) => 'D',
319 s if s.contains(git2::Status::INDEX_RENAMED) => 'R',
320 s if s.contains(git2::Status::INDEX_TYPECHANGE) => 'T',
321 _ => ' ',
322 };
323 let mut wstatus = match entry.status() {
324 s if s.contains(git2::Status::WT_NEW) => {
325 if istatus == ' ' {
326 istatus = '?';
327 }
328 '?'
329 }
330 s if s.contains(git2::Status::WT_MODIFIED) => 'M',
331 s if s.contains(git2::Status::WT_DELETED) => 'D',
332 s if s.contains(git2::Status::WT_RENAMED) => 'R',
333 s if s.contains(git2::Status::WT_TYPECHANGE) => 'T',
334 _ => ' ',
335 };
336
337 if entry.status().contains(git2::Status::IGNORED) {
338 istatus = '!';
339 wstatus = '!';
340 }
341 if istatus == '?' && wstatus == '?' {
342 continue;
343 }
344 let mut extra = "";
345
346 // A commit in a tree is how submodules are stored, so let's go take a
347 // look at its status.
348 //
349 // TODO: check for GIT_FILEMODE_COMMIT
350 let status = entry.index_to_workdir().and_then(|diff| {
351 let ignore = SubmoduleIgnore::Unspecified;
352 diff.new_file()
353 .path_bytes()
354 .and_then(|s| str::from_utf8(s).ok())
355 .and_then(|name| repo.submodule_status(name, ignore).ok())
356 });
357 if let Some(status) = status {
358 if status.contains(git2::SubmoduleStatus::WD_MODIFIED) {
359 extra = " (new commits)";
360 } else if status.contains(git2::SubmoduleStatus::WD_INDEX_MODIFIED)
361 || status.contains(git2::SubmoduleStatus::WD_WD_MODIFIED)
362 {
363 extra = " (modified content)";
364 } else if status.contains(git2::SubmoduleStatus::WD_UNTRACKED) {
365 extra = " (untracked content)";
366 }
367 }
368
369 let (mut a, mut b, mut c) = (None, None, None);
370 if let Some(diff) = entry.head_to_index() {
371 a = diff.old_file().path();
372 b = diff.new_file().path();
373 }
374 if let Some(diff) = entry.index_to_workdir() {
375 a = a.or_else(|| diff.old_file().path());
376 b = b.or_else(|| diff.old_file().path());
377 c = diff.new_file().path();
378 }
379
380 match (istatus, wstatus) {
381 ('R', 'R') => println!(
382 "RR {} {} {}{}",
383 a.unwrap().display(),
384 b.unwrap().display(),
385 c.unwrap().display(),
386 extra
387 ),
388 ('R', w) => println!(
389 "R{} {} {}{}",
390 w,
391 a.unwrap().display(),
392 b.unwrap().display(),
393 extra
394 ),
395 (i, 'R') => println!(
396 "{}R {} {}{}",
397 i,
398 a.unwrap().display(),
399 c.unwrap().display(),
400 extra
401 ),
402 (i, w) => println!("{}{} {}{}", i, w, a.unwrap().display(), extra),
403 }
404 }
405
406 for entry in statuses
407 .iter()
408 .filter(|e| e.status() == git2::Status::WT_NEW)
409 {
410 println!(
411 "?? {}",
412 entry
413 .index_to_workdir()
414 .unwrap()
415 .old_file()
416 .path()
417 .unwrap()
418 .display()
419 );
420 }
421 }
422
423 impl Args {
424 fn format(&self) -> Format {
425 if self.flag_short {
426 Format::Short
427 } else if self.flag_porcelain || self.flag_z {
428 Format::Porcelain
429 } else {
430 Format::Long
431 }
432 }
433 }
434
435 fn main() {
436 let args = Args::parse();
437 match run(&args) {
438 Ok(()) => {}
439 Err(e) => println!("error: {}", e),
440 }
441 }