main.rs

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