7 use open qw{:utf8 :std};
11 my $origin_branch = 'origin'; # Git ref for main repository
12 my $master_branch = 'master'; # working branch
13 my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate Git sha1sums
14 my $dummy_commit_msg = 'dummy commit'; # message to skip in recent changes
15 my $web_commit_msg = qr/^web commit (by (\w+)|from (\d+\.\d+\.\d+\.\d+)):?(.*)/;
17 sub _safe_git (&@) { #{{{
18 # Start a child process safely without resorting /bin/sh.
19 # Return command output or success state (in scalar context).
21 my ($error_handler, @cmdline) = @_;
23 my $pid = open my $OUT, "-|";
25 error("Cannot fork: $!") if !defined $pid;
29 open STDERR, ">&STDOUT"
30 or error("Cannot dup STDOUT: $!");
31 # Git commands want to be in wc.
33 or error("Cannot chdir to $config{srcdir}: $!");
34 exec @cmdline or error("Cannot exec '@cmdline': $!");
46 ($error_handler || sub { })->("'@cmdline' failed: $!") if $?;
48 return wantarray ? @lines : ($? == 0);
50 # Convenient wrappers.
51 sub run_or_die ($@) { _safe_git(\&error, @_) }
52 sub run_or_cry ($@) { _safe_git(sub { warn @_ }, @_) }
53 sub run_or_non ($@) { _safe_git(undef, @_) }
56 sub _merge_past ($$$) { #{{{
57 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
58 # Git merge commands work with the committed changes, except in the
59 # implicit case of '-m' of git-checkout(1). So we should invent a
60 # kludge here. In principle, we need to create a throw-away branch
61 # in preparing for the merge itself. Since branches are cheap (and
62 # branching is fast), this shouldn't cost high.
64 # The main problem is the presence of _uncommitted_ local changes. One
65 # possible approach to get rid of this situation could be that we first
66 # make a temporary commit in the master branch and later restore the
67 # initial state (this is possible since Git has the ability to undo a
68 # commit, i.e. 'git-reset --soft HEAD^'). The method can be summarized
71 # - create a diff of HEAD:current-sha1
73 # - create a dummy branch and switch to it
74 # - rewind to past (reset --hard to the current-sha1)
75 # - apply the diff and commit
76 # - switch to master and do the merge with the dummy branch
77 # - make a soft reset (undo the last commit of master)
79 # The above method has some drawbacks: (1) it needs a redundant commit
80 # just to get rid of local changes, (2) somewhat slow because of the
81 # required system forks. Until someone points a more straight method
82 # (which I would be grateful) I have implemented an alternative method.
83 # In this approach, we hide all the modified files from Git by renaming
84 # them (using the 'rename' builtin) and later restore those files in
85 # the throw-away branch (that is, we put the files themselves instead
86 # of applying a patch).
88 my ($sha1, $file, $message) = @_;
90 my @undo; # undo stack for cleanup in case of an error
91 my $conflict; # file content with conflict markers
94 # Hide local changes from Git by renaming the modified file.
95 # Relative paths must be converted to absolute for renaming.
96 my ($target, $hidden) = (
97 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
99 rename($target, $hidden)
100 or error("rename '$target' to '$hidden' failed: $!");
101 # Ensure to restore the renamed file on error.
103 return if ! -e "$hidden"; # already renamed
104 rename($hidden, $target)
105 or warn "rename '$hidden' to '$target' failed: $!";
108 my $branch = "throw_away_${sha1}"; # supposed to be unique
110 # Create a throw-away branch and rewind backward.
111 push @undo, sub { run_or_cry('git-branch', '-D', $branch) };
112 run_or_die('git-branch', $branch, $sha1);
114 # Switch to throw-away branch for the merge operation.
116 if (!run_or_cry('git-checkout', $master_branch)) {
117 run_or_cry('git-checkout','-f',$master_branch);
120 run_or_die('git-checkout', $branch);
122 # Put the modified file in _this_ branch.
123 rename($hidden, $target)
124 or error("rename '$hidden' to '$target' failed: $!");
126 # _Silently_ commit all modifications in the current branch.
127 run_or_non('git-commit', '-m', $message, '-a');
128 # ... and re-switch to master.
129 run_or_die('git-checkout', $master_branch);
131 # Attempt to merge without complaining.
132 if (!run_or_non('git-pull', '--no-commit', '.', $branch)) {
133 $conflict = readfile($target);
134 run_or_die('git-reset', '--hard');
139 # Process undo stack (in reverse order). By policy cleanup
140 # actions should normally print a warning on failure.
141 while (my $handle = pop @undo) {
145 error("Git merge failed!\n$failure\n") if $failure;
150 sub _parse_diff_tree (@) { #{{{
151 # Parse the raw diff tree chunk and return the info hash.
152 # See git-diff-tree(1) for the syntax.
157 return if !defined @{ $dt_ref } || !length @{ $dt_ref }[0];
161 HEADER: while (my $line = shift @{ $dt_ref }) {
162 return if $line !~ m/^(.+) ($sha1_pattern)/;
169 # Identification lines for the commit.
170 IDENT: while (my $line = shift @{ $dt_ref }) {
171 # Regexps are semi-stolen from gitweb.cgi.
172 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
174 } elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
175 # XXX: collecting in reverse order
176 push @{ $ci{'parents'} }, $1;
177 } elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
178 my ($who, $name, $epoch, $tz) =
182 $ci{ "${who}_epoch" } = $epoch;
183 $ci{ "${who}_tz" } = $tz;
185 if ($name =~ m/^([^<]+) <([^@]+)/) {
186 my ($fullname, $username) = ($1, $2);
187 $ci{"${who}_fullname"} = $fullname;
188 $ci{"${who}_username"} = $username;
190 $ci{"${who}_fullname"} =
191 $ci{"${who}_username"} = $name;
193 } elsif ($line =~ m/^$/) {
194 # Trailing empty line signals next section.
199 error("No 'tree' or 'parents' seen in diff-tree output")
200 if !defined $ci{'tree'} || !defined $ci{'parents'};
202 $ci{'parent'} = @{ $ci{'parents'} }[0];
205 COMMENT: while (my $line = shift @{ $dt_ref }) {
206 if ($line =~ m/^$/) {
207 # Trailing empty line signals next section.
211 push @{ $ci{'comment'} }, $line;
215 FILE: while (my $line = shift @{ $dt_ref }) {
217 ([0-7]{6})[ ] # from mode
218 ([0-7]{6})[ ] # to mode
219 ($sha1_pattern)[ ] # from sha1
220 ($sha1_pattern)[ ] # to sha1
222 ([0-9]{0,3})\t # similarity
225 my ($sha1_from, $sha1_to, $file) =
228 if ($file =~ m/^"(.*)"$/) {
229 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
232 push @{ $ci{'details'} }, {
233 'file' => decode_utf8($file),
234 'sha1_from' => $sha1_from,
235 'sha1_to' => $sha1_to,
243 warn "No detail in diff-tree output" if !defined $ci{'details'};
248 sub git_commit_info (;$$) { #{{{
249 # Return an array of commit info hashes of num commits (default: 1)
250 # starting from the given sha1sum (default: HEAD).
252 my ($sha1, $num) = @_;
257 run_or_die(qq{git-rev-list --max-count=$num $sha1 |
258 git-diff-tree --stdin --pretty=raw -M -r});
261 while (my $parsed = _parse_diff_tree(\@raw_lines)) {
265 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
267 return wantarray ? @ci : $ci[0];
270 sub git_sha1 (;$) { #{{{
271 # Return head sha1sum (of given file).
273 my $file = shift || q{--};
275 # Ignore error since a non-existing file might be given.
276 my ($sha1) = run_or_non('git-rev-list', '--max-count=1', 'HEAD', $file);
278 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
279 } else { debug("Empty sha1sum for '$file'.") }
280 return defined $sha1 ? $sha1 : q{};
283 sub rcs_update () { #{{{
284 # Update working directory.
286 run_or_cry('git-pull', $origin_branch);
289 sub rcs_prepedit ($) { #{{{
290 # Return the commit sha1sum of the file when editing begins.
291 # This will be later used in rcs_commit if a merge is required.
295 return git_sha1($file);
298 sub rcs_commit ($$$) { #{{{
299 # Try to commit the page; returns undef on _success_ and
300 # a version of the page with the rcs's conflict markers on
303 my ($file, $message, $rcstoken) = @_;
305 # XXX: Wiki directory is in the unlocked state when starting this
306 # action. But it takes time for a Git process to finish its job
307 # (especially if a merge required), so we must re-lock to prevent
308 # race conditions. Only when the time of the real commit action
309 # (i.e. git-push(1)) comes, we'll unlock the directory.
312 # Check to see if the page has been changed by someone else since
313 # rcs_prepedit was called.
314 my $cur = git_sha1($file);
315 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
317 if (defined $cur && defined $prev && $cur ne $prev) {
318 my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
319 return $conflict if defined $conflict;
322 # git-commit(1) returns non-zero if file has not been really changed.
323 # so we should ignore its exit status (hence run_or_non).
324 $message = possibly_foolish_untaint($message);
325 if (run_or_non('git-commit', '-m', $message, '-i', $file)) {
327 run_or_cry('git-push', $origin_branch);
330 return undef; # success
333 sub rcs_add ($) { # {{{
334 # Add file to archive.
338 run_or_cry('git-add', $file);
341 sub rcs_recentchanges ($) { #{{{
342 # List of recent changes.
346 eval q{use Date::Parse};
349 my ($sha1, $type, $when, $diffurl, $user, @pages, @message, @rets);
350 INFO: foreach my $ci (git_commit_info('HEAD', $num)) {
351 my $title = @{ $ci->{'comment'} }[0];
353 # Skip redundant commits.
354 next INFO if ($title eq $dummy_commit_msg);
356 $sha1 = $ci->{'sha1'};
358 $when = time - $ci->{'author_epoch'};
360 DETAIL: foreach my $detail (@{ $ci->{'details'} }) {
361 my $diffurl = $config{'diffurl'};
362 my $file = $detail->{'file'};
364 $diffurl =~ s/\[\[file\]\]/$file/go;
365 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
366 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
367 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
370 page => pagename($file),
375 push @message, { line => $title };
377 if (defined $message[0] &&
378 $message[0]->{line} =~ m/$web_commit_msg/) {
379 $user=defined $2 ? "$2" : "$3";
380 $message[0]->{line}=$4;
383 $user = $ci->{'author_username'};
391 message => [@message],
395 $sha1 = $type = $when = $diffurl = $user = undef;
396 @pages = @message = ();
402 sub rcs_notify () { #{{{
403 # Send notification mail to subscribed users.
405 # In usual Git usage, hooks/update script is presumed to send
406 # notification mails (see git-receive-pack(1)). But we prefer
407 # hooks/post-update to support IkiWiki commits coming from a
408 # cloned repository (through command line) because post-update
409 # is called _after_ each ref in repository is updated (update
410 # hook is called _before_ the repository is updated). Since
411 # post-update hook does not accept command line arguments, we
412 # don't have an $ENV variable in this function.
414 # Here, we rely on a simple fact: we can extract all parts of the
415 # notification content by parsing the "HEAD" commit (which also
416 # triggers a refresh of IkiWiki pages) and we can obtain the diff
417 # by comparing HEAD and HEAD^ (the previous commit).
419 my $sha1 = 'HEAD'; # the commit which triggers this action
421 my $ci = git_commit_info($sha1);
422 return if !defined $ci;
424 my @changed_pages = map { $_->{'file'} } @{ $ci->{'details'} };
426 my ($user, $message);
427 if (@{ $ci->{'comment'} }[0] =~ m/$web_commit_msg/) {
428 $user = defined $2 ? "$2" : "$3";
431 $user = $ci->{'author_username'};
432 $message = join "\n", @{ $ci->{'comment'} };
435 require IkiWiki::UserInfo;
436 my @email_recipients = commit_notify_list($user, @changed_pages);
437 return if !@email_recipients;
439 # TODO: if a commit spans multiple pages, this will send
440 # subscribers a diff that might contain pages they did not
441 # sign up for. Should separate the diff per page and
442 # reassemble into one mail with just the pages subscribed to.
443 my $diff = join "\n", run_or_die('git-diff', "${sha1}^", $sha1);
445 my $subject = "$config{wikiname} update of ";
446 if (@changed_pages > 2) {
447 $subject .= "$changed_pages[0] $changed_pages[1] etc";
449 $subject .= join " ", @changed_pages;
451 $subject .= " by $user";
453 my $template = template("notifymail.tmpl");
455 wikiname => $config{wikiname},
461 eval q{use Mail::Sendmail};
463 foreach my $email (@email_recipients) {
466 From => "$config{wikiname} <$config{adminemail}>",
468 Message => $template->output,
469 ) or error("Failed to send update notification mail: $!");
473 sub rcs_getctime ($) { #{{{
474 # Get the ctime of file.
478 my $sha1 = git_sha1($file);
479 my $ci = git_commit_info($sha1);
480 my $ctime = $ci->{'author_epoch'};
481 debug("ctime for '$file': ". localtime($ctime) . "\n");