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