main.rs

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