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

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