1extern crate ansi_term;
2extern crate chrono;
3#[macro_use]
4extern crate clap;
5extern crate colorparse;
6extern crate git2;
7extern crate isatty;
8#[macro_use]
9extern crate quick_error;
10extern crate tempdir;
11
12use std::env;
13use std::ffi::{OsStr, OsString};
14use std::fmt::Write as FmtWrite;
15use std::fs::File;
16use std::io::Read;
17use std::io::Write as IoWrite;
18use std::process::Command;
19use ansi_term::Style;
20use chrono::offset::TimeZone;
21use clap::{App, AppSettings, Arg, ArgGroup, ArgMatches, SubCommand};
22use git2::{Config, Commit, Diff, Object, ObjectType, Oid, Reference, Repository, TreeBuilder};
23use tempdir::TempDir;
24
25quick_error! {
26 #[derive(Debug)]
27 enum Error {
28 Git2(err: git2::Error) {
29 from()
30 cause(err)
31 display("{}", err)
32 }
33 IO(err: std::io::Error) {
34 from()
35 cause(err)
36 display("{}", err)
37 }
38 Msg(msg: String) {
39 from()
40 from(s: &'static str) -> (s.to_string())
41 description(msg)
42 display("{}", msg)
43 }
44 Utf8Error(err: std::str::Utf8Error) {
45 from()
46 cause(err)
47 display("{}", err)
48 }
49 }
50}
51
52type Result<T> = std::result::Result<T, Error>;
53
54const COMMIT_MESSAGE_COMMENT: &'static str = "
55# Please enter the commit message for your changes. Lines starting
56# with '#' will be ignored, and an empty message aborts the commit.
57";
58const COVER_LETTER_COMMENT: &'static str = "
59# Please enter the cover letter for your changes. Lines starting
60# with '#' will be ignored, and an empty message aborts the change.
61";
62const REBASE_COMMENT: &'static str = "\
63#
64# Commands:
65# p, pick = use commit
66# r, reword = use commit, but edit the commit message
67# e, edit = use commit, but stop for amending
68# s, squash = use commit, but meld into previous commit
69# f, fixup = like \"squash\", but discard this commit's log message
70# x, exec = run command (the rest of the line) using shell
71# d, drop = remove commit
72#
73# These lines can be re-ordered; they are executed from top to bottom.
74#
75# If you remove a line here THAT COMMIT WILL BE LOST.
76#
77# However, if you remove everything, the rebase will be aborted.
78";
79const SCISSOR_LINE: &'static str = "\
80# ------------------------ >8 ------------------------";
81const SCISSOR_COMMENT: &'static str = "\
82# Do not touch the line above.
83# Everything below will be removed.
84";
85
86const SHELL_METACHARS: &'static str = "|&;<>()$`\\\"' \t\n*?[#~=%";
87
88const SERIES_PREFIX: &'static str = "refs/heads/git-series/";
89const SHEAD_REF: &'static str = "refs/SHEAD";
90const STAGED_PREFIX: &'static str = "refs/git-series-internals/staged/";
91const WORKING_PREFIX: &'static str = "refs/git-series-internals/working/";
92
93const GIT_FILEMODE_BLOB: u32 = 0o100644;
94const GIT_FILEMODE_COMMIT: u32 = 0o160000;
95
96fn zero_oid() -> Oid {
97 Oid::from_bytes(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00").unwrap()
98}
99
100fn peel_to_commit(r: Reference) -> Result<Commit> {
101 Ok(try!(try!(r.peel(ObjectType::Commit)).into_commit().map_err(|obj| format!("Internal error: expected a commit: {}", obj.id()))))
102}
103
104fn commit_obj_summarize_components(commit: &mut Commit) -> Result<(String, String)> {
105 let short_id_buf = try!(commit.as_object().short_id());
106 let short_id = short_id_buf.as_str().unwrap();
107 let summary = String::from_utf8_lossy(commit.summary_bytes().unwrap());
108 Ok((short_id.to_string(), summary.to_string()))
109}
110
111fn commit_summarize_components(repo: &Repository, id: Oid) -> Result<(String, String)> {
112 let mut commit = try!(repo.find_commit(id));
113 commit_obj_summarize_components(&mut commit)
114}
115
116fn commit_obj_summarize(commit: &mut Commit) -> Result<String> {
117 let (short_id, summary) = try!(commit_obj_summarize_components(commit));
118 Ok(format!("{} {}", short_id, summary))
119}
120
121fn commit_summarize(repo: &Repository, id: Oid) -> Result<String> {
122 let mut commit = try!(repo.find_commit(id));
123 commit_obj_summarize(&mut commit)
124}
125
126fn notfound_to_none<T>(result: std::result::Result<T, git2::Error>) -> Result<Option<T>> {
127 match result {
128 Err(ref e) if e.code() == git2::ErrorCode::NotFound => Ok(None),
129 Err(e) => Err(e.into()),
130 Ok(x) => Ok(Some(x)),
131 }
132}
133
134// If current_id_opt is Some, acts like reference_matching. If current_id_opt is None, acts like
135// reference.
136fn reference_matching_opt<'repo>(repo: &'repo Repository, name: &str, id: Oid, force: bool, current_id_opt: Option<Oid>, log_message: &str) -> Result<Reference<'repo>> {
137 match current_id_opt {
138 None => Ok(try!(repo.reference(name, id, force, log_message))),
139 Some(current_id) => Ok(try!(repo.reference_matching(name, id, force, current_id, log_message))),
140 }
141}
142
143fn parents_from_ids(repo: &Repository, mut parents: Vec<Oid>) -> Result<Vec<Commit>> {
144 parents.sort();
145 parents.dedup();
146 parents.drain(..).map(|id| Ok(try!(repo.find_commit(id)))).collect::<Result<Vec<Commit>>>()
147}
148
149struct Internals<'repo> {
150 staged: TreeBuilder<'repo>,
151 working: TreeBuilder<'repo>,
152}
153
154impl<'repo> Internals<'repo> {
155 fn read(repo: &'repo Repository) -> Result<Self> {
156 let shead = try!(repo.find_reference(SHEAD_REF));
157 let series_name = try!(shead_series_name(&shead));
158 let mut internals = try!(Internals::read_series(repo, &series_name));
159 try!(internals.update_series(repo));
160 Ok(internals)
161 }
162
163 fn read_series(repo: &'repo Repository, series_name: &str) -> Result<Self> {
164 let committed_id = try!(notfound_to_none(repo.refname_to_id(&format!("{}{}", SERIES_PREFIX, series_name))));
165 let maybe_get_ref = |prefix: &str| -> Result<TreeBuilder<'repo>> {
166 match try!(notfound_to_none(repo.refname_to_id(&format!("{}{}", prefix, series_name)))).or(committed_id) {
167 Some(id) => {
168 let c = try!(repo.find_commit(id));
169 let t = try!(c.tree());
170 Ok(try!(repo.treebuilder(Some(&t))))
171 }
172 None => Ok(try!(repo.treebuilder(None))),
173 }
174 };
175 Ok(Internals {
176 staged: try!(maybe_get_ref(STAGED_PREFIX)),
177 working: try!(maybe_get_ref(WORKING_PREFIX)),
178 })
179 }
180
181 fn exists(repo: &'repo Repository, series_name: &str) -> Result<bool> {
182 for prefix in [SERIES_PREFIX, STAGED_PREFIX, WORKING_PREFIX].iter() {
183 let prefixed_name = format!("{}{}", prefix, series_name);
184 if try!(notfound_to_none(repo.refname_to_id(&prefixed_name))).is_some() {
185 return Ok(true);
186 }
187 }
188 Ok(false)
189 }
190
191 // Returns true if it had anything to delete.
192 fn delete(repo: &'repo Repository, series_name: &str) -> Result<bool> {
193 let mut deleted_any = false;
194 for prefix in [STAGED_PREFIX, WORKING_PREFIX].iter() {
195 let prefixed_name = format!("{}{}", prefix, series_name);
196 if let Some(mut r) = try!(notfound_to_none(repo.find_reference(&prefixed_name))) {
197 try!(r.delete());
198 deleted_any = true;
199 }
200 }
201 Ok(deleted_any)
202 }
203
204 fn update_series(&mut self, repo: &'repo Repository) -> Result<()> {
205 let head_id = try!(repo.refname_to_id("HEAD"));
206 try!(self.working.insert("series", head_id, GIT_FILEMODE_COMMIT as i32));
207 Ok(())
208 }
209
210 fn write(&self, repo: &'repo Repository) -> Result<()> {
211 let config = try!(repo.config());
212 let author = try!(get_signature(&config, "AUTHOR"));
213 let committer = try!(get_signature(&config, "COMMITTER"));
214
215 let shead = try!(repo.find_reference(SHEAD_REF));
216 let series_name = try!(shead_series_name(&shead));
217 let maybe_commit = |prefix: &str, tb: &TreeBuilder| -> Result<()> {
218 let tree_id = try!(tb.write());
219 let refname = format!("{}{}", prefix, series_name);
220 let old_commit_id = try!(notfound_to_none(repo.refname_to_id(&refname)));
221 if let Some(id) = old_commit_id {
222 let c = try!(repo.find_commit(id));
223 if c.tree_id() == tree_id {
224 return Ok(());
225 }
226 }
227 let tree = try!(repo.find_tree(tree_id));
228 let mut parents = Vec::new();
229 // Include all commits from tree, to keep them reachable and fetchable. Include base,
230 // because series might not have it as an ancestor; we don't enforce that until commit.
231 for e in tree.iter() {
232 if e.kind() == Some(ObjectType::Commit) {
233 parents.push(e.id());
234 }
235 }
236 let parents = try!(parents_from_ids(repo, parents));
237 let parents_ref: Vec<&_> = parents.iter().collect();
238 let commit_id = try!(repo.commit(None, &author, &committer, &refname, &tree, &parents_ref));
239 try!(repo.reference_ensure_log(&refname));
240 try!(reference_matching_opt(repo, &refname, commit_id, true, old_commit_id, &format!("commit: {}", refname)));
241 Ok(())
242 };
243 try!(maybe_commit(STAGED_PREFIX, &self.staged));
244 try!(maybe_commit(WORKING_PREFIX, &self.working));
245 Ok(())
246 }
247}
248
249fn diff_empty(diff: &Diff) -> bool {
250 diff.deltas().len() == 0
251}
252
253fn add(repo: &Repository, m: &ArgMatches) -> Result<()> {
254 let mut internals = try!(Internals::read(repo));
255 for file in m.values_of_os("change").unwrap() {
256 match try!(internals.working.get(file)) {
257 Some(entry) => { try!(internals.staged.insert(file, entry.id(), entry.filemode())); }
258 None => {
259 if try!(internals.staged.get(file)).is_some() {
260 try!(internals.staged.remove(file));
261 }
262 }
263 }
264 }
265 internals.write(repo)
266}
267
268fn unadd(repo: &Repository, m: &ArgMatches) -> Result<()> {
269 let shead = try!(repo.find_reference(SHEAD_REF));
270 let started = {
271 let shead_target = try!(shead.symbolic_target().ok_or("SHEAD not a symbolic reference"));
272 try!(notfound_to_none(repo.find_reference(shead_target))).is_some()
273 };
274
275 let mut internals = try!(Internals::read(repo));
276 if started {
277 let shead_commit = try!(peel_to_commit(shead));
278 let shead_tree = try!(shead_commit.tree());
279
280 for file in m.values_of("change").unwrap() {
281 match shead_tree.get_name(file) {
282 Some(entry) => {
283 try!(internals.staged.insert(file, entry.id(), entry.filemode()));
284 }
285 None => { try!(internals.staged.remove(file)); }
286 }
287 }
288 } else {
289 for file in m.values_of("change").unwrap() {
290 try!(internals.staged.remove(file))
291 }
292 }
293 internals.write(repo)
294}
295
296fn shead_series_name(shead: &Reference) -> Result<String> {
297 let shead_target = try!(shead.symbolic_target().ok_or("SHEAD not a symbolic reference"));
298 if !shead_target.starts_with(SERIES_PREFIX) {
299 return Err(format!("SHEAD does not start with {}", SERIES_PREFIX).into());
300 }
301 Ok(shead_target[SERIES_PREFIX.len()..].to_string())
302}
303
304fn series(out: &mut Output, repo: &Repository) -> Result<()> {
305 let mut refs = Vec::new();
306 for prefix in [SERIES_PREFIX, STAGED_PREFIX, WORKING_PREFIX].iter() {
307 let l = prefix.len();
308 for r in try!(repo.references_glob(&[prefix, "*"].concat())).names() {
309 refs.push(try!(r)[l..].to_string());
310 }
311 }
312 let shead_target = if let Some(shead) = try!(notfound_to_none(repo.find_reference(SHEAD_REF))) {
313 Some(try!(shead_series_name(&shead)).to_string())
314 } else {
315 None
316 };
317 refs.extend(shead_target.clone().into_iter());
318 refs.sort();
319 refs.dedup();
320
321 let config = try!(try!(repo.config()).snapshot());
322 try!(out.auto_pager(&config, "branch", false));
323 let color_current = try!(out.get_color(&config, "branch", "current", "green"));
324 let color_plain = try!(out.get_color(&config, "branch", "plain", "normal"));
325 for name in refs.iter() {
326 let (star, color) = if Some(name) == shead_target.as_ref() {
327 ('*', color_current)
328 } else {
329 (' ', color_plain)
330 };
331 let new = if try!(notfound_to_none(repo.refname_to_id(&format!("{}{}", SERIES_PREFIX, name)))).is_none() {
332 " (new, no commits yet)"
333 } else {
334 ""
335 };
336 try!(writeln!(out, "{} {}{}", star, color.paint(name as &str), new));
337 }
338 if refs.is_empty() {
339 try!(writeln!(out, "No series; use \"git series start <name>\" to start"));
340 }
341 Ok(())
342}
343
344fn start(repo: &Repository, m: &ArgMatches) -> Result<()> {
345 let head = try!(repo.head());
346 let head_commit = try!(peel_to_commit(head));
347 let head_id = head_commit.as_object().id();
348
349 let name = m.value_of("name").unwrap();
350 if try!(Internals::exists(repo, name)) {
351 return Err(format!("Series {} already exists.\nUse checkout to resume working on an existing patch series.", name).into());
352 }
353 let prefixed_name = &[SERIES_PREFIX, name].concat();
354 try!(repo.reference_symbolic(SHEAD_REF, &prefixed_name, true, &format!("git series start {}", name)));
355
356 let internals = try!(Internals::read(repo));
357 try!(internals.write(repo));
358
359 // git status parses this reflog string; the prefix must remain "checkout: moving from ".
360 try!(repo.reference("HEAD", head_id, true, &format!("checkout: moving from {} to {} (git series start {})", head_id, head_id, name)));
361 println!("HEAD is now detached at {}", try!(commit_summarize(&repo, head_id)));
362 Ok(())
363}
364
365fn checkout_tree(repo: &Repository, treeish: &Object) -> Result<()> {
366 let mut conflicts = Vec::new();
367 let mut dirty = Vec::new();
368 let result = {
369 let mut opts = git2::build::CheckoutBuilder::new();
370 opts.safe();
371 opts.notify_on(git2::CHECKOUT_NOTIFICATION_CONFLICT | git2::CHECKOUT_NOTIFICATION_DIRTY);
372 opts.notify(|t, path, _, _, _| {
373 let path = path.unwrap().to_owned();
374 if t == git2::CHECKOUT_NOTIFICATION_CONFLICT {
375 conflicts.push(path);
376 } else if t == git2::CHECKOUT_NOTIFICATION_DIRTY {
377 dirty.push(path);
378 }
379 true
380 });
381 if isatty::stdout_isatty() {
382 opts.progress(|_, completed, total| {
383 let total = total.to_string();
384 print!("\rChecking out files: {1:0$}/{2}", total.len(), completed, total);
385 });
386 }
387 repo.checkout_tree(treeish, Some(&mut opts))
388 };
389 match result {
390 Err(ref e) if e.code() == git2::ErrorCode::Conflict => {
391 let mut msg = String::new();
392 writeln!(msg, "error: Your changes to the following files would be overwritten by checkout:").unwrap();
393 for path in conflicts {
394 writeln!(msg, " {}", path.to_string_lossy()).unwrap();
395 }
396 writeln!(msg, "Please, commit your changes or stash them before you switch series.").unwrap();
397 return Err(msg.into());
398 }
399 _ => try!(result),
400 }
401 println!("");
402 if !dirty.is_empty() {
403 let mut stderr = std::io::stderr();
404 writeln!(stderr, "Files with changes unaffected by checkout:").unwrap();
405 for path in dirty {
406 writeln!(stderr, " {}", path.to_string_lossy()).unwrap();
407 }
408 }
409 Ok(())
410}
411
412fn checkout(repo: &Repository, m: &ArgMatches) -> Result<()> {
413 match repo.state() {
414 git2::RepositoryState::Clean => (),
415 s => { return Err(format!("{:?} in progress; cannot checkout patch series", s).into()); }
416 }
417 let name = m.value_of("name").unwrap();
418 if !try!(Internals::exists(repo, name)) {
419 return Err(format!("Series {} does not exist.\nUse \"git series start <name>\" to start a new patch series.", name).into());
420 }
421
422 let internals = try!(Internals::read_series(repo, name));
423 let new_head_id = try!(try!(internals.working.get("series")).ok_or(format!("Could not find \"series\" in \"{}\"", name))).id();
424 let new_head = try!(repo.find_commit(new_head_id)).into_object();
425
426 try!(checkout_tree(repo, &new_head));
427
428 let head = try!(repo.head());
429 let head_commit = try!(peel_to_commit(head));
430 let head_id = head_commit.as_object().id();
431 println!("Previous HEAD position was {}", try!(commit_summarize(&repo, head_id)));
432
433 let prefixed_name = &[SERIES_PREFIX, name].concat();
434 try!(repo.reference_symbolic(SHEAD_REF, &prefixed_name, true, &format!("git series checkout {}", name)));
435 try!(internals.write(repo));
436
437 // git status parses this reflog string; the prefix must remain "checkout: moving from ".
438 try!(repo.reference("HEAD", new_head_id, true, &format!("checkout: moving from {} to {} (git series checkout {})", head_id, new_head_id, name)));
439 println!("HEAD is now detached at {}", try!(commit_summarize(&repo, new_head_id)));
440
441 Ok(())
442}
443
444fn base(repo: &Repository, m: &ArgMatches) -> Result<()> {
445 let mut internals = try!(Internals::read(repo));
446
447 let current_base_id = match try!(internals.working.get("base")) {
448 Some(entry) => entry.id(),
449 _ => zero_oid(),
450 };
451
452 if !m.is_present("delete") && !m.is_present("base") {
453 if current_base_id.is_zero() {
454 return Err("Patch series has no base set".into());
455 } else {
456 println!("{}", current_base_id);
457 return Ok(());
458 }
459 }
460
461 let new_base_id = if m.is_present("delete") {
462 zero_oid()
463 } else {
464 let base = m.value_of("base").unwrap();
465 let base_object = try!(repo.revparse_single(base));
466 let base_commit = try!(base_object.peel(ObjectType::Commit));
467 let base_id = base_commit.id();
468 let s_working_series = try!(try!(internals.working.get("series")).ok_or("Could not find entry \"series\" in working vesion of current series"));
469 if base_id != s_working_series.id() && !try!(repo.graph_descendant_of(s_working_series.id(), base_id)) {
470 return Err(format!("Cannot set base to {}: not an ancestor of the patch series {}", base, s_working_series.id()).into());
471 }
472 base_id
473 };
474
475 if current_base_id == new_base_id {
476 println!("Base unchanged");
477 return Ok(());
478 }
479
480 if !current_base_id.is_zero() {
481 println!("Previous base was {}", try!(commit_summarize(&repo, current_base_id)));
482 }
483
484 if new_base_id.is_zero() {
485 try!(internals.working.remove("base"));
486 try!(internals.write(repo));
487 println!("Cleared patch series base");
488 } else {
489 try!(internals.working.insert("base", new_base_id, GIT_FILEMODE_COMMIT as i32));
490 try!(internals.write(repo));
491 println!("Set patch series base to {}", try!(commit_summarize(&repo, new_base_id)));
492 }
493
494 Ok(())
495}
496
497fn detach(repo: &Repository) -> Result<()> {
498 match repo.find_reference(SHEAD_REF) {
499 Ok(mut r) => try!(r.delete()),
500 Err(_) => { return Err("No current patch series to detach from.".into()); }
501 }
502 Ok(())
503}
504
505fn delete(repo: &Repository, m: &ArgMatches) -> Result<()> {
506 let name = m.value_of("name").unwrap();
507 if let Ok(shead) = repo.find_reference(SHEAD_REF) {
508 let shead_target = try!(shead_series_name(&shead));
509 if shead_target == name {
510 return Err(format!("Cannot delete the current series \"{}\"; detach first.", name).into());
511 }
512 }
513 let prefixed_name = &[SERIES_PREFIX, name].concat();
514 let deleted_ref = if let Some(mut r) = try!(notfound_to_none(repo.find_reference(prefixed_name))) {
515 try!(r.delete());
516 true
517 } else {
518 false
519 };
520 let deleted_internals = try!(Internals::delete(repo, name));
521 if !deleted_ref && !deleted_internals {
522 return Err(format!("Nothing to delete: series \"{}\" does not exist.", name).into());
523 }
524 Ok(())
525}
526
527fn get_editor(config: &Config) -> Result<OsString> {
528 if let Some(e) = env::var_os("GIT_EDITOR") {
529 return Ok(e);
530 }
531 if let Ok(e) = config.get_path("core.editor") {
532 return Ok(e.into());
533 }
534 let terminal_is_dumb = match env::var_os("TERM") {
535 None => true,
536 Some(t) => t.as_os_str() == "dumb",
537 };
538 if !terminal_is_dumb {
539 if let Some(e) = env::var_os("VISUAL") {
540 return Ok(e);
541 }
542 }
543 if let Some(e) = env::var_os("EDITOR") {
544 return Ok(e);
545 }
546 if terminal_is_dumb {
547 return Err("TERM unset or \"dumb\" but EDITOR unset".into());
548 }
549 return Ok("vi".into());
550}
551
552// Get the pager to use; with for_cmd set, get the pager for use by the
553// specified git command. If get_pager returns None, don't use a pager.
554fn get_pager(config: &Config, for_cmd: &str, default: bool) -> Option<OsString> {
555 if !isatty::stdout_isatty() {
556 return None;
557 }
558 // pager.cmd can contain a boolean (if false, force no pager) or a
559 // command-specific pager; only treat it as a command if it doesn't parse
560 // as a boolean.
561 let maybe_pager = config.get_path(&format!("pager.{}", for_cmd)).ok();
562 let (cmd_want_pager, cmd_pager) = maybe_pager.map_or((default, None), |p|
563 if let Ok(b) = Config::parse_bool(&p) {
564 (b, None)
565 } else {
566 (true, Some(p))
567 }
568 );
569 if !cmd_want_pager {
570 return None;
571 }
572 let pager =
573 if let Some(e) = env::var_os("GIT_PAGER") {
574 Some(e)
575 } else if let Some(p) = cmd_pager {
576 Some(p.into())
577 } else if let Ok(e) = config.get_path("core.pager") {
578 Some(e.into())
579 } else if let Some(e) = env::var_os("PAGER") {
580 Some(e)
581 } else {
582 Some("less".into())
583 };
584 pager.and_then(|p| if p.is_empty() || p == OsString::from("cat") { None } else { Some(p) })
585}
586
587/// Construct a Command, using the shell if the command contains shell metachars
588fn cmd_maybe_shell<S: AsRef<OsStr>>(program: S, args: bool) -> Command {
589 if program.as_ref().to_string_lossy().contains(|c| SHELL_METACHARS.contains(c)) {
590 let mut cmd = Command::new("sh");
591 cmd.arg("-c");
592 if args {
593 let mut program_with_args = program.as_ref().to_os_string();
594 program_with_args.push(" \"$@\"");
595 cmd.arg(program_with_args).arg(program);
596 } else {
597 cmd.arg(program);
598 }
599 cmd
600 } else {
601 Command::new(program)
602 }
603}
604
605fn run_editor<S: AsRef<OsStr>>(config: &Config, filename: S) -> Result<()> {
606 let editor = try!(get_editor(&config));
607 let editor_status = try!(cmd_maybe_shell(editor, true).arg(&filename).status());
608 if !editor_status.success() {
609 return Err(format!("Editor exited with status {}", editor_status).into());
610 }
611 Ok(())
612}
613
614struct Output {
615 pager: Option<std::process::Child>,
616 include_stderr: bool,
617}
618
619impl Output {
620 fn new() -> Self {
621 Output { pager: None, include_stderr: false }
622 }
623
624 fn auto_pager(&mut self, config: &Config, for_cmd: &str, default: bool) -> Result<()> {
625 if let Some(pager) = get_pager(config, for_cmd, default) {
626 let mut cmd = cmd_maybe_shell(pager, false);
627 cmd.stdin(std::process::Stdio::piped());
628 if env::var_os("LESS").is_none() {
629 cmd.env("LESS", "FRX");
630 }
631 if env::var_os("LV").is_none() {
632 cmd.env("LV", "-c");
633 }
634 let child = try!(cmd.spawn());
635 self.pager = Some(child);
636 self.include_stderr = isatty::stderr_isatty();
637 }
638 Ok(())
639 }
640
641 // Get a color to write text with, taking git configuration into account.
642 //
643 // config: the configuration to determine the color from.
644 // command: the git command to act like.
645 // slot: the color "slot" of that git command to act like.
646 // default: the color to use if not configured.
647 fn get_color(&self, config: &Config, command: &str, slot: &str, default: &str) -> Result<Style> {
648 if !cfg!(unix) {
649 return Ok(Style::new());
650 }
651 let color_ui = try!(notfound_to_none(config.get_str("color.ui"))).unwrap_or("auto");
652 let color_cmd = try!(notfound_to_none(config.get_str(&format!("color.{}", command)))).unwrap_or(color_ui);
653 if color_cmd == "never" || Config::parse_bool(color_cmd) == Ok(false) {
654 return Ok(Style::new());
655 }
656 if self.pager.is_some() {
657 let color_pager = try!(notfound_to_none(config.get_bool(&format!("color.pager")))).unwrap_or(true);
658 if !color_pager {
659 return Ok(Style::new());
660 }
661 } else if !isatty::stdout_isatty() {
662 return Ok(Style::new());
663 }
664 let cfg = format!("color.{}.{}", command, slot);
665 let color = try!(notfound_to_none(config.get_str(&cfg))).unwrap_or(default);
666 colorparse::parse(color).map_err(|e| format!("Error parsing {}: {}", cfg, e).into())
667 }
668
669 fn write_err(&mut self, msg: &str) {
670 if self.include_stderr {
671 if write!(self, "{}", msg).is_err() {
672 write!(std::io::stderr(), "{}", msg).unwrap();
673 }
674 } else {
675 write!(std::io::stderr(), "{}", msg).unwrap();
676 }
677 }
678}
679
680impl Drop for Output {
681 fn drop(&mut self) {
682 if let Some(ref mut child) = self.pager {
683 let status = child.wait().unwrap();
684 if !status.success() {
685 writeln!(std::io::stderr(), "Pager exited with status {}", status).unwrap();
686 }
687 }
688 }
689}
690
691impl IoWrite for Output {
692 fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
693 match self.pager {
694 Some(ref mut child) => child.stdin.as_mut().unwrap().write(buf),
695 None => std::io::stdout().write(buf),
696 }
697 }
698
699 fn flush(&mut self) -> std::io::Result<()> {
700 match self.pager {
701 Some(ref mut child) => child.stdin.as_mut().unwrap().flush(),
702 None => std::io::stdout().flush(),
703 }
704 }
705}
706
707fn get_signature(config: &Config, which: &str) -> Result<git2::Signature<'static>> {
708 let name_var = ["GIT_", which, "_NAME"].concat();
709 let email_var = ["GIT_", which, "_EMAIL"].concat();
710 let which_lc = which.to_lowercase();
711 let name = try!(env::var(&name_var).or_else(
712 |_| config.get_string("user.name").or_else(
713 |_| Err(format!("Could not determine {} name: checked ${} and user.name in git config", which_lc, name_var)))));
714 let email = try!(env::var(&email_var).or_else(
715 |_| config.get_string("user.email").or_else(
716 |_| env::var("EMAIL").or_else(
717 |_| Err(format!("Could not determine {} email: checked ${}, user.email in git config, and $EMAIL", which_lc, email_var))))));
718 Ok(try!(git2::Signature::now(&name, &email)))
719}
720
721fn commit_status(out: &mut Output, repo: &Repository, m: &ArgMatches, do_status: bool) -> Result<()> {
722 let config = try!(try!(repo.config()).snapshot());
723 let shead = match repo.find_reference(SHEAD_REF) {
724 Err(ref e) if e.code() == git2::ErrorCode::NotFound => { println!("No series; use \"git series start <name>\" to start"); return Ok(()); }
725 result => try!(result),
726 };
727 let series_name = try!(shead_series_name(&shead));
728
729 if do_status {
730 try!(out.auto_pager(&config, "status", false));
731 }
732 let get_color = |out: &Output, color: &str, default: &str| {
733 if do_status {
734 out.get_color(&config, "status", color, default)
735 } else {
736 Ok(Style::new())
737 }
738 };
739 let color_normal = Style::new();
740 let color_header = try!(get_color(out, "header", "normal"));
741 let color_updated = try!(get_color(out, "updated", "green"));
742 let color_changed = try!(get_color(out, "changed", "red"));
743
744 let write_status = |status: &mut Vec<ansi_term::ANSIString>, diff: &Diff, heading: &str, color: &Style, show_hints: bool, hints: &[&str]| -> Result<bool> {
745 let mut changes = false;
746
747 try!(diff.foreach(&mut |delta, _| {
748 if !changes {
749 changes = true;
750 status.push(color_header.paint(format!("{}\n", heading.to_string())));
751 if show_hints {
752 for hint in hints {
753 status.push(color_header.paint(format!(" ({})\n", hint)));
754 }
755 }
756 status.push(color_normal.paint("\n"));
757 }
758 status.push(color_normal.paint(" "));
759 status.push(color.paint(format!("{:?}: {}\n", delta.status(), delta.old_file().path().unwrap().to_str().unwrap())));
760 true
761 }, None, None, None));
762
763 if changes {
764 status.push(color_normal.paint("\n"));
765 }
766
767 Ok(changes)
768 };
769
770 let mut status = Vec::new();
771 status.push(color_header.paint(format!("On series {}\n", series_name)));
772
773 let mut internals = try!(Internals::read(repo));
774 let working_tree = try!(repo.find_tree(try!(internals.working.write())));
775 let staged_tree = try!(repo.find_tree(try!(internals.staged.write())));
776
777 let shead_commit = match shead.resolve() {
778 Ok(r) => Some(try!(peel_to_commit(r))),
779 Err(ref e) if e.code() == git2::ErrorCode::NotFound => {
780 status.push(color_header.paint("\nInitial series commit\n"));
781 None
782 }
783 Err(e) => try!(Err(e)),
784 };
785 let shead_tree = match shead_commit {
786 Some(ref c) => Some(try!(c.tree())),
787 None => None,
788 };
789
790 let commit_all = m.is_present("all");
791
792 let (changes, tree, diff) = if commit_all {
793 let diff = try!(repo.diff_tree_to_tree(shead_tree.as_ref(), Some(&working_tree), None));
794 let changes = try!(write_status(&mut status, &diff, "Changes to be committed:", &color_normal, false, &[]));
795 if !changes {
796 status.push(color_normal.paint("nothing to commit; series unchanged\n"));
797 }
798 (changes, working_tree, diff)
799 } else {
800 let diff = try!(repo.diff_tree_to_tree(shead_tree.as_ref(), Some(&staged_tree), None));
801 let changes_to_be_committed = try!(write_status(&mut status, &diff,
802 "Changes to be committed:", &color_updated, do_status,
803 &["use \"git series commit\" to commit",
804 "use \"git series unadd <file>...\" to undo add"]));
805
806 let diff_not_staged = try!(repo.diff_tree_to_tree(Some(&staged_tree), Some(&working_tree), None));
807 let changes_not_staged = try!(write_status(&mut status, &diff_not_staged,
808 "Changes not staged for commit:", &color_changed, do_status,
809 &["use \"git series add <file>...\" to update what will be committed"]));
810
811 if !changes_to_be_committed {
812 if changes_not_staged {
813 status.push(color_normal.paint("no changes added to commit (use \"git series add\" or \"git series commit -a\")\n"));
814 } else {
815 status.push(color_normal.paint("nothing to commit; series unchanged\n"));
816 }
817 }
818
819 (changes_to_be_committed, staged_tree, diff)
820 };
821
822 let status = ansi_term::ANSIStrings(&status).to_string();
823 if do_status || !changes {
824 if do_status {
825 try!(write!(out, "{}", status));
826 } else {
827 return Err(status.into());
828 }
829 return Ok(());
830 }
831
832 // Check that the commit includes the series
833 let series_id = match tree.get_name("series") {
834 None => { return Err(concat!("Cannot commit: initial commit must include \"series\"\n",
835 "Use \"git series add series\" or \"git series commit -a\"").into()); }
836 Some(series) => series.id()
837 };
838
839 // Check that the base is still an ancestor of the series
840 if let Some(base) = tree.get_name("base") {
841 if base.id() != series_id && !try!(repo.graph_descendant_of(series_id, base.id())) {
842 let (base_short_id, base_summary) = try!(commit_summarize_components(&repo, base.id()));
843 let (series_short_id, series_summary) = try!(commit_summarize_components(&repo, series_id));
844 return Err(format!(concat!(
845 "Cannot commit: base {} is not an ancestor of patch series {}\n",
846 "base {} {}\n",
847 "series {} {}"),
848 base_short_id, series_short_id,
849 base_short_id, base_summary,
850 series_short_id, series_summary).into());
851 }
852 }
853
854 let msg = match m.value_of("m") {
855 Some(s) => s.to_string(),
856 None => {
857 let filename = repo.path().join("SCOMMIT_EDITMSG");
858 let mut file = try!(File::create(&filename));
859 try!(write!(file, "{}", COMMIT_MESSAGE_COMMENT));
860 for line in status.lines() {
861 if line.is_empty() {
862 try!(writeln!(file, "#"));
863 } else {
864 try!(writeln!(file, "# {}", line));
865 }
866 }
867 if m.is_present("verbose") {
868 try!(writeln!(file, "{}\n{}", SCISSOR_LINE, SCISSOR_COMMENT));
869 try!(write_diff(&mut file, &DiffColors::plain(), &diff));
870 }
871 drop(file);
872 try!(run_editor(&config, &filename));
873 let mut file = try!(File::open(&filename));
874 let mut msg = String::new();
875 try!(file.read_to_string(&mut msg));
876 if let Some(scissor_index) = msg.find(SCISSOR_LINE) {
877 msg.truncate(scissor_index);
878 }
879 try!(git2::message_prettify(msg, git2::DEFAULT_COMMENT_CHAR))
880 }
881 };
882 if msg.is_empty() {
883 return Err("Aborting series commit due to empty commit message.".into());
884 }
885
886 let author = try!(get_signature(&config, "AUTHOR"));
887 let committer = try!(get_signature(&config, "COMMITTER"));
888 let mut parents: Vec<Oid> = Vec::new();
889 // Include all commits from tree, to keep them reachable and fetchable.
890 for e in tree.iter() {
891 if e.kind() == Some(ObjectType::Commit) && e.name().unwrap() != "base" {
892 parents.push(e.id())
893 }
894 }
895 let parents = try!(parents_from_ids(repo, parents));
896 let parents_ref: Vec<&_> = shead_commit.iter().chain(parents.iter()).collect();
897 let new_commit_oid = try!(repo.commit(Some(SHEAD_REF), &author, &committer, &msg, &tree, &parents_ref));
898
899 if commit_all {
900 internals.staged = try!(repo.treebuilder(Some(&tree)));
901 try!(internals.write(repo));
902 }
903
904 let (new_commit_short_id, new_commit_summary) = try!(commit_summarize_components(&repo, new_commit_oid));
905 try!(writeln!(out, "[{} {}] {}", series_name, new_commit_short_id, new_commit_summary));
906
907 Ok(())
908}
909
910fn cover(repo: &Repository, m: &ArgMatches) -> Result<()> {
911 let mut internals = try!(Internals::read(repo));
912
913 let (working_cover_id, working_cover_content) = match try!(internals.working.get("cover")) {
914 None => (zero_oid(), String::new()),
915 Some(entry) => (entry.id(), try!(std::str::from_utf8(try!(repo.find_blob(entry.id())).content())).to_string()),
916 };
917
918 if m.is_present("delete") {
919 if working_cover_id.is_zero() {
920 return Err("No cover to delete".into());
921 }
922 try!(internals.working.remove("cover"));
923 try!(internals.write(repo));
924 println!("Deleted cover letter");
925 return Ok(());
926 }
927
928 let filename = repo.path().join("COVER_EDITMSG");
929 let mut file = try!(File::create(&filename));
930 if working_cover_content.is_empty() {
931 try!(write!(file, "{}", COVER_LETTER_COMMENT));
932 } else {
933 try!(write!(file, "{}", working_cover_content));
934 }
935 drop(file);
936 let config = try!(repo.config());
937 try!(run_editor(&config, &filename));
938 let mut file = try!(File::open(&filename));
939 let mut msg = String::new();
940 try!(file.read_to_string(&mut msg));
941 let msg = try!(git2::message_prettify(msg, git2::DEFAULT_COMMENT_CHAR));
942 if msg.is_empty() {
943 return Err("Empty cover letter; not changing.\n(To delete the cover letter, use \"git series cover -d\".)".into());
944 }
945
946 let new_cover_id = try!(repo.blob(msg.as_bytes()));
947 if new_cover_id == working_cover_id {
948 println!("Cover letter unchanged");
949 } else {
950 try!(internals.working.insert("cover", new_cover_id, GIT_FILEMODE_BLOB as i32));
951 try!(internals.write(repo));
952 println!("Updated cover letter");
953 }
954
955 Ok(())
956}
957
958fn date_822(t: git2::Time) -> String {
959 let offset = chrono::offset::fixed::FixedOffset::east(t.offset_minutes()*60);
960 let datetime = offset.timestamp(t.seconds(), 0);
961 datetime.to_rfc2822()
962}
963
964fn shortlog(commits: &mut [Commit]) -> String {
965 let mut s = String::new();
966 let mut author_map = std::collections::HashMap::new();
967
968 for mut commit in commits {
969 let author = commit.author().name().unwrap().to_string();
970 author_map.entry(author).or_insert(Vec::new()).push(commit.summary().unwrap().to_string());
971 }
972
973 let mut authors: Vec<_> = author_map.keys().collect();
974 authors.sort();
975 let mut first = true;
976 for author in authors {
977 if first {
978 first = false;
979 } else {
980 writeln!(s, "").unwrap();
981 }
982 let summaries = author_map.get(author).unwrap();
983 writeln!(s, "{} ({}):", author, summaries.len()).unwrap();
984 for summary in summaries {
985 writeln!(s, " {}", summary).unwrap();
986 }
987 }
988
989 s
990}
991
992fn ascii_isalnum(c: char) -> bool {
993 (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
994}
995
996fn sanitize_summary(summary: &str) -> String {
997 let mut s = String::with_capacity(summary.len());
998 let mut prev_dot = false;
999 let mut need_space = false;
1000 for c in summary.chars() {
1001 if ascii_isalnum(c) || c == '_' || c == '.' {
1002 if need_space {
1003 s.push('-');
1004 need_space = false;
1005 }
1006 if !(prev_dot && c == '.') {
1007 s.push(c);
1008 }
1009 } else {
1010 if !s.is_empty() {
1011 need_space = true;
1012 }
1013 }
1014 prev_dot = c == '.';
1015 }
1016 let end = s.trim_right_matches(|c| c == '.' || c == '-').len();
1017 s.truncate(end);
1018 s
1019}
1020
1021#[test]
1022fn test_sanitize_summary() {
1023 let tests = vec![
1024 ("", ""),
1025 ("!!!!!", ""),
1026 ("Test", "Test"),
1027 ("Test case", "Test-case"),
1028 ("Test case", "Test-case"),
1029 (" Test case ", "Test-case"),
1030 ("...Test...case...", ".Test.case"),
1031 ("...Test...case.!!", ".Test.case"),
1032 (".!.Test.!.case.!.", ".-.Test.-.case"),
1033 ];
1034 for (summary, sanitized) in tests {
1035 assert_eq!(sanitize_summary(summary), sanitized.to_string());
1036 }
1037}
1038
1039fn split_message(message: &str) -> (&str, &str) {
1040 let mut iter = message.splitn(2, '\n');
1041 let subject = iter.next().unwrap().trim_right();
1042 let body = iter.next().map(|s| s.trim_left()).unwrap_or("");
1043 (subject, body)
1044}
1045
1046struct DiffColors {
1047 commit: Style,
1048 meta: Style,
1049 frag: Style,
1050 func: Style,
1051 context: Style,
1052 old: Style,
1053 new: Style,
1054}
1055
1056impl DiffColors {
1057 fn plain() -> Self {
1058 DiffColors {
1059 commit: Style::new(),
1060 meta: Style::new(),
1061 frag: Style::new(),
1062 func: Style::new(),
1063 context: Style::new(),
1064 old: Style::new(),
1065 new: Style::new(),
1066 }
1067 }
1068
1069 fn new(out: &Output, config: &Config) -> Result<Self> {
1070 Ok(DiffColors {
1071 commit: try!(out.get_color(&config, "diff", "commit", "yellow")),
1072 meta: try!(out.get_color(&config, "diff", "meta", "bold")),
1073 frag: try!(out.get_color(&config, "diff", "frag", "cyan")),
1074 func: try!(out.get_color(&config, "diff", "func", "normal")),
1075 context: try!(out.get_color(&config, "diff", "context", "normal")),
1076 old: try!(out.get_color(&config, "diff", "old", "red")),
1077 new: try!(out.get_color(&config, "diff", "new", "green")),
1078 })
1079 }
1080}
1081
1082fn diffstat(diff: &Diff) -> Result<String> {
1083 let stats = try!(diff.stats());
1084 let stats_buf = try!(stats.to_buf(git2::DIFF_STATS_FULL|git2::DIFF_STATS_INCLUDE_SUMMARY, 72));
1085 Ok(stats_buf.as_str().unwrap().to_string())
1086}
1087
1088fn write_diff<W: IoWrite>(f: &mut W, colors: &DiffColors, diff: &Diff) -> Result<()> {
1089 let mut err = Ok(());
1090 let normal = Style::new();
1091 try!(diff.print(git2::DiffFormat::Patch, |_, _, l| {
1092 err = || -> Result<()> {
1093 let o = l.origin();
1094 let style = match o {
1095 ' '|'=' => colors.context,
1096 '-'|'<' => colors.old,
1097 '+'|'>' => colors.new,
1098 'F' => colors.meta,
1099 'H' => colors.frag,
1100 _ => normal,
1101 };
1102 let obyte = [o as u8];
1103 let mut v = Vec::new();
1104 if o == '+' || o == '-' || o == ' ' {
1105 v.push(style.paint(&obyte[..]));
1106 }
1107 if o == 'H' {
1108 // Split frag and func
1109 let line = l.content();
1110 let at = &|&(_,&c): &(usize, &u8)| c == b'@';
1111 let not_at = &|&(_,&c): &(usize, &u8)| c != b'@';
1112 match line.iter().enumerate().skip_while(at).skip_while(not_at).skip_while(at).nth(1).unwrap_or((0,&b'\n')) {
1113 (_,&c) if c == b'\n' => v.push(style.paint(&line[..line.len()-1])),
1114 (pos,_) => {
1115 v.push(style.paint(&line[..pos-1]));
1116 v.push(normal.paint(" ".as_bytes()));
1117 v.push(colors.func.paint(&line[pos..line.len()-1]));
1118 },
1119 }
1120 v.push(normal.paint("\n".as_bytes()));
1121 } else {
1122 // The less pager resets ANSI colors at each newline, so emit colors separately for
1123 // each line.
1124 for (n, line) in l.content().split(|c| *c == b'\n').enumerate() {
1125 if n != 0 {
1126 v.push(normal.paint("\n".as_bytes()));
1127 }
1128 if !line.is_empty() {
1129 v.push(style.paint(line));
1130 }
1131 }
1132 }
1133 try!(ansi_term::ANSIByteStrings(&v).write_to(f));
1134 Ok(())
1135 }();
1136 err.is_ok()
1137 }));
1138 err
1139}
1140
1141fn mail_signature() -> String {
1142 format!("-- \ngit-series {}", crate_version!())
1143}
1144
1145fn ensure_space(s: &str) -> &'static str {
1146 if s.is_empty() || s.ends_with(' ') {
1147 ""
1148 } else {
1149 " "
1150 }
1151}
1152
1153fn ensure_nl(s: &str) -> &'static str {
1154 if !s.ends_with('\n') {
1155 "\n"
1156 } else {
1157 ""
1158 }
1159}
1160
1161fn format(out: &mut Output, repo: &Repository, m: &ArgMatches) -> Result<()> {
1162 let config = try!(try!(repo.config()).snapshot());
1163 let to_stdout = m.is_present("stdout");
1164 let no_from = m.is_present("no-from");
1165
1166 let shead_commit = try!(peel_to_commit(try!(try!(repo.find_reference(SHEAD_REF)).resolve())));
1167 let stree = try!(shead_commit.tree());
1168
1169 let series = try!(stree.get_name("series").ok_or("Internal error: series did not contain \"series\""));
1170 let base = try!(stree.get_name("base").ok_or("Cannot format series; no base set.\nUse \"git series base\" to set base."));
1171
1172 let mut revwalk = try!(repo.revwalk());
1173 revwalk.set_sorting(git2::SORT_TOPOLOGICAL|git2::SORT_REVERSE);
1174 try!(revwalk.push(series.id()));
1175 try!(revwalk.hide(base.id()));
1176 let mut commits: Vec<Commit> = try!(revwalk.map(|c| {
1177 let id = try!(c);
1178 let commit = try!(repo.find_commit(id));
1179 if commit.parent_ids().count() > 1 {
1180 return Err(format!("Error: cannot format merge commit as patch:\n{}", try!(commit_summarize(repo, id))).into());
1181 }
1182 Ok(commit)
1183 }).collect::<Result<_>>());
1184 if commits.is_empty() {
1185 return Err("No patches to format; series and base identical.".into());
1186 }
1187
1188 let committer = try!(get_signature(&config, "COMMITTER"));
1189 let committer_name = committer.name().unwrap();
1190 let committer_email = committer.email().unwrap();
1191 let message_id_suffix = format!("{}.git-series.{}", committer.when().seconds(), committer_email);
1192
1193 let cover_entry = stree.get_name("cover");
1194 let mut in_reply_to_message_id = m.value_of("in-reply-to").map(|v| {
1195 format!("{}{}{}",
1196 if v.starts_with('<') { "" } else { "<" },
1197 v,
1198 if v.ends_with('>') { "" } else { ">" })
1199 });
1200
1201 let version = m.value_of("reroll-count");
1202 let subject_prefix = m.value_of("subject-prefix").unwrap_or("PATCH");
1203 let subject_patch = version.map_or(
1204 subject_prefix.to_string(),
1205 |n| format!("{}{}v{}", subject_prefix, ensure_space(&subject_prefix), n));
1206 let file_prefix = version.map_or("".to_string(), |n| format!("v{}-", n));
1207
1208 let signature = mail_signature();
1209
1210 if to_stdout {
1211 try!(out.auto_pager(&config, "format-patch", true));
1212 }
1213 let diffcolors = if to_stdout {
1214 try!(DiffColors::new(out, &config))
1215 } else {
1216 DiffColors::plain()
1217 };
1218 let mut out : Box<IoWrite> = if to_stdout {
1219 Box::new(out)
1220 } else {
1221 Box::new(std::io::stdout())
1222 };
1223 let patch_file = |name: &str| -> Result<Box<IoWrite>> {
1224 let name = format!("{}{}", file_prefix, name);
1225 println!("{}", name);
1226 Ok(Box::new(try!(File::create(name))))
1227 };
1228
1229 if let Some(ref entry) = cover_entry {
1230 let cover_blob = try!(repo.find_blob(entry.id()));
1231 let content = try!(std::str::from_utf8(cover_blob.content())).to_string();
1232 let (subject, body) = split_message(&content);
1233
1234 let series_tree = try!(repo.find_commit(series.id())).tree().unwrap();
1235 let base_tree = try!(repo.find_commit(base.id())).tree().unwrap();
1236 let diff = try!(repo.diff_tree_to_tree(Some(&base_tree), Some(&series_tree), None));
1237 let stats = try!(diffstat(&diff));
1238
1239 if !to_stdout {
1240 out = try!(patch_file("0000-cover-letter.patch"));
1241 }
1242 try!(writeln!(out, "From {} Mon Sep 17 00:00:00 2001", shead_commit.id()));
1243 let cover_message_id = format!("<cover.{}.{}>", shead_commit.id(), message_id_suffix);
1244 try!(writeln!(out, "Message-Id: {}", cover_message_id));
1245 if let Some(ref message_id) = in_reply_to_message_id {
1246 try!(writeln!(out, "In-Reply-To: {}", message_id));
1247 try!(writeln!(out, "References: {}", message_id));
1248 }
1249 in_reply_to_message_id = Some(cover_message_id);
1250 try!(writeln!(out, "From: {} <{}>", committer_name, committer_email));
1251 try!(writeln!(out, "Date: {}", date_822(committer.when())));
1252 try!(writeln!(out, "Subject: [{}{}0/{}] {}\n", subject_patch, ensure_space(&subject_patch), commits.len(), subject));
1253 if !body.is_empty() {
1254 try!(writeln!(out, "{}", body));
1255 }
1256 try!(writeln!(out, "{}", shortlog(&mut commits)));
1257 try!(writeln!(out, "{}", stats));
1258 try!(writeln!(out, "base-commit: {}", base.id()));
1259 try!(writeln!(out, "{}", signature));
1260 }
1261
1262 for (commit_num, commit) in commits.iter().enumerate() {
1263 let first_mail = commit_num == 0 && cover_entry.is_none();
1264 if to_stdout && !first_mail {
1265 try!(writeln!(out, ""));
1266 }
1267
1268 let message = commit.message().unwrap();
1269 let (subject, body) = split_message(message);
1270 let commit_id = commit.id();
1271 let commit_author = commit.author();
1272 let commit_author_name = commit_author.name().unwrap();
1273 let commit_author_email = commit_author.email().unwrap();
1274 let summary_sanitized = sanitize_summary(&subject);
1275 let this_message_id = format!("<{}.{}>", commit_id, message_id_suffix);
1276 let parent = try!(commit.parent(0));
1277 let diff = try!(repo.diff_tree_to_tree(Some(&parent.tree().unwrap()), Some(&commit.tree().unwrap()), None));
1278 let stats = try!(diffstat(&diff));
1279
1280 if !to_stdout {
1281 out = try!(patch_file(&format!("{:04}-{}.patch", commit_num+1, summary_sanitized)));
1282 }
1283 try!(writeln!(out, "From {} Mon Sep 17 00:00:00 2001", commit_id));
1284 try!(writeln!(out, "Message-Id: {}", this_message_id));
1285 if let Some(ref message_id) = in_reply_to_message_id {
1286 try!(writeln!(out, "In-Reply-To: {}", message_id));
1287 try!(writeln!(out, "References: {}", message_id));
1288 }
1289 if first_mail {
1290 in_reply_to_message_id = Some(this_message_id);
1291 }
1292 if no_from {
1293 try!(writeln!(out, "From: {} <{}>", commit_author_name, commit_author_email));
1294 } else {
1295 try!(writeln!(out, "From: {} <{}>", committer_name, committer_email));
1296 }
1297 try!(writeln!(out, "Date: {}", date_822(commit_author.when())));
1298 let prefix = if commits.len() == 1 && cover_entry.is_none() {
1299 if subject_patch.is_empty() {
1300 "".to_string()
1301 } else {
1302 format!("[{}] ", subject_patch)
1303 }
1304 } else {
1305 format!("[{}{}{}/{}] ", subject_patch, ensure_space(&subject_patch), commit_num+1, commits.len())
1306 };
1307 try!(writeln!(out, "Subject: {}{}\n", prefix, subject));
1308
1309 if !no_from && (commit_author_name != committer_name || commit_author_email != committer_email) {
1310 try!(writeln!(out, "From: {} <{}>\n", commit_author_name, commit_author_email));
1311 }
1312 if !body.is_empty() {
1313 try!(write!(out, "{}{}", body, ensure_nl(&body)));
1314 }
1315 try!(writeln!(out, "---"));
1316 try!(writeln!(out, "{}", stats));
1317 try!(write_diff(&mut out, &diffcolors, &diff));
1318 if first_mail {
1319 try!(writeln!(out, "\nbase-commit: {}", base.id()));
1320 }
1321 try!(writeln!(out, "{}", signature));
1322 }
1323
1324 Ok(())
1325}
1326
1327fn log(out: &mut Output, repo: &Repository, m: &ArgMatches) -> Result<()> {
1328 let config = try!(try!(repo.config()).snapshot());
1329 try!(out.auto_pager(&config, "log", true));
1330 let diffcolors = try!(DiffColors::new(out, &config));
1331
1332 let mut revwalk = try!(repo.revwalk());
1333 try!(revwalk.push_ref(SHEAD_REF));
1334
1335 // Walk once before sorting, to find all the commits to hide. Revwalk doesn't support hiding on
1336 // the fly when sorted.
1337 let mut hidden_ids = std::collections::HashSet::new();
1338 while let Some(oid) = revwalk.next() {
1339 let oid = try!(oid);
1340 let commit = try!(repo.find_commit(oid));
1341 let tree = try!(commit.tree());
1342 for parent_id in commit.parent_ids() {
1343 if tree.get_id(parent_id).is_some() {
1344 try!(revwalk.hide(parent_id));
1345 hidden_ids.insert(parent_id);
1346 }
1347 }
1348 }
1349
1350 // set_sorting resets the revwalk
1351 revwalk.set_sorting(git2::SORT_TOPOLOGICAL);
1352 try!(revwalk.push_ref(SHEAD_REF));
1353 for id in hidden_ids {
1354 try!(revwalk.hide(id));
1355 }
1356
1357 let show_diff = m.is_present("patch");
1358
1359 let mut first = true;
1360 for oid in revwalk {
1361 if first {
1362 first = false;
1363 } else {
1364 try!(writeln!(out, ""));
1365 }
1366 let oid = try!(oid);
1367 let commit = try!(repo.find_commit(oid));
1368 let author = commit.author();
1369
1370 try!(writeln!(out, "{}", diffcolors.commit.paint(format!("commit {}", oid))));
1371 try!(writeln!(out, "Author: {} <{}>", author.name().unwrap(), author.email().unwrap()));
1372 try!(writeln!(out, "Date: {}\n", date_822(author.when())));
1373 for line in commit.message().unwrap().lines() {
1374 try!(writeln!(out, " {}", line));
1375 }
1376
1377 if show_diff {
1378 let tree = try!(commit.tree());
1379 let parent_ids: Vec<_> = commit.parent_ids().take_while(|parent_id| tree.get_id(*parent_id).is_none()).collect();
1380
1381 try!(writeln!(out, ""));
1382 if parent_ids.len() > 1 {
1383 try!(writeln!(out, "(Diffs of series merge commits not yet supported)"));
1384 } else {
1385 let parent_tree = if parent_ids.len() == 0 {
1386 None
1387 } else {
1388 Some(try!(try!(repo.find_commit(parent_ids[0])).tree()))
1389 };
1390 let diff = try!(repo.diff_tree_to_tree(parent_tree.as_ref(), Some(&tree), None));
1391 try!(write_diff(out, &diffcolors, &diff));
1392 }
1393 }
1394 }
1395
1396 Ok(())
1397}
1398
1399fn rebase(repo: &Repository, m: &ArgMatches) -> Result<()> {
1400 match repo.state() {
1401 git2::RepositoryState::Clean => (),
1402 git2::RepositoryState::RebaseMerge if repo.path().join("rebase-merge").join("git-series").exists() => {
1403 return Err("git series rebase already in progress.\nUse \"git rebase --continue\" or \"git rebase --abort\".".into());
1404 },
1405 s => { return Err(format!("{:?} in progress; cannot rebase", s).into()); }
1406 }
1407
1408 let internals = try!(Internals::read(repo));
1409 let series = try!(try!(internals.working.get("series")).ok_or("Could not find entry \"series\" in working index"));
1410 let base = try!(try!(internals.working.get("base")).ok_or("Cannot rebase series; no base set.\nUse \"git series base\" to set base."));
1411 if series.id() == base.id() {
1412 return Err("No patches to rebase; series and base identical.".into());
1413 } else if !try!(repo.graph_descendant_of(series.id(), base.id())) {
1414 return Err(format!("Cannot rebase: current base {} not an ancestor of series {}", base.id(), series.id()).into());
1415 }
1416
1417 // Check for unstaged or uncommitted changes before attempting to rebase.
1418 let series_commit = try!(repo.find_commit(series.id()));
1419 let series_tree = try!(series_commit.tree());
1420 let mut unclean = String::new();
1421 if !diff_empty(&try!(repo.diff_tree_to_index(Some(&series_tree), None, None))) {
1422 writeln!(unclean, "Cannot rebase: you have unstaged changes.").unwrap();
1423 }
1424 if !diff_empty(&try!(repo.diff_index_to_workdir(None, None))) {
1425 if unclean.is_empty() {
1426 writeln!(unclean, "Cannot rebase: your index contains uncommitted changes.").unwrap();
1427 } else {
1428 writeln!(unclean, "Additionally, your index contains uncommitted changes.").unwrap();
1429 }
1430 }
1431 if !unclean.is_empty() {
1432 return Err(unclean.into());
1433 }
1434
1435 let mut revwalk = try!(repo.revwalk());
1436 revwalk.set_sorting(git2::SORT_TOPOLOGICAL|git2::SORT_REVERSE);
1437 try!(revwalk.push(series.id()));
1438 try!(revwalk.hide(base.id()));
1439 let commits: Vec<Commit> = try!(revwalk.map(|c| {
1440 let id = try!(c);
1441 let mut commit = try!(repo.find_commit(id));
1442 if commit.parent_ids().count() > 1 {
1443 return Err(format!("Error: cannot rebase merge commit:\n{}", try!(commit_obj_summarize(&mut commit))).into());
1444 }
1445 Ok(commit)
1446 }).collect::<Result<_>>());
1447
1448 let interactive = m.is_present("interactive");
1449 let onto = match m.value_of("onto") {
1450 None => None,
1451 Some(onto) => {
1452 let obj = try!(repo.revparse_single(onto));
1453 let commit = try!(obj.peel(ObjectType::Commit));
1454 Some(commit.id())
1455 },
1456 };
1457
1458 let newbase = onto.unwrap_or(base.id());
1459 if newbase == base.id() && !interactive {
1460 println!("Nothing to do: base unchanged and not rebasing interactively");
1461 return Ok(());
1462 }
1463
1464 let (base_short, _) = try!(commit_summarize_components(&repo, base.id()));
1465 let (newbase_short, _) = try!(commit_summarize_components(&repo, newbase));
1466 let (series_short, _) = try!(commit_summarize_components(&repo, series.id()));
1467
1468 let newbase_obj = try!(repo.find_commit(newbase)).into_object();
1469
1470 let dir = try!(TempDir::new_in(repo.path(), "rebase-merge"));
1471 let final_path = repo.path().join("rebase-merge");
1472 let mut create = std::fs::OpenOptions::new();
1473 create.write(true).create_new(true);
1474
1475 try!(create.open(dir.path().join("git-series")));
1476 try!(create.open(dir.path().join("quiet")));
1477 try!(create.open(dir.path().join("interactive")));
1478
1479 let mut head_name_file = try!(create.open(dir.path().join("head-name")));
1480 try!(writeln!(head_name_file, "detached HEAD"));
1481
1482 let mut onto_file = try!(create.open(dir.path().join("onto")));
1483 try!(writeln!(onto_file, "{}", newbase));
1484
1485 let mut orig_head_file = try!(create.open(dir.path().join("orig-head")));
1486 try!(writeln!(orig_head_file, "{}", series.id()));
1487
1488 let git_rebase_todo_filename = dir.path().join("git-rebase-todo");
1489 let mut git_rebase_todo = try!(create.open(&git_rebase_todo_filename));
1490 for mut commit in commits {
1491 try!(writeln!(git_rebase_todo, "pick {}", try!(commit_obj_summarize(&mut commit))));
1492 }
1493 if let Some(onto) = onto {
1494 try!(writeln!(git_rebase_todo, "exec git series base {}", onto));
1495 }
1496 try!(writeln!(git_rebase_todo, "\n# Rebase {}..{} onto {}", base_short, series_short, newbase_short));
1497 try!(write!(git_rebase_todo, "{}", REBASE_COMMENT));
1498 drop(git_rebase_todo);
1499
1500 // Interactive editor if interactive {
1501 if interactive {
1502 let config = try!(repo.config());
1503 try!(run_editor(&config, &git_rebase_todo_filename));
1504 let mut file = try!(File::open(&git_rebase_todo_filename));
1505 let mut todo = String::new();
1506 try!(file.read_to_string(&mut todo));
1507 let todo = try!(git2::message_prettify(todo, git2::DEFAULT_COMMENT_CHAR));
1508 if todo.is_empty() {
1509 return Err("Nothing to do".into());
1510 }
1511 }
1512
1513 // Avoid races by not calling .into_path until after the rename succeeds.
1514 try!(std::fs::rename(dir.path(), final_path));
1515 dir.into_path();
1516
1517 try!(checkout_tree(repo, &newbase_obj));
1518 try!(repo.reference("HEAD", newbase, true, &format!("rebase -i (start): checkout {}", newbase)));
1519
1520 let status = try!(Command::new("git").arg("rebase").arg("--continue").status());
1521 if !status.success() {
1522 return Err(format!("git rebase --continue exited with status {}", status).into());
1523 }
1524
1525 Ok(())
1526}
1527
1528fn req(out: &mut Output, repo: &Repository, m: &ArgMatches) -> Result<()> {
1529 let config = try!(try!(repo.config()).snapshot());
1530 let shead = try!(repo.find_reference(SHEAD_REF));
1531 let shead_commit = try!(peel_to_commit(try!(shead.resolve())));
1532 let stree = try!(shead_commit.tree());
1533
1534 let series = try!(stree.get_name("series").ok_or("Internal error: series did not contain \"series\""));
1535 let series_id = series.id();
1536 let mut series_commit = try!(repo.find_commit(series_id));
1537 let base = try!(stree.get_name("base").ok_or("Cannot request pull; no base set.\nUse \"git series base\" to set base."));
1538 let mut base_commit = try!(repo.find_commit(base.id()));
1539
1540 let (cover_content, subject, cover_body) = if let Some(entry) = stree.get_name("cover") {
1541 let cover_blob = try!(repo.find_blob(entry.id()));
1542 let content = try!(std::str::from_utf8(cover_blob.content())).to_string();
1543 let (subject, body) = split_message(&content);
1544 (Some(content.to_string()), subject.to_string(), Some(body.to_string()))
1545 } else {
1546 (None, try!(shead_series_name(&shead)), None)
1547 };
1548
1549 let url = m.value_of("url").unwrap();
1550 let tag = m.value_of("tag").unwrap();
1551 let full_tag = format!("refs/tags/{}", tag);
1552 let full_tag_peeled = format!("{}^{{}}", full_tag);
1553 let full_head = format!("refs/heads/{}", tag);
1554 let mut remote = try!(repo.remote_anonymous(url));
1555 try!(remote.connect(git2::Direction::Fetch).map_err(|e| format!("Could not connect to remote repository {}\n{}", url, e)));
1556 let remote_heads = try!(remote.list());
1557
1558 /* Find the requested name as either a tag or head */
1559 let mut opt_remote_tag = None;
1560 let mut opt_remote_tag_peeled = None;
1561 let mut opt_remote_head = None;
1562 for h in remote_heads {
1563 if h.name() == full_tag {
1564 opt_remote_tag = Some(h.oid());
1565 } else if h.name() == full_tag_peeled {
1566 opt_remote_tag_peeled = Some(h.oid());
1567 } else if h.name() == full_head {
1568 opt_remote_head = Some(h.oid());
1569 }
1570 }
1571 let (msg, extra_body, remote_pull_name) = match (opt_remote_tag, opt_remote_tag_peeled, opt_remote_head) {
1572 (Some(remote_tag), Some(remote_tag_peeled), _) => {
1573 if remote_tag_peeled != series_id {
1574 return Err(format!("Remote tag {} does not refer to series {}", tag, series_id).into());
1575 }
1576 let local_tag = try!(repo.find_tag(remote_tag).map_err(|e|
1577 format!("Could not find remote tag {} ({}) in local repository: {}", tag, remote_tag, e)));
1578 let mut local_tag_msg = local_tag.message().unwrap().to_string();
1579 if let Some(sig_index) = local_tag_msg.find("-----BEGIN PGP ") {
1580 local_tag_msg.truncate(sig_index);
1581 }
1582 let extra_body = match cover_content {
1583 Some(ref content) if !local_tag_msg.contains(content) => cover_body,
1584 _ => None,
1585 };
1586 (Some(local_tag_msg), extra_body, full_tag)
1587 },
1588 (Some(remote_tag), None, _) => {
1589 if remote_tag != series_id {
1590 return Err(format!("Remote unannotated tag {} does not refer to series {}", tag, series_id).into());
1591 }
1592 (cover_content, None, full_tag)
1593 }
1594 (_, _, Some(remote_head)) => {
1595 if remote_head != series_id {
1596 return Err(format!("Remote branch {} does not refer to series {}", tag, series_id).into());
1597 }
1598 (cover_content, None, full_head)
1599 },
1600 _ => {
1601 return Err(format!("Remote does not have either a tag or branch named {}", tag).into())
1602 }
1603 };
1604
1605 let commit_subject_date = |commit: &mut Commit| -> String {
1606 let date = date_822(commit.author().when());
1607 let summary = commit.summary().unwrap();
1608 format!(" {} ({})", summary, date)
1609 };
1610
1611 let mut revwalk = try!(repo.revwalk());
1612 revwalk.set_sorting(git2::SORT_TOPOLOGICAL|git2::SORT_REVERSE);
1613 try!(revwalk.push(series_id));
1614 try!(revwalk.hide(base.id()));
1615 let mut commits: Vec<Commit> = try!(revwalk.map(|c| {
1616 Ok(try!(repo.find_commit(try!(c))))
1617 }).collect::<Result<_>>());
1618 if commits.is_empty() {
1619 return Err("No patches to request pull of; series and base identical.".into());
1620 }
1621
1622 let author = try!(get_signature(&config, "AUTHOR"));
1623 let author_email = author.email().unwrap();
1624 let message_id = format!("<pull.{}.{}.git-series.{}>", shead_commit.id(), author.when().seconds(), author_email);
1625
1626 let diff = try!(repo.diff_tree_to_tree(Some(&base_commit.tree().unwrap()), Some(&series_commit.tree().unwrap()), None));
1627 let stats = try!(diffstat(&diff));
1628
1629 try!(out.auto_pager(&config, "request-pull", true));
1630 let diffcolors = try!(DiffColors::new(out, &config));
1631
1632 try!(writeln!(out, "From {} Mon Sep 17 00:00:00 2001", shead_commit.id()));
1633 try!(writeln!(out, "Message-Id: {}", message_id));
1634 try!(writeln!(out, "From: {} <{}>", author.name().unwrap(), author_email));
1635 try!(writeln!(out, "Date: {}", date_822(author.when())));
1636 try!(writeln!(out, "Subject: [GIT PULL] {}\n", subject));
1637 if let Some(extra_body) = extra_body {
1638 try!(writeln!(out, "{}", extra_body));
1639 }
1640 try!(writeln!(out, "The following changes since commit {}:\n", base.id()));
1641 try!(writeln!(out, "{}\n", commit_subject_date(&mut base_commit)));
1642 try!(writeln!(out, "are available in the git repository at:\n"));
1643 try!(writeln!(out, " {} {}\n", url, remote_pull_name));
1644 try!(writeln!(out, "for you to fetch changes up to {}:\n", series.id()));
1645 try!(writeln!(out, "{}\n", commit_subject_date(&mut series_commit)));
1646 try!(writeln!(out, "----------------------------------------------------------------"));
1647 if let Some(msg) = msg {
1648 try!(writeln!(out, "{}", msg));
1649 try!(writeln!(out, "----------------------------------------------------------------"));
1650 }
1651 try!(writeln!(out, "{}", shortlog(&mut commits)));
1652 try!(writeln!(out, "{}", stats));
1653 if m.is_present("patch") {
1654 try!(write_diff(out, &diffcolors, &diff));
1655 }
1656 try!(writeln!(out, "{}", mail_signature()));
1657
1658 Ok(())
1659}
1660
1661fn main() {
1662 let m = App::new("git-series")
1663 .bin_name("git series")
1664 .about("Track patch series in git")
1665 .author("Josh Triplett <josh@joshtriplett.org>")
1666 .version(crate_version!())
1667 .global_setting(AppSettings::ColoredHelp)
1668 .global_setting(AppSettings::UnifiedHelpMessage)
1669 .global_setting(AppSettings::VersionlessSubcommands)
1670 .subcommands(vec![
1671 SubCommand::with_name("add")
1672 .about("Add changes to the index for the next series commit")
1673 .arg_from_usage("<change>... 'Changes to add (\"series\", \"base\", \"cover\")'"),
1674 SubCommand::with_name("base")
1675 .about("Get or set the base commit for the patch series")
1676 .arg(Arg::with_name("base").help("Base commit").conflicts_with("delete"))
1677 .arg_from_usage("-d, --delete 'Clear patch series base'"),
1678 SubCommand::with_name("checkout")
1679 .about("Resume work on a patch series; check out the current version")
1680 .arg_from_usage("<name> 'Patch series to check out'"),
1681 SubCommand::with_name("commit")
1682 .about("Record changes to the patch series")
1683 .arg_from_usage("-a, --all 'Commit all changes'")
1684 .arg_from_usage("-m [msg] 'Commit message'")
1685 .arg_from_usage("-v, --verbose 'Show diff when preparing commit message'"),
1686 SubCommand::with_name("cover")
1687 .about("Create or edit the cover letter for the patch series")
1688 .arg_from_usage("-d, --delete 'Delete cover letter'"),
1689 SubCommand::with_name("delete")
1690 .about("Delete a patch series")
1691 .arg_from_usage("<name> 'Patch series to delete'"),
1692 SubCommand::with_name("detach")
1693 .about("Stop working on any patch series"),
1694 SubCommand::with_name("format")
1695 .about("Prepare patch series for email")
1696 .arg_from_usage("--in-reply-to [Message-Id] 'Make the first mail a reply to the specified Message-Id'")
1697 .arg_from_usage("--no-from 'Don't include in-body \"From:\" headers when formatting patches authored by others'")
1698 .arg_from_usage("-v, --reroll-count=[N] 'Mark the patch series as PATCH vN'")
1699 .arg_from_usage("--stdout 'Write patches to stdout rather than files'")
1700 .arg_from_usage("--subject-prefix [Subject-Prefix] 'Use [Subject-Prefix] instead of the standard [PATCH] prefix'"),
1701 SubCommand::with_name("log")
1702 .about("Show the history of the patch series")
1703 .arg_from_usage("-p, --patch 'Include a patch for each change committed to the series'"),
1704 SubCommand::with_name("rebase")
1705 .about("Rebase the patch series")
1706 .arg_from_usage("[onto] 'Commit to rebase onto'")
1707 .arg_from_usage("-i, --interactive 'Interactively edit the list of commits'")
1708 .group(ArgGroup::with_name("action").args(&["onto", "interactive"]).multiple(true).required(true)),
1709 SubCommand::with_name("req")
1710 .about("Generate a mail requesting a pull of the patch series")
1711 .visible_aliases(&["pull-request", "request-pull"])
1712 .arg_from_usage("-p, --patch 'Include patch in the mail'")
1713 .arg_from_usage("<url> 'Repository URL to request pull of'")
1714 .arg_from_usage("<tag> 'Tag or branch name to request pull of'"),
1715 SubCommand::with_name("status")
1716 .about("Show the status of the patch series"),
1717 SubCommand::with_name("start")
1718 .about("Start a new patch series")
1719 .arg_from_usage("<name> 'Patch series name'"),
1720 SubCommand::with_name("unadd")
1721 .about("Undo \"git series add\", removing changes from the next series commit")
1722 .arg_from_usage("<change>... 'Changes to remove (\"series\", \"base\", \"cover\")'"),
1723 ]).get_matches();
1724
1725 let mut out = Output::new();
1726
1727 let err = || -> Result<()> {
1728 let repo = try!(Repository::discover("."));
1729 match m.subcommand() {
1730 ("", _) => series(&mut out, &repo),
1731 ("add", Some(ref sm)) => add(&repo, &sm),
1732 ("base", Some(ref sm)) => base(&repo, &sm),
1733 ("checkout", Some(ref sm)) => checkout(&repo, &sm),
1734 ("commit", Some(ref sm)) => commit_status(&mut out, &repo, &sm, false),
1735 ("cover", Some(ref sm)) => cover(&repo, &sm),
1736 ("delete", Some(ref sm)) => delete(&repo, &sm),
1737 ("detach", _) => detach(&repo),
1738 ("format", Some(ref sm)) => format(&mut out, &repo, &sm),
1739 ("log", Some(ref sm)) => log(&mut out, &repo, &sm),
1740 ("rebase", Some(ref sm)) => rebase(&repo, &sm),
1741 ("req", Some(ref sm)) => req(&mut out, &repo, &sm),
1742 ("start", Some(ref sm)) => start(&repo, &sm),
1743 ("status", Some(ref sm)) => commit_status(&mut out, &repo, &sm, true),
1744 ("unadd", Some(ref sm)) => unadd(&repo, &sm),
1745 _ => unreachable!()
1746 }
1747 }();
1748
1749 if let Err(e) = err {
1750 let msg = e.to_string();
1751 out.write_err(&format!("{}{}", msg, ensure_nl(&msg)));
1752 drop(out);
1753 std::process::exit(1);
1754 }
1755}