]> 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:

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