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