]> git.madduck.net Git - code/myrepos.git/blob - mr

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

prep
[code/myrepos.git] / mr
1 #!/usr/bin/env perl
2
3 =head1 NAME
4
5 mr - a tool to manage all your version control repos
6
7 =head1 SYNOPSIS
8
9 B<mr> [options] checkout
10
11 B<mr> [options] update
12
13 B<mr> [options] status
14
15 B<mr> [options] commit [-m "message"]
16
17 B<mr> [options] record [-m "message"]
18
19 B<mr> [options] fetch
20
21 B<mr> [options] push
22
23 B<mr> [options] diff
24
25 B<mr> [options] log
26
27 B<mr> [options] grep pattern
28
29 B<mr> [options] run command [param ...]
30
31 B<mr> [options] bootstrap src [directory]
32
33 B<mr> [options] register [repository]
34
35 B<mr> [options] config section ["parameter=[value]" ...]
36
37 B<mr> [options] action [params ...]
38
39 B<mr> [options] [online|offline]
40
41 B<mr> [options] remember action [params ...]
42
43 =head1 DESCRIPTION
44
45 B<mr> is a tool to manage all your version control repos. It can checkout,
46 update, or perform other actions on a set of repositories as if they were
47 one combined repository. It supports any combination of subversion, git,
48 cvs, mercurial, bzr, darcs, fossil and veracity repositories, and support
49 for other version control systems can easily be added.
50
51 B<mr> cds into and operates on all registered repositories at or below your
52 working directory. Or, if you are in a subdirectory of a repository that
53 contains no other registered repositories, it will stay in that directory,
54 and work on only that repository,
55
56 B<mr> is configured by .mrconfig files, which list the repositories. It
57 starts by reading the .mrconfig file in your home directory, and this can
58 in turn chain load .mrconfig files from repositories. It also automatically
59 looks for a .mrconfig file in the current directory, or in one of its
60 parent directories.
61
62 These predefined commands should be fairly familiar to users of any version
63 control system:
64
65 =over 4
66
67 =item checkout (or co)
68
69 Checks out any repositories that are not already checked out.
70
71 =item update
72
73 Updates each repository from its configured remote repository.
74
75 If a repository isn't checked out yet, it will first check it out.
76
77 =item status
78
79 Displays a status report for each repository, showing what
80 uncommitted changes are present in the repository. For distributed version
81 control systems, also shows unpushed local branches.
82
83 =item commit (or ci)
84
85 Commits changes to each repository. (By default, changes are pushed to the
86 remote repository too, when using distributed systems like git. If you
87 don't like this default, you can change it in your .mrconfig, or use record
88 instead.)
89
90 The optional -m parameter allows specifying a commit message.
91
92 =item record
93
94 Records changes to the local repository, but does not push them to the
95 remote repository. Only supported for distributed version control systems.
96
97 The optional -m parameter allows specifying a commit message.
98
99 =item fetch
100
101 Fetches from each repository's remote repository, but does not
102 update the working copy. Only supported for some distributed version
103 control systems.
104
105 =item push
106
107 Pushes committed local changes to the remote repository. A no-op for
108 centralized version control systems.
109
110 =item diff
111
112 Show a diff of uncommitted changes.
113
114 =item log
115
116 Show the commit log.
117
118 =item grep pattern
119
120 Searches for a pattern in each repository using the grep subcommand. Uses
121 ack-grep on VCS that do not have their own.
122
123 =item run command [param ...]
124
125 Runs the specified command in each repository.
126
127 =back
128
129 These commands are also available:
130
131 =over 4
132
133 =item bootstrap src [directory]
134
135 Causes mr to retrieve the source C<src> and use it as a .mrconfig file to
136 checkout the repositories listed in it, into the specified directory.
137
138 B<mr> understands several types of sources:
139
140 =over 4
141
142 =item URL for curl
143
144 C<src> may be an URL understood by B<curl>.
145
146 =item copy via ssh
147
148 To use B<scp> to download, the C<src> may have the form
149 C<ssh://[user@]host:file>.
150
151 =item local file
152
153 You can retrieve the config file by other means and pass its B<path> as C<src>.
154
155 =item standard input
156
157 If source C<src> consists in a single dash C<->, config file is read from
158 standard input.
159
160 =back
161
162 The directory will be created if it does not exist. If no directory is
163 specified, the current directory will be used.
164
165 As a special case, if source C<src> includes a repository named ".", that
166 is checked out into the top of the specified directory.
167
168 =item list (or ls)
169
170 List the repositories that mr will act on.
171
172 =item register
173
174 Register an existing repository in a mrconfig file. By default, the
175 repository in the current directory is registered, or you can specify a
176 directory to register.
177
178 The mrconfig file that is modified is chosen by either the -c option, or by
179 looking for the closest known one at or in a parent of the current directory.
180
181 =item config
182
183 Adds, modifies, removes, or prints a value from a mrconfig file. The next
184 parameter is the name of the section the value is in. To add or modify
185 values, use one or more instances of "parameter=value". Use "parameter=" to
186 remove a parameter. Use just "parameter" to get the value of a parameter.
187
188 For example, to add (or edit) a repository in src/foo:
189
190   mr config src/foo checkout="svn co svn://example.com/foo/trunk foo"
191
192 To show the command that mr uses to update the repository in src/foo:
193
194   mr config src/foo update
195
196 To see the built-in library of shell functions contained in mr:
197
198   mr config DEFAULT lib
199
200 The mrconfig file that is used is chosen by either the -c option, or by
201 looking for the closest known one at or in a parent of the current directory.
202
203 =item offline
204
205 Advises mr that it is in offline mode. Any commands that fail in
206 offline mode will be remembered, and retried when mr is told it's online.
207
208 =item online
209
210 Advices mr that it is in online mode again. Commands that failed while in
211 offline mode will be re-run.
212
213 =item remember
214
215 Remember a command, to be run later when mr re-enters online mode. This
216 implicitly puts mr into offline mode. The command can be any regular mr
217 command. This is useful when you know that a command will fail due to being
218 offline, and so don't want to run it right now at all, but just remember
219 to run it when you go back online.
220
221 =item help
222
223 Displays this help.
224
225 =back
226
227 Actions can be abbreviated to any unambiguous substring, so
228 "mr st" is equivalent to "mr status", and "mr up" is equivalent to "mr
229 update"
230
231 Additional parameters can be passed to most commands, and are passed on
232 unchanged to the underlying version control system. This is mostly useful
233 if the repositories mr will act on all use the same version control
234 system.
235
236 =head1 OPTIONS
237
238 =over 4
239
240 =item -d directory
241
242 =item --directory directory
243
244 Specifies the topmost directory that B<mr> should work in. The default is
245 the current working directory.
246
247 =item -c mrconfig
248
249 =item --config mrconfig
250
251 Use the specified mrconfig file. The default is to use both F<~/.mrconfig>
252 as well as look for a F<.mrconfig> file in the current directory, or in one
253 of its parent directories.
254
255 =item -f
256
257 =item --force
258
259 Force mr to act on repositories that would normally be skipped due to their
260 configuration.
261
262 =item -v
263
264 =item --verbose
265
266 Be verbose.
267
268 =item -q
269
270 =item --quiet
271
272 Be quiet. This suppresses mr's usual output, as well as any output from
273 commands that are run (including stderr output). If a command fails,
274 the output will be shown.
275
276 =item -k
277
278 =item --insecure
279
280 Accept untrusted SSL certificates when bootstrapping.
281
282 =item -s
283
284 =item --stats
285
286 Expand the statistics line displayed at the end to include information
287 about exactly which repositories failed and were skipped, if any.
288
289 =item -i
290
291 =item --interactive
292
293 Interactive mode. If a repository fails to be processed, a subshell will be
294 started which you can use to resolve or investigate the problem. Exit the
295 subshell to continue the mr run.
296
297 =item -n [number]
298
299 =item --no-recurse [number]
300
301 If no number if specified, just operate on the repository for the current
302 directory, do not recurse into deeper repositories.
303
304 If a number is specified, will recurse into repositories at most that many
305 subdirectories deep. For example, with -n 2 it would recurse into ./src/foo,
306 but not ./src/packages/bar.
307
308 =item -j [number]
309
310 =item --jobs [number]
311
312 Run the specified number of jobs in parallel, or an unlimited number of jobs
313 with no number specified. This can greatly speed up operations such as updates.
314 It is not recommended for interactive operations.
315
316 Note that running more than 10 jobs at a time is likely to run afoul of
317 ssh connection limits. Running between 3 and 5 jobs at a time will yield
318 a good speedup in updates without loading the machine too much.
319
320 =item -t
321
322 =item --trust-all
323
324 Trust all mrconfig files even if they are not listed in F<~/.mrtrust>.
325 Use with caution.
326
327 =item -p
328
329 =item --path
330
331 This obsolete flag is ignored.
332
333 =back
334
335 =head1 MRCONFIG FILES
336
337 Here is an example F<.mrconfig> file:
338
339   [src]
340   checkout = svn checkout svn://svn.example.com/src/trunk src
341   chain = true
342
343   [src/linux-2.6]
344   checkout = git clone git://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux-2.6.git &&
345         cd linux-2.6 &&
346         git checkout -b mybranch origin/master
347
348 The F<.mrconfig> file uses a variant of the INI file format. Lines
349 starting with "#" are comments. Values can be continued to the
350 following line by indenting the line with whitespace.
351
352 The C<DEFAULT> section allows setting default values for the sections that
353 come after it.
354
355 The C<ALIAS> section allows adding aliases for actions. Each parameter
356 is an alias, and its value is the action to use.
357
358 All other sections add repositories. The section header specifies the
359 directory where the repository is located. This is relative to the directory
360 that contains the mrconfig file, but you can also choose to use absolute
361 paths. (Note that you can use environment variables in section names; they
362 will be passed through the shell for expansion. For example, 
363 C<[$HOSTNAME]>, or C<[${HOSTNAME}foo]>).
364
365 Within a section, each parameter defines a shell command to run to handle a
366 given action. mr contains default handlers for "update", "status",
367 "commit", and other standard actions.
368
369 Normally you only need to specify what to do for "checkout". Here you
370 specify the command to run in order to create a checkout of the repository.
371 The command will be run in the parent directory, and must create the
372 repository's directory. So use C<git clone>, C<svn checkout>, C<bzr branch>
373 or C<bzr checkout> (for a bound branch), etc.
374
375 Note that these shell commands are run in a C<set -e> shell
376 environment, where any additional parameters you pass are available in
377 C<$@>. All commands other than "checkout" are run inside the repository,
378 though not necessarily at the top of it.
379
380 The C<MR_REPO> environment variable is set to the path to the top of the
381 repository. (For the "register" action, "MR_REPO" is instead set to the 
382 basename of the directory that should be created when checking the
383 repository out.)
384
385 The C<MR_CONFIG> environment variable is set to the .mrconfig file
386 that defines the repo being acted on, or, if the repo is not yet in a config
387 file, the F<.mrconfig> file that should be modified to register the repo.
388
389 The C<MR_ACTION> environment variable is set to the command being run
390 (update, checkout, etc).
391
392 A few parameters have special meanings:
393
394 =over 4
395
396 =item skip
397
398 If the "skip" parameter is set and its command returns true, then B<mr>
399 will skip acting on that repository. The command is passed the action
400 name in C<$1>.
401
402 Here are two examples. The first skips the repo unless
403 mr is run by joey. The second uses the hours_since function
404 (included in mr's built-in library) to skip updating the repo unless it's
405 been at least 12 hours since the last update.
406
407   [mystuff]
408   checkout = ...
409   skip = test `whoami` != joey
410
411   [linux]
412   checkout = ...
413   skip = [ "$1" = update ] && ! hours_since "$1" 12
414  
415 Another way to use skip is for a lazy checkout. This makes mr skip
416 operating on a repo unless it already exists. To enable the 
417 repo, you have to explicitly check it out (using "mr --force -d foo checkout").
418
419   [foo]
420   checkout = ...
421   skip = lazy
422
423 =item order
424
425 The "order" parameter can be used to override the default ordering of
426 repositories. The default order value is 10. Use smaller values to make
427 repositories be processed earlier, and larger values to make repositories
428 be processed later.
429
430 Note that if a repository is located in a subdirectory of another
431 repository, ordering it to be processed earlier is not recommended.
432
433 =item chain
434
435 If the "chain" parameter is set and its command returns true, then B<mr>
436 will try to load a F<.mrconfig> file from the root of the repository.
437
438 =item include
439
440 If the "include" parameter is set, its command is ran, and should output
441 additional mrconfig file content. The content is included as if it were
442 part of the including file.
443
444 Unlike all other parameters, this parameter does not need to be placed
445 within a section.
446
447 B<mr> ships several libraries that can be included to add support for
448 additional version control type things (unison, git-svn, git-fake-bare,
449 git-subtree). To include them all, you could use:
450
451   include = cat /usr/share/mr/*
452
453 See the individual files for details.
454
455 =item deleted
456
457 If the "deleted" parameter is set and its command returns true, then
458 B<mr> will treat the repository as deleted. It won't ever actually delete
459 the repository, but it will warn if it sees the repository's directory.
460 This is useful when one mrconfig file is shared among multiple machines,
461 to keep track of and remember to delete old repositories.
462
463 =item lib
464
465 The "lib" parameter can specify some shell code that will be run
466 before each command, this can be a useful way to define shell
467 functions for other commands to use. 
468
469 Unlike most other parameters, this can be specified multiple times, in
470 which case the chunks of shell code are accumulatively concatenated
471 together.
472
473 =item fixups
474
475 If the "fixups" parameter is set, its command is run whenever a repository
476 is checked out, or updated. This provides an easy way to do things
477 like permissions fixups, or other tweaks to the repository content,
478 whenever the repository is changed.
479
480 =item VCS_action
481
482 When looking for a command to run for a given action, mr first looks for
483 a parameter with the same name as the action. If that is not found, it
484 looks for a parameter named "VCS_action" (substituting in the name of the
485 version control system and the action).
486
487 Internally, mr has settings for "git_update", "svn_update", etc. To change
488 the action that is performed for a given version control system, you can
489 override these VCS specific actions. To add a new version control system,
490 you can just add VCS specific actions for it.
491
492 =item pre_ and post_
493
494 If a "pre_action" parameter is set, its command is run before mr performs the
495 specified action. Similarly, "post_action" parameters are run after mr
496 successfully performs the specified action. For example, "pre_commit" is
497 run before committing; "post_update" is run after updating.
498
499 =item _append
500
501 Any parameter can be suffixed with C<_append>, to add an additional value
502 to the existing value of the parameter. In this way, actions 
503 can be constructed accumulatively.
504
505 =item VCS_test
506
507 The name of the version control system is itself determined by
508 running each defined "VCS_test" action, until one succeeds.
509
510 =back
511
512 =head1 UNTRUSTED MRCONFIG FILES
513
514 Since mrconfig files can contain arbitrary shell commands, they can do
515 anything. This flexibility is good, but it also allows a malicious mrconfig
516 file to delete your whole home directory. Such a file might be contained
517 inside a repository that your main F<~/.mrconfig> checks out. To
518 avoid worries about evil commands in a mrconfig file, mr defaults to
519 reading all mrconfig files other than the main F<~/.mrconfig> in untrusted
520 mode. In untrusted mode, mrconfig files are limited to running only known
521 safe commands (like "git clone") in a carefully checked manner.
522
523 To configure mr to trust other mrconfig files, list them in F<~/.mrtrust>.
524 One mrconfig file should be listed per line. Either the full pathname
525 should be listed, or the pathname can start with F<~/> to specify a file
526 relative to your home directory.
527
528 =head1 OFFLINE LOG FILE
529
530 The F<~/.mrlog> file contains commands that mr has remembered to run later,
531 due to being offline. You can delete or edit this file to remove commands,
532 or even to add other commands for 'mr online' to run. If the file is
533 present, mr assumes it is in offline mode.
534
535 =head1 EXTENSIONS
536
537 mr can be extended to support things such as unison and git-svn. Some
538 files providing such extensions are available in F</usr/share/mr/>. See
539 the documentation in the files for details about using them.
540
541 =head1 EXIT STATUS
542
543 mr returns nonzero if a command failed in any of the repositories.
544
545 =head1 AUTHOR
546
547 Copyright 2007-2011 Joey Hess <joey@kitenet.net>
548
549 Licensed under the GNU GPL version 2 or higher.
550
551 http://myrepos.branchable.com/
552
553 =cut
554
555 use warnings;
556 use strict;
557 use Getopt::Long;
558 use Cwd qw(getcwd abs_path);
559
560 # things that can happen when mr runs a command
561 use constant {
562         OK => 0,
563         FAILED => 1,
564         SKIPPED => 2,
565         ABORT => 3,
566 };
567
568 # configurables
569 my $config_overridden=0;
570 my $verbose=0;
571 my $quiet=0;
572 my $stats=0;
573 my $force=0;
574 my $insecure=0;
575 my $interactive=0;
576 my $max_depth;
577 my $no_chdir=0;
578 my $jobs=1;
579 my $trust_all=0;
580 my $directory=getcwd();
581
582 my $HOME_MR_CONFIG = "$ENV{HOME}/.mrconfig";
583 $ENV{MR_CONFIG}=find_mrconfig();
584
585 # globals :-(
586 my %config;
587 my %configfiles;
588 my %knownactions;
589 my %alias;
590 my (@ok, @failed, @skipped);
591
592 main();
593
594 sub shellquote {
595         my $i=shift;
596         $i=~s/'/'"'"'/g;
597         return "'$i'";
598 }
599
600 # Runs a shell command using a supplied function.
601 # The lib will be included in the shell command line, and any params
602 # will be available in the shell as $1, $2, etc.
603 my $lastlib;
604 sub runsh {
605         my ($action, $topdir, $subdir, $command, $params, $runner) = @_;
606
607         # optimisation: avoid running the shell for true and false
608         if ($command =~ /^\s*true\s*$/) {
609                 $?=0;
610                 return 0;
611         }
612         elsif ($command =~ /^\s*false\s*$/) {
613                 $?=0;
614                 return 1;
615         }
616         
617         my $quotedparams=join(" ", (map { shellquote($_) } @$params));
618         my $lib=exists $config{$topdir}{$subdir}{lib} ?
619                        $config{$topdir}{$subdir}{lib}."\n" : "";
620         if ($verbose && (! defined $lastlib || $lastlib ne $lib)) {
621                 print "mr library now: >>$lib<<\n";
622                 $lastlib=$lib;
623         }
624         my $shellcode="set -e;".$lib.
625                 "my_sh(){ $command\n }; my_sh $quotedparams";
626         print "mr $action: running $action >>$command<<\n" if $verbose;
627         $runner->($shellcode);
628 }
629
630 my %perl_cache;
631 sub perl {
632         my $id=shift;
633         my $s=shift;
634         if ($s =~ m/^perl:\s+(.*)/s) {
635                 return $perl_cache{$1} if exists $perl_cache{$1};
636                 my $sub=eval "sub {$1}";
637                 if (! defined $sub) {
638                         print STDERR "mr: bad perl code in $id: $@\n";
639                 }
640                 return $perl_cache{$1} = $sub;
641         }
642         return undef;
643 }
644
645 my %vcs;
646 sub vcs_test {
647         my ($action, $dir, $topdir, $subdir) = @_;
648
649         if (exists $vcs{$dir}) {
650                 return $vcs{$dir};
651         }
652
653         my $test="";
654         my %perltest;
655         foreach my $vcs_test (
656                         sort {
657                                 length $a <=> length $b 
658                                           ||
659                                        $a cmp $b
660                         } grep { /_test$/ } keys %{$config{$topdir}{$subdir}}) {
661                 my ($vcs)=$vcs_test =~ /(.*)_test/;
662                 my $p=perl($vcs_test, $config{$topdir}{$subdir}{$vcs_test});
663                 if (defined $p) {
664                         $perltest{$vcs}=$p;
665                 }
666                 else {
667                         $test="my_$vcs_test() {\n$config{$topdir}{$subdir}{$vcs_test}\n}\n".$test;
668                         $test.="if my_$vcs_test; then echo $vcs; fi\n";
669                 }
670         }
671
672         my @vcs;
673         foreach my $vcs (keys %perltest) {
674                 if ($perltest{$vcs}->()) {
675                         push @vcs, $vcs;
676                 }
677         }
678
679         push @vcs, split(/\n/,
680                 runsh("vcs test", $topdir, $subdir, $test, [], sub {
681                         my $sh=shift;
682                         my $ret=`$sh`;
683                         return $ret;
684                 })) if length $test;
685         if (@vcs > 1) {
686                 print STDERR "mr $action: found multiple possible repository types (@vcs) for ".fulldir($topdir, $subdir)."\n";
687                 return undef;
688         }
689         if (! @vcs) {
690                 return $vcs{$dir}=undef;
691         }
692         else {
693                 return $vcs{$dir}=$vcs[0];
694         }
695 }
696         
697 sub findcommand {
698         my ($action, $dir, $topdir, $subdir, $is_checkout) = @_;
699         
700         if (exists $config{$topdir}{$subdir}{$action}) {
701                 return $config{$topdir}{$subdir}{$action};
702         }
703
704         if ($is_checkout) {
705                 return undef;
706         }
707
708         my $vcs=vcs_test(@_);
709
710         if (defined $vcs && 
711             exists $config{$topdir}{$subdir}{$vcs."_".$action}) {
712                 return $config{$topdir}{$subdir}{$vcs."_".$action};
713         }
714         else {
715                 return undef;
716         }
717 }
718
719 sub fulldir {
720         my ($topdir, $subdir) = @_;
721         return $subdir =~ /^\// ? $subdir : $topdir.$subdir;
722 }
723
724 sub action {
725         my ($action, $dir, $topdir, $subdir, $force_checkout) = @_;
726         my $fulldir=fulldir($topdir, $subdir);
727         my $checkout_dir;
728
729         $ENV{MR_CONFIG}=$configfiles{$topdir};
730         my $is_checkout=($action eq 'checkout');
731         my $is_update=($action =~ /update/);
732
733         ($ENV{MR_REPO}=$dir) =~ s!/$!!;
734         $ENV{MR_ACTION}=$action;
735         
736         foreach my $testname ("skip", "deleted") {
737                 next if $force && $testname eq "skip";
738
739                 my $testcommand=findcommand($testname, $dir, $topdir, $subdir, $is_checkout);
740
741                 if (defined $testcommand) {
742                         my $ret=runsh "$testname test", $topdir, $subdir,
743                                 $testcommand, [$action],
744                                 sub { system(shift()) };
745                         if ($ret != 0) {
746                                 if (($? & 127) == 2) {
747                                         print STDERR "mr $action: interrupted\n";
748                                         return ABORT;
749                                 }
750                                 elsif ($? & 127) {
751                                         print STDERR "mr $action: $testname test received signal ".($? & 127)."\n";
752                                         return ABORT;
753                                 }
754                         }
755                         if ($ret >> 8 == 0) {
756                                 if ($testname eq "deleted") {
757                                         if (-d $dir) {
758                                                 print STDERR "mr error: $dir should be deleted yet still exists\n";
759                                                 return FAILED;
760                                         }
761                                 }
762                                 print "mr $action: skip $dir skipped\n" if $verbose;
763                                 return SKIPPED;
764                         }
765                 }
766         }
767
768         if ($is_checkout) {
769                 $checkout_dir=$dir;
770                 if (! $force_checkout) {
771                         if (-d $dir) {
772                                 print "mr $action: $dir already exists, skipping checkout\n" if $verbose;
773                                 return SKIPPED;
774                         }
775         
776                         $dir=~s/^(.*)\/[^\/]+\/?$/$1/;
777                 }
778         }
779         elsif ($is_update) {
780                 if (! -d $dir) {
781                         return action("checkout", $dir, $topdir, $subdir);
782                 }
783         }
784
785         my $command=findcommand($action, $dir, $topdir, $subdir, $is_checkout);
786
787         if ($is_checkout && ! -d $dir) {
788                 print "mr $action: creating parent directory $dir\n" if $verbose;
789                 system("mkdir", "-p", $dir);
790         }
791
792         if (! $no_chdir && ! chdir($dir)) {
793                 print STDERR "mr $action: failed to chdir to $dir: $!\n";
794                 return FAILED;
795         }
796         elsif (! defined $command) {
797                 my $vcs=vcs_test(@_);
798                 if (! defined $vcs) {
799                         print STDERR "mr $action: unknown repository type and no defined $action command for $fulldir\n";
800                         return FAILED;
801                 }
802                 else {
803                         print STDERR "mr $action: no defined action for $vcs repository $fulldir, skipping\n";
804                         return SKIPPED;
805                 }
806         }
807         else {
808                 my $actionmsg;
809                 if (! $no_chdir) {
810                         $actionmsg="mr $action: $fulldir";
811                 }
812                 else {
813                         my $s=$directory;
814                         $s=~s/^\Q$fulldir\E\/?//;
815                         $actionmsg="mr $action: $fulldir (in subdir $s)";
816                 }
817                 print "$actionmsg\n" unless $quiet;
818
819                 my $hookret=hook("pre_$action", $topdir, $subdir);
820                 return $hookret if $hookret != OK;
821
822                 my $ret=runsh $action, $topdir, $subdir,
823                         $command, \@ARGV, sub {
824                                 my $sh=shift;
825                                 if ($quiet) {
826                                         my $output = qx/$sh 2>&1/;
827                                         my $ret = $?;
828                                         if ($ret != 0) {
829                                                 print "$actionmsg\n";
830                                                 print STDERR $output;
831                                         }
832                                         return $ret;
833                                 }
834                                 else {
835                                         system($sh);
836                                 }
837                         };
838                 if ($ret != 0) {
839                         if (($? & 127) == 2) {
840                                 print STDERR "mr $action: interrupted\n";
841                                 return ABORT;
842                         }
843                         elsif ($? & 127) {
844                                 print STDERR "mr $action: received signal ".($? & 127)."\n";
845                                 return ABORT;
846                         }
847                         print STDERR "mr $action: failed ($ret)\n" if $verbose;
848                         if ($ret >> 8 != 0) {
849                                 print STDERR "mr $action: command failed\n";
850                                 if (-e "$ENV{HOME}/.mrlog" && $action ne 'remember') {
851                                         # recreate original command line to
852                                         # remember, and avoid recursing
853                                         my @orig=@ARGV;
854                                         @ARGV=('-n', $action, @orig);
855                                         action("remember", $dir, $topdir, $subdir);
856                                         @ARGV=@orig;
857                                 }
858                         }
859                         elsif ($ret != 0) {
860                                 print STDERR "mr $action: command died ($ret)\n";
861                         }
862                         return FAILED;
863                 }
864                 else {
865                         if ($is_checkout && ! -d $dir) {
866                                 print STDERR "mr $action: $dir missing after checkout\n";;
867                                 return FAILED;
868                         }
869
870                         my $ret=hook("post_$action", $topdir, $subdir);
871                         return $ret if $ret != OK;
872                         
873                         if ($is_checkout || $is_update) {
874                                 if ($is_checkout && ! $no_chdir) {
875                                         if (! chdir($checkout_dir)) {
876                                                 print STDERR "mr $action: failed to chdir to $checkout_dir: $!\n";
877                                                 return FAILED;
878                                         }
879                                 }
880                                 my $ret=hook("fixups", $topdir, $subdir);
881                                 return $ret if $ret != OK;
882                         }
883                         
884                         return OK;
885                 }
886         }
887 }
888
889 sub hook {
890         my ($hook, $topdir, $subdir) = @_;
891
892         my $command=$config{$topdir}{$subdir}{$hook};
893         return OK unless defined $command;
894         my $ret=runsh $hook, $topdir, $subdir, $command, [], sub {
895                         my $sh=shift;
896                         if ($quiet) {
897                                 my $output = qx/$sh 2>&1/;
898                                 my $ret = $?;
899                                 if ($ret != 0) {
900                                         print STDERR $output;
901                                 }
902                                 return $ret;
903                         }
904                         else {
905                                 system($sh);
906                         }
907                 };
908         if ($ret != 0) {
909                 if (($? & 127) == 2) {
910                         print STDERR "mr $hook: interrupted\n";
911                         return ABORT;
912                 }
913                 elsif ($? & 127) {
914                         print STDERR "mr $hook: received signal ".($? & 127)."\n";
915                         return ABORT;
916                 }
917                 else {
918                         return FAILED;
919                 }
920         }
921
922         return OK;
923 }
924
925 # run actions on multiple repos, in parallel
926 sub mrs {
927         my $action=shift;
928         my @repos=@_;
929
930         $| = 1;
931         my @active;
932         my @fhs;
933         my @out;
934         my $running=0;
935         while (@fhs or @repos) {
936                 while ((!$jobs || $running < $jobs) && @repos) {
937                         $running++;
938                         my $repo = shift @repos;
939                         pipe(my $outfh, CHILD_STDOUT);
940                         pipe(my $errfh, CHILD_STDERR);
941                         my $pid;
942                         unless ($pid = fork) {
943                                 die "mr $action: cannot fork: $!" unless defined $pid;
944                                 open(STDOUT, ">&CHILD_STDOUT") || die "mr $action cannot reopen stdout: $!";
945                                 open(STDERR, ">&CHILD_STDERR") || die "mr $action cannot reopen stderr: $!";
946                                 close CHILD_STDOUT;
947                                 close CHILD_STDERR;
948                                 close $outfh;
949                                 close $errfh;
950                                 exit action($action, @$repo);
951                         }
952                         close CHILD_STDOUT;
953                         close CHILD_STDERR;
954                         push @active, [$pid, $repo];
955                         push @fhs, [$outfh, $errfh];
956                         push @out, ['',     ''];
957                 }
958                 my ($rin, $rout) = ('','');
959                 my $nfound;
960                 foreach my $fh (@fhs) {
961                         next unless defined $fh;
962                         vec($rin, fileno($fh->[0]), 1) = 1 if defined $fh->[0];
963                         vec($rin, fileno($fh->[1]), 1) = 1 if defined $fh->[1];
964                 }
965                 $nfound = select($rout=$rin, undef, undef, 1);
966                 foreach my $channel (0, 1) {
967                         foreach my $i (0..$#fhs) {
968                                 next unless defined $fhs[$i];
969                                 my $fh = $fhs[$i][$channel];
970                                 next unless defined $fh;
971                                 if (vec($rout, fileno($fh), 1) == 1) {
972                                         my $r = '';
973                                         if (sysread($fh, $r, 1024) == 0) {
974                                                 close($fh);
975                                                 $fhs[$i][$channel] = undef;
976                                                 if (! defined $fhs[$i][0] &&
977                                                     ! defined $fhs[$i][1]) {
978                                                         waitpid($active[$i][0], 0);
979                                                         print STDOUT $out[$i][0];
980                                                         print STDERR $out[$i][1];
981                                                         record($active[$i][1], $? >> 8);
982                                                         splice(@fhs, $i, 1);
983                                                         splice(@active, $i, 1);
984                                                         splice(@out, $i, 1);
985                                                         $running--;
986                                                 }
987                                         }
988                                         $out[$i][$channel] .= $r;
989                                 }
990                         }
991                 }
992         }
993 }
994
995 sub record {
996         my $dir=shift()->[0];
997         my $ret=shift;
998
999         if ($ret == OK) {
1000                 push @ok, $dir;
1001                 print "\n" unless $quiet;
1002         }
1003         elsif ($ret == FAILED) {
1004                 if ($interactive) {
1005                         chdir($dir) unless $no_chdir;
1006                         print STDERR "mr: Starting interactive shell. Exit shell to continue.\n";
1007                         system((getpwuid($<))[8], "-i");
1008                 }
1009                 push @failed, $dir;
1010                 print "\n" unless $quiet;
1011         }
1012         elsif ($ret == SKIPPED) {
1013                 push @skipped, $dir;
1014         }
1015         elsif ($ret == ABORT) {
1016                 exit 1;
1017         }
1018         else {
1019                 die "unknown exit status $ret";
1020         }
1021 }
1022
1023 sub showstats {
1024         my $action=shift;
1025         if (! @ok && ! @failed && ! @skipped) {
1026                 die "mr $action: no repositories found to work on\n";
1027         }
1028         print "mr $action: finished (".join("; ",
1029                 showstat($#ok+1, "ok", "ok"),
1030                 showstat($#failed+1, "failed", "failed"),
1031                 showstat($#skipped+1, "skipped", "skipped"),
1032         ).")\n" unless $quiet;
1033         if ($stats) {
1034                 if (@skipped) {
1035                         print "mr $action: (skipped: ".join(" ", @skipped).")\n" unless $quiet;
1036                 }
1037                 if (@failed) {
1038                         print STDERR "mr $action: (failed: ".join(" ", @failed).")\n";
1039                 }
1040         }
1041 }
1042
1043 sub showstat {
1044         my $count=shift;
1045         my $singular=shift;
1046         my $plural=shift;
1047         if ($count) {
1048                 return "$count ".($count > 1 ? $plural : $singular);
1049         }
1050         return;
1051 }
1052
1053 # an ordered list of repos
1054 sub repolist {
1055         my @list;
1056         foreach my $topdir (sort keys %config) {
1057                 foreach my $subdir (sort keys %{$config{$topdir}}) {
1058                         push @list, {
1059                                 topdir => $topdir,
1060                                 subdir => $subdir,
1061                                 order => $config{$topdir}{$subdir}{order},
1062                         };
1063                 }
1064         }
1065         return sort {
1066                 $a->{order}  <=> $b->{order}
1067                              ||
1068                 $a->{topdir} cmp $b->{topdir}
1069                              ||
1070                 $a->{subdir} cmp $b->{subdir}
1071         } @list;
1072 }
1073
1074 sub repodir {
1075         my $repo=shift;
1076         my $topdir=$repo->{topdir};
1077         my $subdir=$repo->{subdir};
1078         my $ret=($subdir =~/^\//) ? $subdir : $topdir.$subdir;
1079         $ret=~s/\/\.$//;
1080         return $ret;
1081 }
1082
1083 # Figure out which repos to act on.  Returns a list of array refs
1084 # in the format:
1085 #
1086 #   [ "$full_repo_path/", "$mr_config_path/", $section_header ]
1087 sub selectrepos {
1088         my @repos;
1089         foreach my $repo (repolist()) {
1090                 my $topdir=$repo->{topdir};
1091                 my $subdir=$repo->{subdir};
1092
1093                 next if $subdir eq 'DEFAULT';
1094                 my $dir=repodir($repo);
1095                 my $d=$directory;
1096                 $dir.="/" unless $dir=~/\/$/;
1097                 $d.="/" unless $d=~/\/$/;
1098                 next if $dir ne $d && $dir !~ /^\Q$d\E/;
1099                 if (defined $max_depth) {
1100                         my @a=split('/', $dir);
1101                         my @b=split('/', $d);
1102                         do { } while (@a && @b && shift(@a) eq shift(@b));
1103                         next if @a > $max_depth || @b > $max_depth;
1104                 }
1105                 push @repos, [$dir, $topdir, $subdir];
1106         }
1107         if (! @repos) {
1108                 # fallback to find a leaf repo
1109                 foreach my $repo (reverse repolist()) {
1110                         my $topdir=$repo->{topdir};
1111                         my $subdir=$repo->{subdir};
1112                         
1113                         next if $subdir eq 'DEFAULT';
1114                         my $dir=repodir($repo);
1115                         my $d=$directory;
1116                         $dir.="/" unless $dir=~/\/$/;
1117                         $d.="/" unless $d=~/\/$/;
1118                         if ($d=~/^\Q$dir\E/) {
1119                                 push @repos, [$dir, $topdir, $subdir];
1120                                 last;
1121                         }
1122                 }
1123                 $no_chdir=1;
1124         }
1125         return @repos;
1126 }
1127
1128 sub expandenv {
1129         my $val=shift;
1130         
1131
1132         if ($val=~/\$/) {
1133                 $val=`echo "$val"`;
1134                 chomp $val;
1135         }
1136         
1137         return $val;
1138 }
1139
1140 my %trusted;
1141 sub is_trusted_config {
1142         my $config=shift; # must be abs_pathed already
1143
1144         # We always trust ~/.mrconfig.
1145         return 1 if $config eq abs_path($HOME_MR_CONFIG);
1146
1147         return 1 if $trust_all;
1148
1149         my $trustfile=$ENV{HOME}."/.mrtrust";
1150
1151         if (! %trusted) {
1152                 $trusted{$HOME_MR_CONFIG}=1;
1153                 if (open (TRUST, "<", $trustfile)) {
1154                         while (<TRUST>) {
1155                                 chomp;
1156                                 s/^~\//$ENV{HOME}\//;
1157                                 my $d=abs_path($_);
1158                                 $trusted{$d}=1 if defined $d;
1159                         }
1160                         close TRUST;
1161                 }
1162         }
1163
1164         return $trusted{$config};
1165 }
1166
1167
1168 sub is_trusted_repo {
1169         my $repo=shift;
1170         
1171         # Tightly limit what is allowed in a repo name.
1172         # No ../, no absolute paths, and no unusual filenames
1173         # that might try to escape to the shell.
1174         return $repo =~ /^[-_.+\/A-Za-z0-9]+$/ &&
1175                $repo !~ /\.\./ && $repo !~ /^\//;
1176 }
1177
1178 sub is_trusted_checkout {
1179         my $command=shift;
1180         
1181         # To determine if the command is safe, compare it with the
1182         # *_trusted_checkout config settings. Those settings are
1183         # templates for allowed commands, so make sure that each word
1184         # of the command matches the corresponding word of the template.
1185         
1186         my @words;
1187         foreach my $word (split(' ', $command)) {
1188                 # strip quoting
1189                 if ($word=~/^'(.*)'$/) {
1190                         $word=$1;
1191                 }
1192                 elsif ($word=~/^"(.*)"$/) {
1193                         $word=$1;
1194                 }
1195
1196                 push @words, $word;
1197         }
1198
1199         foreach my $key (grep { /_trusted_checkout$/ }
1200                          keys %{$config{''}{DEFAULT}}) {
1201                 my @twords=split(' ', $config{''}{DEFAULT}{$key});
1202                 next if @words > @twords;
1203
1204                 my $match=1;
1205                 my $url;
1206                 for (my $c=0; $c < @twords && $match; $c++) {
1207                         if ($twords[$c] eq '$url') {
1208                                 # Match all the typical characters found in
1209                                 # urls, plus @ which svn can use. Note
1210                                 # that the "url" might also be a local
1211                                 # directory.
1212                                 $match=(
1213                                         defined $words[$c] &&
1214                                         $words[$c] =~ /^[-_.+:@\/A-Za-z0-9]+$/
1215                                 );
1216                                 $url=$words[$c];
1217                         }
1218                         elsif ($twords[$c] eq '$repo') {
1219                                 # If a repo is not specified, assume it
1220                                 # will be the last path component of the
1221                                 # url, or something derived from it, and
1222                                 # check that.
1223                                 if (! defined $words[$c] && defined $url) {
1224                                         ($words[$c])=$url=~/\/([^\/]+)\/?$/;
1225                                 }
1226
1227                                 $match=(
1228                                         defined $words[$c] &&
1229                                         is_trusted_repo($words[$c])
1230                                 );
1231                         }
1232                         elsif (defined $words[$c] && $words[$c]=~/^($twords[$c])$/) {
1233                                 $match=1;
1234                         }
1235                         else {
1236                                 $match=0;
1237                         }
1238                 }
1239                 return 1 if $match;
1240         }
1241
1242         return 0;
1243 }
1244
1245 my %loaded;
1246 sub loadconfig {
1247         my $f=shift;
1248         my $dir=shift;
1249         my $bootstrap_src=shift;
1250
1251         my @toload;
1252
1253         my $in;
1254         my $trusted;
1255         if (ref $f eq 'GLOB') {
1256                 $dir="";
1257                 $in=$f;
1258                 $trusted=1;
1259         }
1260         else {
1261                 my $absf=abs_path($f);
1262                 if ($loaded{$absf}) {
1263                         return;
1264                 }
1265                 $loaded{$absf}=1;
1266
1267                 $trusted=is_trusted_config($absf);
1268
1269                 if (! defined $dir) {
1270                         ($dir)=$f=~/^(.*\/)[^\/]+$/;
1271                         if (! defined $dir) {
1272                                 $dir=".";
1273                         }
1274                 }
1275
1276                 $dir=abs_path($dir)."/";
1277                 
1278                 if (! exists $configfiles{$dir}) {
1279                         $configfiles{$dir}=$f;
1280                 }
1281
1282                 # copy in defaults from first parent
1283                 my $parent=$dir;
1284                 while ($parent=~s/^(.*\/)[^\/]+\/?$/$1/) {
1285                         if ($parent eq '/') {
1286                                 $parent="";
1287                         }
1288                         if (exists $config{$parent} &&
1289                             exists $config{$parent}{DEFAULT}) {
1290                                 $config{$dir}{DEFAULT}={ %{$config{$parent}{DEFAULT}} };
1291                                 last;
1292                         }
1293                 }
1294                 
1295                 if (! -e $f) {
1296                         return;
1297                 }
1298
1299                 print "mr: loading config $f\n" if $verbose;
1300                 open($in, "<", $f) || die "mr: open $f: $!\n";
1301         }
1302         my @lines=<$in>;
1303         close $in unless ref $f eq 'GLOB';
1304
1305         my $section;
1306
1307         # Keep track of the current line in the config file;
1308         # when a file is included track the current line from the include.
1309         my $lineno=0;
1310         my $included=undef;
1311
1312         my $line;
1313         my $nextline = sub {
1314                 if ($included) {
1315                         $included--;
1316                 }
1317                 else {
1318                         $included=undef;
1319                         $lineno++;
1320                 }
1321                 $line=shift @lines;
1322                 chomp $line;
1323                 return $line;
1324         };
1325         my $lineerror = sub {
1326                 my $msg=shift;
1327                 if (defined $included) {
1328                         die "mr: $msg at $f line $lineno, included line: $line\n";
1329                 }
1330                 else {
1331                         die "mr: $msg at $f line $lineno\n";
1332                 }
1333         };
1334         my $trusterror = sub {
1335                 my $msg=shift;
1336         
1337                 if (defined $bootstrap_src) {
1338                         die "mr: $msg in untrusted $bootstrap_src line $lineno\n".
1339                                 "(To trust this url, --trust-all can be used; but please use caution;\n".
1340                                 "this can allow arbitrary code execution!)\n";
1341                 }
1342                 else {
1343                         die "mr: $msg in untrusted $f line $lineno\n".
1344                                 "(To trust this file, list it in ~/.mrtrust.)\n";
1345                 }
1346         };
1347
1348         while (@lines) {
1349                 $_=$nextline->();
1350
1351                 next if /^\s*\#/ || /^\s*$/;
1352
1353                 if (! $trusted && /[[:cntrl:]]/) {
1354                         $trusterror->("illegal control character");
1355                 }
1356
1357                 if (/^\[([^\]]*)\]\s*$/) {
1358                         $section=$1;
1359
1360                         if (! $trusted) {
1361                                 if (! is_trusted_repo($section) ||
1362                                     $section eq 'ALIAS' ||
1363                                     $section eq 'DEFAULT') {
1364                                         $trusterror->("illegal section \"[$section]\"");
1365                                 }
1366                         }
1367                         $section=expandenv($section) if $trusted;
1368                         if ($section ne 'ALIAS' &&
1369                             ! exists $config{$dir}{$section} &&
1370                             exists $config{$dir}{DEFAULT}) {
1371                                 # copy in defaults
1372                                 $config{$dir}{$section}={ %{$config{$dir}{DEFAULT}} };
1373                         }
1374                 }
1375                 elsif (/^(\w+)\s*=\s*(.*)/) {
1376                         my $parameter=$1;
1377                         my $value=$2;
1378
1379                         # continued value
1380                         while (@lines && $lines[0]=~/^\s(.+)/) {
1381                                 $value.="\n$1";
1382                                 chomp $value;
1383                                 $nextline->();
1384                         }
1385
1386                         if (! $trusted) {
1387                                 # Untrusted files can only contain a few
1388                                 # settings in specific known-safe formats.
1389                                 if ($parameter eq 'checkout') {
1390                                         if (! is_trusted_checkout($value)) {
1391                                                 $trusterror->("illegal checkout command \"$value\"");
1392                                         }
1393                                 }
1394                                 elsif ($parameter eq 'order') {
1395                                         # not interpreted as a command, so
1396                                         # safe.
1397                                 }
1398                                 elsif ($value eq 'true' || $value eq 'false') {
1399                                         # skip=true , deleted=true etc are
1400                                         # safe.
1401                                 }
1402                                 else {
1403                                         $trusterror->("illegal setting \"$parameter=$value\"");
1404                                 }
1405                         }
1406
1407                         if ($parameter eq "include") {
1408                                 print "mr: including output of \"$value\"\n" if $verbose;
1409                                 my @inc=`$value`;
1410                                 if ($?) {
1411                                         print STDERR "mr: include command exited nonzero ($?)\n";
1412                                 }
1413                                 $included += @inc;
1414                                 unshift @lines, @inc;
1415                                 next;
1416                         }
1417
1418                         if (! defined $section) {
1419                                 $lineerror->("parameter ($parameter) not in section");
1420                         }
1421                         if ($section eq 'ALIAS') {
1422                                 $alias{$parameter}=$value;
1423                         }
1424                         elsif ($parameter eq 'lib' or $parameter =~ s/_append$//) {
1425                                 $config{$dir}{$section}{$parameter}.="\n".$value."\n";
1426                         }
1427                         else {
1428                                 $config{$dir}{$section}{$parameter}=$value;
1429                                 if ($parameter =~ /.*_(.*)/) {
1430                                         $knownactions{$1}=1;
1431                                 }
1432                                 else {
1433                                         $knownactions{$parameter}=1;
1434                                 }
1435                                 if ($parameter eq 'chain' &&
1436                                     length $dir && $section ne "DEFAULT") {
1437                                         my $chaindir="$section";
1438                                         if ($chaindir !~ m!^/!) {
1439                                                 $chaindir=$dir.$chaindir;
1440                                         }
1441                                         if (-e "$chaindir/.mrconfig") {
1442                                                 my $ret=system($value);
1443                                                 if ($ret != 0) {
1444                                                         if (($? & 127) == 2) {
1445                                                                 print STDERR "mr: chain test interrupted\n";
1446                                                                 exit 2;
1447                                                         }
1448                                                         elsif ($? & 127) {
1449                                                                 print STDERR "mr: chain test received signal ".($? & 127)."\n";
1450                                                         }
1451                                                 }
1452                                                 else {
1453                                                         push @toload, ["$chaindir/.mrconfig", $chaindir];
1454                                                 }
1455                                         }
1456                                 }
1457                         }
1458                 }
1459                 else {
1460                         $lineerror->("parse error");
1461                 }
1462         }
1463
1464         foreach my $c (@toload) {
1465                 loadconfig(@$c);
1466         }
1467 }
1468
1469 sub startingconfig {
1470         %alias=%config=%configfiles=%knownactions=%loaded=();
1471         my $datapos=tell(DATA);
1472         loadconfig(\*DATA);
1473         seek(DATA,$datapos,0); # rewind
1474 }
1475
1476 sub modifyconfig {
1477         my $f=shift;
1478         # the section to modify or add
1479         my $targetsection=shift;
1480         # fields to change in the section
1481         # To remove a field, set its value to "".
1482         my %changefields=@_;
1483
1484         my @lines;
1485         my @out;
1486
1487         if (-e $f) {
1488                 open(my $in, "<", $f) || die "mr: open $f: $!\n";
1489                 @lines=<$in>;
1490                 close $in;
1491         }
1492
1493         my $formatfield=sub {
1494                 my $field=shift;
1495                 my @value=split(/\n/, shift);
1496
1497                 return "$field = ".shift(@value)."\n".
1498                         join("", map { "\t$_\n" } @value);
1499         };
1500         my $addfields=sub {
1501                 my @blanks;
1502                 while ($out[$#out] =~ /^\s*$/) {
1503                         unshift @blanks, pop @out;
1504                 }
1505                 foreach my $field (sort keys %changefields) {
1506                         if (length $changefields{$field}) {
1507                                 push @out, "$field = $changefields{$field}\n";
1508                                 delete $changefields{$field};
1509                         }
1510                 }
1511                 push @out, @blanks;
1512         };
1513
1514         my $section;
1515         while (@lines) {
1516                 $_=shift(@lines);
1517
1518                 if (/^\s*\#/ || /^\s*$/) {
1519                         push @out, $_;
1520                 }
1521                 elsif (/^\[([^\]]*)\]\s*$/) {
1522                         if (defined $section && 
1523                             $section eq $targetsection) {
1524                                 $addfields->();
1525                         }
1526
1527                         $section=expandenv($1);
1528
1529                         push @out, $_;
1530                 }
1531                 elsif (/^(\w+)\s*=\s(.*)/) {
1532                         my $parameter=$1;
1533                         my $value=$2;
1534
1535                         # continued value
1536                         while (@lines && $lines[0]=~/^\s(.+)/) {
1537                                 shift(@lines);
1538                                 $value.="\n$1";
1539                                 chomp $value;
1540                         }
1541
1542                         if ($section eq $targetsection) {
1543                                 if (exists $changefields{$parameter}) {
1544                                         if (length $changefields{$parameter}) {
1545                                                 $value=$changefields{$parameter};
1546                                         }
1547                                         delete $changefields{$parameter};
1548                                 }
1549                         }
1550
1551                         push @out, $formatfield->($parameter, $value);
1552                 }
1553         }
1554
1555         if (defined $section && 
1556             $section eq $targetsection) {
1557                 $addfields->();
1558         }
1559         elsif (%changefields) {
1560                 push @out, "\n[$targetsection]\n";
1561                 foreach my $field (sort keys %changefields) {
1562                         if (length $changefields{$field}) {
1563                                 push @out, $formatfield->($field, $changefields{$field});
1564                         }
1565                 }
1566         }
1567
1568         open(my $out, ">", $f) || die "mr: write $f: $!\n";
1569         print $out @out;
1570         close $out;     
1571 }
1572
1573 sub dispatch {
1574         my $action=shift;
1575
1576         # actions that do not operate on all repos
1577         if ($action eq 'config') {
1578                 config(@ARGV);
1579         }
1580         elsif ($action eq 'register') {
1581                 register(@ARGV);
1582         }
1583         elsif ($action eq 'bootstrap') {
1584                 bootstrap();
1585         }
1586         elsif ($action eq 'remember' ||
1587                $action eq 'offline' ||
1588                $action eq 'online') {
1589                 my @repos=selectrepos;
1590                 action($action, @{$repos[0]}) if @repos;
1591                 exit 0;
1592         }
1593
1594         if (!$jobs || $jobs > 1) {
1595                 mrs($action, selectrepos());
1596         }
1597         else {
1598                 foreach my $repo (selectrepos()) {
1599                         record($repo, action($action, @$repo));
1600                 }
1601         }
1602 }
1603
1604 sub help {
1605         my $help=q#
1606                 case `uname -s` in
1607                         SunOS)
1608                         SHOWMANFILE="man -f"
1609                         ;;
1610                         Darwin)
1611                         SHOWMANFILE="man"
1612                         ;;
1613                         *)
1614                         SHOWMANFILE="man"
1615                         ;;
1616                 esac
1617                 if [ ! -e "$MR_PATH" ]; then
1618                         error "cannot find program path"
1619                 fi
1620                 tmp=$(mktemp -t mr.XXXXXXXXXX) || error "mktemp failed"
1621                 trap "rm -f $tmp" exit
1622                 pod2man -c mr "$MR_PATH" > "$tmp" || error "pod2man failed"
1623                 $SHOWMANFILE "$tmp" || error "man failed"
1624         #;
1625         exec($help) || die "exec: $!";
1626 }
1627
1628 sub config {
1629         if (@_ < 2) {
1630                 die "mr config: not enough parameters\n";
1631         }
1632         my $section=shift;
1633         if ($section=~/^\//) {
1634                 # try to convert to a path relative to the config file
1635                 my ($dir)=$ENV{MR_CONFIG}=~/^(.*\/)[^\/]+$/;
1636                 $dir=abs_path($dir);
1637                 $dir.="/" unless $dir=~/\/$/;
1638                 if ($section=~/^\Q$dir\E(.*)/) {
1639                         $section=$1;
1640                 }
1641         }
1642         my %changefields;
1643         foreach (@_) {
1644                 if (/^([^=]+)=(.*)$/) {
1645                         $changefields{$1}=$2;
1646                 }
1647                 else {
1648                         my $found=0;
1649                         foreach my $topdir (sort keys %config) {
1650                                 if (exists $config{$topdir}{$section} &&
1651                                     exists $config{$topdir}{$section}{$_}) {
1652                                         print $config{$topdir}{$section}{$_}."\n";
1653                                         $found=1;
1654                                         last if $section eq 'DEFAULT';
1655                                 }
1656                         }
1657                         if (! $found) {
1658                                 die "mr config: $section $_ not set\n";
1659                         }
1660                 }
1661         }
1662         modifyconfig($ENV{MR_CONFIG}, $section, %changefields) if %changefields;
1663         exit 0;
1664 }
1665
1666 sub register {
1667         if ($config_overridden) {
1668                 # Find the directory that the specified config file is
1669                 # located in.
1670                 ($directory)=abs_path($ENV{MR_CONFIG})=~/^(.*\/)[^\/]+$/;
1671         }
1672         else {
1673                 # Find the closest known mrconfig file to the current
1674                 # directory.
1675                 $directory.="/" unless $directory=~/\/$/;
1676                 my $foundconfig=0;
1677                 foreach my $topdir (reverse sort keys %config) {
1678                         next unless length $topdir;
1679                         if ($directory=~/^\Q$topdir\E/) {
1680                                 $ENV{MR_CONFIG}=$configfiles{$topdir};
1681                                 $directory=$topdir;
1682                                 $foundconfig=1;
1683                                 last;
1684                         }
1685                 }
1686                 if (! $foundconfig) {
1687                         $directory=""; # no config file, use builtin
1688                 }
1689         }
1690         if (@ARGV) {
1691                 my $subdir=shift @ARGV;
1692                 if (! chdir($subdir)) {
1693                         print STDERR "mr register: failed to chdir to $subdir: $!\n";
1694                 }
1695         }
1696
1697         $ENV{MR_REPO}=getcwd();
1698         my $command=findcommand("register", $ENV{MR_REPO}, $directory, 'DEFAULT', 0);
1699         if (! defined $command) {
1700                 die "mr register: unknown repository type\n";
1701         }
1702
1703         $ENV{MR_REPO}=~s/.*\/(.*)/$1/;
1704         $command="set -e; ".$config{$directory}{DEFAULT}{lib}."\n".
1705                 "my_action(){ $command\n }; my_action ".
1706                 join(" ", map { s/\\/\\\\/g; s/"/\"/g; '"'.$_.'"' } @ARGV);
1707         print "mr register: running >>$command<<\n" if $verbose;
1708         exec($command) || die "exec: $!";
1709 }
1710
1711 sub bootstrap {
1712         eval q{use File::Copy};
1713         die $@ if $@;
1714
1715         my $src=shift @ARGV;
1716         my $dir=shift @ARGV || ".";
1717         
1718         if (! defined $src || ! length $src) {
1719                 die "mr: bootstrap requires source\n";
1720         }
1721
1722         # Retrieve config file.
1723         eval q{use File::Temp};
1724         die $@ if $@;
1725         my $tmpconfig=File::Temp->new();
1726         if ($src =~ m!^[\w\d]+://!) {
1727                 # Download the config file to a temporary location.
1728                 my @downloader;
1729                 if ($src =~ m!^ssh://(.*)!) {
1730                         @downloader = ("scp", $1, $tmpconfig);
1731                 }
1732                 else {
1733                         @downloader = ("curl", "-A", "mr", "-L", "-s", $src, "-o", $tmpconfig);
1734                         push(@downloader, "-k") if $insecure;
1735                 }
1736                 my $status = system(@downloader);
1737                 die "mr bootstrap: invalid SSL certificate for $src (consider -k)\n"
1738                         if $downloader[0] eq 'curl' && $status >> 8 == 60;
1739                 die "mr bootstrap: download of $src failed\n" if $status != 0;
1740         }
1741         elsif ($src eq '-') {
1742                 # Config file is read from stdin.
1743                 copy(\*STDIN, $tmpconfig) || die "stdin: $!";
1744         }
1745         else {
1746                 # Config file is local.
1747                 die "mr bootstrap: cannot read file '$src'"
1748                         unless -r $src;
1749                 copy($src, $tmpconfig) || die "copy: $!";
1750         }
1751
1752         # Sanity check on destination directory.
1753         if (! -e $dir) {
1754                 system("mkdir", "-p", $dir);
1755         }
1756         chdir($dir) || die "chdir $dir: $!";
1757
1758         # Special case to handle checkout of the "." repo, which 
1759         # would normally be skipped.
1760         my $topdir=abs_path(".")."/";
1761         my @repo=($topdir, $topdir, ".");
1762         loadconfig($tmpconfig, $topdir, $src);
1763         record(\@repo, action("checkout", @repo, 1))
1764                 if exists $config{$topdir}{"."}{"checkout"};
1765
1766         if (-e ".mrconfig") {
1767                 print STDERR "mr bootstrap: .mrconfig file already exists, not overwriting with $src\n";
1768         }
1769         else {
1770                 move($tmpconfig, ".mrconfig") || die "rename: $!";
1771         }
1772
1773         # Reload the config file (in case we got a different version)
1774         # and checkout everything else.
1775         startingconfig();
1776         loadconfig(".mrconfig");
1777         dispatch("checkout");
1778         @skipped=grep { abs_path($_) ne abs_path($topdir) } @skipped;
1779         showstats("bootstrap");
1780         exitstats();
1781 }
1782
1783 # alias expansion and command stemming
1784 sub expandaction {
1785         my $action=shift;
1786         if (exists $alias{$action}) {
1787                 $action=$alias{$action};
1788         }
1789         if (! exists $knownactions{$action}) {
1790                 my @matches = grep { /^\Q$action\E/ }
1791                         keys %knownactions, keys %alias;
1792                 if (@matches == 1) {
1793                         $action=$matches[0];
1794                 }
1795                 elsif (@matches == 0) {
1796                         die "mr: unknown action \"$action\" (known actions: ".
1797                                 join(", ", sort keys %knownactions).")\n";
1798                 }
1799                 else {
1800                         die "mr: ambiguous action \"$action\" (matches: ".
1801                                 join(", ", @matches).")\n";
1802                 }
1803         }
1804         return $action;
1805 }
1806
1807 sub find_mrconfig {
1808         my $dir=getcwd();
1809         while (length $dir) {
1810                 if (-e "$dir/.mrconfig") {
1811                         return "$dir/.mrconfig";
1812                 }
1813                 $dir=~s/\/[^\/]*$//;
1814         }
1815         return $HOME_MR_CONFIG;
1816 }
1817
1818 sub getopts {
1819         my @saved=@ARGV;
1820         Getopt::Long::Configure("bundling", "no_permute");
1821         my $result=GetOptions(
1822                 "d|directory=s" => sub { $directory=abs_path($_[1]) },
1823                 "c|config=s" => sub { $ENV{MR_CONFIG}=$_[1]; $config_overridden=1 },
1824                 "p|path" => sub { }, # now default, ignore
1825                 "f|force" => \$force,
1826                 "v|verbose" => \$verbose,
1827                 "q|quiet" => \$quiet,
1828                 "s|stats" => \$stats,
1829                 "k|insecure" => \$insecure,
1830                 "i|interactive" => \$interactive,
1831                 "n|no-recurse:i" => \$max_depth,
1832                 "j|jobs:i" => \$jobs,
1833                 "t|trust-all" => \$trust_all,
1834         );
1835         if (! $result || @ARGV < 1) {
1836                 die("Usage: mr [options] action [params ...]\n".
1837                     "(Use mr help for man page.)\n");
1838         }
1839         
1840         $ENV{MR_SWITCHES}="";
1841         foreach my $option (@saved) {
1842                 last if $option eq $ARGV[0];
1843                 $ENV{MR_SWITCHES}.="$option ";
1844         }
1845 }
1846
1847 sub init {
1848         $SIG{INT}=sub {
1849                 print STDERR "mr: interrupted\n";
1850                 exit 2;
1851         };
1852         
1853         # This can happen if it's run in a directory that was removed
1854         # or other strangeness.
1855         if (! defined $directory) {
1856                 die("mr: failed to determine working directory\n");
1857         }
1858         # Make sure MR_CONFIG is an absolute path, but don't use abs_path since
1859         # the config file might be a symlink to elsewhere, and the directory it's
1860         # in is significant.
1861         if ($ENV{MR_CONFIG} !~ /^\//) {
1862                 $ENV{MR_CONFIG}=getcwd()."/".$ENV{MR_CONFIG};
1863         }
1864         # Try to set MR_PATH to the path to the program.
1865         eval {
1866                 use FindBin qw($Bin $Script);
1867                 $ENV{MR_PATH}=$Bin."/".$Script;
1868         };
1869 }
1870         
1871 sub exitstats {
1872         if (@failed) {
1873                 exit 1;
1874         }
1875         else {
1876                 exit 0;
1877         }
1878 }
1879
1880 sub main {
1881         getopts();
1882         init();
1883         help(@ARGV) if $ARGV[0] eq 'help';
1884
1885         startingconfig();
1886         loadconfig($HOME_MR_CONFIG);
1887         loadconfig($ENV{MR_CONFIG});
1888         #use Data::Dumper; print Dumper(\%config);
1889         
1890         my $action=expandaction(shift @ARGV);
1891         dispatch($action);
1892
1893         showstats($action);
1894         exitstats();
1895 }
1896
1897 # Finally, some useful actions that mr knows about by default.
1898 # These can be overridden in ~/.mrconfig.
1899 __DATA__
1900 [ALIAS]
1901 co = checkout
1902 ci = commit
1903 ls = list
1904
1905 [DEFAULT]
1906 order = 10
1907 lib =
1908         error() {
1909                 echo "mr: $@" >&2
1910                 exit 1
1911         }
1912         warning() {
1913                 echo "mr (warning): $@" >&2
1914         }
1915         info() {
1916                 echo "mr: $@" >&2
1917         }
1918         hours_since() {
1919                 if [ -z "$1" ] || [ -z "$2" ]; then
1920                         error "mr: usage: hours_since action num"
1921                 fi
1922                 for dir in .git .svn .bzr CVS .hg _darcs _FOSSIL_; do
1923                         if [ -e "$MR_REPO/$dir" ]; then
1924                                 flagfile="$MR_REPO/$dir/.mr_last$1"
1925                                 break
1926                         fi
1927                 done
1928                 if [ -z "$flagfile" ]; then
1929                         error "cannot determine flag filename"
1930                 fi
1931                 delta=`perl -wle 'print -f shift() ? int((-M _) * 24) : 9999' "$flagfile"`
1932                 if [ "$delta" -lt "$2" ]; then
1933                         return 1
1934                 else
1935                         touch "$flagfile"
1936                         return 0
1937                 fi
1938         }
1939         is_bzr_checkout() {
1940                 LANG=C bzr info | egrep -q '^Checkout'
1941         }
1942         lazy() {
1943                 if [ -d "$MR_REPO" ]; then
1944                         return 1
1945                 else
1946                         return 0
1947                 fi
1948         }
1949
1950 svn_test = perl: -d "$ENV{MR_REPO}/.svn"
1951 git_test = perl: -e "$ENV{MR_REPO}/.git"
1952 bzr_test = perl: -d "$ENV{MR_REPO}/.bzr"
1953 cvs_test = perl: -d "$ENV{MR_REPO}/CVS"
1954 hg_test  = perl: -d "$ENV{MR_REPO}/.hg"
1955 darcs_test = perl: -d "$ENV{MR_REPO}/_darcs"
1956 fossil_test = perl: -f "$ENV{MR_REPO}/_FOSSIL_"
1957 git_bare_test = perl: 
1958         -d "$ENV{MR_REPO}/refs/heads" && -d "$ENV{MR_REPO}/refs/tags" &&
1959         -d "$ENV{MR_REPO}/objects" && -f "$ENV{MR_REPO}/config" &&
1960         `GIT_CONFIG="$ENV{MR_REPO}"/config git config --get core.bare` =~ /true/
1961 vcsh_test = perl:
1962         -d "$ENV{MR_REPO}/refs/heads" && -d "$ENV{MR_REPO}/refs/tags" &&
1963         -d "$ENV{MR_REPO}/objects" && -f "$ENV{MR_REPO}/config" &&
1964         `GIT_CONFIG="$ENV{MR_REPO}"/config git config --get vcsh.vcsh` =~ /true/
1965 veracity_test  = perl: -d "$ENV{MR_REPO}/.sgdrawer"
1966
1967 svn_update = svn update "$@"
1968 git_update = git pull "$@"
1969 bzr_update = 
1970         if is_bzr_checkout; then
1971                 bzr update "$@"
1972         else
1973                 bzr merge --pull "$@"
1974         fi
1975 cvs_update = cvs -q update "$@"
1976 hg_update  = hg pull "$@"; hg update "$@"
1977 darcs_update = darcs pull -a "$@"
1978 fossil_update = fossil pull "$@"
1979 vcsh_update = vcsh run "$MR_REPO" git pull "$@"
1980 veracity_update = vv pull "$@" && vv update "$@"
1981
1982 git_fetch = git fetch --all --prune --tags
1983 git_svn_fetch = git svn fetch
1984 darcs_fetch = darcs fetch
1985 hg_fetch = hg pull
1986
1987 svn_status = svn status "$@"
1988 git_status = git status -s "$@" || true; git --no-pager log --branches --not --remotes --simplify-by-decoration --decorate --oneline || true
1989 bzr_status = bzr status --short "$@"; bzr missing
1990 cvs_status = cvs -q status | grep -E '^(File:.*Status:|\?)' | grep -v 'Status: Up-to-date'
1991 hg_status  = hg status "$@"; hg summary --quiet | grep -v 'parent: 0:'
1992 darcs_status = darcs whatsnew -ls "$@" || true
1993 fossil_status = fossil changes "$@"
1994 vcsh_status = vcsh run "$MR_REPO" git -c status.relativePaths=false status -s "$@" || true
1995 veracity_status = vv status "$@"
1996
1997 svn_commit = svn commit "$@"
1998 git_commit = git commit -a "$@" && git push --all
1999 bzr_commit = 
2000         if is_bzr_checkout; then
2001                 bzr commit "$@"
2002         else
2003                 bzr commit "$@" && bzr push
2004         fi
2005 cvs_commit = cvs commit "$@"
2006 hg_commit  = hg commit "$@" && hg push
2007 darcs_commit = darcs record -a "$@" && darcs push -a
2008 fossil_commit = fossil commit "$@"
2009 vcsh_commit = vcsh run "$MR_REPO" git commit -a "$@" && vcsh run "$MR_REPO" git push --all
2010 veracity_commit = vv commit "$@" && vv push
2011
2012 git_record = git commit -a "$@"
2013 bzr_record =
2014         if is_bzr_checkout; then
2015                 bzr commit --local "$@"
2016         else
2017                 bzr commit "$@"
2018         fi
2019 hg_record  = hg commit "$@"
2020 darcs_record = darcs record -a "$@"
2021 fossil_record = fossil commit "$@"
2022 vcsh_record = vcsh run "$MR_REPO" git commit -a "$@"
2023 veracity_record = vv commit "$@"
2024
2025 svn_push = :
2026 git_push = git push "$@"
2027 bzr_push = bzr push "$@"
2028 cvs_push = :
2029 hg_push = hg push "$@"
2030 darcs_push = darcs push -a "$@"
2031 fossil_push = fossil push "$@"
2032 vcsh_push = vcsh run "$MR_REPO" git push "$@"
2033 veracity_push = vv push "$@"
2034
2035 svn_diff = svn diff "$@"
2036 git_diff = git diff "$@"
2037 bzr_diff = bzr diff "$@"
2038 cvs_diff = cvs -q diff "$@"
2039 hg_diff  = hg diff "$@"
2040 darcs_diff = darcs diff -u "$@"
2041 fossil_diff = fossil diff "$@"
2042 vcsh_diff = vcsh run "$MR_REPO" git diff "$@"
2043 veracity_diff = vv diff "$@"
2044
2045 svn_log = svn log "$@"
2046 git_log = git log "$@"
2047 bzr_log = bzr log "$@"
2048 cvs_log = cvs log "$@"
2049 hg_log  = hg log "$@"
2050 darcs_log = darcs changes "$@"
2051 git_bare_log = git log "$@"
2052 fossil_log = fossil timeline "$@"
2053 vcsh_log = vcsh run "$MR_REPO" git log "$@"
2054 veracity_log = vv log "$@"
2055
2056 hg_grep = hg grep "$@"
2057 cvs_grep = ack-grep "$@"
2058 svn_grep = ack-grep "$@"
2059 git_svn_grep = git grep "$@"
2060 git_grep = git grep "$@"
2061 bzr_grep = ack-grep "$@"
2062
2063 run = "$@"
2064
2065 svn_register =
2066         url=`LC_ALL=C svn info . | grep -i '^URL:' | cut -d ' ' -f 2`
2067         if [ -z "$url" ]; then
2068                 error "cannot determine svn url"
2069         fi
2070         echo "Registering svn url: $url in $MR_CONFIG"
2071         mr -c "$MR_CONFIG" config "`pwd`" checkout="svn co '$url' '$MR_REPO'"
2072 git_register = 
2073         url="`LC_ALL=C git config --get remote.origin.url`" || true
2074         if [ -z "$url" ]; then
2075                 error "cannot determine git url"
2076         fi
2077         echo "Registering git url: $url in $MR_CONFIG"
2078         mr -c "$MR_CONFIG" config "`pwd`" checkout="git clone '$url' '$MR_REPO'"
2079 bzr_register =
2080         url="`LC_ALL=C bzr info . | egrep -i 'checkout of branch|parent branch' | awk '{print $NF}' | head -n 1`"
2081         if [ -z "$url" ]; then
2082                 error "cannot determine bzr url"
2083         fi
2084         echo "Registering bzr url: $url in $MR_CONFIG"
2085         mr -c "$MR_CONFIG" config "`pwd`" checkout="bzr branch '$url' '$MR_REPO'"
2086 cvs_register =
2087         repo=`cat CVS/Repository`
2088         root=`cat CVS/Root`
2089         if [ -z "$root" ]; then
2090                 error "cannot determine cvs root"
2091                 fi
2092         echo "Registering cvs repository $repo at root $root"
2093         mr -c "$MR_CONFIG" config "`pwd`" checkout="cvs -d '$root' co -d '$MR_REPO' '$repo'"
2094 hg_register = 
2095         url=`hg showconfig paths.default`
2096         echo "Registering mercurial repo url: $url in $MR_CONFIG"
2097         mr -c "$MR_CONFIG" config "`pwd`" checkout="hg clone '$url' '$MR_REPO'"
2098 darcs_register = 
2099         url=`cat _darcs/prefs/defaultrepo`
2100         echo "Registering darcs repository $url in $MR_CONFIG"
2101         mr -c "$MR_CONFIG" config "`pwd`" checkout="darcs get '$url' '$MR_REPO'"
2102 git_bare_register = 
2103         url="`LC_ALL=C GIT_CONFIG=config git config --get remote.origin.url`" || true
2104         if [ -z "$url" ]; then
2105                 error "cannot determine git url"
2106         fi
2107         echo "Registering git url: $url in $MR_CONFIG"
2108         mr -c "$MR_CONFIG" config "`pwd`" checkout="git clone --bare '$url' '$MR_REPO'"
2109 vcsh_register =
2110         url="`LC_ALL=C vcsh run "$MR_REPO" git config --get remote.origin.url`" || true
2111         if [ -z "$url" ]; then
2112                 error "cannot determine git url"
2113         fi
2114         echo "Registering git url: $url in $MR_CONFIG"
2115         mr -c "$MR_CONFIG" config "`pwd`" checkout="vcsh clone '$url' '$MR_REPO'"
2116 fossil_register =
2117         url=`fossil remote-url`
2118         repo=`fossil info | grep repository | sed -e 's/repository:*.//g' -e 's/ //g'`
2119         echo "Registering fossil repository $url in $MR_CONFIG"
2120         mr -c "$MR_CONFIG" config "`pwd`" checkout="mkdir -p '$MR_REPO' && cd '$MR_REPO' && fossil open '$repo'"
2121 veracity_register =
2122         url=`vv config | grep sync_targets | sed -e 's/sync_targets:*.//g' -e 's/ //g'`
2123         repo=`vv repo info | grep repository | sed -e 's/Current repository:*.//g' -e 's/ //g'`
2124         echo "Registering veracity repository $url in $MR_CONFIG"
2125         mr -c "$MR_CONFIG" config "`pwd`" checkout="mkdir -p '$MR_REPO' && cd '$MR_REPO' && vv checkout '$repo'"
2126
2127 svn_trusted_checkout = svn co $url $repo
2128 svn_alt_trusted_checkout = svn checkout $url $repo
2129 git_trusted_checkout = git clone $url $repo
2130 bzr_trusted_checkout = bzr checkout|clone|branch|get $url $repo
2131 # cvs: too hard
2132 hg_trusted_checkout = hg clone $url $repo
2133 darcs_trusted_checkout = darcs get $url $repo
2134 git_bare_trusted_checkout = git clone --bare $url $repo
2135 vcsh_old_trusted_checkout = vcsh run "$MR_REPO" git clone $url $repo
2136 vcsh_trusted_checkout = vcsh clone $url $repo
2137 # fossil: messy to do
2138 veracity_trusted_checkout = vv clone $url $repo
2139
2140
2141 list = true
2142 config = 
2143 bootstrap = 
2144
2145 online =
2146         if [ -s ~/.mrlog ]; then
2147                 info "running offline commands"
2148                 mv -f ~/.mrlog ~/.mrlog.old
2149                 if ! sh -e ~/.mrlog.old; then
2150                         error "offline command failed; left in ~/.mrlog.old"
2151                 fi
2152                 rm -f ~/.mrlog.old
2153         else
2154                 info "no offline commands to run"
2155         fi
2156 offline =
2157         umask 077
2158         touch ~/.mrlog
2159         info "offline mode enabled"
2160 remember =
2161         info "remembering command: 'mr $@'"
2162         command="mr -d '$(pwd)' $MR_SWITCHES"
2163         for w in "$@"; do
2164                 command="$command '$w'"
2165         done
2166         if [ ! -e ~/.mrlog ] || ! grep -q -F "$command" ~/.mrlog; then
2167                 echo "$command" >> ~/.mrlog
2168         fi
2169
2170 ed = echo "A horse is a horse, of course, of course.."
2171 T = echo "I pity the fool."
2172 right = echo "Not found."
2173
2174 # vim:sw=8:sts=0:ts=8:noet
2175 # Local variables:
2176 # indent-tabs-mode: t
2177 # cperl-indent-level: 8
2178 # End: