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