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