#!/usr/bin/perl

## Easy GIT (eg), a usable version of git
## Version .70
## Copyright 2008 by Elijah Newren
## 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 = ".70";
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'
      },
    merge => {
      unmodified_help => 1,
      unmodified_behavior => 1,
      section => 'projects',
      about => 'Join two or more development histories (branches) together'
      },
    mv => {
      unmodified_help => 1,
      unmodified_behavior => 1,
      section => 'modification',
      about => 'Move or rename files (or directories or symlinks)'
      },
    rebase => {
      unmodified_help => 1,
      unmodified_behavior => 1,
      extra => 1,
      section => 'timesavers',
      about => "Port local commits, making them be based on a different\n" .
               "                repository version"
      },
    remote => {
      unmodified_help => 1,
      unmodified_behavior => 1,
      extra => 1,
      section => 'collaboration',
      about => 'Manage named remote repositories',
      },
  );
}



#*************************************************************************#
#*************************************************************************#
#*************************************************************************#
#                   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 since the last commit in the working copy
      \$ git diff | git apply -R

  (Advanced) Reverse changes since the last commit to the version of foo.c
  in the staging area:
      \$ eg diff --staged | git 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';
  }
}

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

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} = "";
  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 { &$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#.*/##;
  $basename =~ s#\.git$##;
  $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);
  if ($debug == 2) {
    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]
            [--staged|-d|--dirty] [-F FILE | -m MSG | --amend]
            [--] [FILE...]

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

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

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

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

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

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

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

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

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

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

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

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

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

  -m MSG
    Use MSG as the commit message.

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

  The "-b" and "--bypass-unknown-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 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                                     -> 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, $staged) = (0, 0, 0);
  my $result = main::GetOptions(
    "--help"                      => sub { $self->help() },
    "all-known|a"                 => \$all_known,
    "bypass-unknown-check|b"      => \$bypass_unknown,
    "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);
  $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;
  $self->{'commit_flags'} .= " -a" if $all_known;

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

  die "No staged changes, but --staged given"
      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 --others --directory`;
    foreach my $file (@unknown_files) {
      print OUTPUT $file;
    }
    close(OUTPUT);
  }

  $self->{args} .= " $self->{commit_flags}";
  unshift(@ARGV, split(' ', $self->{args}));
}

###########################################################################
# 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";
  close(OUTPUT);
  
  exit $self->{exit_status};
}

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

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

sub remote_urls {
  return "
<Sorry, this help page has not been written yet.  This is just a stub.>
";
}

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;
  $topic =~ s/-/_/g if $topic;

  if (defined $topic) {
    die "No topic help for '$topic' exists.  Try 'eg help topic'.\n"
      if !$self->can($topic);
    $help_msg = $self->$topic();
  } else {
    $topic = "Topics";
    $help_msg = "
glossary      <Not yet written; this is just a stub>
remote-urls   Format for referring to remote repositories
revisions     <Not yet written; this is just a stub>
staging       <Not yet written; this is just a stub>
storage       <Not yet written; this is just a stub>
";
  }

  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
  none is specified.
";
  $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);
}

###########################################################################
# 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;
  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");
  print "Copy local repository to remote location...\n" if $debug < 2;
  ExecUtil::execute("rsync -e ssh -az --delete ./ $self->{remote_dir}");

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

  # FIXME: I should clean up git-daemon-export-ok, hooks/post-update, and
  # the files that 'man git-update-server-info' says it creates.

  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");
  die "Could not determine remote branches from repository '$repository'\n"
    if $ret != 0;
  my @remote_refs = split('\n', $output);
  if (@remote_refs > 1) {
    my @remote_branches = map { m#[0-9a-f]+.*/(.*)$# && $1 } @remote_refs;
    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;
  }
  die "'$repository' has no branches to pull!\n" if @remote_refs == 0;

  return $remote_refs[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 @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
    my $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);
    @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 branches
  that exist in both the current and remote repositories will be involved
  by default (no tags will be sent).  The --all-branches, --all-tags, and
  --mirror options exist to extend the list of changes included.  The
  --branch and --tag options can be used to narrow the changes sent to
  those explicitly specified.

  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 common branches
      \$ eg push myserver.com:git-stuff/my-repo.git

  Push commits in all branches, including branches that do not 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.repo

  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.

  --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 push, but is essentially the same other
  than presentation.  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), --all becomes the more specific
  --all-branches, 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;
}

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, $all_tags, $mirror, $thin, $repo) = (0, 0, 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,
    "--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();
  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
      RepoUtil::unset_config("default.push.url");
      RepoUtil::set_config("default.push.remote", $repository);
    } 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
    my $url = RepoUtil::get_config("branch.$branch.remote");

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

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

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

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

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

###########################################################################
# 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]
            [--in | --since] [REVISION] [--] [PATH...]

Description:
  Undoes previous changes, optionally also immediately making a commit once
  the old version of the files are obtained (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 made by this command are only performed in the
  working copy.  As an advanced option, one can instead have the reverting
  be applied to the staging area (the area tracking content explicitly
  marked by you as ready to be committted).

  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 really only a shortcut for calling eg diff and
  sending its output to eg apply (and optionally also calling eg commit).

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 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 currently in the staging area.  This is done by:
      \$ eg revert --staged --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
    Instead of changing files in the working copy, change staged files.

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

  # Safety check
  if (!@ARGV) {
    die "Aborting: no arguments specified.  If you want to revert and lose\n" .
        "all local changes in your workcopy copy, use\n" .
        "  eg revert --since HEAD\n"
  }

  my $initial_commit = RepoUtil::initial_commit();

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

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

  # 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 "Aborting: --staged is incompatible with --in\n" if $staged && $in;

  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} = '';
  $self->{staged} = '--cached' if $staged;
  $self->{revs} = "@$revs";
  $self->{revs} = "HEAD" if !@$revs;
  if ($in) {
    # One more sanity check
    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
    die "Cannot revert a merge commit without specifying a parent!\n"
      if !defined($m) && @list > 2;

    # Get the parent revision for diffing against it
    my $first_rev = $self->{revs};
    my $parent = $m || 1;
    $first_rev .= "^$parent";
    $self->{revs} = "$first_rev $self->{revs}";
  }
  $self->{files} = "";
  $self->{files} = "-- " if @$files;
  $self->{files} .= "@$files";
}

sub run {
  my $self = shift;

  if ($self->{initial_commit}) {
    die "Oops" if $self->{staged} ne "--cached";
    ExecUtil::execute("git rm $self->{staged} -q $self->{files}");
  } else {
    ExecUtil::execute(
      "git diff $self->{staged} $self->{revs} $self->{files} | " .
      "git apply $self->{staged} -R");
  }
  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->{staged}) {
      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).  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.

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
  print "(On branch $branch";
  print ", no commits yet" if $initial_commit;
  print ")\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;

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

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

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}) {
    $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 "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 "        cd $top_dir && git ls-files --exclude-standard --others --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)`;
  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();

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