#!/usr/bin/perl -w

## Easy GIT (eg), a frontend for git designed for former cvs and svn users
## Version .97
## Copyright 2008, 2009 by Elijah Newren, and others
## Licensed under GNU GPL, version 2.

## To use eg, simply stick this file in your path.  Then fire off an
## 'eg help' to get oriented.  You may also be interested in
##   http://www.gnome.org/~newren/eg/git-for-svn-users.html
## to get a comparison to svn in terms of capabilities and commands.
## Webpage for eg: http://www.gnome.org/~newren/eg

package main;

use warnings;
use Getopt::Long;
use Cwd qw(getcwd abs_path);
use List::Util qw(max);

# configurables
my $debug=0;

# globals :-(
my $outfh;
my $version = ".97";
my $eg_exec = abs_path($0);
my %command;    # command=>{section, short_description} mapping
my $section = {
  'creation' =>
    { order => 1,
      desc  => 'Creating repositories',
    },
  'discovery' =>
    { order => 2,
      desc  => 'Obtaining information about changes, history, & state',
    },
  'modification' =>
    { order => 3,
      desc  => 'Making, undoing, or recording changes',
    },
  'projects' =>
    { order => 4,
      desc  => 'Managing branches',
    },
  'collaboration' =>
    { order => 5,
      desc  => 'Collaboration'
    },
  'timesavers' =>
    { order => 6,
      desc  => 'Time saving commands'
    },
  'compatibility' =>
    { order => 7,
      extra => 1,
      desc  => 'Commands provided solely for compatibility with other ' .
               'prominent SCMs'
    },
  'misc' =>
    { order => 8,
      extra => 1,
      desc  => 'Miscellaneous'
    },
  };
my ($curdir, $topdir, $gitdir);

## Commands to list in help even though we haven't overridden the git versions
## (yet, in most cases)
INIT {
  %command = (
    blame => {
      unmodified_help => 1,
      unmodified_behavior => 1,
      extra => 1,
      section => 'discovery',
      about => 'Show what version and author last modified each line of a file'
      },
    bisect => {
      unmodified_help => 1,
      unmodified_behavior => 1,
      section => 'timesavers',
      about => 'Find the change that introduced a bug by binary search'
      },
    grep => {
      unmodified_help => 1,
      unmodified_behavior => 1,
      extra => 1,
      section => 'discovery',
      about => 'Print lines of known files matching a pattern'
      },
    mv => {
      unmodified_help => 1,
      unmodified_behavior => 1,
      section => 'modification',
      about => 'Move or rename files (or directories or symlinks)'
      },
  );
}



#*************************************************************************#
#*************************************************************************#
#*************************************************************************#
#                   CLASSES DEFINING ACTIONS TO PERFORM                   #
#*************************************************************************#
#*************************************************************************#
#*************************************************************************#

###########################################################################
# subcommand, a base class for all eg subcommands                         #
###########################################################################
package subcommand;
sub new {
  my $class = shift;
  my $self = {git_repo_needed => 1, @_};  # Hashref initialized as we're told
  bless($self, $class);

  # Our "see also" section in help usually references the same subsection
  # as our class name.
  $self->{git_equivalent} = ref($self) if !defined $self->{git_equivalent};

  # We allow direct instantiation of the subcommand class only if they
  # provide a command name for us to pass to git.
  if (ref($class) eq "subcommand" && !defined $self->{command}) {
    die "Invalid subcommand usage"
  }

  # Most commands must be run inside a git working directory
  unless (!$self->{git_repo_needed} || (@ARGV > 0 && $ARGV[0] eq "--help")) {
    $self->{git_dir} = RepoUtil::git_dir();
    die "Must be run inside a git repository!\n" if !defined $self->{git_dir};
  }

  # Many commands do not work if no commit has yet been made
  if ($self->{initial_commit_error_msg} &&
      RepoUtil::initial_commit() &&
      (@ARGV < 1 || $ARGV[0] ne "--help")) {
    die "$self->{initial_commit_error_msg}\n";
  }

  return $self;
}

sub help {
  my $self = shift;
  my $package_name = ref($self);
  $package_name =~ s/_/-/;  # Packages use underscores, commands use dashes

  my $git_equiv = $self->{git_equivalent};
  $git_equiv =~ s/_/-/;  # Packages use underscores, commands use dashes

  if ($package_name eq "subcommand") {
    exit ExecUtil::execute("git $self->{command} --help")
  }

  open(OUTPUT, "| less -FRSX");
  print OUTPUT "$package_name: $command{$package_name}{about}\n";
  print OUTPUT $self->{'help'};
  print OUTPUT "\nDifferences from git $package_name:";
  print OUTPUT "\n  None.\n" if !defined $self->{'differences'};
  print OUTPUT $self->{'differences'} if defined $self->{'differences'};
  if ($git_equiv) {
    print OUTPUT "\nSee also\n";
    print OUTPUT <<EOF;
  Run 'man git-$git_equiv' for a comprehensive list of options available.
  eg $package_name is designed to accept the same options as git $git_equiv, and
  with the same meanings unless specified otherwise in the above
  "Differences" section.
EOF
  }
  close(OUTPUT);
  exit 0;
}

sub preprocess {
  my $self = shift;

  my $result=main::GetOptions("--help" => sub { $self->help() });
}

sub quote_args {
  my $self = shift;
  my @args = @_;

  # Quote arguments with special characters so that when we
  # do something like
  #   system("$command hardcoded_arg1 @args")
  # that the @args will get passed correctly to the shell command $command
  my @newargs;
  foreach my $arg (@args) {
    my $quotes_needed = 0;
    if ($arg =~ /[;'"<>()|`* \\]/) {
      $quotes_needed = 1;
    }

    $arg =~ s#\\#\\\\#g;    # Backslash escape backslashes
    $arg =~ s#"#\\"#g;      # Backslash escape quotes
    $arg =~ s#`#\\`#g;      # Backslash escape backticks

    $arg = '"'.$arg.'"' if $quotes_needed;

    push(@newargs, $arg);
  }
  return @newargs;
}

sub run {
  my $self = shift;
  my $package_name = ref($self);

  my $subcommand = 
    $package_name eq "subcommand" ? $self->{'command'} : $package_name;

  @ARGV = $self->quote_args(@ARGV);
  return ExecUtil::execute("git $subcommand @ARGV", ignore_ret => 1);
}

###########################################################################
# add                                                                     #
###########################################################################
package add;
@add::ISA = qw(subcommand);
INIT {
  $command{add} = {
    unmodified_behavior => 1,
    section => 'compatibility',
    about => 'Mark content in files as being ready for commit'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(@_);
  bless($self, $class);
  $self->{'help'} = "
Description:
  eg add is provided for backward compatibility; it has identical usage and
  functionality as 'eg stage'.  See 'eg help stage' for more details.
";
  return $self;
}

###########################################################################
# apply                                                                   #
###########################################################################
package apply;
@apply::ISA = qw(subcommand);
INIT {
  $command{apply} = {
    about => 'Apply a patch in a git repository'
  };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(@_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg apply [--staged] [-R | --reverse] [-pNUM]

Description:
  Applies a patch to a git repository.

Examples:
  Reverse changes in foo.patch
      \$ eg apply -R foo.patch

  (Advanced) Reverse changes since the last commit to the version of foo.c
  in the staging area (equivalent to 'eg revert --staged foo.c'):
      \$ eg diff --staged foo.c | eg apply -R --staged

Options:
  --staged
    Apply the patch to the staged (explicitly marked as ready to be committed)
    versions of files

  --reverse, -R
    Apply the patch in reverse.

  -pNUM
    Remove NUM leading paths from filenames.  For example, with the filename
      /home/user/bla/foo.c
    using -p0 would leave the name unmodified, using -p1 would yield
      home/user/bla/foo.c
    and using -p3 would yield
      bla/foo.c
";
  $self->{'differences'} = '
  eg apply is identical to git apply except that it accepts --staged as a
  synonym for --cached.
';
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  my $result = main::GetOptions("--help" => sub { $self->help() });
  foreach my $i (0..$#ARGV) {
    $ARGV[$i] = "--cached" if $ARGV[$i] eq "--staged";
  }
}

###########################################################################
# branch                                                                  #
###########################################################################
package branch;
@branch::ISA = qw(subcommand);
INIT {
  $command{branch} = {
    section => 'projects',
    about => 'List, create, or delete branches'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    initial_commit_error_msg => "No branches can be created, deleted, or " .
                                "listed until a commit has been made.",
    @_
    );
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg branch [-r]
  eg branch [-s] NEWBRANCH [STARTPOINT]
  eg branch -d BRANCH

Description:
  List the existing branches that you can switch to, create a new branch,
  or delete an existing branch.  For switching the working copy to a
  different branch, use the eg switch command instead.

  Note that branches are local; creation of branches in a remote repository
  can be accomplished by first creating a local branch and then pushing the
  new branch to the remote repository using eg push.

Examples
  List the available local branches
      \$ eg branch

  Create a new branch named random_stuff, based off the last commit.
      \$ eg branch random_stuff

  Create a new branch named sec-48 based off the 4.8 branch
      \$ eg branch sec-48 4.8

  Delete the branch named bling
      \$ eg branch -d bling

  Create a new branch named my_fixes in the default remote repository
      \$ eg branch my_fixes
      \$ eg push --branch my_fixes

  (Advanced) Create a new branch named bling, based off the remote tracking
  branch of the same name
      \$ eg branch bling origin/bling
  See 'eg remote' for more details about setting up named remotes and
  remote tracking branches, and 'eg help topic storage' for more details on
  differences between branches and remote tracking branches.

Options:
  -d
    Delete specified branch

  -r
    List remote tracking branches (see 'eg help topic storage') for more
    details.  This is useful when using named remote repositories (see 'eg
    help remote')

  -s
    After creating the new branch, switch to it
";
  $self->{'differences'} = '
  eg branch is identical to git branch other than adding a new -s option for
  switching to a branch immediately after creating it.
';
  return $self;
}

sub run {
  my $self = shift;
  my $package_name = ref($self);

  my $switch = 0;
  if (scalar(@ARGV) > 1 && $ARGV[0] eq "-s") {
    $switch = 1;
    shift @ARGV;
  }

  @ARGV = $self->quote_args(@ARGV);
  ExecUtil::execute("git branch @ARGV", ignore_ret => 1);
  ExecUtil::execute("git checkout $ARGV[0]", ignore_ret => 1)
    if ($switch);
}

###########################################################################
# bundle                                                                  #
###########################################################################
package bundle;
@bundle::ISA = qw(subcommand);
INIT {
  $command{bundle} = {
    extra => 1,
    section => 'collaboration',
    about => 'Pack repository updates (or whole repository) into a file'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    initial_commit_error_msg => "No bundles can be created until a commit " .
                                "has been made.",
    @_
    );
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg bundle create FILENAME [REFERENCES]
  eg bundle create-update NEWFILENAME OLDFILENAME [REFERENCES]
  eg bundle verify FILENAME

Description:
  Bundle creates a file which contains a repository, or a subset thereof.
  This is useful when two machines cannot be directly connected (thus
  preventing use of the standard interactive git protocols -- git, ssh,
  rsync or http), but changes still need to be communicated between the
  machines.

  The remote side can use the resulting file (or the path to it) as the URL
  for the repository they want to clone or pull updates from.

Examples
  Create a bundle in the file repo.bundle which contains the whole repository
      \$ eg bundle create repo.bundle

  After getting the bundle named repo.bundle from a collaborator (which
  must contain \"HEAD\" as one of the references if you explicitly list which
  ones to be included at creation time), clone the repository into the
  directory named project-name
      \$ eg clone /path/to/repo.bundle project-name

  Create a bundle in the file called new-repo containing only updates since
  the bundle old-repo was created.
      \$ eg bundle create-update new-repo old-repo

  Pulls updates from a new bundle we have been sent.
      \$ eg pull /path/to/repo.bundle

  Pull updates from a new bundle we have been sent, if we first overwrite
  the bundle we originally original cloned from with the new bundle
      \$ eg pull

  (Advanced) Create a bundle containing the two branches debug and
  installer, and the tag named v2.3, in the file called my-changes
      \$ eg bundle create my-changes debug installer v2.3

  (Advanced) Create a bundle in the file called new-repo that contains
  updates since the bundle old-bundle was created, but don't include the
  new branch secret-stuff or crazy-idea
      \$ eg bundle create-update new-repo old-bundle ^secret-stuff ^crazy-idea
      
Options:
  eg bundle create FILENAME [REFERENCES]
  eg bundle create-update NEWFILENAME OLDFILENAME [REFERENCES]
  eg bundle verify FILENAME

  create FILENAME [REFERENCES]
    Create a new bundle in the file FILENAME.  If no REFERENCES are passed,
    all branches and tags (plus \"HEAD\") will be included.  See below for
    a basic explanation of REFERENCES.

  create-update NEWFILENAME OLDFILENAME [REFERENCES]

    Create a new bundle in the file NEWFILENAME, but don't include any
    commits already included in OLDFILENAME.  See below for a basic
    explanation of REFERNCES.  By default, any new branch or tags will be
    included as well; exclude specific branches or tags by passing ^BRANCH
    or ^TAG as a reference; see below for more details.

  verify FILENAME
    Check whether the given bundle in FILENAME will cleanly apply to the
    current repository.

  REFERENCES
    Which commits to include or exclude from the bundle.  Probably best
    explained by example:

      Example            Meaning
      -----------------  --------------------------------------------------
      master             Include the master branch
      master~10..master  Include the last 10 commits on the master branch
      ^baz foo bar       Include commits on the foo or bar branch, except for
                           those that are in the baz branch
";
  $self->{'differences'} = '
  eg bundle differs from git bundle in two ways:
    (1) eg bundle defaults to "-all HEAD" if no revisions are passed to create
    (2) eg bundle provides a create-update subcommand
';
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  #
  # Parse options
  #
  my @args;
  my $result=main::GetOptions("--help" => sub { $self->help() });

  # Get the (sub)subcommand
  $self->{subcommand} = shift @ARGV;
  push(@args, $self->{subcommand});

  if ($self->{subcommand} eq 'create') {
    my $filename = shift @ARGV ||
      die "Error: need a filename to write bundle to.\n";
    push(@args, $filename);  # Handle the filename
    if (!@ARGV) {
      push(@args, ("--all", "HEAD"));
    }
  }
  elsif ($self->{subcommand} eq 'create-update') {
    pop(@args);  # 'create-update' isn't a real git bundle subcommand

    my $newname = shift @ARGV || 
      die "You must specify a new and an old filename.\n";
    my $oldname = shift @ARGV || 
      die "You must also specify an old filename\n";

    die "$oldname does not exist.\n" if ! -f $oldname;

    my ($retval, $output) =
      ExecUtil::execute_captured("git bundle list-heads $oldname");
    my @lines = split '\n', $output;

    my @refs = map { m#^([0-9a-f]+)# && "^$1" } @lines;
    push(@args, ('create', $newname, "--all", "HEAD", @refs));
  }
  push(@args, @ARGV);

  # Reset @ARGV with the built up list of arguments
  @ARGV = @args;
}

###########################################################################
# cat                                                                     #
###########################################################################
package cat;
@cat::ISA = qw(subcommand);
INIT {
  $command{cat} = {
    new_command => 1,
    extra => 1,
    section => 'compatibility',
    about => 'Output the current or specified version of files'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    git_equivalent => 'show',
    initial_commit_error_msg => "Error: Cannot show committed versions of " .
                                "files when no commits have occurred.",
    @_
    );
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg cat [REVISION:]FILE...

Description:
  Output the specified file(s) as of the given revisions.

  Note that this basically is just a compatibility alias provided for users
  of other SCMs.  You should consider using 'git show' instead, though with
  core git whenever you specify a REVISION, you will need to specify the
  path to FILE relative to the toplevel project directory, instead of a
  path for FILE relative to the current directory.

Examples
  Output the most recently committed version of foo.c
      \$ eg cat foo.c

  Output the version of bar.h from the 5th to last commit on the
  ugly_fixes branch
      \$ eg cat ugly_fixes~5:bar.h

  Concatenate the version of hello.c from two commits ago and the
  version of world.h from the branch timbuktu, and output the result:
      \$ eg cat HEAD~1:hello.c timbuktu:world.h
";
  $self->{'differences'} = '
  The output of "git show FILE" is probably confusing to users at first.
  Thus, "eg cat FILE" calls "git show HEAD:PATH/TO/FILE".
';
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  my $result=main::GetOptions("--help" => sub { $self->help() });

  # Get important directories
  my ($cur_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();

  my @args;
  foreach my $arg (@ARGV) {
    if ($arg !~ /:/) {
      my ($path) = Util::reroot_paths__from_to_files($cur_dir, $top_dir, $arg);
      push(@args, "HEAD:$path");
    } else {
      my ($REVISION, $FILE) = split(/:/, $arg, 2);
      my ($path) = Util::reroot_paths__from_to_files($cur_dir, $top_dir, $FILE);
      push(@args, "$REVISION:$path");
    }
  }

  @ARGV = @args;
}

sub run {
  my $self = shift;
  my $package_name = ref($self);

  @ARGV = $self->quote_args(@ARGV);
  return ExecUtil::execute("git show @ARGV", ignore_ret => 1);
}

###########################################################################
# changes                                                                 #
###########################################################################
package changes;
@changes::ISA = qw(subcommand);
INIT {
  $command{changes} = {
    new_command => 1,
    section => 'misc',
    about => 'Provide an overview of the changes from git to eg'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(git_equivalent => '', @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg changes [--details]

Options
  --details
    In addition to the summary of which commands were changed, list the
    changes to each command.
";
  $self->{'differences'} = '
  eg changes is unique to eg; git does not have a similar command.
';
  return $self;
}

sub preprocess {
  my $self = shift;

  $self->{details} = 0;
  my $result = main::GetOptions(
    "--help"    => sub { $self->help() },
    "--details" => \$self->{details},
    );
  die "Unrecognized arguments: @ARGV\n" if @ARGV;
}

sub run {
  my $self = shift;
  my $package_name = ref($self);

  if ($debug == 2) {
    print "    >>(No commands to run, just data to print)<<\n";
    return;
  }

  # Print valid subcommands sorted by section
  my $indent = "  ";
  my $header_indent = "";
  open(OUTPUT, "|less -FRSX");

  if ($self->{details}) {
    print OUTPUT "Summary of changes:\n";
    $indent = "    ";
    $header_indent = "  ";
  }
  print OUTPUT "${header_indent}Modified Behavior:\n";
  foreach my $c (sort keys %command) {
    next if $command{$c}{unmodified_behavior};
    next if $command{$c}{new_command};
    print OUTPUT "$indent$c\n";
  }
  print OUTPUT "${header_indent}New commands:\n";
  foreach my $c (sort keys %command) {
    next if !$command{$c}{new_command};
    print OUTPUT "$indent$c\n";
  }
  print OUTPUT "${header_indent}Modified Help Only:\n";
  foreach my $c (sort keys %command) {
    next if $command{$c}{unmodified_help};
    next if !$command{$c}{unmodified_behavior};
    next if $command{$c}{new_command};
    print OUTPUT "$indent$c\n";
  }

  if ($self->{details}) {
    foreach my $c (sort keys %command) {
      next if $command{$c}{unmodified_help} || $command{$c}{unmodified_behavior};

      next if !$c->can("new");
      my $obj = $c->new(initial_commit_error_msg => '');

      print OUTPUT "Changes to $c:\n";
      if ($obj->{differences}) {
        $obj->{differences} =~ s/^\n//;
        print OUTPUT $obj->{differences};
      } else {
        print OUTPUT "  <Unknown>.\n";
      }
    }
  }
  close(OUTPUT);
}

###########################################################################
# checkout                                                                #
###########################################################################
package checkout;
@checkout::ISA = qw(subcommand);
INIT {
  $command{checkout} = {
    section => 'compatibility',
    about => 'Compatibility wrapper for clone/switch/revert'
  };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(git_repo_needed => 0, @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg checkout [--depth DEPTH] REPOSITORY [DIRECTORY]
  eg checkout [-b] BRANCH
  eg checkout [REVISION] PATH...

Description:
  eg checkout simulates the checkout command from both git and svn - if you
  are not used to checkout from those systems, you should use eg clone, eg
  switch, or eg revert and ignore eg checkout.

  The first usage form of eg checkout is used to get a new project based on
  a (usually remote) repository.  Users are encouraged to use eg clone
  instead, though eg checkout accepts all parameters that eg clone does.

  The second usage form of eg checkout is used to switch to a different
  branch (optionally also creating it first).  This is something that can
  be done with no network connectivity in git and thus eg.  Users can find
  identical functionality in eg switch.

  The third usage form of eg checkout is used to replace files in the
  working copy with versions from an older commit, i.e. to revert files to
  an older version.  Users can find the same functionality (as well as many
  other capabilities) in eg revert.

Examples:
  Get a local copy of cairo
      \$ eg checkout git://git.cairographics.org/git/cairo

  Switch to the stable branch
      \$ eg checkout stable

  Replace foo.c with the third to last version before the most recent
  commit (Note that HEAD always refers to the current branch, and the
  current branch always refers to its most recent commit)
      \$ eg checkout HEAD~3 foo.c
";
  $self->{'differences'} = '
  eg checkout accepts all parameters that git checkout accepts with the
  same meanings and same output (eg checkout merely calls git checkout in
  such cases).

  The only difference between eg and git regarding checkout is that eg
  checkout will also accept all arguments to git clone, and then call git
  clone.
';
  return $self;
}

sub _looks_like_git_repo {
  my $path = shift;

  my $clone_protocol = qr#^(?:git|ssh|http|https|rsync)://#;
  my $git_dir = RepoUtil::git_dir();
  my $in_working_copy = defined $git_dir ? 1 : 0;

  # If the path looks like a git, ssh, http, https, or rsync url, then it
  # looks like we're being given a url to a git repo
  if ($path =~ /$clone_protocol/) {
    return 1;
  }

  # If the path isn't a clone_protocol url and isn't a directory, it can't be
  # a git repo
  if (! -d $path) {
    return 0;
  }

  my $path_is_absolute = ($path =~ m#^/#);
  return (!$in_working_copy || ($in_working_copy && $path_is_absolute));
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  my $result = main::GetOptions("--help" => sub { $self->help() });
  $self->{command} = 'checkout';
  die "eg checkout requires at least one argument.\n" if !@ARGV;

  #
  # Determine whether this should be a call to git clone or git checkout
  #
  my $clone_protocol = qr#^(?:git|ssh|http|https|rsync)://#;
  if (_looks_like_git_repo($ARGV[-1]) ||
      (! -d $ARGV[-1] && @ARGV > 1 && _looks_like_git_repo($ARGV[-2]))
     ) {
    $self->{command} = 'clone';
  }

  # Avoid checking out a remote tracking branch
  my $valid_ref = RepoUtil::valid_ref($ARGV[-1]);
  if ($self->{command} eq 'checkout' &&    # Checkout, not clone
      (@ARGV == 1 || $ARGV[1] =~ /^-/) &&  # First form of checkout
      ($ARGV[-1] =~ m#/# && $valid_ref)) { # They want a remote-tracking branch
    print STDERR<<EOF;
Aborting: Should not switch to a remote tracking branch.  Please instead
create a branch based on the remote tracking branch (use the command
'eg branch NEWBRANCH $ARGV[-1]') and then switch to the new branch.
EOF
    exit 1;
  }

}

sub run {
  my $self = shift;

  @ARGV = $self->quote_args(@ARGV);
  if ($self->{command} ne 'clone') {
    # If this operation isn't a clone, then we should have checked for
    # whether we are in a git directory.  But we didn't do that, just in
    # case it was a clone.  So, do it now.
    $self->{git_dir} = RepoUtil::git_dir();
    die "Must be run inside a git repository!\n" if !defined $self->{git_dir};

    return ExecUtil::execute("git checkout @ARGV", ignore_ret => 1);
  } else {
    return ExecUtil::execute("$eg_exec  clone    @ARGV", ignore_ret => 1);
  }
}

###########################################################################
# cherry_pick                                                             #
###########################################################################
package cherry_pick;
@cherry_pick::ISA = qw(subcommand);
INIT {
  $command{"cherry-pick"} = {
    extra => 1,
    section => 'modification',
    about => 'Apply (or reverse) a commit, usually from another branch'
  };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(@_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg cherry-pick [--reverse] [--edit] [-n] [-m parent-number] [-s] [-x] REVISION

Description:
  Given an existing revision, apply the change between its parent and it
  (or reverse apply if the --reverse option is present), and record a new
  revision with this change.  Your working tree must be clean (no local
  unsaved modifications) in order to run eg cherry-pick.

Examples:
  Apply the fix 3 commits behind the tip of the experimental branch
  (i.e. the fix made in experimental~3) to the current branch
      \$ eg cherry-pick experimental~3

  Make a new commit that reverses the changes made in the most recent
  commit of the current branch
      \$ eg cherry-pick -R HEAD

Options:
  --reverse, --revert, -R
    Reverse apply the changes from the specified commit (i.e. revert the
    specified revision with a new commit).

  --edit, -e
    With this option, eg cherry-pick will let you edit the commit message
    prior to committing.

  -x
    When recording the commit, append to the original commit message a note
    that indicates which commit this change was cherry-picked from.  Append
    the note only for cherry picks without conflicts. Do not use this
    option if you are cherry-picking from your private branch because the
    information is useless to the recipient. If on the other hand you are
    cherry-picking between two publicly visible branches (e.g. backporting
    a fix to a maintenance branch for an older release from a development
    branch), adding this information can be useful.

    This option is turned on automatically when -R is specified.

  --mainline parent-number, -m parent-number
    cherry-pick always applies the changes between a revision and its
    parent; thus if a revision represents a merge commit, it is not clear
    which parent cherry-pick should get the changes relative to.  This
    option specifies the parent number (starting from 1) of the mainline
    and allows cherry-pick to replay the change relative to the specified
    parent.

  --no-commit, -n
    Usually cherry-pick automatically creates a commit. This flag applies
    the change necessary to cherry-pick the named revision to your working
    tree and staging area, but does not make the commit. In addition, when
    this option is used, the staging area can contain unsaved changes and
    the cherry-pick will be done against the beginning state of your
    staging area.

    This is useful when cherry-picking more than one commit into a single
    combined change.

  --signoff, -s
    Add Signed-off-by line at the end of the commit message.

  REVISION
    A reference to a recorded version of the repository.  See 'eg help
    topic revisions' for more details.
";
  $self->{'differences'} = '
  eg cherry-pick contains both the functionality of git cherry-pick and git
  revert.  If the -R option is specified, eg cherry-pick calls git revert
  (after removing the -R option); otherwise it calls git cherry-pick.
';
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  my ($reverse, $dash_x, $mainline) = (0, 0, -1);
  Getopt::Long::Configure("permute");  # Allow unrecognized options through
  my $result = main::GetOptions(
    "--help"       => sub { $self->help() },
    "mainline|m=i" => \$mainline,
    "reverse|R"    => \$reverse,
    "revert"       => \$reverse,
    "x"            => \$dash_x,
    );
  $self->{reverse} = $reverse;
  unshift(@ARGV, "-x") if (!$reverse && $dash_x);
  unshift(@ARGV, ("-m", $mainline)) if $mainline != -1;
}

sub run {
  my $self = shift;

  @ARGV = $self->quote_args(@ARGV);
  if ($self->{reverse}) {
    return ExecUtil::execute("git revert @ARGV", ignore_ret => 1);
  } else {
    return ExecUtil::execute("git cherry-pick @ARGV", ignore_ret => 1);
  }
}

###########################################################################
# clone                                                                   #
###########################################################################
package clone;
@clone::ISA = qw(subcommand);
INIT {
  $command{clone} = {
    section => 'creation',
    about => 'Clone a repository into a new directory'
  };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(git_repo_needed => 0, @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg clone [--depth DEPTH] REPOSITORY [DIRECTORY]

Description:
  Obtains a copy of a remote repository, including all history by default.
  A --depth option can be passed to only include a specified number of
  recent commits instead of all history (however, this option exists mostly
  due to the fact that users of other SCMs fail to understand that all
  history can be compressed into a size that is often smaller than the
  working copy).

  See 'eg help topic remote-urls' for a detailed list of the different ways
  to refer to remote repositories.

Examples:
  Get a local clone of cairo
      \$ eg clone git://git.cairographics.org/git/cairo

  Get a clone of a local project in a new directory 'mycopy'
      \$ eg clone /path/to/existing/repo mycopy

  Get a clone of a project hosted on someone's website, asking for only the
  most recent 20 commits instead of all history, and storing it in the
  local directory mydir
      \$ eg clone --depth 20 http://www.random.machine/path/to/git.repo mydir

Options:
  --depth DEPTH
    Only download the DEPTH most recent commits instead of all history
";
  $self->{'differences'} = "
  eg clone and git clone are very similar, but eg clone by default sets up
  a branch for each remote branch automatically (instead of only creating
  one branch, typically master).
";
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  $self->{args} = [];
  $self->{bare} = 0;
  my $record_arg   = sub { push(@{$self->{args}}, "--$_[0]"); };
  my $record_args  = sub { $_[0] = "--$_[0]"; push(@{$self->{args}}, @_);  };
  my $result = main::GetOptions(
    "help"             => sub { $self->help() },
    "template=s"       => sub { &$record_args(@_) },
    "local|l"          => sub { &$record_arg(@_) },
    "shared|s"         => sub { &$record_arg(@_) },
    "no-hard-links"    => sub { &$record_arg(@_) },
    "quiet|q"          => sub { &$record_arg(@_) },
    "no-checkout|n"    => sub { &$record_arg(@_) },
    "bare"             => sub { $self->{bare} = 1; &$record_arg(@_) },
    "origin|o=s"       => sub { &$record_args(@_) },
    "upload-pack|u=s"  => sub { &$record_args(@_) },
    "reference=s"      => sub { &$record_args(@_) },
    "depth=i"          => sub { &$record_args(@_) },
    );
  $self->{repository} = shift @ARGV;
  die "No repository specified!\n" if !$self->{repository};
  my $basename = $self->{repository};
  $basename =~ s#/*$##;     # Remove trailing slashes
  $basename =~ s#.*[/:]##;  # Remove everything but final dirname
  $basename =~ s#\.git$##;  # Remote .git suffix, if present
  $self->{directory} = shift @ARGV || $basename;

  push(@{$self->{args}}, ($self->{repository}, $self->{directory}));
}

sub run {
  my $self = shift;

  #
  # Perform the clone
  #
  @args = $self->quote_args(@{$self->{args}});
  my $ret = ExecUtil::execute("git clone @args", ignore_ret => 1);
  return if $self->{bare};
  if ($debug == 2) {
    return if $self->{bare};
    print "    >>Running: 'cd $self->{directory}'<<\n";
    print "    >>Running: 'git branch -r'<<\n";
    print "    --- Setting up extra branches by default ---\n";
    print "    >>Running, for each remote branch besides master (referred to as BRANCH):\n";
    print "        git branch --no-track BRANCH origin/BRANCH\n";
  } elsif ($ret == 0) {
    # Switch to the appropriate directory, remembering the repository we
    # checked out
    die "$self->{directory} does not exist after checkout!"
      if ! -d $self->{directory};
    $self->{repository} = main::abs_path($self->{repository})
      if -d $self->{repository};
    chdir($self->{directory});

    # Set up a branch for each remote branch, not just master
    my @local_branches = split('\n', `git branch | sed -e "s/^..//"`);
    my @branches = `git branch -r`;
    foreach my $branch (@branches) {
      chomp($branch);
      $branch =~ s#  origin/##;
      next if $branch eq "HEAD";
      next if grep {$branch eq $_} @local_branches;
      ExecUtil::execute("git branch --no-track $branch origin/$branch");
    }
  }
}

###########################################################################
# commit                                                                  #
###########################################################################
package commit;
@commit::ISA = qw(subcommand);
INIT {
  $command{commit} = {
    section => 'modification',
    about => 'Record changes locally'
    };
  $alias{'checkin'} = "commit";
  $alias{'ci'}      = "commit";
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(@_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg commit [-a|--all-known] [-b|--bypass-unknown-check]
            [--staged|-d|--dirty] [-F FILE | -m MSG | --amend] [--]
            [FILE...]

Description:
  Records changes locally along with a log message describing the
  changes you have made.  If no -F or -m option is supplied, an editor
  is opened for you to enter a log message.

  In order to prevent common errors, the commit will abort with a warning
  message if there are no changes to commit, there are conflicts from a
  merge, or if eg detects that the choice of what to commit is ambiguous.
  In particular, if you have any \"newly created\" unknown files present,
  or if you have both staged changes (i.e. changes explicitly marked as
  ready for commit) and unstaged changes, then you will get a warning
  rather than having the commit occur.  You can run 'eg status' to get the
  status of various files and their changes.  These commit checks can be
  bypassed with various options.

Examples:
  Record current changes locally, not changing anything in CVS...OR...get
  a warning message if eg detects that the choice of what to commit is not
  necessarily clear.
      \$ eg commit

  Record current changes, ignoring any unknown files present.  Also
  remember the list of unknown files so that their existence will not
  trigger future \"You have new unknown files present\" warnings when not
  using the -b flag.
      \$ eg commit -b

  Record brand new file and current changes.
      \$ eg stage file.c
      \$ eg commit -a
  Note: Running 'eg stage FILE' explicitly marks FILE as being ready to
  commit.  Since you likely haven't explicitly marked your other changes as
  ready to commit, pass the -a flag to specify that both kinds of changes
  should be recorded.

  (Advanced) Record staged changes, ignoring both unstaged changes and
  unknown files.
      \$ eg commit --staged

Options:
  --all-known, -a
    (Could also be called --act-like-other-vcses).  Commit both staged
    (i.e. explictly marked as ready for commit) changes and unstaged
    changes.

    Incompatible with explicitly specifying files to commit on the command
    line, and incompatible with the --staged option.

  --bypass-unknown-check, -b
    Commit local changes, even if there are unknown files around.  If this
    flag is not used and unknown files are currently present that were not
    present the last time the -b flag was used, then the commit will be
    aborted with a warning message.

  --staged, --dirty, -d
    Commit only staged changes and bypass sanity checks.  (\"dirty\" is kept
    as a synonym in order to provide a short (-d) form.  The term \"dirty\"
    is used to convey the fact that the working area will likely not be
    \"clean\" after a commit since unstaged changes will still be present).

    WARNING: Do not try to use -s as a shorthand for --staged; -s has a
    different meaning (see 'git commit --help')

    Incompatible with explicitly specifying files to commit on the command
    line, and incompatible with the --all-known option.

  -F FILE
    Use the contents of FILE as the commit message

  -m MSG
    Use MSG as the commit message.

  --amend
    Amend the last commit on the current branch.
";
  $self->{'differences'} = '
  The "--staged" (and "-d" and "--dirty" aliases) are unique to eg commit;
  git commit behavior differs from eg commit in that it acts by default
  like the --staged flag was passed UNLESS either the -a option is passed
  or files are explicitly listed on the command line.

  The "--bypass-unknown-check" is unique to eg commit; git commit
  behavior differs by always turning on this functionality -- there is
  no way to have git commit do an unknown files sanity check or a no
  active branch check for you.

  "-a" is not nearly as useful for eg commit as it is for git commit.  "-a"
  has the same behavior in both, but the "smart" behavior of eg commit
  means it is only rarely needed.

  The "--all-known" alias for "-a" is known as "--all" to git-commit; I
  find the latter confusing and misleading and thus renamed to the former
  for eg commit.

  To be precise about the behavior of a plain "eg commit":
     If the working copy is clean                -> warn user: nothing to commit
     else if there are unmerged files            -> warn user: unmerged files
     else if there are new untracked files       -> warn user: new unknown files
     else if both "staged" & unstaged changes[1] -> warn user: mix
     else                                        -> run "git commit -a"
  Actually, I do not pass -a if there are only staged changes present, but
  the result is the same.  Note that this essentially boils down to making
  the user do less work (no need to remember -a in the common case) and
  extending the sanity checks git commit does (which currently only covers
  the clean working copy case) to also prevent a number of other very
  common user pitfalls.

  [1] The reason for putting "staged" in quotes comes from the case of
  running "eg commit --amend" when you have local unstaged changes.  Does
  the user want to merely amend the prior commit message or add their
  changes to the previous commit?  (Even if the index matches HEAD at this
  time, we are committing relative to HEAD^1.)  It is not clear what the
  user wants, so we warn and ask them to use -a or --staged.
';
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  #
  # Parse options
  #
  $self->{args} = [];
  my $record_arg   = sub { push(@{$self->{args}}, "--$_[0]"); };
  my $record_args  = sub { $_[0] = "--$_[0]"; push(@{$self->{args}}, @_);  };
  my ($all_known, $bypass_unknown, $staged, $amend) = (0, 0, 0, 0);
  my $result = main::GetOptions(
    "--help"                      => sub { $self->help() },
    "all-known|a"                 => \$all_known,
    "bypass-unknown-check|b"      => \$bypass_unknown,
    "staged|dirty|d"              => \$staged,
    "s"                           => sub { &$record_arg(@_) },
    "v"                           => sub { &$record_arg(@_) },
    "u"                           => sub { &$record_arg(@_) },
    "c=s"                         => sub { &$record_args(@_) },
    "C=s"                         => sub { &$record_args(@_) },
    "F=s"                         => sub { &$record_args(@_) },
    "m=s"                         => sub { &$record_args(@_) },
    "amend"                       => sub { $amend = 1; &$record_arg(@_) },
    "allow-empty"                 => sub { &$record_arg(@_) },
    "no-verify"                   => sub { &$record_arg(@_) },
    "e"                           => sub { &$record_arg(@_) },
    "author=s"                    => sub { &$record_args(@_) },
    "cleanup=s"                   => sub { &$record_args(@_) },
    );
  my ($opts, $revs, $files) = Util::git_rev_parse(@ARGV);

  #
  # Set up flags based on options, do sanity checking of options
  #
  my ($check_unknown, $check_mixed, $check_no_branch);
  $self->{'commit_flags'} = [];
  die "Cannot specify both --all-known (-a) and --staged (-d)!\n" if
    $all_known && $staged;
  die "Cannot specify --staged when specifying files!\n" if @$files && $staged;
  $check_unknown   = !$bypass_unknown && !$staged && !@$files;
  $check_mixed     = !$all_known      && !$staged && !@$files;
  push(@{$self->{'commit_flags'}}, "-a") if $all_known;

  #
  # Lots of sanity checks
  #
  my $status =
    RepoUtil::commit_push_checks($package_name,
                                 {no_changes       => 1,
                                  unknown          => $check_unknown,
                                  partially_staged => $check_mixed});

  if ($status->{has_unstaged_changes} &&
      !$status->{has_staged_changes} && $amend && !$all_known && !$staged) {
    print STDERR <<EOF;
Aborting: It is not clear whether you want to simply amend the commit message
or whether you want to include your local changes in the amended commit.  Please
pass --staged to just amend the previous commit message, or pass -a to include
your current local changes with the previous amended commit.
EOF
    exit 1;
  }

  die "No staged changes, but --staged given.\n"
      if (!$status->{has_staged_changes} && $staged && !$amend);

  if (!$all_known && !$staged &&
      $status->{has_unstaged_changes} && !$status->{has_staged_changes} &&
      !@$files) {
    push(@{$self->{'commit_flags'}}, "-a");
  }

  #
  # Record the set of unknown files we ignored with -b, so the -b flag isn't
  # needed next time.
  #
  if ($bypass_unknown) {
    RepoUtil::record_ignored_unknowns();
  }

  push(@{$self->{args}}, @{$self->{commit_flags}});
  unshift(@ARGV, @{$self->{args}});
}

###########################################################################
# config                                                                  #
###########################################################################
package config;
@config::ISA = qw(subcommand);
INIT {
  $command{config} = {
    unmodified_behavior => 1,
    extra => 1,
    section => 'misc',
    about => 'Get or set configuration options'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(@_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg config OPTION [ VALUE ]
  eg config --unset OPTION
  eg config [ --list ]

Description:
  Gets or sets configuration options.

  See the 'Configuration File' section of 'man git-config' for a fairly
  comprehensive list of special options used by eg (and git).

Examples:
  Get the value of the configuration option user.email
      \$ eg config user.email

  Set the value of the configuration option user.email to whizbang\@flashy.org
      \$ eg config user.email whizbang\@flashy.org

  Unset the values of the configuration options branch.master.remote
  and branch.master.merge
      \$ eg config --unset branch.master.remote
      \$ eg config --unset branch.master.merge

  List all options that have been set
      \$ eg config --list  
";
  return $self;
}

###########################################################################
# diff                                                                    #
###########################################################################
package diff;
@diff::ISA = qw(subcommand);
INIT {
  $command{diff} = {
    section => 'discovery',
    about => 'Show changes to file contents'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(@_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg diff [--unstaged | --staged] [REVISION] [REVISION] [FILE...]

Description:
  Shows differences between different versions of the project.  By default,
  it shows the differences between the last locally recorded version and the
  version in the working copy.

Examples:
  Show local unrecorded changes
      \$ eg diff

  In a project with the current branch being 'master', show the differences
  between the version before the last recorded commit and the working copy.
      \$ eg diff master~1
  Or do the same using \"HEAD\" which is a synonym for the current branch:
      \$ eg diff HEAD~1

  Show changes to the file myscript.py between 10 versions before last
  recorded commit and the last recorded commit (assumes the current branch
  is 'master').
      \$ eg diff master~10 master myscript.py

  (Advanced) Show changes between staged (ready-to-be-committed) version of
  files and the working copy (use 'eg stage' to stage files).  In other
  words, show the unstaged changes.
      \$ eg diff --unstaged

  (Advanced) Show changes between last recorded copy and the staged (ready-
  to-be-committed) version of files (use 'eg stage' to stage files).  In
  other words, show the staged changes.
      \$ eg diff --staged

  (Advanced) Show changes between 5 versions before the last recorded
  commit and the currently staged (ready-to-be-committed) version of the
  repository.  (Use 'eg stage' to stage files).
      \$ eg diff --staged HEAD~5

Options:
  REVISION
    A reference to a recorded version of the repository, defaulting to HEAD
    (meaning the most recent commit on the current branch).  See 'eg help
    topic revisions' for more details.

  --staged
    Show changes between the last commit and the staged copy of files.
    Cannot be used when two revisions have been specified.

  --unstaged
    Show changes between the staged copy of files and the current working
    directory.  Cannot be used when a revision is specified.
";
  $self->{'differences'} = '
  Changes to eg diff relative to git diff are:
    (1) Different defaults for what to diff relative to
    (2) Providing a more consistent double-dot operator

  Section 1: Different defaults for what to diff relative to

  The following illustrate the two changed defaults of eg diff:
    eg diff            <=> git diff HEAD
    eg diff --unstaged <=> git diff
  (Which is not 100% accurate due to merges; see below.)  In more detail:

  The "--unstaged" option is unique to eg diff; to get the same behavior
  with git diff you simply list no revisions and omit the "--cached" flag.

  When neither --staged nor --unstaged are specified to eg diff and no
  revisions are given, eg diff will pass along the revision "HEAD" to git
  diff.

  The "--staged" option is an alias for "--cached" unique to eg diff (the
  purpose of the alias is to reduce the number of different names in git
  used to refer to the same concept.)

  Merges: The above is slightly modified if the user has an incomplete
  merge; if the user has conflicts during a merge (or uses --no-commit when
  calling merge) and then tries "eg diff", it will abort with a message
  telling the user that there is no "last" commit and will provide
  alternative suggestions.

  Section 2: Providing a more consistent double-dot operator

    The .. operator of git diff (e.g. git diff master..devel) means what
    the ... operator of git log means, and vice-versa.  This causes lots of
    confusion.  We fix this by aliasing making the .. operator of eg diff
    do exactly what the ... operator of git diff does.  To see why:
    
    Meanings of git commands, as a reminder (A and B are revisions):
      git diff A..B  <=> git diff A B                      # Endpoint difference
      git diff A...B <=> git diff $(git merge-base A B) B
    
    Why this is confusing (compare to above):
      git log A..B  <=> git log $(git merge-base A B) B
      git log A...B <=> git log ^$(git merge-base A B) A B # Endpoint difference
    
    So, my translation:
      eg diff A B   <=>  git diff A B    <=> git diff A..B
      eg diff A..B  <=>  git diff A...B
      eg diff A...B <=>  git diff A...B

    Reasons for this change:
      * New users automatically get sane behavior, and use either eg diff A B
        or eg diff A..B, each doing what one would expect.  They do not ever
        realize that A...B is a bit weird because they have no need to try to
        use it; eg diff A B covers their needs.
      * Users worried about switching between eg and git without having to
        modify their command lines can always use either diff A B or
        diff A...B, but never any other form; using this subset ensures that
        both eg and git behave identically.
      * Users only access git diff A..B behavior through eg diff A B, which
        is less typing and makes more sense.
      * Since git diff A..B and git diff A B are the same, the latter is far
        more common, and the former is confusing, odds are that if any git
        user suggests someone use git diff A..B they probably really meant
        git diff A...B
';
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  my ($opts, $revs, $files) = Util::git_rev_parse(@ARGV);
  ## Could also use (do I want to switch over?):
  # my ($opts, $revs, $files) = RepoUtil::parse_args(@ARGV);

  # Replace '..' with '...' in revision specifiers.  Use backslash escaping to
  # get actual dots and not just any character.  Use negative lookbehind and
  # lookahead assertions to avoid replacing '...' with '....'.
  my @new_revs = map(m#(.+)(?<!\.)\.\.(?!\.)(.+)# ? "$1...$2" : $_, @$revs);
  $revs = \@new_revs;

  #
  # Parse options
  #
  $self->{'opts'} = "";
  @ARGV = @$opts;
  my ($staged, $unstaged, $no_index) = (0, 0, 0);
  Getopt::Long::Configure("permute");
  my $result = main::GetOptions(
    "--help"         => sub { $self->help() },
    "staged|cached"  => \$staged,
    "unstaged"       => \$unstaged,
    "no-index"       => \$no_index,
    );
  die "Cannot specify both --staged and --unstaged!\n" if $staged && $unstaged;
  $self->{'opts'} .= " --cached" if $staged;
  $self->{'opts'} .= " --no-index" if $no_index;
  $self->{opts} .= " @ARGV";

  #
  # Parse revs
  #
  die "eg diff: Too many revisions specified.\n" if (scalar @$revs > 2);
  die "eg diff: Cannot specify '--staged' with more than 1 revision.\n"
    if ($staged && scalar @$revs > 1);
  die "eg diff: Cannot specify '--unstaged' with any revisions.\n"
    if ($unstaged && scalar @$revs > 0);
  # 'eg diff' (without arguments) should act like 'git diff HEAD', unless
  # we are in an aborted merge state 
  if (!@$revs && !$unstaged && !$staged && !$no_index) {
    if (-f "$self->{git_dir}/MERGE_HEAD") {
      my @merge_branches = RepoUtil::merge_branches();
      my $list = join(", ", @merge_branches);
      print STDERR <<EOF;
Aborting: Cannot show the changes since the last commit, since you are in the
middle of a merge and there are multiple last commits.  Try passing one of
  --unstaged, $list
to eg diff.

For additional conflict resolution help, try eg log --merge or
  eg show BRANCH:FILE
where FILE is any file in your working copy and BRANCH is one of
  $list
EOF
      exit 1;
    }
    push(@$revs, "HEAD")
  }

  @ARGV = split ' ', "$self->{opts} @$revs @$files"
}

###########################################################################
# gc                                                                      #
###########################################################################
package gc;
@gc::ISA = qw(subcommand);
INIT {
  $command{gc} = {
    unmodified_behavior => 1,
    extra => 1,
    section => 'timesavers',
    about => 'Optimize the local repository to make later operations faster',
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(@_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg gc

Description:
  Optimizes the local repository; in particular, this command compresses
  file revisions to reduce disk space and increase performance.

  This command is occasionally called during normal git usage, making
  explicit usage of this command unnecessary for many users.  However, the
  automatic calls of this command only do simple and quick optimizations,
  so some users (particularly those with many revisions) may benefit from
  manually invoking this command periodically (such as from nightly or
  weekly cron scripts).
";
  return $self;
}

###########################################################################
# help                                                                    #
###########################################################################
package help;
@help::ISA = qw(subcommand);
INIT {
  $command{help} = {
    section => 'misc',
    about => 'Get command syntax and examples'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(exit_status => 0,
                                git_equivalent => '',
                                git_repo_needed => 0,
                                @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg help [COMMAND]
  eg help topic [TOPIC]

Description:
  Shows general help for eg, for one of its subcommands, or for a
  specialized topic.

Examples:
  Show help for eg
      \$ eg help

  Show help for the switch command of eg
      \$ eg help switch

  Show which topics have available help
      \$ eg help topic

  Show the help for the staging topic
      \$ eg help topic staging
";
  $self->{'differences'} = "
  eg help uses its own help system, ignoring the one from git help...except
  that eg help will call git help if asked for help on a subcommand it does
  not recognize.

  'git help COMMAND', by default, simply calls 'man git-COMMAND'.  The git
  man pages are really nice for people who are experts with git; they are
  comprehensive and detailed.  However, new users tend to get lost in a sea
  of details and advanced topics (among other problems).  'eg help COMMAND'
  provides much simpler pages of its own and refers to the manpages for
  more details.  The eg help pages also list any differences between the eg
  commands and the git ones, to assist interested users in learning git.

  If you simply want a brief list of available options and descriptions,
  you may also want to try running 'git COMMAND -h' (which differs from
  the two identical commands 'git COMMAND --help' and 'git help COMMAND').
";

  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  $self->{all} = 0;
  my $result=main::GetOptions("--help" => sub { $self->help() },
                              "--all"  => \$self->{all});
}

sub run {
  my $self = shift;
  my $package_name = ref($self);

  if ($debug == 2) {
    print "    >>(No commands to run, just data to print)<<\n";
    return;
  }

  # Check if we were asked to get help on a subtopic rather than toplevel help
  if (@ARGV > 0) {
    my $subcommand = shift @ARGV;
    $subcommand =~ s/-/_/;  # Packages use underscores, commands use dashes
    if (@ARGV != 0 && ($subcommand ne 'topic' || @ARGV != 1)) {
      die "Too many arguments to help.\n";
    }
    die "Oops, there's a bug.\n" if $self->{exit_status} != 0;
    $subcommand = "help::topic" if $subcommand eq 'topic';

    if (!$subcommand->can("new")) {
      print "$subcommand is not modified by eg (eg $subcommand is equivalent" .
            " to git $subcommand).\nWill try running 'git help $subcommand'" .
            " in 2 seconds...\n";
      sleep 2;
      exit ExecUtil::execute("git help $subcommand");
    }

    my $subcommand_obj = $subcommand->new(initial_commit_error_msg => '',
                                          git_repo_needed => 0);
    $subcommand_obj->help();
  }

  # Print valid subcommands sorted by section
  open(OUTPUT, "| less -FRSX");
  foreach my $name (sort
                    {$section->{$a}{'order'} <=> $section->{$b}{'order'}}
                    keys %$section) {
    next if $section->{$name}{extra} && !$self->{all};
    print OUTPUT "$section->{$name}{desc}\n";
    foreach my $c (sort keys %command) {
      next if !defined $command{$c}{section};
      next if $command{$c}{section} ne $name;
      next if $command{$c}{extra} && !$self->{all};
      printf OUTPUT "  eg %-11s %s\n", $c, $command{$c}{about};
    }
    print OUTPUT "\n";
  }

  # Check to see if someone added a command with an invalid section
  my $broken_commands = "";
  foreach my $c (keys %command) {
    next if !defined $command{$c}{section};
    next if defined $section->{$command{$c}{section}};
    my $tmp = sprintf("  eg %-10s %s\n", $c, $command{$c}{about});
    $broken_commands .= $tmp;
  }
  if ($broken_commands) {
    print OUTPUT "Broken (typo in classification?) commands:\n" .
                 "$broken_commands\n";
  }

  # And let them know how to get more detailed help...
  print OUTPUT "Additional help:\n";
  print OUTPUT "  eg help COMMAND      Get more help on COMMAND.\n";
  print OUTPUT "  eg help --all        List more commands (not really all)\n";
  print OUTPUT "  eg help topic        List specialized help topics.\n";

  # And let them know how to compare to git
  if ($self->{all}) {
    print OUTPUT "\n";
    print OUTPUT "Learning or comparing to git\n";
    print OUTPUT "  eg --translate ARGS  Show commands that would be executed for 'eg ARGS'\n";
    print OUTPUT "  eg --debug ARGS      Show & run commands that would be executed by 'eg ARGS'\n";
  }

  close(OUTPUT);
  
  exit $self->{exit_status};
}

###########################################################################
# help::topic                                                             #
###########################################################################
package help::topic;

sub new {
  my $class = shift;
  my $self = {};
  bless($self, $class);
  return $self;
}

sub refspecs {
  return "
Before reading up on refspecs, be sure you understand all the following
help pages:
  eg help merge
  eg help pull
  eg help push
  eg help rebase
  eg help remote
  eg help topic storage
refspecs compress knowledge from pieces of all those things into a short
amount of space.

refspecs are command line parameters to eg push or eg pull, used at the end
of the command line.  refspecs provide fine-grained control of pushing and
pulling changes in the following two areas:
  Since branches, tags, and remote tracking branches are all implemented by
  creating simple files consisting solely of a sha1sum, it is possible to
  push to or pull from different reference names and different reference
  types.

  Pushing and pulling of (possibly remote tracking) branches are typically
  accompanied by sanity checks to make sure the sha1sums on each end are
  related (to make sure that updates don't throw away previous commits, for
  example).  In some cases it is desirable to ignore such checks, such as
  when a branch has been rebased or commits have been amended.

The canonical format of a refspec is
  [+]SRC:DEST
That is, an optional plus character followed by a source reference, then a
colon character, then the destination reference.  There are a couple
special abbreviations, noted in the abbreviations section below.  The
meaning and syntax of the parts of a refspec are discussed next.

General source and destination handling
  Both the source and the destination reference are typically named by
  their path specification under the .git directory.  Examples:
    refs/heads/bob            # branch: bob
    refs/tags/v2.0            # tag: v2.0
    refs/remotes/jill/stable  # remote-tracking branch: jill/stable
  Leading directory paths can be omitted if no ambiguity would result.

  The refspec specifies that the push or pull operation should take the
  sha1sum from SRC in the source repository, and use it to fast-foward DEST
  in the destination repository.  The operation will fail if updating DEST
  would not be a fast-foward, unless the optional plus in the refspec is
  present.

  Pull operations are somewhat unusual.  For a pull, DEST is usually not
  the current branch.  In such cases, the current branch is also updated
  after DEST is.  The method of updating depends on whether --rebase was
  specified, and whether the latest revision of the current branch is an
  ancestor of the revision stored by DEST:
    If --rebase is specified:
      Rebase the current branch against DEST
    If --rebase is not specified, current branch is an ancestor of DEST:
      Fast-forward the current branch to DEST
    If --rebase is not specified, current branch is not an ancestor of DEST:
      Merge DEST into the current branch

Overriding push and pull sanity checks
  For both push and pull operations, the operation will fail if updating
  DEST to SRC is not a fast-forward.  This tends to happen in a few
  different circumstances:
    For pushes:
      * If someone else has pushed updates to the specified location
        already -- in such cases one should resolve the problem by doing a
        pull before attempting a push rather than overriding the safety
        check.
      * If one has rewritten history (e.g. using rebase, commit --amend,
        reset followed by subsequent commits)
    For pulls:
      * If one is pulling to a branch instead of a remote tracking branch
        -- in such a case, one should instead either specify a remote
        tracking branch for DEST or specify an empty DEST rather than
        overriding the safety check.
      * If one has somehow recorded commits directly to a remote tracking
        branch
      * If history has been rewritten on the remote end (e.g. by using
        rebase, commit --amend, reset followed by subsequent commits).
  In all such cases, users can choose to throw away any existing unique
  commits at the DEST end and make DEST record the same sha1sum as SRC, by
  using a plus character at the beginning of the refspec.

Abbreviations of refspecs
  Globbing syntax
    For either pushes or pulls, one can use a globbing syntax, such as
      refs/heads/*:refs/remotes/jim/*
    or
      refs/heads/*:refs/heads/*
    in order to specify pulling or pushing multiple locations at once.

  The following special abbreviations are allowed for both pushes and pulls:
    tag TAG
      This is equivalent to specifying refs/tags/TAG:refs/tags/TAG.

  The following special abbreviations are allowed for pushes:
    :REFERENCE
      This specifies delete the reference at the remote end (think of it as
      \"using nothing to update the remote reference\")

    REFERENCE
      This is the same as REFERENCE:REFERENCE

  The following special abbreviations are allowed for pulls:
    REFERENCE:
      This is used to merge REFERENCE into the current branch directly
      without storing the remote branch in some remote tracking branch.

    REFERENCE
      This is the same as REFERENCE: which is explained above.
";
}


sub remote_urls {
#
# NOTE: The help for remote_urls is basically lifted from the git manpages,
# which are licensed under GPLv2 (as is eg).
#
  return "
Any of the following notations can be used to name a remote repository:
  rsync://host.xz/path/to/repo.git/
  http://host.xz/path/to/repo.git/
  https://host.xz/path/to/repo.git/
  git://host.xz/path/to/repo.git/
  git://host.xz/~user/path/to/repo.git/
  ssh://[user@]host.xz[:port]/path/to/repo.git/
  ssh://[user@]host.xz/path/to/repo.git/
  ssh://[user@]host.xz/~user/path/to/repo.git/
  ssh://[user@]host.xz/~/path/to/repo.git
You can also use any of the following, which are identical to the last
three above, respectively
  [user@]host.xz:/path/to/repo.git/
  [user@]host.xz:~user/path/to/repo.git/
  [user@]host.xz:path/to/repo.git
Finally, you can also use the following notation to name a not-so-remote
repository:
  /path/to/repo.git/
  file:///path/to/repo.git/
These last two are identical other than that the latter disables some local
optimizations (such as hardlinking copies of history when cloning, in order
to save disk space).
";
}

sub revisions {
#
# NOTE: The pictoral example of revision suffixes is taken from the
# git-rev-parse manpage, which is licensed under GPLv2 (as is eg).
#
  return "
There are MANY different ways to refer to revisions (also referred to as
commits) of the repository.  Most are only needed for fine-grained control
in very large projects; the basics should be sufficient for most.

Basics
  The most common ways of referring to revisions (or commits), are:
    - Branch or tag name (e.g. stable, v0.77, master, 2.28branch, version-1-0)
    - Counting back from another revision (e.g. stable~1, stable~2, stable~3)
    - Cryptographic checksum (e.g. dae86e1950b1277e545cee180551750029cfe735)
    - Abbreviated checksum (e.g. dae86e)

  The output of 'eg log' shows (up to) two names for each revision: its
  cryptographic checksum and the count backward relative to the currently
  active branch (if the revision being shown in eg log is not part of the
  currently active branch then only the cryptographic checksum is shown).

  One can always check the validity of a revision name and what revision
  it refers to using 'eg log -1 REVISION' (the -1 to show only one revision).

Branches and Tags
  Users can specify a tag name to refer to the revision marked by that tag.
  Run 'eg tag' to get a list of existing tags.

  Users can specify a branch name to refer to the most recent revision of
  that branch.  Use 'eg branch' to get a list of existing branches.

Cryptographic checksums
  Each revision of a repository has an associated cryptographic checksum
  (in particular, a sha1sum) identifying it.  This cryptographic checksum
  is a sequence of 40 letters and numbers from 0-9 and a-f.  For example,
    dae86e1950b1277e545cee180551750029cfe735
  In addition to using these sha1sums to refer to revisions, one can also
  use an abbreviation of a sha1sum so long as enough characters are used to
  uniquely identify the revision (typically 6-8 characters are enough).

Special Names
  There are a few special revision names.

  Names that always exist:
    HEAD - A reference to the most recent revision of the current branch
           (thus HEAD refers to the same revision as using the branch
           name).  If there is no active branch, such as after running
           'eg switch TAG', then HEAD refers to the revision switched to.

           Note that the files in the working copy are always considered to
           be a (possibly modifed) copy of the revision pointed to by HEAD.

  Names that only exist in special cases:
    ORIG_HEAD -  Some operations (such as merge or reset) change which
                 revision the working copy is relative to.  These will
                 record the old value of HEAD in ORIG_HEAD.  This allows
                 one to undo such operations by running
                   eg reset --working-copy ORIG_HEAD
    FETCH_HEAD - When downloading branches from other repositories (via
                 the fetch or pull commands), the tip of the last fetched
                 branch is stored in FETCH_HEAD.
    MERGE_HEAD - If a merge operation results in conflicts, then the merge
                 will stop and wait for you to manually fix the conflicts.
                 In such a case, MERGE_HEAD will store the tip of the
                 branch(es) being merged into the current branch.  (The
                 current branch can be accessed, as always, through HEAD.)

Suffixes for counting backwards
  There are two suffixes for counting backwards from revisions to other
  revisions: ~ and ^.

  Adding ~N after a revision, with N a non-negative integer, means to count
  backwards N commits before the specified revision.  If any revision along
  the path has more than one parent (i.e. if any revision is a merge
  commit), then the first parent is always followed.  Thus, if stable is a
  branch, then
    stable   means the last revision on the stable branch
    stable~1 means one revision before the last on the stable branch
    stable~2 means two revisions before the last on the stable branch
    stable~3 means three revisions before the last on the stable branch
  In short, ~N goes back N generation of parents, always following the
  first parent.

  Adding ^N after a revision, with N a non-negative integer, means the Nth
  parent of the specified revision.  N can be omitted in which case it is
  assumed to have the value 1.  Thus, if stable is a branch, then
    stable   means the last revision on the stable branch
    stable^1 means the first parent of the last revision on the stable branch
    stable^2 means the second parent of the last revision on the stable branch
    stable^3 means the third parent of the last revision on the stable branch
  In short, ^N picks out one parent from the first generation of parents.

  Revisions with suffixes can themselves have suffixes, thus
    stable~5 = stable~3~2

  Here is an illustration with an unusually high amount of merging.  The
  illustration has 10 revisions each tagged with a different letter of the
  alphabet, with A referring to the most recent revision:
                A
               / \\
              /   \\
             B     C
            /|\\    |
           / | \\   |
          /  |  \\ /
         D   E   F
        / \\     / \\
       G   H   I   J

  From the illustration, the following equalities hold:
       A =      = A^0
       B = A^   = A^1     = A~1
       C = A^2  = A^2
       D = A^^  = A^1^1   = A~2
       E = B^2  = A^^2
       F = B^3  = A^^3
       G = A^^^ = A^1^1^1 = A~3
       H = D^2  = B^^2    = A^^^2  = A~2^2
       I = F^   = B^3^    = A^^3^
       J = F^2  = B^3^2   = A^^3^2

Revisions from logged branch tip history
  By default, all changes to each branch and to the special identifier HEAD
  are recorded in something called a reflog (short for \"reference log\",
  because calling it a \"branch log\" would not have made the glossary of
  special terms long enough).  Each entry of the reflog records the
  previous revision recorded by the branch, the new revision the branch was
  changed to, the command used to make the change (commit, merge, reset,
  pull, checkout, etc.), and when the change was made.  One can get an
  overview of the changes made to a branch (including the special branch
  'HEAD') by running
    eg reflog show BRANCHNAME

  One can make use of the reflog to refer to revisions that a branch used
  to point to.  The format for referring to revisions from the reflog are
    BRANCH\@{HISTORY_REFERENCE}
  Examples follow.

  Revisions that the branch pointed to, in order
    Assuming that ultra-bling is the name of a branch, the following can be
    used to refer to revisions ultra-bling used to point to:
      ultra-bling\@{0} is the same as ultra-bling
      ultra-bling\@{1} is the revision pointed to before the last change
      ultra-bling\@{2} is the revision ultra-bling pointed to two changes ago
      ultra-bling\@{3} is the revision ultra-bling pointed to three changes ago
    Note that any of these beyond the first could easily refer to commits
    that are no longer part of the ultra-bling branch (due to using a
    command like reset or commit --amend).

  Revisions that the branch pointed to at a previous time
    Assuing that fixes is the name of a branch, the following can be used to
    refer to revisions that fixes used to point to:
      fixes\@{yesterday}           - revision fixes pointed to yesterday
      fixes\@{1 day 3 hours ago}   - revision fixes pointed to 1 day 3 hours ago
      fixes\@{2008-02-29 12:34:00} - revision fixes had at 12:34 on Feb 29, 2008
    Again, these could refer to revisions that are no longer part of the
    fixes branch, 

  Using the branch log can be used to recover \"lost\" revisions that are
  no longer part of (or have never been part of) any branch reported by 'eg
  branch'.

Commit messages
  One can also refer a revision using the beginning of the commit message
  recorded in it.  This is done using with the two-character prefix :/
  followed by the beginning of the commit message.  Note that quotation marks
  are also often used to avoid having the shell split the commit message into
  different arguments.  Examples:
    :/\"Fix the biggest bug blocking the 1.0 release\"
    :/\"Make the translation from url\"
    :/\"Add a README file\"
  Note that if the commit message starts with an exclamation mark ('!'), then
  you need to type two of them; for example example:
    :/\"!!Commit messages starting with an exclamation mark are retarded\"

Other methods
  There are even more methods of referring to revisions.  Run \"man
  git-rev-parse\", and look for the \"SPECIFYING REVISIONS\" section for
  more details.
";
}

sub staging {
  return "
Marking changes from certain files as ready for commit allows you to split
your changes into two distinct sets (those that are ready for commit, and
those that aren't).  This includes support for limiting diffs to changes in
one of these two sets, and for committing just the changes that are ready.
It's a simple feature that comes in surprisingly handy:

  * When doing conflict resolution from large merges, hunks of changes can
    be categorized into known-to-be-good and still-needs-more-fixing
    subsets.

  * When reviewing a largish patch from someone else, hunks of changes can
    be categorized into known-to-be-good and still-needs-review subsets.

  * By staging your changes, you can go ahead and add temporary debugging
    code and have less fear of forgetting to remove it before committing --
    you will be warned about having both staged and unstaged changes at
    commit time, and you will have an easy way to locate the temporary
    code.

  * It makes it easier to keep \"dirty\" changes in your working copy for a
    long time without committing them.

Staging changes and working with staged changes
  Mark all changes in foo.py and baz.c as ready to be committed
    eg stage foo.py baz.c

  Selectively stage part of the changes
    eg stage -p
  (You will be asked whether to stage each change, listed in diff format;
  the main options to know are \"y\" for yes, \"n\" for no, and \"s\" for
  splitting the selected change into smaller changes; see 'man git-add' for
  more details).

  Get all unstaged changes to bar.C and foo.pl
    eg diff --unstaged foo.pl bar.C

  Get all staged changes
    eg diff --staged

  Get all changes
    eg diff

  Revert the staged changes to bar.C, foo.pl and foo.py
    eg unstage bar.C foo.pl foo.py

  Commit just the staged changes
    eg commit --staged
";
}

sub storage {
  return "
Basics
  Each revision is referred to by a cryptographic checksum (in particular,
  a sha1sum) of its contents.  Each revision also knows which revision(s)
  it was derived from, known as the revision's parent(s).

  Each branch records the cryptographic checksum of the most recent commit
  for the branch.  Since each commit records its parent(s), a branch
  consists of its most recent commit plus all ancestors of that commit.
  When a new commit is made on a branch, the branch just replaces the
  cryptographic checksum of the old commit with the new one.

  Remote tracking branches, if used (see 'eg help remote'), differ from
  normal branches only in that they have a slash in their name.  For
  example, the remote tracking branch that tracks the contents of the
  stable branch of the remote named bob would be called bob/stable.  By
  their nature, remote tracking branches only track the contents of a
  branch of a remote repository; one does not switch to and commit to these
  branches.

  Tags simply record a single revision, much like branches, but tags are
  not advanced when additional commits are made.  Tags are not stored as
  part of a branch, though by default tags that point to commits which are
  downloaded (as part of merging changes from a branch) are themselves
  downloaded as well.

  Neither branches nor tags are revision controlled, though there is a log
  of changes made to each branch (known as a reflog, short for \"reference
  log\", because calling it a \"branch log\" wouldn't make the glossary of
  special terms long enough).

Pictorial explanation
  Using the letters A-P as shorthand for different revisions and their
  cryptographic checksums (which we'll assume were created in the order
  A...P for purposes of illustration), an example of the kind of structure
  built up by having commits track their parents is:
        N
        |
        M   P
        |   |
        L   O
        | \\ |
        J   K
        |   |
        H   I
        | /
        G
        |
        F
       / \\
      C   E
      |   |
      B   D
      |
      A
  In this picture, F has two parents (C and E) and is thus a merge commit.
  L is also a merge commit, having parents J and K.  There are two branches
  depicted here, which can be identified by N and P (due to the fact that
  branches simply track their most recent commit).  This history is
  somewhat unusual in that there is no unique start of history; instead
  there are two beginnings of history -- A and D.  Such a history can be
  created by pulling from, and merging with, a branch from another
  repository that shares no common history.  While unusual, it is fully
  supported.

  For further illustration, let's assume that the following branches exist:
      stable: N
      bling:  P
  Then the picture of each branch, side by side (using revision identifiers
  explained in 'eg help topic revisions'), is:
            stable
              |
           stable~1                                     bling
              |                                           |   
           stable~2                                    bling~1
              |   \\                                       |   
        stable~3  stable~2^2                           bling~2
              |     |                                     |   
        stable~4  stable~2^2~1                         bling~3
              |  /                                     /      
          stable~6                                bling~4     
              |                                     |         
          stable~7                                bling~5     
            /   \\                                 /   \\       
      stable~8  stable~7^2                   bling~6  bling~5^2
          |       |                             |       |     
      stable~9  stable~7^2~1                 bling~7  bling~5^2~1     
          |                                     |             
      stable~10                              bling~8             
  Note that there are many commits which are part of both branches,
  including two commits (I and K in the original picture) which were
  probably created after these two branches separated.  This is simply due
  to recording both parents in merge commits.

  Note that this tree-like or graph-like structure of branches is an
  example of something that computer scientists call a Directed Acyclic
  Graph (DAG); referring to it as such provides us the opportunity to
  make the glossary of special terminology longer.

Files and directories in a git repository (stuff under .git)
  You may find the following files and directories in your git repository.
  This document will discuss the highlights; see the repository-layout.html
  page distributed with git for more details.

  COMMIT_EDITMSG
    A leftover file from previous commits; this is the file that commit
    messages are recorded to when when you do not specify a -m or -F option
    to commit (thus causing an editor to be invoked).

  config
    A simple text file recording configuration options; see 'eg help config'.

  description
    A file that is only used by gitweb, currently.  If you use gitweb, this
    files provides a description of the project tracked in the repository.

  HEAD
  ORIG_HEAD
  FETCH_HEAD
  MERGE_HEAD
    See the Special Names section of 'eg help topic revisions'; these files
    record these special revisions.

  git-daemon-export-ok
    This file is only relevant if you are using git-daemon, a server to
    provide access to your repositories via the git:// protocol.
    git-daemon refuses to provide access to any repository that does not
    have a git-daemon-export-ok file.

  hooks
    A directory containing customizations scripts used by various commands.
    These scripts are only used if they are executable.

  index
    A binary file which records the staging area.  See 'eg help topic
    staging' for more information.

  info
    A directory with additional info about the repository

    info/exclude
      An additional place to specify ignored files.  Users typically use
      .gitignore files in the relevant directories to ignore files, but
      ignored files can also be listed here.

    info/ignored-unknown
      A list of unknown files known to exist previously, used to determine
      whether unknown files should cause commit (or push or publish) to
      abort.  See 'eg help commit' for more information; this list is
      updated whenever the -b flag is passed to commit.

    info/refs
      This is a file created by 'eg update-server-info' and is needed for
      repositories accessed over http.

  logs
    History of changes to references (i.e. to branches, tags, or
    remote-tracking branches).  The file logs/PATH/TO/FILE in the
    repository records the changes to the reference PATH/TO/FILE in the
    repository.  See also the 'Revisions from logged branch tip history'
    section of 'eg help topic revisions'.

  objects
    Storage of actual user data (files, directory trees, commit objects).
    Storage is done according to sha1sum of each object (splitting sha1sums
    into a combination of directory name and file name).  There are also
    packs, which compress many objects into one file for tighter storage
    and reduced disk usage.

  packed-refs
    The combination of paths, filenames, and sha1sums from many different
    refs -- one per line; see refs below.

  refs
    Storage of references (branches, heads, or remote tracking branches).
    Each reference is a simple file consisting of a sha1sum (see 'eg help
    topic storage' for more information).  The path provides the type of
    the reference, the file name provides the name for the reference, and
    the sha1sum is the revision the reference refers to.

    Branches are stored under refs/heads/*, tags under refs/tags/*, and
    remote tracking branches under refs/remotes/REMOTENAME/*.  Note that
    some of these references may appear in packed-refs instead of having
    a file somewhere under the refs directory.
";
}

sub help {
  my $self = shift;
  my $help_msg;

  # Get the topic we want more info on (replace dashes, since they can't
  # be in function names)
  my $topic = shift @ARGV;
  my $orig_topic = $topic;
  $topic =~ s/-/_/g if $topic;

  ### FIXME: Add the following topics, plus maybe some others
  # glossary      <Not yet written; this is just a stub>

  my $topics = "
refspecs      Advanced pushing and pulling: detailed control of storage
remote-urls   Format for referring to remote (and not-so-remote) repositories
revisions     Various methods for referring to revisions
staging       Marking a subset of the local changes ready for committing
storage       High level overview of how commits, tags, and branches are stored
";

  if (defined $topic) {
    die "No topic help for '$topic' exists.  Try 'eg help topic'.\n"
      if !$self->can($topic);
    $help_msg = $self->$topic();
    if ($topics =~ m#^(\Q$orig_topic\E.*)#m) {
      $topic = $1;
    }
  } else {
    $topic = "Topics";
    $help_msg = $topics;
  }

  open(OUTPUT, "| less -FRSX");
  print OUTPUT "$topic\n";
  print OUTPUT $help_msg;
  close(OUTPUT);

  exit 0;
}

###########################################################################
# info                                                                    #
###########################################################################
package info;
@info::ISA = qw(subcommand);
INIT {
  $command{info} = {
    new_command => 1,
    section => 'discovery',
    extra => 1,
    about => 'Show some basic information about the current repository'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(git_equivalent => '', git_repo_needed => 0, @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg info [/PATH/TO/REPOSITORY]

Description:
  Shows information about the specified repository, or the current
  repository if none is specified.

  Most of the output of eg info is self-explanatory, but some fields
  benefit from extra explanation or pointers about where to find related
  information.  These fields are:

    Total commits
      The total number of commits (or revisions) found in the repository.
      eg log can be used to view revision authors, dates, and commit log
      messages.

    Local repository
      eg has a number of files and directories it uses to track your data,
      including (by default) a copy of the entire history of the project.
      These files and directories are all stored below a single directory,
      referred to as the local repository.  See 'eg help topic storage' for
      more details.

    Named remote repositories
      To make it easier to track changes from multiple remote repositories,
      eg provides the ability to provide nicknames for and work with
      multiple branches from a remote repository and even working with
      multiple remote repositories at once.  See 'eg help remote' for more
      details, though you will want to make sure you understand 'eg help
      pull' and 'eg help push' first.

    Current branch
      All development is done on a branch, though smaller projects may only
      use one branch per repository (thus making the repository effectively
      serve as a branch).  In contrast to cvs and svn which refer to
      mainline development as \"HEAD\" and \"TRUNK\", respectively, eg
      calls the mainline development a branch as well, with the default
      name of \"master\").  See 'eg help branch' and 'eg help topic
      storage' for more details.

    Cryptographic checksum
      Each revision has an associated cryptographic checksum of both its
      contents and the revision(s) it was derived from, providing strong
      data consistency checks and guarantees.  These checksums are shown in
      the output of eg log, and serve as a way to refer to revisions.  See
      also 'eg help topic storage' for more details.

    Default pull/push configuration options:
      The default repository to push to or pull from defaults to 'origin',
      if the 'origin' remote has been set up (see 'eg help remote' for
      setting up remote repository nicknames).

      However, the default repository can be set on a per-branch basis as a
      configuration option (see 'eg help config').  In fact, a number of
      default pull/push actions can be set as per-branch configuration
      options: default merge options to use on a given branch, default
      branch to merge with from the remote repository, and whether to
      rebase (rewrite local commits on top of new remote commits; see 'eg
      help rebase') rather than merge (keep local commits as they are and
      just make a merge commit combining local and remote changes; see 'eg
      help merge').

";
  $self->{'differences'} = '
  eg info is unique to eg; git does not have a similar command.  It
  originally was intended just to do something nice if svn converts happen
  to try this command, but I have found it to be a really nice way of
  helping users get their bearings.  It also provides some nice statistics
  that git users may appreciate (particularly when it comes time to fill
  out the Git User Survey).
';
  return $self;
}

sub preprocess {
  my $self = shift;

  my $path = shift @ARGV;
  die "Aborting: Too many arguments to eg info.\n" if @ARGV;

  if ($path) {
    die "$path does not look like a directory.\n" if ! -d $path;
    my ($ret, $useless_output) =
      ExecUtil::execute_captured("git ls-remote $path", ignore_ret => 1);
    if ($ret != 0) {
      die "$path does not appear to be a git archive " .
          "(maybe it has no commits yet?).\n";
    }
    chdir($path);
  }

  # Set git_dir
  $self->{git_dir} = RepoUtil::git_dir();
  die "Must be run inside a git repository!\n" if !defined $self->{git_dir};
}

sub run {
  my $self=shift;

  my $branch = RepoUtil::current_branch();

  #
  # Special case the situation of no commits being present
  #
  if (RepoUtil::initial_commit()) {
    if ($debug < 2) {
      print STDERR <<EOF;
Total commits: 0
Local repository: $self->{git_dir}
There are no commits in this repository.  Please use eg stage to mark new
files as being ready to commit, and eg commit to commit them.
EOF
    }
    exit 1;
  }

  #
  # Repository-global information
  #

  # total commits
  my $total_commits = ExecUtil::output("git rev-list --all | wc -l");;
  print "Total commits: $total_commits\n" if $debug < 2;

  # local repo
  print "Local repository: $self->{git_dir}\n" if $debug < 2;

  # named remote repos
  my %remotes;
  my $longest = 0;
  my @abbrev_remotes = split('\n', ExecUtil::output("git remote"));
  foreach $remote (@abbrev_remotes) {
    chomp($remote);
    my $url = RepoUtil::get_config("remote.$remote.url");
    $remotes{$remote} = $url;
    $longest = main::max($longest, length($remote));
  }
  if (scalar keys %remotes > 0 && $debug < 2) {
    print "Named remote repositories: (name -> location)\n";
    foreach my $remote (sort keys %remotes) {
      printf "  %${longest}s -> %s\n", $remote, $remotes{$remote};
    }
  }

  #
  # Stats for the current branch...
  #
  return if !defined($branch);

  # File & directory stats only work if we're in the toplevel directory
  my ($orig_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();
  chdir($top_dir);

  # Name
  print "Current branch: $branch\n" if $debug < 2;

  # Sha1sum
  my $current_commit = ExecUtil::output("git show-ref -s -h | head -n 1");
  print "  Cryptographic checksum (sha1sum): $current_commit\n" if $debug < 2;

  # Default pull/push options
  RepoUtil::migrate_old_easy_git_pull_push_options();
  my $default = "-None-";
  my $print_config_options = 0;
  my ($ret, $options) =
    ExecUtil::execute_captured("git config --get-regexp ^branch\.$branch\.*",
                               ignore_ret => 1);
  chomp($options);
  my @lines;
  if ($ret == 0) {
    @lines = split('\n', $options);
    my $line_count = scalar(@lines);
    $print_config_options = ($line_count > 0);

    if ($options =~ /^branch\.$branch\.remote (.*)$/m) {
      $default = $1;
      $print_config_options = ($line_count > 1);
    } else {
      my @output = `git config --get-regexp remote.origin.*`;
      $default = "origin" if @output;
    }
  }
  print "  Default pull/push repository: $default\n" if $debug < 2;
  if ($print_config_options && $debug < 2) {
    print "  Default pull/push options:\n";
    foreach my $line (@lines) {
      $line =~ s/\s+/ = /;
      print "    $line\n";
    }
  }

  # No. contributors
  my $contributors  = ExecUtil::output("git shortlog -s -n HEAD | wc -l");
  print "  Number of contributors: $contributors\n" if $debug < 2;

  # No. files
  my $num_files = ExecUtil::output("git ls-tree -r HEAD | wc -l");
  print "  Number of files: $num_files\n" if $debug < 2;

  # No. dirs
  my $num_dirs = ExecUtil::output(
                    "git ls-tree -r -t HEAD " .
                    " | grep -E '[0-9]+ tree'" .
                    " | wc -l");
  print "  Number of directories: $num_dirs\n" if $debug < 2;

  # Some ugly, nasty code to get the biggest file.  Seems to be the only
  # method I could find that would work given the corner case filenames
  # (spaces and unicode chars) in the git.git repo (Try eg info on repo
  # from 'git clone git://git.kernel.org/pub/scm/git/git.git').
  my @files = `git ls-tree -r -l --full-name HEAD`;
  my %biggest = (name => '', size => 0);
  foreach my $line (@files) {
    if ($line =~ m#^[0-9]+ [a-z]+ [0-9a-f]+[ ]*(\d+)[ \t]*(.*)$#) {
      my ($size, $file) = ($1, $2);
      if ($file =~ m#^\".*\"#) { $file = eval "$file" };  # Unicode fix
      if ($size >= $biggest{size}) {
        $biggest{name} = $file;
        $biggest{size} = $size;
      }
    }
  }
  my $biggest_file = "$biggest{size} ($biggest{name})";
  print "  Biggest file size, in bytes: $biggest_file\n" if $debug < 2;

  # No. commits
  my $branch_depth  = ExecUtil::output("git rev-list HEAD | wc -l");;
  print "  Commits: $branch_depth\n" if $debug < 2;

  # Other possibilities:
  #   Disk space used by respository (du -hs .git, or packfile size?)
  #   Disk space used by working copy (???)
  #   Number of unpacked objects?

  chdir($orig_dir);
}

###########################################################################
# init                                                                    #
###########################################################################
package init;
@init::ISA = qw(subcommand);
INIT {
  $command{init} = {
    unmodified_behavior => 1,
    section => 'creation',
    about => 'Create a new repository'
  };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(git_repo_needed => 0, @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg init [--shared]

Description:
  Creates a new repository.

  If you want to publish a copy of an existing repository so that others
  can access it, use eg publish instead.

  Note for cvs/svn users: With cvs or svn it is common to create an empty
  repository on \"the server\", then check it out locally and start adding
  files and committing.  With eg, it is more natural to create a repository
  on your local machine and start creating and adding files, then later
  (possibly as soon as one commit later) publishing your work to \"the
  server\".  git (and thus eg) does not currently allow cloning empty
  repositories, so for now you must change habits.

Examples:
  Create a new blank repository, then use it by creating and adding a file
  to it:
      \$ mkdir project
      \$ cd project
      \$ eg init
      Create and edit a file called foo.py
      \$ eg stage foo.py
      \$ eg commit

  Create a repository to track further changes to an existing project.  Then
  start using it right away
      \$ cd cool-program
      \$ eg init
      \$ eg stage .           # Recursively adds all files
      \$ eg commit -m \"Initial import of all files\"
      Make more changes to fix a bug or add a new feature or...
      \$ eg commit

  (Advanced) Create a new blank repository meant to be used in a
  centralized fashion, i.e. a repository for many users to commit to.
      \$ mkdir new-project
      \$ cd new-project
      \$ eg init --shared
      Check repository ownership and user groups to ensure they are right

Options:
  --shared
    Set up a repository that will shared amongst several users; note that
    you are responsible for creating a common group for developers so that
    they can all write to the repository.  Ask your sysadmin or see the
    groupadd(8), usermod(8), chgrp(1), and chmod(1) manpages.
";
  return $self;
}

###########################################################################
# log                                                                     #
###########################################################################
package log;
@log::ISA = qw(subcommand);
INIT {
  $command{log} = {
    section => 'discovery',
    about => 'Show history of recorded changes'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    initial_commit_error_msg => "Error: No recorded commits to show yet.",
    @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg log

Description:
  Shows a history of recorded changes.  Displays commit identifiers,
  the authors of the changes, and commit messages.
";
  $self->{'differences'} = '
  eg log output differs from git log output by showing simpler revision
  identifiers that will be easier for new users to understand and use.
  In detail:
    eg log
  is essentially the same as
    git log | git name-rev --stdin --refs=$(git symbolic-ref HEAD) | less
  However, it implements the name-rev behavior internally to provide
  incremental history processing (which avoids slow upfront full-history
  analyses) in common cases.
';
  return $self;
}

sub _get_values {
  my ($names, $sha1sum) = @_;
  my ($name, $distance);
  if (defined($names->{$sha1sum})) {
    ($name, $distance) = @{$names->{$sha1sum}};
  }
  return ($name, $distance);
}

sub _get_revision_name {
  my ($sha1sum, $filehandle, $names) = @_;
  my ($name, $distance);

  # If we've already determined teh name of this sha1sum before, just return it
  ($name, $distance) = _get_values($names, $sha1sum);
  return $name if defined $name;

  # Loop over rev-list output, naming the parents of each commit as we walk
  # backward in history (breaking whenever if we hit our sha1sum)
  while (<$filehandle>) {
    # Each line of the rev-list output is of form
    #   sha1sum-of-commit sha1sum-of-parent1 sha1sum-of-parent2...
    my ($child, $parent, @merge_parents) = split;

    next if !$parent;

    # Determine the name of the current commit, and its distance from the head
    # of the current branch
    my ($cur_name, $distance) = _get_values($names, $child);
    die "Yikes!  Your history is b0rken!\n" if (!$cur_name);

    # Determine any name we previously determined for $parent, the name we
    # would give it relative to $child, and determine which should "win"
    my ($orig_parent_name, $orig_parent_distance) = _get_values($names, $parent);
    if ($cur_name =~ /^(.*)~(\d+)$/) {
      my $count = $2 + 1;
      $parent_name = "$1~$count";
    } else {
      $parent_name = "$cur_name~1";
    }
    $parent_distance = $distance + 1;
    if (!$orig_parent_name || $orig_parent_distance > $parent_distance) {
      $names->{$parent} = [$parent_name, $parent_distance];
    }

    # Do the same for other parents, though their naming scheme is slightly
    # different
    my $count=2;
    foreach my $merge_parent (@merge_parents) {
      ($orig_parent_name, $orig_parent_distance) =
        _get_values($names, $merge_parent);
      if (!$orig_parent_name || $orig_parent_distance > $parent_distance) {
        $names->{$merge_parent} = ["$cur_name^$count", $parent_distance];
      }
      $count++;
    }

    # Check if we found the needed sha1sum, and exit early if so
    push(@merge_parents, $parent);
    last if (grep {$_ eq $sha1sum} @merge_parents);
  }

  # Check if we found the needed sha1sum; if so, return it
  ($name, $distance) = _get_values($names, $sha1sum);
  return $name if $name;

  # We didn't find the wanted sha1sum; it has no name relative to the current
  # branch using tildes and hats.
  return "";
}

sub run {
  my $self = shift;
  @ARGV = $self->quote_args(@ARGV);

  my $branch = RepoUtil::current_branch();
  my ($ret, $revision) =
    ExecUtil::execute_captured("git rev-parse refs/heads/$branch");
  chomp($revision);

  # We can just run plain git log if there's not current branch
  if (!$branch) {
    ExecUtil::execute("git log @ARGV");
    return;
  }

  # Show the user the essential equivalent to what we manually do
  if ($debug) {
    print "    >>Running: git log @ARGV | \\\n" .
       "               git name-rev --stdin --refs=refs/heads/$branch | \\\n" .
       "               less\n";
    return if $debug == 2;
  }

  # Setup name determination via output from git rev-list
  my %names;
  open(REV_LIST_INPUT, "git rev-list --parents $branch | ");
  $names{$revision} = [$branch, 0];

  # Loop over the output of git log, printing/modifying as we go
  open(INPUT, "git log @ARGV | ");
  open(OUTPUT, "| less -FRSX");
  #open(OUTPUT, ">&STDOUT");
  while (<INPUT>) {
    # If it's a commit line, determine the name of the commit and print it too
    if (/^(commit ([0-9a-f]{40}))$/) {
      my $name = _get_revision_name($2, REV_LIST_INPUT, \%names);
      print OUTPUT "$1 ($name)\n" if $name;
      print OUTPUT "$1\n"         if !$name;
    } else {
      print OUTPUT;
    }
  }
  close(INPUT);
  close(OUTPUT);

  # Make sure we close the pipe from rev-list too
  close(REV_LIST_INPUT);
}

###########################################################################
# merge                                                                   #
###########################################################################
package merge;
@merge::ISA = qw(subcommand);
INIT {
  $command{merge} = {
    unmodified_behavior => 1,
    section => 'projects',
    about => 'Join two or more development histories (branches) together'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    initial_commit_error_msg => "No branches can be merged until there is " .
                                "at least one commit.",
    @_
    );
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg merge [-m MESSAGE] BRANCH...

Description:
  Merges another branch (or more than one branch) into the current branch.

  You may want to skip to the examples; the remainder of this description
  section just has boring details about how merges work.

  There are three different ways to handle merges depending on whether the
  current branch or the specified merge branches have commits not found in
  the other.  These cases are:
    1) The current branch contains all commits in the specified branch(es).
         In this case, there is nothing to do.
    2) Both the current branch and the specified merge branch(es) contain
       commits not found in the other:
         In this case, a new commit will be created which (a) includes
         changes from both the current branch and the merge branch(es) and
         (b) records the parents of the new commit as the last revision of
         the current branch and the last revision(s) of the merge
         branch(es).
    3) The specified merge branch has all the commits found in the current
       branch.
         In this case, a new commit is not needed to merge the branches
         together.  Instead, the current branch simply changes the record
         of its last revision to that of the specified merge branch.  This
         is known as a fast-forward update.
  See 'eg help topic storage' for more information.

Examples:
  Merge all changes from the stable branch that are not already in the
  current branch, into the current branch.
      \$ eg merge stable

  Merge all changes from the refactor branch into the current branch (i.e.
  same as the previous example but merging in a different branch)
      \$ eg merge refactor

Options:
  -m MESSAGE
    Use MESSAGE as the commit message for the created merge commit, if
    a merge commit is needed.
";
  return $self;
}

###########################################################################
# publish                                                                 #
###########################################################################
package publish;
@publish::ISA = qw(subcommand);
INIT {
  $command{publish} = {
    extra => 1,
    new_command => 1,
    section => 'collaboration',
    about => 'Publish a copy of the current repository on a remote machine'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    git_equivalent => '',
    initial_commit_error_msg => "Error: No recorded commits to publish.",
    @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg publish [--bypass-modification-check] REMOTE_DIRECTORY

Description:
  Publishes a copy of the current repository on a remote machine.  Note
  that local changes will be ignored; only committed changes will be
  published.  You must have ssh access to the remote machine and must have
  both rsync and ssh installed on your local machine (every modern distro
  or OS installs both by default).

  The remote directory should be specified using rsync syntax, even if the
  remote repository will be accessed by some other protocol.  Typical rsync
  syntax for a (usually remote) directory is
     [[USER@]MACHINE:]PATH
  If PATH is not absolute and MACHINE is specified, it is taken as relative
  to the user's home directory on MACHINE.  See the examples below for more
  detail, or the rsync(1) manpage.  If any files or directories exist below
  the specified remote directory, they will be removed or replaced.

  Note that if git is not installed on the remote machine, you will be
  unable to push updates to the remote repository (however, you can
  republish over the top of the previous copy).

Examples:
  Publish a copy of the current repository on the machine myserver.com in
  the directory /var/scratch/git-stuff/my-repo.git.  Then immediately
  make a clone of the remote repository
      \$ eg publish myserver.com:/var/scratch/git-stuff/my-repo.git
      \$ cd
      \$ eg clone myserver.com:/var/scratch/git-stuff/my-repo.git

  Publish a copy of the current repository on the machine www.gnome.org, in
  the public_html/myproj subdirectory of the home directory of the remote
  user fake, then immediately clone it again into a separate directory
  named another-myproj.
      \$ eg publish fake\@www.gnome.org:public_html/myproj
      \$ cd 
      \$ eg clone http://www.gnome.org/~fake/myproj another-myproj

Options
  --bypass-modification-check, -b
    To prevent you from publishing an incomplete set of changes, publish
    typically checks whether you have new unknown files or modified files
    present and aborts if so.  You can bypass these checks with this
    option.
";
  $self->{'differences'} = '
  eg publish is unique to eg; git makes publishing repositories annoyingly
  painful.  The steps that eg publish performs are (assuming one is in the
  toplevel directory and that GIT_DIR=.git):
      touch .git/git-daemon-export-ok
      git gc
      cd .git
      git --bare update-server-info
      mv .git/hooks/post-update.sample .git/hooks/post-update
      chmod u+x hooks/post-update
      cd ..
      rsync -e ssh -az --delete .git REMOTE_DIRECTORY
  Since this does make some minor changes to the local repository that are
  unnecessary after the rsync command has completed, I might add some code
  to try to clean the .git directory back up.  I doubt any of it will hurt
  if I do not get around to it, though.

  eg publish also will setup the published repository as the new origin (if
  a remote named origin does not already exist), so that future pushes and
  pulls use the published repository.
';
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  my $bypass_modification_check = 0;
  my $result = main::GetOptions(
    "--help"           => sub { $self->help() },
    "bypass-modification-check|b" => \$bypass_modification_check,
    );

  die "Invalid/insufficient args to eg publish: @ARGV\n" if @ARGV != 1;
  $self->{remote_dir} = shift @ARGV;

  if (!$bypass_modification_check) {
    my $status = RepoUtil::commit_push_checks($package_name,
                                              {unknown => 1, changes => 1});
  } else {
    # Record the set of unknown files we ignored with -b, so the -b flag
    # isn't needed next time.
    RepoUtil::record_ignored_unknowns();
  }
}

sub run {
  my $self = shift;

  my $orig_dir = main::getcwd();
  chdir($self->{git_dir});
  print "    >>Running: 'cd $self->{git_dir}'<<\n" if $debug;

  #
  # Warn the user if they have files that may have too restrictive permissions
  #
  my @non_readable_files = `find . ! -perm -004`;
  if (scalar @non_readable_files > 0) {
    print STDERR <<EOF;
WARNING: Some files under $self->{git_dir} are not world readable (see the
chmod(1) manpage).  These permissions will be preserved in the published
copy, so you will need to manually change the permissions of the published
repository if you want them to be world readable (alternatively, you could
modify the permissions of files under $self->{git_dir} and re-run eg publish.)

EOF
  }

  #
  # Setup the repository for rsyncing
  #
  ExecUtil::execute("touch git-daemon-export-ok");
  print "Optimizing local repository and compressing it...\n" if $debug < 2;
  ExecUtil::execute("git gc");
  ExecUtil::execute("git --bare update-server-info");
  if (-f "hooks/post-update.sample") {
    ExecUtil::execute("mv hooks/post-update.sample hooks/post-update");
  }
  ExecUtil::execute("chmod u+x hooks/post-update");
  my $is_bare = ExecUtil::output("git config --get core.bare");
  ExecUtil::execute("git config core.bare true");

  #
  # rsync .git to the publish location
  #
  print "Copy local repository to remote location...\n" if $debug < 2;
  ExecUtil::execute(
    "rsync -e ssh -az --delete --exclude=refs/remotes " .
    "--exclude=COMMIT_EDITMSG --exclude=index --exclude=logs " .
    "--exclude=info/ignored-unknown " .
    "--exclude=ORIG_HEAD --exclude=FETCH_HEAD --exclude=MERGE_HEAD " .
    "./ \"$self->{remote_dir}\"");

  #
  # Undo any temporary changes we did for publishing
  #
  ExecUtil::execute("git config core.bare $is_bare");
  # FIXME: I should clean up git-daemon-export-ok, hooks/post-update, and
  # the files that 'man git-update-server-info' says it creates.

  #
  # Set up the published repository as the default ("origin"), if origin
  # is not already setup.  Otherwise, tell the user how to simplify
  # future pushes/pulls.
  #
  my @output = `git config --get-regexp remote.origin.*`;
  if (@output) { 
    print <<EOF;
NOTE: Not setting up $self->{remote_dir} as your default push/pull location,
since you already have one.  To set up easy pushes and pulls to this location,
run
  eg remote add NICKNAME $self->{remote_dir}
and then do future pushes and pulls with
  eg push NICKNAME
  eg pull NICKNAME
EOF
  } else {
    ExecUtil::execute("git remote add origin $self->{remote_dir}");

    #
    # Set up the configuration variables branch.BRANCH.(remote|merge)
    # for each BRANCH (used later as default push/pull locations)
    #
    my @branches = `git branch`;
    print "    >>Running: 'git branch'<<\n" if $debug;
    foreach my $branch (@branches) {
      chomp($branch);
      $branch =~ s#..##;
      next if $branch eq "HEAD";
      RepoUtil::set_config("branch.$branch.remote", "origin");
      RepoUtil::set_config("branch.$branch.merge",  "refs/heads/$branch");
    }
  }

  chdir($orig_dir);
}

###########################################################################
# pull                                                                    #
###########################################################################
package pull;
@pull::ISA = qw(subcommand);
INIT {
  $command{pull} = {
    section => 'collaboration',
    about => 'Get updates from another repository and merge them'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(@_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg pull [--branch BRANCH] [--no-tags] [--all-tags] [--tag TAG]
          [--no-commit] [--rebase] REPOSITORY

Description:
  Pull changes from another repository and merge them into the local
  repository.  If there are no conflicts, the result will be committed.

  See 'eg help topic remote-urls' for valid syntax for remote repositories.
  If you frequently pull from the same repository, you may want to set up a
  nickname for it (see 'eg help remote'), so that you can specify the
  nickname instead of the full repository URL every time.

  By default, tags in the remote repository associated with commits that
  are pulled, will themselves be pulled.  One can specify to pull
  additional or fewer tags with the --all-tags, --no-tags, or --tag TAG
  options.

  If there is more than one branch (on either end):
    If the local repository has more than one branch, the changes are
    always merged into the active branch (use 'eg info' or 'eg branch' to
    determine the active branch).

    If you do not specify which remote branch to pull, and you have not
    previously pulled a remote branch from the given repository, then eg
    will abort and ask you to specify a remote branch (giving you a list to
    choose from).

  Note for users of named remote repositories and remote tracking branches:
    If you set up named remote repositories (using 'eg remote'), you can
    make 'eg pull' obtain changes from several branches at once.  In such a
    case, eg will take the changes and record them in special local
    branches known as \"remote tracking branches\", a step which involves
    no merging.  Most of these branches will not be handled further after
    this step.  eg will then take changes from just the branch(es)
    specified (with the --branch option, or with the
    branch.CURRENTBRANCH.merge configuration variable, or by the last
    branch(es) merged), and merge it/them into the active branch.

    The advantage of pulling changes from branches that you do not
    immediately merge with is that you can then later inspect, review, or
    merge with such changes (using 'eg merge') even if not connected to the
    network.  Naming the remote repositories also allows you to use the
    shorter name instead of the full location of the repository.  (eg
    remote also provides the ability to update from groups of remote
    repositories simultaneously.)  See 'eg help remote' and 'eg help topic
    storage' for more information about named remote repositories and
    remote tracking branches.

Examples:
  Pull changes from myserver.com:git-stuff/my-repo.git
      \$ eg pull myserver.com:git-stuff/my-repo.git

  Pull changes from the stable branch of git://git.foo.org/whizbang into the
  active local branch
      \$ eg pull --branch stable git://git.foo.org/whizbang

  Pull changes from the debug branch in the remote repository nicknamed
  'carl' (see 'eg help remote' for more information about nicknames for
  remote repositories)
      \$ eg pull --branch debug carl

  Pull changes from a remote repository that has multiple branches
      Hmm, we don't know which branches the remote repository has.  Just
      try it.
      \$ eg pull ssh://machine.fake.gov/~user/hack.git
      That gave us an error telling us it didn't know which branch to pull
      from, but it told us that there were 3 branches: 'master', 'stable',
      and 'nasty-hack'.  Let's get changes from the nasty-hack branch!
      \$ eg pull --branch nasty-hack ssh://machine.fake.gov/~user/hack.git

Options
  --branch BRANCH
    Merge the changes from the remote branch BRANCH.  May be used multiple
    times to merge changes from multiple remote branches at once.

  --no-tags
    Do not download any tags from the remote repository

  --all-tags
    Download all tags from the remote repository.

  --tag TAG
    Download TAG from the remote repository

  --no-commit
    Perform the merge but do not commit even if the merge is clean.

  --rebase
    Instead of a merge, perform a rebase; in other words rewrite commit
    history so that your recent local commits become commits on top of the
    changes downloaded from the remote repository.

    NOTE: This is a potentially _dangerous_ operation.  Rewriting history
    that has been pushed or pulled into another repository can break
    subsequent pushes and pulls with those repositories.  (Such breaks can
    be fixed, at the cost of having to modify the commit history of each
    affected repository.)  Do not use this option without thoroughly
    understanding 'eg help rebase'.
";
  $self->{'differences'} = "
  eg pull and git pull are nearly identical.  eg provides a slightly more
  meaningful name for --tags (\"--all-tags\"), and introduces a new option
  named --branch.  The new option (1) avoids the need to explain refspecs
  too early to users, (2) makes command line examples more
  self-documenting.  eg still accepts refspecs at the end of the
  commandline the same as git pull, however their explanation is deferred
  to 'eg help topic refspecs'.
";
  return $self;
}

#
# FIXME: This function really isn't needed anymore...
#
sub _get_only_branch {
  my $repository = shift;

  if ($debug == 2) {
    print "    >>Running: 'git ls-remote -h $repository'<<\n";
    return;
  }

  # Check if the remote repository has exactly 1 branch...if so, return it,
  # otherwise throw an error
  my ($ret, $output) = 
    ExecUtil::execute_captured("git ls-remote -h $repository",
                               capture_stdout_only => 1);
  die "Could not determine remote branches from repository '$repository'\n"
    if $ret != 0;
  my @remote_refs = split('\n', $output);

  die "'$repository' has no branches to pull!\n" if @remote_refs == 0;
  my @remote_branches = map { m#[0-9a-f]+.*/(.*)$# && $1 } @remote_refs;

  if (@remote_branches > 1) {
    print STDERR <<EOF;
Aborting: It is not clear which remote branch to pull changes from.  Please
retry, specifying which branch(es) you want to be merged into your current
branch.  Existing remote branches of
  $repository
are
  @remote_branches
EOF
    exit 1;
  }

  return $remote_branches[0];
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  RepoUtil::migrate_old_easy_git_pull_push_options();

  #
  # Parse options
  #
  $self->{args} = [];
  my $record_arg  = 
    sub { my $prefix = "";
          $prefix = "no-" if defined $_[1] && $_[1] == 0;
          push(@{$self->{args}}, "--$prefix$_[0]");
        };
  my $record_args  = sub { $_[0] = "--$_[0]"; push(@{$self->{args}}, @_);  };
  my ($no_tags, $all_tags) = (0, 0);
  my @branches;
  my @tags;
  my $result = main::GetOptions(
    "--help"           => sub { $self->help() },
    "--branch=s"       => sub { push(@branches, $_[1]) },
    "--tag=s"          => sub { push(@tags, $_[1]) },
    "--all-tags"       => \$all_tags,
    "--no-tags"        => \$no_tags,
    "commit!"          => sub { &$record_arg(@_) },
    "summary!"         => sub { &$record_arg(@_) },
    "-n"               => sub { &$record_arg(@_) },
    "squash!"          => sub { &$record_arg(@_) },
    "ff!"              => sub { &$record_arg(@_) },
    "strategy=s"       => sub { &$record_args(@_) },
    "s=s"              => sub { &$record_args(@_) },
    "rebase!"          => sub { &$record_arg(@_) },
    "quiet|q"          => sub { &$record_arg(@_) },
    "verbose|v"        => sub { &$record_arg(@_) },
    "append|a"         => sub { &$record_arg(@_) },
    "--upload-pack=s"  => sub { &$record_args(@_) },
    "force|f"          => sub { &$record_arg(@_) },
    "tags"             => \$all_tags,
    "keep|k"           => sub { &$record_arg(@_) },
    "update-head-ok|u" => sub { &$record_arg(@_) },
    "--depth=i"        => sub { &$record_args(@_) },
    );
  die "Cannot specify both --all-tags and --no-tags!\n"
    if $all_tags && $no_tags;
  die "Cannot specify request tags along with --all-tags or --no-tags!\n"
    if @tags && ($all_tags || $no_tags);
  my $repository = shift @ARGV;
  my @git_refspecs = @ARGV;

  # Record the tags or no-tags arguments
  push(@{$self->{args}}, "--tags") if $all_tags;
  push(@{$self->{args}}, "--no-tags") if $no_tags;

  #
  # Get the repository to pull from
  #
  if ($repository) {
    push(@{$self->{args}}, $repository);
  } elsif (!$repository && @branches) {
    $repository = RepoUtil::get_default_push_pull_repository();
    push(@{$self->{args}}, $repository);
  } else {
    # Just drop through to the git pull defaults.
  }

  #
  # Get the branch(es) to pull from
  #
  push(@branches, @git_refspecs);

  if (!@branches && !@tags) {
    my $branch = RepoUtil::current_branch();
    if ($branch) {
      my ($merge_branch, $url);
      if ($repository) {
        $merge_branch = RepoUtil::get_config("remote.$repository.merge");
      } else {
        $merge_branch = RepoUtil::get_config("branch.$branch.merge");
        $url = RepoUtil::get_config("branch.$branch.remote");
      }
      if (!$merge_branch && ($repository || $url)) {
        my $only_branch = _get_only_branch($repository || $url);
        push(@branches, $only_branch);
      }
    }
  }

  foreach my $branch (@branches) {
    push(@{$self->{args}}, $branch);
  }
  foreach my $tag (@tags) {
    push(@{$self->{args}}, ("tag", $tag));
  }
}

sub run {
  my $self = shift;

  @args = $self->quote_args(@{$self->{args}});
  return ExecUtil::execute("git pull @args", ignore_ret => 1);
}

###########################################################################
# push                                                                    #
###########################################################################
package push;
@push::ISA = qw(subcommand);
INIT {
  $command{push} = {
    section => 'collaboration',
    about => 'Push local commits to a published repository'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    initial_commit_error_msg => "Error: No recorded commits to push.",
    @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg push [--bypass-modification-check] [--branch BRANCH] [--tag TAG]
          [--all-branches] [--all-tags] [--mirror] REPOSITORY

Description:
  Push committed changes in the current repository to a published remote
  repository.  The push can fail if the remote repository has commits not
  in the current repository; this can be fixed by pulling and merging
  changes from the remote repository (use eg pull for this) and then
  repeating the push.  Note that for getting changes directly to a fellow
  developer's clone, you should have them use 'eg pull' rather than trying
  to use 'eg push' on your end.

  Branches and tags are typically considered private; thus only the current
  branch will be involved by default (no tags will be sent).  The
  --all-branches, --matching-branches, --all-tags, and --mirror options
  exist to extend the list of changes included.  The --branch and --tag
  options can be used to specifically send different changes.

  See 'eg help topic remote-urls' for valid syntax for remote repositories.

  If you frequently push to the same repository, you may want to set up a
  nickname for it (see 'eg help remote'), so that you can specify the
  nickname instead of the full repository URL every time.

Examples:
  Push commits in the current branch
      \$ eg push myserver.com:git-stuff/my-repo.git

  Push commits in all branches that already exist both locally and remotely
      \$ eg push --matching-branches ssh://web.site/path/to/project.git

  Push commits in all branches, including branches that do no already exist
  remotely, and all tags, to the remote nicknamed 'alice'
      \$ eg push --all-branches --all-tags alice

  Push all local branches and tags and delete anything on the remote end
  that is not in the current repository
      \$ eg push --mirror ssh://jim\@host.xz:22/~jim/project/published

  Create a two new tags locally, then push both
      \$ eg tag MY_PROJECT_1_0
      \$ eg tag USELESS_ALIAS_FOR_1_0
      \$ eg push --tag MY_PROJECT_1_0 --tag USELESS_ALIAS_FOR_1_0

  Push the changes in just the stable branch
      \$ eg push --branch stable 

Options
  --bypass-modification-check, -b
    To prevent you from pushing an incomplete set of changes, push
    typically checks whether you have new unknown files or modified files
    present and aborts if so.  You can bypass these checks with this
    option.

  --branch BRANCH
    Push commits in the specified branch.  May be reused multiple times to
    push commits in multiple branches.

    As an advanced option, one can use the syntax LOCAL:REMOTE for the
    branch.  For example, \"--branch my_bugfix:stable\" would mean to use
    the my_bugfix branch of the current repository to update the stable
    branch of the remote repository.

  --tag TAG
    Push the specified tag to the remote repository.

  --all-branches
    Push commits from all branches, including branches that do not yet exist
    in the remote repository

  --matching-branches
    Push commits from all branches that exist locally and remotely.  Note that
    this option is ignored if specific branches or tags are specified, or the
    --all-branches or --all-tags options.

  --all-tags
    Push all tags to the remote repository.

  --mirror
    Make the remote repository a mirror of the local one.  This turns on
    both --all-branches and --all-tags, but it also means that tags and
    branches that do not exist in the local repository will be deleted from
    the remote repository.
";
  $self->{'differences'} = "
  eg push tries to simplify git, but is essentially the same other than
  defaulting to pushing only the current branch instead of matching
  branches.  eg does provide extra --tag and --branch flags to make command
  lines more self-documenting, and to avoid introducing refspecs (a very
  confusing topic for new users) too early.  However, refspecs still work
  with eg push, and users can learn about them by running 'eg help topic
  refspecs'.

  eg push also avoids pushing into a non-bare repository, by disabling
  such pushes in cases it can detect unless the user specifies both source
  and destination references explicitly (which can be done by running, for
  example, 'eg push origin master:master').
";
  return $self;
}

sub _get_push_repository {
  my ($repository) = @_;

  if (defined $repository) {
    return RepoUtil::get_config("remote.$repository.url") || $repository;
  } else {
    return RepoUtil::get_config("remote.origin.url")
  }
}

# _check_if_bare: Return whether the given repository is bare.  Returns
# undef the repository doesn't specify a valid repository or the repository
# is not of a type where we can determine bare-ness.  Otherwise returns
# either the string "true" or "false".
sub _check_if_bare {
  my $repository = shift;

  # Don't know how to check rsync, http, https, or git repositories to see
  # if they are bare.
  return undef if $repository =~ m#^(rsync|http|https|git)://#;

  #
  # Check local directories
  #
  if ($repository =~ m#^file://(.*)#) {
    $repository = $1;
  }
  if (-d $repository) {
    my $orig_dir = main::getcwd();
    chdir($repository);

    my ($ret, $output) = 
      ExecUtil::execute_captured("git rev-parse --is-bare-repository",
                                 ignore_ret => 1);

    chdir($orig_dir);
    return undef if $ret != 0;
    chomp($output);
    return $output;
  }

  #
  # Check ssh systems
  #
  my ($machine, $path);
  if ($repository =~ m#^ssh://((?:.*?@)?)([^/:]*)(?::[0-9]+)?(.*)$#) {
    $user = $1;
    $machine = $2;
    $path = $3;
    $path =~ s#^/~#~#;  # Change leading /~ into plain ~
  } elsif ($repository =~ m#^((?:.*?@)?)([^:]*):(.*)$#) {
    $user = $1;
    $machine = $2;
    $path = $3;
  }
  return undef if !defined $machine || !defined $path;

  my ($ret, $output) = 
    ExecUtil::execute_captured(
      "ssh $user$machine 'cd $path && git rev-parse --is-bare-repository'",
      ignore_ret => 1);
  return undef if $ret != 0;
  chomp($output);
  return $output;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  RepoUtil::migrate_old_easy_git_pull_push_options();

  #
  # Parse options
  #
  $self->{args} = [];
  my $record_arg   = sub { push(@{$self->{args}}, "--$_[0]"); };
  my $record_args  = sub { $_[0] = "--$_[0]"; push(@{$self->{args}}, @_);  };
  my ($all_branches, $matching_branches, $all_tags, $mirror) = (0, 0, 0, 0);
  my ($thin, $repo) = (0, 0);
  my @branches;
  my @tags;
  my $bypass_modification_check = 0;
  my $result = main::GetOptions(
    "--help"              => sub { $self->help() },
    "--branch=s"          => sub { push(@branches, $_[1]) },
    "--tag=s"             => sub { push(@tags, $_[1]) },
    "--all-branches"      => \$all_branches,
    "--matching-branches" => \$matching_branches,
    "--all-tags"          => \$all_tags,
    "--mirror"            => \$mirror,
    "--dry-run"           => sub { &$record_arg(@_) },
    "--receive-pack=s"    => sub { &$record_args(@_) },
    "force|f"             => sub { &$record_arg(@_) },
    "repo=s"              => \$repo,
    "thin"                => sub { &$record_arg(@_) },
    "no-thin"             => sub { &$record_arg(@_) },
    "verbose|v"           => sub { &$record_arg(@_) },
    "bypass-modification-check|b" => \$bypass_modification_check,
    );
  die "Cannot specify individual branches and request all branches too!\n"
    if @branches && ($all_branches || $mirror);
  die "Cannot specify individual tags and request all tags too!\n"
    if @tags && ($all_tags || $mirror);
  my $repository = shift @ARGV;
  my @git_refspecs = @ARGV;

  if (!$bypass_modification_check) {
    my $status = RepoUtil::commit_push_checks($package_name,
                                              {unknown => 1, changes => 1});
  } else {
    # Record the set of unknown files we ignored with -b, so the -b flag
    # isn't needed next time.
    RepoUtil::record_ignored_unknowns();
  }

  push(@{$self->{args}}, "--all")    if $all_branches;
  push(@{$self->{args}}, "--tags")   if $all_tags;
  push(@{$self->{args}}, "--mirror") if $mirror;

  #
  # Get the repository to pull from
  #
  my $remote;
  if ($repository) {
    push(@{$self->{args}}, $repository);
  } elsif (!$repository && (@branches || @tags)) {
    $repository = RepoUtil::get_default_push_pull_repository();
    push(@{$self->{args}}, $repository);
    $remote = $repository;
  } else {
    # Just drop through to the git pull defaults.
  }

  #
  # Prevent pushing to a non-bare repository (on local filesystem or over
  # ssh; I don't know how to detect other cases)...unless user explicitly
  # specifies both source and destination references explicitly
  #
  $repository = _get_push_repository($repository);
  my $push_to_non_bare_repo;
  if ($repository) {

    # If the user uses a refspec including a colon character, assume
    # they know what they are doing and skip the non-bare check
    if (! grep {$_ =~ /:/} @git_refspecs) {

      # Check if we have already determined this repository to be bare
      my $is_bare;
      $is_bare = RepoUtil::get_config("remote.$remote.bare") if $remote;
      if (defined $is_bare) {
        $push_to_non_bare_repo = ($is_bare eq "false");
      } else {
        $is_bare = _check_if_bare($repository);
        if (defined $is_bare && defined $remote) {
          RepoUtil::set_config("remote.$remote.bare", $is_bare);
        }
        $push_to_non_bare_repo = (defined $is_bare && $is_bare eq "false");
      }
    }
  }
  # Throw an error if the user is trying to push to a bare repository
  # (and not using a refspec with a colon character)
  if ($push_to_non_bare_repo) {
    print STDERR <<EOF;
Aborting: You are trying to push to a repository with an associated working
copy, which will leave its working copy out of sync with its repository.
Rather than pushing changes to that repository, you should go to where that
repository is located and pull changes into it (using eg pull).  If you
know what you are doing and know how to deal with the consequences, you can
override this check by explicitly specifying source and destination
references, e.g.
  eg push REMOTE BRANCH:REMOTE_BRANCH
Please refer to
  eg help topic refspecs
to learn what this syntax means and what the consequences of overriding this
check are.
EOF
    exit 1;
  }

  #
  # Get the branch(es) to push
  #
  push(@branches, @git_refspecs);
  push(@{$self->{args}}, @branches);
  foreach my $tag (@tags) {
    push(@{$self->{args}}, ("tag", $tag));
  }
}

sub run {
  my $self = shift;

  @args = $self->quote_args(@{$self->{args}});
  return ExecUtil::execute("git push @args", ignore_ret => 1);
}

###########################################################################
# rebase                                                                  #
###########################################################################
package rebase;
@rebase::ISA = qw(subcommand);
INIT {
  $command{rebase} = {
    extra => 1,
    section => 'timesavers',
    about => "Port local commits, making them be based on a different\n" .
             "                repository version"
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    initial_commit_error_msg => "Error: No recorded commits to rewrite.",
    @_);
  bless($self, $class);
  #
  # Note: Parts of help were taken from the git-rebase manpage, which
  # was also available under GPLv2.
  #
  $self->{'help'} = "
Usage:
  eg rebase [-i | --interactive] [ --since SINCE ] [ --onto ONTO ]
            [ --against AGAINST ] [BRANCH_TO_REBASE]
  eg rebase [ --continue | --skip | --abort ]

Description:
  Rewrites commits on a branch, making them be based on a different
  repository version.  Technically, the old commits are not overwritten or
  deleted (only new ones are written), meaning that other branches sharing
  the same commits will be unaffected and users can undo a rebase (until
  the unused commits are cleaned up after a few weeks).

  WARNING:
    Rebasing commits in a branch is an advanced operation which changes
    history in a way that will cause problems for anyone who already has a
    copy of the branch in their repository when they try to pull updates
    from you.  This may cause them to experience many conflicts in their
    merges and require them to resolve those conflicts manually, or rewrite
    their own history, or even toss out their changes and simply accept
    your version.  (The last of those options is common enough that there
    is a special method of pulling and pushing changes in such cases; see
    'eg help topic refspecs' for more details.)

  Non-interactive rebase (running without the --interactive or -i flags):
    Specifying which commits to rewrite and what to rewrite them relative
    to involves specifying up to three branches or revisions: SINCE, ONTO,
    and BRANCH_TO_REBASE.  eg will take all commits in the BRANCH_TO_REBASE
    branch that are not in the SINCE branch, and record them as commits on
    top of the tip of the ONTO branch.  The ONTO and SINCE branches are not
    changed by this operation.  The BRANCH_TO_REBASE branch is changed to
    record the tip of the newly written branch.

    See also the \"If a conflict occurs\" section below.

  Interactive rebase (running with the --interactive or -i flag):
    Interactive rebasing allows you a chance to edit the commits which are
    rebased, including
      * reordering commits
      * removing commits
      * combining multiple commits into one commit
      * amending commits to include different changes or log messages
      * splitting one commit into multiple commits
    When running interactively, eg rebase will begin by making a list of
    the commits which are about to be rebased and allow you to change the
    the list before rebasing.  The list will include one commit per line,
    allowing you to
      * reorder commits by reordering lines
      * removing commits by removing lines
      * combining multiple commits into one, by changing 'pick' to 'squash'
        at the beginning of each line of the commits you want combined
        *except* the first
      * amend a commit by changing the 'pick' at the beginning of the line
        of the relevant commit to 'edit'.  This will make eg rebase stop
        after applying that commit, allowing you to make changes and run
        'eg commit --amend' followed by 'eg rebase --continue'.
      * split one commit into multiple commits by changing 'pick' at the
        beginning of the line of the relevant commit to 'edit'.  This will
        make eg rebase stop *after* applying that commit, allowing you to
        manually undo that commit while keeping the changes in the working
        copy (with 'eg reset HEAD~1') and then make multiple commits (with
        'eg commit') before running 'eg rebase --continue'.  Note that eg
        stash may come in handy for testing the split commits.

  If a conflict occurs:
    Rebase will stop at the first problematic commit and leave conflict
    markers (<<<<<<) in the tree.  You can use eg status and eg diff to
    find the problematic files and locations.  Once you edit the files to
    fix the conflicts, you can run
      eg resolved FILE
    to mark the conflicts in FILE as resolved.  Once you have resolved all
    conflicts, you can run
      eg rebase --continue
    If you simply want to skip the problematic patch (and end up with one
    less commit), you can instead run
      eg rebase --skip
    Alternatively, to abort the rebase and return to your previous state,
    you can run
      eg rebase --abort

Examples:
  Take a branch named topic that was split off of the master branch, and
  update it to be based on the new tip of master.
      \$ eg rebase --since master --onto master topic
    Pictorally, this changes:
                 A---B---C topic
                /
           D---E---F---G master
    into
                         A'--B'--C' topic
                        /
           D---E---F---G master

  Same as the the above example, with less typing
      \$ eg rebase --against master topic

  Same as the last two examples, assuming topic is the current branch
      \$ eg rebase --against master

  Take a branch named topic that is based off of a branch named next, which
  is in turn based off master, and rewrite topic so that it appears to be
  based off the most recent version of master.
      \$ eg rebase --since next --onto master topic
    Pictorally, this changes
           o---o---o---o---o  master
                \\
                 o---o---o---o---o  next
                                  \\
                                   o---o---o  topic
    into
           o---o---o---o---o  master
               |            \\
               |             o'--o'--o'  topic
                \\
                 o---o---o---o---o  next

  Take just the last two commits of the current branch, and rewrite them
  to be relative to the commit just before the most recent on the master
  branch.
      \$ eg rebase --since current~2 --onto master~1 current
    Pictorally, this changes:
                    A---B---C---D---E  current
                   /
           F---G---H---I---J---K master
    into
                            D'---E' current
                           /
           F---G---H---I---J---K master

  Reorder the last two commits on the current branch
      \$ eg rebase --interactive --since HEAD~2
  (Then edit the file you are presented with and change the order of the
  two lines beginning with 'pick')
    Pictorally, this changes:
           A---B---C---D---E---F master
    into
           A---B---C---D---F'---E' master

Options:
  --since SINCE
    Upstream branch to compare against; only commits not found in this
    branch will be rebased.  Note that if --onto is not specified, the
    value of SINCE will be used for that as well.

    The value of SINCE is not restricted to existing branch names; any
    valid revision can be used (due to the fact that all revisions know
    their parents and a revision plus its ancestors can define a branch).

  --onto ONTO
    Starting point at which to create the new commits.  If the --onto
    option is not specified, the starting point is whatever is provided by
    the --since option.  Any valid revision can be used for the value of
    ONTO.

  --against AGAINST
    An alias for --since AGAINST, provided to make command lines clearer
    when the --onto flag is not also used.  (Typically, --against is used
    if --onto is not, and --since is used if --onto is, but --against and
    --since can be used interchangably.)

  --interactive, -i
    Make a list of the revisions which are about to be rebased and let the
    user edit that list before rebasing.  Can be used to split, combine,
    remove, insert, reorder, or edit commits.

  --continue
    Restart the rebasing process after resovling a conflict

  --skip
    Restart the rebasing process by skipping the current patch (resulting
    in a rewritten history with one less commit).

  --abort
    Abort the stopped rebase operation and restore the original branch
";
  $self->{'differences'} = "
  The only differences between eg rebase and git rebase are cosmetic;
  further, eg rebase accepts all options and flags that git rebase accepts.

  eg adds the identically behaved flags --since and --against in
  preference to using the position of the branch/revision name on the
  command line.  Note that
    git rebase master
  is somewhat confusing in that it isn't rebasing master but the current
  branch.  To make this clearer, eg allows (and encourages) the form
    eg rebase --against master
  where --against has the same meaning as --since, but is clearer in cases
  where the --onto flag is not also used.
";
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  #
  # Parse options
  #
  $self->{args} = [];
  my $record_arg   = sub { push(@{$self->{args}}, "--$_[0]"); };
  my $record_args  = sub { $_[0] = "--$_[0]"; push(@{$self->{args}}, @_);  };
  my $since;
  my $result = main::GetOptions(
    "--help"              => sub { $self->help() },
    "interactive|i"       => sub { &$record_arg(@_) },
    "verbose|v"           => sub { &$record_arg(@_) },
    "merge|m"             => sub { &$record_arg(@_) },
    "C=i"                 => sub { &$record_args(@_) },
    "whitespace=s"        => sub { push(@{$self->{args}},"--whitespace=$_[1]") },
    "preserve-merges|p"   => sub { &$record_arg(@_) },
    "onto=s"              => sub { &$record_args(@_) },
    "against=s"           => sub { $since=$_[1] },
    "since=s"             => sub { $since=$_[1] },
    "continue"            => sub { &$record_arg(@_) },
    "skip"                => sub { &$record_arg(@_) },
    "abort"               => sub { &$record_arg(@_) },
    );
  die "Too many branches/revisions specified\n"
    if @ARGV > 1 && defined $since;
  push(@{$self->{args}}, $since) if defined $since;
  push(@{$self->{args}}, @ARGV);
}

sub run {
  my $self = shift;

  @args = $self->quote_args(@{$self->{args}});
  return ExecUtil::execute("git rebase @args", ignore_ret => 1);
}

###########################################################################
# remote                                                                  #
###########################################################################
package remote;
@remote::ISA = qw(subcommand);
INIT {
  $command{remote} = {
    unmodified_behavior => 1,
    extra => 1,
    section => 'collaboration',
    about => 'Manage named remote repositories',
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg remote
  eg remote add REMOTENAME URL
  eg remote rm REMOTENAME
  eg remote update GROUPNAME

Description:
  eg remote is a convenience utility to make it easy to track changes from
  multiple remote repositories.  It is used to
    1) Set up
         REMOTENAME -> URL
       aliases that can be used in the place of full urls to simplify
       commands such as push or pull
    2) Pulling updates from multiple branches of a remote repository at
       once and storing them in remote tracking branches (which differ from
       normal branches only in that they have a prefix of REMOTENAME/ in
       their name).
    3) Pulling updates from multiple branches of multiple remote
       repositories at once, storing them all in remote tracking branches.

Examples:
  The examples section is split into three categories:
    1) Managing which remotes exist:
    2) Using one or more existing remotes
    3) Using remote tracking branches created through usage of remotes

  Category 1: Managing which remotes exist:

    List which removes exist
      \$ eg remote
    or, list remotes and their urls (among other things)
      \$ eg info

    Add a new remote for the url ssh://some.machine.org//path/to/repo.git,
    giving it the name jim
      \$ eg remote add jim ssh://some.machine.org//path/to/repo.git

    Add a new remote for the url git://composit.org//location/eyecandy.git,
    giving it the name bling
      \$ eg remote add bling git://composit.org//location/eyecandy.git

    Delete the remote named bob, and remove all related remote tracking
    branches (i.e. those branches whose names begin with \"bob/\"), as well
    as any associated configuration settings
      \$ eg remote rm bob
    
  Category 2: Using one or more existing remotes

    Pull updates for all branches of the remote jill, storing each in a
    remote tracking branch of the local repository named jill/BRANCH.
      \$ eg fetch jill

    Pull changes from the magic branch of the remote merlin and merge it
    into the current branch (i.e. standard pull behavior) AND also update
    all remote tracking branches associated with the remote (i.e. act as if
    'eg fetch merlin' was also run)
      \$ eg pull --branch magic merlin

    Grab updates from all remotes, i.e. run 'eg fetch REMOTE' for each
    remote.
      \$ eg remote update
    (Technically, some remotes could be manually configured to be excluded
    from this update.)

    Grab updates from all remotes in the group named friends (created by
    use of 'eg config remotes.friends \"REMOTE1 REMOTE2...\"'), i.e. run
    'eg fetch REMOTE' for each remote in the friends group
      \$ eg remote update friends

  Category 3: Using remote tracking branches created through usage of remotes

    List all remote tracking branches
      \$ eg branch -r

    Merge the remote tracking branch jill/stable into the current branch
      \$ eg merge jill/stable

    Get a history of the changes on the bling/explode branch
      \$ eg log bling/explode

    Create a new branch named my-testing based off of the remote tracking
    branch jenny/testing
      \$ eg branch my-testing jenny/testing
";
  return $self;
}

###########################################################################
# reset                                                                   #
###########################################################################
package reset;
@reset::ISA = qw(subcommand);
INIT {
  $command{reset} = {
    extra => 1,
    section => 'modification',
    about => 'Forget local commits and (optionally) undo their changes'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(@_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg reset [--working-copy | --no-unstaging] [REVISION]

Description:
  Forgets local commits for the active branch and (optionally) undoes their
  changes in the working copy.  If you have staged changes (changes you
  explictly marked as ready for commit) this function also unstages them by
  default.  See 'eg help topic staging' to learn about the staging area.

  From a computer science point of view, eg reset moves the current branch
  tip to point at an older commit, and also optionally changes the working
  copy and staging area to match the version of the repository recorded in
  the older commit.

  Note that this function should be used with caution; it is often used to
  discard unwanted data or to modify recent local \"history\" of commits.
  You want to be careful to not also discard wanted data, and modifying
  history is a bad idea if someone has already obtained a copy of that
  local history from you (rewriting history makes merging and updating
  problematic).

Examples:
  Throw away all changes since the last commit
      \$ eg reset --working-copy HEAD
  Note that HEAD always refers to the current branch, and the current
  branch always refers to its last commit.

  Throw away the last three commits and all current changes (this is a bad
  idea if someone has gotten a copy of these commits from you; this should
  only be done for truly local changes that you no longer want).
      \$ eg reset --working-copy HEAD~3

  Unrecord the last two commits, but keep the changes corresponding to these
  commits in the working copy.  (This can be used to fix a set of \"broken\"
  commits.)
      \$ eg reset HEAD~2

  While working on the \"stable\" branch, you decide that the last 5 commits
  should have been part of a separate branch.  Here's how you retroactively
  make it so:
      Verify that your working copy is clean...then
      \$ eg branch difficult_bugfix
      \$ eg reset --working-copy HEAD~5
      \$ eg switch difficult_bugfix
  The first step creates a new branch that initially could be considered an
  alias for the stable branch, but does not switch to it.  The second step
  moves the stable branch tip back 5 commits and modifies the working copy
  to match.  The last step switches to the difficult_bugfix branch, which
  updates the working copy with the contents of that branch.  Thus, in the
  end, the working copy will have the same contents as before you executed
  these three steps (unless you had local changes when you started, in
  which case those local changes will be gone).

  Stage files (mark changes in them as good and ready for commit but
  without yet committing them), then change your mind and unstage all
  files.
      \$ eg stage foo.c bla.h
      \$ eg reset HEAD
  Note that using HEAD as the commit means to forget all commits since HEAD
  (always an empty set) and undo any staged changes since that commit.

Options:
  --working-copy
    Also make the working tree match the version of the repository recorded
    in the specified commit.  If this option is not present, the working
    copy will not be modified.

  --no-unstaging
    Do not modify the staging area; only change the current branch tip to
    point to the older commit.

  REVISION
    A reference to a recorded version of the repository, defaulting to HEAD
    (meaning the most recent commit on the current branch).  See 'eg help
    topic revisions' for more details.

";
  $self->{'differences'} = '
  The only differences between eg reset and git reset are cosmetic;
  further, eg reset accepts all options and flags that git reset accepts.

  git reset uses option names of --soft, --mixed, and --hard.  While eg
  reset will accept these option names for compatibility, it provides
  alternative names that are more meaningful:
    --working-copy     <=> --hard
    --no-unstaging     <=> --soft
  There is no alternate name for --mixed, since it is the default and thus
  does not need to appear on the command line at all.

  The modified revert command of eg is encouraged for reverting specific
  files, though eg reset has the same file-specific reverting that git
  reset does.
';
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  #
  # Parse options
  #
  my ($hard, $soft) = (0, 0);
  my $result = main::GetOptions(
    "--help"         => sub { $self->help() },
    "--working-copy" => \$hard,
    "--no-unstaging" => \$soft,
    );
  die "Cannot specify both --working-copy and --no-unstaging!\n"
    if $hard && $soft;
  unshift(@ARGV, "--hard") if $hard;
  unshift(@ARGV, "--soft") if $soft;
}

###########################################################################
# resolved                                                                #
###########################################################################
package resolved;
@resolved::ISA = qw(subcommand);
INIT {
  $command{resolved} = {
    new_command => 1,
    extra => 1,
    section => 'compatibility',
    about => 'Declare conflicts resolved and mark file as ready for commit'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(git_equivalent => 'add', @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg resolved PATH...

Description:
  Declare conflicts resolved for the specified paths, and mark contents of
  those files as ready for commit.

Examples
  After fixing any update or merge conflicts in foo.c, declare the fixing to
  be done and the contents ready to commit.
      \$ eg resolved foo.c
";
  $self->{'differences'} = '
  eg resolved is a command new to eg that is not part of git; however, it
  simply calls git add.
';
  return $self;
}

sub run {
  my $self = shift;
  my $package_name = ref($self);

  @ARGV = $self->quote_args(@ARGV);
  return ExecUtil::execute("git add @ARGV", ignore_ret => 1);
}

###########################################################################
# revert                                                                  #
###########################################################################
package revert;
@revert::ISA = qw(subcommand);
INIT {
  $command{revert} = {
    extra => 1,
    section => 'modification',
    about => 'Revert local changes and/or changes from previous commits'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(git_equivalent => '', @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg revert [-m PARENT_NUMBER] [--staged | --unstaged]
            [--in | --since] [REVISION] [--] [PATH...]

Description:
  (Note: If you want to check out an earlier revision, use the switch
  command; revert does not change the parent of the working directory.  If
  you want to undo commits, use either (1) the reset command to set the
  branch tip to a previous revision (i.e. to discard commits from history),
  or (2) the cherry-pick command with the -R option to reverse apply a
  previous commit on top of the current state and record the new result;
  revert does not modify the branch tip.)

  eg revert undoes previous changes in your working directory, including:
  restoring deleted files to a previously recorded version, removing
  recorded conflict states, undoing prior adds or stages, and discarding
  local modifications.  eg revert can optionally also immediately make a
  commit after the reversion is performed (by default, no commit is
  performed).  This command has many options for exactly what to revert,
  and it may be useful to skip to the examples section below and then come
  back and read the description.

  This command has the ability to either revert changes *since* a given
  commit, or to revert the changes *in* a given commit.  When a commit is
  specified, either the --since or --in flags must also be specified to
  make it clear which behavior is desired.  If no commit is specified and
  neither --since nor --in is provided, the default is to assume you want
  to undo changes since the last commit.

  Finally, revert can operate on a subset of paths if specified.  When a
  directory path is specified, all changes under the given directory will
  be reverted.

  To avoid accidental loss of local changes, nothing will be done when no
  arguments are specified.  (However, you will be given a helpful message
  suggesting commands that you might want to run; this message detects a
  variety of situations and prompts you accordingly.)

  (Advanced usage notes)
    By default, changes are reverted in both the working copy and in the
    staging area (i.e. the area tracking content explicitly marked by you
    as ready to be committed; see 'eg help topic staging' for more
    details).  One can limit the reversion of changes to just the working
    copy (using the --unstaged flag), or to just the staging area (using
    the --staged flag).  Note that, in addition to reverting changes to the
    working copy since a given revision (with the --since REVISION flag),
    you can also revert changes to the working copy relative to the staging
    area (by specifying --unstaged without passing the --since flag).

    When reverting the changes made *in* a merge commit, the revert command
    needs to know which parent of the merge the revert should be relative to.
    This can be specified using the -m option.

Examples:
  Undo changes since the last commit on the current branch to bar.h and
  foo.c.  This can be done with either of the following methods:
      \$ eg revert bar.h foo.c                      # Method #1
      \$ eg revert --since HEAD bar.h foo.c         # Method #2, more explicit

  While on the bling branch, revert the changes in the last 3 commits (as
  well as any local changes).  This can be done by:
      \$ eg revert --since bling~3

  While on the stable branch, you determine that the seventh commit prior
  to the most recent was faulty and you simply want to undo it.  This can
  be accomplished by:
      \$ eg revert --in stable~7

  You decide that all changes to foobar.cpp in your working copy and in the
  last 2 commits are bad and want to revert them.  This is done by:
  of:
      \$ eg revert --since HEAD~2 -- foobar.c

  You decide that some of the changes in the merge commit HEAD~4 are bad.
  You would like to revert the changes to baz.py in HEAD~4 relative to its
  second parent.  This can be accomplished as follows:
      \$ eg revert -m 2 --in HEAD~4 baz.py
  
  (Advanced) Undo a previous stage, marking changes in foo.c as not
  being ready for commit:
      \$ eg revert --staged foo.c

  (Advanced) You decide that the changes to abracadabra.xml made in commit
  HEAD~8 are bad.  You want to revert those changes in the version of
  abracadabra.xml but only to your working copy.  This is done by:
      \$ eg revert --unstaged --in HEAD~8 -- abracadabra.xml

Options:
  --since
    Revert the changes made since the specified commit, including any local
    changes.  This takes the difference between the specified commit and
    the current version of the files and reverses these changes.

  --in
    Revert the changes made in the specified commit.  This takes the
    difference between the parent of the specified commit and the specified
    commit and reverse applies it.

  REVISION
    A reference to a recorded version of the repository, defaulting to HEAD
    (meaning the most recent commit on the current branch).  See 'eg help
    topic revisions' for more details.

  -m PARENT_NUMBER
    When reverting the changes made in a merge commit, the revert command
    needs to know which parent of the merge the revert should be relative
    to.  Use this flag with the parent number (1, 2, 3...) to specify which
    parent commit to revert relative to.

    Can only be used with the --in option.

  --staged
    Make changes only to the staged (explicitly marked as ready to be
    committed) version of files.

  --unstaged
    Make changes only to the unstaged version of files, i.e. only to the
    working copy.

  --
    This option can be used to separate command-line options and commits
    from the list of files, (useful when filenames might be mistaken for
    command-line options or be mistaken as a branch or tag name).

  PATH...
    One or more files or directories.  The changes reverted will be limited
    to the listed files or files below the listed directories.
";
  $self->{'differences'} = '
  eg revert is similar to the revert command of svn, hg, bzr, or darcs.  It
  is not provided by any one git command; it overlaps with about five
  different git commands in specific cases.  git users wanting the
  functionality in eg revert will typically be guided by expert git users
  towards whichever git command seems like the most natural fit for the
  particular case the user asks about.  Quite often, such users will
  continue using the command they are given for subsequent situations...and
  will often stumble across multiple cases where the git command no longer
  matches the wanted revert behavior.

  git does provide a command called revert, which is a subset of the
  behavior of eg cherry-pick:
    git revert COMMIT
  is the same as
    eg cherry-pick -R COMMIT
  which is, modulo the automatic commit message provided by git revert, the
  same as
    eg revert --in COMMIT && eg commit
  Note that while eg revert --in may look similar to git revert, the former
  is about undoing changes in just the working copy, is typically
  restricted to a specific subset of files, and is usually just one change
  of many towards testing or creating something new to be committed.  The
  latter is always concerned with reverse applying an entire commit, and is
  almost always used to immediately record that change.

  Note that git revert commands are invalid syntax in eg (since eg revert
  always requires the --since or --in flags to be specified whenever a
  commit is).  This means that eg can catch such cases and notify git
  users to adopt the eg cherry-pick -R command.

  Due to these changes, eg revert should be much more welcoming to users of
  svn, hg, bzr, or darcs.  It also provides a simple discovery mechanism
  for existing git users to allow them to easily work with eg.
  Additionally, these changes also make the reset and checkout/switch
  subcommands of eg easier to understand by limiting their scope instead of
  each having two very different capabilities.  (Technically, eg reset and
  eg checkout still have those capabilities for backwards compatibility, I
  just omit them in the documentation.)

  It seems that perhaps eg revert could be extended further, to accept
  things like
      \$ eg revert --in HEAD~8..HEAD~5
  to allow reverting changes made in a range of commits.  The --in could
  even be optional in such a case, since the range makes it clear what is
  wanted.
';
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  my ($cur_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();
  my $initial_commit = RepoUtil::initial_commit();

  # Parsing opts
  my ($staged, $unstaged, $in) = (0, 0, -1);
  my $m;
  my $rev;
  my $result = main::GetOptions(
    "--help"         => sub { $self->help() },
    "-m=i"           => \$m,
    "--staged"       => \$staged,
    "--unstaged"     => \$unstaged,
    "--in=s"         => sub { $in = 1; $rev = $_[1]; },
    "--since=s"      => sub { $in = 0; $rev = $_[1]; },
    );

  # Parsing revs and files
  my ($opts, $revs, $files) = RepoUtil::parse_args(@ARGV);
  unshift(@$revs, $rev) if defined($rev);

  # Determining whether there are modified or unmerged files
  my $files_modified = RepoUtil::files_modified();
  my @quoted_files;
  if (@$files) {
    @quoted_files = $self->quote_args(@$files);
  } else {
    push(@quoted_files, $top_dir);
  }
  my @unmerged_files = `git ls-files --full-name -u -- @quoted_files`;
  @unmerged_files = map { m/.*[ ]+(.*)/ && $1 } @unmerged_files;
  @unmerged_files = Util::uniquify_list(@unmerged_files);

  #
  # Big ol' safety checks and warnings
  #
  if (!@$revs && !@$files) {
    if (-f "$self->{git_dir}/MERGE_HEAD") {
      print STDERR<<EOF;
Aborting: no revisions or files specified to revert.  If you want to abort
your incomplete merge, try 'eg revert --since HEAD' (or, alternatively,
'eg reset --working-copy HEAD').
EOF
      exit 1;
    }
    elsif (-d "$self->{git_dir}/rebase-merge" ||
           -d "$self->{git_dir}/rebase-apply") {
      print STDERR<<EOF;
Aborting: no revisions or files specified to revert.  If you want to abort
your incomplete rebase, try:
  eg rebase --abort
EOF
      exit 1;
    }
    elsif (!$files_modified && !$initial_commit) {
      my $active_branch = RepoUtil::current_branch() || 'HEAD';
      print STDERR<<EOF;
There are no local changes to revert and you specified no revisions to revert
(or revert back to).  Please specify a revision with --in or --since.
Alternatively, if you want to modify commits instead of just the working copy
then use reset instead of revert:

If you want to undo a rebase or a merge (including a pull or update), try:
  eg reset --working-copy ORIG_HEAD
If you want to undo the last commit (but keep its changes in the working copy),
try:
  eg reset $active_branch~1
If you just want to amend the last commit without undoing it, make the
additional changes you want and run:
  eg commit --amend
If you want to undo previous reset commands, get the appropriate reflog
reference from eg reflog (for example, using HEAD\@{1} for <REF>) and run:
  eg reset --working-copy <REF>
EOF
      exit 1;
    }
    elsif (!$initial_commit) {
      print STDERR<<EOF;
Aborting: no revisions or files specified.  If you want to revert and lose
all changes since the last commit, try adding the arguments
  --since HEAD
to the end of your command.
EOF
      exit 1;
    } else {
      print STDERR<<EOF;
Aborting: no files specified.
EOF
      exit 1;
    }
  }

  if (!@$revs && -f "$self->{git_dir}/MERGE_HEAD") {
    my @merge_branches = RepoUtil::merge_branches();
    my $list = join(", ", @merge_branches);
    print STDERR <<EOF;
Aborting: Cannot revert the changes since the last commit, since you are in
the middle of a merge and there are multiple last commits.  Please add
  --since BRANCH
to your flags to eg revert, where BRANCH is one of
  $list
If you simply want to abort your merge and undo its conflicts, run
  eg revert --since HEAD
EOF
    exit 1;
  }

  # Sanity checks
  die "Cannot specify -m without specifying --in.\n" if !$in && defined($m);
  die "Can only specify one revision\n" if @$revs > 1;
  die "No revision specified after --in\n"    if ($in == 1 && !@$revs);
  die "No revision specified after --since\n" if ($in == 0 && !@$revs);
  if ($in == -1 && @$revs) {
    die "You must specify either --in or --since when specifying a revision.\n".
        "(git users:) If you are used to git revert; try running\n".
        "  eg cherry-pick -R @ARGV\n";
  }
  die "Unrecognized options: @$opts\n" if @$opts;
  $in = 0 if $in == -1;
  if (!$staged && !$unstaged) {
    $staged = 1;
    $unstaged = 1;
  }

  if ($initial_commit) {
    die "Cannot revert a previous commit since there are no previous " .
      "commits.\n" if $in;
    die "Cannot revert to a previous commit since there are no previous " .
        "commits.\n" if !$in && (@$revs || !$staged);
  }

  if (@unmerged_files && $in) {
    die "Aborting: please clear conflicts from @unmerged_files before " .
        "proceeding.\n";
  }

  # Record needed information
  $self->{staged} = $staged;
  $self->{unstaged} = $unstaged;
  $self->{just_recent_unstaged} = !$in && !$staged && !@$revs;
  $self->{in} = $in;
  $self->{revs} = "@$revs";
  $self->{revs} = "HEAD" if !@$revs;
  $self->{initial_commit} = $initial_commit;
  if ($in) {
    # Get the revision whose changes we want to revert, and its parents
    Util::push_debug(new_value => 0);
    my $links = ExecUtil::output(
                  "git rev-list --parents --max-count=1 $self->{revs}");
    Util::pop_debug();
    my @list = split(' ', $links);  # commit id + parent ids

    # Get a symbolic name for the parent revision we will diff against
    my $first_rev = $self->{revs};
    my $parent = $m || 1;
    $first_rev .= "^$parent";

    # Reverting changes in merge commits can only be done against one parent
    die "Cannot revert a merge commit without specifying a parent!\n"
      if !defined($m) && @list > 2;

    # Reverting relative to a parent can only be done with existing parents
    if ($parent + 1 > scalar(@list)) {
      die "Cannot revert the changes made in a commit that has no prior " .
        "commit\n" if !defined($m);
      die "The specified commit does not have $m parents; try a lower " .
        "value for -m\n" if defined($m);
    }

    # The combination of revs to diff between
    $self->{revs} = "$first_rev $self->{revs}";
  }

  # reroot files relative to top of repo
  my @rerooted_files = 
    Util::reroot_paths__from_to_files($cur_dir, $top_dir, @$files);
  $self->{files} = \@rerooted_files;

  # Determine some other stuff needed 
  my ($new_files, $newish_files, $revert_files);
  my ($staged_info, $old_staged_info);
  if (!$in && !$initial_commit) {
    my $revision = (@$revs) ? $revs->[0] : "HEAD";
    ($new_files, $newish_files, $revert_files, $staged_info, $old_staged_info) =
       RepoUtil::get_revert_info($revision, @quoted_files);
  } elsif ($initial_commit) {
    $new_files = \@rerooted_files;
    $newish_files = [];
    $revert_files = [];
  }
  $self->{new_files} = $new_files;
  $self->{newish_files} = $newish_files;
  $self->{revert_files} = $revert_files;
  $self->{staged_info} = $staged_info;
  $self->{old_staged_info} = $old_staged_info;
}

sub run {
  my $self = shift;

  # Determine some useful directories; run from top of repo
  my ($cur_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();
  chdir($top_dir) if $top_dir ne $cur_dir;
  if ($debug && $top_dir ne $cur_dir) {
    print "    >>Running: cd $top_dir\n";
  }

  # Get the list of files we are working with (well, most of them...)
  my @files = $self->quote_args( @{$self->{files}} );
  my $file_list = "";
  $file_list = "-- @files" if @files;

  if (!$self->{in} && $self->{just_recent_unstaged}) {
    # If we're reverting unstaged changes only, and the user didn't specify a
    # revision to revert relative to, then we want to revert relative to the
    # index, not relative to HEAD or some prior commit.
    ExecUtil::execute("git checkout $file_list", ignore_ret => 1);
  }
  elsif (!$self->{in}) {

    # Any newly added files should be unstaged, not deleted
    if ($self->{staged} && @{$self->{new_files}}) {
      my @new_files = $self->quote_args( @{$self->{new_files}} );
      ExecUtil::execute("git rm --cached -q -- @new_files", ignore_ret => 1);
    }

    # Since "git checkout REVISION -- FILES..." doesn't remove files, we
    # need to do that manually
    if (@{$self->{newish_files}}) {
      my $flags = "";
      $flags = "--cached" if ($self->{staged} && !$self->{unstaged});
      my @delete_files = $self->quote_args( @{$self->{newish_files}} );
      ExecUtil::execute("git rm $flags -q -- @delete_files", ignore_ret => 1);
    }

    # Now undo mode changes, content changes, conflict markings, etc. by
    # calling git checkout
    if ($self->{unstaged} && (@{$self->{revert_files}} || !@files)) {
      my $revert_list;
      if (@files) {
        my @revert_files = $self->quote_args( @{$self->{revert_files}} );
        $revert_list = "-- @revert_files";
      } else {
        $revert_list = "-- $top_dir";
      }
      ExecUtil::execute("git checkout $self->{revs} $revert_list");
    }

    if ($self->{unstaged} && !$self->{staged} && $self->{staged_info}) {
      # Restore the index files stomped on by the above git checkout command,
      # and by the git rm command above that
      ExecUtil::execute("echo -nE '$self->{staged_info}' " .
                        "| git update-index --index-info",
                        ignore_ret => 1);
    }

    if (!$self->{unstaged} && $self->{staged} && $self->{old_staged_info}) {
      # Write out new entries to the index file
      ExecUtil::execute("echo -nE '$self->{old_staged_info}' " .
                        "| git update-index --index-info",
                        ignore_ret => 1);
    }

    #
    # Remove any files recording an incomplete merge, if user is undoing
    # the merge
    #
    if (!@files && $self->{staged} && $self->{revs} eq "HEAD") {
      if (-f "$self->{git_dir}/MERGE_MSG") {
        unlink("$self->{git_dir}/MERGE_MSG") if $debug < 2;
        print "    >>Running: rm $self->{git_dir}/MERGE_MSG\n" if $debug;
      }
      if (-f "$self->{git_dir}/MERGE_HEAD") {
        unlink("$self->{git_dir}/MERGE_HEAD") if $debug < 2;
        print "    >>Running: rm $self->{git_dir}/MERGE_HEAD\n" if $debug;
      }
    }

  }

  if ($self->{in}) {
    # Must do unstaged changes first, or extra unknown files can "appear"
    my @flags;
    push(@flags, "")         if $self->{unstaged};
    push(@flags, "--cached") if $self->{staged};

    foreach my $flag (@flags) {
      my @diff_flags = ("--binary");
      push(@diff_flags, $self->{in} ? "" : $flag);
      my @apply_flags = ("--whitespace=nowarn");
      push(@apply_flags, $flag);

      # Print out the (nearly) equivalent commands if the user asked for
      # debugging information
      if ($debug) {
        print "    >>Running: " .
              "git diff @diff_flags $self->{revs} $file_list | " .
              "git apply @apply_flags -R\n";
      }

      # Sadly, using "git diff... | git apply ... -R" doesn't quite work,
      # because apply complains very loudly if the diff is empty.  So,
      # we have to run diff, slurp in its output, check if its nonempty,
      # and then only pipe that output back out to git apply if we have
      # an actual diff to revert.
      if ($debug < 2) {
        open(DIFF, "git diff @diff_flags $self->{revs} $file_list |");
        my @output = <DIFF>;
        my $diff = join("", @output);
        # Listing unmerged paths doesn't count as nonempty
        $diff =~ s/\* Unmerged path.*\n//g;
        close(DIFF);
        $ret = $?;
        exit $ret >> 8 if $ret;

        if ($diff) {
          open(APPLY, "| git apply @apply_flags -R");
          print APPLY $diff;
          close(APPLY);
        }
      }
    }
  }

  # Return to original directory
  chdir($cur_dir);
}

###########################################################################
# rm                                                                      #
###########################################################################
package rm;
@rm::ISA = qw(subcommand);
INIT {
  $command{rm} = {
    extra => 1,
    section => 'modification',
    about => 'Remove files from subsequent commits and the working copy'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(@_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg rm [-f] [-r] [--staged] FILE...

Description:
  Marks the contents of the specified files for removal from the next
  commit.  Also removes the given files from the working copy, unless
  otherwise specified with the --staged flag.

  To prevent data loss, the removal will be aborted if the file has
  modifications.  This check can be overriden with the -f flag.

Examples:
  Mark the content of the files foo and bar for removal from the next
  commit, and delete these files from the working copy.
      \$ eg rm foo bar

  Mark the content of the file baz.c for removal from the next commit, but
  keep baz.c in the working copy as an unknown file.
      \$ eg rm --staged baz.c

  (Advanced) Remove all *.txt files under the Documentation directory OR
  any of its subdirectories.  Note that the asterisk must be preceded with
  a backslash to prevent standard shell expansion.  (Google for 'shell
  expansion' if that makes no sense to you.)
      \$ eg rm Documentation/\\*.txt

Options:
  -f
    Override the file-modification check.

  -r
    Allow recursive removal when a directory name is given.  Without this
    option attempted removal of directories will fail.

  --staged
    Only remove the files from the staging area (the area with changes
    marked as ready to be recorded in the next commit; see 'eg help topic
    staging' for more details).  When using this flag, the given files will
    not be removed from the working copy and will instead become
    \"unknown\" files.

  --
    This option can be used to separate command-line options from the list
    of files, (useful when filenames might be mistaken for command-line
    options).
";
  $self->{'differences'} = '
  eg rm is identical to git rm except that it accepts --staged as a synonym
  for --cached.
';
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  my $result = main::GetOptions("--help" => sub { $self->help() });
  foreach my $i (0..$#ARGV) {
    $ARGV[$i] = "--cached" if $ARGV[$i] eq "--staged";
  }
}

###########################################################################
# stage                                                                   #
###########################################################################
package stage;
@stage::ISA = qw(subcommand);
INIT {
  $command{stage} = {
    new_command => 1,
    section => 'modification',
    about => 'Mark content in files as being ready for commit'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(git_equivalent => 'add', @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg stage [--] PATH...

Description:
  Marks the contents of the specified files as being ready to commit,
  scheduling them for addition to the repository.  (This is also known as
  staging.)  When a directory is passed, all files in that directory or any
  subdirectory are recursively added.

  You can use 'eg unstage PATH...' to unstage files.

  See 'eg help topic staging' for more details, including situations where
  you might find staging useful.

Examples:
  Create a new file, and mark it for addition to the repository.
      \$ echo hi > there
      \$ eg stage there

  (Advanced) Mark some changes as good, add some verbose sanity checking code,
  then commit just the good changes.
      Implement some cool new feature in somefile.C
      \$ eg stage somefile.C
      Add some verbose sanity checking code to somefile.C
      Decide to commit the new feature code but not the sanity checking code:
      \$ eg commit --staged

  (Advanced) Show changes in a file, split by those that you have marked as
  good and those that you haven't:
      Make various edits
      \$ eg stage file1 file2
      Make more edits, include some to file1
      \$ eg diff            # Look at all the changes
      \$ eg diff --staged   # Look at the \"ready to be committed\" changes
      \$ eg diff --unstaged # Look at the changes not ready to be commited

Options:
  --
    This option can be used to separate command-line options from the list
    of files, (useful when filenames might be mistaken for command-line
    options).
";
  $self->{'differences'} = '
  eg stage is a command new to eg that is not part of git (update: it is
  part of newer versions of git, with identical meaning to eg).  eg stage
  merely calls git add.
';
  return $self;
}

sub run {
  my $self = shift;
  my $package_name = ref($self);

  @ARGV = $self->quote_args(@ARGV);
  return ExecUtil::execute("git add @ARGV", ignore_ret => 1);
}

###########################################################################
# stash                                                                   #
###########################################################################
package stash;
@stash::ISA = qw(subcommand);
INIT {
  $command{stash} = {
    section => 'timesavers',
    about => 'Save and revert local changes, or apply stashed changes',
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    initial_commit_error_msg => "Error: Cannot stash away changes when there " .
                                "is no commit yet.",
    @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg stash list [--details]
  eg stash [save DESCRIPTION]
  eg stash apply [DESCRIPTION]
  eg stash show [OPTIONS] [DESCRIPTION]
  eg stash (drop [DESCRIPTION] | clear)

Description:
  This command can be used to remove any changes since the last commit,
  stashing these changes away so they can be reapplied later.  It can also
  be used to apply any previously stashed away changes.  This command can
  be used multiple times to have multiple sets of changes stashed away.

  Unknown files (files which you have never run 'eg stage' on) are
  unaffected; they will not be stashed away or reverted.

  When no arguments are specified to eg stash, the current changes are
  saved away with a default description.

Examples:
  You have lots of changes that you're working on, then get an important
  but simple bug report.  You can stash away your current changes, fix the
  important bug, and then reapply the stashed changes:
      \$ eg stash
      fix, fix, fix, build, test, etc.
      \$ eg commit
      \$ eg stash apply

  You can provide a description of the changes being stashed away, and
  apply previous stashes by their description (or a unique substring of the
  description).
      make lots of changes
      \$ eg stash save incomplete refactoring work
      work on something else that you think will be a quick fix
      \$ eg stash save longer fix than I thought
      fix some important but one-liner bug
      \$ eg commit
      \$ eg stash list
      \$ eg stash apply incomplete refactoring work
      finish off the refactoring
      \$ eg commit
      \$ eg stash apply fix than I
      etc., etc.

  You want to get some details about an existing stash created above:
      \$ eg stash show incomplete refactoring
      \$ eg stash show -p incomplete refactoring

Options:
  list [--details]
    Show the saved stash descriptions.  If the --details flag is present,
    provide more information about each stash.

  save DESCRIPTION
    Save current changes with the description DESCRIPTION.  The
    description cannot start with \"-\".

  apply [DESCRIPTION]
    Apply the stashed changes with the specified description.  If no
    description is specified, and more than one stash has been saved, an
    error message will be shown.  The description cannot start with \"-\".

  show [OPTIONS] [DESCRIPTION]
    Show the stashed changes with the specified description.  If no
    description is specified, and more than one stash has been saved, an
    error message will be shown.  The description cannot start with \"-\".

    Note that the output shown is the output from diff --stat.  If you
    want the full patch, pass the -p option.  Other options for
    controlling diff output (such as --name-status or --dirstat, see
    'git help diff') are also possible options.

  drop [DESCRIPTION]
    Delete the specified stash.  The description cannot start with
    \"-\".

  clear
    Delete all stashed changes.
";
  $self->{'differences'} = '
  eg stash is only cosmetically different than git stash, and is fully
  backwards compatible.

  eg stash list, by default, only shows the saved description -- not
  the reflog syntax or branch the change was made on.

  eg stash apply and eg stash show also accept any string and will
  apply or show the stash whose description contains that string.
  While stash and apply accept reflog syntax like their git stash
  counterparts, i.e. while
      $ eg stash apply stash@{3}
  will work, I think it will be easier for the user to run
      $ eg stash apply rudely interrupted changes
';
  return $self;
}

sub preprocess {
  my $self = shift;
  my $package_name = ref($self);

  #
  # Parse options
  #
  my @args;
  my $result=main::GetOptions("--help" => sub { $self->help() });

  # Get the (sub)subcommand
  if (scalar @ARGV == 0) {
    $self->{subcommand} = 'save';
  } else {
    $self->{subcommand} = shift @ARGV;
    push(@args, $self->{subcommand});

    if ($self->{subcommand} eq 'apply' && @ARGV > 0 && $ARGV[0] eq '--index') {
      push(@args, shift @ARGV);
    }
    if ($self->{subcommand} eq 'save' &&
        @ARGV > 0 && $ARGV[0] eq '--keep-index') {
      push(@args, shift @ARGV);
    }
    if ($self->{subcommand} eq 'show') {
      while(@ARGV > 0 && $ARGV[0] =~ /^-/) {
        push(@args, shift @ARGV);
      }
    }
    if ($self->{subcommand} eq 'branch') {
      push(@args, shift @ARGV);  # Pull off the branch name
    }
  }

  # Show a help message if they picked a bad stash subaction.
  my @valid_commands = qw(list show apply clear save drop pop branch create);
  if (! grep {$_ eq $self->{subcommand}} @valid_commands) {
    print STDERR<<EOF;
Aborting; invalid stash subcommand: $self->{subcommand}
EOF
    exit 1;
  }

  # Translate the description passed to apply or show into a reflog reference
  my @commands_accepting_existing_stash = qw(show drop pop apply branch);
  if ((grep {$_ eq $self->{subcommand}} @commands_accepting_existing_stash) &&
      scalar @ARGV > 0) {
    my $stash_description = "@ARGV";
    @ARGV = ();
    if ($stash_description =~ m#^stash\@{[^{]+}$#) {
      push(@args, $stash_description)
    } else {
      # Will need to compare arguments to existing stash descriptions...
      print "  >>Getting stash descriptions to compare to arguments:\n"
        if $debug;
      my ($retval, $output) =
        ExecUtil::execute_captured("$eg_exec stash list --refs");
      my @lines = split('\n', $output);
      my %refs;
      my %bad_refs;
      while (@lines) {
        my $desc = shift @lines;
        my $ref = shift @lines;
        $bad_refs{$desc}++ if defined $refs{$desc};
        $refs{$desc} = $ref;
      }

      # See if the stash description matches zero, one, or more existing
      # stash descriptions; convert it to a reflog entry if only one
      my @matches = grep {$_ =~ m#\Q$stash_description\E#} (keys %refs);
      if (scalar @matches == 0) {
        die "No stash matching '$stash_description' exists!  Aborting.\n";
      } elsif (scalar @matches == 1) {
        # Only one regex match; use it
        $stash_description = $matches[0];
      } else {
        # See if our string matches one stash description exactly; if so,
        # we can use it.
        if (!grep {$_ eq $stash_description} (keys %refs)) {
          die "Stash description '$stash_description' matches multiple " .
              "stashes:\n  " . join("\n  ", @matches) . "\n" .
              "Aborting.\n";
        }
      }
      die "Stash description '$stash_description' matches multiple stashes.\n"
        if $bad_refs{$stash_description};

      push(@args, $refs{$stash_description});
    }
  } elsif ($self->{subcommand} eq 'list' && @ARGV) {
    my $arg = shift @ARGV;
    if ($arg eq '--refs') {
      $self->{show_refs} = 1;
    } elsif ($arg eq '--details') {
      $self->{show_details} = 1;
    } else {
      unshift(@ARGV, $arg);
    }
  }

  # Add any unprocessed args to the arguments to use
  push(@args, @ARGV);

  # Reset @ARGV with the built up list of arguments
  @ARGV = @args;
}

sub postprocess {
  my $self = shift;
  my $output = shift;

  if ($debug == 2) {
    print "    >>(No commands to run, just data to print)<<\n";
    return;
  }

  my @lines = split('\n', $output);
  if ($self->{subcommand} eq 'list') {
    my $regex = 
      qr#(stash\@{[^}]+}): (?:WIP )?[Oo]n [^ ]*: (?:[0-9a-f]+\.\.\. )?#;
    foreach my $line (@lines) {
      if ($self->{show_details}) {
        print "$line\n";
      } else {
        $line =~ s/$regex//;
        print "$line\n";
        print "$1\n" if $self->{show_refs};
      }
    }
  } else {
    foreach my $line (@lines) {
      print "$line\n";
    }
  }
}

###########################################################################
# status                                                                  #
###########################################################################
package status;
@status::ISA = qw(subcommand);
INIT {
  $command{status} = {
    section => 'discovery',
    about => 'Summarize current changes'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(@_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg status

Description:
  Show the current state of the project.  In addition to showing the
  currently active branch, this command will list files with content in any
  of the following states:

     Unknown
       Files that are not explicitly ignored (i.e. do not appear in an
       ignore list such as a .gitignore file) but whose contents are still
       not tracked by git.

       These files can become known by running 'eg stage FILENAME', or
       ignored by having their name added to a .gitignore file.

     Changed but not updated (\"unstaged\")
       Files whose contents have been modified in the working copy.

       (Advanced usage note) If you explicitly mark all the changes in a
       file as ready to be committed, then the file will not appear in this
       list and will instead appear in the \"staged\" list (see below).
       However, a file can appear in both the unstaged and staged lists if
       only part of the changes in the file are marked as ready for commit.

     Changes ready to be committed (\"staged\")
       Files with content changes that have explicitly been marked as ready
       to be committed.  This state only typically appears in advanced
       usage.

       Files enter this state through the use of 'eg stage'.  Files can
       return to the unstaged state by running 'eg revert --staged FILE'.
       See 'eg help topic staging' to learn about the staging area.
";
  $self->{'differences'} = '
  eg status output is essentially just a streamlined and cleaned version of
  git status output.

  The streamlining serves to avoid information overload to new users (which
  is only possible with a less error prone "commit" command) and the
  cleaning (removal of leading hash marks) serves to make the system more
  inviting to new users.

  A slight wording change was done to transform "untracked" to "unknown"
  since, as Havoc pointed out, the word "tracked" may not be very self
  explanatory (in addition to the real meaning, users might think of:
  "tracked in the index?", "related to remote tracking branches?", "some
  fancy new monitoring scheme unique to git that other vcses do not have?",
  "is there some other meaning?").  I do not know if "known" will fully
  solve this, but I suspect it will be more self-explanatory than
  "tracked".

  There are also slight changes to the section names to reinforce
  consistent naming when referring to the same concept (staging, in this
  case), but the changes are very slight.
';
  return $self;
}

sub postprocess {
  my $self = shift;
  my $output = shift;

  if ($debug == 2) {
    print "    >>(No commands to run, just data to print)<<\n";
    return;
  }

  my $branch;
  my $initial_commit = 0;
  my %files = ( unknown => undef, unstaged => undef, staged => undef );
  my @basic_info;

  if ($output =~ m/^fatal:/) {
    print STDERR $output;
    exit 128;
  }
  my @lines = split('\n', $output);
  my $cur_state = -1;
  while (@lines) {
    my $line = shift @lines;
    my $section = undef;

    if ($line =~ m/^# On branch (.*)$/) {
      $branch = $1;
    } elsif ($line =~ m/^# Initial commit$/) {
      $initial_commit = 1;
    } elsif ($line =~ m/^# Untracked files:$/) {
      $cur_state = 1;
      $section = 'unknown';
      $title = "Unknown files:";
    } elsif ($line =~ m/^# Changes to be committed:$/) {
      $cur_state = 2;
      $section = 'staged';
      $title = 'Changes ready to be committed ("staged"):';
    } elsif ($line =~ m/^# Changed but not updated:$/) {
      $cur_state = 2;
      $section = 'unstaged';
      $title = 'Changed but not updated ("unstaged"):';
    } elsif ($cur_state < 0) {
      next if $line !~ m/^# (.+)/;
      push(@basic_info, $1);
    }

    # If we're inside a section type, parse it
    if ($cur_state > 0) {
      my @section_files;
      my $hints;

      # Parse the hints first
      $line = shift @lines;
      while ($line =~ m/^#\s+\(use ".*/) {
        $hints .= $line;
        $line = shift @lines;
      }
      die("Bug parsing git status output") if $line ne '#';
      $line = shift @lines; # Get rid of blank line

      while (defined $line && $line =~ m/^#.+$/) {
        if ($cur_state == 1) {
          if ($line =~ m/^#(\s+)(.*)/) { 
            my $file = $2;
            push @section_files, "$1$file";
          }
        } elsif ($cur_state == 2) {
          if ($line =~ m/^#(\s+.*:\s+)(.*)/) {
            my $file = $2;
            push(@section_files, "$1$file");
          }
        }
        $line = shift @lines;
      }

      if (defined($files{$section})) {
        push(@{$files{$section}{'file_list'}}, @section_files);
      } else {
        $files{$section} = { title     => $title,
                             hint      => $hints,
                             file_list => \@section_files };
      }

      # Record that we finished parsing this section
      $cur_state = 0;
    }
  }

  # Print out the branch we are on
  if (defined $branch) {
    print "(On branch $branch";
    print ", no commits yet" if $initial_commit;
    print ")\n";
  } else {
    print "(No active branch)\n";
  }
  foreach my $line (@basic_info) {
    print "($line)\n";
  }

  # Print out all the various changes
  foreach my $section ('staged', 'unstaged', 'unknown') {
    if (defined($files{$section})) {
      print "$files{$section}{'title'}\n";
      foreach my $fileline (@{$files{$section}{'file_list'}}) {
        print "$fileline\n";
      }
    }
  }

}

###########################################################################
# switch                                                                  #
###########################################################################
package switch;
@switch::ISA = qw(subcommand);
INIT {
  $command{switch} = {
    new_command => 1,
    section => 'projects',
    about => 'Switch the working copy to another branch'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    git_equivalent => 'checkout',
    initial_commit_error_msg => "Error: Cannot create or switch branches " .
                                "until a commit has been made.",
    @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg switch BRANCH
  eg switch REVISION

Description:
  Switches the working copy to another branch, or to another tag or
  revision.  (Switch is an operation that can be done locally, without any
  network connectivity).

  To list, create, or delete branches to switch to, use eg branch.  To
  list, create, or delete tags to switch to, use eg tag.  To list, create,
  or delete revisions, use eg log, eg commit, or eg reset, respectively.
  :-)

Examples:
  Switch to the 4.8 branch
      \$ eg switch 4.8

  Switch the working copy to the v4.3 tag
      \$ eg switch v4.3

";
  $self->{'differences'} = '
  eg switch is a subset of the functionality of git checkout; the abilities
  and flags for creating and switching branches are identical between the
  two, just the name of the function is different.

  The ability of git checkout to get older versions of files is not part of
  eg switch; instead that ability can be found with eg revert.
';
  return $self;
}

sub preprocess {
  my $self = shift;

  if (scalar(@ARGV) == 0) {
    print STDERR<<EOF;
No branch (or revision) to switch to specified!  See the help for eg switch
and eg branch.  The following branches exist, with the current branch marked
with an asterisk:

EOF
    my $branch_obj = "branch"->new();
    $branch_obj->run();
    exit 1;
  }

  # Don't let them try to use eg switch to check out older revisions of files;
  # this is just supposed to be a subset of git checkout
  if (!grep {$_ =~ /^-/} @ARGV) {
    die "Invalid arguments to eg switch: @ARGV\n" if @ARGV > 1;
    Util::push_debug(new_value => 0);
    my $valid_ref = RepoUtil::valid_ref($ARGV[0]);
    Util::pop_debug();
    die "Invalid branch/revision reference: $ARGV[0]\n" if !$valid_ref;
  }

  # Avoid switching to a remote tracking branch
  if ($ARGV[-1] =~ m#/#) {
    print STDERR<<EOF;
Aborting: Should not switch to a remote tracking branch.  Please instead
create a branch based on the remote tracking branch (use the command
'eg branch NEWBRANCH $ARGV[-1]') and then switch to the new branch.
EOF
    exit 1;
  }

  $self->SUPER::preprocess();
}

sub run {
  my $self = shift;
  my $package_name = ref($self);

  @ARGV = $self->quote_args(@ARGV);
  return ExecUtil::execute("git checkout @ARGV", ignore_ret => 1);
}

###########################################################################
# tag                                                                     #
###########################################################################
package tag;
@tag::ISA = qw(subcommand);
INIT {
  $command{tag} = {
    unmodified_behavior => 1,
    extra => 1,
    section => 'modification',
    about => 'Provide a name for a specific version of the repository'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    initial_commit_error_msg => "No tags can be created, deleted, or " .
                                "listed until a commit has been made.",
    @_
    );
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg tag TAG [REVISION]
  eg tag -d TAG

Description:
  Create or delete a tag (i.e. a nickname) for a specific version of the
  project.  (Tags can also be annotated or digitally signed; see the 'See
  Also section.)

  Note that tags are local; creation of tags in a remote repository can be
  accomplished by first creating a local tag and then pushing the new tag
  to the remote repository using eg push.

Examples
  List the available local tags
      \$ eg tag

  Create a new tag named good-version for the last commit.
      \$ eg tag good-version

  Create a new tag named version-2.0.3 for 3 versions before the last commit
  (assuming one is on a branch named project-2.0)
      \$ eg tag version-2.0.3 project-2.0~3

  Delete the tag named gooey
      \$ eg tag -d gooey

  Create a new tag named look_at_me in the default remote repository
      \$ eg tag look_at_me
      \$ eg push --tag look_at_me

Options:
  -d
    Delete the specified tag
";
  return $self;
}

###########################################################################
# unstage                                                                 #
###########################################################################
package unstage;
@unstage::ISA = qw(revert);
INIT {
  $command{unstage} = {
    new_command => 1,
    extra => 1,
    section => 'modification',
    about => 'Mark changes in files as no longer ready for commit'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(git_equivalent => '', @_);
  bless($self, $class);

  unshift(@ARGV, "--") if scalar(@ARGV) > 0 && $ARGV[0] ne "--";
  unshift(@ARGV, "--staged");

  $self->{'help'} = "
Usage:
  eg unstage [--] PATH...

Description:
  Marks the changes in the specified files as not being ready to commit.
  When a directory is passed, all files in that directory or any
  subdirectory are recursively unstaged.

  Note that this command is equivalent to 'eg revert --staged PATH...'

  See 'eg help topic staging' for more details, including situations where
  you might find staging useful.

Examples:
  Create a new file, and mark it for addition to the repository, then change
  your mind
      \$ echo hi > there
      \$ eg stage there
      \$ eg unstage there

  Modify an existing file, mark the modified version as being ready for commit,
  then change your mind
      \$ echo some extra info at end of file >> foo
      \$ eg stage foo
      \$ eg unstage foo
";
  $self->{'differences'} = '
  eg unstage is a command new to eg that is not part of git; it is implemented
  on top of eg revert --staged, though it could as easily simply call through
  to git reset.
';
  return $self;
}

# unstage inherits from revert, and simply modifies @ARGV in new(), so that
# revert will get run with the right arguments

###########################################################################
# update                                                                  #
###########################################################################
package update;
@update::ISA = qw(subcommand);
INIT {
  $command{update} = {
    new_command => 1,
    extra => 1,
    section => 'compatibility',
    about => 'Use antiquated workflow for refreshing working copy, if safe'
    };
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(
    git_equivalent => 'pull',
    @_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg update

Description:
  Gets updates from the default remote repository if updating is safe, and
  provides suggestions on proceeding otherwise.

  eg update does not accept any options...other than --help.

Examples:
  Get any updates from the remote repository
      \$ eg update
";
  $self->{'differences'} = '
  eg update is unique to eg; it exists primarily to ease the transition for
  cvs/svn users and to do something useful for them.  In particular, eg
  update is used just to do fast-forward updates when there are no local
  changes; if anything more than this is needed, eg advises users to run
  other commands.

  Here are the special cases eg update detects and provides tailored
  messages for:
    * User has local commits           => ask user to use eg pull instead
    * User provides argument to update => tell user to use eg switch for
                                          checking out an older revision or
                                          eg revert to undo changes to a file
    * User has locally deleted files   => tell user to use eg revert to
                                          undo local changes (and that they do
                                          not need to delete the file first as
                                          they did with cvs)
    * User has local modifications     => Tell user to stash or commit their
                                          changes before pulling updates
    * No default repository to contact => Tell user to run "eg remote add
                                          origin REPOSITORY_URL"
    * branch.BRANCH.merge not set and  => Warn user that we do not know which
      more than one remote branch         branch to pull from and suggest eg
      present                             pull or setting branch.BRANCH.merge
';
  return $self;
}

sub preprocess {
  my $self = shift;

  # Check for the --help arg
  my $result=main::GetOptions("--help" => sub { $self->help() });

  # Abort if the user specified any args other than --help
  if (@ARGV) {
    print STDERR <<EOF;
Aborting: No arguments to update are allowed.  If you are trying to switch
to a different revision, use eg switch.  If you are trying to undo the changes
to a particular file, use eg revert.
EOF
    exit 1;
  }

  # Check if there are local changes
  my $status = RepoUtil::commit_push_checks();
  my $has_changes = $status->{has_staged_changes} ||
    $status->{has_unstaged_changes} || $status->{has_unmerged_changes};
  if ($has_changes) {
    print STDERR <<EOF;
Aborting: You have local changes, and pulling updates could put your
working copy in a nonworking state.  Consider committing your changes
before updating, or using eg stash to stash the changes away and reapply
them after the update.
EOF

    if ($status->{output} =~ /^\s+deleted:/m) {
      print STDERR "\n";
      print STDERR <<EOF;
NOTE: If you are trying to undo the changes in a file, just run
  eg revert FILE
This works whether or not the file has been deleted.
EOF
    }
    
    exit 1;
  }

  if ($debug) {
    print "  >>Commands to determine where to update from:\n";
  }

  # Check if there is a default repository to pull from
  # <This code mostly taken from pull, but "origin" serves as extra backup>
  my $branch = RepoUtil::current_branch() || "HEAD";
  my $repo = RepoUtil::get_default_push_pull_repository();
  $self->{repository} = $repo;
  $self->{local_branch} = $branch;

  # Check if there is a default branch to pull
  my $merge_branch = RepoUtil::get_config("branch.$branch.merge");
  if (!$merge_branch) {
    # Check if the remote repository has exactly 1 branch...if so, return it,
    # otherwise throw an error
    my ($ret, $output) = 
      ExecUtil::execute_captured("git ls-remote -h $self->{repository}");
    if ($ret == 0) {
      my @remote_refs = split('\n', $output);
      if (@remote_refs == 1) {
        # git ls-remote -h output changed at some point to include the sha1sum;
        # we only want the refspec
        if ($remote_refs[0] =~ /^[0-9a-f]+\s+(.*)/) {
          $merge_branch = $1;
        } else {
          $merge_branch = $remote_refs[0];
        }
      }
    }
  }
  if (!$merge_branch) {
    print STDERR <<EOF;
Error: It is not clear which remote branch to update from.
You can either use eg pull instead, or run 
  eg config branch.$branch.merge BRANCHANME
EOF
    exit 1;
  }
  $self->{merge_branch} = $merge_branch;
}

sub run {
  my $self = shift;
  my $package_name = ref($self);

  # Get value to set ORIG_HEAD to (unless we are on the initial commit)
  Util::push_debug(new_value => 0);
  my ($retval, $orig_sha1sum) = 
    ExecUtil::execute_captured("git rev-parse HEAD", ignore_ret => 1);
  my $has_orig_head = ($retval == 0);
  Util::pop_debug();

  # Do the fetch && reset, making sure to set ORIG_HEAD
  my ($ret, $output) = 
    ExecUtil::execute_captured("git fetch $self->{repository} " .
                               "$self->{merge_branch}:$self->{local_branch}",
                               ignore_ret => 1);
  if ($output =~ /\[rejected\].*\(non fast forward\)/) {
    die "fatal: Cannot update because you have local commits; " .
        "try 'eg pull' instead.\n";
  } elsif ($ret != 0) {
    die "Error updating (output = $output); please report the bug, and\n" .
        "try using 'eg pull' instead.\n";
  } else {
    ExecUtil::execute_captured("git reset --hard $self->{local_branch}");
    if ($has_orig_head && $debug < 2) {
      open(ORIG_HEAD, "> $self->{git_dir}/ORIG_HEAD");
      print ORIG_HEAD $output;
      close(ORIG_HEAD);
    }
    print "Updated the current branch.\n" if ($debug < 2);
  }
}

###########################################################################
# version                                                                 #
###########################################################################
package version;
@version::ISA = qw(subcommand);

BEGIN {
  undef *version::new unless $] < 5.010; # avoid name clashing
}

sub new {
  my $class = shift;
  my $self = $class->SUPER::new(git_repo_needed => 0, @_);
  bless($self, $class);
}

# Override help because we don't want to both definining $command{help}
sub help {
  my $self = shift;

  $self->{'help'} = "
Usage:
  eg version

Description:
  Show the current version of eg.
";

  open(OUTPUT, ">&STDOUT");
  print OUTPUT $self->{'help'};
  close(OUTPUT);
  exit 0;
}

sub run {
  my $self = shift;

  print "eg version $version\n" if $debug < 2;
  print "    >>(We can print the eg version directly)<<\n" if $debug == 2;
  $self->SUPER::run();
}



#*************************************************************************#
#*************************************************************************#
#*************************************************************************#
#                             UTILITY CLASSES                             #
#*************************************************************************#
#*************************************************************************#
#*************************************************************************#

###########################################################################
# ExecUtil                                                                #
###########################################################################
package ExecUtil;

# _execute_impl is the guts for execute() and execute_captured()
sub _execute_impl {
  my ($command, @opts) = @_;
  my ($ret, $output);
  my %options = ( ignore_ret => 0, capture_output => 0, @opts );

  if ($debug) {
    print "    >>Running: '$command'<<\n";
    return $options{capture_output} ? (0, "") : 0 if $debug == 2;
  }

  #
  # Execute the relevant command, in a subdirectory if needed, and capturing
  # stdout and stderr if wanted
  #
  if ($options{capture_output}) {
    if ($options{capture_stdout_only}) {
      $output = `$command`;
    } else {
      $output = `$command 2>&1`;
    }
    $ret = $?;
  } elsif (defined $outfh) {
    open(OUTPUT, "$command 2>&1 |");
    while (<OUTPUT>) {
      print $outfh $_;
    }
    close(OUTPUT);
    $ret = $?;
  } else {
    system($command);
    $ret = $?;
  }

  #
  # Determine retval
  #
  if ($ret != 0) {
    if (($? & 127) == 2) {
      print STDERR "eg: interrupted\n";
    }
    elsif ($? & 127) {
      print STDERR "eg: received signal ".($? & 127)."\n";
    }
    elsif (! $options{ignore_ret}) {
      print STDERR "eg: failed ($ret)\n" if $debug;
      if ($ret >> 8 != 0) {
        print STDERR "eg: command ($command) failed\n";
      }
      elsif ($ret != 0) {
        print STDERR "eg: command ($command) died (retval=$ret)\n";
      }
    }
  }

  return $options{capture_output} ? ($ret, $output) : $ret;
}

# executes a command, capturing its output (both STDOUT and STDERR),
# returning both the return value and the output
sub execute_captured {
  my ($command, @options) = @_;
  return _execute_impl($command, capture_output => 1, @options);
}

# executes a command, returning its chomped output
sub output {
  my ($command, @options) = @_;
  my ($ret, $output) = execute_captured($command, @options);
  die "Failed executing '$command'!\n" if $ret != 0;
  chomp($output);
  return $output
}

# executes a command (output not captured), returning its return value
sub execute {
  my ($command, @options) = @_;
  return _execute_impl($command, @options);
}

###########################################################################
# RepoUtil                                                                #
###########################################################################
package RepoUtil;

# current_branch: Get the currently active branch
sub current_branch {
  Util::push_debug(new_value => $debug ? 1 : 0);
  my ($ret, $output) = ExecUtil::execute_captured("git symbolic-ref HEAD",
                                                  ignore_ret => 1);
  Util::pop_debug();

  return undef if $ret != 0;
  chomp($output);
  $output =~ s#refs/heads/## || die "Current branch ($output) is funky.\n";
  return $output;
}

sub git_dir {
  my $options = {force => 0, @_};  # Hashref initialized as we're told
  if (!$options->{force}) {
    return $gitdir if ($gitdir);
  }

  Util::push_debug(new_value => 0);
  my ($ret, $output) = 
    ExecUtil::execute_captured("git rev-parse --git-dir", ignore_ret => 1);
  Util::pop_debug();

  return undef if $ret != 0;
  chomp($output);
  return $output;
}

sub get_dirs {
  my $options = {force => 0, @_};  # Hashref initialized as we're told

  if ($curdir && !$options->{force}) {
    return ($curdir, $topdir, $gitdir);
  }

  Util::push_debug(new_value => 0);

  $curdir = main::getcwd();

  # Get the toplevel repository directory
  $topdir = $curdir;
  my ($ret, $rel_dir) = 
    ExecUtil::execute_captured("git rev-parse --show-prefix", ignore_ret => 1);
  chomp($rel_dir);
  if ($ret != 0) {
    $topdir = undef;
  } elsif ($rel_dir) {
    $rel_dir =~ s#/$##;  # Remove trailing slash
    $topdir =~ s#\Q$rel_dir\E$##;
    $topdir =~ s#/$##;  # Remove trailing slash
  }

  $gitdir = git_dir(force => $options->{force});

  Util::pop_debug();

  return ($curdir, $topdir, $gitdir);
}

sub initial_commit {
  my @output = `git rev-parse --verify -q HEAD`;
  return $?;
}

sub valid_ref {
  my ($ref) = @_;
  my ($ret, $sha1sum) =
    ExecUtil::execute_captured("git rev-parse --verify -q $ref",
                               ignore_ret => 1);
  return $ret == 0;
}

sub files_modified() {
  my @output = `git status -a`;
  return $? == 0;
}

sub merge_branches {
  my $git_dir = RepoUtil::git_dir();
  my $active_branch = RepoUtil::current_branch() || 'HEAD';
  my @merge_branches =
    `cat $git_dir/MERGE_HEAD | git name-rev --stdin`;
  @merge_branches = map { /^[0-9a-f]* \((.*)\)$/ && $1 } @merge_branches;
  my @all_merge_branches = ($active_branch, @merge_branches);
  return @all_merge_branches;
}

sub get_config {
  my $key = shift;
  my ($ret, $output) = ExecUtil::execute_captured("git config --get $key",
                                                  ignore_ret => 1);
  return undef if $ret != 0;
  chomp($output);
  return $output;
}

sub set_config {
  my $key = shift;
  my $value = shift;
  ExecUtil::execute("git config $key \"$value\"");
}

sub unset_config {
  my $key = shift;
  ExecUtil::execute("git config --unset $key", ignore_ret => 1);
}

sub get_default_push_pull_repository {
  my $branch = current_branch();
  return undef if !$branch;

  my $default_remote = `git config --get branch.$branch.remote`;
  if ($default_remote) {
    chomp($default_remote);
    return $default_remote;
  }

  my @output = `git config --get-regexp remote\.origin\.*`;
  if (@output) {
    return "origin";
  } else {
    print STDERR <<EOF;
Aborting: No repository specified, and "origin" is not set up as a remote
repository.  Please specify a repository or setup "origin" by running
  eg remote add origin URL
EOF
  }
}

sub migrate_old_easy_git_pull_push_options()
{
  my @options = `git config --get-regexp "^default.*"`;
  return if $? != 0;
  my @remotes = `git remote`;
  chomp(@remotes);

  Util::push_debug(new_value => 0);

  my ($ret, $output);
  chomp(@options);
  foreach my $option (@options) {
    my ($key, $value) = split(' ', $option);
    my $section = ($key =~ /^(.*)\./ && $1);
    ($ret, $output) =
      ExecUtil::execute_captured("git config --remove-section $section",
                                 ignore_ret => 1);

    next if $option =~ /^default\.push/;
    next if $option =~ /^default\.branch\.[^ ]+\.url\b/;

    if ($option =~ /^default\.(branch\.([^ ]+)\.remote) (.*)$/) {
      my $newkey = $1;
      my $branch = $2;
      my $remote = $3;
      if (grep {$remote eq $_} @remotes) {
        ($ret, $output) = ExecUtil::execute_captured("git config --get $newkey",
                                                     ignore_ret => 1);
        if ($ret != 0) {
          ($ret, $output) =
            ExecUtil::execute_captured("git config $newkey $value");
        }
      }
    } elsif ($option =~ /^default\.(branch\.([^ ]+)\.merge) (.*)$/) {
      my $newkey = $1;
      my $branch = $2;
      ($ret, $output) = ExecUtil::execute_captured("git config --get $newkey",
                                                   ignore_ret => 1);
      if ($ret != 0) {
        if (RepoUtil::valid_ref($branch)) {
          ($ret, $output) =
            ExecUtil::execute_captured("git config $newkey refs/heads/$value");
        }
      }
    } else {
      $option =~ s/\s+/ = /;
      print STDERR<<EOF;
Abort: Tried to migrate obsolete (and broken) EasyGit-specific configuration
values, but ran across one I did not recognize:
  $option
Please file a bug report, and or manually unset this configuration value
EOF
      exit 1;
    }
  }

  Util::pop_debug();
}

# Error messages spewed by commit with non-clean working copies
sub commit_error_message_checks {
  my ($commit_type, $check_for, $status, $new_unknown) = @_;

  if ($status->{has_unmerged_changes}) {
    print STDERR <<EOF;
Aborting: You have unresolved conflicts from your merge (run 'eg status' to get
the list of files with conflicts).  You must first resolve any conflicts and
then mark the relevant files as being ready for commit (see 'eg help stage' to
learn how to do so) before proceeding.
EOF
    exit 1;
  }

  if ($check_for->{no_changes} && $status->{has_no_changes}) {
    print STDERR <<EOF;
Committing changes should (usually) only be done on a branch.  Specify
--bypass-no-branch-check to commit anyway.
EOF
    exit 1;
  }

  if ($check_for->{no_changes} && $status->{has_no_changes}) {
    print STDERR "Aborting: Nothing to commit (run 'eg status' for details).\n";
    exit 1;
  }
  elsif ($check_for->{unknown} && $check_for->{partially_staged} &&
         $status->{has_new_unknown_files} && 
         $status->{has_unstaged_changes} && $status->{has_staged_changes}) {
    print STDERR <<EOF;
Aborting: It is not clear which changes should be committed; you have new
unknown files, staged (explictly marked as ready for commit) changes, and
unstaged changes all present.  Run 'eg help $commit_type' for details.
New unknown files:
EOF
    foreach my $file (@$new_unknown) {
      print STDERR "  $file\n";
    }
    exit 1;
  }
  elsif ($check_for->{unknown} && $status->{has_new_unknown_files}) {
    print STDERR <<EOF;
Aborting: You have new unknown files present and it is not clear whether
they should be committed.  Run 'eg help $commit_type' for details.
New unknown files:
EOF
    foreach my $file (@$new_unknown) {
      print STDERR "  $file\n";
    }
    exit 1;
  }
  elsif ($check_for->{partially_staged} &&
         $status->{has_unstaged_changes} && $status->{has_staged_changes}) {
    print STDERR <<EOF;
Aborting: It is not clear which changes should be committed; you have both
staged (explictly marked as ready for commit) changes and unstaged changes
present.  Run 'eg help $commit_type' for details.
EOF
    exit 1;
  }
}

# Error messages spewed by push, publish for non-clean working copies
sub push_error_message_checks {
  my ($clean_check_type, $check_for, $status, $new_unknown) = @_;

  if ($status->{has_unmerged_changes}) {
    print STDERR <<EOF;
Aborting: You have unresolved conflicts from your merge (run 'eg status' to get
the list of files with conflicts).  You should first resolve any conflicts
before trying to $clean_check_type your work elsewhere.
EOF
    exit 1;
  }

  if ($check_for->{unknown} && $check_for->{changes} &&
      $status->{has_new_unknown_files} && 
      ($status->{has_unstaged_changes} || $status->{has_staged_changes})) {
    print STDERR <<EOF;
Aborting: You have new unknown files and changed files present.  You should
first commit any such changes (or use the -b flag to bypass this check) before
trying to $clean_check_type your work elsewhere.
New unknown files:
EOF
    foreach my $file (@$new_unknown) {
      print STDERR "  $file\n";
    }
    exit 1;
  }
  elsif ($check_for->{unknown} && $status->{has_new_unknown_files}) {
    print STDERR <<EOF;
Aborting: You have new unknown files present.  You should either commit these
new files before trying to $clean_check_type your work elsewhere, or use the
-b flag to bypass this check.
New unknown files:
EOF
    foreach my $file (@$new_unknown) {
      print STDERR "  $file\n";
    }
    exit 1;
  }
  elsif ($check_for->{changes} &&
         ($status->{has_unstaged_changes} || $status->{has_staged_changes})) {
    print STDERR <<EOF;
Aborting: You have modified your files since the last commit.  You should
first commit any such changes before trying to $clean_check_type your work
elsewhere, or use the -b flag to bypass this check.
EOF
    exit 1;
  }
}

sub commit_push_checks {
  my ($clean_check_type, $check_for) = @_;
  my %status;

  # Determine some useful directories
  my ($cur_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();

  # Save debug mode, print out commands used up front
  if ($debug) {
    Util::push_debug(new_value => 0);
    if ($clean_check_type) {
      print "    >>Commands to gather data for pre-$clean_check_type sanity checks:\n";
    } else {
      print "    >>Commands to gather data for sanity checks:\n";
    }
    print "        git status\n";
    print "        git ls-files --unmerged\n";
    print "        git symbolic-ref HEAD\n" if $check_for->{no_branch};
    print "        cd $top_dir && git ls-files --exclude-standard --others --directory --no-empty-directory\n";
  } else {
    Util::push_debug(new_value => 0);
  }

  #
  # Determine which types of changes are present
  #
  my ($ret, $output) = ExecUtil::execute_captured("$eg_exec status");
  my @unmerged_files = `git ls-files --unmerged`;
  $status{has_new_unknown_files} = ($output =~ /^Unknown files:$/m);
  $status{has_unstaged_changes}  = ($output =~ /^Changed but not updated/m);
  $status{has_staged_changes}    = ($output =~ /^Changes ready to be commit/m);
  $status{has_no_changes}        =
    ($output =~ /^nothing to commit \(working directory clean\)\n\z/m);
  $status{has_unmerged_changes}  = (scalar @unmerged_files > 0);
  $status{output} = $output;

  #
  # Determine which unknown files are "newly created"
  #
  my @new_unknown = `(cd "$top_dir" && git ls-files --exclude-standard --others --directory --no-empty-directory)`;
  chomp(@new_unknown);
  if ($check_for->{unknown} && $status{has_new_unknown_files} &&
      -f "$git_dir/info/ignored-unknown") {
    my @old_unknown_files = `cat $git_dir/info/ignored-unknown`;
    chomp(@old_unknown_files);
    @new_unknown = Util::difference(\@new_unknown, \@old_unknown_files);
    $status{has_new_unknown_files} = (scalar(@new_unknown) > 0);
  }
  @new_unknown =
    Util::reroot_paths__from_to_files($top_dir, $cur_dir, @new_unknown);

  Util::pop_debug();

  if ($check_for->{no_branch}) {
    my $rc = system('git symbolic-ref -q HEAD >/dev/null');
    $status{has_no_branch} = $rc >> 8;
  }

  return \%status if !defined $clean_check_type;

  if ($clean_check_type =~ /commit/) {
    commit_error_message_checks($clean_check_type,
                                $check_for,
                                \%status,
                                \@new_unknown);
  } elsif ($clean_check_type eq "push" || $clean_check_type eq "publish") {
    push_error_message_checks($clean_check_type,
                              $check_for,
                              \%status,
                              \@new_unknown);
  } else {
    die "Unrecognized clean_check_type: $clean_check_type";
  }

  return \%status;
}

sub record_ignored_unknowns {
  # Determine some useful directories
  my ($cur_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();

  mkdir "$git_dir/info" unless -d "$git_dir/info";
  open(OUTPUT, "> $git_dir/info/ignored-unknown");
  my @unknown_files = `cd "$top_dir" && git ls-files --exclude-standard --others --directory --no-empty-directory`;
  foreach my $file (@unknown_files) {
    print OUTPUT $file;
  }
  close(OUTPUT);
}

sub parse_args {
  my (@args) = @_;

  Util::push_debug(new_value => 0);

  my (@opts, @revs, @files);
  my $stop_marker_found;

  # Get the opts
  while (@args) {
    my $arg = shift @args;
    if ($arg eq "--") {
      $stop_marker_found = 1;
      last;
    }

    if ($arg =~ /^-/) {
      push(@opts, $arg);
    } else {
      unshift(@args, $arg);
      last;
    }
  }

  # Get the revisions
  if (!$stop_marker_found) {
    while (@args) {
      my $arg = shift @args;
      if ($arg eq "--") {
        $stop_marker_found = 1;
        last;
      }

      my @revs_to_check = split('\.\.\.?', $arg);
      my $found_invalid_ref = 0;
      foreach my $ref (@revs_to_check) {
        if (!RepoUtil::valid_ref($ref)) {
          $found_invalid_ref = 1;
          last;
        }
      }
      if ($found_invalid_ref) {
        unshift(@args, $arg);
        last;
      } else {
        push(@revs, $arg);
      }
    }
  }

  # Get the files
  @files = @args;
  if (!$stop_marker_found && @files && $files[0] eq "--") {
    shift @files;
  }

  ## FIXME: I should add sanity checking: whether there are too many revs
  ## specified (or too few), whether any of @revs are also valid filenames,
  ## and maybe whether all @files refer to valid paths (maybe including
  ## only allowing files instead of also directories)

  Util::pop_debug();

  return (\@opts, \@revs, \@files);
}

sub _convert_tree_info_to_stage_info {
  my @lines = @_;
  @lines = map {m/(\d+) [a-z]+ ([0-9a-f]{40})\s+(.*)/ && "$1 $2 0\t$3\n"} @lines;
  return @lines;
}

sub _get_files_from_stage_info {
  my @lines = @_;
  chomp(@lines);
  my @files = map { m/.*[ \t]+(.*)/ && $1 } @lines;
  @files = Util::uniquify_list(@files);
  return @files;
}

sub get_revert_info {
  my ($revision, @quoted_files) = @_;

  my @new_files;           # Files to remove from staging area
  my @newish_files;        # Files to delete (can retrieve unmodified contents of
                           # these files from previous revisions)
  my @revert_files;        # Files whose contents should be reverted
  my @removed_index_files; # Files that will be restored in the index when we
                           # revert @revert_files; need to undo these restores if
                           # we're only supposed to undo unstaged changes
  my $staged_info;
  my $old_staged_info;

  @staging_info = `git ls-files --full-name -s -- @quoted_files`;
  $staged_info = join('', @staging_info);
  @staged_files = _get_files_from_stage_info(@staging_info);

  my @head_info    = `git ls-tree -r --full-name HEAD -- @quoted_files`;
  @head_info = _convert_tree_info_to_stage_info(@head_info);
  @head_files = _get_files_from_stage_info(@head_info);

  @new_files = Util::difference(\@staged_files, \@head_files);

  if ($revision ne "HEAD") {
    my @rev_info = `git ls-tree -r --full-name $revision -- @quoted_files`;
    @rev_info = _convert_tree_info_to_stage_info(@rev_info);
    $old_staged_info = join('', @rev_info);
    @revert_files = _get_files_from_stage_info(@rev_info);
    
    @newish_files = Util::difference(\@head_files, \@revert_files);
  } else {
    @revert_files = @head_files;
    $old_staged_info = join('', @head_info);
  }

  @revert_files = () if !@quoted_files;
  @removed_index_files = Util::difference(\@revert_files, \@staged_files);
  if (@removed_index_files) {
    my $stage_info_to_remove_files;
    foreach my $file (@removed_index_files) {
      $stage_info_to_remove_files .=
        "0 0000000000000000000000000000000000000000\t$file\n";
    }
    $staged_info .= $stage_info_to_remove_files;
  }

  return (\@new_files, \@newish_files, \@revert_files,
          $staged_info, $old_staged_info);
}

###########################################################################
# Util                                                                    #
###########################################################################
package Util;

# Return items in @$lista but not in @$listb
sub difference {
  my ($lista, $listb) = @_;
  my %count;

  foreach my $item (@$lista) { $count{$item}++ };
  foreach my $item (@$listb) { $count{$item}-- };

  my @ret = grep { $count{$_} == 1 } keys %count;
}

# Return items in both @$lista and in @$listb
sub intersect {
  my ($lista, $listb) = @_;
  my %original;
  my @both = ();

  map { $original{$_} = 1 } @$lista;
  @both = grep { $original{$_} } @$listb;

  return @both;
}

# Returns whether @$list contains $item
sub contains {
  my ($list, $item) = @_;
  my $found = 0;
  foreach my $elem (@$list) {
    if ($item eq $elem) {
      $found = 1;
      last;
    }
  }

  return $found;
}

sub uniquify_list {
  my @list = @_;
  my %unique;
  @unique{@list} = @list;
  return keys %unique;
}

# Have git's rev-parse command parse @args and decide which part is files,
# which is options, and which are revisions.  Further, have git translate
# revisions into full 40-character hexadecimal commit ids.
sub git_rev_parse {
  my @args = @_;

  Util::push_debug(new_value => 0);

  my ($ret, $output) = 
    ExecUtil::execute_captured("git rev-parse @args", ignore_ret => 1);
  if ($ret != 0) {
    $output =~ /^(fatal:.*)$/m   && print STDERR "$1\n";
    $output =~ /^(Use '--'.*)$/m && print STDERR "$1\n";
    exit 1;
  }
  my @opts  = split('\n', `git rev-parse --no-revs --flags    @args`);
  my @revs  = split('\n', `git rev-parse --revs-only          @args`);
  my @files = split('\n', `git rev-parse --no-revs --no-flags @args`);

  # Translate sha1sums back to human specified version of revisions.  Note that
  # something like "REV1...REV2" is translated into "SHA1 SHA2 ^SHA3", so one
  # argument may have become 3 revisions.  options and files should translate
  # one to one, though, so we can back out the original revision names.
  @revs = @args[scalar(@opts)..scalar(@args)-scalar(@files)-1];

  Util::pop_debug();

  return (\@opts, \@revs, \@files);
}

# reroot_paths__from_to_files
#   Given
#     $from   absolute path of directory files were originally relative to
#     $to     absolute path of directory you want files relative to
#     @files  list of files with paths relative to $from
#   returns a list of files with paths relative to $to
#   For example:
#     reroot_paths__from_to_files("/home", "/home/newren", ('bar', '../foo'))
#   would return
#     ('../bar', '../../foo')
#   Another example:
#     reroot_paths__from_to_files("/tmp/junk", "/tmp", ('bar', '../foo'))
#   would return
#     ('junk/bar', 'foo')
sub reroot_paths__from_to_files {
  my ($from, $to, @files) = @_;
  $from =~ s#/*$#/#;   # Make sure $from ends with exactly 1 slash
  $to   =~ s#/*$#/#;   # Make sure $to   ends with exactly 1 slash

  my @new_paths;
  foreach my $file (@files) {
    # Get the old path for the file, removing any "PATH/.." sequences
    my $oldpath = "$from$file";
    $oldpath =~ s#/+#/#;               # Remove duplicate slashes in path
    $oldpath = "$1$2" while $oldpath =~ m#^(.*?)(?!\.\./)[^/]+/\.\./(.*)$#;

    # Find what $oldpath and $to have in common
    my $common_leading_path = "";
    my $combined = "$oldpath\n$to";
    if ($combined =~ /^(.*).*\n\1.*$/) {
      $common_leading_path = $1;
    }

    # Now get the unique parts of $oldpath and $to
    my $remainder_old_path = substr($oldpath, length($common_leading_path));
    my $remainder_to       = substr($to,      length($common_leading_path));

    # Do an s/DIRECTORY_NAME/../ on remainder_to, since we want to know
    # the relative path for getting from $to to $from.
    $remainder_to =~ s#[^/]+#..#g;

    push(@new_paths, "$remainder_to$remainder_old_path");
  }

  return @new_paths;
}

{
my @debug_values;
sub push_debug {
  my @opts = @_;
  my %options = ( @opts );
  die "Called without new_value!" if !defined($options{new_value});

  my $old_value = $debug;
  push(@debug_values, $debug);
  $debug = $options{new_value};
  return $old_value;
}

sub pop_debug {
  $debug = pop @debug_values;
}
}


#*************************************************************************#
#*************************************************************************#
#*************************************************************************#
#                              MAIN PROGRAM                               #
#*************************************************************************#
#*************************************************************************#
#*************************************************************************#

package main;

sub launch {
  my $job=shift;
  my $orig_job = $job;
  $job =~ s/-/_/;  # Packages must have underscores, commands often have dashes

  # Create the action to execute
  my $action;
  $action = $job->new()                           if  $job->can("new");
  $action = subcommand->new(command => $orig_job) if !$job->can("new");

  # preprocess
  if ($action->can("preprocess")) {
    # Do not skip commands normally executed during the preprocess stage,
    # since they just gather data.
    Util::push_debug(new_value => $debug ? 1 : 0);

    print ">>Stage: Preprocess<<\n" if $debug;
    $action->preprocess();

    Util::pop_debug();
  }

  # run & postprocess
  if (!$action->can("postprocess")) {
    print ">>Stage: Run<<\n" if $debug;
    $action->run();
  } else {
    my $output = "";
    open($outfh, '>', \$output) || die "eg $job: cannot open \$outfh: $!";
    print ">>Stage: Run<<\n" if $debug;
    $action->run();
    print ">>Stage: Postprocess<<\n" if $debug;
    $action->postprocess($output);
  }

  # wrapup
  if ($action->can("wrapup")) {
    print ">>Stage: Wrapup<<\n" if $debug;
    $action->wrapup();
  }
}

sub version {
  my $version_obj = "version"->new();
  $version_obj->run();
  exit 0;
}

# User gave invalid input; print an error_message, then show command usage
sub help {
  my $error_message = shift;
  my %extra_args;

  # Clear out any arguments so that help object doesn't think we asked for
  # a specific help topic.
  @ARGV = ();

  # Print any error message we were given
  if (defined $error_message) {
    print STDERR "$error_message\n\n";
    $extra_args{exit_status} = 1;
  }

  # Now show help.
  my $help_obj = "help"->new(%extra_args);
  $help_obj->run();
}

sub main {
  #
  # Get any global options 
  #
  Getopt::Long::Configure("no_bundling", "no_permute",
                          "pass_through", "no_auto_abbrev", "no_ignore_case");
  my $result=GetOptions(
               "--debug"     => sub { $debug = 1 },
               "--help"      => sub { help() },
               "--translate" => sub { $debug = 2 },
               "--version"   => sub { version() },
                        );
  die "eg: Error parsing arguments. (Try 'eg help')\n" if !$result;
  die "eg: No subcommand specified. (Try 'eg help')\n" if @ARGV < 1;
  die "eg: Invalid argument '$ARGV[0]'. (Try 'eg help')\n"
    if ($ARGV[0] !~ m#^[a-z]#);

  #
  # Now execute the action
  #
  my $action = shift @ARGV;
  launch($action);
}

main();
