h8rt3rmin8r

easygit.perl

Oct 16th, 2018
258
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/perl -w
  2.  
  3. ## Easy GIT (eg), a frontend for git designed for former cvs and svn users
  4. ## Version 1.7.5.2
  5. ## Copyright 2008-2013 by Elijah Newren and others
  6. ## Licensed under GNU GPL, version 2.
  7.  
  8. ## To use eg, simply stick this file in your path.  Then fire off an
  9. ## 'eg help' to get oriented.  You may also be interested in
  10. ##   http://www.gnome.org/~newren/eg/git-for-svn-users.html
  11. ## to get a comparison to svn in terms of capabilities and commands.
  12. ## Webpage for eg: http://www.gnome.org/~newren/eg
  13.  
  14. use strict;
  15. use warnings;
  16.  
  17. package main;
  18.  
  19. use Getopt::Long;
  20. use Cwd qw(getcwd abs_path);
  21. use List::Util qw(max);
  22. use File::Temp qw/ tempfile /;
  23.  
  24. # configurables
  25. my $DEBUG = $ENV{EASYGIT_DEBUG} || 0;
  26. my $GIT_CMD = $ENV{EASYGIT_GIT_CMD} || "git";  # Includes any global args, thus "git --exec-path=..."
  27. my $USE_PAGER = exists($ENV{EASYGIT_USE_PAGER}) ? $ENV{EASYGIT_USE_PAGER} : -1;
  28.  
  29. # globals :-(
  30. my $OUTFH;
  31. my $VERSION = "1.7.5.2";
  32. my $EG_EXEC = abs_path($0);
  33. my %ALIAS;
  34. my %COMMAND;    # command=>{section, short_description} mapping
  35. my $SECTION = {
  36.   'creation' =>
  37.     { order => 1,
  38.       desc  => 'Creating repositories',
  39.     },
  40.   'discovery' =>
  41.     { order => 2,
  42.       desc  => 'Obtaining information about changes, history, & state',
  43.     },
  44.   'modification' =>
  45.     { order => 3,
  46.       desc  => 'Making, undoing, or recording changes',
  47.     },
  48.   'projects' =>
  49.     { order => 4,
  50.       desc  => 'Managing branches',
  51.     },
  52.   'collaboration' =>
  53.     { order => 5,
  54.       desc  => 'Collaboration'
  55.     },
  56.   'timesavers' =>
  57.     { order => 6,
  58.       desc  => 'Time saving commands'
  59.     },
  60.   'compatibility' =>
  61.     { order => 7,
  62.       extra => 1,
  63.       desc  => 'Commands provided solely for compatibility with other ' .
  64.                'prominent SCMs'
  65.     },
  66.   'misc' =>
  67.     { order => 8,
  68.       extra => 1,
  69.       desc  => 'Miscellaneous'
  70.     },
  71.   };
  72. my ($CURDIR, $TOPDIR, $GITDIR);
  73.  
  74. ## Commands to list in help even though we haven't overridden the git versions
  75. ## (yet, in most cases)
  76. INIT {
  77.   %COMMAND = (
  78.     blame => {
  79.       unmodified_help => 1,
  80.       unmodified_behavior => 1,
  81.       extra => 1,
  82.       section => 'discovery',
  83.       about => 'Show what version and author last modified each line of a file'
  84.       },
  85.     bisect => {
  86.       unmodified_help => 1,
  87.       unmodified_behavior => 1,
  88.       section => 'timesavers',
  89.       about => 'Find the change that introduced a bug by binary search'
  90.       },
  91.     grep => {
  92.       unmodified_help => 1,
  93.       unmodified_behavior => 1,
  94.       extra => 1,
  95.       section => 'discovery',
  96.       about => 'Print lines of known files matching a pattern'
  97.       },
  98.     mv => {
  99.       unmodified_help => 1,
  100.       unmodified_behavior => 1,
  101.       section => 'modification',
  102.       about => 'Move or rename files (or directories or symlinks)'
  103.       },
  104.   );
  105. }
  106.  
  107.  
  108.  
  109. #*************************************************************************#
  110. #*************************************************************************#
  111. #*************************************************************************#
  112. #                   CLASSES DEFINING ACTIONS TO PERFORM                   #
  113. #*************************************************************************#
  114. #*************************************************************************#
  115. #*************************************************************************#
  116.  
  117. ###########################################################################
  118. # subcommand, a base class for all eg subcommands                         #
  119. ###########################################################################
  120. package subcommand;
  121. sub new {
  122.   my $class = shift;
  123.   my $self = {git_repo_needed => 0, @_};  # Hashref initialized as we're told
  124.   bless($self, $class);
  125.  
  126.   # Our "see also" section in help usually references the same subsection
  127.   # as our class name.
  128.   $self->{git_equivalent} = ref($self) if !defined $self->{git_equivalent};
  129.  
  130.   # We allow direct instantiation of the subcommand class only if they
  131.   # provide a command name for us to pass to git.
  132.   if (ref($class) eq "subcommand" && !defined $self->{command}) {
  133.     die "Invalid subcommand usage"
  134.   }
  135.  
  136.   # Most commands must be run inside a git working directory
  137.   unless (!$self->{git_repo_needed} || (@ARGV > 0 && $ARGV[0] eq "--help")) {
  138.     $self->{git_dir} = RepoUtil::git_dir();
  139.     if (!defined $self->{git_dir}) {
  140.       # Couldn't find git repository.  That could be for any of three reasons:
  141.  
  142.       # 1) Is 'git' even in the user's PATH?
  143.       my @paths_to_git = grep {-x "$_/git"} split(/:/, $ENV{PATH});
  144.       if (!@paths_to_git) {
  145.         die "Error: Cannot find git in your PATH!\n";
  146.       }
  147.  
  148.       # 2) Does 'git' even work (possible bad installation)?
  149.       my ($ret, $output) =
  150.         ExecUtil::execute_captured("$GIT_CMD --version", ignore_ret => 1);
  151.       if ($ret != 0 || $output !~ /^git version .*$/) {
  152.       die "Error: Cannot execute git (check your git installation)!\n";
  153.       }
  154.  
  155.       # 3) They just aren't in a project tracked by git
  156.       die "Error: Must be run inside a git-tracked working directory!\n";
  157.     }
  158.   }
  159.  
  160.   # Many commands do not work if no commit has yet been made
  161.   if ($self->{initial_commit_error_msg} &&
  162.       RepoUtil::initial_commit() &&
  163.       (@ARGV < 1 || $ARGV[0] ne "--help")) {
  164.     die "$self->{initial_commit_error_msg}\n";
  165.   }
  166.  
  167.   return $self;
  168. }
  169.  
  170. sub help {
  171.   my $self = shift;
  172.   my $package_name = ref($self);
  173.   $package_name =~ s/_/-/;  # Packages use underscores, commands use dashes
  174.  
  175.   my $git_equiv = $self->{git_equivalent};
  176.   $git_equiv =~ s/_/-/;  # Packages use underscores, commands use dashes
  177.  
  178.   if ($package_name eq "subcommand") {
  179.     exit ExecUtil::execute("$GIT_CMD $self->{command} --help")
  180.   }
  181.  
  182.   $ENV{"LESS"} = "FRSX" unless defined $ENV{"LESS"};
  183.   my $less = ($USE_PAGER == 1) ? "less" :
  184.              ($USE_PAGER == 0) ? "cat" :
  185.              `$GIT_CMD config core.pager` || "less";
  186.   chomp($less);
  187.   open(OUTPUT, "| $less");
  188.   print OUTPUT "$package_name: $COMMAND{$package_name}{about}\n";
  189.   print OUTPUT $self->{'help'};
  190.   print OUTPUT "\nDifferences from git $package_name:";
  191.   print OUTPUT "\n  None.\n" if !defined $self->{'differences'};
  192.   print OUTPUT $self->{'differences'} if defined $self->{'differences'};
  193.   if ($git_equiv) {
  194.     print OUTPUT "\nSee also\n";
  195.     print OUTPUT <<EOF;
  196.   Run 'git help $git_equiv' for a comprehensive list of options available.
  197.   eg $package_name is designed to accept the same options as git $git_equiv, and
  198.   with the same meanings unless specified otherwise in the above
  199.   "Differences" section.
  200. EOF
  201.   }
  202.   close(OUTPUT);
  203.   exit 0;
  204. }
  205.  
  206. sub preprocess {
  207.   my $self = shift;
  208.  
  209.   return if (scalar(@ARGV) > 0 && $ARGV[0] eq "--");
  210.   my $result=main::GetOptions("--help" => sub { $self->help() });
  211. }
  212.  
  213. sub run {
  214.   my $self = shift;
  215.   my $package_name = ref($self);
  216.  
  217.   my $subcommand =
  218.     $package_name eq "subcommand" ? $self->{'command'} : $package_name;
  219.  
  220.   @ARGV = Util::quote_args(@ARGV);
  221.   return ExecUtil::execute("$GIT_CMD $subcommand @ARGV", ignore_ret => 1);
  222. }
  223.  
  224. ###########################################################################
  225. # add                                                                     #
  226. ###########################################################################
  227. package add;
  228. @add::ISA = qw(subcommand);
  229. INIT {
  230.   $COMMAND{add} = {
  231.     unmodified_behavior => 1,
  232.     section => 'compatibility',
  233.     about => 'Mark content in files as being ready for commit'
  234.     };
  235. }
  236.  
  237. sub new {
  238.   my $class = shift;
  239.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  240.   bless($self, $class);
  241.   $self->{'help'} = "
  242. Description:
  243.  eg add is provided for backward compatibility; it has identical usage and
  244.  functionality as 'eg stage'.  See 'eg help stage' for more details.
  245. ";
  246.   return $self;
  247. }
  248.  
  249. ###########################################################################
  250. # apply                                                                   #
  251. ###########################################################################
  252. package apply;
  253. @apply::ISA = qw(subcommand);
  254. INIT {
  255.   $COMMAND{apply} = {
  256.     about => 'Apply a patch in a git repository'
  257.   };
  258. }
  259.  
  260. sub new {
  261.   my $class = shift;
  262.   my $self = $class->SUPER::new(git_repo_needed => 0, @_);
  263.   bless($self, $class);
  264.   $self->{'help'} = "
  265. Usage:
  266.  eg apply [--staged] [-R | --reverse] [-pNUM]
  267.  
  268. Description:
  269.  Applies a patch to a git repository.
  270.  
  271. Examples:
  272.  Reverse changes in foo.patch
  273.      \$ eg apply -R foo.patch
  274.  
  275.  (Advanced) Reverse changes since the last commit to the version of foo.c
  276.  in the staging area (equivalent to 'eg revert --staged foo.c'):
  277.      \$ eg diff --staged foo.c | eg apply -R --staged
  278.  
  279. Options:
  280.  --staged
  281.    Apply the patch to the staged (explicitly marked as ready to be committed)
  282.    versions of files
  283.  
  284.  --reverse, -R
  285.    Apply the patch in reverse.
  286.  
  287.  -pNUM
  288.    Remove NUM leading paths from filenames.  For example, with the filename
  289.      /home/user/bla/foo.c
  290.    using -p0 would leave the name unmodified, using -p1 would yield
  291.      home/user/bla/foo.c
  292.    and using -p3 would yield
  293.      bla/foo.c
  294. ";
  295.   $self->{'differences'} = '
  296.  eg apply is identical to git apply except that it accepts --staged as a
  297.  synonym for --cached.
  298. ';
  299.   return $self;
  300. }
  301.  
  302. sub preprocess {
  303.   my $self = shift;
  304.  
  305.   my $result = main::GetOptions("--help" => sub { $self->help() });
  306.   foreach my $i (0..$#ARGV) {
  307.     $ARGV[$i] = "--cached" if $ARGV[$i] eq "--staged";
  308.   }
  309. }
  310.  
  311. ###########################################################################
  312. # branch                                                                  #
  313. ###########################################################################
  314. package branch;
  315. @branch::ISA = qw(subcommand);
  316. INIT {
  317.   $COMMAND{branch} = {
  318.     section => 'projects',
  319.     about => 'List, create, or delete branches'
  320.     };
  321.   $ALIAS{'br'} = "branch";
  322. }
  323.  
  324. sub new {
  325.   my $class = shift;
  326.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  327.   bless($self, $class);
  328.   $self->{'help'} = "
  329. Usage:
  330.  eg branch [-r]
  331.  eg branch [-s] NEWBRANCH [STARTPOINT]
  332.  eg branch -d BRANCH
  333.  
  334. Description:
  335.  List the existing branches that you can switch to, create a new branch,
  336.  or delete an existing branch.  For switching the working copy to a
  337.  different branch, use the eg switch command instead.
  338.  
  339.  Note that branches are local; creation of branches in a remote repository
  340.  can be accomplished by first creating a local branch and then pushing the
  341.  new branch to the remote repository using eg push.
  342.  
  343. Examples
  344.  List the available local branches
  345.      \$ eg branch
  346.  
  347.  Create a new branch named random_stuff, based off the last commit.
  348.      \$ eg branch random_stuff
  349.  
  350.  Create a new branch named sec-48 based off the 4.8 branch
  351.      \$ eg branch sec-48 4.8
  352.  
  353.  Delete the branch named bling
  354.      \$ eg branch -d bling
  355.  
  356.  Create a new branch named my_fixes in the default remote repository
  357.      \$ eg branch my_fixes
  358.      \$ eg push --branch my_fixes
  359.  
  360.  (Advanced) Create a new branch named bling, based off the remote tracking
  361.  branch of the same name
  362.      \$ eg branch bling origin/bling
  363.  See 'eg remote' for more details about setting up named remotes and
  364.  remote tracking branches, and 'eg help topic storage' for more details on
  365.  differences between branches and remote tracking branches.
  366.  
  367. Options:
  368.  -d
  369.    Delete specified branch
  370.  
  371.  -r
  372.    List remote tracking branches (see 'eg help topic storage') for more
  373.    details.  This is useful when using named remote repositories (see 'eg
  374.    help remote')
  375.  
  376.  -s
  377.    After creating the new branch, switch to it
  378. ";
  379.   $self->{'differences'} = '
  380.  eg branch is identical to git branch other than adding a new -s option for
  381.  switching to a branch immediately after creating it.
  382. ';
  383.   return $self;
  384. }
  385.  
  386. sub run {
  387.   my $self = shift;
  388.  
  389.   my $switch = 0;
  390.   if (scalar(@ARGV) > 1 && $ARGV[0] eq "-s") {
  391.     $switch = 1;
  392.     shift @ARGV;
  393.   }
  394.  
  395.   @ARGV = Util::quote_args(@ARGV);
  396.   my $ret = ExecUtil::execute("$GIT_CMD branch @ARGV", ignore_ret => 1);
  397.   $ret = ExecUtil::execute("$GIT_CMD checkout $ARGV[0]", ignore_ret => 1)
  398.     if ($switch && $ret == 0);
  399.   return $ret;
  400. }
  401.  
  402. ###########################################################################
  403. # bundle                                                                  #
  404. ###########################################################################
  405. package bundle;
  406. @bundle::ISA = qw(subcommand);
  407. INIT {
  408.   $COMMAND{bundle} = {
  409.     extra => 1,
  410.     section => 'collaboration',
  411.     about => 'Pack repository updates (or whole repository) into a file'
  412.     };
  413. }
  414.  
  415. sub new {
  416.   my $class = shift;
  417.   my $self = $class->SUPER::new(
  418.     git_repo_needed => 1,
  419.     initial_commit_error_msg => "No bundles can be created until a commit " .
  420.                                 "has been made.",
  421.     @_
  422.     );
  423.   bless($self, $class);
  424.   $self->{'help'} = "
  425. Usage:
  426.  eg bundle create FILENAME [REFERENCES]
  427.  eg bundle create-update NEWFILENAME OLDFILENAME [REFERENCES]
  428.  eg bundle verify FILENAME
  429.  
  430. Description:
  431.  Bundle creates a file which contains a repository, or a subset thereof.
  432.  This is useful when two machines cannot be directly connected (thus
  433.  preventing use of the standard interactive git protocols -- git, ssh,
  434.  rsync or http), but changes still need to be communicated between the
  435.  machines.
  436.  
  437.  The remote side can use the resulting file (or the path to it) as the URL
  438.  for the repository they want to clone or pull updates from.
  439.  
  440. Examples
  441.  Create a bundle in the file repo.bundle which contains the whole repository
  442.      \$ eg bundle create repo.bundle
  443.  
  444.  After getting the bundle named repo.bundle from a collaborator (which
  445.  must contain \"HEAD\" as one of the references if you explicitly list which
  446.  ones to be included at creation time), clone the repository into the
  447.  directory named project-name
  448.      \$ eg clone /path/to/repo.bundle project-name
  449.  
  450.  Create a bundle in the file called new-repo containing only updates since
  451.  the bundle old-repo was created.
  452.      \$ eg bundle create-update new-repo old-repo
  453.  
  454.  Pulls updates from a new bundle we have been sent.
  455.      \$ eg pull /path/to/repo.bundle
  456.  
  457.  Pull updates from a new bundle we have been sent, if we first overwrite
  458.  the bundle we originally original cloned from with the new bundle
  459.      \$ eg pull
  460.  
  461.  (Advanced) Create a bundle containing the two branches debug and
  462.  installer, and the tag named v2.3, in the file called my-changes
  463.      \$ eg bundle create my-changes debug installer v2.3
  464.  
  465.  (Advanced) Create a bundle in the file called new-repo that contains
  466.  updates since the bundle old-bundle was created, but don't include the
  467.  new branch secret-stuff or crazy-idea
  468.      \$ eg bundle create-update new-repo old-bundle ^secret-stuff ^crazy-idea
  469.      
  470. Options:
  471.  eg bundle create FILENAME [REFERENCES]
  472.  eg bundle create-update NEWFILENAME OLDFILENAME [REFERENCES]
  473.  eg bundle verify FILENAME
  474.  
  475.  create FILENAME [REFERENCES]
  476.    Create a new bundle in the file FILENAME.  If no REFERENCES are passed,
  477.    all branches and tags (plus \"HEAD\") will be included.  See below for
  478.    a basic explanation of REFERENCES.
  479.  
  480.  create-update NEWFILENAME OLDFILENAME [REFERENCES]
  481.  
  482.    Create a new bundle in the file NEWFILENAME, but don't include any
  483.    commits already included in OLDFILENAME.  See below for a basic
  484.    explanation of REFERNCES.  By default, any new branch or tags will be
  485.    included as well; exclude specific branches or tags by passing ^BRANCH
  486.    or ^TAG as a reference; see below for more details.
  487.  
  488.  verify FILENAME
  489.    Check whether the given bundle in FILENAME will cleanly apply to the
  490.    current repository.
  491.  
  492.  REFERENCES
  493.    Which commits to include or exclude from the bundle.  Probably best
  494.    explained by example:
  495.  
  496.      Example            Meaning
  497.      -----------------  --------------------------------------------------
  498.      master             Include the master branch
  499.      master~10..master  Include the last 10 commits on the master branch
  500.      ^baz foo bar       Include commits on the foo or bar branch, except for
  501.                           those that are in the baz branch
  502. ";
  503.   $self->{'differences'} = '
  504.  eg bundle differs from git bundle in two ways:
  505.    (1) eg bundle defaults to "--all HEAD" if no revisions are passed to create
  506.    (2) eg bundle provides a create-update subcommand
  507. ';
  508.   return $self;
  509. }
  510.  
  511. sub preprocess {
  512.   my $self = shift;
  513.  
  514.   #
  515.   # Parse options
  516.   #
  517.   my @args;
  518.   my $result=main::GetOptions("--help" => sub { $self->help() });
  519.  
  520.   # Get the (sub)subcommand
  521.   $self->{subcommand} = shift @ARGV;
  522.   push(@args, $self->{subcommand});
  523.  
  524.   if ($self->{subcommand} eq 'create') {
  525.     my $filename = shift @ARGV ||
  526.       die "Error: need a filename to write bundle to.\n";
  527.     push(@args, $filename);  # Handle the filename
  528.     if (!@ARGV) {
  529.       push(@args, ("--all", "HEAD"));
  530.     }
  531.   }
  532.   elsif ($self->{subcommand} eq 'create-update') {
  533.     pop(@args);  # 'create-update' isn't a real git bundle subcommand
  534.  
  535.     my $newname = shift @ARGV ||
  536.       die "You must specify a new and an old filename.\n";
  537.     my $oldname = shift @ARGV ||
  538.       die "You must also specify an old filename\n";
  539.  
  540.     die "$oldname does not exist.\n" if ! -f $oldname;
  541.  
  542.     my ($retval, $output) =
  543.       ExecUtil::execute_captured("$GIT_CMD bundle list-heads $oldname");
  544.     my @lines = split '\n', $output;
  545.  
  546.     my @refs = map { m#^([0-9a-f]+)# && "^$1" } @lines;
  547.     push(@args, ('create', $newname, "--all", "HEAD", @refs));
  548.   }
  549.   push(@args, @ARGV);
  550.  
  551.   # Reset @ARGV with the built up list of arguments
  552.   @ARGV = @args;
  553. }
  554.  
  555. ###########################################################################
  556. # cat                                                                     #
  557. ###########################################################################
  558. package cat;
  559. @cat::ISA = qw(subcommand);
  560. INIT {
  561.   $COMMAND{cat} = {
  562.     new_command => 1,
  563.     extra => 1,
  564.     section => 'compatibility',
  565.     about => 'Output the current or specified version of files'
  566.     };
  567. }
  568.  
  569. sub new {
  570.   my $class = shift;
  571.   my $self = $class->SUPER::new(
  572.     git_repo_needed => 1,
  573.     git_equivalent => 'show',
  574.     initial_commit_error_msg => "Error: Cannot show committed versions of " .
  575.                                 "files when no commits have occurred.",
  576.     @_
  577.     );
  578.   bless($self, $class);
  579.   $self->{'help'} = "
  580. Usage:
  581.  eg cat [REVISION:]FILE...
  582.  
  583. Description:
  584.  Output the specified file(s) as of the given revisions.
  585.  
  586.  Note that this basically is just a compatibility alias provided for users
  587.  of other SCMs.  You should consider using 'git show' instead, though with
  588.  core git whenever you specify a REVISION, you will need to specify the
  589.  path to FILE relative to the toplevel project directory, instead of a
  590.  path for FILE relative to the current directory.
  591.  
  592. Examples
  593.  Output the most recently committed version of foo.c
  594.      \$ eg cat foo.c
  595.  
  596.  Output the version of bar.h from the 5th to last commit on the
  597.  ugly_fixes branch
  598.      \$ eg cat ugly_fixes~5:bar.h
  599.  
  600.  Concatenate the version of hello.c from two commits ago and the
  601.  version of world.h from the branch timbuktu, and output the result:
  602.      \$ eg cat HEAD~1:hello.c timbuktu:world.h
  603. ";
  604.   $self->{'differences'} = '
  605.  The output of "git show FILE" is probably confusing to users at first,
  606.  as is the need to specify files relative to the top of the git project
  607.  rather than relative to the current directory.  Thus, "eg cat FILE"
  608.  calls "git show HEAD:PATH/TO/FILE".
  609. ';
  610.   return $self;
  611. }
  612.  
  613. sub preprocess {
  614.   my $self = shift;
  615.  
  616.   my $result=main::GetOptions("--help" => sub { $self->help() });
  617.  
  618.   # Get important directories
  619.   my ($cur_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();
  620.  
  621.   my @args;
  622.   foreach my $arg (@ARGV) {
  623.     if ($arg !~ /:/) {
  624.       my ($path) = Util::reroot_paths__from_to_files($cur_dir, $top_dir, $arg);
  625.       push(@args, "HEAD:$path");
  626.     } else {
  627.       my ($REVISION, $FILE) = split(/:/, $arg, 2);
  628.       my ($path) = Util::reroot_paths__from_to_files($cur_dir, $top_dir, $FILE);
  629.       push(@args, "$REVISION:$path");
  630.     }
  631.   }
  632.  
  633.   @ARGV = @args;
  634. }
  635.  
  636. sub run {
  637.   my $self = shift;
  638.  
  639.   @ARGV = Util::quote_args(@ARGV);
  640.   return ExecUtil::execute("$GIT_CMD show @ARGV", ignore_ret => 1);
  641. }
  642.  
  643. ###########################################################################
  644. # changes                                                                 #
  645. ###########################################################################
  646. package changes;
  647. @changes::ISA = qw(subcommand);
  648. INIT {
  649.   $COMMAND{changes} = {
  650.     new_command => 1,
  651.     section => 'misc',
  652.     about => 'Provide an overview of the changes from git to eg'
  653.     };
  654. }
  655.  
  656. sub new {
  657.   my $class = shift;
  658.   my $self = $class->SUPER::new(git_repo_needed => 1, git_equivalent => '', @_);
  659.   bless($self, $class);
  660.   $self->{'help'} = "
  661. Usage:
  662.  eg changes [--details]
  663.  
  664. Options
  665.  --details
  666.    In addition to the summary of which commands were changed, list the
  667.    changes to each command.
  668. ";
  669.   $self->{'differences'} = '
  670.  eg changes is unique to eg; git does not have a similar command.
  671. ';
  672.   return $self;
  673. }
  674.  
  675. sub preprocess {
  676.   my $self = shift;
  677.  
  678.   $self->{details} = 0;
  679.   my $result = main::GetOptions(
  680.     "--help"    => sub { $self->help() },
  681.     "--details" => \$self->{details},
  682.     );
  683.   die "Unrecognized arguments: @ARGV\n" if @ARGV;
  684. }
  685.  
  686. sub run {
  687.   my $self = shift;
  688.  
  689.   if ($DEBUG == 2) {
  690.     print "    >>(No commands to run, just data to print)<<\n";
  691.     return;
  692.   }
  693.  
  694.   # Print valid subcommands sorted by section
  695.   my $indent = "  ";
  696.   my $header_indent = "";
  697.   $ENV{"LESS"} = "FRSX" unless defined $ENV{"LESS"};
  698.   my $less = ($USE_PAGER == 1) ? "less" :
  699.              ($USE_PAGER == 0) ? "cat" :
  700.              `$GIT_CMD config core.pager` || "less";
  701.   chomp($less);
  702.   open(OUTPUT, "| $less");
  703.  
  704.   if ($self->{details}) {
  705.     print OUTPUT "Summary of changes:\n";
  706.     $indent = "    ";
  707.     $header_indent = "  ";
  708.   }
  709.   print OUTPUT "${header_indent}Modified Behavior:\n";
  710.   foreach my $c (sort keys %COMMAND) {
  711.     next if $COMMAND{$c}{unmodified_behavior};
  712.     next if $COMMAND{$c}{new_command};
  713.     print OUTPUT "$indent$c\n";
  714.   }
  715.   print OUTPUT "${header_indent}New commands:\n";
  716.   foreach my $c (sort keys %COMMAND) {
  717.     next if !$COMMAND{$c}{new_command};
  718.     print OUTPUT "$indent$c\n";
  719.   }
  720.   print OUTPUT "${header_indent}Modified Help Only:\n";
  721.   foreach my $c (sort keys %COMMAND) {
  722.     next if $COMMAND{$c}{unmodified_help};
  723.     next if !$COMMAND{$c}{unmodified_behavior};
  724.     next if $COMMAND{$c}{new_command};
  725.     print OUTPUT "$indent$c\n";
  726.   }
  727.  
  728.   if ($self->{details}) {
  729.     foreach my $c (sort keys %COMMAND) {
  730.       next if $COMMAND{$c}{unmodified_help} || $COMMAND{$c}{unmodified_behavior};
  731.  
  732.       my $real_c = $c;
  733.       $c =~ s/-/_/;  # Packages use underscores, commands use dashes
  734.       next if !$c->can("new");
  735.       my $obj = $c->new(initial_commit_error_msg => '');
  736.  
  737.       print OUTPUT "Changes to $real_c:\n";
  738.       if ($obj->{differences}) {
  739.         $obj->{differences} =~ s/^\n//;
  740.         print OUTPUT $obj->{differences};
  741.       } else {
  742.         print OUTPUT "  <Unknown>.\n";
  743.       }
  744.     }
  745.   }
  746.   close(OUTPUT);
  747. }
  748.  
  749. ###########################################################################
  750. # checkout                                                                #
  751. ###########################################################################
  752. package checkout;
  753. @checkout::ISA = qw(subcommand);
  754. INIT {
  755.   $COMMAND{checkout} = {
  756.     section => 'compatibility',
  757.     about => 'Compatibility wrapper for clone/switch/revert'
  758.   };
  759. }
  760.  
  761. sub new {
  762.   my $class = shift;
  763.   my $self = $class->SUPER::new(git_repo_needed => 0, @_);
  764.   bless($self, $class);
  765.   $self->{'help'} = "
  766. Usage:
  767.  eg checkout [-b] BRANCH
  768.  eg checkout [REVISION] PATH...
  769.  
  770. Description:
  771.  eg checkout mostly exists as a compatibility wrapper for those used to
  772.  other systems (cvs/svn and git).  If you:
  773.    (1) want a new copy of the source code from a remote repository
  774.    OR
  775.    (2) want to switch your working copy to a different branch
  776.    OR
  777.    (3) want to revert the contents of a file to its content from a
  778.        different revision
  779.  Then use:
  780.    (1) eg clone
  781.    (2) eg switch
  782.    (3) eg revert
  783.  
  784.  eg checkout will accept the same arguments as eg clone (for getting a new
  785.  copy of the source code from a remote repository), but will provide an
  786.  error message and tell the user to use eg clone in such cases.
  787.  
  788.  The first usage form of eg checkout is used to switch to a different
  789.  branch (optionally also creating it first).  This is something that can
  790.  be done with no network connectivity in git and thus eg.  Users can find
  791.  identical functionality in eg switch.
  792.  
  793.  The second usage form of eg checkout is used to replace files in the
  794.  working copy with versions from an older commit, i.e. to revert files to
  795.  an older version.  Note that this only works when the specified files
  796.  also existed in the older version (eg checkout will not delete or unstage
  797.  files for you), does not work for the initial commit (since there's no
  798.  older revision to revert back to -- unless you are an advanced user
  799.  interested in just undoing the changes since the most recent staging),
  800.  and cannot be used to undo an incomplete merge (since it only operates on
  801.  a subset of files and not everything since a given commit).  Users can
  802.  find the same functionality (without all the caveats) as well as other
  803.  capabilities in eg revert.
  804.  
  805. Examples:
  806.  Switch to the stable branch
  807.      \$ eg checkout stable
  808.  
  809.  Replace foo.c with the third to last version before the most recent
  810.  commit (Note that HEAD always refers to the current branch, and the
  811.  current branch always refers to its most recent commit)
  812.      \$ eg checkout HEAD~3 foo.c
  813. ";
  814.   $self->{'differences'} = '
  815.  eg checkout accepts all parameters that git checkout accepts with the
  816.  same meanings and same output (eg checkout merely calls git checkout in
  817.  such cases).
  818.  
  819.  The only difference between eg and git regarding checkout is that eg
  820.  checkout will also accept all arguments to git clone, and then tell users
  821.  that they must have meant to run eg clone (a much nicer error message for
  822.  users trying to get a copy of source code from a remote repository than
  823.  "fatal: Not a git repository").
  824. ';
  825.   return $self;
  826. }
  827.  
  828. sub _looks_like_git_repo ($) {
  829.   my $path = shift;
  830.  
  831.   my $clone_protocol = qr#^(?:git|ssh|http|https|rsync)://#;
  832.   my $git_dir = RepoUtil::git_dir();
  833.   my $in_working_copy = defined $git_dir ? 1 : 0;
  834.  
  835.   # If the path looks like a git, ssh, http, https, or rsync url, then it
  836.   # looks like we're being given a url to a git repo
  837.   if ($path =~ /$clone_protocol/) {
  838.     return 1;
  839.   }
  840.  
  841.   # If the path isn't a clone_protocol url and isn't a directory, it can't be
  842.   # a git repo
  843.   if (! -d $path) {
  844.     return 0;
  845.   }
  846.  
  847.   my $path_is_absolute = ($path =~ m#^/#);
  848.   return (!$in_working_copy || ($in_working_copy && $path_is_absolute));
  849. }
  850.  
  851. sub preprocess {
  852.   my $self = shift;
  853.  
  854.   if (scalar(@ARGV) > 0 && $ARGV[0] ne "--") {
  855.     main::GetOptions("--help" => sub { $self->help() });
  856.   }
  857.  
  858.   $self->{command} = 'checkout';
  859.   die "eg checkout requires at least one argument.\n" if !@ARGV;
  860.  
  861.   #
  862.   # Determine whether this should be a call to git clone or git checkout
  863.   #
  864.   my $clone_protocol = qr#^(?:git|ssh|http|https|rsync)://#;
  865.   if (_looks_like_git_repo($ARGV[-1]) ||
  866.       (! -d $ARGV[-1] && @ARGV > 1 && _looks_like_git_repo($ARGV[-2]))
  867.      ) {
  868.     $self->{command} = 'clone';
  869.   }
  870. }
  871.  
  872. sub run {
  873.   my $self = shift;
  874.  
  875.   @ARGV = Util::quote_args(@ARGV);
  876.   if ($self->{command} ne 'clone') {
  877.     # If this operation isn't a clone, then we should have checked for
  878.     # whether we are in a git directory.  But we didn't do that, just in
  879.     # case it was a clone.  So, do it now.
  880.     $self->{git_dir} = RepoUtil::git_dir();
  881.     die "Must be run inside a git repository!\n" if !defined $self->{git_dir};
  882.  
  883.     return ExecUtil::execute("$GIT_CMD checkout @ARGV", ignore_ret => 1);
  884.   } else {
  885.     die "Did you mean to run\n  eg clone @ARGV\n?\n";
  886.   }
  887. }
  888.  
  889. ###########################################################################
  890. # cherry_pick                                                             #
  891. ###########################################################################
  892. package cherry_pick;
  893. @cherry_pick::ISA = qw(subcommand);
  894. INIT {
  895.   $COMMAND{"cherry-pick"} = {
  896.     extra => 1,
  897.     section => 'modification',
  898.     about => 'Apply (or reverse) a commit, usually from another branch'
  899.   };
  900. }
  901.  
  902. sub new {
  903.   my $class = shift;
  904.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  905.   bless($self, $class);
  906.   $self->{'help'} = "
  907. Usage:
  908.  eg cherry-pick [--reverse] [--edit] [-n] [-m parent-number] [-s] [-x] REVISION
  909.  
  910. Description:
  911.  Given an existing revision, apply the change between its parent and it
  912.  (or reverse apply if the --reverse option is present), and record a new
  913.  revision with this change.  Your working tree must be clean (no local
  914.  unsaved modifications) in order to run eg cherry-pick.
  915.  
  916. Examples:
  917.  Apply the fix 3 commits behind the tip of the experimental branch
  918.  (i.e. the fix made in experimental~3) to the current branch
  919.      \$ eg cherry-pick experimental~3
  920.  
  921.  Make a new commit that reverses the changes made in the most recent
  922.  commit of the current branch
  923.      \$ eg cherry-pick -R HEAD
  924.  
  925. Options:
  926.  --reverse, --revert, -R
  927.    Reverse apply the changes from the specified commit (i.e. revert the
  928.    specified revision with a new commit).
  929.  
  930.  --edit, -e
  931.    With this option, eg cherry-pick will let you edit the commit message
  932.    prior to committing.
  933.  
  934.  -x
  935.    When recording the commit, append to the original commit message a note
  936.    that indicates which commit this change was cherry-picked from.  Append
  937.    the note only for cherry picks without conflicts. Do not use this
  938.    option if you are cherry-picking from your private branch because the
  939.    information is useless to the recipient. If on the other hand you are
  940.    cherry-picking between two publicly visible branches (e.g. backporting
  941.    a fix to a maintenance branch for an older release from a development
  942.    branch), adding this information can be useful.
  943.  
  944.    This option is turned on automatically when -R is specified.
  945.  
  946.  --mainline parent-number, -m parent-number
  947.    cherry-pick always applies the changes between a revision and its
  948.    parent; thus if a revision represents a merge commit, it is not clear
  949.    which parent cherry-pick should get the changes relative to.  This
  950.    option specifies the parent number (starting from 1) of the mainline
  951.    and allows cherry-pick to replay the change relative to the specified
  952.    parent.
  953.  
  954.  --no-commit, -n
  955.    Usually cherry-pick automatically creates a commit. This flag applies
  956.    the change necessary to cherry-pick the named revision to your working
  957.    tree and staging area, but does not make the commit. In addition, when
  958.    this option is used, the staging area can contain unsaved changes and
  959.    the cherry-pick will be done against the beginning state of your
  960.    staging area.
  961.  
  962.    This is useful when cherry-picking more than one commit into a single
  963.    combined change.
  964.  
  965.  --signoff, -s
  966.    Add Signed-off-by line at the end of the commit message.
  967.  
  968.  REVISION
  969.    A reference to a recorded version of the repository.  See 'eg help
  970.    topic revisions' for more details.
  971. ";
  972.   $self->{'differences'} = '
  973.  eg cherry-pick contains both the functionality of git cherry-pick and git
  974.  revert.  If the -R option is specified, eg cherry-pick calls git revert
  975.  (after removing the -R option); otherwise it calls git cherry-pick.
  976. ';
  977.   return $self;
  978. }
  979.  
  980. sub preprocess {
  981.   my $self = shift;
  982.  
  983.   my ($reverse, $dash_x, $mainline) = (0, 0, -1);
  984.   Getopt::Long::Configure("permute");  # Allow unrecognized options through
  985.   my $result = main::GetOptions(
  986.     "--help"       => sub { $self->help() },
  987.     "mainline|m=i" => \$mainline,
  988.     "reverse|R"    => \$reverse,
  989.     "revert"       => \$reverse,
  990.     "x"            => \$dash_x,
  991.     );
  992.   $self->{reverse} = $reverse;
  993.   unshift(@ARGV, "-x") if (!$reverse && $dash_x);
  994.   unshift(@ARGV, ("-m", $mainline)) if $mainline != -1;
  995. }
  996.  
  997. sub run {
  998.   my $self = shift;
  999.  
  1000.   @ARGV = Util::quote_args(@ARGV);
  1001.   if ($self->{reverse}) {
  1002.     return ExecUtil::execute("$GIT_CMD revert @ARGV", ignore_ret => 1);
  1003.   } else {
  1004.     return ExecUtil::execute("$GIT_CMD cherry-pick @ARGV", ignore_ret => 1);
  1005.   }
  1006. }
  1007.  
  1008. ###########################################################################
  1009. # clone                                                                   #
  1010. ###########################################################################
  1011. package clone;
  1012. @clone::ISA = qw(subcommand);
  1013. INIT {
  1014.   $COMMAND{clone} = {
  1015.     section => 'creation',
  1016.     about => 'Clone a repository into a new directory'
  1017.   };
  1018. }
  1019.  
  1020. sub new {
  1021.   my $class = shift;
  1022.   my $self = $class->SUPER::new(git_repo_needed => 0, @_);
  1023.   bless($self, $class);
  1024.   $self->{'help'} = "
  1025. Usage:
  1026.  eg clone [--depth DEPTH] REPOSITORY [DIRECTORY]
  1027.  
  1028. Description:
  1029.  Obtains a copy of a remote repository, including all history by default.
  1030.  A --depth option can be passed to only include a specified number of
  1031.  recent commits instead of all history (however, this option exists mostly
  1032.  due to the fact that users of other SCMs fail to understand that all
  1033.  history can be compressed into a size that is often smaller than the
  1034.  working copy).
  1035.  
  1036.  See 'eg help topic remote-urls' for a detailed list of the different ways
  1037.  to refer to remote repositories.
  1038.  
  1039. Examples:
  1040.  Get a local clone of cairo
  1041.      \$ eg clone git://git.cairographics.org/git/cairo
  1042.  
  1043.  Get a clone of a local project in a new directory 'mycopy'
  1044.      \$ eg clone /path/to/existing/repo mycopy
  1045.  
  1046.  Get a clone of a project hosted on someone's website, asking for only the
  1047.  most recent 20 commits instead of all history, and storing it in the
  1048.  local directory mydir
  1049.      \$ eg clone --depth 20 http://www.random.machine/path/to/git.repo mydir
  1050.  
  1051. Options:
  1052.  --depth DEPTH
  1053.    Only download the DEPTH most recent commits instead of all history
  1054. ";
  1055.   return $self;
  1056. }
  1057.  
  1058. ###########################################################################
  1059. # commit                                                                  #
  1060. ###########################################################################
  1061. package commit;
  1062. @commit::ISA = qw(subcommand);
  1063. INIT {
  1064.   $COMMAND{commit} = {
  1065.     section => 'modification',
  1066.     about => 'Record changes locally'
  1067.     };
  1068.   $ALIAS{'checkin'} = "commit";
  1069.   $ALIAS{'ci'}      = "commit";
  1070. }
  1071.  
  1072. sub new {
  1073.   my $class = shift;
  1074.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  1075.   bless($self, $class);
  1076.   $self->{'help'} = "
  1077. Usage:
  1078.  eg commit [-a|--all-known] [-b|--bypass-unknown-check]
  1079.            [--staged|-d|--dirty] [-F FILE | -m MSG] [--amend] [--]
  1080.            [FILE...]
  1081.  
  1082. Description:
  1083.  Records changes locally along with a log message describing the
  1084.  changes you have made.  If no -F or -m option is supplied, an editor
  1085.  is opened for you to enter a log message.
  1086.  
  1087.  In order to prevent common errors, the commit will abort with a warning
  1088.  message if there are no changes to commit, there are conflicts from a
  1089.  merge, or if eg detects that the choice of what to commit is ambiguous.
  1090.  In particular, if you have any \"newly created\" unknown files present,
  1091.  or if you have both staged changes (i.e. changes explicitly marked as
  1092.  ready for commit) and unstaged changes, then you will get a warning
  1093.  rather than having the commit occur.  You can run 'eg status' to get the
  1094.  status of various files and their changes.  These commit checks can be
  1095.  bypassed with various options.
  1096.  
  1097. Examples:
  1098.  Record current changes locally, not changing anything in CVS...OR...get
  1099.  a warning message if eg detects that the choice of what to commit is not
  1100.  necessarily clear.
  1101.      \$ eg commit
  1102.  
  1103.  Record current changes, ignoring any unknown files present.  Also
  1104.  remember the list of unknown files so that their existence will not
  1105.  trigger future \"You have new unknown files present\" warnings when not
  1106.  using the -b flag.
  1107.      \$ eg commit -b
  1108.  
  1109.  Record brand new file and current changes.
  1110.      \$ eg stage file.c
  1111.      \$ eg commit -a
  1112.  Note: Running 'eg stage FILE' explicitly marks FILE as being ready to
  1113.  commit.  Since you likely haven't explicitly marked your other changes as
  1114.  ready to commit, pass the -a flag to specify that both kinds of changes
  1115.  should be recorded.
  1116.  
  1117.  (Advanced) Record staged changes, ignoring both unstaged changes and
  1118.  unknown files.
  1119.      \$ eg commit --staged
  1120.  
  1121. Options:
  1122.  --all-known, -a
  1123.    (Could also be called --act-like-other-vcses).  Commit both staged
  1124.    (i.e. explictly marked as ready for commit) changes and unstaged
  1125.    changes.
  1126.  
  1127.    Incompatible with explicitly specifying files to commit on the command
  1128.    line, and incompatible with the --staged option.
  1129.  
  1130.  --bypass-unknown-check, -b
  1131.    Commit local changes, even if there are unknown files around.  If this
  1132.    flag is not used and unknown files are currently present that were not
  1133.    present the last time the -b flag was used, then the commit will be
  1134.    aborted with a warning message.
  1135.  
  1136.  --staged, --dirty, -d
  1137.    Commit only staged changes and bypass sanity checks.  (\"dirty\" is kept
  1138.    as a synonym in order to provide a short (-d) form.  The term \"dirty\"
  1139.    is used to convey the fact that the working area will likely not be
  1140.    \"clean\" after a commit since unstaged changes will still be present).
  1141.  
  1142.    WARNING: Do not try to use -s as a shorthand for --staged; -s has a
  1143.    different meaning (see 'git commit --help')
  1144.  
  1145.    Incompatible with explicitly specifying files to commit on the command
  1146.    line, and incompatible with the --all-known option.
  1147.  
  1148.  -F FILE
  1149.    Use the contents of FILE as the commit message
  1150.  
  1151.  -m MSG
  1152.    Use MSG as the commit message.
  1153.  
  1154.  --amend
  1155.    Amend the last commit on the current branch.
  1156. ";
  1157.   $self->{'differences'} = '
  1158.  The "--staged" (and "-d" and "--dirty" aliases) are unique to eg commit;
  1159.  git commit behavior differs from eg commit in that it acts by default
  1160.  like the --staged flag was passed UNLESS either the -a option is passed
  1161.  or files are explicitly listed on the command line.
  1162.  
  1163.  The "--bypass-unknown-check" is unique to eg commit; git commit
  1164.  behavior differs by always turning on this functionality -- there is
  1165.  no way to have git commit do an unknown files sanity check for you.
  1166.  
  1167.  "-a" is not nearly as useful for eg commit as it is for git commit.  "-a"
  1168.  has the same behavior in both, but the "smart" behavior of eg commit
  1169.  means it is only rarely needed.
  1170.  
  1171.  The "--all-known" alias for "-a" is known as "--all" to git-commit; I
  1172.  find the latter confusing and misleading and thus renamed to the former
  1173.  for eg commit.
  1174.  
  1175.  To be precise about the behavior of a plain "eg commit":
  1176.     If the working copy is clean                -> warn user: nothing to commit
  1177.     else if there are unmerged files            -> warn user: unmerged files
  1178.     else if there are new untracked files       -> warn user: new unknown files
  1179.     else if both "staged" & unstaged changes[1] -> warn user: mix
  1180.     else                                        -> run "git commit -a"
  1181.  Actually, I do not pass -a if there are only staged changes present, but
  1182.  the result is the same.  Note that this essentially boils down to making
  1183.  the user do less work (no need to remember -a in the common case) and
  1184.  extending the sanity checks git commit does (which currently only covers
  1185.  the clean working copy case) to also prevent a number of other very
  1186.  common user pitfalls.
  1187.  
  1188.  [1] The reason for putting "staged" in quotes comes from the case of
  1189.  running "eg commit --amend" when you have local unstaged changes.  Does
  1190.  the user want to merely amend the prior commit message or add their
  1191.  changes to the previous commit?  (Even if the index matches HEAD at this
  1192.  time, we are committing relative to HEAD^1.)  It is not clear what the
  1193.  user wants, so we warn and ask them to use -a or --staged.
  1194. ';
  1195.   return $self;
  1196. }
  1197.  
  1198. sub preprocess {
  1199.   my $self = shift;
  1200.   my $package_name = ref($self);
  1201.  
  1202.   #
  1203.   # Parse options
  1204.   #
  1205.   $self->{args} = [];
  1206.   my $record_arg   = sub { push(@{$self->{args}}, "$_[0]$_[1]"); };
  1207.   my $record_args  = sub { push(@{$self->{args}}, "$_[0]$_[1]");
  1208.                            push(@{$self->{args}}, splice(@_, 2)); };
  1209.   my ($all_known, $bypass_unknown, $staged, $amend,
  1210.       $dry_run, $allow_empty, $include) = (0, 0, 0, 0, 0, 0, 0);
  1211.   Getopt::Long::Configure("permute");
  1212.   my $result = main::GetOptions(
  1213.     "--help|h"                    => sub { $self->help() },
  1214.     "all-known|a"                 => \$all_known,
  1215.     "bypass-unknown-check|b"      => \$bypass_unknown,
  1216.     "staged|dirty|d"              => \$staged,
  1217.     "dry-run"                     => sub { $dry_run = 1,
  1218.                                            &$record_arg("--", @_) },
  1219.     "s"                           => sub { &$record_arg("-", @_) },
  1220.     "v"                           => sub { &$record_arg("-", @_) },
  1221.     "u"                           => sub { &$record_arg("-", @_) },
  1222.     "c=s"                         => sub { &$record_args("-", @_) },
  1223.     "C=s"                         => sub { &$record_args("-", @_) },
  1224.     "F=s"                         => sub { &$record_args("-", @_) },
  1225.     "file=s"                      => sub { &$record_args("--", @_) },
  1226.     "m=s"                         => sub { &$record_args("-", @_) },
  1227.     "amend"                       => sub { $amend = 1; &$record_arg("--", @_) },
  1228.     "allow-empty"                 => sub { $allow_empty = 1;
  1229.                                            &$record_arg("--", @_) },
  1230.     "interactive"                 => sub { $allow_empty = 1;
  1231.                                            &$record_arg("--", @_) },
  1232.     "no-verify"                   => sub { &$record_arg("--", @_) },
  1233.     "e"                           => sub { &$record_arg("-", @_) },
  1234.     "author=s"                    => sub { &$record_args("--", @_) },
  1235.     "cleanup=s"                   => sub { &$record_args("--", @_) },
  1236.     "include|i=s"                 => sub { $include = 1;
  1237.                                            &$record_args("--", @_) },
  1238.     );
  1239.   my ($opts, $revs, $files) = RepoUtil::parse_args([], @ARGV);
  1240.  
  1241.   #
  1242.   # Set up flags based on options, do sanity checking of options
  1243.   #
  1244.   my ($check_no_changes, $check_unknown, $check_mixed, $check_unmerged);
  1245.   my $skip_all = $include || $dry_run;
  1246.   $self->{'commit_flags'} = [];
  1247.   die "Cannot specify both --all-known (-a) and --staged (-d)!\n" if
  1248.     $all_known && $staged;
  1249.   die "Cannot specify --staged when specifying files!\n" if @$files && $staged;
  1250.   $check_no_changes = !$amend && !$allow_empty && !$skip_all;
  1251.   $check_unknown   = !$bypass_unknown && !$staged && !@$files && !$skip_all;
  1252.   $check_mixed     = !$all_known      && !$staged && !@$files && !$skip_all;
  1253.   $check_unmerged  = !$skip_all;
  1254.   push(@{$self->{'commit_flags'}}, "-a") if $all_known;
  1255.  
  1256.   #
  1257.   # Lots of sanity checks
  1258.   #
  1259.   my $status =
  1260.     RepoUtil::commit_push_checks($package_name,
  1261.                                  {no_changes       => $check_no_changes,
  1262.                                   unknown          => $check_unknown,
  1263.                                   partially_staged => $check_mixed,
  1264.                                   unmerged_changes => $check_unmerged});
  1265.  
  1266.   if ($amend && !$all_known && !$staged && !$skip_all && !@$files &&
  1267.       $status->{has_unstaged_changes} && !$status->{has_staged_changes}) {
  1268.     print STDERR <<EOF;
  1269. Aborting: It is not clear whether you want to simply amend the commit
  1270. message or whether you want to include your local changes in the amended
  1271. commit.  Please pass --staged to just amend the previous commit message, or
  1272. pass -a to include your current local changes with the previous amended
  1273. commit.
  1274. EOF
  1275.     exit 1;
  1276.   }
  1277.  
  1278.   die "No staged changes, but --staged given.\n"
  1279.       if (!$status->{has_staged_changes} && $staged && !$amend && !$dry_run);
  1280.  
  1281.   if (!$all_known && !$include && !$staged &&
  1282.       $status->{has_unstaged_changes} && !$status->{has_staged_changes} &&
  1283.       !@$files) {
  1284.     push(@{$self->{'commit_flags'}}, "-a");
  1285.   }
  1286.  
  1287.   #
  1288.   # Record the set of unknown files we ignored with -b, so the -b flag isn't
  1289.   # needed next time.
  1290.   #
  1291.   if ($bypass_unknown) {
  1292.     RepoUtil::record_ignored_unknowns();
  1293.   }
  1294.  
  1295.   push(@{$self->{args}}, @{$self->{commit_flags}});
  1296.   unshift(@ARGV, @{$self->{args}});
  1297. }
  1298.  
  1299. ###########################################################################
  1300. # config                                                                  #
  1301. ###########################################################################
  1302. package config;
  1303. @config::ISA = qw(subcommand);
  1304. INIT {
  1305.   $COMMAND{config} = {
  1306.     unmodified_behavior => 1,
  1307.     extra => 1,
  1308.     section => 'misc',
  1309.     about => 'Get or set configuration options'
  1310.     };
  1311. }
  1312.  
  1313. sub new {
  1314.   my $class = shift;
  1315.   my $self = $class->SUPER::new(git_repo_needed => 0, @_);
  1316.   bless($self, $class);
  1317.   $self->{'help'} = "
  1318. Usage:
  1319.  eg config OPTION [ VALUE ]
  1320.  eg config --unset OPTION
  1321.  eg config [ --list ]
  1322.  
  1323. Description:
  1324.  Gets or sets configuration options.
  1325.  
  1326.  See the 'Configuration File' section of 'git help config' for a fairly
  1327.  comprehensive list of special options used by eg (and git).
  1328.  
  1329. Examples:
  1330.  Get the value of the configuration option user.email
  1331.      \$ eg config user.email
  1332.  
  1333.  Set the value of the configuration option user.email to whizbang\@flashy.org
  1334.      \$ eg config user.email whizbang\@flashy.org
  1335.  
  1336.  Unset the values of the configuration options branch.master.remote
  1337.  and branch.master.merge
  1338.      \$ eg config --unset branch.master.remote
  1339.      \$ eg config --unset branch.master.merge
  1340.  
  1341.  List all options that have been set
  1342.      \$ eg config --list  
  1343. ";
  1344.   return $self;
  1345. }
  1346.  
  1347. ###########################################################################
  1348. # diff                                                                    #
  1349. ###########################################################################
  1350. package diff;
  1351. @diff::ISA = qw(subcommand);
  1352. INIT {
  1353.   $COMMAND{diff} = {
  1354.     section => 'discovery',
  1355.     about => 'Show changes to file contents'
  1356.     };
  1357. }
  1358.  
  1359. sub new {
  1360.   my $class = shift;
  1361.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  1362.   bless($self, $class);
  1363.   $self->{'help'} = "
  1364. Usage:
  1365.  eg diff [--unstaged | --staged] [REVISION] [REVISION] [FILE...]
  1366.  
  1367. Description:
  1368.  Shows differences between different versions of the project.  By default,
  1369.  it shows the differences between the last locally recorded version and the
  1370.  version in the working copy.
  1371.  
  1372. Examples:
  1373.  Show local unrecorded changes
  1374.      \$ eg diff
  1375.  
  1376.  In a project with the current branch being 'master', show the differences
  1377.  between the version before the last recorded commit and the working copy.
  1378.      \$ eg diff master~1
  1379.  Or do the same using \"HEAD\" which is a synonym for the current branch:
  1380.      \$ eg diff HEAD~1
  1381.  
  1382.  Show changes to the file myscript.py between 10 versions before last
  1383.  recorded commit and the last recorded commit (assumes the current branch
  1384.  is 'master').
  1385.      \$ eg diff master~10 master myscript.py
  1386.  
  1387.  (Advanced) Show changes between staged (ready-to-be-committed) version of
  1388.  files and the working copy (use 'eg stage' to stage files).  In other
  1389.  words, show the unstaged changes.
  1390.      \$ eg diff --unstaged
  1391.  
  1392.  (Advanced) Show changes between last recorded copy and the staged (ready-
  1393.  to-be-committed) version of files (use 'eg stage' to stage files).  In
  1394.  other words, show the staged changes.
  1395.      \$ eg diff --staged
  1396.  
  1397.  (Advanced) Show changes between 5 versions before the last recorded
  1398.  commit and the currently staged (ready-to-be-committed) version of the
  1399.  repository.  (Use 'eg stage' to stage files).
  1400.      \$ eg diff --staged HEAD~5
  1401.  
  1402. Options:
  1403.  REVISION
  1404.    A reference to a recorded version of the repository, defaulting to HEAD
  1405.    (meaning the most recent commit on the current branch).  See 'eg help
  1406.    topic revisions' for more details.
  1407.  
  1408.  --staged
  1409.    Show changes between the last commit and the staged copy of files.
  1410.    Cannot be used when two revisions have been specified.
  1411.  
  1412.  --unstaged
  1413.    Show changes between the staged copy of files and the current working
  1414.    directory.  Cannot be used when a revision is specified.
  1415. ";
  1416.   $self->{'differences'} = '
  1417.  Changes to eg diff relative to git diff are:
  1418.    (1) Different defaults for what to diff relative to
  1419.    (2) Providing a more consistent double-dot operator
  1420.  
  1421.  Section 1: Different defaults for what to diff relative to
  1422.  
  1423.  The following illustrate the two changed defaults of eg diff:
  1424.    eg diff            <=> git diff HEAD
  1425.    eg diff --unstaged <=> git diff
  1426.  (Which is not 100% accurate due to merges; see below.)  In more detail:
  1427.  
  1428.  The "--unstaged" option is unique to eg diff; to get the same behavior
  1429.  with git diff you simply list no revisions and omit the "--cached" flag.
  1430.  
  1431.  When neither --staged nor --unstaged are specified to eg diff and no
  1432.  revisions are given, eg diff will pass along the revision "HEAD" to git
  1433.  diff.
  1434.  
  1435.  The "--staged" option is an alias for "--cached" unique to eg diff; the
  1436.  purpose of the alias is to reduce the number of different names in git
  1437.  used to refer to the same concept.  (Update: the --staged flag is now
  1438.  part of git with the same meaning as in eg.)
  1439.  
  1440.  Merges: The above is slightly modified if the user has an incomplete
  1441.  merge; if the user has conflicts during a merge (or uses --no-commit when
  1442.  calling merge) and then tries "eg diff", it will abort with a message
  1443.  telling the user that there is no "last" commit and will provide
  1444.  alternative suggestions.
  1445.  
  1446.  Section 2: Providing a more consistent double-dot operator
  1447.  
  1448.    The .. operator of git diff (e.g. git diff master..devel) means what
  1449.    the ... operator of git log means, and vice-versa.  This causes lots of
  1450.    confusion.  We fix this by making the .. operator of eg diff
  1451.    do exactly what the ... operator of git diff does.  To see why:
  1452.    
  1453.    Meanings of git commands, as a reminder (A and B are revisions):
  1454.      git diff A..B  <=> git diff A B                      # Endpoint difference
  1455.      git diff A...B <=> git diff $(git merge-base A B) B  # Changes from base
  1456.    
  1457.    Why this is confusing (compare to above):
  1458.      git log A..B  <=> git log ^$(git merge-base A B) B   # Changes from base
  1459.      git log A...B <=> git log A B ^$(git merge-base A B) # Endpoint difference
  1460.    
  1461.    So, my translation:
  1462.      eg diff A B   <=>  git diff A B    <=> git diff A..B
  1463.      eg diff A..B  <=>  git diff A...B
  1464.      eg diff A...B <=>  git diff A...B
  1465.  
  1466.    Reasons for this change:
  1467.      * New users automatically get sane behavior, and use either eg diff A B
  1468.        or eg diff A..B, each doing what one would expect.  They do not ever
  1469.        realize that A...B is a bit weird because they have no need to try to
  1470.        use it; eg diff A B covers their needs.
  1471.      * Users worried about switching between eg and git without having to
  1472.        modify their command lines can always use either diff A B or
  1473.        diff A...B, but never any other form; using this subset ensures that
  1474.        both eg and git behave identically.
  1475.      * Users only access git diff A..B behavior through eg diff A B, which
  1476.        is less typing and makes more sense.
  1477.      * Since git diff A..B and git diff A B are the same, the latter is far
  1478.        more common, and the former is confusing, odds are that if any git
  1479.        user suggests someone use git diff A..B they probably really meant
  1480.        git diff A...B
  1481. ';
  1482.   return $self;
  1483. }
  1484.  
  1485. sub preprocess {
  1486.   my $self = shift;
  1487.  
  1488.   # Avoid Util::git_rev_parse because it fails on t2010-checkout-ambiguous by
  1489.   # treating "--quiet" as a revision rather than an option; use our own
  1490.   # parse_args implementation instead.
  1491.   my ($opts, $revs, $files) = RepoUtil::parse_args(["--extcmd", "-x"], @ARGV);
  1492.  
  1493.   # Replace '..' with '...' in revision specifiers.  Use backslash escaping to
  1494.   # get actual dots and not just any character.  Use negative lookbehind and
  1495.   # lookahead assertions to avoid replacing '...' with '....'.
  1496.   my @new_revs = map(m#(.+)(?<!\.)\.\.(?!\.)(.+)# ? "$1...$2" : $_, @$revs);
  1497.   $revs = \@new_revs;
  1498.  
  1499.   #
  1500.   # Parse options
  1501.   #
  1502.   $self->{'opts'} = "";
  1503.   @ARGV = @$opts;
  1504.   my ($staged, $unstaged, $no_index, $ours, $theirs) = (0, 0, 0, 0, 0);
  1505.   my $extcmd;
  1506.   Getopt::Long::Configure("permute");
  1507.   my $result = main::GetOptions(
  1508.     "--help"         => sub { $self->help() },
  1509.     "staged|cached"  => \$staged,
  1510.     "unstaged"       => \$unstaged,
  1511.     "no-index"       => \$no_index,
  1512.     "extcmd=s"       => \$extcmd,
  1513.     "ours"           => \$ours,
  1514.     "theirs"         => \$theirs,
  1515.     );
  1516.   die "Cannot specify both --staged and --unstaged!\n" if $staged && $unstaged;
  1517.   my @args;
  1518.   push(@args, "--cached") if $staged;
  1519.   push(@args, "--no-index") if $no_index;
  1520.   push(@args, "--extcmd", $extcmd) if $extcmd;
  1521.   push(@args, "--theirs") if $theirs;
  1522.   push(@args, "--ours") if $ours;
  1523.   push(@args, @ARGV);
  1524.  
  1525.   #
  1526.   # Parse revs
  1527.   #
  1528.   die "eg diff: Cannot specify '--staged' with more than 1 revision.\n"
  1529.     if ($staged && scalar @$revs > 1);
  1530.   die "eg diff: Cannot specify '--unstaged' with any revisions.\n"
  1531.     if ($unstaged && scalar @$revs > 0);
  1532.   # 'eg diff' (without arguments) should act like 'git diff HEAD', unless
  1533.   # we are in an aborted merge state
  1534.   if (!@$revs && !$unstaged && !$staged && !$no_index && !$ours && !$theirs) {
  1535.     if (-f "$self->{git_dir}/MERGE_HEAD") {
  1536.       my @merge_branches = RepoUtil::merge_branches();
  1537.       my $list = join(", ", @merge_branches);
  1538.       print STDERR <<EOF;
  1539. Aborting: Cannot show the changes since the last commit, since you are in the
  1540. middle of a merge and there are multiple last commits.  Try passing one of
  1541.   --unstaged, $list
  1542. to eg diff.
  1543.  
  1544. For additional conflict resolution help, try eg log --merge or
  1545.   eg show BRANCH:FILE
  1546. where FILE is any file in your working copy and BRANCH is one of
  1547.   $list
  1548. EOF
  1549.       exit 1;
  1550.     }
  1551.     if (RepoUtil::initial_commit()) {
  1552.       print STDERR <<EOF;
  1553. Aborting: Cannot show the changes since the last commit, since you do not
  1554. yet have any commits on the current branch.  Try passing --unstaged to diff,
  1555. or making a commit first.
  1556. EOF
  1557.       exit 1;
  1558.     }
  1559.     push(@$revs, "HEAD")
  1560.   }
  1561.  
  1562.   push(@args, @$revs);
  1563.   push(@args, "--");
  1564.   push(@args, @$files);
  1565.   @ARGV = @args;
  1566. }
  1567.  
  1568. ###########################################################################
  1569. # difftool                                                                #
  1570. ###########################################################################
  1571. package difftool;
  1572. @difftool::ISA = qw(diff);
  1573. INIT {
  1574.   $COMMAND{difftool} = {
  1575.     new_command => 1,
  1576.     extra => 1,
  1577.     section => 'discovery',
  1578.     about => 'Show changes to file contents using an external tool'
  1579.     };
  1580. }
  1581.  
  1582. sub new {
  1583.   my $class = shift;
  1584.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  1585.   bless($self, $class);
  1586.  
  1587.   $self->{'help'} = "
  1588. Usage:
  1589.  eg difftool [--tool=<tool>] [--unstaged | --staged] [REVISION] [REVISION] [FILE...]
  1590.  
  1591. Description:
  1592.  Shows differences between different versions of the project using an
  1593.  external tool.  By default, it shows the differences between the last
  1594.  locally recorded version and the version in the working copy.
  1595.  
  1596.  This command behaves just like 'eg diff'; see 'eg help diff' for more
  1597.  details.
  1598.  
  1599.  You can configure the default external tool with 'eg config'.  You can
  1600.  specify the default tool by setting 'diff.tool'; you can configure the
  1601.  tool by setting 'difftool.<tool>.cmd'.  See the 'Configuration File'
  1602.  section of 'git help config' for more details.
  1603.  
  1604. Example:
  1605.  Show local unrecorded changes in vimdiff
  1606.      \$ eg difftool --tool=vimdiff
  1607.  
  1608.  See 'eg help diff' for more diff examples.
  1609.  
  1610. ";
  1611.   $self->{'differences'} = "
  1612.  git difftool behaves just like git diff, but launches an external tool
  1613.  instead of using git's built-in machinery.  eg diff is quite different from
  1614.  git diff (see 'eg help diff' for details); eg difftool behaves just like
  1615.  eg diff.
  1616. ";
  1617.   return $self;
  1618. }
  1619.  
  1620.  
  1621.  
  1622. ###########################################################################
  1623. # gc                                                                      #
  1624. ###########################################################################
  1625. package gc;
  1626. @gc::ISA = qw(subcommand);
  1627. INIT {
  1628.   $COMMAND{gc} = {
  1629.     unmodified_behavior => 1,
  1630.     extra => 1,
  1631.     section => 'timesavers',
  1632.     about => 'Optimize the local repository to make later operations faster',
  1633.     };
  1634. }
  1635.  
  1636. sub new {
  1637.   my $class = shift;
  1638.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  1639.   bless($self, $class);
  1640.   $self->{'help'} = "
  1641. Usage:
  1642.  eg gc
  1643.  
  1644. Description:
  1645.  Optimizes the local repository; in particular, this command compresses
  1646.  file revisions to reduce disk space and increase performance.
  1647.  
  1648.  This command is occasionally called during normal git usage, making
  1649.  explicit usage of this command unnecessary for many users.  However, the
  1650.  automatic calls of this command only do simple and quick optimizations,
  1651.  so some users (particularly those with many revisions) may benefit from
  1652.  manually invoking this command periodically (such as from nightly or
  1653.  weekly cron scripts).
  1654. ";
  1655.   return $self;
  1656. }
  1657.  
  1658. ###########################################################################
  1659. # help                                                                    #
  1660. ###########################################################################
  1661. package help;
  1662. @help::ISA = qw(subcommand);
  1663. INIT {
  1664.   $COMMAND{help} = {
  1665.     section => 'misc',
  1666.     about => 'Get command syntax and examples'
  1667.     };
  1668. }
  1669.  
  1670. sub new {
  1671.   my $class = shift;
  1672.   my $self = $class->SUPER::new(exit_status => 0,
  1673.                                 git_equivalent => '',
  1674.                                 git_repo_needed => 0,
  1675.                                 @_);
  1676.   bless($self, $class);
  1677.   $self->{'help'} = "
  1678. Usage:
  1679.  eg help --all
  1680.  eg help [COMMAND]
  1681.  eg help topic [TOPIC]
  1682.  
  1683. Description:
  1684.  Shows general help for eg, for one of its subcommands, or for a
  1685.  specialized topic.
  1686.  
  1687. Examples:
  1688.  Show help for eg
  1689.      \$ eg help
  1690.  
  1691.  Show help for extended list of commands available in eg
  1692.      \$ eg help --all
  1693.  
  1694.  Show help for the switch command of eg
  1695.      \$ eg help switch
  1696.  
  1697.  Show which topics have available help
  1698.      \$ eg help topic
  1699.  
  1700.  Show the help for the staging topic
  1701.      \$ eg help topic staging
  1702. ";
  1703.   $self->{'differences'} = "
  1704.  eg help uses its own help system, ignoring the one from git help...except
  1705.  that eg help will call git help if asked for help on a subcommand it does
  1706.  not recognize.
  1707.  
  1708.  'git help COMMAND', by default, simply calls 'man git-COMMAND'.  The git
  1709.  man pages are really nice for people who are experts with git; they are
  1710.  comprehensive and detailed.  However, new users tend to get lost in a sea
  1711.  of details and advanced topics (among other problems).  'eg help COMMAND'
  1712.  provides much simpler pages of its own and refers to the manpages for
  1713.  more details.  The eg help pages also list any differences between the eg
  1714.  commands and the git ones, to assist interested users in learning git.
  1715.  
  1716.  If you simply want a brief list of available options and descriptions,
  1717.  you may also want to try running 'git COMMAND -h' (which differs from
  1718.  the two identical commands 'git COMMAND --help' and 'git help COMMAND').
  1719. ";
  1720.  
  1721.   return $self;
  1722. }
  1723.  
  1724. sub preprocess {
  1725.   my $self = shift;
  1726.  
  1727.   $self->{all} = 0;
  1728.   my $result=main::GetOptions("--help" => sub { $self->help() },
  1729.                               "--all"  => \$self->{all});
  1730. }
  1731.  
  1732. sub run {
  1733.   my $self = shift;
  1734.  
  1735.   if ($DEBUG == 2) {
  1736.     print "    >>(No commands to run, just data to print)<<\n";
  1737.     return;
  1738.   }
  1739.  
  1740.   # Check if we were asked to get help on a subtopic rather than toplevel help
  1741.   if (@ARGV > 0) {
  1742.     my $orig_subcommand = shift @ARGV;
  1743.     my $subcommand = $orig_subcommand;
  1744.     $subcommand =~ s/-/_/;  # Packages use underscores, commands use dashes
  1745.     if (@ARGV != 0 && ($subcommand ne 'topic' || @ARGV != 1)) {
  1746.       die "Too many arguments to help.\n";
  1747.     }
  1748.     die "Oops, there's a bug.\n" if $self->{exit_status} != 0;
  1749.     $subcommand = "help::topic" if $subcommand eq 'topic';
  1750.  
  1751.     if (!$subcommand->can("new")) {
  1752.       print "$orig_subcommand is not modified by eg (eg $orig_subcommand is" .
  1753.             " equivalent to git $orig_subcommand).\nWill try running 'git" .
  1754.             " help $orig_subcommand' in 2 seconds...\n";
  1755.       sleep 2;
  1756.       exit ExecUtil::execute("$GIT_CMD help $orig_subcommand");
  1757.     }
  1758.  
  1759.     my $subcommand_obj = $subcommand->new(initial_commit_error_msg => '',
  1760.                                           git_repo_needed => 0);
  1761.     $subcommand_obj->help();
  1762.   }
  1763.  
  1764.   # Set up a pager, if wanted
  1765.   $ENV{"LESS"} = "FRSX" unless defined $ENV{"LESS"};
  1766.   my $less = ($USE_PAGER == 1) ? "less" :
  1767.              ($USE_PAGER == 0) ? "cat" :
  1768.              `$GIT_CMD config core.pager` || "less";
  1769.   chomp($less);
  1770.   open(OUTPUT, "| $less");
  1771.  
  1772.   # Help users know about the --all switch
  1773.   if (!$self->{all}) {
  1774.     print OUTPUT "(Run 'eg help --all' for a more detailed list.)\n\n";
  1775.   }
  1776.  
  1777.   # Print valid subcommands sorted by section
  1778.   foreach my $name (sort
  1779.                     {$SECTION->{$a}{'order'} <=> $SECTION->{$b}{'order'}}
  1780.                     keys %$SECTION) {
  1781.     next if $SECTION->{$name}{extra} && !$self->{all};
  1782.     print OUTPUT "$SECTION->{$name}{desc}\n";
  1783.     foreach my $c (sort keys %COMMAND) {
  1784.       next if !defined $COMMAND{$c}{section};
  1785.       next if $COMMAND{$c}{section} ne $name;
  1786.       next if $COMMAND{$c}{extra} && !$self->{all};
  1787.       printf OUTPUT "  eg %-11s %s\n", $c, $COMMAND{$c}{about};
  1788.     }
  1789.     print OUTPUT "\n";
  1790.   }
  1791.  
  1792.   # Check to see if someone added a command with an invalid section
  1793.   my $broken_commands = "";
  1794.   foreach my $c (keys %COMMAND) {
  1795.     next if !defined $COMMAND{$c}{section};
  1796.     next if defined $SECTION->{$COMMAND{$c}{section}};
  1797.     my $tmp = sprintf("  eg %-10s %s\n", $c, $COMMAND{$c}{about});
  1798.     $broken_commands .= $tmp;
  1799.   }
  1800.   if ($broken_commands) {
  1801.     print OUTPUT "Broken (typo in classification?) commands:\n" .
  1802.                  "$broken_commands\n";
  1803.   }
  1804.  
  1805.   # And let them know how to get more detailed help...
  1806.   print OUTPUT "Additional help:\n";
  1807.   print OUTPUT "  eg help COMMAND      Get more help on COMMAND.\n";
  1808.   print OUTPUT "  eg help --all        List more commands (not really all)\n";
  1809.   print OUTPUT "  eg help topic        List specialized help topics.\n";
  1810.  
  1811.   # And let them know how to compare to git
  1812.   if ($self->{all}) {
  1813.     print OUTPUT "\n";
  1814.     print OUTPUT "Learning or comparing to git\n";
  1815.     print OUTPUT "  eg --translate ARGS  Show commands that would be executed for 'eg ARGS'\n";
  1816.     print OUTPUT "  eg --debug ARGS      Show & run commands that would be executed by 'eg ARGS'\n";
  1817.   }
  1818.  
  1819.   close(OUTPUT);
  1820.  
  1821.   exit $self->{exit_status};
  1822. }
  1823.  
  1824. ###########################################################################
  1825. # help::topic                                                             #
  1826. ###########################################################################
  1827. package help::topic;
  1828.  
  1829. sub new {
  1830.   my $class = shift;
  1831.   my $self = {};
  1832.   bless($self, $class);
  1833.   return $self;
  1834. }
  1835.  
  1836. sub middle_of_am {
  1837.   my $continue_text = "
  1838. 1. Standard case
  1839.  
  1840. When all conflicts have been resolved, run
  1841.  eg am --resolved
  1842. Do NOT run \"eg commit\" to continue an interrupted rebase (unless you want
  1843. to manually insert a new commit; if you already accidentally ran eg commit,
  1844. then run 'eg reset HEAD~1' to undo it).  If you try to continue without
  1845. resolving all conflicts, the command will error out and tell you that some
  1846. conflicts remain to be resolved.
  1847.  
  1848. 2. Special case -- skipping a commit
  1849.  
  1850. If you do not want this particular commit to be included in the final
  1851. result, run
  1852.  eg am --skip";
  1853.   my $abort_text = "
  1854. To abort your rebase operation, simply run
  1855.  eg am --abort";
  1856.  
  1857.   return _conflict_resolution_message(op => "am",
  1858.                                       show_empty_case => 1,
  1859.                                       continue_text => $continue_text,
  1860.                                       abort_text => $abort_text
  1861.                                       );
  1862. }
  1863.  
  1864. sub middle_of_merge {
  1865.   my $completion_text = "
  1866. When all conflicts have been resolved, run
  1867.  eg commit
  1868.  
  1869. The log message will be pre-populated with a sample commit message for you,
  1870. noting the merge and any file conflicts.  If you try to run this command
  1871. without resolving all conflicts, the command will error out and tell you
  1872. that some conflicts remain to be resolved.";
  1873.   my $abort_text = "
  1874. To abort your merge operation, simply run
  1875.  eg merge --abort";
  1876.   return _conflict_resolution_message(op => "merge",
  1877.                                       show_empty_case => 0,
  1878.                                       continue_text => $completion_text,
  1879.                                       abort_text => $abort_text);
  1880. }
  1881.  
  1882. sub middle_of_rebase {
  1883.   my $extra_stop_info = "
  1884.  
  1885. If you are in the middle of an interactive rebase (i.e. you specified the
  1886. --interactive flag), then rebase can also stop if you selected to edit a
  1887. commit, even when there are no conflicts.  In such a case where there are
  1888. no conflicts, there is something else you may want to do:
  1889.  5) Editing during an interactive rebase
  1890. Before telling git to continue the operation.";
  1891.   my $continue_text = "
  1892. 1. Standard case
  1893.  
  1894. When all conflicts have been resolved, run
  1895.  eg rebase --continue
  1896. Do NOT run \"eg commit\" to continue an interrupted rebase (unless you want
  1897. to manually insert a new commit; if you already accidentally ran eg commit,
  1898. then run 'eg reset HEAD~1' to undo it).  If you try to continue without
  1899. resolving all conflicts, the command will error out and tell you that some
  1900. conflicts remain to be resolved.
  1901.  
  1902. 2. Special case -- skipping a commit
  1903.  
  1904. If you do not want this particular commit to be included in the final
  1905. result, run
  1906.  eg rebase --skip";
  1907.   my $abort_text = "
  1908. To abort your rebase operation, simply run
  1909.  eg rebase --abort";
  1910.   my $interactive_edit_text = "
  1911. ******************* Editing during an interactive rebase *******************
  1912.  
  1913. When an interactive rebase stops to allow you to edit a commit, make any
  1914. necessary changes to files, then run
  1915.  eg commit --amend
  1916. If you do not use the --amend flag, you will be inserting a new commit
  1917. after the one you chose to edit.
  1918.  
  1919. After you are done amending the previous commit (and/or commit message),
  1920. run 'eg rebase --continue' to allow the rebase operation to continue.
  1921. ";
  1922.   return _conflict_resolution_message(op => "rebase",
  1923.                                       show_empty_case => 1,
  1924.                                       extra_stop_info => $extra_stop_info,
  1925.                                       continue_text => $continue_text,
  1926.                                       abort_text => $abort_text,
  1927.                                       final_text => $interactive_edit_text,
  1928.                                       );
  1929. }
  1930.  
  1931. sub _conflict_resolution_message (%) {
  1932.   my $opts = {op              => "!!!FIXME!!!",
  1933.               show_empty_case => 0,
  1934.               extra_stop_info => '',
  1935.               continue_text   => '!!!FIXME!!!',
  1936.               abort_text      => '!!!FIXME!!!',
  1937.               final_text      => '',
  1938.               @_};  # Hashref initialized as we're told
  1939.   my $result = "
  1940. When conflicting changes are detected, a $opts->{op} operation will stop to
  1941. allow a user to resolve the conflicts.  At this stage there is one of four
  1942. things a user may want to do:
  1943.  1) Find out more about what conflicts occurred
  1944.  2) Resolve the conflicts
  1945.  3) Tell git to complete the operation
  1946.  4) Abort the operation
  1947. Each will be discussed below.$opts->{extra_stop_info}
  1948.  
  1949. *************** Find out more about what conflicts occurred ***************
  1950.  
  1951. 1. Standard case
  1952.  
  1953. In order to find out which files have conflicts, run
  1954.  eg status
  1955. and then look for lines that begin with \"unmerged:\".  You can then open
  1956. the relevant file in an editor and look for lines with conflict markers,
  1957. i.e. lines that start with one of
  1958.  <<<<<<<
  1959.  =======
  1960.  >>>>>>>
  1961. Between the <'s and the ='s will be one version of the changed file, while
  1962. betwen the ='s and the >'s will be another version.
  1963.  
  1964. 2. Simple tip
  1965.  
  1966. Since git will stage any changes it is able to successfully merge, you can
  1967. find the unresolved conflict sections of a file by running
  1968.  eg diff --unstaged FILE
  1969. ";
  1970.   if ($opts->{show_empty_case}) {
  1971.   $result .= "
  1972. 3. Special empty commit case
  1973.  
  1974. Sometimes, during a $opts->{op}, the changes in a commit will no longer be
  1975. necessary since they have already been included in the code which your
  1976. commit is being applied on top of.  In such a case, eg status will simply
  1977. show that there are no changes at all, and you can continue by telling git
  1978. to skip the current unneeded commit (see below).
  1979.  
  1980. 4. Difficult cases
  1981. "
  1982.   } else {
  1983.   $result .= "
  1984. 3. Difficult cases
  1985. ";
  1986.   }
  1987.   $result .= "
  1988. You can run
  1989.  eg ls-files --unmerged
  1990. to get a list of all files in the unmerged state.  This will list up to
  1991. three lines for each file, and look like the following:
  1992.   100644 45b983be36b73c0788dc9cbcb76cbb80fc7bb057 1 foo.C
  1993.   100644 ce013625030ba8dba906f756967f9e9ca394464a 2 foo.C
  1994.   100644 dd7e1c6f0fefe118f0b63d9f10908c460aa317a6 3 foo.C
  1995. The first line corresponds to a version of the file at some common point in
  1996. history, the second and third lines correspond to different versions of the
  1997. file being merged (relative to the common version).  Each line is of the
  1998. form
  1999.  mode   internal-object-name                     stage filename
  2000. The mode represents the permission bits and or type (executable file,
  2001. symlink etc.), the internal-object-name is git's internal name for the
  2002. contents of the file, the stage is a simple integer, and you should
  2003. recognize the filename.
  2004.  
  2005. You can make use of this information to detect the following situations:
  2006.  A) There's a conflict in mode change (e.g. removed the executable bit on
  2007.     one side of history, turned the file into a symlink in another)
  2008.  B) The file is deleted in one version and modified in another (when this
  2009.     happens either the 2nd or 3rd stage line will be missing)
  2010. Further, you can view the different versions of the file easily, by using
  2011. either of:
  2012.  eg show :STAGE:FILENAME
  2013.  eg show INTERNAL-OBJECT-NAME
  2014. Some examples using the output above:
  2015.  eg show :2:foo.C
  2016.  eg show dd7e1c6f0fefe118f0b63d9f10908c460aa317a6
  2017.  
  2018. ************************** Resolve the conflicts **************************
  2019.  
  2020. 1. Standard case.
  2021.  
  2022. For each file with conflicts, edit the file to remove the conflict markers
  2023. and provide just the correct version of the merged file.  Then run
  2024.  eg stage FILE
  2025. to tell git that you have resolved the conflicts in FILE.
  2026.  
  2027. 2. Special cases
  2028.  
  2029. Nearly all special cases (and even the standard case) boil down to making
  2030. sure the file has the correct contents, the correct permission bits and
  2031. type, and then running
  2032.  eg stage FILE
  2033.  
  2034. If the file is a binary, then there will not be any conflict markers.  In
  2035. such a case, simply ensure that the contents of the file are what you want
  2036. and then run eg stage, as noted above.
  2037.  
  2038. If the file is deleted on one side of history and changed in another,
  2039. decide what contents the file should have.  If the correct resolution is to
  2040. delete the file, run
  2041.  eg rm FILE
  2042. Otherwise, put the appropriate contents in the file and run eg stage as
  2043. noted above.
  2044.  
  2045. If the file has a mode conflict, then fix up the mode of the file (run
  2046. 'man chmod' and 'man ln' for help on how to do so).  Note that the modes
  2047. used by git are as follows:
  2048.  100644  --  Normal, non-executable file
  2049.  100755  --  File with the executable bit set
  2050.  120000  --  symlink
  2051.  160000  --  A git submodule (run 'git help submodule' for more info)
  2052.  
  2053. ******************** Tell git to continue the operation ********************
  2054. $opts->{continue_text}
  2055.  
  2056. *************************** Abort the operation ***************************
  2057. $opts->{abort_text}
  2058. ";
  2059.   $result .= $opts->{final_text};
  2060.   return $result;
  2061. }
  2062.  
  2063. sub middle_of_bisect {
  2064.   return "
  2065. When git is bisecting, it will pick commits that need to be tested, check
  2066. them out, and then let you test them.  (Unless, of course, you give git a
  2067. script that it can run to automatically test commits.)  At this point you
  2068. can test and then:
  2069.  
  2070. 1) Continue
  2071.  
  2072.  eg bisect good    # Mark the current commit as good, give me a new commit
  2073. OR
  2074.  eg bisect bad     # Mark the current commit as bad, give me a new commit
  2075.  
  2076. 2) Skip this particular commit
  2077.  
  2078.  eg bisect skip    # Can't test the current version; give me a new commit
  2079.  
  2080. 3) Abort
  2081.  
  2082.  eg bisect reset
  2083.  
  2084. See 'git help bisect' for more details."
  2085. }
  2086.  
  2087. sub refspecs {
  2088.   return "
  2089. Before reading up on refspecs, be sure you understand all the following
  2090. help pages:
  2091.  eg help merge
  2092.  eg help pull
  2093.  eg help push
  2094.  eg help rebase
  2095.  eg help remote
  2096.  eg help topic storage
  2097. refspecs compress knowledge from pieces of all those things into a short
  2098. amount of space.
  2099.  
  2100. refspecs are command line parameters to eg push or eg pull, used at the end
  2101. of the command line.  refspecs provide fine-grained control of pushing and
  2102. pulling changes in the following two areas:
  2103.  Since branches, tags, and remote tracking branches are all implemented by
  2104.  creating simple files consisting solely of a sha1sum, it is possible to
  2105.  push to or pull from different reference names and different reference
  2106.  types.
  2107.  
  2108.  Pushing and pulling of (possibly remote tracking) branches are typically
  2109.  accompanied by sanity checks to make sure the sha1sums on each end are
  2110.  related (to make sure that updates don't throw away previous commits, for
  2111.  example).  In some cases it is desirable to ignore such checks, such as
  2112.  when a branch has been rebased or commits have been amended.
  2113.  
  2114. The canonical format of a refspec is
  2115.  [+]SRC:DEST
  2116. That is, an optional plus character followed by a source reference, then a
  2117. colon character, then the destination reference.  There are a couple
  2118. special abbreviations, noted in the abbreviations section below.  The
  2119. meaning and syntax of the parts of a refspec are discussed next.
  2120.  
  2121. General source and destination handling
  2122.  Both the source and the destination reference are typically named by
  2123.  their path specification under the .git directory.  Examples:
  2124.    refs/heads/bob            # branch: bob
  2125.    refs/tags/v2.0            # tag: v2.0
  2126.    refs/remotes/jill/stable  # remote-tracking branch: jill/stable
  2127.  Leading directory paths can be omitted if no ambiguity would result.
  2128.  
  2129.  The refspec specifies that the push or pull operation should take the
  2130.  sha1sum from SRC in the source repository, and use it to fast-foward DEST
  2131.  in the destination repository.  The operation will fail if updating DEST
  2132.  would not be a fast-foward, unless the optional plus in the refspec is
  2133.  present.
  2134.  
  2135.  Pull operations are somewhat unusual.  For a pull, DEST is usually not
  2136.  the current branch.  In such cases, the current branch is also updated
  2137.  after DEST is.  The method of updating depends on whether --rebase was
  2138.  specified, and whether the latest revision of the current branch is an
  2139.  ancestor of the revision stored by DEST:
  2140.    If --rebase is specified:
  2141.      Rebase the current branch against DEST
  2142.    If --rebase is not specified, current branch is an ancestor of DEST:
  2143.      Fast-forward the current branch to DEST
  2144.    If --rebase is not specified, current branch is not an ancestor of DEST:
  2145.      Merge DEST into the current branch
  2146.  
  2147. Overriding push and pull sanity checks
  2148.  For both push and pull operations, the operation will fail if updating
  2149.  DEST to SRC is not a fast-forward.  This tends to happen in a few
  2150.  different circumstances:
  2151.    For pushes:
  2152.      * If someone else has pushed updates to the specified location
  2153.        already -- in such cases one should resolve the problem by doing a
  2154.        pull before attempting a push rather than overriding the safety
  2155.        check.
  2156.      * If one has rewritten history (e.g. using rebase, commit --amend,
  2157.        reset followed by subsequent commits)
  2158.    For pulls:
  2159.      * If one is pulling to a branch instead of a remote tracking branch
  2160.        -- in such a case, one should instead either specify a remote
  2161.        tracking branch for DEST or specify an empty DEST rather than
  2162.        overriding the safety check.
  2163.      * If one has somehow recorded commits directly to a remote tracking
  2164.        branch
  2165.      * If history has been rewritten on the remote end (e.g. by using
  2166.        rebase, commit --amend, reset followed by subsequent commits).
  2167.  In all such cases, users can choose to throw away any existing unique
  2168.  commits at the DEST end and make DEST record the same sha1sum as SRC, by
  2169.  using a plus character at the beginning of the refspec.
  2170.  
  2171. Abbreviations of refspecs
  2172.  Globbing syntax
  2173.    For either pushes or pulls, one can use a globbing syntax, such as
  2174.      refs/heads/*:refs/remotes/jim/*
  2175.    or
  2176.      refs/heads/*:refs/heads/*
  2177.    in order to specify pulling or pushing multiple locations at once.
  2178.  
  2179.  The following special abbreviations are allowed for both pushes and pulls:
  2180.    tag TAG
  2181.      This is equivalent to specifying refs/tags/TAG:refs/tags/TAG.
  2182.  
  2183.  The following special abbreviations are allowed for pushes:
  2184.    :REFERENCE
  2185.      This specifies delete the reference at the remote end (think of it as
  2186.      \"using nothing to update the remote reference\")
  2187.  
  2188.    REFERENCE
  2189.      This is the same as REFERENCE:REFERENCE
  2190.  
  2191.  The following special abbreviations are allowed for pulls:
  2192.    REFERENCE:
  2193.      This is used to merge REFERENCE into the current branch directly
  2194.      without storing the remote branch in some remote tracking branch.
  2195.  
  2196.    REFERENCE
  2197.      This is the same as REFERENCE: which is explained above.
  2198. ";
  2199. }
  2200.  
  2201.  
  2202. sub remote_urls {
  2203. #
  2204. # NOTE: The help for remote_urls is basically lifted from the git manpages,
  2205. # which are licensed under GPLv2 (as is eg).
  2206. #
  2207.   return "
  2208. Any of the following notations can be used to name a remote repository:
  2209.  rsync://host.xz/path/to/repo.git/
  2210.  http://host.xz/path/to/repo.git/
  2211.  https://host.xz/path/to/repo.git/
  2212.  git://host.xz/path/to/repo.git/
  2213.  git://host.xz/~user/path/to/repo.git/
  2214.  ssh://[user@]host.xz[:port]/path/to/repo.git/
  2215.  ssh://[user@]host.xz/path/to/repo.git/
  2216.  ssh://[user@]host.xz/~user/path/to/repo.git/
  2217.  ssh://[user@]host.xz/~/path/to/repo.git
  2218. You can also use any of the following, which are identical to the last
  2219. three above, respectively
  2220.  [user@]host.xz:/path/to/repo.git/
  2221.  [user@]host.xz:~user/path/to/repo.git/
  2222.  [user@]host.xz:path/to/repo.git
  2223. Finally, you can also use the following notation to name a not-so-remote
  2224. repository:
  2225.  /path/to/repo.git/
  2226.  file:///path/to/repo.git/
  2227. These last two are identical other than that the latter disables some local
  2228. optimizations (such as hardlinking copies of history when cloning, in order
  2229. to save disk space).
  2230. ";
  2231. }
  2232.  
  2233. sub revisions {
  2234. #
  2235. # NOTE: The pictoral example of revision suffixes is taken from the
  2236. # git-rev-parse manpage, which is licensed under GPLv2 (as is eg).
  2237. #
  2238.   return "
  2239. There are MANY different ways to refer to revisions (also referred to as
  2240. commits) of the repository.  Most are only needed for fine-grained control
  2241. in very large projects; the basics should be sufficient for most.
  2242.  
  2243. Basics
  2244.  The most common ways of referring to revisions (or commits), are:
  2245.    - Branch or tag name (e.g. stable, v0.77, master, 2.28branch, version-1-0)
  2246.    - Counting back from another revision (e.g. stable~1, stable~2, stable~3)
  2247.    - Cryptographic checksum (e.g. dae86e1950b1277e545cee180551750029cfe735)
  2248.    - Abbreviated checksum (e.g. dae86e)
  2249.  
  2250.  The output of 'eg log' shows (up to) two names for each revision: its
  2251.  cryptographic checksum and the count backward relative to the currently
  2252.  active branch (if the revision being shown in eg log is not part of the
  2253.  currently active branch then only the cryptographic checksum is shown).
  2254.  
  2255.  One can always check the validity of a revision name and what revision
  2256.  it refers to using 'eg log -1 REVISION' (the -1 to show only one revision).
  2257.  
  2258. Branches and Tags
  2259.  Users can specify a tag name to refer to the revision marked by that tag.
  2260.  Run 'eg tag' to get a list of existing tags.
  2261.  
  2262.  Users can specify a branch name to refer to the most recent revision of
  2263.  that branch.  Use 'eg branch' to get a list of existing branches.
  2264.  
  2265. Cryptographic checksums
  2266.  Each revision of a repository has an associated cryptographic checksum
  2267.  (in particular, a sha1sum) identifying it.  This cryptographic checksum
  2268.  is a sequence of 40 letters and numbers from 0-9 and a-f.  For example,
  2269.    dae86e1950b1277e545cee180551750029cfe735
  2270.  In addition to using these sha1sums to refer to revisions, one can also
  2271.  use an abbreviation of a sha1sum so long as enough characters are used to
  2272.  uniquely identify the revision (typically 6-8 characters are enough).
  2273.  
  2274. Special Names
  2275.  There are a few special revision names.
  2276.  
  2277.  Names that always exist:
  2278.    HEAD - A reference to the most recent revision of the current branch
  2279.           (thus HEAD refers to the same revision as using the branch
  2280.           name).  If there is no active branch, such as after running
  2281.           'eg switch TAG', then HEAD refers to the revision switched to.
  2282.  
  2283.           Note that the files in the working copy are always considered to
  2284.           be a (possibly modifed) copy of the revision pointed to by HEAD.
  2285.  
  2286.  Names that only exist in special cases:
  2287.    ORIG_HEAD -  Some operations (such as merge or reset) change which
  2288.                 revision the working copy is relative to.  These will
  2289.                 record the old value of HEAD in ORIG_HEAD.  This allows
  2290.                 one to undo such operations by running
  2291.                   eg reset --working-copy ORIG_HEAD
  2292.    FETCH_HEAD - When downloading branches from other repositories (via
  2293.                 the fetch or pull commands), the tip of the last fetched
  2294.                 branch is stored in FETCH_HEAD.
  2295.    MERGE_HEAD - If a merge operation results in conflicts, then the merge
  2296.                 will stop and wait for you to manually fix the conflicts.
  2297.                 In such a case, MERGE_HEAD will store the tip of the
  2298.                 branch(es) being merged into the current branch.  (The
  2299.                 current branch can be accessed, as always, through HEAD.)
  2300.  
  2301. Suffixes for counting backwards
  2302.  There are two suffixes for counting backwards from revisions to other
  2303.  revisions: ~ and ^.
  2304.  
  2305.  Adding ~N after a revision, with N a non-negative integer, means to count
  2306.  backwards N commits before the specified revision.  If any revision along
  2307.  the path has more than one parent (i.e. if any revision is a merge
  2308.  commit), then the first parent is always followed.  Thus, if stable is a
  2309.  branch, then
  2310.    stable   means the last revision on the stable branch
  2311.    stable~1 means one revision before the last on the stable branch
  2312.    stable~2 means two revisions before the last on the stable branch
  2313.    stable~3 means three revisions before the last on the stable branch
  2314.  In short, ~N goes back N generation of parents, always following the
  2315.  first parent.
  2316.  
  2317.  Adding ^N after a revision, with N a non-negative integer, means the Nth
  2318.  parent of the specified revision.  N can be omitted in which case it is
  2319.  assumed to have the value 1.  Thus, if stable is a branch, then
  2320.    stable   means the last revision on the stable branch
  2321.    stable^1 means the first parent of the last revision on the stable branch
  2322.    stable^2 means the second parent of the last revision on the stable branch
  2323.    stable^3 means the third parent of the last revision on the stable branch
  2324.  In short, ^N picks out one parent from the first generation of parents.
  2325.  
  2326.  Revisions with suffixes can themselves have suffixes, thus
  2327.    stable~5 = stable~3~2
  2328.  
  2329.  Here is an illustration with an unusually high amount of merging.  The
  2330.  illustration has 10 revisions each tagged with a different letter of the
  2331.  alphabet, with A referring to the most recent revision:
  2332.                A
  2333.               / \\
  2334.              /   \\
  2335.             B     C
  2336.            /|\\    |
  2337.           / | \\   |
  2338.          /  |  \\ /
  2339.         D   E   F
  2340.        / \\     / \\
  2341.       G   H   I   J
  2342.  
  2343.  From the illustration, the following equalities hold:
  2344.       A =      = A^0
  2345.       B = A^   = A^1     = A~1
  2346.       C = A^2  = A^2
  2347.       D = A^^  = A^1^1   = A~2
  2348.       E = B^2  = A^^2
  2349.       F = B^3  = A^^3
  2350.       G = A^^^ = A^1^1^1 = A~3
  2351.       H = D^2  = B^^2    = A^^^2  = A~2^2
  2352.       I = F^   = B^3^    = A^^3^
  2353.       J = F^2  = B^3^2   = A^^3^2
  2354.  
  2355. Revisions from logged branch tip history
  2356.  By default, all changes to each branch and to the special identifier HEAD
  2357.  are recorded in something called a reflog (short for \"reference log\",
  2358.  because calling it a \"branch log\" would not have made the glossary of
  2359.  special terms long enough).  Each entry of the reflog records the
  2360.  previous revision recorded by the branch, the new revision the branch was
  2361.  changed to, the command used to make the change (commit, merge, reset,
  2362.  pull, checkout, etc.), and when the change was made.  One can get an
  2363.  overview of the changes made to a branch (including the special branch
  2364.  'HEAD') by running
  2365.    eg reflog show BRANCHNAME
  2366.  
  2367.  One can make use of the reflog to refer to revisions that a branch used
  2368.  to point to.  The format for referring to revisions from the reflog are
  2369.    BRANCH\@{HISTORY_REFERENCE}
  2370.  Examples follow.
  2371.  
  2372.  Revisions that the branch pointed to, in order
  2373.    Assuming that ultra-bling is the name of a branch, the following can be
  2374.    used to refer to revisions ultra-bling used to point to:
  2375.      ultra-bling\@{0} is the same as ultra-bling
  2376.      ultra-bling\@{1} is the revision pointed to before the last change
  2377.      ultra-bling\@{2} is the revision ultra-bling pointed to two changes ago
  2378.      ultra-bling\@{3} is the revision ultra-bling pointed to three changes ago
  2379.    Note that any of these beyond the first could easily refer to commits
  2380.    that are no longer part of the ultra-bling branch (due to using a
  2381.    command like reset or commit --amend).
  2382.  
  2383.  Revisions that the branch pointed to at a previous time
  2384.    Assuing that fixes is the name of a branch, the following can be used to
  2385.    refer to revisions that fixes used to point to:
  2386.      fixes\@{yesterday}           - revision fixes pointed to yesterday
  2387.      fixes\@{1 day 3 hours ago}   - revision fixes pointed to 1 day 3 hours ago
  2388.      fixes\@{2008-02-29 12:34:00} - revision fixes had at 12:34 on Feb 29, 2008
  2389.    Again, these could refer to revisions that are no longer part of the
  2390.    fixes branch,
  2391.  
  2392.  Using the branch log can be used to recover \"lost\" revisions that are
  2393.  no longer part of (or have never been part of) any branch reported by 'eg
  2394.  branch'.
  2395.  
  2396. Commit messages
  2397.  One can also refer a revision using the beginning of the commit message
  2398.  recorded in it.  This is done using with the two-character prefix :/
  2399.  followed by the beginning of the commit message.  Note that quotation marks
  2400.  are also often used to avoid having the shell split the commit message into
  2401.  different arguments.  Examples:
  2402.    :/\"Fix the biggest bug blocking the 1.0 release\"
  2403.    :/\"Make the translation from url\"
  2404.    :/\"Add a README file\"
  2405.  Note that if the commit message starts with an exclamation mark ('!'), then
  2406.  you need to type two of them; for example example:
  2407.    :/\"!!Commit messages starting with an exclamation mark are retarded\"
  2408.  
  2409. Other methods
  2410.  There are even more methods of referring to revisions.  Run \"man
  2411.  git-rev-parse\", and look for the \"SPECIFYING REVISIONS\" section for
  2412.  more details.
  2413. ";
  2414. }
  2415.  
  2416. sub staging {
  2417.   return "
  2418. Marking changes from certain files as ready for commit allows you to split
  2419. your changes into two distinct sets (those that are ready for commit, and
  2420. those that aren't).  This includes support for limiting diffs to changes in
  2421. one of these two sets, and for committing just the changes that are ready.
  2422. It's a simple feature that comes in surprisingly handy:
  2423.  
  2424.  * When doing conflict resolution from large merges, hunks of changes can
  2425.    be categorized into known-to-be-good and still-needs-more-fixing
  2426.    subsets.
  2427.  
  2428.  * When reviewing a largish patch from someone else, hunks of changes can
  2429.    be categorized into known-to-be-good and still-needs-review subsets.
  2430.  
  2431.  * By staging your changes, you can go ahead and add temporary debugging
  2432.    code and have less fear of forgetting to remove it before committing --
  2433.    you will be warned about having both staged and unstaged changes at
  2434.    commit time, and you will have an easy way to locate the temporary
  2435.    code.
  2436.  
  2437.  * It makes it easier to keep \"dirty\" changes in your working copy for a
  2438.    long time without committing them.
  2439.  
  2440. Staging changes and working with staged changes
  2441.  Mark all changes in foo.py and baz.c as ready to be committed
  2442.    eg stage foo.py baz.c
  2443.  
  2444.  Selectively stage part of the changes
  2445.    eg stage -p
  2446.  (You will be asked whether to stage each change, listed in diff format;
  2447.  the main options to know are \"y\" for yes, \"n\" for no, and \"s\" for
  2448.  splitting the selected change into smaller changes; see 'git help add' for
  2449.  more details).
  2450.  
  2451.  Get all unstaged changes to bar.C and foo.pl
  2452.    eg diff --unstaged foo.pl bar.C
  2453.  
  2454.  Get all staged changes
  2455.    eg diff --staged
  2456.  
  2457.  Get all changes
  2458.    eg diff
  2459.  
  2460.  Revert the staged changes to bar.C, foo.pl and foo.py
  2461.    eg unstage bar.C foo.pl foo.py
  2462.  
  2463.  Commit just the staged changes
  2464.    eg commit --staged
  2465. ";
  2466. }
  2467.  
  2468. sub storage {
  2469.   return "
  2470. Basics
  2471.  Each revision is referred to by a cryptographic checksum (in particular,
  2472.  a sha1sum) of its contents.  Each revision also knows which revision(s)
  2473.  it was derived from, known as the revision's parent(s).
  2474.  
  2475.  Each branch records the cryptographic checksum of the most recent commit
  2476.  for the branch.  Since each commit records its parent(s), a branch
  2477.  consists of its most recent commit plus all ancestors of that commit.
  2478.  When a new commit is made on a branch, the branch just replaces the
  2479.  cryptographic checksum of the old commit with the new one.
  2480.  
  2481.  Remote tracking branches, if used (see 'eg help remote'), differ from
  2482.  normal branches only in that they have a slash in their name.  For
  2483.  example, the remote tracking branch that tracks the contents of the
  2484.  stable branch of the remote named bob would be called bob/stable.  By
  2485.  their nature, remote tracking branches only track the contents of a
  2486.  branch of a remote repository; one does not switch to and commit to these
  2487.  branches.
  2488.  
  2489.  Tags simply record a single revision, much like branches, but tags are
  2490.  not advanced when additional commits are made.  Tags are not stored as
  2491.  part of a branch, though by default tags that point to commits which are
  2492.  downloaded (as part of merging changes from a branch) are themselves
  2493.  downloaded as well.
  2494.  
  2495.  Neither branches nor tags are revision controlled, though there is a log
  2496.  of changes made to each branch (known as a reflog, short for \"reference
  2497.  log\", because calling it a \"branch log\" wouldn't make the glossary of
  2498.  special terms long enough).
  2499.  
  2500. Pictorial explanation
  2501.  Using the letters A-P as shorthand for different revisions and their
  2502.  cryptographic checksums (which we'll assume were created in the order
  2503.  A...P for purposes of illustration), an example of the kind of structure
  2504.  built up by having commits track their parents is:
  2505.        N
  2506.        |
  2507.        M   P
  2508.        |   |
  2509.        L   O
  2510.        | \\ |
  2511.        J   K
  2512.        |   |
  2513.        H   I
  2514.        | /
  2515.        G
  2516.        |
  2517.        F
  2518.       / \\
  2519.      C   E
  2520.      |   |
  2521.      B   D
  2522.      |
  2523.      A
  2524.  In this picture, F has two parents (C and E) and is thus a merge commit.
  2525.  L is also a merge commit, having parents J and K.  There are two branches
  2526.  depicted here, which can be identified by N and P (due to the fact that
  2527.  branches simply track their most recent commit).  This history is
  2528.  somewhat unusual in that there is no unique start of history; instead
  2529.  there are two beginnings of history -- A and D.  Such a history can be
  2530.  created by pulling from, and merging with, a branch from another
  2531.  repository that shares no common history.  While unusual, it is fully
  2532.  supported.
  2533.  
  2534.  For further illustration, let's assume that the following branches exist:
  2535.      stable: N
  2536.      bling:  P
  2537.  Then the picture of each branch, side by side (using revision identifiers
  2538.  explained in 'eg help topic revisions'), is:
  2539.            stable
  2540.              |
  2541.           stable~1                                     bling
  2542.              |                                           |  
  2543.           stable~2                                    bling~1
  2544.              |   \\                                       |  
  2545.        stable~3  stable~2^2                           bling~2
  2546.              |     |                                     |  
  2547.        stable~4  stable~2^2~1                         bling~3
  2548.              |  /                                     /      
  2549.          stable~6                                bling~4    
  2550.              |                                     |        
  2551.          stable~7                                bling~5    
  2552.            /   \\                                 /   \\      
  2553.      stable~8  stable~7^2                   bling~6  bling~5^2
  2554.          |       |                             |       |    
  2555.      stable~9  stable~7^2~1                 bling~7  bling~5^2~1    
  2556.          |                                     |            
  2557.      stable~10                              bling~8            
  2558.  Note that there are many commits which are part of both branches,
  2559.  including two commits (I and K in the original picture) which were
  2560.  probably created after these two branches separated.  This is simply due
  2561.  to recording both parents in merge commits.
  2562.  
  2563.  Note that this tree-like or graph-like structure of branches is an
  2564.  example of something that computer scientists call a Directed Acyclic
  2565.  Graph (DAG); referring to it as such provides us the opportunity to
  2566.  make the glossary of special terminology longer.
  2567.  
  2568. Files and directories in a git repository (stuff under .git)
  2569.  You may find the following files and directories in your git repository.
  2570.  This document will discuss the highlights; see the repository-layout.html
  2571.  page distributed with git for more details.
  2572.  
  2573.  COMMIT_EDITMSG
  2574.    A leftover file from previous commits; this is the file that commit
  2575.    messages are recorded to when when you do not specify a -m or -F option
  2576.    to commit (thus causing an editor to be invoked).
  2577.  
  2578.  config
  2579.    A simple text file recording configuration options; see 'eg help config'.
  2580.  
  2581.  description
  2582.    A file that is only used by gitweb, currently.  If you use gitweb, this
  2583.    files provides a description of the project tracked in the repository.
  2584.  
  2585.  HEAD
  2586.  ORIG_HEAD
  2587.  FETCH_HEAD
  2588.  MERGE_HEAD
  2589.    See the Special Names section of 'eg help topic revisions'; these files
  2590.    record these special revisions.
  2591.  
  2592.  git-daemon-export-ok
  2593.    This file is only relevant if you are using git-daemon, a server to
  2594.    provide access to your repositories via the git:// protocol.
  2595.    git-daemon refuses to provide access to any repository that does not
  2596.    have a git-daemon-export-ok file.
  2597.  
  2598.  hooks
  2599.    A directory containing customizations scripts used by various commands.
  2600.    These scripts are only used if they are executable.
  2601.  
  2602.  index
  2603.    A binary file which records the staging area.  See 'eg help topic
  2604.    staging' for more information.
  2605.  
  2606.  info
  2607.    A directory with additional info about the repository
  2608.  
  2609.    info/exclude
  2610.      An additional place to specify ignored files.  Users typically use
  2611.      .gitignore files in the relevant directories to ignore files, but
  2612.      ignored files can also be listed here.
  2613.  
  2614.    info/ignored-unknown
  2615.      A list of unknown files known to exist previously, used to determine
  2616.      whether unknown files should cause commit (or push or publish) to
  2617.      abort.  See 'eg help commit' for more information; this list is
  2618.      updated whenever the -b flag is passed to commit.
  2619.  
  2620.    info/refs
  2621.      This is a file created by 'eg update-server-info' and is needed for
  2622.      repositories accessed over http.
  2623.  
  2624.  logs
  2625.    History of changes to references (i.e. to branches, tags, or
  2626.    remote-tracking branches).  The file logs/PATH/TO/FILE in the
  2627.    repository records the changes to the reference PATH/TO/FILE in the
  2628.    repository.  See also the 'Revisions from logged branch tip history'
  2629.    section of 'eg help topic revisions'.
  2630.  
  2631.  objects
  2632.    Storage of actual user data (files, directory trees, commit objects).
  2633.    Storage is done according to sha1sum of each object (splitting sha1sums
  2634.    into a combination of directory name and file name).  There are also
  2635.    packs, which compress many objects into one file for tighter storage
  2636.    and reduced disk usage.
  2637.  
  2638.  packed-refs
  2639.    The combination of paths, filenames, and sha1sums from many different
  2640.    refs -- one per line; see refs below.
  2641.  
  2642.  refs
  2643.    Storage of references (branches, heads, or remote tracking branches).
  2644.    Each reference is a simple file consisting of a sha1sum (see 'eg help
  2645.    topic storage' for more information).  The path provides the type of
  2646.    the reference, the file name provides the name for the reference, and
  2647.    the sha1sum is the revision the reference refers to.
  2648.  
  2649.    Branches are stored under refs/heads/*, tags under refs/tags/*, and
  2650.    remote tracking branches under refs/remotes/REMOTENAME/*.  Note that
  2651.    some of these references may appear in packed-refs instead of having
  2652.    a file somewhere under the refs directory.
  2653. ";
  2654. }
  2655.  
  2656. sub help {
  2657.   my $self = shift;
  2658.   my $help_msg;
  2659.  
  2660.   # Get the topic we want more info on (replace dashes, since they can't
  2661.   # be in function names)
  2662.   my $topic = shift @ARGV;
  2663.   my $orig_topic = $topic;
  2664.   $topic =~ s/-/_/g if $topic;
  2665.  
  2666.   ### FIXME: Add the following topics, plus maybe some others
  2667.   # glossary      <Not yet written; this is just a stub>
  2668.  
  2669.   my $topics = "
  2670. middle-of-am      How to resolve or abort an incomplete am (apply mail)
  2671. middle-of-bisect  How to continue or abort a bisection
  2672. middle-of-merge   How to resolve or abort an incomplete merge
  2673. middle-of-rebase  How to resolve or abort an incomplete rebase
  2674.  
  2675. refspecs      Advanced pushing and pulling: detailed control of storage
  2676. remote-urls   Format for referring to remote (and not-so-remote) repositories
  2677. revisions     Various methods for referring to revisions
  2678. staging       Marking a subset of the local changes ready for committing
  2679. storage       High level overview of how commits, tags, and branches are stored
  2680. ";
  2681.  
  2682.   if (defined $topic) {
  2683.     die "No topic help for '$topic' exists.  Try 'eg help topic'.\n"
  2684.       if !$self->can($topic);
  2685.     $help_msg = $self->$topic();
  2686.     if ($topics =~ m#^(\Q$orig_topic\E.*)#m) {
  2687.       $topic = $1;
  2688.     }
  2689.   } else {
  2690.     $topic = "Topics";
  2691.     $help_msg = $topics;
  2692.   }
  2693.  
  2694.   $ENV{"LESS"} = "FRSX" unless defined $ENV{"LESS"};
  2695.   my $less = ($USE_PAGER == 1) ? "less" :
  2696.              ($USE_PAGER == 0) ? "cat" :
  2697.              `$GIT_CMD config core.pager` || "less";
  2698.   chomp($less);
  2699.   open(OUTPUT, "| $less");
  2700.   print OUTPUT "$topic\n";
  2701.   print OUTPUT $help_msg;
  2702.   close(OUTPUT);
  2703.  
  2704.   exit 0;
  2705. }
  2706.  
  2707. ###########################################################################
  2708. # info                                                                    #
  2709. ###########################################################################
  2710. package info;
  2711. @info::ISA = qw(subcommand);
  2712. INIT {
  2713.   $COMMAND{info} = {
  2714.     new_command => 1,
  2715.     section => 'discovery',
  2716.     extra => 1,
  2717.     about => 'Show some basic information about the current repository'
  2718.     };
  2719. }
  2720.  
  2721. sub new {
  2722.   my $class = shift;
  2723.   my $self = $class->SUPER::new(git_equivalent => '', git_repo_needed => 0, @_);
  2724.   bless($self, $class);
  2725.   $self->{'help'} = "
  2726. Usage:
  2727.  eg info [/PATH/TO/REPOSITORY]
  2728.  
  2729. Description:
  2730.  Shows information about the specified repository, or the current
  2731.  repository if none is specified.
  2732.  
  2733.  Most of the output of eg info is self-explanatory, but some fields
  2734.  benefit from extra explanation or pointers about where to find related
  2735.  information.  These fields are:
  2736.  
  2737.    Total commits
  2738.      The total number of commits (or revisions) found in the repository.
  2739.      eg log can be used to view revision authors, dates, and commit log
  2740.      messages.
  2741.  
  2742.    Local repository
  2743.      eg has a number of files and directories it uses to track your data,
  2744.      including (by default) a copy of the entire history of the project.
  2745.      These files and directories are all stored below a single directory,
  2746.      referred to as the local repository.  See 'eg help topic storage' for
  2747.      more details.
  2748.  
  2749.    Named remote repositories
  2750.      To make it easier to track changes from multiple remote repositories,
  2751.      eg provides the ability to provide nicknames for and work with
  2752.      multiple branches from a remote repository and even working with
  2753.      multiple remote repositories at once.  See 'eg help remote' for more
  2754.      details, though you will want to make sure you understand 'eg help
  2755.      pull' and 'eg help push' first.
  2756.  
  2757.    Current branch
  2758.      All development is done on a branch, though smaller projects may only
  2759.      use one branch per repository (thus making the repository effectively
  2760.      serve as a branch).  In contrast to cvs and svn which refer to
  2761.      mainline development as \"HEAD\" and \"TRUNK\", respectively, eg
  2762.      calls the mainline development a branch as well, with the default
  2763.      name of \"master\").  See 'eg help branch' and 'eg help topic
  2764.      storage' for more details.
  2765.  
  2766.    Cryptographic checksum
  2767.      Each revision has an associated cryptographic checksum of both its
  2768.      contents and the revision(s) it was derived from, providing strong
  2769.      data consistency checks and guarantees.  These checksums are shown in
  2770.      the output of eg log, and serve as a way to refer to revisions.  See
  2771.      also 'eg help topic storage' for more details.
  2772.  
  2773.    Default pull/push configuration options:
  2774.      The default repository to push to or pull from defaults to 'origin',
  2775.      if the 'origin' remote has been set up (see 'eg help remote' for
  2776.      setting up remote repository nicknames).
  2777.  
  2778.      However, the default repository can be set on a per-branch basis as a
  2779.      configuration option (see 'eg help config').  In fact, a number of
  2780.      default pull/push actions can be set as per-branch configuration
  2781.      options: default merge options to use on a given branch, default
  2782.      branch to merge with from the remote repository, and whether to
  2783.      rebase (rewrite local commits on top of new remote commits; see 'eg
  2784.      help rebase') rather than merge (keep local commits as they are and
  2785.      just make a merge commit combining local and remote changes; see 'eg
  2786.      help merge').
  2787.  
  2788. ";
  2789.   $self->{'differences'} = '
  2790.  eg info is unique to eg; git does not have a similar command.  It
  2791.  originally was intended just to do something nice if svn converts happen
  2792.  to try this command, but I have found it to be a really nice way of
  2793.  helping users get their bearings.  It also provides some nice statistics
  2794.  that git users may appreciate (particularly when it comes time to fill
  2795.  out the Git User Survey).
  2796. ';
  2797.   return $self;
  2798. }
  2799.  
  2800. sub preprocess {
  2801.   my $self = shift;
  2802.  
  2803.   my $path = shift @ARGV;
  2804.   die "Aborting: Too many arguments to eg info.\n" if @ARGV;
  2805.  
  2806.   if ($path) {
  2807.     die "$path does not look like a directory.\n" if ! -d $path;
  2808.     my ($ret, $useless_output) =
  2809.       ExecUtil::execute_captured("$GIT_CMD ls-remote $path", ignore_ret => 1);
  2810.     if ($ret != 0) {
  2811.       die "$path does not appear to be a git archive " .
  2812.           "(maybe it has no commits yet?).\n";
  2813.     }
  2814.     chdir($path);
  2815.   }
  2816.  
  2817.   # Set git_dir
  2818.   $self->{git_dir} = RepoUtil::git_dir();
  2819.   die "Must be run inside a git repository!\n" if !defined $self->{git_dir};
  2820. }
  2821.  
  2822. sub run {
  2823.   my $self=shift;
  2824.  
  2825.   my $branch = RepoUtil::current_branch();
  2826.  
  2827.   #
  2828.   # Special case the situation of no commits being present
  2829.   #
  2830.   if (RepoUtil::initial_commit()) {
  2831.     if ($DEBUG < 2) {
  2832.       print STDERR <<EOF;
  2833. Total commits: 0
  2834. Local repository: $self->{git_dir}
  2835. There are no commits in this repository.  Please use eg stage to mark new
  2836. files as being ready to commit, and eg commit to commit them.
  2837. EOF
  2838.     }
  2839.     exit 1;
  2840.   }
  2841.  
  2842.   #
  2843.   # Repository-global information
  2844.   #
  2845.  
  2846.   # total commits
  2847.   my $total_commits = ExecUtil::output("$GIT_CMD rev-list --all | wc -l");
  2848.   print "Total commits: $total_commits\n" if $DEBUG < 2;
  2849.  
  2850.   # local repo
  2851.   print "Local repository: $self->{git_dir}\n" if $DEBUG < 2;
  2852.  
  2853.   # named remote repos
  2854.   my %remotes;
  2855.   my $longest = 0;
  2856.   my @abbrev_remotes = split('\n', ExecUtil::output("$GIT_CMD remote"));
  2857.   foreach my $remote (@abbrev_remotes) {
  2858.     chomp($remote);
  2859.     my $url = RepoUtil::get_config("remote.$remote.url");
  2860.     $remotes{$remote} = $url;
  2861.     $longest = main::max($longest, length($remote));
  2862.   }
  2863.   if (scalar keys %remotes > 0 && $DEBUG < 2) {
  2864.     print "Named remote repositories: (name -> location)\n";
  2865.     foreach my $remote (sort keys %remotes) {
  2866.       printf "  %${longest}s -> %s\n", $remote, $remotes{$remote};
  2867.     }
  2868.   }
  2869.  
  2870.   #
  2871.   # Stats for the current branch...
  2872.   #
  2873.   return if !defined($branch);
  2874.  
  2875.   # File & directory stats only work if we're in the toplevel directory
  2876.   my ($orig_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();
  2877.   chdir($top_dir);
  2878.  
  2879.   # Name
  2880.   print "Current branch: $branch\n" if $DEBUG < 2;
  2881.  
  2882.   # Sha1sum
  2883.   my $current_commit = ExecUtil::output("$GIT_CMD show-ref -s -h | head -n 1");
  2884.   print "  Cryptographic checksum (sha1sum): $current_commit\n" if $DEBUG < 2;
  2885.  
  2886.   # Default pull/push options
  2887.   my $default = "-None-";
  2888.   my $print_config_options = 0;
  2889.   my ($ret, $options) =
  2890.     ExecUtil::execute_captured("$GIT_CMD config --get-regexp " .
  2891.                                "^branch\.$branch\.*", ignore_ret => 1);
  2892.   chomp($options);
  2893.   my @lines;
  2894.   if ($ret == 0) {
  2895.     @lines = split('\n', $options);
  2896.     my $line_count = scalar(@lines);
  2897.     $print_config_options = ($line_count > 0);
  2898.  
  2899.     if ($options =~ /^branch\.$branch\.remote (.*)$/m) {
  2900.       $default = $1;
  2901.       $print_config_options = ($line_count > 1);
  2902.     } else {
  2903.       my @output = `$GIT_CMD config --get-regexp remote.origin.*`;
  2904.       $default = "origin" if @output;
  2905.     }
  2906.   }
  2907.   print "  Default pull/push repository: $default\n" if $DEBUG < 2;
  2908.   if ($print_config_options && $DEBUG < 2) {
  2909.     print "  Default pull/push options:\n";
  2910.     foreach my $line (@lines) {
  2911.       $line =~ s/\s+/ = /;
  2912.       print "    $line\n";
  2913.     }
  2914.   }
  2915.  
  2916.   # No. contributors
  2917.   my $contributors  = ExecUtil::output("$GIT_CMD shortlog -s -n HEAD | wc -l");
  2918.   print "  Number of contributors: $contributors\n" if $DEBUG < 2;
  2919.  
  2920.   # No. files
  2921.   my $num_files = ExecUtil::output("$GIT_CMD ls-tree -r HEAD | wc -l");
  2922.   print "  Number of files: $num_files\n" if $DEBUG < 2;
  2923.  
  2924.   # No. dirs
  2925.   my $num_dirs = ExecUtil::output(
  2926.                     "$GIT_CMD ls-tree -r -t HEAD " .
  2927.                     " | grep -E '[0-9]+ tree'" .
  2928.                     " | wc -l");
  2929.   print "  Number of directories: $num_dirs\n" if $DEBUG < 2;
  2930.  
  2931.   # Some ugly, nasty code to get the biggest file.  Seems to be the only
  2932.   # method I could find that would work given the corner case filenames
  2933.   # (spaces and unicode chars) in the git.git repo (Try eg info on repo
  2934.   # from 'git clone git://git.kernel.org/pub/scm/git/git.git').
  2935.   my @files = `$GIT_CMD ls-tree -r -l --full-name HEAD`;
  2936.   my %biggest = (name => '', size => 0);
  2937.   foreach my $line (@files) {
  2938.     if ($line =~ m#^[0-9]+ [a-z]+ [0-9a-f]+[ ]*(\d+)[ \t]*(.*)$#) {
  2939.       my ($size, $file) = ($1, $2);
  2940.       if ($file =~ m#^\".*\"#) { $file = eval "$file" };  # Unicode fix
  2941.       if ($size >= $biggest{size}) {
  2942.         $biggest{name} = $file;
  2943.         $biggest{size} = $size;
  2944.       }
  2945.     }
  2946.   }
  2947.   my $biggest_file = "$biggest{size} ($biggest{name})";
  2948.   print "  Biggest file size, in bytes: $biggest_file\n" if $DEBUG < 2;
  2949.  
  2950.   # No. commits
  2951.   my $branch_depth  = ExecUtil::output("$GIT_CMD rev-list HEAD | wc -l");
  2952.   print "  Commits: $branch_depth\n" if $DEBUG < 2;
  2953.  
  2954.   # Other possibilities:
  2955.   #   Disk space used by respository (du -hs .git, or packfile size?)
  2956.   #   Disk space used by working copy (???)
  2957.   #   Number of unpacked objects?
  2958.  
  2959.   chdir($orig_dir);
  2960.  
  2961.   # Well, if we got this far, it must have worked, so...
  2962.   return 0;
  2963. }
  2964.  
  2965. ###########################################################################
  2966. # init                                                                    #
  2967. ###########################################################################
  2968. package init;
  2969. @init::ISA = qw(subcommand);
  2970. INIT {
  2971.   $COMMAND{init} = {
  2972.     unmodified_behavior => 1,
  2973.     section => 'creation',
  2974.     about => 'Create a new repository'
  2975.   };
  2976. }
  2977.  
  2978. sub new {
  2979.   my $class = shift;
  2980.   my $self = $class->SUPER::new(git_repo_needed => 0, @_);
  2981.   bless($self, $class);
  2982.   $self->{'help'} = "
  2983. Usage:
  2984.  eg init [--shared]
  2985.  
  2986. Description:
  2987.  Creates a new repository.
  2988.  
  2989.  If you want to publish a copy of an existing repository so that others
  2990.  can access it, use 'eg publish' instead.
  2991.  
  2992.  Note for cvs/svn users: With cvs or svn it is common to create an empty
  2993.  repository on \"the server\", then check it out locally and start adding
  2994.  files and committing.  With eg, it is more natural to create a repository
  2995.  on your local machine and start creating and adding files, then later
  2996.  (possibly as soon as one commit later) publishing your work to \"the
  2997.  server\".  git (and thus eg) does not currently allow cloning empty
  2998.  repositories, so for now you must change habits.
  2999.  
  3000. Examples:
  3001.  Create a new blank repository, then use it by creating and adding a file
  3002.  to it:
  3003.      \$ mkdir project
  3004.      \$ cd project
  3005.      \$ eg init
  3006.      Create and edit a file called foo.py
  3007.      \$ eg stage foo.py
  3008.      \$ eg commit
  3009.  
  3010.  Create a repository to track further changes to an existing project.  Then
  3011.  start using it right away
  3012.      \$ cd cool-program
  3013.      \$ eg init
  3014.      \$ eg stage .           # Recursively adds all files
  3015.      \$ eg commit -m \"Initial import of all files\"
  3016.      Make more changes to fix a bug or add a new feature or...
  3017.      \$ eg commit
  3018.  
  3019.  (Advanced) Create a new blank repository meant to be used in a
  3020.  centralized fashion, i.e. a repository for many users to commit to.
  3021.      \$ mkdir new-project
  3022.      \$ cd new-project
  3023.      \$ eg init --shared
  3024.      Check repository ownership and user groups to ensure they are right
  3025.  
  3026. Options:
  3027.  --shared
  3028.    Set up a repository that will shared amongst several users; note that
  3029.    you are responsible for creating a common group for developers so that
  3030.    they can all write to the repository.  Ask your sysadmin or see the
  3031.    groupadd(8), usermod(8), chgrp(1), and chmod(1) manpages.
  3032. ";
  3033.   return $self;
  3034. }
  3035.  
  3036. ###########################################################################
  3037. # log                                                                     #
  3038. ###########################################################################
  3039. package log;
  3040. @log::ISA = qw(subcommand);
  3041. INIT {
  3042.   $COMMAND{log} = {
  3043.     section => 'discovery',
  3044.     about => 'Show history of recorded changes'
  3045.     };
  3046. }
  3047.  
  3048. sub new {
  3049.   my $class = shift;
  3050.   my $self = $class->SUPER::new(
  3051.     git_repo_needed => 1,
  3052.     @_);
  3053.   bless($self, $class);
  3054.   $self->{'help'} = "
  3055. Usage:
  3056.  eg log
  3057.  
  3058. Description:
  3059.  Shows a history of recorded changes.  Displays commit identifiers,
  3060.  the authors of the changes, and commit messages.
  3061. ";
  3062.   $self->{'differences'} = '
  3063.  eg log output differs from git log output by showing simpler revision
  3064.  identifiers that will be easier for new users to understand and use.
  3065.  In detail:
  3066.    eg log
  3067.  is essentially the same as
  3068.    git log | git name-rev --stdin --refs=$(git symbolic-ref HEAD) | less
  3069.  However, it implements the name-rev behavior internally to provide
  3070.  incremental history processing (which avoids slow upfront full-history
  3071.  analyses) in common cases.
  3072. ';
  3073.   return $self;
  3074. }
  3075.  
  3076. sub _get_values ($$) {
  3077.   my ($names, $sha1sum) = @_;
  3078.   my ($name, $distance);
  3079.   if (defined($names->{$sha1sum})) {
  3080.     ($name, $distance) = @{$names->{$sha1sum}};
  3081.   }
  3082.   return ($name, $distance);
  3083. }
  3084.  
  3085. sub _path_count ($) {
  3086.   my ($name) = @_;
  3087.   my @matches = ($name =~ m/[~^]/g);
  3088.   return scalar @matches;
  3089. }
  3090.  
  3091. sub _get_revision_name ($$$) {
  3092.   my ($sha1sum, $filehandle, $names) = @_;
  3093.   my ($name, $distance);
  3094.  
  3095.   # If we've already determined teh name of this sha1sum before, just return it
  3096.   ($name, $distance) = _get_values($names, $sha1sum);
  3097.   return $name if defined $name;
  3098.  
  3099.   # Loop over rev-list output, naming the parents of each commit as we walk
  3100.   # backward in history (breaking whenever if we hit our sha1sum)
  3101.   while (<$filehandle>) {
  3102.     # Each line of the rev-list output is of form
  3103.     #   sha1sum-of-commit sha1sum-of-parent1 sha1sum-of-parent2...
  3104.     my ($child, $parent, @merge_parents) = split;
  3105.  
  3106.     next if !$parent;
  3107.  
  3108.     # Determine the name of the current commit, and its distance from the head
  3109.     # of the current branch
  3110.     my ($cur_name, $distance) = _get_values($names, $child);
  3111.     die "Yikes!  Your history is b0rken!\n" if (!$cur_name);
  3112.  
  3113.     # Determine any name we previously determined for $parent, the name we
  3114.     # would give it relative to $child, and determine which should "win"
  3115.     my ($orig_parent_name, $orig_parent_distance) = _get_values($names, $parent);
  3116.     my $parent_name;
  3117.     if ($cur_name =~ /^(.*)~(\d+)$/) {
  3118.       my $count = $2 + 1;
  3119.       $parent_name = "$1~$count";
  3120.     } else {
  3121.       $parent_name = "$cur_name~1";
  3122.     }
  3123.     my $parent_distance = $distance + 1;
  3124.     if (!$orig_parent_name ||
  3125.         _path_count($orig_parent_name) > _path_count($parent_name)) {
  3126.       $names->{$parent} = [$parent_name, $parent_distance];
  3127.     }
  3128.  
  3129.     # Do the same for other parents, though their naming scheme is slightly
  3130.     # different
  3131.     my $count=2;
  3132.     foreach my $merge_parent (@merge_parents) {
  3133.       ($orig_parent_name, $orig_parent_distance) =
  3134.         _get_values($names, $merge_parent);
  3135.       if (!$orig_parent_name ||
  3136.           _path_count($orig_parent_name) > _path_count("$cur_name^$count")) {
  3137.         $names->{$merge_parent} = ["$cur_name^$count", $parent_distance];
  3138.       }
  3139.       $count++;
  3140.     }
  3141.  
  3142.     # Check if we found the needed sha1sum, and exit early if so
  3143.     push(@merge_parents, $parent);
  3144.     last if (grep {$_ eq $sha1sum} @merge_parents);
  3145.   }
  3146.  
  3147.   # Check if we found the needed sha1sum; if so, return it
  3148.   ($name, $distance) = _get_values($names, $sha1sum);
  3149.   return $name if $name;
  3150.  
  3151.   # We didn't find the wanted sha1sum; it has no name relative to the current
  3152.   # branch using tildes and hats.
  3153.   return "";
  3154. }
  3155.  
  3156. sub run {
  3157.   my $self = shift;
  3158.   @ARGV = Util::quote_args(@ARGV);
  3159.  
  3160.   my $branch = RepoUtil::current_branch();
  3161.  
  3162.   # Check whether to warn if there are no commits.  We don't want to parse
  3163.   # all the arguments to determine if there is a valid revision listed on the
  3164.   # command line (or, failing that, whether HEAD reference a valid revision);
  3165.   # instead, we just check for the simple case of no branches existing yet.
  3166.   if (!`$GIT_CMD branch -a`) {
  3167.     die "Error: No recorded commits to show yet.\n";
  3168.   }
  3169.  
  3170.   # We can just run plain git log if there's not current branch
  3171.   if (!$branch || !RepoUtil::valid_ref($branch)) {
  3172.     return ExecUtil::execute("$GIT_CMD log @ARGV", ignore_ret => 1);
  3173.   }
  3174.  
  3175.   my ($ret, $revision) =
  3176.     ExecUtil::execute_captured("$GIT_CMD rev-parse refs/heads/$branch");
  3177.   exit $ret if $ret;
  3178.   chomp($revision);
  3179.  
  3180.   # Show the user the essential equivalent to what we manually do
  3181.   if ($DEBUG) {
  3182.     print "    >>Running: $GIT_CMD log @ARGV | \\\n" .
  3183.        "               $GIT_CMD name-rev --stdin " .
  3184.            "--refs=refs/heads/$branch | \\\n" .
  3185.        "               less\n";
  3186.     return 0 if $DEBUG == 2;
  3187.   }
  3188.  
  3189.   # Setup name determination via output from git rev-list
  3190.   my %names;
  3191.   open(REV_LIST_INPUT, "$GIT_CMD rev-list --parents $branch -- | ");
  3192.   $names{$revision} = [$branch, 0];
  3193.  
  3194.   # Loop over the output of git log, printing/modifying as we go
  3195.   my $old_git_pager_in_use = $ENV{"GIT_PAGER_IN_USE"};
  3196.   if (-t STDOUT) {
  3197.     # use colors
  3198.     $ENV{"GIT_PAGER_IN_USE"} = "1";
  3199.   }
  3200.   open(INPUT, "$GIT_CMD log @ARGV | ");
  3201.   $ENV{"LESS"} = "FRSX" unless defined $ENV{"LESS"};
  3202.   my $less = ($USE_PAGER == 1) ? "less" :
  3203.              ($USE_PAGER == 0) ? "cat" :
  3204.              `$GIT_CMD config core.pager` || "less";
  3205.   chomp($less);
  3206.   my $pid = open(OUTPUT, "| $less");
  3207.  
  3208.   # Make sure that we don't leave the terminal in a weird state if the user
  3209.   # hits Ctrl-C during eg log
  3210.   local $SIG{INT} =
  3211.     sub { kill 'SIGKILL', $pid; close(INPUT); close(OUTPUT); close(REV_LIST_INPUT);
  3212.           exit(0); };
  3213.  
  3214.   #open(OUTPUT, ">&STDOUT");
  3215.   while (<INPUT>) {
  3216.     # If it's a commit line, determine the name of the commit and print it too
  3217.     # ANSI color escape sequences make this regex kind of ugly...
  3218.     if (/^((?:\e\[.*?m)?commit ([0-9a-f]{40}))((?:\e\[m)?)$/) {
  3219.       my $name = _get_revision_name($2, *REV_LIST_INPUT, \%names);
  3220.       print OUTPUT "$1 ($name)$3\n" if $name;
  3221.       print OUTPUT "$1$3\n"         if !$name;
  3222.     } else {
  3223.       print OUTPUT;
  3224.     }
  3225.   }
  3226.   my ($ret1, $ret2, $ret3);
  3227.   close(INPUT);  $ret1 = $? >> 8;
  3228.   close(OUTPUT); $ret2 = $? >> 8;
  3229.   $ENV{"GIT_PAGER_IN_USE"} = $old_git_pager_in_use;
  3230.  
  3231.   # Make sure we close the pipe from rev-list too; We use "$? && $!"
  3232.   # instead of "$?" because we don't care about the return value of the
  3233.   # rev-list program -- which we prematurely close -- just whether the close
  3234.   # succeeded.  We can't just use "$!" because if --pretty="format:%s" is
  3235.   # passed to eg log, then $! will be "Bad file descriptor" which translates
  3236.   # to a nonzero exit status.
  3237.   # (This is my best guess at what to do given the random failures from
  3238.   # t1411-reflog-show.sh, and reading 'man perlfunc' under 'close'; it seems
  3239.   # to work.)
  3240.   close(REV_LIST_INPUT);  $ret3 = ($? >> 8) && $!;
  3241.  
  3242.   return $ret1 || $ret2 || $ret3;
  3243. }
  3244.  
  3245. ###########################################################################
  3246. # merge                                                                   #
  3247. ###########################################################################
  3248. package merge;
  3249. @merge::ISA = qw(subcommand);
  3250. INIT {
  3251.   $COMMAND{merge} = {
  3252.     unmodified_behavior => 1,
  3253.     section => 'projects',
  3254.     about => 'Join two or more development histories (branches) together'
  3255.     };
  3256. }
  3257.  
  3258. sub new {
  3259.   my $class = shift;
  3260.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  3261.   bless($self, $class);
  3262.   $self->{'help'} = "
  3263. Usage:
  3264.  eg merge [-m MESSAGE] BRANCH...
  3265.  
  3266. Description:
  3267.  Merges another branch (or more than one branch) into the current branch.
  3268.  
  3269.  You may want to skip to the examples; the remainder of this description
  3270.  section just has boring details about how merges work.
  3271.  
  3272.  There are three different ways to handle merges depending on whether the
  3273.  current branch or the specified merge branches have commits not found in
  3274.  the other.  These cases are:
  3275.    1) The current branch contains all commits in the specified branch(es).
  3276.         In this case, there is nothing to do.
  3277.    2) Both the current branch and the specified merge branch(es) contain
  3278.       commits not found in the other:
  3279.         In this case, a new commit will be created which (a) includes
  3280.         changes from both the current branch and the merge branch(es) and
  3281.         (b) records the parents of the new commit as the last revision of
  3282.         the current branch and the last revision(s) of the merge
  3283.         branch(es).
  3284.    3) The specified merge branch has all the commits found in the current
  3285.       branch.
  3286.         In this case, a new commit is not needed to merge the branches
  3287.         together.  Instead, the current branch simply changes the record
  3288.         of its last revision to that of the specified merge branch.  This
  3289.         is known as a fast-forward update.
  3290.  See 'eg help topic storage' for more information.
  3291.  
  3292. Examples:
  3293.  Merge all changes from the stable branch that are not already in the
  3294.  current branch, into the current branch.
  3295.      \$ eg merge stable
  3296.  
  3297.  Merge all changes from the refactor branch into the current branch (i.e.
  3298.  same as the previous example but merging in a different branch)
  3299.      \$ eg merge refactor
  3300.  
  3301. Options:
  3302.  -m MESSAGE
  3303.    Use MESSAGE as the commit message for the created merge commit, if
  3304.    a merge commit is needed.
  3305. ";
  3306.   return $self;
  3307. }
  3308.  
  3309. ###########################################################################
  3310. # publish                                                                 #
  3311. ###########################################################################
  3312. package publish;
  3313. @publish::ISA = qw(subcommand);
  3314. INIT {
  3315.   $COMMAND{publish} = {
  3316.     extra => 1,
  3317.     new_command => 1,
  3318.     section => 'collaboration',
  3319.     about => 'Publish a copy of the current repository on a remote machine'
  3320.     };
  3321. }
  3322.  
  3323. sub new {
  3324.   my $class = shift;
  3325.   my $self = $class->SUPER::new(
  3326.     git_repo_needed => 1,
  3327.     git_equivalent => '',
  3328.     initial_commit_error_msg => "Error: No recorded commits to publish.",
  3329.     @_);
  3330.   bless($self, $class);
  3331.   $self->{'help'} = "
  3332. Usage:
  3333.  eg publish [-b|--bypass-modification-check] [-g|--group GROUP]
  3334.             [REMOTE_ALIAS] SSH_URL
  3335.  
  3336. Description:
  3337.  Publishes a copy of the current repository on a remote machine.  Note
  3338.  that local changes will be ignored; only committed changes will be
  3339.  published.  You must have ssh access to the remote machine and must have
  3340.  both git and ssh installed on both local and remote machines.
  3341.  
  3342.  After publishing the repository, it is accessible via the remote
  3343.  REMOTE_ALIAS, thus allowing you to use REMOTE_ALIAS to push and pull
  3344.  commands.  If REMOTE_ALIAS is not specified, it defaults to 'origin'.
  3345.  
  3346.  If the --group (or -g) option is specified, the given GROUP must be a
  3347.  valid unix group on the remote machine, and the user must be a member of
  3348.  that group.  When this option is passed, eg publish will ensure that all
  3349.  files are readable and writable by members of that group.
  3350.  
  3351.  Note that the remote location is specified using a ssh url; see 'eg help
  3352.  topic remote_urls' for a full list of valid possibilities, but the
  3353.  general case is to use scp(1) syntax: [[USER@]MACHINE]:REMOTE_PATH.  Note
  3354.  that if any files or directories exist below the specified remote
  3355.  directory, publish will abort.
  3356.  
  3357. Examples:
  3358.  Publish a copy of the current repository on the machine myserver.com in
  3359.  the directory /var/scratch/git-stuff/my-repo.git, and make it readable
  3360.  and writable by the unix group 'gitters'.  Then immediately make a clone
  3361.  of the remote repository
  3362.      \$ eg publish -g gitters myserver.com:/var/scratch/git-stuff/my-repo.git
  3363.      \$ cd ..
  3364.      \$ eg clone myserver.com:/var/scratch/git-stuff/my-repo.git
  3365.  
  3366.  Publish a copy of the current repository on the machine www.gnome.org, in
  3367.  the public_html/myproj subdirectory of the home directory of the remote
  3368.  user fake, then immediately clone it again into a separate directory
  3369.  named another-myproj.
  3370.      \$ eg publish fake\@www.gnome.org:public_html/myproj
  3371.      \$ cd ..
  3372.      \$ eg clone http://www.gnome.org/~fake/myproj another-myproj
  3373.  
  3374. Options
  3375.  --bypass-modification-check, -b
  3376.    To prevent you from publishing an incomplete set of changes, publish
  3377.    typically checks whether you have new unknown files or modified files
  3378.    present and aborts if so.  You can bypass these checks with this
  3379.    option.
  3380. ";
  3381.   $self->{'differences'} = '
  3382.  eg publish is unique to eg, designed to condense the multiple necessary
  3383.  steps with git into one (or a few) commands.  The steps that eg publish
  3384.  performs are essentially:
  3385.      if ( git config --get remote.REMOTE_ALIAS.url > /dev/null); then
  3386.        echo "REMOTE_ALIAS already defined"; false;
  3387.      fi &&
  3388.      ssh [USER@]MACHINE "
  3389.        test -d REMOTE_PATH && echo "REMOTE_PATH already exists!" && exit 1;
  3390.        if (! groups | grep "\bGROUP\b" > /dev/null); then
  3391.          echo "Cannot change to group GROUP";  exit 1;
  3392.        fi;
  3393.        if (! type -p git>/dev/null);then echo "Cannot find git"; exit 1; fi &&
  3394.        newgrp GROUP;
  3395.        mkdir -p REMOTE_PATH &&
  3396.        cd REMOTE_PATH &&
  3397.        git init [--shared] --bare &&
  3398.        touch git-daemon-export-ok &&
  3399.        (mv hooks/post-update.sample hooks/post-update || true) &&
  3400.        chmod u+x hooks/post-update" &&
  3401.      git remote add REMOTE_ALIAS [USER@]MACHINE:REMOTE_PATH &&
  3402.      git push
  3403.  Note that the command involving git-daemon-export-ok is only needed if
  3404.  you will be cloning/pulling from the repository via the git:// protocol
  3405.  (in which case you are responsible for running git-daemon on the remote
  3406.  machine), and the post-update hook related stuff is only necessary if you
  3407.  are trying to clone/pull via the http:// protocol (in which case you are
  3408.  responsible for running a webserver such as httpd on the remote machine);
  3409.  neither of these steps are needed if you are cloning/pulling via ssh, but
  3410.  they do not cause problems either.
  3411.  
  3412.  MULTI-USER NOTE: If you want multiple people to be able to push to the
  3413.  resulting repository, you will need to ensure that they all have ssh
  3414.  access to the machine, that they are all part of the same unix group, and
  3415.  that you use the --group option to ensure that the repository is set up
  3416.  to be shared by the relevant group.
  3417. ';
  3418.   return $self;
  3419. }
  3420.  
  3421. sub preprocess {
  3422.   my $self = shift;
  3423.   my $package_name = ref($self);
  3424.  
  3425.   my $bypass_modification_check = 0;
  3426.   my $group;
  3427.   my $result = main::GetOptions(
  3428.     "--help"           => sub { $self->help() },
  3429.     "bypass-modification-check|b" => \$bypass_modification_check,
  3430.     "group|g=s"                   => \$group,
  3431.     );
  3432.  
  3433.   die "Aborting: Need a URL to push to!\n" if @ARGV < 1;
  3434.   die "Aborting: Too many args to eg publish: @ARGV\n" if @ARGV > 2;
  3435.   my $extra_info = (@ARGV == 2) ? "" : ", please specify a REMOTE_ALIAS";
  3436.   $self->{remote} = (@ARGV == 2) ? shift @ARGV : "origin";
  3437.   $self->{repository} = shift @ARGV;
  3438.   $self->{group} = $group;
  3439.  
  3440.   die "Aborting: remote '$self->{remote}' already exists$extra_info!\n"
  3441.     if RepoUtil::get_config("remote.$self->{remote}.url");
  3442.  
  3443.   if (!$bypass_modification_check) {
  3444.     my $status = RepoUtil::commit_push_checks($package_name,
  3445.                                               {unknown => 1,
  3446.                                                changes => 1,
  3447.                                                unmerged_changes => 1});
  3448.   } else {
  3449.     # Record the set of unknown files we ignored with -b, so the -b flag
  3450.     # isn't needed next time.
  3451.     RepoUtil::record_ignored_unknowns();
  3452.   }
  3453. }
  3454.  
  3455. sub run {
  3456.   my $self = shift;
  3457.  
  3458.   my ($user, $machine, $port, $path) =
  3459.     Util::split_ssh_repository($self->{repository});
  3460.   if (!defined $path) {
  3461.     # It may be a local path rather than an ssh path...
  3462.     if ($self->{repository} =~ m#^/[^:]*#) {
  3463.       $path = $self->{repository};
  3464.     } else {
  3465.       die "Aborting: Could not parse remote repository URL " .
  3466.           "'$self->{repository}'.\n";
  3467.     }
  3468.   }
  3469.  
  3470.   my ($sg, $sge, $check_group, $shared) = ("", "", "", "");
  3471.   if (defined $self->{group}) {
  3472.     $check_group = "
  3473.        if (! groups | grep '\\b$self->{group}\\b' > /dev/null); then
  3474.          echo 'Cannot change to group $self->{group}!'; exit 1;
  3475.        fi;";
  3476.     $sg = "sg $self->{group} -c '";
  3477.     $sge = "'";
  3478.     $shared = "--shared ";
  3479.   }
  3480.  
  3481.   my $ret;
  3482.   if (defined $machine) {
  3483.     print "Setting up remote repository via ssh...\n";
  3484.     $ret = ExecUtil::execute("
  3485.      ssh $port -q $user$machine \"
  3486.        test -d $path && echo '$path already exists!' && exit 1; $check_group
  3487.        if (! which git>/dev/null);then echo 'Cannot find git'; exit 1; fi;
  3488.        ${sg}mkdir -p $path${sge} &&
  3489.        cd $path &&
  3490.        ${sg}git init ${shared}--bare${sge} &&
  3491.        touch git-daemon-export-ok &&
  3492.        (mv hooks/post-update.sample hooks/post-update || true) &&
  3493.        chmod u+x hooks/post-update\"",
  3494.       ignore_ret => 1);
  3495.   } else {
  3496.     print "Setting up not-so-remote repository...\n";
  3497.     $ret = ExecUtil::execute("
  3498.        test -d $path && echo '$path already exists!' && exit 1; $check_group
  3499.        if (! which git>/dev/null);then echo 'Cannot find git'; exit 1; fi;
  3500.        ${sg}mkdir -p $path${sge} &&
  3501.        cd $path &&
  3502.        ${sg}$GIT_CMD init ${shared}--bare${sge} &&
  3503.        touch git-daemon-export-ok &&
  3504.        (mv hooks/post-update.sample hooks/post-update || true) &&
  3505.        chmod u+x hooks/post-update",
  3506.       ignore_ret => 1);
  3507.   }
  3508.   die "Remote repository setup failed!\n" if $ret != 0;
  3509.  
  3510.   print "Creating new remote $self->{remote}...\n";
  3511.   #if ($self->{remote} ne "origin") {
  3512.   #  print "If $self->{remote} should be a default push/pull location, run:\n" .
  3513.   #        "   eg track [LOCAL_BRANCH] $self->{remote}/REMOTE_BRANCH\n";
  3514.   #}
  3515.   ExecUtil::execute("$GIT_CMD remote add $self->{remote} $self->{repository}");
  3516.   print "Pushing to new remote $self->{remote}...\n";
  3517.   $ret = ExecUtil::execute("$GIT_CMD push --mirror $self->{remote}");
  3518.   if ($ret) {
  3519.     ExecUtil::execute("$GIT_CMD remote rm $self->{remote}");
  3520.     return $ret;
  3521.   }
  3522.  
  3523.   print "Done.\n";
  3524.  
  3525.   return 0;
  3526. }
  3527.  
  3528. ###########################################################################
  3529. # pull                                                                    #
  3530. ###########################################################################
  3531. package pull;
  3532. @pull::ISA = qw(subcommand);
  3533. INIT {
  3534.   $COMMAND{pull} = {
  3535.     section => 'collaboration',
  3536.     about => 'Get updates from another repository and merge them'
  3537.     };
  3538. }
  3539.  
  3540. sub new {
  3541.   my $class = shift;
  3542.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  3543.   bless($self, $class);
  3544.   $self->{'help'} = "
  3545. Usage:
  3546.  eg pull [--branch BRANCH] [--no-tags] [--all-tags] [--tag TAG]
  3547.          [--no-commit] [--rebase] REPOSITORY
  3548.  
  3549. Description:
  3550.  Pull changes from another repository and merge them into the local
  3551.  repository.  If there are no conflicts, the result will be committed.
  3552.  
  3553.  See 'eg help topic remote-urls' for valid syntax for remote repositories.
  3554.  If you frequently pull from the same repository, you may want to set up a
  3555.  nickname for it (see 'eg help remote'), so that you can specify the
  3556.  nickname instead of the full repository URL every time.  If you want to
  3557.  set a (different) default repository and branch to pull from, see 'eg
  3558.  track'.
  3559.  
  3560.  By default, tags in the remote repository associated with commits that
  3561.  are pulled, will themselves be pulled.  One can specify to pull
  3562.  additional or fewer tags with the --all-tags, --no-tags, or --tag TAG
  3563.  options.
  3564.  
  3565.  If there is more than one branch (on either end):
  3566.    If the local repository has more than one branch, the changes are
  3567.    always merged into the active branch (use 'eg info' or 'eg branch' to
  3568.    determine the active branch).
  3569.  
  3570.    If you do not specify which remote branch to pull, and you have not
  3571.    previously pulled a remote branch from the given repository, then eg
  3572.    will abort and ask you to specify a remote branch (giving you a list to
  3573.    choose from).
  3574.  
  3575.  Note for users of named remote repositories and remote tracking branches:
  3576.    If you set up named remote repositories (using 'eg remote'), you can
  3577.    make 'eg pull' obtain changes from several branches at once.  In such a
  3578.    case, eg will take the changes and record them in special local
  3579.    branches known as \"remote tracking branches\", a step which involves
  3580.    no merging.  Most of these branches will not be handled further after
  3581.    this step.  eg will then take changes from just the branch(es)
  3582.    specified (with the --branch option, or with the
  3583.    branch.CURRENTBRANCH.merge configuration variable, or by the last
  3584.    branch(es) merged), and merge it/them into the active branch.
  3585.  
  3586.    The advantage of pulling changes from branches that you do not
  3587.    immediately merge with is that you can then later inspect, review, or
  3588.    merge with such changes (using 'eg merge') even if not connected to the
  3589.    network.  Naming the remote repositories also allows you to use the
  3590.    shorter name instead of the full location of the repository.  (eg
  3591.    remote also provides the ability to update from groups of remote
  3592.    repositories simultaneously.)  See 'eg help remote' and 'eg help topic
  3593.    storage' for more information about named remote repositories and
  3594.    remote tracking branches.
  3595.  
  3596. Examples:
  3597.  Pull changes from myserver.com:git-stuff/my-repo.git
  3598.      \$ eg pull myserver.com:git-stuff/my-repo.git
  3599.  
  3600.  Pull changes from the stable branch of git://git.foo.org/whizbang into the
  3601.  active local branch
  3602.      \$ eg pull --branch stable git://git.foo.org/whizbang
  3603.  
  3604.  Pull changes from the debug branch in the remote repository nicknamed
  3605.  'carl' (see 'eg help remote' for more information about nicknames for
  3606.  remote repositories)
  3607.      \$ eg pull --branch debug carl
  3608.  
  3609.  Pull changes from a remote repository that has multiple branches
  3610.      Hmm, we don't know which branches the remote repository has.  Just
  3611.      try it.
  3612.      \$ eg pull ssh://machine.fake.gov/~user/hack.git
  3613.      That gave us an error telling us it didn't know which branch to pull
  3614.      from, but it told us that there were 3 branches: 'master', 'stable',
  3615.      and 'nasty-hack'.  Let's get changes from the nasty-hack branch!
  3616.      \$ eg pull --branch nasty-hack ssh://machine.fake.gov/~user/hack.git
  3617.  
  3618. Options
  3619.  --branch BRANCH
  3620.    Merge the changes from the remote branch BRANCH.  May be used multiple
  3621.    times to merge changes from multiple remote branches at once.
  3622.  
  3623.  --no-tags
  3624.    Do not download any tags from the remote repository
  3625.  
  3626.  --all-tags
  3627.    Download all tags from the remote repository.
  3628.  
  3629.  --tag TAG
  3630.    Download TAG from the remote repository
  3631.  
  3632.  --no-commit
  3633.    Perform the merge but do not commit even if the merge is clean.
  3634.  
  3635.  --rebase
  3636.    Instead of a merge, perform a rebase; in other words rewrite commit
  3637.    history so that your recent local commits become commits on top of the
  3638.    changes downloaded from the remote repository.
  3639.  
  3640.    NOTE: This is a potentially dangerous operation if you have local
  3641.    commits not found in the repository you are pulling from but which are
  3642.    found in some other repository (e.g. your local commits have been
  3643.    directly pulled from your copy by another developer, or to your copy
  3644.    from another developer).  In such a case, unless the other copy of
  3645.    these commits are also rebased (or discarded), you will probably get
  3646.    into trouble and need to thoroughly understand 'eg help rebase' before
  3647.    using this option.
  3648. ";
  3649.   $self->{'differences'} = "
  3650.  eg pull and git pull are nearly identical.  eg provides a slightly more
  3651.  meaningful name for --tags (\"--all-tags\"), introduces a new option
  3652.  named --branch, and tries to assist the user when no branch to
  3653.  merge/rebase is specified on the command line or in the config.
  3654.  
  3655.  The new --branch option (1) avoids the need to explain refspecs too early
  3656.  to users, (2) makes command line examples more self-documenting.  eg
  3657.  still accepts refspecs at the end of the commandline the same as git
  3658.  pull, however their explanation is deferred to 'eg help topic refspecs'.
  3659.  
  3660.  When no branch to merge/rebase is specified, eg pull will provide a list
  3661.  of known branches at the remote end.  In the special case that the remote
  3662.  has exactly one branch, eg will use that branch for merging/rebasing
  3663.  rather than erroring out.
  3664. ";
  3665.   return $self;
  3666. }
  3667.  
  3668. sub preprocess {
  3669.   my $self = shift;
  3670.  
  3671.   #
  3672.   # Parse options
  3673.   #
  3674.   $self->{args} = [];
  3675.   my $record_arg  =
  3676.     sub { my $prefix = "";
  3677.           $prefix = "no-" if defined $_[1] && $_[1] == 0;
  3678.           push(@{$self->{args}}, "--$prefix$_[0]");
  3679.         };
  3680.   my $record_args  = sub { $_[0] = "--$_[0]"; push(@{$self->{args}}, @_);  };
  3681.   my ($no_tags, $all_tags) = (0, 0);
  3682.   my @branches;
  3683.   my @tags;
  3684.   my $result = main::GetOptions(
  3685.     "--help"           => sub { $self->help() },
  3686.     "--branch=s"       => sub { push(@branches, $_[1]) },
  3687.     "--tag=s"          => sub { push(@tags, $_[1]) },
  3688.     "--all-tags"       => \$all_tags,
  3689.     "--no-tags"        => \$no_tags,
  3690.     "commit!"          => sub { &$record_arg(@_) },
  3691.     "summary!"         => sub { &$record_arg(@_) },
  3692.     "no-stat|n"        => sub { &$record_arg(@_) },
  3693.     "squash!"          => sub { &$record_arg(@_) },
  3694.     "ff!"              => sub { &$record_arg(@_) },
  3695.     "strategy|s=s"     => sub { &$record_args(@_) },
  3696.     "rebase!"          => sub { &$record_arg(@_) },
  3697.     "quiet|q"          => sub { &$record_arg(@_) },
  3698.     "verbose|v"        => sub { &$record_arg(@_) },
  3699.     "append|a"         => sub { &$record_arg(@_) },
  3700.     "upload-pack=s"    => sub { &$record_args(@_) },
  3701.     "force|f"          => sub { &$record_arg(@_) },
  3702.     "tags"             => \$all_tags,
  3703.     "keep|k"           => sub { &$record_arg(@_) },
  3704.     "update-head-ok|u" => sub { &$record_arg(@_) },
  3705.     "--depth=i"        => sub { &$record_args(@_) },
  3706.     );
  3707.   die "Cannot specify both --all-tags and --no-tags!\n"
  3708.     if $all_tags && $no_tags;
  3709.   die "Cannot specify individual tags along with --all-tags or --no-tags!\n"
  3710.     if @tags && ($all_tags || $no_tags);
  3711.   my $repository = shift @ARGV;
  3712.   my @git_refspecs = @ARGV;
  3713.  
  3714.   # Record the tags or no-tags arguments
  3715.   push(@{$self->{args}}, "--tags") if $all_tags;
  3716.   push(@{$self->{args}}, "--no-tags") if $no_tags;
  3717.  
  3718.   #
  3719.   # Get the repository to pull from
  3720.   #
  3721.   my $repo_is_a_remote = 1;
  3722.   my $repo_specified = defined($repository);
  3723.   if ($repository) {
  3724.     push(@{$self->{args}}, $repository);
  3725.     $repo_is_a_remote = 0 if !RepoUtil::get_config("remote.$repository.url");
  3726.   } else {
  3727.     $repository = RepoUtil::get_default_push_pull_repository();
  3728.     if (!$repository) {
  3729.       # This line should never be reached
  3730.       die "Don't know what to pull!"
  3731.     }
  3732.     push(@{$self->{args}}, $repository) if (!$repo_specified && @branches);
  3733.   }
  3734.  
  3735.   #
  3736.   # Get the branch(es) to pull from
  3737.   #
  3738.   push(@branches, @git_refspecs);
  3739.  
  3740.   # If we were given explicit branches or tags to pull, then we know what
  3741.   # to pull.  Also, for compatibility with git, if the repository specified
  3742.   # is a url rather than a remotename, then we should pull from HEAD if
  3743.   # no other refspecs are specified.
  3744.   #
  3745.   # In all other cases...
  3746.   if ($repo_is_a_remote && !@branches && !@tags) {
  3747.     my $dont_know_what_to_pull = 0;
  3748.  
  3749.     # If we don't have a current branch, we can't tell what branch to merge
  3750.     my $branch = RepoUtil::current_branch();
  3751.     if (!$branch) {
  3752.       $dont_know_what_to_pull = 1;
  3753.       goto PULL_CHECK;
  3754.     }
  3755.  
  3756.     # If there's no default remote, we must ignore branch.$branch.merge so
  3757.     # we don't know what branch to merge
  3758.     my ($merge_branch, $default_remote);
  3759.     $default_remote = RepoUtil::get_config("branch.$branch.remote");
  3760.     if (!$default_remote) {
  3761.       $dont_know_what_to_pull = 1;
  3762.       goto PULL_CHECK;
  3763.     }
  3764.  
  3765.     # If the default remote doesn't match the specified repository, we must
  3766.     # ignore branch.$branch.remote so we don't know what branch to merge
  3767.     if ($repo_specified and $repository ne $default_remote) {
  3768.       $dont_know_what_to_pull = 1;
  3769.       goto PULL_CHECK;
  3770.     }
  3771.  
  3772.     # If branch.$branch.merge is not set we don't know what branch to merge
  3773.     $merge_branch = RepoUtil::get_config("branch.$branch.merge");
  3774.     if (!$merge_branch) {
  3775.       $dont_know_what_to_pull = 1;
  3776.       goto PULL_CHECK;
  3777.     }
  3778.  
  3779.     PULL_CHECK:
  3780.     # Even if we don't know what to pull, if the remote repository has exactly
  3781.     # one branch, then we can just pull from that.
  3782.     if ($dont_know_what_to_pull) {
  3783.       my $location = $repository || $default_remote;
  3784.       my $only_branch = RepoUtil::get_only_branch($location, "pull");
  3785.       push(@{$self->{args}}, $location) if !$repo_specified;
  3786.       push(@branches, $only_branch);
  3787.     }
  3788.   }
  3789.  
  3790.   foreach my $branch (@branches) {
  3791.     push(@{$self->{args}}, $branch);
  3792.   }
  3793.   foreach my $tag (@tags) {
  3794.     push(@{$self->{args}}, ("tag", $tag));
  3795.   }
  3796. }
  3797.  
  3798. sub run {
  3799.   my $self = shift;
  3800.  
  3801.   my @args = Util::quote_args(@{$self->{args}});
  3802.   return ExecUtil::execute("$GIT_CMD pull @args", ignore_ret => 1);
  3803. }
  3804.  
  3805. ###########################################################################
  3806. # push                                                                    #
  3807. ###########################################################################
  3808. package push;
  3809. @push::ISA = qw(subcommand);
  3810. INIT {
  3811.   $COMMAND{push} = {
  3812.     section => 'collaboration',
  3813.     about => 'Push local commits to a published repository'
  3814.     };
  3815. }
  3816.  
  3817. sub new {
  3818.   my $class = shift;
  3819.   my $self = $class->SUPER::new(
  3820.     git_repo_needed => 1,
  3821.     initial_commit_error_msg => "Error: No recorded commits to push.",
  3822.     @_);
  3823.   bless($self, $class);
  3824.   $self->{'help'} = "
  3825. Usage:
  3826.  eg push [--bypass-modification-check] [--branch BRANCH] [--tag TAG]
  3827.          [--all-branches] [--all-tags] [--mirror] REPOSITORY
  3828.  
  3829. Description:
  3830.  Push committed changes in the current repository to a published remote
  3831.  repository.  Note that this command cannot be used to create a new remote
  3832.  repository; use 'eg publish' (which both creates a remote repository and
  3833.  pushes to it) if you need to do that.
  3834.  
  3835.  The push can fail if the remote repository has commits not
  3836.  in the current repository; this can be fixed by pulling and merging
  3837.  changes from the remote repository (use eg pull for this) and then
  3838.  repeating the push.  Note that for getting changes directly to a fellow
  3839.  developer's clone, you should have them use 'eg pull' rather than trying
  3840.  to use 'eg push' on your end.
  3841.  
  3842.  Branches and tags are typically considered private; thus only the current
  3843.  branch will be involved by default (no tags will be sent).  The
  3844.  --all-branches, --matching-branches, --all-tags, and --mirror options
  3845.  exist to extend the list of changes included.  The --branch and --tag
  3846.  options can be used to specifically send different changes.
  3847.  
  3848.  See 'eg help topic remote-urls' for valid syntax for remote repositories.
  3849.  
  3850.  If you frequently push to the same repository, you may want to set up a
  3851.  nickname for it (see 'eg help remote'), so that you can specify the
  3852.  nickname instead of the full repository URL every time.  Also, if you want
  3853.  to change the default repository and branch to push to, see 'eg track'.
  3854.  
  3855. Examples:
  3856.  Push commits in the current branch
  3857.      \$ eg push myserver.com:git-stuff/my-repo.git
  3858.  
  3859.  Push commits in all branches that already exist both locally and remotely
  3860.      \$ eg push --matching-branches ssh://web.site/path/to/project.git
  3861.  
  3862.  Push commits in all branches, including branches that do no already exist
  3863.  remotely, and all tags, to the remote nicknamed 'alice'
  3864.      \$ eg push --all-branches --all-tags alice
  3865.  
  3866.  Push all local branches and tags and delete anything on the remote end
  3867.  that is not in the current repository
  3868.      \$ eg push --mirror ssh://jim\@host.xz:22/~jim/project/published
  3869.  
  3870.  Create a two new tags locally, then push both
  3871.      \$ eg tag MY_PROJECT_1_0
  3872.      \$ eg tag USELESS_ALIAS_FOR_1_0
  3873.      \$ eg push --tag MY_PROJECT_1_0 --tag USELESS_ALIAS_FOR_1_0
  3874.  
  3875.  Push the changes in just the stable branch
  3876.      \$ eg push --branch stable
  3877.  
  3878. Options
  3879.  --bypass-modification-check, -b
  3880.    To prevent you from pushing an incomplete set of changes, push
  3881.    typically checks whether you have new unknown files or modified files
  3882.    present and aborts if so.  You can bypass these checks with this
  3883.    option.
  3884.  
  3885.  --branch BRANCH
  3886.    Push commits in the specified branch.  May be reused multiple times to
  3887.    push commits in multiple branches.
  3888.  
  3889.    As an advanced option, one can use the syntax LOCAL:REMOTE for the
  3890.    branch.  For example, \"--branch my_bugfix:stable\" would mean to use
  3891.    the my_bugfix branch of the current repository to update the stable
  3892.    branch of the remote repository.
  3893.  
  3894.  --tag TAG
  3895.    Push the specified tag to the remote repository.
  3896.  
  3897.  --all-branches
  3898.    Push commits from all branches, including branches that do not yet exist
  3899.    in the remote repository
  3900.  
  3901.  --matching-branches
  3902.    Push commits from all branches that exist locally and remotely.  Note that
  3903.    this option is ignored if specific branches or tags are specified, or the
  3904.    --all-branches or --all-tags options.
  3905.  
  3906.  --all-tags
  3907.    Push all tags to the remote repository.
  3908.  
  3909.  --mirror
  3910.    Make the remote repository a mirror of the local one.  This turns on
  3911.    both --all-branches and --all-tags, but it also means that tags and
  3912.    branches that do not exist in the local repository will be deleted from
  3913.    the remote repository.
  3914. ";
  3915.   $self->{'differences'} = "
  3916.  eg push is largely the same as git push, despite attempts to simplify in
  3917.  a number of areas:
  3918.  
  3919.    (1) push.default=tracking is the default if push.default is unset (git
  3920.        uses push.default=matching if push.default is unset).  This seems
  3921.        to match the intuition of most former cvs/svn users, though it is
  3922.        my one dangerous default change for existing git users.  Tough
  3923.        call, since the 'safe' defaults for each group are unsafe and/or
  3924.        confusing for the other.  A new --matching-branches flag is added
  3925.        to get the old behavior (the plain ':' refspec from git does the
  3926.        same, but --matching-branches is more self-documenting and also
  3927.        predates the ':' refspec).
  3928.  
  3929.    (2) eg prevents pushing into a bare repository as a push-side check
  3930.        rather than a receive-side check (when it can determine that the
  3931.        remote repository is bare -- i.e. if the repository url is for a
  3932.        locally mounted filesystem or uses ssh).  eg also allows the check
  3933.        to be overridden on the push-side (by specifying a refspec
  3934.        containing a ':' character).  This means it can work for users of
  3935.        existing repositories (created with git < 1.7), and it provides a
  3936.        solution that both avoids working copy inconsistency for new users
  3937.        while allowing more advanced users to do what they need on the same
  3938.        repository, and without forcing users to twiddle with the
  3939.        configuration of the remote repository.  However, this method
  3940.        doesn't work for repositories accessed via git://, and only works
  3941.        for ssh-accessed repositories if users have ssh setup to not need a
  3942.        password (kerberos, ssh-keys, etc.).
  3943.  
  3944.    (3) eg performs checks for uncommitted changes and newly created
  3945.        unknown files and warns/aborts if such exist when the user pushes
  3946.        (most former cvs/svn users are not yet familiar with the fact that
  3947.        only committed stuff gets pushed/pulled).  As with eg commit, such
  3948.        checks can be overridden with the -b flag.
  3949.  
  3950.    (4) eg provides extra --tag and --branch flags to make command lines
  3951.        more self-documenting and to avoid excessively early introduction
  3952.        of refspecs (a very confusing topic for new users).  However,
  3953.        refspecs still work with eg push, and users can learn about them by
  3954.        running 'eg help topic refspecs'.
  3955. ";
  3956.   return $self;
  3957. }
  3958.  
  3959. sub _get_push_repository ($) {
  3960.   my ($repository) = @_;
  3961.  
  3962.   if (defined $repository) {
  3963.     return RepoUtil::get_config("remote.$repository.pushurl") ||
  3964.            RepoUtil::get_config("remote.$repository.url") ||
  3965.            $repository;
  3966.   } else {
  3967.     return RepoUtil::get_config("remote.origin.url")
  3968.   }
  3969. }
  3970.  
  3971. # _check_if_bare: Return whether the given repository is bare.  Returns
  3972. # undef the repository doesn't specify a valid repository or the repository
  3973. # is not of a type where we can determine bare-ness.  Otherwise returns
  3974. # either the string "true" or "false".
  3975. sub _check_if_bare ($) {
  3976.   my $repository = shift;
  3977.  
  3978.   # Don't know how to check rsync, http, https, or git repositories to see
  3979.   # if they are bare.
  3980.   return undef if $repository =~ m#^(rsync|http|https|git)://#;
  3981.  
  3982.   #
  3983.   # Check local directories
  3984.   #
  3985.   if ($repository =~ m#^file://(.*)#) {
  3986.     $repository = $1;
  3987.   }
  3988.   if (-d $repository) {
  3989.     my $orig_dir = main::getcwd();
  3990.     chdir($repository);
  3991.  
  3992.     my ($ret, $output) =
  3993.       ExecUtil::execute_captured("$GIT_CMD rev-parse --is-bare-repository",
  3994.                                  ignore_ret => 1);
  3995.  
  3996.     chdir($orig_dir);
  3997.     return undef if $ret != 0;
  3998.     chomp($output);
  3999.     return $output;
  4000.   }
  4001.  
  4002.   #
  4003.   # Check ssh systems
  4004.   #
  4005.   my ($user, $machine, $port, $path) = Util::split_ssh_repository($repository);
  4006.   return undef if !defined $machine || !defined $path;
  4007.  
  4008.   my ($ret, $output) =
  4009.     ExecUtil::execute_captured(
  4010.       "ssh $port -q -o BatchMode=yes $user$machine 'cd $path && $GIT_CMD rev-parse --is-bare-repository'",
  4011.       ignore_ret => 1);
  4012.   return undef if $ret != 0;
  4013.   chomp($output);
  4014.   my @lines = split('\n', $output);
  4015.   my $result = $lines[-1];
  4016.   # If ssh or git itself failed, $ret could still be 0 but $result could be
  4017.   # something other than "true" or "false"
  4018.   return undef if (! grep {$_ eq $result} ["true", "false"]);
  4019.   return $result;
  4020. }
  4021.  
  4022. sub preprocess {
  4023.   my $self = shift;
  4024.   my $package_name = ref($self);
  4025.  
  4026.   #
  4027.   # Parse options
  4028.   #
  4029.   $self->{args} = [];
  4030.   my $record_arg   = sub { push(@{$self->{args}}, "--$_[0]"); };
  4031.   my $record_args  = sub { $_[0] = "--$_[0]"; push(@{$self->{args}}, @_);  };
  4032.   my ($all_branches, $matching_branches, $all_tags, $mirror) = (0, 0, 0, 0);
  4033.   my ($thin, $repo) = (0, 0);
  4034.   my @branches;
  4035.   my @tags;
  4036.   my $bypass_modification_check = 0;
  4037.   my $result = main::GetOptions(
  4038.     "--help"              => sub { $self->help() },
  4039.     "--branch=s"          => sub { push(@branches, $_[1]) },
  4040.     "--tag=s"             => sub { push(@tags, $_[1]) },
  4041.     "--all-branches|all"  => \$all_branches,
  4042.     "--matching-branches" => \$matching_branches,
  4043.     "--all-tags"          => \$all_tags,
  4044.     "tags"                => \$all_tags,
  4045.     "--mirror"            => \$mirror,
  4046.     "--dry-run"           => sub { &$record_arg(@_) },
  4047.     "--porcelain"         => sub { &$record_arg(@_) },
  4048.     "--progress"          => sub { &$record_arg(@_) },
  4049.     "--receive-pack=s"    => sub { &$record_args(@_) },
  4050.     "force|f"             => sub { &$record_arg(@_) },
  4051.     "repo=s"              => \$repo,
  4052.     "thin"                => sub { &$record_arg(@_) },
  4053.     "no-thin"             => sub { &$record_arg(@_) },
  4054.     "verbose|v"           => sub { &$record_arg(@_) },
  4055.     "set-upstream|u"      => sub { &$record_arg(@_) },
  4056.     "bypass-modification-check|b" => \$bypass_modification_check,
  4057.     );
  4058.   die "Cannot specify individual branches and request all branches too!\n"
  4059.     if @branches && ($all_branches || $mirror);
  4060.   die "Cannot specify individual tags and request all tags too!\n"
  4061.     if @tags && ($all_tags || $mirror);
  4062.   my $repository = shift @ARGV;
  4063.   my @git_refspecs = @ARGV;
  4064.  
  4065.   if (!$bypass_modification_check) {
  4066.     my $status = RepoUtil::commit_push_checks($package_name,
  4067.                                               {unknown => 1,
  4068.                                                changes => 1,
  4069.                                                unmerged_changes => 1});
  4070.   } else {
  4071.     # Record the set of unknown files we ignored with -b, so the -b flag
  4072.     # isn't needed next time.
  4073.     RepoUtil::record_ignored_unknowns();
  4074.   }
  4075.  
  4076.   push(@{$self->{args}}, "--all")    if $all_branches;
  4077.   push(@{$self->{args}}, "--tags")   if $all_tags;
  4078.   push(@{$self->{args}}, "--mirror") if $mirror;
  4079.  
  4080.   my $default_specified = 0;
  4081.   $default_specified = 1  if $all_branches;
  4082.   $default_specified = 1  if $all_tags;
  4083.   $default_specified = 1  if $mirror;
  4084.  
  4085.   #
  4086.   # Get the repository to push to
  4087.   #
  4088.   if (defined $repository && $repository =~ m#^-#) {
  4089.     die "Invalid repository to push to: $repository\n";
  4090.   }
  4091.   my $remote;
  4092.   if ($repository) {
  4093.     push(@{$self->{args}}, $repository);
  4094.   } elsif (!$repository && (@branches || @tags || !$default_specified)) {
  4095.     $repository = RepoUtil::get_default_push_pull_repository();
  4096.     push(@{$self->{args}}, $repository);
  4097.     $remote = $repository;
  4098.   } else {
  4099.     # Just drop through to the git push defaults.
  4100.   }
  4101.  
  4102.   #
  4103.   # Prevent pushing to a non-bare repository (on local filesystem or over
  4104.   # ssh; I don't know how to detect other cases)...unless user explicitly
  4105.   # specifies both source and destination references explicitly
  4106.   #
  4107.   my $remote_chk = $remote || $repository;
  4108.   $repository = _get_push_repository($repository);
  4109.   my $push_to_non_bare_repo;
  4110.   if ($repository) {
  4111.  
  4112.     # If the user uses a refspec including a colon character, assume
  4113.     # they know what they are doing and skip the non-bare check
  4114.     if (! grep {$_ =~ /:/} @git_refspecs) {
  4115.  
  4116.       # Check if we have already determined this repository to be bare
  4117.       my $is_bare;
  4118.       $is_bare = RepoUtil::get_config("remote.$remote.bare") if $remote;
  4119.       if (defined $is_bare) {
  4120.         $push_to_non_bare_repo = ($is_bare eq "false");
  4121.       } else {
  4122.         $is_bare = _check_if_bare($repository);
  4123.         if (defined $is_bare && defined $remote) {
  4124.           RepoUtil::set_config("remote.$remote.bare", $is_bare);
  4125.         }
  4126.         $push_to_non_bare_repo = (defined $is_bare && $is_bare eq "false");
  4127.       }
  4128.     }
  4129.   }
  4130.   # Throw an error if the user is trying to push to a bare repository
  4131.   # (and not using a refspec with a colon character)
  4132.   if ($push_to_non_bare_repo) {
  4133.     print STDERR <<EOF;
  4134. Aborting: You are trying to push to a repository with an associated working
  4135. copy, which will leave its working copy out of sync with its repository.
  4136. Rather than pushing changes to that repository, you should go to where that
  4137. repository is located and pull changes into it (using eg pull).  If you
  4138. know what you are doing and know how to deal with the consequences, you can
  4139. override this check by explicitly specifying source and destination
  4140. references, e.g.
  4141.   eg push REMOTE BRANCH:REMOTE_BRANCH
  4142. Please refer to
  4143.   eg help topic refspecs
  4144. to learn what this syntax means and what the consequences of overriding this
  4145. check are.
  4146. EOF
  4147.     exit 1;
  4148.   }
  4149.  
  4150.   #
  4151.   # Get the default branch to push to, if needed
  4152.   #
  4153.   push(@{$self->{args}}, ":") if $matching_branches;
  4154.   $default_specified = 1  if $matching_branches;
  4155.  
  4156.   if (!@branches && !@tags && !@git_refspecs && !$default_specified) {
  4157.     # User hasn't specified what to push; default choices:
  4158.     # 1 - remote.$remote.(push|mirror) options
  4159.     my $default_known = 0;
  4160.     if (defined(RepoUtil::get_config("remote.$remote_chk.push")) ||
  4161.         defined(RepoUtil::get_config("remote.$remote_chk.mirror"))) {
  4162.       $default_known = 1;
  4163.     }
  4164.     # 2 - push.default option
  4165.     if (defined(RepoUtil::get_config("push.default"))) {
  4166.       $default_known = 1;
  4167.     }
  4168.     # 3 - branch.$branch.merge option
  4169.     if (!$default_known) {
  4170.       my $branch = RepoUtil::current_branch();
  4171.       my $push_branch = RepoUtil::get_config("branch.$branch.merge");
  4172.       if (defined $push_branch) {
  4173.         $push_branch =~ s#refs/heads/##;
  4174.         push(@{$self->{args}}, "$branch:$push_branch");
  4175.         $default_known = 1;
  4176.       }
  4177.     }
  4178.     # 4 - the only branch that exists at the remote end
  4179.     if (!$default_known && defined $repository) {
  4180.       my $only_branch = RepoUtil::get_only_branch($repository, "push");
  4181.       push(@{$self->{args}}, $only_branch);
  4182.     }
  4183.   }
  4184.  
  4185.   #
  4186.   # Get the branch(es) to push
  4187.   #
  4188.   push(@branches, @git_refspecs);
  4189.   push(@{$self->{args}}, @branches);
  4190.   foreach my $tag (@tags) {
  4191.     push(@{$self->{args}}, ("tag", $tag));
  4192.   }
  4193. }
  4194.  
  4195. sub run {
  4196.   my $self = shift;
  4197.  
  4198.   my @args = Util::quote_args(@{$self->{args}});
  4199.   return ExecUtil::execute("$GIT_CMD push @args", ignore_ret => 1);
  4200. }
  4201.  
  4202. ###########################################################################
  4203. # rebase                                                                  #
  4204. ###########################################################################
  4205. package rebase;
  4206. @rebase::ISA = qw(subcommand);
  4207. INIT {
  4208.   $COMMAND{rebase} = {
  4209.     extra => 1,
  4210.     section => 'timesavers',
  4211.     about => "Port local commits, making them be based on a different\n" .
  4212.              "                repository version"
  4213.     };
  4214. }
  4215.  
  4216. sub new {
  4217.   my $class = shift;
  4218.   my $self = $class->SUPER::new(
  4219.     git_repo_needed => 1,
  4220.     initial_commit_error_msg => "Error: No recorded commits to rewrite.",
  4221.     @_);
  4222.   bless($self, $class);
  4223.   #
  4224.   # Note: Parts of help were taken from the git-rebase manpage, which
  4225.   # was also available under GPLv2.
  4226.   #
  4227.   $self->{'help'} = "
  4228. Usage:
  4229.  eg rebase [-i | --interactive] [ --since SINCE ] [ --onto ONTO ]
  4230.            [ --against AGAINST ] [BRANCH_TO_REBASE]
  4231.  eg rebase [ --continue | --skip | --abort ]
  4232.  
  4233. Description:
  4234.  Rewrites commits on a branch, making them be based on a different
  4235.  repository version.  Technically, the old commits are not overwritten or
  4236.  deleted (only new ones are written), meaning that other branches sharing
  4237.  the same commits will be unaffected and users can undo a rebase (until
  4238.  the unused commits are cleaned up after a few weeks).
  4239.  
  4240.  WARNING:
  4241.    Rebasing commits in a branch is an advanced operation which changes
  4242.    history in a way that will cause problems for anyone who already has a
  4243.    copy of the branch in their repository when they try to pull updates
  4244.    from you.  This may cause them to experience many conflicts in their
  4245.    merges and require them to resolve those conflicts manually, or rewrite
  4246.    their own history, or even toss out their changes and simply accept
  4247.    your version.  (The last of those options is common enough that there
  4248.    is a special method of pulling and pushing changes in such cases; see
  4249.    'eg help topic refspecs' for more details.)
  4250.  
  4251.  Non-interactive rebase (running without the --interactive or -i flags):
  4252.    Specifying which commits to rewrite and what to rewrite them relative
  4253.    to involves specifying up to three branches or revisions: SINCE, ONTO,
  4254.    and BRANCH_TO_REBASE.  eg will take all commits in the BRANCH_TO_REBASE
  4255.    branch that are not in the SINCE branch, and record them as commits on
  4256.    top of the tip of the ONTO branch.  The ONTO and SINCE branches are not
  4257.    changed by this operation.  The BRANCH_TO_REBASE branch is changed to
  4258.    record the tip of the newly written branch.
  4259.  
  4260.    See also the \"If a conflict occurs\" section below.
  4261.  
  4262.  Interactive rebase (running with the --interactive or -i flag):
  4263.    Interactive rebasing allows you a chance to edit the commits which are
  4264.    rebased, including
  4265.      * reordering commits
  4266.      * removing commits
  4267.      * combining multiple commits into one commit
  4268.      * amending commits to include different changes or log messages
  4269.      * splitting one commit into multiple commits
  4270.    When running interactively, eg rebase will begin by making a list of
  4271.    the commits which are about to be rebased and allow you to change the
  4272.    the list before rebasing.  The list will include one commit per line,
  4273.    allowing you to
  4274.      * reorder commits by reordering lines
  4275.      * removing commits by removing lines
  4276.      * combining multiple commits into one, by changing 'pick' to 'squash'
  4277.        at the beginning of each line of the commits you want combined
  4278.        *except* the first
  4279.      * amend a commit by changing the 'pick' at the beginning of the line
  4280.        of the relevant commit to 'edit'.  This will make eg rebase stop
  4281.        after applying that commit, allowing you to make changes and run
  4282.        'eg commit --amend' followed by 'eg rebase --continue'.
  4283.      * split one commit into multiple commits by changing 'pick' at the
  4284.        beginning of the line of the relevant commit to 'edit'.  This will
  4285.        make eg rebase stop *after* applying that commit, allowing you to
  4286.        manually undo that commit while keeping the changes in the working
  4287.        copy (with 'eg reset HEAD~1') and then make multiple commits (with
  4288.        'eg commit') before running 'eg rebase --continue'.  Note that eg
  4289.        stash may come in handy for testing the split commits.
  4290.  
  4291.  If a conflict occurs:
  4292.    Rebase will stop at the first problematic commit and leave conflict
  4293.    markers (<<<<<<) in the tree.  You can use eg status and eg diff to
  4294.    find the problematic files and locations.  Once you edit the files to
  4295.    fix the conflicts, you can run
  4296.      eg resolved FILE
  4297.    to mark the conflicts in FILE as resolved.  Once you have resolved all
  4298.    conflicts, you can run
  4299.      eg rebase --continue
  4300.    If you simply want to skip the problematic patch (and end up with one
  4301.    less commit), you can instead run
  4302.      eg rebase --skip
  4303.    Alternatively, to abort the rebase and return to your previous state,
  4304.    you can run
  4305.      eg rebase --abort
  4306.  
  4307. Examples:
  4308.  Take a branch named topic that was split off of the master branch, and
  4309.  update it to be based on the new tip of master.
  4310.      \$ eg rebase --since master --onto master topic
  4311.    Pictorally, this changes:
  4312.                 A---B---C topic
  4313.                /
  4314.           D---E---F---G master
  4315.    into
  4316.                         A'--B'--C' topic
  4317.                        /
  4318.           D---E---F---G master
  4319.  
  4320.  Same as the the above example, with less typing
  4321.      \$ eg rebase --against master topic
  4322.  
  4323.  Same as the last two examples, assuming topic is the current branch
  4324.      \$ eg rebase --against master
  4325.  
  4326.  Take a branch named topic that is based off of a branch named next, which
  4327.  is in turn based off master, and rewrite topic so that it appears to be
  4328.  based off the most recent version of master.
  4329.      \$ eg rebase --since next --onto master topic
  4330.    Pictorally, this changes
  4331.           o---o---o---o---o  master
  4332.                \\
  4333.                 o---o---o---o---o  next
  4334.                                  \\
  4335.                                   o---o---o  topic
  4336.    into
  4337.           o---o---o---o---o  master
  4338.               |            \\
  4339.               |             o'--o'--o'  topic
  4340.                \\
  4341.                 o---o---o---o---o  next
  4342.  
  4343.  Take just the last two commits of the current branch, and rewrite them
  4344.  to be relative to the commit just before the most recent on the master
  4345.  branch.
  4346.      \$ eg rebase --since current~2 --onto master~1 current
  4347.    Pictorally, this changes:
  4348.                    A---B---C---D---E  current
  4349.                   /
  4350.           F---G---H---I---J---K master
  4351.    into
  4352.                            D'---E' current
  4353.                           /
  4354.           F---G---H---I---J---K master
  4355.  
  4356.  Reorder the last two commits on the current branch
  4357.      \$ eg rebase --interactive --since HEAD~2
  4358.  (Then edit the file you are presented with and change the order of the
  4359.  two lines beginning with 'pick')
  4360.    Pictorally, this changes:
  4361.           A---B---C---D---E---F master
  4362.    into
  4363.           A---B---C---D---F'---E' master
  4364.  
  4365. Options:
  4366.  --since SINCE
  4367.    Upstream branch to compare against; only commits not found in this
  4368.    branch will be rebased.  Note that if --onto is not specified, the
  4369.    value of SINCE will be used for that as well.
  4370.  
  4371.    The value of SINCE is not restricted to existing branch names; any
  4372.    valid revision can be used (due to the fact that all revisions know
  4373.    their parents and a revision plus its ancestors can define a branch).
  4374.  
  4375.  --onto ONTO
  4376.    Starting point at which to create the new commits.  If the --onto
  4377.    option is not specified, the starting point is whatever is provided by
  4378.    the --since option.  Any valid revision can be used for the value of
  4379.    ONTO.
  4380.  
  4381.  --against AGAINST
  4382.    An alias for --since AGAINST, provided to make command lines clearer
  4383.    when the --onto flag is not also used.  (Typically, --against is used
  4384.    if --onto is not, and --since is used if --onto is, but --against and
  4385.    --since can be used interchangably.)
  4386.  
  4387.  --interactive, -i
  4388.    Make a list of the revisions which are about to be rebased and let the
  4389.    user edit that list before rebasing.  Can be used to split, combine,
  4390.    remove, insert, reorder, or edit commits.
  4391.  
  4392.  --continue
  4393.    Restart the rebasing process after resovling a conflict
  4394.  
  4395.  --skip
  4396.    Restart the rebasing process by skipping the current patch (resulting
  4397.    in a rewritten history with one less commit).
  4398.  
  4399.  --abort
  4400.    Abort the stopped rebase operation and restore the original branch
  4401. ";
  4402.   $self->{'differences'} = "
  4403.  The only differences between eg rebase and git rebase are cosmetic;
  4404.  further, eg rebase accepts all options and flags that git rebase accepts.
  4405.  
  4406.  eg adds the identically behaved flags --since and --against in
  4407.  preference to using the position of the branch/revision name on the
  4408.  command line.  Note that
  4409.    git rebase master
  4410.  is somewhat confusing in that it isn't rebasing master but the current
  4411.  branch.  To make this clearer, eg allows (and encourages) the form
  4412.    eg rebase --against master
  4413.  The reason that both --against and --since flags were added (with
  4414.  identical behavior), is that the former makes for clearer command lines
  4415.  when the --onto flag is not also used.
  4416. ";
  4417.   return $self;
  4418. }
  4419.  
  4420. sub preprocess {
  4421.   my $self = shift;
  4422.  
  4423.   #
  4424.   # Parse options
  4425.   #
  4426.   $self->{args} = [];
  4427.   my $record_arg   = sub { push(@{$self->{args}}, "--$_[0]"); };
  4428.   my $record_args  = sub { $_[0] = "--$_[0]"; push(@{$self->{args}}, @_);  };
  4429.   my $since;
  4430.   my $result = main::GetOptions(
  4431.     "--help"              => sub { $self->help() },
  4432.     "interactive|i"       => sub { &$record_arg(@_) },
  4433.     "verbose|v"           => sub { &$record_arg(@_) },
  4434.     "merge|m"             => sub { &$record_arg(@_) },
  4435.     "C=i"                 => sub { &$record_args(@_) },
  4436.     "whitespace=s"        => sub { push(@{$self->{args}},"--whitespace=$_[1]") },
  4437.     "preserve-merges|p"   => sub { &$record_arg(@_) },
  4438.     "onto=s"              => sub { &$record_args(@_) },
  4439.     "against=s"           => sub { $since=$_[1] },
  4440.     "since=s"             => sub { $since=$_[1] },
  4441.     "continue"            => sub { &$record_arg(@_) },
  4442.     "skip"                => sub { &$record_arg(@_) },
  4443.     "abort"               => sub { &$record_arg(@_) },
  4444.     );
  4445.   die "Too many branches/revisions specified\n"
  4446.     if @ARGV > 1 && defined $since;
  4447.   push(@{$self->{args}}, $since) if defined $since;
  4448.   push(@{$self->{args}}, @ARGV);
  4449. }
  4450.  
  4451. sub run {
  4452.   my $self = shift;
  4453.  
  4454.   my @args = Util::quote_args(@{$self->{args}});
  4455.   return ExecUtil::execute("$GIT_CMD rebase @args", ignore_ret => 1);
  4456. }
  4457.  
  4458. ###########################################################################
  4459. # remote                                                                  #
  4460. ###########################################################################
  4461. package remote;
  4462. @remote::ISA = qw(subcommand);
  4463. INIT {
  4464.   $COMMAND{remote} = {
  4465.     unmodified_behavior => 1,
  4466.     extra => 1,
  4467.     section => 'collaboration',
  4468.     about => 'Manage named remote repositories',
  4469.     };
  4470. }
  4471.  
  4472. sub new {
  4473.   my $class = shift;
  4474.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  4475.   bless($self, $class);
  4476.   $self->{'help'} = "
  4477. Usage:
  4478.  eg remote
  4479.  eg remote add REMOTENAME URL
  4480.  eg remote rm REMOTENAME
  4481.  eg remote update GROUPNAME
  4482.  
  4483. Description:
  4484.  eg remote is a convenience utility to make it easy to track changes from
  4485.  multiple remote repositories.  It is used to
  4486.    1) Set up
  4487.         REMOTENAME -> URL
  4488.       aliases that can be used in the place of full urls to simplify
  4489.       commands such as push or pull
  4490.    2) Pulling updates from multiple branches of a remote repository at
  4491.       once and storing them in remote tracking branches (which differ from
  4492.       normal branches only in that they have a prefix of REMOTENAME/ in
  4493.       their name).
  4494.    3) Pulling updates from multiple branches of multiple remote
  4495.       repositories at once, storing them all in remote tracking branches.
  4496.  
  4497. Examples:
  4498.  The examples section is split into three categories:
  4499.    1) Managing which remotes exist:
  4500.    2) Using one or more existing remotes
  4501.    3) Using remote tracking branches created through usage of remotes
  4502.  
  4503.  Category 1: Managing which remotes exist:
  4504.  
  4505.    List which removes exist
  4506.      \$ eg remote
  4507.    or, list remotes and their urls (among other things)
  4508.      \$ eg info
  4509.  
  4510.    Add a new remote for the url ssh://some.machine.org//path/to/repo.git,
  4511.    giving it the name jim
  4512.      \$ eg remote add jim ssh://some.machine.org//path/to/repo.git
  4513.  
  4514.    Add a new remote for the url git://composit.org//location/eyecandy.git,
  4515.    giving it the name bling
  4516.      \$ eg remote add bling git://composit.org//location/eyecandy.git
  4517.  
  4518.    Delete the remote named bob, and remove all related remote tracking
  4519.    branches (i.e. those branches whose names begin with \"bob/\"), as well
  4520.    as any associated configuration settings
  4521.      \$ eg remote rm bob
  4522.    
  4523.  Category 2: Using one or more existing remotes
  4524.  
  4525.    Pull updates for all branches of the remote jill, storing each in a
  4526.    remote tracking branch of the local repository named jill/BRANCH.
  4527.      \$ eg fetch jill
  4528.  
  4529.    Pull changes from the magic branch of the remote merlin and merge it
  4530.    into the current branch (i.e. standard pull behavior) AND also update
  4531.    all remote tracking branches associated with the remote (i.e. act as if
  4532.    'eg fetch merlin' was also run)
  4533.      \$ eg pull --branch magic merlin
  4534.  
  4535.    Grab updates from all remotes, i.e. run 'eg fetch REMOTE' for each
  4536.    remote.
  4537.      \$ eg remote update
  4538.    (Technically, some remotes could be manually configured to be excluded
  4539.    from this update.)
  4540.  
  4541.    Grab updates from all remotes in the group named friends (created by
  4542.    use of 'eg config remotes.friends \"REMOTE1 REMOTE2...\"'), i.e. run
  4543.    'eg fetch REMOTE' for each remote in the friends group
  4544.      \$ eg remote update friends
  4545.  
  4546.  Category 3: Using remote tracking branches created through usage of remotes
  4547.  
  4548.    List all remote tracking branches
  4549.      \$ eg branch -r
  4550.  
  4551.    Merge the remote tracking branch jill/stable into the current branch
  4552.      \$ eg merge jill/stable
  4553.  
  4554.    Get a history of the changes on the bling/explode branch
  4555.      \$ eg log bling/explode
  4556.  
  4557.    Create a new branch named my-testing based off of the remote tracking
  4558.    branch jenny/testing
  4559.      \$ eg branch my-testing jenny/testing
  4560. ";
  4561.   return $self;
  4562. }
  4563.  
  4564. ###########################################################################
  4565. # reset                                                                   #
  4566. ###########################################################################
  4567. package reset;
  4568. @reset::ISA = qw(subcommand);
  4569. INIT {
  4570.   $COMMAND{reset} = {
  4571.     extra => 1,
  4572.     section => 'modification',
  4573.     about => 'Forget local commits and (optionally) undo their changes'
  4574.     };
  4575. }
  4576.  
  4577. sub new {
  4578.   my $class = shift;
  4579.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  4580.   bless($self, $class);
  4581.   $self->{'help'} = "
  4582. Usage:
  4583.  eg reset [--working-copy | --no-unstaging] [REVISION]
  4584.  
  4585. Description:
  4586.  Forgets local commits for the active branch and (optionally) undoes their
  4587.  changes in the working copy.  If you have staged changes (changes you
  4588.  explictly marked as ready for commit) this function also unstages them by
  4589.  default.  See 'eg help topic staging' to learn about the staging area.
  4590.  
  4591.  From a computer science point of view, eg reset moves the current branch
  4592.  tip to point at an older commit, and also optionally changes the working
  4593.  copy and staging area to match the version of the repository recorded in
  4594.  the older commit.
  4595.  
  4596.  Note that this function should be used with caution; it is often used to
  4597.  discard unwanted data or to modify recent local \"history\" of commits.
  4598.  You want to be careful to not also discard wanted data, and modifying
  4599.  history is a bad idea if someone has already obtained a copy of that
  4600.  local history from you (rewriting history makes merging and updating
  4601.  problematic).
  4602.  
  4603. Examples:
  4604.  Throw away all changes since the last commit
  4605.      \$ eg reset --working-copy HEAD
  4606.  Note that HEAD always refers to the current branch, and the current
  4607.  branch always refers to its last commit.
  4608.  
  4609.  Throw away the last three commits and all current changes (this is a bad
  4610.  idea if someone has gotten a copy of these commits from you; this should
  4611.  only be done for truly local changes that you no longer want).
  4612.      \$ eg reset --working-copy HEAD~3
  4613.  
  4614.  Unrecord the last two commits, but keep the changes corresponding to these
  4615.  commits in the working copy.  (This can be used to fix a set of \"broken\"
  4616.  commits.)
  4617.      \$ eg reset HEAD~2
  4618.  
  4619.  While working on the \"stable\" branch, you decide that the last 5 commits
  4620.  should have been part of a separate branch.  Here's how you retroactively
  4621.  make it so:
  4622.      Verify that your working copy is clean...then
  4623.      \$ eg branch difficult_bugfix
  4624.      \$ eg reset --working-copy HEAD~5
  4625.      \$ eg switch difficult_bugfix
  4626.  The first step creates a new branch that initially could be considered an
  4627.  alias for the stable branch, but does not switch to it.  The second step
  4628.  moves the stable branch tip back 5 commits and modifies the working copy
  4629.  to match.  The last step switches to the difficult_bugfix branch, which
  4630.  updates the working copy with the contents of that branch.  Thus, in the
  4631.  end, the working copy will have the same contents as before you executed
  4632.  these three steps (unless you had local changes when you started, in
  4633.  which case those local changes will be gone).
  4634.  
  4635.  Stage files (mark changes in them as good and ready for commit but
  4636.  without yet committing them), then change your mind and unstage all
  4637.  files.
  4638.      \$ eg stage foo.c bla.h
  4639.      \$ eg reset HEAD
  4640.  Note that using HEAD as the commit means to forget all commits since HEAD
  4641.  (always an empty set) and undo any staged changes since that commit.
  4642.  
  4643. Options:
  4644.  --working-copy
  4645.    Also make the working tree match the version of the repository recorded
  4646.    in the specified commit.  If this option is not present, the working
  4647.    copy will not be modified.
  4648.  
  4649.  --no-unstaging
  4650.    Do not modify the staging area; only change the current branch tip to
  4651.    point to the older commit.
  4652.  
  4653.  REVISION
  4654.    A reference to a recorded version of the repository, defaulting to HEAD
  4655.    (meaning the most recent commit on the current branch).  See 'eg help
  4656.    topic revisions' for more details.
  4657.  
  4658. ";
  4659.   $self->{'differences'} = '
  4660.  The only differences between eg reset and git reset are cosmetic;
  4661.  further, eg reset accepts all options and flags that git reset accepts.
  4662.  
  4663.  git reset uses option names of --soft, --mixed, and --hard.  While eg
  4664.  reset will accept these option names for compatibility, it provides
  4665.  alternative names that are more meaningful:
  4666.    --working-copy     <=> --hard
  4667.    --no-unstaging     <=> --soft
  4668.  There is no alternate name for --mixed, since it is the default and thus
  4669.  does not need to appear on the command line at all.
  4670.  
  4671.  The modified revert command of eg is encouraged for reverting specific
  4672.  files, though eg reset has the same file-specific reverting that git
  4673.  reset does.
  4674. ';
  4675.   return $self;
  4676. }
  4677.  
  4678. sub preprocess {
  4679.   my $self = shift;
  4680.  
  4681.   #
  4682.   # Parse options
  4683.   #
  4684.   my ($hard, $soft) = (0, 0);
  4685.   return if (scalar(@ARGV) > 0 && $ARGV[0] eq "--");
  4686.  
  4687.   my $result = main::GetOptions(
  4688.     "--help"         => sub { $self->help() },
  4689.     "--working-copy" => \$hard,
  4690.     "--no-unstaging" => \$soft,
  4691.     );
  4692.   die "Cannot specify both --working-copy and --no-unstaging!\n"
  4693.     if $hard && $soft;
  4694.   unshift(@ARGV, "--hard") if $hard;
  4695.   unshift(@ARGV, "--soft") if $soft;
  4696. }
  4697.  
  4698. ###########################################################################
  4699. # resolved                                                                #
  4700. ###########################################################################
  4701. package resolved;
  4702. @resolved::ISA = qw(subcommand);
  4703. INIT {
  4704.   $COMMAND{resolved} = {
  4705.     new_command => 1,
  4706.     extra => 1,
  4707.     section => 'compatibility',
  4708.     about => 'Declare conflicts resolved and mark file as ready for commit'
  4709.     };
  4710. }
  4711.  
  4712. sub new {
  4713.   my $class = shift;
  4714.   my $self = $class->SUPER::new(git_repo_needed => 1,
  4715.                                 git_equivalent => 'add',
  4716.                                 @_);
  4717.   bless($self, $class);
  4718.   $self->{'help'} = "
  4719. Usage:
  4720.  eg resolved PATH...
  4721.  
  4722. Description:
  4723.  Declare conflicts resolved for the specified paths, and mark contents of
  4724.  those files as ready for commit.
  4725.  
  4726. Examples
  4727.  After fixing any update or merge conflicts in foo.c, declare the fixing to
  4728.  be done and the contents ready to commit.
  4729.      \$ eg resolved foo.c
  4730. ";
  4731.   $self->{'differences'} = "
  4732.  eg resolved is a command new to eg that is not part of git.  It is
  4733.  almost synonymous with git add; however, there are two differences:
  4734.  (a) eg resolved will work on a locally deleted file in the unmerged
  4735.  state (git add will complain that there's 'No such file or
  4736.  directory', and some users have had difficulty trying to find out
  4737.  that they needed to run git rm on such files), (b) eg resolved only
  4738.  works on files in the unmerged state (reporting an error if files
  4739.  not in such a state are specified).
  4740. ";
  4741.   return $self;
  4742. }
  4743.  
  4744. sub run {
  4745.   my $self = shift;
  4746.  
  4747.   die "Error: Must specify paths to resolve.\n" if !@ARGV;
  4748.   @ARGV = Util::quote_args(@ARGV);
  4749.  
  4750.   # Determine which files are actually unmerged
  4751.   my ($ret, $output) =
  4752.     ExecUtil::execute_captured("$GIT_CMD ls-files -u --error-unmatch @ARGV",
  4753.       ignore_ret => 1);
  4754.   chomp($output);
  4755.   my @lines = split('\n', $output);
  4756.  
  4757.   # If there are some files that do not have conflicts, scream at the user
  4758.   if ($ret != 0) {
  4759.     my @not_unmerged_paths;
  4760.  
  4761.     foreach my $line (@lines) {
  4762.       if ($line =~ m/^error: pathspec '(.*?)' did not match any file/) {
  4763.         push(@not_unmerged_paths, $1);
  4764.       }
  4765.     }
  4766.     if (@not_unmerged_paths) {
  4767.       die "Error: The following are not unmerged files and thus don't " .
  4768.           "need resolving:\n  " . join("\n  ", @not_unmerged_paths) . "\n";
  4769.     } else {
  4770.       die "$output\n";
  4771.     }
  4772.   }
  4773.  
  4774.   # Determine the unmerged files (users may have passed a directory which
  4775.   # has both unmerged files and modified but unstaged ones; we only want
  4776.   # to stage the unmerged files from such a directory).
  4777.   my %files;
  4778.   foreach my $line (@lines) {
  4779.     $line =~ m/^\d+ [0-9a-f]+ \d\t(.*)$/;
  4780.     $files{$1} = 1;
  4781.   }
  4782.   my @unmerged_files = keys %files;
  4783.  
  4784.   # Run add -u instead of just add, since we want locally deleted files to
  4785.   # be picked up as well.
  4786.   return ExecUtil::execute("$GIT_CMD add -u @unmerged_files", ignore_ret => 1);
  4787. }
  4788.  
  4789. ###########################################################################
  4790. # revert                                                                  #
  4791. ###########################################################################
  4792. package revert;
  4793. @revert::ISA = qw(subcommand);
  4794. INIT {
  4795.   $COMMAND{revert} = {
  4796.     section => 'modification',
  4797.     about => 'Revert local changes and/or changes from previous commits'
  4798.     };
  4799. }
  4800.  
  4801. sub new {
  4802.   my $class = shift;
  4803.   my $self = $class->SUPER::new(git_repo_needed => 1, git_equivalent => '', @_);
  4804.   bless($self, $class);
  4805.   $self->{'help'} = "
  4806. Usage:
  4807.  eg revert [[-m PARENT_NUMBER] --in REVISION | --since REVISION]
  4808.            [--staged | --unstaged] [--] [PATH...]
  4809.  
  4810. Description:
  4811.  eg revert undoes edits to your files, without changing the commit history
  4812.  or changing which commit is active.  (If you are looking for a different
  4813.  kind of 'undo'; they are discussed and contrasted below.)  There are many
  4814.  options for what to revert; you may want to jump ahead to the examples
  4815.  section below and then come back and read the full description.
  4816.  
  4817.  The work eg revert does includes discarding local modifications, removing
  4818.  recorded conflict states, undoing add or stage operations (i.e. unstaging
  4819.  files), and restoring deleted files to the previously recorded version.
  4820.  If you revert changes since some revision prior to the most recent,
  4821.  revert will also remove any files which were added in a later revision.
  4822.  
  4823.  By default, eg revert will revert edits since the last commit(*).  One
  4824.  can specify a different revision to revert file contents back to, or
  4825.  revert edits made in a single previous commit(**).  (Advanced usage note:
  4826.  eg revert will undo both staged and unstaged changes by default; you can
  4827.  request only one of these; see 'eg help topic staging' for more details
  4828.  on what staged and unstaged changes are.)
  4829.  
  4830.  (*) For an initial or root commit, eg revert will simply undo adds.  When
  4831.  in an uncompleted merge state, it is an error to not specify which commit
  4832.  to revert relative to (with the --since flag).
  4833.  
  4834. . (**) When reverting the changes made *in* a merge commit, the revert
  4835.  command needs to know which parent of the merge the revert should be
  4836.  relative to.  This can be specified using the -m option.
  4837.  
  4838.  To avoid accidental loss of local changes, nothing will be done when no
  4839.  arguments are provided to eg revert.  However, eg revert will check for
  4840.  various special cases (from the different types of 'undo' below), and try
  4841.  to provide an error message tailored to any special circumstances
  4842.  relevant to you.
  4843.  
  4844.  === Comparison of different types of 'undo' available ===
  4845.  * Back up or switch to an earlier commit (eg switch)
  4846.  * Make a new commit to reverse the changes of a previous commit (eg
  4847.    cherry-pick -R)
  4848.  * Remove commits from history (eg reset OR eg rebase --interactive)
  4849.  * Reverting edits, without switching commits or changing commit history
  4850.    (eg revert)
  4851.  * Abort an incomplete operation
  4852.    * Incomplete merge:      eg revert --since HEAD
  4853.    * Unfinished rebase:     eg rebase --abort
  4854.    * Unfinished apply mail: eg am --abort
  4855.    * Unfinished bisect:     eg bisect reset
  4856.  
  4857. Examples:
  4858.  Undo changes since the last commit on the current branch to bar.h and
  4859.  foo.c.  This can be done with either of the following methods:
  4860.      \$ eg revert bar.h foo.c                      # Method #1
  4861.      \$ eg revert --since HEAD bar.h foo.c         # Method #2, more explicit
  4862.  
  4863.  While on the bling branch, revert the changes in the last 3 commits (as
  4864.  well as any local changes) to any file under the directory docs.  This
  4865.  can be done by:
  4866.      \$ eg revert --since bling~3 docs
  4867.  
  4868.  While on the stable branch, you determine that the seventh commit prior
  4869.  to the most recent had a faulty change to foosubdir and baz.txt and you
  4870.  simply want to undo it.  This can be accomplished by:
  4871.      \$ eg revert --in stable~7 -- foosubdir baz.txt
  4872.  
  4873.  You decide that all changes to foobar.cpp in your working copy and in the
  4874.  last 2 commits are bad and want to revert them.  This is done by:
  4875.  of:
  4876.      \$ eg revert --since HEAD~2 -- foobar.c
  4877.  
  4878.  You decide that some of the changes in the merge commit HEAD~4 are bad.
  4879.  You would like to revert the changes to baz.py in HEAD~4 relative to its
  4880.  second parent.  This can be accomplished as follows:
  4881.      \$ eg revert -m 2 --in HEAD~4 baz.py
  4882.  
  4883.  (Advanced) Undo a previous stage, marking changes in foo.c as not
  4884.  being ready for commit (this is equivalent to eg unstage foo.c):
  4885.      \$ eg revert --staged foo.c
  4886.  
  4887.  (Advanced) Undo changes since the most recent stage to soopergloo.f77
  4888.      \$ eg revert --unstaged soopergloo.f77
  4889.  
  4890.  (Advanced) You decide that the changes to abracadabra.xml made in commit
  4891.  HEAD~8 are bad.  You want to revert those changes in the version of
  4892.  abracadabra.xml but only to your working copy.  This is done by:
  4893.      \$ eg revert --unstaged --in HEAD~8 -- abracadabra.xml
  4894.  
  4895. Options:
  4896.  --since
  4897.    Revert the changes made since the specified commit, including any local
  4898.    changes.  This takes the difference between the specified commit and
  4899.    the current version of the files and reverses these changes.
  4900.  
  4901.  --in
  4902.    Revert the changes made in the specified commit.  This takes the
  4903.    difference between the parent of the specified commit and the specified
  4904.    commit and reverse applies it.
  4905.  
  4906.  REVISION
  4907.    A reference to a recorded version of the repository, defaulting to HEAD
  4908.    (meaning the most recent commit on the current branch).  See 'eg help
  4909.    topic revisions' for more details.
  4910.  
  4911.  -m PARENT_NUMBER
  4912.    When reverting the changes made in a merge commit, the revert command
  4913.    needs to know which parent of the merge the revert should be relative
  4914.    to.  Use this flag with the parent number (1, 2, 3...) to specify which
  4915.    parent commit to revert relative to.
  4916.  
  4917.    Can only be used with the --in option.
  4918.  
  4919.  --staged
  4920.    Make changes only to the staged (explicitly marked as ready to be
  4921.    committed) version of files.
  4922.  
  4923.  --unstaged
  4924.    Make changes only to the unstaged version of files, i.e. only to the
  4925.    working copy.
  4926.  
  4927.  --
  4928.    This option can be used to separate command-line options and commits
  4929.    from the list of files, (useful when filenames might be mistaken for
  4930.    command-line options or be mistaken as a branch or tag name).
  4931.  
  4932.  PATH...
  4933.    One or more files or directories.  The changes reverted will be limited
  4934.    to the listed files or files below the listed directories.
  4935. ";
  4936.   $self->{'differences'} = '
  4937.  eg revert is similar to the revert command of svn, hg, bzr, or darcs.  It
  4938.  is not provided by any one git command; it overlaps with about five
  4939.  different git commands in specific cases.  git users wanting the
  4940.  functionality in eg revert will typically be guided by expert git users
  4941.  towards whichever git command seems like the most natural fit for the
  4942.  particular case the user asks about.  Quite often, such users will
  4943.  continue using the command they are given for subsequent situations...and
  4944.  will often stumble across multiple cases where the git command no longer
  4945.  matches the wanted revert behavior.
  4946.  
  4947.  git does provide a command called revert, which is a subset of the
  4948.  behavior of eg cherry-pick:
  4949.    git revert COMMIT
  4950.  is the same as
  4951.    eg cherry-pick -R COMMIT
  4952.  which is, modulo the automatic commit message provided by git revert, the
  4953.  same as
  4954.    eg revert --in COMMIT && eg commit
  4955.  Note that while eg revert --in may look similar to git revert, the former
  4956.  is about undoing changes in just the working copy, is typically
  4957.  restricted to a specific subset of files, and is usually just one change
  4958.  of many towards testing or creating something new to be committed.  The
  4959.  latter is always concerned with reverse applying an entire commit, and is
  4960.  almost always used to immediately record that change.
  4961.  
  4962.  Note that git revert commands are invalid syntax in eg (since eg revert
  4963.  always requires the --since or --in flags to be specified whenever a
  4964.  commit is).  This means that eg can catch such cases and notify git
  4965.  users to adopt the eg cherry-pick -R command.
  4966.  
  4967.  Due to these changes, eg revert should be much more welcoming to users of
  4968.  svn, hg, bzr, or darcs.  It also provides a simple discovery mechanism
  4969.  for existing git users to allow them to easily work with eg.
  4970.  Additionally, these changes also make the reset and checkout/switch
  4971.  subcommands of eg easier to understand by limiting their scope instead of
  4972.  each having two very different capabilities.  (Technically, eg reset and
  4973.  eg checkout still have those capabilities for backwards compatibility, I
  4974.  just omit them in the documentation.)
  4975.  
  4976.  It seems that perhaps eg revert could be extended further, to accept
  4977.  things like
  4978.      \$ eg revert --in HEAD~8..HEAD~5 foo.c
  4979.  to allow reverting changes made in a range of commits.  The --in could
  4980.  even be optional in such a case, since the range makes it clear what is
  4981.  wanted.
  4982. ';
  4983.   return $self;
  4984. }
  4985.  
  4986. sub preprocess {
  4987.   my $self = shift;
  4988.  
  4989.   my ($cur_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();
  4990.   my $initial_commit = RepoUtil::initial_commit();
  4991.  
  4992.   # Parsing opts
  4993.   my ($staged, $unstaged, $in) = (0, 0, -1);
  4994.   my $m;
  4995.   my $rev;
  4996.   my $result = main::GetOptions(
  4997.     "--help"         => sub { $self->help() },
  4998.     "-m=i"           => \$m,
  4999.     "--staged"       => \$staged,
  5000.     "--unstaged"     => \$unstaged,
  5001.     "--in=s"         => sub { $in = 1; $rev = $_[1]; },
  5002.     "--since=s"      => sub { $in = 0; $rev = $_[1]; },
  5003.     );
  5004.  
  5005.   # Parsing revs and files
  5006.   my ($opts, $revs, $files) = RepoUtil::parse_args([], @ARGV);
  5007.   unshift(@$revs, $rev) if defined($rev);
  5008.  
  5009.   #
  5010.   # Big ol' safety checks and warnings
  5011.   #
  5012.   if (!@$revs && !@$files) {
  5013.     my $files_modified = RepoUtil::files_modified();
  5014.     if (-f "$self->{git_dir}/MERGE_HEAD") {
  5015.       print STDERR<<EOF;
  5016. Aborting: no revisions or files specified to revert.  If you want to abort
  5017. your incomplete merge, try 'eg reset --working-copy HEAD'.
  5018. EOF
  5019.       exit 1;
  5020.     }
  5021.     elsif (-d "$self->{git_dir}/rebase-merge" ||
  5022.            -d "$self->{git_dir}/rebase-apply") {
  5023.       print STDERR<<EOF;
  5024. Aborting: no revisions or files specified to revert.  If you want to abort
  5025. your incomplete rebase, try:
  5026.   eg rebase --abort
  5027. EOF
  5028.       exit 1;
  5029.     }
  5030.     elsif (!$files_modified && !$initial_commit) {
  5031.       my $active_branch = RepoUtil::current_branch() || 'HEAD';
  5032.       print STDERR<<EOF;
  5033. There are no local changes to revert and you specified no revisions to revert
  5034. (or revert back to).  Please specify a revision with --in or --since.
  5035. Alternatively, if you want to modify commits instead of just the working copy
  5036. then use reset instead of revert:
  5037.  
  5038. If you want to undo a rebase (or a 'pull --rebase'), try:
  5039.   eg rebase --abort
  5040. If you want to undo a merge (or a plain 'pull'), try:
  5041.   eg merge --abort
  5042. If you want to undo the last commit (but keep its changes in the working copy),
  5043. try:
  5044.   eg reset $active_branch~1
  5045. If you just want to amend the last commit without undoing it, make the
  5046. additional changes you want and run:
  5047.   eg commit --amend
  5048. If you want to undo previous reset commands, get the appropriate reflog
  5049. reference from eg reflog (for example, using HEAD\@{1} for <REF>) and run:
  5050.   eg reset --working-copy <REF>
  5051. EOF
  5052.       exit 1;
  5053.     }
  5054.     elsif (!$initial_commit) {
  5055.       print STDERR<<EOF;
  5056. Aborting: no revisions or files specified.  If you want to revert and lose
  5057. all changes since the last commit, try adding the arguments
  5058.   --since HEAD
  5059. to the end of your command.
  5060. EOF
  5061.       exit 1;
  5062.     } else {
  5063.       print STDERR<<EOF;
  5064. Aborting: no files specified.
  5065. EOF
  5066.       exit 1;
  5067.     }
  5068.   }
  5069.  
  5070.   # Sanity checks
  5071.   die "Cannot specify -m without specifying --in.\n" if !$in && defined($m);
  5072.   die "Can only specify one revision\n" if @$revs > 1;
  5073.   die "No revision specified after --in\n"    if ($in == 1 && !@$revs);
  5074.   die "No revision specified after --since\n" if ($in == 0 && !@$revs);
  5075.   if ($in == -1 && @$revs) {
  5076.     die "You must specify either --in or --since when specifying a revision.\n".
  5077.         "(git users:) If you are used to git revert; try running\n".
  5078.         "  eg cherry-pick -R @ARGV\n";
  5079.   }
  5080.   die "Unrecognized options: @$opts\n" if @$opts;
  5081.   $in = 0 if $in == -1;
  5082.   if (!$staged && !$unstaged) {
  5083.     $staged = 1;
  5084.     $unstaged = 1;
  5085.   }
  5086.  
  5087.   # Special checks in the case of an incomplete merge to make sure we know
  5088.   # what to revert back to; if no --since or --in specified then we can only
  5089.   # proceed if the user is only reverting unstaged changes
  5090.   if (!@$revs && $staged && -f "$self->{git_dir}/MERGE_HEAD") {
  5091.     my @merge_branches = RepoUtil::merge_branches();
  5092.     my $list = join(", ", @merge_branches);
  5093.     print STDERR <<EOF;
  5094. Aborting: Cannot revert the changes since the last commit, since you are in
  5095. the middle of a merge and there are multiple last commits.  Please add
  5096.   --since BRANCH
  5097. to your flags to eg revert, where BRANCH is one of
  5098.   $list
  5099. If you simply want to abort your merge and undo its conflicts, run
  5100.   eg merge --abort
  5101. EOF
  5102.     exit 1;
  5103.   }
  5104.  
  5105.   if ($initial_commit) {
  5106.     die "Cannot revert a previous commit since there are no previous " .
  5107.       "commits.\n" if $in;
  5108.     die "Cannot revert to a previous commit since there are no previous " .
  5109.         "commits.\n" if !$in && @$revs;
  5110.   }
  5111.  
  5112.   my @quoted_files = Util::quote_args(@$files);
  5113.   my @unmerged_files = `$GIT_CMD ls-files --full-name -u -- @quoted_files`;
  5114.   if (@unmerged_files && $in) {
  5115.     die "Aborting: please clear conflicts from @unmerged_files before " .
  5116.         "proceeding.\n";
  5117.   }
  5118.  
  5119.   # Record needed information
  5120.   $self->{staged} = $staged;
  5121.   $self->{unstaged} = $unstaged;
  5122.   $self->{just_recent_unstaged} = !$in && !$staged && !@$revs;
  5123.   $self->{in} = $in;
  5124.   $self->{revs} = "@$revs";
  5125.   $self->{revs} = "HEAD" if !@$revs;
  5126.   $self->{initial_commit} = $initial_commit;
  5127.   if ($in) {
  5128.     # Get the revision whose changes we want to revert, and its parents
  5129.     Util::push_debug(new_value => 0);
  5130.     my $links = ExecUtil::output(
  5131.                   "$GIT_CMD rev-list --parents --max-count=1 $self->{revs}");
  5132.     Util::pop_debug();
  5133.     my @list = split(' ', $links);  # commit id + parent ids
  5134.  
  5135.     # Get a symbolic name for the parent revision we will diff against
  5136.     my $first_rev = $self->{revs};
  5137.     my $parent = $m || 1;
  5138.     $first_rev .= "^$parent";
  5139.  
  5140.     # Reverting changes in merge commits can only be done against one parent
  5141.     die "Cannot revert a merge commit without specifying a parent!\n"
  5142.       if !defined($m) && @list > 2;
  5143.  
  5144.     # Reverting relative to a parent can only be done with existing parents
  5145.     if ($parent + 1 > scalar(@list)) {
  5146.       die "Cannot revert the changes made in a commit that has no prior " .
  5147.         "commit\n" if !defined($m);
  5148.       die "The specified commit does not have $m parents; try a lower " .
  5149.         "value for -m\n" if defined($m);
  5150.     }
  5151.  
  5152.     # The combination of revs to diff between
  5153.     $self->{revs} = "$first_rev $self->{revs}";
  5154.   }
  5155.  
  5156.   # Determine some other stuff needed
  5157.   $self->{files} = \@quoted_files;
  5158.   my ($new_files, $newish_files, $revert_files);
  5159.   my ($newly_added_files, $new_since_rev_files, $other_files);
  5160.   if (!$in && !$initial_commit) {
  5161.     my $revision = (@$revs) ? $revs->[0] : "HEAD";
  5162.     ($newly_added_files, $new_since_rev_files, $other_files) =
  5163.        RepoUtil::get_revert_info($revision, @quoted_files);
  5164.   } elsif ($initial_commit) {
  5165.     $newly_added_files = $files;
  5166.     $new_since_rev_files = [];
  5167.     $other_files = [];
  5168.   }
  5169.   $self->{newly_added_files} = $newly_added_files;
  5170.   $self->{new_since_rev_files} = $new_since_rev_files;
  5171.   $self->{other_files} = $other_files;
  5172. }
  5173.  
  5174. sub run {
  5175.   my $self = shift;
  5176.  
  5177.   my $git_dir = RepoUtil::git_dir();
  5178.   my $paths_specified = scalar(@{$self->{files}}) > 0;
  5179.   my $ret = 0;
  5180.  
  5181.   if (!$self->{in}) {
  5182.     my $revision = $self->{revs};
  5183.     my @newly_added_files = @{$self->{newly_added_files}};
  5184.     my @new_since_rev_files = @{$self->{new_since_rev_files}};
  5185.     my @other_files = @{$self->{other_files}};
  5186.     my @all_files = @{$self->{files}};
  5187.  
  5188.     #
  5189.     # Case: Initial commit
  5190.     #
  5191.     if ($self->{initial_commit}) {
  5192.       $ret = ExecUtil::execute("$GIT_CMD rm --cached --quiet -- " .
  5193.                                "@newly_added_files", ignore_ret => 1);
  5194.       exit $ret if $ret;
  5195.     }
  5196.  
  5197.     #
  5198.     # Set: Reverting both staged and unstaged changes
  5199.     #
  5200.     elsif ($self->{staged} && $self->{unstaged}) {
  5201.       #
  5202.       # Case: ALL staged and unstaged changes since some revision
  5203.       #
  5204.       if (!$paths_specified) {
  5205.         if (@newly_added_files) {
  5206.           # git reset is not quiet even when requested and has idiotic return
  5207.           # state; if three files have conflicts and I try to reset some
  5208.           # file other than those three, the command is successful but it
  5209.           # spews warnings and gives a bad exit status
  5210.           ExecUtil::execute("$GIT_CMD reset -q $revision --" .
  5211.                             " @newly_added_files >/dev/null",
  5212.                             ignore_ret => 1);
  5213.         }
  5214.  
  5215.         my ($revision_sha1, $head_sha1, $temp_ret);
  5216.         if ($revision ne "HEAD") {
  5217.           Util::push_debug(new_value => 0);
  5218.           ($temp_ret, $revision_sha1) =
  5219.             ExecUtil::execute_captured("$GIT_CMD rev-parse --verify $revision",
  5220.                                        ignore_ret => 1);
  5221.           ($temp_ret, $head_sha1) =
  5222.             ExecUtil::execute_captured("$GIT_CMD rev-parse --verify HEAD",
  5223.                                        ignore_ret => 1);
  5224.           Util::pop_debug();
  5225.         }
  5226.  
  5227.         $ret = ExecUtil::execute("$GIT_CMD reset --hard $revision",
  5228.                                  ignore_ret => 1);
  5229.         exit $ret if $ret;
  5230.  
  5231.         if ($revision ne "HEAD" && $revision_sha1 ne $head_sha1) {
  5232.           # Note, cannot git reset --soft HEAD, since HEAD has changed in
  5233.           # the above reset...
  5234.           $ret = ExecUtil::execute("$GIT_CMD reset --soft HEAD\@{1}",
  5235.                                    ignore_ret => 1);
  5236.           exit $ret if $ret;
  5237.         }
  5238.       }
  5239.  
  5240.       #
  5241.       # Case: Selected staged and unstaged changes since some revision
  5242.       #
  5243.       if ($paths_specified) {
  5244.         if (@newly_added_files) {
  5245.           # See rant above about 'git reset is not quiet even when requested'
  5246.           ExecUtil::execute("$GIT_CMD reset -q $revision --" .
  5247.                             " @newly_added_files >/dev/null",
  5248.                             ignore_ret => 1);
  5249.         }
  5250.         if (@new_since_rev_files) {
  5251.           # Ugh, when --quiet doesn't actually mean "quiet".
  5252.           # (Reproduce with git-1.6.0.6 on incomplete merge handling testcase)
  5253.           $ret = ExecUtil::execute("$GIT_CMD rm --quiet --force " .
  5254.                                    "--ignore-unmatch -- @new_since_rev_files" .
  5255.                                    " > /dev/null",
  5256.                                    ignore_ret => 1);
  5257.           exit $ret if $ret;
  5258.         }
  5259.         if (@other_files) {
  5260.           $ret = ExecUtil::execute("$GIT_CMD checkout $revision -- " .
  5261.                                    "@other_files", ignore_ret => 1);
  5262.           exit $ret if $ret;
  5263.         }
  5264.       }
  5265.     }
  5266.  
  5267.     #
  5268.     # Set: Reverting just staged changes
  5269.     #
  5270.     elsif ($self->{staged}) {
  5271.       if ($paths_specified) {
  5272.         $ret = ExecUtil::execute("$GIT_CMD reset -q $revision -- @all_files",
  5273.                                  ignore_ret => 1);
  5274.         exit $ret if $ret;
  5275.       } else {
  5276.         $ret = ExecUtil::execute("$GIT_CMD read-tree $revision",
  5277.                                  ignore_ret => 1);
  5278.         exit $ret if $ret;
  5279.       }
  5280.     }
  5281.  
  5282.     #
  5283.     # Set: Reverting just unstaged changes
  5284.     #
  5285.     elsif ($self->{unstaged}) {
  5286.       if ($self->{just_recent_unstaged}) {
  5287.         die "Assertion failed: Paths not specified.\n" if (!$paths_specified);
  5288.         $ret = ExecUtil::execute("$GIT_CMD checkout -- @all_files",
  5289.                                  ignore_ret => 1);
  5290.         exit $ret if $ret;
  5291.       }
  5292.       else {
  5293.         if (@newly_added_files) {
  5294.           # This results in a no-op essentially, but at least it shows the
  5295.           # equivalent commands when no new_since_rev_files and no other_files
  5296.           push(@other_files, @newly_added_files);
  5297.         }
  5298.  
  5299.         if (@new_since_rev_files) {
  5300.           $ret = ExecUtil::execute("rm -f @new_since_rev_files",
  5301.                                    ignore_ret => 1);
  5302.           exit $ret if $ret;
  5303.         }
  5304.  
  5305.         if (@other_files || !$paths_specified) {
  5306.           my $cf = "@other_files";
  5307.           if (!$paths_specified) {
  5308.             my ($cur_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();
  5309.             ($cf) = Util::reroot_paths__from_to_files($top_dir, $cur_dir, '.');
  5310.           }
  5311.           my $old_git_index_file = $ENV{"GIT_INDEX_FILE"};
  5312.           $ENV{"GIT_INDEX_FILE"} = "$git_dir/tmp_index";
  5313.           $ret = ExecUtil::execute("$GIT_CMD checkout $revision " .
  5314.                                    "-- $cf", ignore_ret => 1);
  5315.           $ENV{"GIT_INDEX_FILE"} = $old_git_index_file;
  5316.           exit $ret if $ret;
  5317.  
  5318.           my ($tmp_index) = Util::quote_args("$git_dir/tmp_index");
  5319.           $ret = ExecUtil::execute("rm $tmp_index");
  5320.           exit $ret if $ret;
  5321.         }
  5322.       }
  5323.     }
  5324.   }
  5325.  
  5326.   if ($self->{in}) {
  5327.     # Must do unstaged changes first, or extra unknown files can "appear"
  5328.     my $location_flag;
  5329.     $location_flag = ""         if $self->{unstaged};
  5330.     $location_flag = "--cached" if $self->{staged};
  5331.     $location_flag = "--index"  if ($self->{staged} && $self->{unstaged});
  5332.  
  5333.     my @files = @{$self->{files}};
  5334.     my $marker = "";
  5335.     $marker = "-- " if (@files);
  5336.  
  5337.     my ($cur_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();
  5338.  
  5339.     my @diff_flags = ("--binary");
  5340.     my @apply_flags = ("--whitespace=nowarn", "--reject");
  5341.     push(@apply_flags, $location_flag) if $location_flag;
  5342.  
  5343.     # Print out the (nearly) equivalent commands if the user asked for
  5344.     # debugging information
  5345.     if ($DEBUG) {
  5346.       print "    >>Running: " .
  5347.             "$GIT_CMD diff @diff_flags $self->{revs} ${marker}@files | ";
  5348.       print "(cd $top_dir && " if ($top_dir ne $cur_dir);
  5349.       print "$GIT_CMD apply @apply_flags -R";
  5350.       print ")" if ($top_dir ne $cur_dir);
  5351.       print "\n";
  5352.     }
  5353.  
  5354.     # Sadly, using "git diff... | git apply ... -R" doesn't quite work,
  5355.     # because apply complains very loudly if the diff is empty.  So,
  5356.     # we have to run diff, slurp in its output, check if its nonempty,
  5357.     # and then only pipe that output back out to git apply if we have
  5358.     # an actual diff to revert.
  5359.     if ($DEBUG < 2) {
  5360.       open(DIFF, "$GIT_CMD diff @diff_flags $self->{revs} ${marker}@files |");
  5361.       my @output = <DIFF>;
  5362.       my $diff = join("", @output);
  5363.       # Listing unmerged paths doesn't count as nonempty
  5364.       $diff =~ s/\* Unmerged path.*\n//g;
  5365.       close(DIFF);
  5366.       $ret = $?;
  5367.       exit $ret >> 8 if $ret;
  5368.  
  5369.       if ($diff) {
  5370.         chdir($top_dir) if $top_dir ne $cur_dir;
  5371.         open(APPLY, "| $GIT_CMD apply @apply_flags -R");
  5372.         print APPLY $diff;
  5373.         close(APPLY);
  5374.         chdir($cur_dir) if $top_dir ne $cur_dir;
  5375.       }
  5376.     }
  5377.   }
  5378.  
  5379.   return 0;
  5380. }
  5381.  
  5382. ###########################################################################
  5383. # rm                                                                      #
  5384. ###########################################################################
  5385. package rm;
  5386. @rm::ISA = qw(subcommand);
  5387. INIT {
  5388.   $COMMAND{rm} = {
  5389.     extra => 1,
  5390.     section => 'modification',
  5391.     about => 'Remove files from subsequent commits and the working copy'
  5392.     };
  5393. }
  5394.  
  5395. sub new {
  5396.   my $class = shift;
  5397.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  5398.   bless($self, $class);
  5399.   $self->{'help'} = "
  5400. Usage:
  5401.  eg rm [-f] [-r] [--staged] FILE...
  5402.  
  5403. Description:
  5404.  Marks the contents of the specified files for removal from the next
  5405.  commit.  Also removes the given files from the working copy, unless
  5406.  otherwise specified with the --staged flag.
  5407.  
  5408.  To prevent data loss, the removal will be aborted if the file has
  5409.  modifications.  This check can be overriden with the -f flag.
  5410.  
  5411. Examples:
  5412.  Mark the content of the files foo and bar for removal from the next
  5413.  commit, and delete these files from the working copy.
  5414.      \$ eg rm foo bar
  5415.  
  5416.  Mark the content of the file baz.c for removal from the next commit, but
  5417.  keep baz.c in the working copy as an unknown file.
  5418.      \$ eg rm --staged baz.c
  5419.  
  5420.  (Advanced) Remove all *.txt files under the Documentation directory OR
  5421.  any of its subdirectories.  Note that the asterisk must be preceded with
  5422.  a backslash to prevent standard shell expansion.  (Google for 'shell
  5423.  expansion' if that makes no sense to you.)
  5424.      \$ eg rm Documentation/\\*.txt
  5425.  
  5426. Options:
  5427.  -f
  5428.    Override the file-modification check.
  5429.  
  5430.  -r
  5431.    Allow recursive removal when a directory name is given.  Without this
  5432.    option attempted removal of directories will fail.
  5433.  
  5434.  --staged
  5435.    Only remove the files from the staging area (the area with changes
  5436.    marked as ready to be recorded in the next commit; see 'eg help topic
  5437.    staging' for more details).  When using this flag, the given files will
  5438.    not be removed from the working copy and will instead become
  5439.    \"unknown\" files.
  5440.  
  5441.  --
  5442.    This option can be used to separate command-line options from the list
  5443.    of files, (useful when filenames might be mistaken for command-line
  5444.    options).
  5445. ";
  5446.   $self->{'differences'} = '
  5447.  eg rm is identical to git rm except that it accepts --staged as a synonym
  5448.  for --cached.
  5449. ';
  5450.   return $self;
  5451. }
  5452.  
  5453. sub preprocess {
  5454.   my $self = shift;
  5455.  
  5456.   return if (scalar(@ARGV) > 0 && $ARGV[0] eq "--");
  5457.   my $result = main::GetOptions("--help" => sub { $self->help() });
  5458.  
  5459.   foreach my $i (0..$#ARGV) {
  5460.     $ARGV[$i] = "--cached" if $ARGV[$i] eq "--staged";
  5461.   }
  5462. }
  5463.  
  5464. ###########################################################################
  5465. # squash                                                                  #
  5466. ###########################################################################
  5467. package squash;
  5468. @squash::ISA = qw(subcommand);
  5469. INIT {
  5470.   $COMMAND{squash} = {
  5471.     new_command => 1,
  5472.     extra => 1,
  5473.     section => 'modification',
  5474.     about => 'Combine all changes since a given revision into a new commit'
  5475.     };
  5476. }
  5477.  
  5478. sub new {
  5479.   my $class = shift;
  5480.   my $self = $class->SUPER::new(git_repo_needed => 1, git_equivalent => '', @_);
  5481.   bless($self, $class);
  5482.   $self->{'help'} = "
  5483. Usage:
  5484.  eg squash [--against REVISION]
  5485.  
  5486. Description:
  5487.  Combines all commits since REVISION into a single commit, and open an
  5488.  editor with the concatenation of log messages for the user to edit to
  5489.  create a new log message.
  5490.  
  5491.  REVISION must be an ancestor of the current commit.  If REVISION is
  5492.  not specified, the remote tracking branch for the current branch is
  5493.  assumed.  (If there is no such branch, eg squash will abort with an
  5494.  error.)
  5495.  
  5496. Examples:
  5497.  Combine all commits in the current branch that aren't in origin/master
  5498.  into a single commit
  5499.      \$ eg squash --against origin/master
  5500.  
  5501. Options:
  5502.  --against
  5503.    An optional command line argument that makes it clearer what is
  5504.    happening.  (In the example above, we are not \"squashing origin/master\",
  5505.    we are squashing all changes since origin/master on top of origin/master.
  5506. ";
  5507.   $self->{'differences'} = '
  5508.  eg squash is a command new to eg that is not part of git.
  5509. ';
  5510.   return $self;
  5511. }
  5512.  
  5513. sub preprocess {
  5514.   my $self = shift;
  5515.  
  5516.   my $since;
  5517.   my $result = main::GetOptions(
  5518.     "--help"    => sub { $self->help() },
  5519.     "against=s" => sub { $since=$_[1] },
  5520.     );
  5521.   $since = shift @ARGV if !defined($since);
  5522.   die "Aborting: Too many revisions specified.\n" if @ARGV > 1;
  5523.   if (!defined($since)) {
  5524.     my $branch = RepoUtil::current_branch();
  5525.     die "Aborting: No revision specified.\n" if !defined($branch);
  5526.     my $merge_remote = RepoUtil::get_config("branch.$branch.remote");
  5527.     my $merge_branch = RepoUtil::get_config("branch.$branch.merge");
  5528.     die "Aborting: No revision specified.\n" if !defined($merge_branch);
  5529.     $merge_branch =~ s#^refs/heads/##;
  5530.     $since = "$merge_remote/$merge_branch";
  5531.   }
  5532.  
  5533.   $self->{since} = $since;
  5534.  
  5535.   Util::push_debug(new_value => 0);
  5536.   my ($retval, $orig_head, $since_sha1sum);
  5537.  
  5538.   # Get the sha1sum where HEAD points now, make sure HEAD is valid
  5539.   ($retval, $orig_head) =
  5540.     ExecUtil::execute_captured("$GIT_CMD rev-parse HEAD", ignore_ret => 1);
  5541.   die "Aborting: You have no commits on HEAD.\n" if $retval != 0;
  5542.   chomp($orig_head);
  5543.   $self->{orig_head} = $orig_head;
  5544.  
  5545.   # Get the sha1sum where $since points now, make sure it is valid
  5546.   ($retval, $since_sha1sum) =
  5547.     ExecUtil::execute_captured("$GIT_CMD rev-parse $self->{since}",
  5548.                                ignore_ret => 1);
  5549.   die "Invalid revision reference: $self->{since}\n" if $retval != 0;
  5550.   chomp($since_sha1sum);
  5551.  
  5552.   # Make sure user has no staged changes
  5553.   my $output = `$GIT_CMD diff --cached --quiet`;
  5554.   die "Aborting: You have staged changes; please commit them first.\n" if $?;
  5555.  
  5556.   # Ensure $self->{since} is an ancestor of HEAD
  5557.   my $command = "$GIT_CMD rev-list HEAD..$self->{since} | wc -l";
  5558.   my ($ret, $unique_to_since) = ExecUtil::execute_captured($command);
  5559.   die "Couldn't parse '$command' output '$unique_to_since'"
  5560.     unless ($unique_to_since =~ /^\s*([0-9]+)$/);
  5561.   my $need_commits = $1;
  5562.   die "Aborting: $self->{since} is not an ancestor of HEAD.\n" if $need_commits;
  5563.   die "Aborting: There are no commits since $self->{since}.\n"
  5564.     if $orig_head eq $since_sha1sum;
  5565.  
  5566.   Util::pop_debug();
  5567. }
  5568.  
  5569. sub run {
  5570.   my $self = shift;
  5571.  
  5572.   # Fill out a basic log message
  5573.   my ($fh, $filename) = main::tempfile();
  5574.   print $fh <<EOF;
  5575. # Please combine the following commit messages into a single commit message.
  5576. # Lines starting with a '#' will be ignored.
  5577.  
  5578. EOF
  5579.   close($fh);
  5580.   my $ret = ExecUtil::execute("$GIT_CMD log --reverse --no-merges --pretty=format:" .
  5581.             "'#commit %H%n#Author: %an <%ae>%n#Date:   %ad%n%n%s%n%n%b' " .
  5582.             " $self->{since}..$self->{orig_head} >> $filename");
  5583.   exit $ret if $ret;
  5584.  
  5585.   # Now, reset and commit
  5586.   $ret = ExecUtil::execute("$GIT_CMD reset --soft $self->{since}");
  5587.   exit $ret if $ret;
  5588.   $ret = ExecUtil::execute("$GIT_CMD commit -F $filename --edit",
  5589.                            ignore_ret => 1);
  5590.  
  5591.   # Restore the branch pointer if the commit failed (e.g. empty log message)
  5592.   ExecUtil::execute("$GIT_CMD reset --soft $self->{orig_head}") if $ret != 0;
  5593.  
  5594.   unlink($filename);
  5595.   return 0;
  5596. }
  5597.  
  5598. ###########################################################################
  5599. # stage                                                                   #
  5600. ###########################################################################
  5601. package stage;
  5602. @stage::ISA = qw(subcommand);
  5603. INIT {
  5604.   $COMMAND{stage} = {
  5605.     new_command => 1,
  5606.     section => 'modification',
  5607.     about => 'Mark content in files as being ready for commit'
  5608.     };
  5609. }
  5610.  
  5611. sub new {
  5612.   my $class = shift;
  5613.   my $self = $class->SUPER::new(git_repo_needed => 1,
  5614.                                 git_equivalent => 'add',
  5615.                                 @_);
  5616.   bless($self, $class);
  5617.   $self->{'help'} = "
  5618. Usage:
  5619.  eg stage [--] PATH...
  5620.  
  5621. Description:
  5622.  Marks the contents of the specified files as being ready to commit,
  5623.  scheduling them for addition to the repository.  (This is also known as
  5624.  staging.)  This step is often not neccessary, since 'eg commit' will fall
  5625.  back to unstaged changes if you have not staged anything.  When a
  5626.  directory is passed, all files in that directory or any subdirectory are
  5627.  recursively added.
  5628.  
  5629.  You can use 'eg unstage PATH...' to unstage files.
  5630.  
  5631.  See 'eg help topic staging' for more details, including situations where
  5632.  you might find staging useful.
  5633.  
  5634. Examples:
  5635.  Create a new file, and mark it for addition to the repository.
  5636.      \$ echo hi > there
  5637.      \$ eg stage there
  5638.  
  5639.  (Advanced) Mark some changes as good, add some verbose sanity checking code,
  5640.  then commit just the good changes.
  5641.      Implement some cool new feature in somefile.C
  5642.      \$ eg stage somefile.C
  5643.      Add some verbose sanity checking code to somefile.C
  5644.      Decide to commit the new feature code but not the sanity checking code:
  5645.      \$ eg commit --staged
  5646.  
  5647.  (Advanced) Show changes in a file, split by those that you have marked as
  5648.  good and those that you haven't:
  5649.      Make various edits
  5650.      \$ eg stage file1 file2
  5651.      Make more edits, include some to file1
  5652.      \$ eg diff            # Look at all the changes
  5653.      \$ eg diff --staged   # Look at the \"ready to be committed\" changes
  5654.      \$ eg diff --unstaged # Look at the changes not ready to be commited
  5655.  
  5656. Options:
  5657.  --
  5658.    This option can be used to separate command-line options from the list
  5659.    of files, (useful when filenames might be mistaken for command-line
  5660.    options).
  5661. ";
  5662.   $self->{'differences'} = '
  5663.  eg stage is a command new to eg that is not part of git (update: it is
  5664.  part of newer versions of git, with identical meaning to eg).  eg stage
  5665.  merely calls git add.
  5666. ';
  5667.   return $self;
  5668. }
  5669.  
  5670. sub run {
  5671.   my $self = shift;
  5672.  
  5673.   @ARGV = Util::quote_args(@ARGV);
  5674.   return ExecUtil::execute("$GIT_CMD add @ARGV", ignore_ret => 1);
  5675. }
  5676.  
  5677. ###########################################################################
  5678. # stash                                                                   #
  5679. ###########################################################################
  5680. package stash;
  5681. @stash::ISA = qw(subcommand);
  5682. INIT {
  5683.   $COMMAND{stash} = {
  5684.     section => 'timesavers',
  5685.     about => 'Save and revert local changes, or apply stashed changes',
  5686.     };
  5687. }
  5688.  
  5689. sub new {
  5690.   my $class = shift;
  5691.   my $self = $class->SUPER::new(
  5692.     git_repo_needed => 1,
  5693.     initial_commit_error_msg => "Error: Cannot stash away changes when there " .
  5694.                                 "is no commit yet.",
  5695.     @_);
  5696.   bless($self, $class);
  5697.   $self->{'help'} = "
  5698. Usage:
  5699.  eg stash list [--details]
  5700.  eg stash [save DESCRIPTION]
  5701.  eg stash apply [DESCRIPTION]
  5702.  eg stash show [OPTIONS] [DESCRIPTION]
  5703.  eg stash (drop [DESCRIPTION] | clear)
  5704.  
  5705. Description:
  5706.  This command can be used to remove any changes since the last commit,
  5707.  stashing these changes away so they can be reapplied later.  It can also
  5708.  be used to apply any previously stashed away changes.  This command can
  5709.  be used multiple times to have multiple sets of changes stashed away.
  5710.  
  5711.  Unknown files (files which you have never run 'eg stage' on) are
  5712.  unaffected; they will not be stashed away or reverted.
  5713.  
  5714.  When no arguments are specified to eg stash, the current changes are
  5715.  saved away with a default description.
  5716.  
  5717.  WARNING: Using the default description can be a bad idea if you will not
  5718.  be reapplying the stash very soon.  The default description provided for
  5719.  you is based on the commit message of the most recent commit, which has
  5720.  confused some users into believing that they have already incorporated
  5721.  changes from a stash and throwing the stash away (something that can be
  5722.  recovered from, but which involves some sleuthing and low-level commands
  5723.  like git-fsck and git-cat-file).
  5724.  
  5725. Examples:
  5726.  You have lots of changes that you're working on, then get an important
  5727.  but simple bug report.  You can stash away your current changes, fix the
  5728.  important bug, and then reapply the stashed changes:
  5729.      \$ eg stash
  5730.      fix, fix, fix, build, test, etc.
  5731.      \$ eg commit
  5732.      \$ eg stash apply
  5733.  
  5734.  You can provide a description of the changes being stashed away, and
  5735.  apply previous stashes by their description (or a unique substring of the
  5736.  description).
  5737.      make lots of changes
  5738.      \$ eg stash save incomplete refactoring work
  5739.      work on something else that you think will be a quick fix
  5740.      \$ eg stash save longer fix than I thought
  5741.      fix some important but one-liner bug
  5742.      \$ eg commit
  5743.      \$ eg stash list
  5744.      \$ eg stash apply incomplete refactoring work
  5745.      finish off the refactoring
  5746.      \$ eg commit
  5747.      \$ eg stash apply fix than I
  5748.      etc., etc.
  5749.  
  5750.  You want to get some details about an existing stash created above:
  5751.      \$ eg stash show incomplete refactoring
  5752.      \$ eg stash show -p incomplete refactoring
  5753.  
  5754. Options:
  5755.  list [--details]
  5756.    Show the saved stash descriptions.  If the --details flag is present,
  5757.    provide more information about each stash.
  5758.  
  5759.  save DESCRIPTION
  5760.    Save current changes with the description DESCRIPTION.  The
  5761.    description cannot start with \"-\".
  5762.  
  5763.  apply [DESCRIPTION]
  5764.    Apply the stashed changes with the specified description.  If no
  5765.    description is specified, and more than one stash has been saved, an
  5766.    error message will be shown.  The description cannot start with \"-\".
  5767.  
  5768.  show [OPTIONS] [DESCRIPTION]
  5769.    Show the stashed changes with the specified description.  If no
  5770.    description is specified, and more than one stash has been saved, an
  5771.    error message will be shown.  The description cannot start with \"-\".
  5772.  
  5773.    Note that the output shown is the output from diff --stat.  If you
  5774.    want the full patch, pass the -p option.  Other options for
  5775.    controlling diff output (such as --name-status or --dirstat, see
  5776.    'git help diff') are also possible options.
  5777.  
  5778.  drop [DESCRIPTION]
  5779.    Delete the specified stash.  The description cannot start with
  5780.    \"-\".
  5781.  
  5782.  clear
  5783.    Delete all stashed changes.
  5784. ";
  5785.   $self->{'differences'} = '
  5786.  eg stash is only cosmetically different than git stash, and is fully
  5787.  backwards compatible.
  5788.  
  5789.  eg stash list, by default, only shows the saved description -- not
  5790.  the reflog syntax or branch the change was made on.
  5791.  
  5792.  eg stash apply and eg stash show also accept any string and will
  5793.  apply or show the stash whose description contains that string.
  5794.  Although stash and apply accept reflog syntax (like their git stash
  5795.  counterparts), i.e. while
  5796.      $ eg stash apply stash@{3}
  5797.  will work, I think it will be easier for the user to run
  5798.      $ eg stash apply rudely interrupted changes
  5799. ';
  5800.   return $self;
  5801. }
  5802.  
  5803. sub preprocess {
  5804.   my $self = shift;
  5805.   my $package_name = ref($self);
  5806.  
  5807.   #
  5808.   # Parse options
  5809.   #
  5810.   my @args;
  5811.   if (scalar(@ARGV) > 0 && $ARGV[0] ne "--") {
  5812.     main::GetOptions("--help" => sub { $self->help() });
  5813.   }
  5814.  
  5815.   # Get the (sub)subcommand
  5816.   if (scalar @ARGV == 0) {
  5817.     $self->{subcommand} = 'save';
  5818.   } elsif ($ARGV[0] =~ /^--/) {
  5819.     $self->{subcommand} = "save";
  5820.   } else {
  5821.     $self->{subcommand} = shift @ARGV;
  5822.     if ($self->{subcommand} eq '-k') {
  5823.       $self->{subcommand} = "save";
  5824.       unshift @ARGV, '-k';
  5825.     }
  5826.     push(@args, $self->{subcommand});
  5827.  
  5828.     # Pass all flags on to git
  5829.     while(@ARGV > 0 && $ARGV[0] =~ /^-/ && $ARGV[0] !~ /^--$/) {
  5830.       if ($self->{subcommand} eq 'list' && $ARGV[0] eq '--refs') {
  5831.         $self->{show_refs} = 1;
  5832.         shift @ARGV;
  5833.       } elsif ($self->{subcommand} eq 'list' && $ARGV[0] eq '--details') {
  5834.         $self->{show_details} = 1;
  5835.         shift @ARGV;
  5836.       } else {
  5837.         push(@args, shift @ARGV);
  5838.       }
  5839.     }
  5840.     if ($self->{subcommand} eq 'branch') {
  5841.       push(@args, shift @ARGV);  # Pull off the branch name
  5842.     }
  5843.   }
  5844.  
  5845.   # Show a help message if they picked a bad stash subaction.
  5846.   my @valid_commands = qw(list show apply clear save drop pop branch create);
  5847.   if (! grep {$_ eq $self->{subcommand}} @valid_commands) {
  5848.     print STDERR<<EOF;
  5849. Aborting; invalid stash subcommand: $self->{subcommand}
  5850. EOF
  5851.     exit 1;
  5852.   }
  5853.  
  5854.   # Translate the description passed to apply or show into a reflog reference
  5855.   my @commands_accepting_existing_stash = qw(show drop pop apply branch);
  5856.   if ((grep {$_ eq $self->{subcommand}} @commands_accepting_existing_stash) &&
  5857.       scalar @ARGV > 0) {
  5858.     my $stash_description = "@ARGV";
  5859.     my $single_word_desc = (scalar(@ARGV) == 1);
  5860.     @ARGV = ();
  5861.     if ($stash_description =~ m#^stash\@{[^{]+}$# ||
  5862.         ($single_word_desc && RepoUtil::valid_ref($stash_description))) {
  5863.       push(@args, $stash_description)
  5864.     } else {
  5865.       # Will need to compare arguments to existing stash descriptions...
  5866.       print "  >>Getting stash descriptions to compare to arguments:\n"
  5867.         if $DEBUG;
  5868.       my ($retval, $output) =
  5869.         ExecUtil::execute_captured("$EG_EXEC stash list --refs");
  5870.       my @lines = split('\n', $output);
  5871.       my %refs;
  5872.       my %bad_refs;
  5873.       while (@lines) {
  5874.         my $desc = shift @lines;
  5875.         my $ref = shift @lines;
  5876.         $bad_refs{$desc}++ if defined $refs{$desc};
  5877.         $refs{$desc} = $ref;
  5878.       }
  5879.  
  5880.       # See if the stash description matches zero, one, or more existing
  5881.       # stash descriptions; convert it to a reflog entry if only one
  5882.       my @matches = grep {$_ =~ m#\Q$stash_description\E#} (keys %refs);
  5883.       if (scalar @matches == 0) {
  5884.         die "No stash matching '$stash_description' exists!  Aborting.\n";
  5885.       } elsif (scalar @matches == 1) {
  5886.         # Only one regex match; use it
  5887.         $stash_description = $matches[0];
  5888.       } else {
  5889.         # See if our string matches one stash description exactly; if so,
  5890.         # we can use it.
  5891.         if (!grep {$_ eq $stash_description} (keys %refs)) {
  5892.           die "Stash description '$stash_description' matches multiple " .
  5893.               "stashes:\n  " . join("\n  ", @matches) . "\n" .
  5894.               "Aborting.\n";
  5895.         }
  5896.       }
  5897.       die "Stash description '$stash_description' matches multiple stashes.\n"
  5898.         if $bad_refs{$stash_description};
  5899.  
  5900.       push(@args, $refs{$stash_description});
  5901.     }
  5902.   }
  5903.  
  5904.   # Add any unprocessed args to the arguments to use
  5905.   push(@args, @ARGV);
  5906.  
  5907.   # Reset @ARGV with the built up list of arguments
  5908.   @ARGV = @args;
  5909. }
  5910.  
  5911. sub run {
  5912.   my $self = shift;
  5913.   my $package_name = ref($self);
  5914.   my $ret;
  5915.  
  5916.   @ARGV = Util::quote_args(@ARGV);
  5917.   if ($self->{subcommand} eq 'list') {
  5918.     my $output = "";
  5919.     open($OUTFH, '>', \$output) ||
  5920.       die "eg $package_name: cannot open \$OUTFH: $!";
  5921.  
  5922.     $ret = ExecUtil::execute("$GIT_CMD $package_name @ARGV", ignore_ret => 1);
  5923.  
  5924.     my @lines = split('\n', $output);
  5925.     my $regex =
  5926.       qr#(stash\@{[^}]+}): (?:WIP )?[Oo]n [^:]*: (?:[0-9a-f]+\.\.\. )?#;
  5927.     foreach my $line (@lines) {
  5928.       if ($self->{show_details}) {
  5929.         print "$line\n";
  5930.       } else {
  5931.         $line =~ s/$regex//;
  5932.         print "$line\n";
  5933.         print "$1\n" if $self->{show_refs};
  5934.       }
  5935.     }
  5936.   } else {
  5937.     $ret = ExecUtil::execute("$GIT_CMD $package_name @ARGV", ignore_ret => 1);
  5938.   }
  5939.   return $ret;
  5940. }
  5941.  
  5942. ###########################################################################
  5943. # status                                                                  #
  5944. ###########################################################################
  5945. package status;
  5946. @status::ISA = qw(subcommand);
  5947. INIT {
  5948.   $COMMAND{status} = {
  5949.     section => 'discovery',
  5950.     about => 'Summarize current changes'
  5951.     };
  5952.   $ALIAS{'st'} = "status";
  5953. }
  5954.  
  5955. sub new {
  5956.   my $class = shift;
  5957.   my $self = $class->SUPER::new(git_repo_needed => 1, @_);
  5958.   bless($self, $class);
  5959.   $self->{'help'} = "
  5960. Usage:
  5961.  eg status
  5962.  
  5963. Description:
  5964.  Show the current state of the project.  In addition to showing the
  5965.  currently active branch, whether you have unpushed local commits,
  5966.  whether you have stashed any sets of changes away (see 'eg help
  5967.  stash'), this command will list files with content in any of the
  5968.  following states:
  5969.  
  5970.     Unknown files
  5971.       Files that are not explicitly ignored (i.e. do not appear in an
  5972.       ignore list such as a .gitignore file) but whose contents are still
  5973.       not tracked by git.
  5974.  
  5975.       These files can become known by running 'eg stage FILENAME', or
  5976.       ignored by having their name added to a .gitignore file.
  5977.  
  5978.     Newly created unknown files
  5979.       Same as unknown files; the reason for splitting unknown files into
  5980.       two sets is to make it easier to find the files users are more
  5981.       likely to want to add.  Also, 'eg commit' will by default error out
  5982.       with a warning message if there are any newly created unknown files
  5983.       in order to prevent forgetting to add files that should be included
  5984.       in a commit.
  5985.  
  5986.     Modified submodules:
  5987.       subdirectories that are tracked under their own git repository, and
  5988.       that are being tracked via use of the 'git submodule' command.
  5989.  
  5990.     Changes not staged for commit (\"unstaged\")
  5991.       Files whose contents have been modified in the working copy.
  5992.  
  5993.       (Advanced usage note) If you explicitly mark all the changes in a
  5994.       file as ready to be committed, then the file will not appear in this
  5995.       list and will instead appear in the \"staged\" list (see below).
  5996.       However, a file can appear in both the unstaged and staged lists if
  5997.       only part of the changes in the file are marked as ready for commit.
  5998.  
  5999.     Unmerged paths (files with conflicts)
  6000.       Files which could not be automatically merged.  If such files are
  6001.       text files, they will have the typical conflict markers.  These
  6002.       files need to be manually edited to give them the correct contents,
  6003.       and then the user should inform git that the conflicts are resolved
  6004.       by running 'eg resolved FILENAME'.
  6005.  
  6006.     Changes ready to be committed (\"staged\")
  6007.       Files with content changes that have explicitly been marked as ready
  6008.       to be committed.  This state only typically appears in advanced
  6009.       usage.
  6010.  
  6011.       Files enter this state through the use of 'eg stage'.  Files can
  6012.       return to the unstaged state by running 'eg unstage' See 'eg help
  6013.       topic staging' to learn about the staging area.
  6014.  
  6015. ";
  6016.   $self->{'differences'} = "
  6017.  eg status output is essentially just a streamlined and cleaned version of
  6018.  git status output, with the addition of a new section (newly created
  6019.  untracked files) and an extra status message being displayed when in the
  6020.  middle of a special state (am, bisect, merge, or rebase).
  6021.  
  6022.  The streamlining serves to avoid information overload to new users (which
  6023.  is only possible with a less error prone \"commit\" command) and the
  6024.  cleaning (removal of leading hash marks) serves to make the system more
  6025.  inviting to new users.
  6026.  
  6027.  A slight wording change was done to transform \"untracked\" to \"unknown\"
  6028.  since, as Havoc pointed out, the word \"tracked\" may not be very self
  6029.  explanatory (in addition to the real meaning, users might think of:
  6030.  \"tracked in the index?\", \"related to remote tracking branches?\", \"some
  6031.  fancy new monitoring scheme unique to git that other vcses do not have?\",
  6032.  \"is there some other meaning?\").  I do not know if \"known\" will fully
  6033.  solve this, but I suspect it will be more self-explanatory than
  6034.  \"tracked\".
  6035.  
  6036.  There are also slight changes to the section names to reinforce
  6037.  consistent naming when referring to the same concept (staging, in this
  6038.  case), but the changes are very slight.
  6039.  
  6040.  The extra status message when in the middle of an am, bisect, merge,
  6041.  or rebase serves two purposes: to remind users that they are in the
  6042.  middle of some operation (some people don't use the special prompt
  6043.  from git's bash-completion support), and to provide a command users
  6044.  can run to get help resolving such situations.  (Many users were
  6045.  confused about or unaware how to resolve incomplete merges and
  6046.  rebases; providing them with a specially written help page they
  6047.  could access seemed to effectively assist them figure out the
  6048.  appropriate steps to take -- especially in tricky or special cases.)
  6049. ";
  6050.   return $self;
  6051. }
  6052.  
  6053. sub preprocess {
  6054.   my $self = shift;
  6055.  
  6056.   my @old_argv = @ARGV;
  6057.   my $no_filter = 0;
  6058.   Getopt::Long::Configure("permute");
  6059.   my $result = main::GetOptions(
  6060.     "help|h"    => sub { $self->help() },
  6061.     "short|s"   => sub { $no_filter = 1 },
  6062.     "suno|sunormal|suall" => sub { $no_filter = 1 },  # git status parser allows combining -s and -u options, somewhat weirdly
  6063.     "porcelain" => sub { $no_filter = 1 },
  6064.     "z"         => sub { $no_filter = 1 },
  6065.     );
  6066.   @ARGV = @old_argv;
  6067.   $self->{no_filter} = $no_filter;
  6068. }
  6069.  
  6070. sub run {
  6071.   my $self = shift;
  6072.  
  6073.   -t STDOUT and $ENV{"GIT_PAGER_IN_USE"}=1;
  6074.   return $self->SUPER::run() if $self->{no_filter};
  6075.  
  6076.   $self->{special_state} = RepoUtil::get_special_state($self->{git_dir});
  6077.  
  6078.   @ARGV = Util::quote_args(@ARGV);
  6079.   return ExecUtil::execute("$GIT_CMD status @ARGV", ignore_ret => 1);
  6080. }
  6081.  
  6082. sub postprocess {
  6083.   my $self = shift;
  6084.   my $output = shift;
  6085.  
  6086.   # If we can't parse the git status output, what we tell the user...
  6087.   my $workaround_msg =
  6088.     "You'll need to use an older git or a newer eg or 'git status'.";
  6089.  
  6090.   if ($DEBUG == 2) {
  6091.     print "    >>(No commands to run, just data to print)<<\n";
  6092.     return;
  6093.   }
  6094.  
  6095.   if ($self->{no_filter}) {
  6096.     print $output;
  6097.     return;
  6098.   }
  6099.  
  6100.   my $branch;
  6101.   my $initial_commit = 0;
  6102.   my @sections;
  6103.   my %files;
  6104.   my %section_mapping = (
  6105.        'Untracked files:' => 'Unknown files:',
  6106.        'Changes to be committed:' => 'Changes ready to be committed ("staged"):',
  6107.        'Changed but not updated:' => 'Changes not staged for commit ("unstaged"):',
  6108.        'Changes not staged for commit:' => 'Changes not staged for commit ("unstaged"):',
  6109.        'Unmerged paths:' => 'Unmerged paths (files with conflicts):'
  6110.        );
  6111.  
  6112.   my @basic_info;
  6113.   my @diff_info;
  6114.  
  6115.   # Exit early if git status had an error
  6116.   if ($output =~ m/^fatal:/) {
  6117.     print STDERR $output;
  6118.     exit 128;
  6119.   }
  6120.  
  6121.   my $status_hints = RepoUtil::get_config("advice.statusHints");
  6122.   $status_hints = (!defined($status_hints) || $status_hints eq "true");
  6123.  
  6124.   # Parse the output
  6125.   my @lines = split('\n', $output);
  6126.   my $cur_state = -1;
  6127.   while (@lines) {
  6128.     my $line = shift @lines;
  6129.     my $section = undef;
  6130.     my $title;
  6131.  
  6132.     if ($line =~ m/^# On branch (.*)$/) {
  6133.       $branch = $1;
  6134.     } elsif ($line =~ m/^# Initial commit$/) {
  6135.       $initial_commit = 1;
  6136.     } elsif ($line =~ m/^# ([A-Z].*:)$/) {
  6137.       $cur_state = 1;
  6138.       $title = $section_mapping{$1} || $1;
  6139.       $section = $title;
  6140.     } elsif ($cur_state < 0) {
  6141.       next if $line !~ m/^# (.+)/;
  6142.       push(@basic_info, $1);
  6143.     } elsif ($line =~ m/^no changes added to commit/ ||
  6144.              $line =~ m/^# Untracked files not listed/) {
  6145.       next;  # Skip this line
  6146.     } elsif ($line =~ m#^(?:\e\[.*?m)?diff --git a/#) {
  6147.       push(@diff_info, $line);
  6148.       push(@diff_info, @lines);
  6149.       last;
  6150.     } else {
  6151.       die "ERROR: Cannot parse git status output.\n" .
  6152.           "$workaround_msg\n" .
  6153.           "Remaining unparsed lines:\n$line\n" . join("\n", @lines) . "\n";
  6154.     }
  6155.  
  6156.     # If we're inside a section type, parse it
  6157.     if ($cur_state > 0) {
  6158.       push (@sections, $section);
  6159.       my @section_files;
  6160.       my $hints;
  6161.  
  6162.       # Parse the hints first
  6163.       $line = shift @lines;
  6164.       if ($status_hints) {
  6165.         while ($line =~ m/^#\s+\((?:use "|commit).*/) {
  6166.           $hints .= $line;
  6167.           $line = shift @lines;
  6168.         }
  6169.         die("Bug parsing git status output.\n$workaround_msg\n") if $line ne '#';
  6170.         $line = shift @lines; # Get rid of blank line
  6171.       }
  6172.  
  6173.       while (defined $line && $line =~ m/^(?:\e\[.*?m)?#.+$/) {
  6174.         if ($line =~ m/^(?:\e\[.*?m)?#(\s+)(.*)/) {
  6175.           my $space = $1;
  6176.           my $file = $2;
  6177.  
  6178.           # Remove leading space character for submodule changes
  6179.           # (There's no real reason to do this other than laziness in
  6180.           # updating test file results; output looks fine either way.)
  6181.           $space =~ s/^[ ]//;
  6182.           # Workaround the file not have proper terminating color escape sequence
  6183.           if ($file =~ /^\s*\e\[.*?m/ && $file !~ /\e\[m$/) {
  6184.             $file .= "\e[m";
  6185.           }
  6186.           push @section_files, "$space$file";
  6187.         }
  6188.         $line = shift @lines;
  6189.         unshift(@lines, $line) if $line && $line =~ m#^(?:\e\[.*?m)?diff --git a/#;
  6190.       }
  6191.  
  6192.       if (defined($files{$section})) {
  6193.         push(@{$files{$section}{'file_list'}}, @section_files);
  6194.       } else {
  6195.         $files{$section} = { title     => $title, # may be undef
  6196.                              hint      => $hints,
  6197.                              file_list => \@section_files };
  6198.       }
  6199.  
  6200.       # Record that we finished parsing this section
  6201.       $cur_state = 0;
  6202.     }
  6203.   }
  6204.  
  6205.   # Split the unknown files into those that are newly created and those that
  6206.   # have been around
  6207.   if (defined($files{'Unknown files:'})) {
  6208.     # Get the list of unknown files that have been around for a while
  6209.     my ($cur_dir, $top_dir, $git_dir) = RepoUtil::get_dirs();
  6210.     my %old_unknown;
  6211.     if (-f "$git_dir/info/ignored-unknown") {
  6212.       my @old_unknown_files = `cat "$git_dir/info/ignored-unknown"`;
  6213.       chomp(@old_unknown_files);
  6214.       @old_unknown_files =
  6215.         Util::reroot_paths__from_to_files($top_dir, $cur_dir, @old_unknown_files);
  6216.       map { $old_unknown{$_} = 1 } @old_unknown_files;
  6217.     }
  6218.  
  6219.     my @new_unknowns;
  6220.     my @old_unknowns;
  6221.     foreach my $fileline (@{$files{'Unknown files:'}{'file_list'}}) {
  6222.       $fileline =~ m#(\s+(?:\e\[.*?m)?)(.*?)((?:\e\[m)?)$# ||
  6223.         die "Failed parsing git status output: '$fileline'\n$workaround_msg\n";
  6224.       if ($old_unknown{$2}) {
  6225.         push(@old_unknowns, $fileline);
  6226.       } else {
  6227.         push(@new_unknowns, $fileline);
  6228.       }
  6229.     }
  6230.  
  6231.     my ($index) = grep $sections[$_] eq "Unknown files:", 0 .. $#sections;
  6232.     splice(@sections, $index, 1);
  6233.     if (@new_unknowns) {
  6234.       $files{'new_unknowns'} = { title     => 'Newly created unknown files:',
  6235.                                  file_list => \@new_unknowns };
  6236.       splice(@sections, $index++, 0, 'new_unknowns');
  6237.     }
  6238.     if (@old_unknowns) {
  6239.       $files{'old_unknowns'} = { title     => 'Unknown files:',
  6240.                                  file_list => \@old_unknowns };
  6241.       splice(@sections, $index, 0, 'old_unknowns');
  6242.     }
  6243.   }
  6244.  
  6245.   # Print out the branch we are on
  6246.   if (defined $branch) {
  6247.     print "(On branch $branch";
  6248.     print ", no commits yet" if $initial_commit;
  6249.     print ")\n";
  6250.   }
  6251.   foreach my $line (@basic_info) {
  6252.     print "($line)\n";
  6253.   }
  6254.   my ($retval, $num_stashes) =
  6255.       ExecUtil::execute_captured("$GIT_CMD stash list | wc -l");
  6256.   chomp($num_stashes);
  6257.   if ($num_stashes > 0) {
  6258.     print "(You have $num_stashes stash(es).  Use 'eg stash list' to see them.)\n";
  6259.   }
  6260.  
  6261.   # Print out info about any special state we're in
  6262.   my $notice = "";
  6263.   if (defined $self->{special_state}) {
  6264.     my ($highlight, $reset) = ("", "");
  6265.     if (-t STDOUT) {
  6266.       $highlight=`$GIT_CMD config --get-color color.status.header "red reverse"`;
  6267.       $reset=`$GIT_CMD config --get-color "" "reset"`;
  6268.     }
  6269.  
  6270.     $notice .= "($highlight";
  6271.     $notice .= "YOU ARE IN THE MIDDLE OF A $self->{special_state}; ";
  6272.     $notice .= "RUN 'eg help topic middle-of-";
  6273.     if ($self->{special_state} eq "APPLY MAIL OR REBASE") {
  6274.       # FIXME: How do we get into this state anyway, and what should they run?
  6275.       # Well, printing nothing will just get them the general topic page, then
  6276.       # they can pick between am and rebase
  6277.     } elsif ($self->{special_state} =~ /REBASE$/) {
  6278.       $notice .= "rebase";
  6279.     } elsif ($self->{special_state} eq "APPLY MAIL") {
  6280.       $notice .= "am";
  6281.     } elsif ($self->{special_state} eq "MERGE") {
  6282.       $notice .= "merge";
  6283.     } elsif ($self->{special_state} eq "BISECT") {
  6284.       $notice .= "bisect";
  6285.     }
  6286.     $notice .= "' FOR MORE INFO.";
  6287.     $notice .= "$reset)\n";
  6288.     print $notice;
  6289.   }
  6290.  
  6291.   # Print out all the various changes
  6292.   my $linecount = 0;
  6293.   foreach my $section (@sections) {
  6294.     if (defined($files{$section})) {
  6295.       print "$files{$section}{'title'}\n";
  6296.       $linecount += 1;
  6297.       foreach my $fileline (@{$files{$section}{'file_list'}}) {
  6298.         print "$fileline\n";
  6299.         $linecount += 1;
  6300.       }
  6301.     }
  6302.   }
  6303.  
  6304.   # Repeat the notice so users will see it
  6305.   if (defined $self