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
16 sub _safe_git (&@) { #{{{
17 # Start a child process safely without resorting /bin/sh.
18 # Return command output or success state (in scalar context).
20 my ($error_handler, @cmdline) = @_;
22 my $pid = open my $OUT, "-|";
24 error("Cannot fork: $!") if !defined $pid;
28 open STDERR, ">&STDOUT"
29 or error("Cannot dup STDOUT: $!");
30 # Git commands want to be in wc.
32 or error("Cannot chdir to $config{srcdir}: $!");
33 exec @cmdline or error("Cannot exec '@cmdline': $!");
45 ($error_handler || sub { })->("'@cmdline' failed: $!") if $?;
47 return wantarray ? @lines : ($? == 0);
49 # Convenient wrappers.
50 sub run_or_die ($@) { _safe_git(\&error, @_) }
51 sub run_or_cry ($@) { _safe_git(sub { warn @_ }, @_) }
52 sub run_or_non ($@) { _safe_git(undef, @_) }
55 sub _merge_past ($$$) { #{{{
56 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
57 # Git merge commands work with the committed changes, except in the
58 # implicit case of '-m' of git-checkout(1). So we should invent a
59 # kludge here. In principle, we need to create a throw-away branch
60 # in preparing for the merge itself. Since branches are cheap (and
61 # branching is fast), this shouldn't cost high.
63 # The main problem is the presence of _uncommitted_ local changes. One
64 # possible approach to get rid of this situation could be that we first
65 # make a temporary commit in the master branch and later restore the
66 # initial state (this is possible since Git has the ability to undo a
67 # commit, i.e. 'git-reset --soft HEAD^'). The method can be summarized
70 # - create a diff of HEAD:current-sha1
72 # - create a dummy branch and switch to it
73 # - rewind to past (reset --hard to the current-sha1)
74 # - apply the diff and commit
75 # - switch to master and do the merge with the dummy branch
76 # - make a soft reset (undo the last commit of master)
78 # The above method has some drawbacks: (1) it needs a redundant commit
79 # just to get rid of local changes, (2) somewhat slow because of the
80 # required system forks. Until someone points a more straight method
81 # (which I would be grateful) I have implemented an alternative method.
82 # In this approach, we hide all the modified files from Git by renaming
83 # them (using the 'rename' builtin) and later restore those files in
84 # the throw-away branch (that is, we put the files themselves instead
85 # of applying a patch).
87 my ($sha1, $file, $message) = @_;
89 my @undo; # undo stack for cleanup in case of an error
90 my $conflict; # file content with conflict markers
93 # Hide local changes from Git by renaming the modified file.
94 # Relative paths must be converted to absolute for renaming.
95 my ($target, $hidden) = (
96 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
98 rename($target, $hidden)
99 or error("rename '$target' to '$hidden' failed: $!");
100 # Ensure to restore the renamed file on error.
102 return if ! -e "$hidden"; # already renamed
103 rename($hidden, $target)
104 or warn "rename '$hidden' to '$target' failed: $!";
107 my $branch = "throw_away_${sha1}"; # supposed to be unique
109 # Create a throw-away branch and rewind backward.
110 push @undo, sub { run_or_cry('git-branch', '-D', $branch) };
111 run_or_die('git-branch', $branch, $sha1);
113 # Switch to throw-away branch for the merge operation.
115 if (!run_or_cry('git-checkout', $master_branch)) {
116 run_or_cry('git-checkout','-f',$master_branch);
119 run_or_die('git-checkout', $branch);
121 # Put the modified file in _this_ branch.
122 rename($hidden, $target)
123 or error("rename '$hidden' to '$target' failed: $!");
125 # _Silently_ commit all modifications in the current branch.
126 run_or_non('git-commit', '-m', $message, '-a');
127 # ... and re-switch to master.
128 run_or_die('git-checkout', $master_branch);
130 # Attempt to merge without complaining.
131 if (!run_or_non('git-pull', '--no-commit', '.', $branch)) {
132 $conflict = readfile($target);
133 run_or_die('git-reset', '--hard');
138 # Process undo stack (in reverse order). By policy cleanup
139 # actions should normally print a warning on failure.
140 while (my $handle = pop @undo) {
144 error("Git merge failed!\n$failure\n") if $failure;
149 sub _parse_diff_tree (@) { #{{{
150 # Parse the raw diff tree chunk and return the info hash.
151 # See git-diff-tree(1) for the syntax.
156 return if !defined @{ $dt_ref } || !length @{ $dt_ref }[0];
160 HEADER: while (my $line = shift @{ $dt_ref }) {
161 return if $line !~ m/^(.+) ($sha1_pattern)/;
168 # Identification lines for the commit.
169 IDENT: while (my $line = shift @{ $dt_ref }) {
170 # Regexps are semi-stolen from gitweb.cgi.
171 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
173 } elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
174 # XXX: collecting in reverse order
175 push @{ $ci{'parents'} }, $1;
176 } elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
177 my ($who, $name, $epoch, $tz) =
181 $ci{ "${who}_epoch" } = $epoch;
182 $ci{ "${who}_tz" } = $tz;
184 if ($name =~ m/^([^<]+) <([^@]+)/) {
185 my ($fullname, $username) = ($1, $2);
186 $ci{"${who}_fullname"} = $fullname;
187 $ci{"${who}_username"} = $username;
189 $ci{"${who}_fullname"} =
190 $ci{"${who}_username"} = $name;
192 } elsif ($line =~ m/^$/) {
193 # Trailing empty line signals next section.
198 error("No 'tree' or 'parents' seen in diff-tree output")
199 if !defined $ci{'tree'} || !defined $ci{'parents'};
201 $ci{'parent'} = @{ $ci{'parents'} }[0];
204 COMMENT: while (my $line = shift @{ $dt_ref }) {
205 if ($line =~ m/^$/) {
206 # Trailing empty line signals next section.
210 push @{ $ci{'comment'} }, $line;
214 FILE: while (my $line = shift @{ $dt_ref }) {
216 ([0-7]{6})[ ] # from mode
217 ([0-7]{6})[ ] # to mode
218 ($sha1_pattern)[ ] # from sha1
219 ($sha1_pattern)[ ] # to sha1
221 ([0-9]{0,3})\t # similarity
224 my ($sha1_from, $sha1_to, $file) =
227 if ($file =~ m/^"(.*)"$/) {
228 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
231 push @{ $ci{'details'} }, {
232 'file' => decode_utf8($file),
233 'sha1_from' => $sha1_from,
234 'sha1_to' => $sha1_to,
242 warn "No detail in diff-tree output" if !defined $ci{'details'};
247 sub git_commit_info (;$$) { #{{{
248 # Return an array of commit info hashes of num commits (default: 1)
249 # starting from the given sha1sum (default: HEAD).
251 my ($sha1, $num) = @_;
256 run_or_die(qq{git-rev-list --max-count=$num $sha1 |
257 git-diff-tree --stdin --pretty=raw -M -r});
260 while (my $parsed = _parse_diff_tree(\@raw_lines)) {
264 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
266 return wantarray ? @ci : $ci[0];
269 sub git_sha1 (;$) { #{{{
270 # Return head sha1sum (of given file).
272 my $file = shift || q{--};
274 # Ignore error since a non-existing file might be given.
275 my ($sha1) = run_or_non('git-rev-list', '--max-count=1', 'HEAD', $file);
277 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
278 } else { debug("Empty sha1sum for '$file'.") }
279 return defined $sha1 ? $sha1 : q{};
282 sub rcs_update () { #{{{
283 # Update working directory.
285 run_or_cry('git-pull', $origin_branch);
288 sub rcs_prepedit ($) { #{{{
289 # Return the commit sha1sum of the file when editing begins.
290 # This will be later used in rcs_commit if a merge is required.
294 return git_sha1($file);
297 sub rcs_commit ($$$) { #{{{
298 # Try to commit the page; returns undef on _success_ and
299 # a version of the page with the rcs's conflict markers on
302 my ($file, $message, $rcstoken) = @_;
304 # XXX: Wiki directory is in the unlocked state when starting this
305 # action. But it takes time for a Git process to finish its job
306 # (especially if a merge required), so we must re-lock to prevent
307 # race conditions. Only when the time of the real commit action
308 # (i.e. git-push(1)) comes, we'll unlock the directory.
311 # Check to see if the page has been changed by someone else since
312 # rcs_prepedit was called.
313 my $cur = git_sha1($file);
314 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
316 if (defined $cur && defined $prev && $cur ne $prev) {
317 my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
318 return $conflict if defined $conflict;
321 # git-commit(1) returns non-zero if file has not been really changed.
322 # so we should ignore its exit status (hence run_or_non).
323 $message = possibly_foolish_untaint($message);
324 if (run_or_non('git-commit', '-m', $message, '-i', $file)) {
326 run_or_cry('git-push', $origin_branch);
329 return undef; # success
332 sub rcs_add ($) { # {{{
333 # Add file to archive.
337 run_or_cry('git-add', $file);
340 sub rcs_recentchanges ($) { #{{{
341 # List of recent changes.
345 eval q{use Date::Parse};
348 my ($sha1, $type, $when, $diffurl, $user, @pages, @message, @rets);
349 INFO: foreach my $ci (git_commit_info('HEAD', $num)) {
350 my $title = @{ $ci->{'comment'} }[0];
352 # Skip redundant commits.
353 next INFO if ($title eq $dummy_commit_msg);
355 $sha1 = $ci->{'sha1'};
357 $when = time - $ci->{'author_epoch'};
359 DETAIL: foreach my $detail (@{ $ci->{'details'} }) {
360 my $diffurl = $config{'diffurl'};
361 my $file = $detail->{'file'};
363 $diffurl =~ s/\[\[file\]\]/$file/go;
364 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
365 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
366 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
369 page => pagename($file),
374 push @message, { line => $title };
376 if (defined $message[0] &&
377 $message[0]->{line} =~ m/$config{web_commit_regexp}/) {
378 $user=defined $2 ? "$2" : "$3";
379 $message[0]->{line}=$4;
382 $user = $ci->{'author_username'};
390 message => [@message],
394 $sha1 = $type = $when = $diffurl = $user = undef;
395 @pages = @message = ();
401 sub rcs_notify () { #{{{
402 # Send notification mail to subscribed users.
404 # In usual Git usage, hooks/update script is presumed to send
405 # notification mails (see git-receive-pack(1)). But we prefer
406 # hooks/post-update to support IkiWiki commits coming from a
407 # cloned repository (through command line) because post-update
408 # is called _after_ each ref in repository is updated (update
409 # hook is called _before_ the repository is updated). Since
410 # post-update hook does not accept command line arguments, we
411 # don't have an $ENV variable in this function.
413 # Here, we rely on a simple fact: we can extract all parts of the
414 # notification content by parsing the "HEAD" commit (which also
415 # triggers a refresh of IkiWiki pages) and we can obtain the diff
416 # by comparing HEAD and HEAD^ (the previous commit).
418 my $sha1 = 'HEAD'; # the commit which triggers this action
420 my $ci = git_commit_info($sha1);
421 return if !defined $ci;
423 my @changed_pages = map { $_->{'file'} } @{ $ci->{'details'} };
425 my ($user, $message);
426 if (@{ $ci->{'comment'} }[0] =~ m/$config{web_commit_regexp}/) {
427 $user = defined $2 ? "$2" : "$3";
430 $user = $ci->{'author_username'};
431 $message = join "\n", @{ $ci->{'comment'} };
434 require IkiWiki::UserInfo;
440 join "\n", run_or_die('git-diff', "${sha1}^", $sha1);
441 }, $user, @changed_pages);
444 sub rcs_getctime ($) { #{{{
445 # Get the ctime of file.
449 my $sha1 = git_sha1($file);
450 my $ci = git_commit_info($sha1);
451 my $ctime = $ci->{'author_epoch'};
452 debug("ctime for '$file': ". localtime($ctime) . "\n");