#!/usr/bin/perl

## Easy GIT (eg), a usable version of git
## Version .85
## Copyright 2008 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 = ".85";
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'
    },
  };
## 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";
  }

  # Quote arguments with spaces, asterisks, or backslashes, so that when we
  # do something like
  #   system("$command hardcoded_arg1 @ARGV")
  # later, the arguments get passed correctly to the shell command $command
  my @newargs;
  foreach my $arg (@ARGV) {
    if ($arg =~ /[ "*\\]/) {
      $arg =~ s#"#\\"#;      # Backslash escape quotes
      $arg = '"'.$arg.'"';   # Quote the characters in this argument
    }
    push(@newargs, $arg);
  }
  @ARGV = @newargs;

  return $self;
}

sub help {
  my $self = shift;
  my $package_name = ref($self);
  my $git_equiv = $self->{git_equivalent};

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

  open(OUTPUT, ">&STDOUT");
  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 run {
  my $self = shift;
  my $package_name = ref($self);

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

  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
";
  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;
  }

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

###########################################################################
# 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 just a compatibility alias provided for users of
  other SCMs.  You should consider using 'git show' instead.

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:FILE".
';
  return $self;
}

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

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

  my @args;
  foreach my $arg (@ARGV) {
    if ($arg !~ /:/) {
      push(@args, "HEAD:$arg");
    } else {
      push(@args, $arg);
    }
  }

  @ARGV = @args;
}

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

  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");

  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";
      }
    }
    print OUTPUT <<EOF;
Other general changes:
  Intelligent memory of remote repositories and branches:
    eg uses the configuration variables default.branch.BRANCH.remote,
    default.branch.BRANCH.merge, and default.remote.BRANCH.url.  These are
    convenience parameters that record which repositories and branches
    users have pulled from recently, so they need not always specify this
    information (and need not take the extra steps of setting
    branch.BRANCH.(remote|merge), and can learn about remotes later).

    eg also uses the configuration variables default.push.remote,
    default.push.url, and default.push.branches.  Like the pull
    counterparts, these are convenience parameters that record which
    repositories and branches users have pushed to recently.

    eg pull and eg push will use the same defaults as git pull and git push
    (branch.BRANCH.(remote|url|merge), but use these configuration
    variables as a backup.  eg pull and eg push also sets these variables
    each time they are called with new repositories and branches.  (eg
    clone and eg publish also set these, and eg info makes use of them in
    part of its output).

    default.*.remote can be the name of a real remote (e.g. 'origin'), or
    the name of another configuration variable serving as a fake remote
    (e.g. default.*).  default.branch.BRANCH.merge has the same meaning and
    syntax as branch.BRANCH.merge, and default.*.url has the same syntax
    and meaning as remote.REMOTE.url.  default.push.branches is simply
    a set of refspecs to list on the push command line.
EOF
  }
  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
  if ($self->{command} eq 'checkout' &&    # Checkout, not clone
      (@ARGV == 1 || $ARGV[1] =~ /^-/) &&  # First form of checkout
      $ARGV[-1] =~ m#/#) {                 # 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;

  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);
  }
}

###########################################################################
# 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 does a bit more work.

  eg clone will
    (1) set up a branch for each remote branch automatically (instead of
        only creating master)
    (2) not set branch.master.(remote|merge) as git clone does
    (3) set up the configuration variables
        default.branch.BRANCH.(remote|merge) for each BRANCH.  (This is in
        lieu of (2) and part of eg's intelligent memory of remote
        repositories and branches; see 'eg changes --details' for more
        info)
    (4) set up the configuration variables default.push.remote (this
        complements the setup for pulls done in (3), so that pushes have
        good defaults too.)
";
  return $self;
}

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

  $self->{args} = "";
  $self->{bare} = 0;
  my $record_arg   = sub { $self->{args} .= " --$_[0]"; };
  my $record_args  = sub { $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;

  $self->{args} .= " $self->{repository} $self->{directory}";
}

sub run {
  my $self = shift;

  #
  # Perform the clone
  #
  my $ret = ExecUtil::execute("git clone $self->{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";
    print "    --- Default push/pull location setup ---\n";
    print "    >>Running: 'git config --remove-section branch.master'<<\n";
    print "    >>Running, for each remote branch (referred to as BRANCH):\n";
    print "        git config default.branch.BRANCH.remote origin\n";
    print "        git config default.branch.BRANCH.merge  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");
    }

    # Unset branch.$branch.(remote|merge)
    foreach my $branch (@local_branches) {
      ExecUtil::execute("git config --remove-section branch.$branch");
    }

    # Set up the configuration variables default.branch.BRANCH.(remote|merge)
    # for each BRANCH (used later as default pull locations)
    foreach my $branch (@branches) {
      chomp($branch);
      $branch =~ s#  origin/##;
      next if $branch eq "HEAD";
      RepoUtil::set_config("default.branch.$branch.remote", "origin");
      RepoUtil::set_config("default.branch.$branch.merge",  $branch);
    }

    # Set up the configuration variable default.push.remote (use later as
    # a default push location)
    RepoUtil::set_config("default.push.remote", "origin");
  }
}

###########################################################################
# 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]
            [--bypass-no-branch-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.

  --bypass-no-branch-check
    Commit local changes, even if it would not be recorded to a branch.
    Most users do not know how to recover changes that were recorded when
    there was no active branch.  You should probably create a branch before
    committing (using eg branch), but this flag exists for special cases
    (such as special splitting of commits during a rebase operation.)

  --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" and "--bypass-no-branch-check" are 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 and unstaged changes -> warn user: mix
     else if there is no active branch        -> warn user: no active branch
     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.
';
  return $self;
}

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

  #
  # Parse options
  #
  $self->{args} = "";
  my $record_arg   = sub { $self->{args} .= " --$_[0]"; };
  my $record_args  = sub { $self->{args} .= " --@_";    };
  my ($all_known, $bypass_unknown, $bypass_no_branch, $staged) = (0, 0, 0, 0);
  my $result = main::GetOptions(
    "--help"                      => sub { $self->help() },
    "all-known|a"                 => \$all_known,
    "bypass-unknown-check|b"      => \$bypass_unknown,
    "bypass-no-branch-check"      => \$bypass_no_branch,
    "staged|staged|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 { &$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;
  $check_no_branch = !$bypass_no_branch;
  $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,
                                  no_branch        => $check_no_branch,
                                  partially_staged => $check_mixed});

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

  if (!$all_known && !$staged &&
      $status->{has_unstaged_changes} && !$status->{has_staged_changes}) {
    $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) {
    open(OUTPUT, "> .git/info/ignored-unknown");
    my @unknown_files = `git ls-files --exclude-standard --others --directory --no-empty-directory`;
    foreach my $file (@unknown_files) {
      print OUTPUT $file;
    }
    close(OUTPUT);
  }

  $self->{args} .= " $self->{commit_flags}";
  unshift(@ARGV, split(' ', $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 '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'} = '
  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.
';
  return $self;
}

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

  my ($opts, $revs, $files) = Util::git_rev_parse(@ARGV);

  #
  # Parse options
  #
  $self->{'opts'} = "";
  @ARGV = @$opts;
  my ($staged, $unstaged) = (0, 0);
  my $result = main::GetOptions(
    "--help"         => sub { $self->help() },
    "staged|cached"  => \$staged,
    "unstaged"       => \$unstaged,
    );
  die "Cannot specify both --staged and --unstaged!\n" if $staged && $unstaged;
  $self->{'opts'} .= " --cached" if $staged;
  $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) {
    if (-f "$self->{git_dir}/MERGE_HEAD") {
      my $active_branch = RepoUtil::current_branch() || 'HEAD';
      my @merge_branches =
        `cat $self->{git_dir}/MERGE_HEAD | git name-rev --stdin`;
      @merge_branches = map { /^[0-9a-f]* \((.*)\)$/ && $1 } @merge_branches;
      my @targets = ($active_branch, @merge_branches);
      my $list = join(", ", @targets);
      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 = "$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" 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 allow users to easily learn git.
';

  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;
    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")) {
      die "Sorry, $subcommand is not overridden or modified for eg, and no\n" .
          "help has been written for it.  If you're feeling brave, you may\n" .
          "want to try running 'git help $subcommand'.\n";
    }

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

  # Print valid subcommands sorted by section
  open(OUTPUT, ">&STDOUT");
  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 %-10s %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 (something prevented by eg)
      * 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 revert --staged 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, ">&STDOUT");
  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/merge repositories and branches:
      eg remembers previous arguments to eg push and eg pull, since these
      arguments are often repeated.  See 'eg help pull' and 'eg help push'
      for more details.
";
  $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 $current_branch = ExecUtil::output("git symbolic-ref HEAD |sed -e s#.*/##");

  #
  # 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};
    }
  }

  # Default push repo
  my $default_push_repo;
  $default_push_repo = RepoUtil::get_config("branch.$current_branch.remote");
  if (!$default_push_repo) {
    my $url = RepoUtil::get_config("default.push.remote");
    if (defined $url && $url eq "default.push.url") {
      $url = RepoUtil::get_config($url) ;
    }
    if (defined $url && $debug < 2) {
      print "Default remote repository to push to: $url\n";
    }
  }

  #
  # Stats for the current 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: $current_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 push repo
  if ($default_push_repo && $debug < 2) {
    print "  Default remote repository to push to:   $default_push_repo\n";
  }

  # Default pull repo & branch
  my ($default_repo, $default_merge);
  $default_repo = RepoUtil::get_config("branch.$current_branch.remote");
  if (!$default_repo) {
    $default_repo = 
      RepoUtil::get_config("default.branch.$current_branch.remote");
    if (defined $default_repo && $default_repo =~ /^default\.remote\./) {
      $default_repo = RepoUtil::get_config("default.remote.$current_branch.url")
    }
  }
  $default_merge = RepoUtil::get_config("branch.$current_branch.merge") ||
                   RepoUtil::get_config("default.branch.$current_branch.merge");
  if ($default_repo && $debug < 2) {
    print "  Default remote repository to pull from: $default_repo\n";
  }
  if ($default_merge && $debug < 2) {
    $default_merge =~ s#refs/heads/##;
    print "  Default remote branch to merge from:    $default_merge\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 --full-name --name-only HEAD " .
                    " | grep '/'" .
                    " | sed -e \"s#\(.*\)/.*#\1#\" " .
                    " | sort " .
                    " | uniq " .
                    " | 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?
}

###########################################################################
# 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 the same as
    git log | git name-rev --stdin --refs=$(git symbolic-ref HEAD) | less

  If I could figure out how to make git log show references relative to
  "HEAD" when not working on any (named) branch (i.e. "when the HEAD is
  detached", to put it in gitspeak), I would do that too.  Unfortunately, I
  have not figured that out yet.
';
  return $self;
}

sub run {
  my $branch = RepoUtil::current_branch();

  if ($debug) {
    print "    >>Running: git log @ARGV | \\\n" .
       "               git name-rev --stdin --refs=refs/heads/$branch | \\\n" .
       "               less\n";
    return if $debug == 2;
  }

  open(INPUT, "git log @ARGV | " .
              "git name-rev --stdin --refs=refs/heads/$branch |");
  open(OUTPUT, "| less");
  while (<INPUT>) {
    print OUTPUT;
  }
  close(INPUT);
  close(OUTPUT);
}

###########################################################################
# 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
      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 does some extra work so that future pushes and pulls will
  use the published repository by default.  It does this by setting the
  default.branch.BRANCH.(remote|merge) and default.push.(url|remote)
  variables.  See "eg changes --details" for more information about these
  (unique to eg) configuration variables.
';
  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});
  }
}

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");
  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.

  #
  # Explain the next two steps if we're in debug mode...
  #
  print "  >>Setting up default push & pull locations for the local repo,<<\n".
        "  >>so that it pushes/pulls from the published repository:      <<\n"
    if $debug;

  #
  # Set up the configuration variables default.branch.BRANCH.(remote|merge)
  # for each BRANCH (used later as default 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("default.branch.$branch.remote", $self->{remote_dir});
    RepoUtil::set_config("default.branch.$branch.merge",  $branch);
    RepoUtil::unset_config("default.remote.$branch.url");
  }

  #
  # Set up the configuration variable default.push.remote (use later as
  # a default push location)
  #
  RepoUtil::set_config("default.push.url",    $self->{remote_dir});
  RepoUtil::set_config("default.push.remote", "default.push.url");
  RepoUtil::unset_config("default.push.branches");

  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 the repository to pull the changes from is not specified, the last
  repository specified will be reused.  Run 'eg info' to be reminded which
  repository this is.

  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 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 very similar, but eg pull does a bit more work.

  eg pull generalizes the repository fallback of git pull (namely 'origin')
  to the last repository used, and also adds a fallback of the last branch
  used.  It does so via the configuration variables
  default.branch.BRANCH.(remote|merge) and default.remote.BRANCH.url (see
  'eg changes --details' for more info).  Note that eg pull also updates
  these configuration variables whenver a repository (or branch) are
  specified on the command line.

  eg also introduces a new option named --branch in order to (1) avoid the
  need to explain refspecs too early to users, (2) to make command line
  examples more self-documenting.  eg still accepts refspecs at the end of
  the commandline the same as git pull, they simply are deferred to the git
  manpages.
";
  return $self;
}

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);

  #
  # Parse options
  #
  $self->{args} = "";
  my $record_arg  = 
    sub { my $prefix = "";
          $prefix = "no-" if defined $_[1] && $_[1] == 0;
          $self->{args} .= " --$prefix$_[0]";
        };
  my $record_args = sub { $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 $url;  # Used if $repository is blank or not defined
  my @git_refspecs = @ARGV;

  # Record the tags or no-tags arguments
  $self->{args} .= " --tags"    if $all_tags;
  $self->{args} .= " --no-tags" if $no_tags;

  #
  # Get the repository to pull from
  #
  Util::push_debug(new_value => 0);
  my $branch = RepoUtil::current_branch() || "HEAD";
  Util::pop_debug();
  if ($repository) {
    # Repository option #1: The one they listed on the command line
    $self->{args} .= " $repository";

    #
    # Remember the repository for the next pull...
    #
    if (system("git remote | grep '^$repository\$' >/dev/null") == 0) {
      # The remote repository is a remote name, not a url
      RepoUtil::unset_config("default.remote.$branch.url");
      RepoUtil::set_config("default.branch.$branch.remote", $repository);
    } else {
      # The remote repository is a url
      $repository = main::abs_path($repository) if -d $repository;
      RepoUtil::set_config("default.remote.$branch.url", $repository);
      RepoUtil::set_config("default.branch.$branch.remote",
                           "default.remote.$branch");
    }
    # Don't reuse merge branch from a different repository
    RepoUtil::unset_config("default.branch.$branch.merge")
  } else {
    # Repository option #2: branch.<active branch>.remote variable
    $url = RepoUtil::get_config("branch.$branch.remote");

    # Repository option #3: default.branch.<active branch>.remote variable
    $url = RepoUtil::get_config("default.branch.$branch.remote") if !$url;
    $url = RepoUtil::get_config("$url.url") if $url && $url =~ /^default\.remote\./;

    die "No repository to pull from specified!\n" if !$url;

    $self->{args} .= " $url";
  }

  #
  # Get the branch(es) to pull from
  #
  push(@branches, @git_refspecs);
  my $merge_branch = RepoUtil::get_config("branch.$branch.merge");
  my $defaults = RepoUtil::get_config("default.branch.$branch.merge");
  my @default_branches;
  @default_branches = split(' ', $defaults) if $defaults;
  if (@branches) {
    # Specified on the command line; remember this for later
    RepoUtil::set_config("default.branch.$branch.merge", "@branches");
  } elsif (!@branches &&  @default_branches && !@tags && !$merge_branch) {
    @branches = @default_branches
  } elsif (!@branches && !@default_branches && !@tags && !$merge_branch) {
    my $only_branch = _get_only_branch($repository || $url);
    @branches = ($only_branch);
  }

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

  $self->{args} =~ s/^\s+//;
}

sub run {
  my $self = shift;

  return ExecUtil::execute("git pull $self->{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 to a fellow
  developer's repository and working copy, 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 the repository to push the changes to is not specified, the last
  repository specified will be reused.  Run 'eg info' to be reminded which
  repository this is.

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 last repository we pushed to
      \$ eg push --all-branches --all-tags

  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.  refspecs are put off until later with the --branch tag being
  introduced to specify branch(es) to push (which also makes push commands
  more self-documenting) and eg push tries to save the user some work by
  remembering the last pushed-to repository instead of always defaulting to
  "origin".
';
  return $self;
}

# _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);

  #
  # Parse options
  #
  $self->{args} = "";
  my $record_arg  = sub { $self->{args} .= " --$_[0]"; };
  my $record_args = sub { $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});
  }

  $self->{args} .= " --all"    if $all_branches;
  $self->{args} .= " --tags"   if $all_tags;
  $self->{args} .= " --mirror" if $mirror;

  #
  # Get the repository to push to, including more general fallbacks
  #
  Util::push_debug(new_value => 0);
  my $branch = RepoUtil::current_branch() || "HEAD";
  Util::pop_debug();

  my $remote;
  if ($repository) {
    # Repository option #1: The one they listed on the command line
    $self->{args} .= " $repository";

    #
    # Remember the repository for the next push...
    #
    if (system("git remote | grep '^$repository\$' >/dev/null") == 0) {
      # The remote repository is a remote name, not a url
      $remote = $repository;
      $repository = `git config --get remote.$repository.url`;
      chomp($repository);

      # Record the new default push location
      RepoUtil::unset_config("default.push.url");
      RepoUtil::set_config("default.push.remote", $remote);
    } else {
      # The remote repository is a url
      $repository = main::abs_path($repository) if -d $repository;
      RepoUtil::set_config("default.push.url", $repository);
      RepoUtil::set_config("default.push.remote", "default.push.url");
    }
    # Don't reuse push branches from a different repository
    RepoUtil::unset_config("default.push.branches")
  } elsif (!$repo) {
    # Repository option #2: branch.<active branch>.remote variable
    $remote = RepoUtil::get_config("branch.$branch.remote");
    if ($remote) {
      $repository = `git config --get remote.$remote.url`;
      chomp($repository);
    }

    # Repository option #3: default.push.remote variable
    if (!$remote) {
      $default = RepoUtil::get_config("default.push.remote");
      if ($default eq "default.push.url") {
        $repository = RepoUtil::get_config($default);
      } else {
        $remote = $default;
      }
    }

    die "No repository to push to specified!\n" if !$repository;

    if ($remote) {
      $self->{args} .= " $remote";
    } else {
      $self->{args} .= " $repository ";
    }
  }

  #
  # Prevent pushing to a non-bare repository...in most cases
  #
  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).  See
  eg help topic refspecs
for advanced methods of pushing (and pulling), including ways to override
this check and deal with the consequences.
EOF
    exit 1;
  }

  #
  # Get the branch(es) to push
  #
  push(@branches, @git_refspecs);
  my $defaults = RepoUtil::get_config("default.push.branches");
  my @default_branches;
  @default_branches = split(' ', $defaults) if $defaults;
  if (@branches) {
    # Specified on the command line; remember this for later
    RepoUtil::set_config("default.push.branches", "@branches");
  } elsif (!@branches &&  @default_branches && !@tags) {
    @branches = @default_branches
  } elsif (!@branches && !$all_branches && !$matching_branches && !@tags) {
    push @branches, $branch;
  }

  $self->{args} .= " @branches";
  foreach my $tag (@tags) {
    $self->{args} .= " tag $tag";
  }

  $self->{args} =~ s/^\s+//;
}

sub run {
  my $self = shift;

  return ExecUtil::execute("git push $self->{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 { $self->{args} .= " --$_[0]"; };
  my $record_args = sub { $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 { &$record_args(@_) },
    "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;
  $self->{args} .= " $since" if defined $since;
  $self->{args} .= " @ARGV";
}

sub run {
  my $self = shift;

  return ExecUtil::execute("git rebase $self->{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(
    initial_commit_error_msg => "Error: No recorded commits to forget.",
    @_);
  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);

  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(@_);
  bless($self, $class);
  $self->{'help'} = "
Usage:
  eg revert [--commit | --no-commit] [-m PARENT_NUMBER] [--staged | --unstaged]
            [--in | --since] [REVISION] [--] [PATH...]

Description:
  Undoes previous changes, optionally also immediately making 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.

  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 committted; 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).

  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, then the changes since the last
  commit on the current branch will be reverted (i.e. it behaves like
  \"--since HEAD\" was passed).

  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.

  Finally, revert can operate on a subset of paths if specified.

  To avoid accidental loss of local changes, nothing will be done when no
  arguments are specified.

  Note that eg revert is mostly a convenience wrapper around combinations
  of diff and apply; the diff and apply commands of eg can be used directly
  to obtain finer-grained control over the exact changes reverted.

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 in HEAD~4 relative to its second
  parent.  This can be accomplished as follows:
      \$ eg revert -m 2 --in HEAD~4
  
  (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:
  --commit
    Commit your files immediately after reverting.  There must be no local
    changes prior to running revert if this option is used.  --commit is not
    the default.

  --no-commit
    The opposite of --commit, this flag is the default and exists just for
    completeness.

  -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.

  --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.

  --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.

  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.

  --
    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'} = '
  git revert is a strict subset of the capabilities of eg revert; eg revert
  also contains part of the abilities of the git checkout and git reset
  commands (namely, the second form of each), as well as a couple new
  things to round it all out.

  Due to these changes, eg revert should be much more welcoming to users of
  svn, hg, bzr, or darcs (all of which assume the --since behavior for
  revert), while also still having the capabilities of git revert (which
  assumes the --in behavior of revert).  This also makes 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.)

  The biggest surprises for users of git revert are:
    1) They have to specify the --in flag
    2) No commit is made by default; --commit must be specified to get one
  Neither of these will cause data loss; they will just require a bit more
  work.

  It seems that perhaps eg revert should 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.
';
  return $self;
}

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

  my $initial_commit = RepoUtil::initial_commit();

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

  # Parsing revs and files
  my ($opts, $revs, $files) = Util::git_rev_parse(@ARGV);

  # Safety check
  if (!@$revs && !@$files) {
    if (!$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;
    }
  }

  # Sanity checks
  die "Cannot specify -m without specifying --in.\n" if !$in && defined($m);
  die "Unrecognized options: @$opts\n" if @$opts;
  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);
  die "You must specify either --in or --since when specifying a revision\n"
    if ($in == -1 && @$revs);
  $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);
    $self->{initial_commit} = 1;
  }

  # Set up flags to pass to diff/apply/commit
  $self->{commit} = $commit;
  $self->{staged} = $staged;
  $self->{unstaged} = $unstaged;
  $self->{in} = $in;
  $self->{revs} = "@$revs";
  $self->{revs} = "HEAD" if !@$revs;
  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}";
  }
  $self->{files} = "";
  $self->{files} = "-- " if @$files;
  $self->{files} .= "@$files";
}

sub run {
  my $self = shift;

  #
  # Revert changes the user requested
  #
  if ($self->{initial_commit}) {
    # Initial commit: Must use rm command instead of piping diff to apply -R
    ExecUtil::execute("git rm --cached -q $self->{files}", ignore_ret => 1);
  } else {
    # Standard case: Pipe output of diff to apply -R...for both index &
    # working copy
    my @flags;
    push(@flags, "--cached") if $self->{staged};
    push(@flags, "")         if $self->{unstaged};

    foreach my $flag (@flags) {

      my $diff_flag = $self->{in} ? "" : $flag;

      # Print out the (nearly) equivalent commands if the user asked for
      # debugging information
      if ($debug) {
        print "git diff $diff_flag $self->{revs} $self->{files} | " .
              "git apply $flag -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
      # and actual diff to revert.
      if ($debug < 2) {
        open(DIFF, "git diff $diff_flag $self->{revs} $self->{files} |");
        my @output = <DIFF>;
        my $diff = join("", @output);
        close(DIFF);
        $ret = $?;
        exit $ret >> 8 if $ret;

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

  #
  # Make a commit if the user requested one
  #
  if ($self->{commit}) {
    # We could just execute "eg commit $self->{staged}" if we 
    # $self->{staged} =~ s/cached/staged/, but that isn't as helpful for
    # debug output anyway, so split it into two commands...
    if (!$self->{unstaged}) {
      ExecUtil::execute("git commit")
    } else {
      ExecUtil::execute("git commit -a")
    }
  }
}

###########################################################################
# 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 revert --staged 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).
";
  return $self;
}

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

  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] | save DESCRIPTION | apply [DESCRIPTION] |
            show [DESCRIPTION] | clear)
  eg stash

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.

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.

  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 [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 \"--\".

  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);
    }
  }

  # Show a help message if they picked a bad stash subaction.
  if (! grep {$_ eq $self->{subcommand}} qw(list show apply clear save)) {
    $self->help();
  }

  # Translate the description passed to apply or show into a reflog reference
  if ((grep {$_ eq $self->{subcommand}} qw(apply show)) && 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 @lines = split('\n', $output);
  my $cur_state = 0;
  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"):';
    }

    # If we're inside a section type, parse it
    if ($cur_state > 0) {
      my @section_files;
      my $hint = shift @lines;
      shift @lines; # Get rid of blank line

      $line = shift @lines;
      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      => $hint,
                             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";
  }

  # 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 $ret = ExecUtil::execute("git show-ref $ARGV[0] > /dev/null 2>&1",
                                ignore_ret => 1);
    Util::pop_debug();
    die "Invalid branch: $ARGV[0]\n" if $ret != 0;
  }

  # 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);

  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;
}

###########################################################################
# 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.

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.

  eg update does not accept any options.  Period.  Well, okay, other than
  --help.
';
  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.
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_unknown_files} ||
    $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
    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 $url = RepoUtil::get_config("branch.$branch.remote");
  if (!$url) {
    $url = RepoUtil::get_config("default.branch.$branch.remote") if !$url;
    if (defined $url &&  $url =~ /^default\.remote\./) {
      $url = RepoUtil::get_config("$url.url");
    }
  }
  if (!$url) {
    my $ret = ExecUtil::execute("git remote | grep origin > /dev/null",
                                ignore_ret => 1);
    $url = "origin" if $ret == 0;
  }
  die "No repository to update from (perhaps try eg pull instead?)\n" if !$url;
  $self->{repository} = $url;
  $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) {
    my $defaults = RepoUtil::get_config("default.branch.$branch.merge");
    my @default_branches;
    @default_branches = split(' ', $defaults) if $defaults;
    if (@default_branches == 1) {
      $merge_branch = $defaults;
    }
  }
  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) {
        $merge_branch = $remote_refs[0];
      }
    }
  }
  die "No remote branch to update from (perhaps try eg pull instead?\n"
    if !$merge_branch;
  $self->{merge_branch} = $merge_branch;
}

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

  # Should only do the reset if the fetch worked...?
  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}");
    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");
  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 {
  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 {
  Util::push_debug(new_value => 0);

  my $curdir = main::getcwd();

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

  my $gitdir = git_dir();

  Util::pop_debug();

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

sub initial_commit {
  my @output = `git show-ref -h`;
  foreach my $line (@output) {
    next if $line !~ /^[0-9a-f]+ HEAD$/;

    # We found a commit id for HEAD, so this must not be the initial commit
    return 0;  
  }

  # We couldn't find a commit id for HEAD, so this must be the initial commit
  return 1;
}

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);
}

# 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_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";  # $file has a newline
    }
    exit 1;
  }
  elsif ($check_for->{unknown} && $status->{has_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";  # $file has a newline
    }
    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_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";  # $file has a newline
    }
    exit 1;
  }
  elsif ($check_for->{unknown} && $status->{has_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";  # $file has a newline
    }
    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_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);

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

  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;
}


###########################################################################
# 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;
}

# 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 @ARGV", 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    @ARGV`);
  my @revs  = split('\n', `git rev-parse --revs-only          @ARGV`);
  my @files = split('\n', `git rev-parse --no-revs --no-flags @ARGV`);

  Util::pop_debug();

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

{
my @debug_values;
sub push_debug {
  my @opts = @_;
  my %options = ( @opts );
  die "Called without new_value!" if !defined($options{new_value});

  push(@debug_values, $debug);
  $debug = $options{new_value};
}

sub pop_debug {
  $debug = pop @debug_values;
}
}


#*************************************************************************#
#*************************************************************************#
#*************************************************************************#
#                              MAIN PROGRAM                               #
#*************************************************************************#
#*************************************************************************#
#*************************************************************************#

package main;

sub launch {
  my $job=shift;

  # Create the action to execute
  my $action;
  $action = $job->new()                      if  $job->can("new");
  $action = subcommand->new(command => $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]#);

  #
  # Set up an interrupt signal handler
  #
  $SIG{INT}=sub {
    print STDERR "eg: interrupted\n";
    exit 2;
  };

  #
  # Now execute the action
  #
  my $action = shift @ARGV;
  launch($action);
}

main();
