7 use open qw{:utf8 :std};
11 my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate Git sha1sums
12 my $dummy_commit_msg = 'dummy commit'; # message to skip in recent changes
14 sub _safe_git (&@) { #{{{
15 # Start a child process safely without resorting /bin/sh.
16 # Return command output or success state (in scalar context).
18 my ($error_handler, @cmdline) = @_;
20 my $pid = open my $OUT, "-|";
22 error("Cannot fork: $!") if !defined $pid;
26 # Git commands want to be in wc.
28 or error("Cannot chdir to $config{srcdir}: $!");
29 exec @cmdline or error("Cannot exec '@cmdline': $!");
41 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
43 return wantarray ? @lines : ($? == 0);
45 # Convenient wrappers.
46 sub run_or_die ($@) { _safe_git(\&error, @_) }
47 sub run_or_cry ($@) { _safe_git(sub { warn @_ }, @_) }
48 sub run_or_non ($@) { _safe_git(undef, @_) }
51 sub _merge_past ($$$) { #{{{
52 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
53 # Git merge commands work with the committed changes, except in the
54 # implicit case of '-m' of git checkout(1). So we should invent a
55 # kludge here. In principle, we need to create a throw-away branch
56 # in preparing for the merge itself. Since branches are cheap (and
57 # branching is fast), this shouldn't cost high.
59 # The main problem is the presence of _uncommitted_ local changes. One
60 # possible approach to get rid of this situation could be that we first
61 # make a temporary commit in the master branch and later restore the
62 # initial state (this is possible since Git has the ability to undo a
63 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
66 # - create a diff of HEAD:current-sha1
68 # - create a dummy branch and switch to it
69 # - rewind to past (reset --hard to the current-sha1)
70 # - apply the diff and commit
71 # - switch to master and do the merge with the dummy branch
72 # - make a soft reset (undo the last commit of master)
74 # The above method has some drawbacks: (1) it needs a redundant commit
75 # just to get rid of local changes, (2) somewhat slow because of the
76 # required system forks. Until someone points a more straight method
77 # (which I would be grateful) I have implemented an alternative method.
78 # In this approach, we hide all the modified files from Git by renaming
79 # them (using the 'rename' builtin) and later restore those files in
80 # the throw-away branch (that is, we put the files themselves instead
81 # of applying a patch).
83 my ($sha1, $file, $message) = @_;
85 my @undo; # undo stack for cleanup in case of an error
86 my $conflict; # file content with conflict markers
89 # Hide local changes from Git by renaming the modified file.
90 # Relative paths must be converted to absolute for renaming.
91 my ($target, $hidden) = (
92 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
94 rename($target, $hidden)
95 or error("rename '$target' to '$hidden' failed: $!");
96 # Ensure to restore the renamed file on error.
98 return if ! -e "$hidden"; # already renamed
99 rename($hidden, $target)
100 or warn "rename '$hidden' to '$target' failed: $!";
103 my $branch = "throw_away_${sha1}"; # supposed to be unique
105 # Create a throw-away branch and rewind backward.
106 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
107 run_or_die('git', 'branch', $branch, $sha1);
109 # Switch to throw-away branch for the merge operation.
111 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
112 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
115 run_or_die('git', 'checkout', $branch);
117 # Put the modified file in _this_ branch.
118 rename($hidden, $target)
119 or error("rename '$hidden' to '$target' failed: $!");
121 # _Silently_ commit all modifications in the current branch.
122 run_or_non('git', 'commit', '-m', $message, '-a');
123 # ... and re-switch to master.
124 run_or_die('git', 'checkout', $config{gitmaster_branch});
126 # Attempt to merge without complaining.
127 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
128 $conflict = readfile($target);
129 run_or_die('git', 'reset', '--hard');
134 # Process undo stack (in reverse order). By policy cleanup
135 # actions should normally print a warning on failure.
136 while (my $handle = pop @undo) {
140 error("Git merge failed!\n$failure\n") if $failure;
145 sub _parse_diff_tree ($@) { #{{{
146 # Parse the raw diff tree chunk and return the info hash.
147 # See git-diff-tree(1) for the syntax.
149 my ($prefix, $dt_ref) = @_;
152 return if !defined @{ $dt_ref } ||
153 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
157 while (my $line = shift @{ $dt_ref }) {
158 return if $line !~ m/^(.+) ($sha1_pattern)/;
165 # Identification lines for the commit.
166 while (my $line = shift @{ $dt_ref }) {
167 # Regexps are semi-stolen from gitweb.cgi.
168 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
171 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
172 # XXX: collecting in reverse order
173 push @{ $ci{'parents'} }, $1;
175 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
176 my ($who, $name, $epoch, $tz) =
180 $ci{ "${who}_epoch" } = $epoch;
181 $ci{ "${who}_tz" } = $tz;
183 if ($name =~ m/^([^<]+) <([^@>]+)/) {
184 my ($fullname, $username) = ($1, $2);
185 $ci{"${who}_fullname"} = $fullname;
186 $ci{"${who}_username"} = $username;
189 $ci{"${who}_fullname"} =
190 $ci{"${who}_username"} = $name;
193 elsif ($line =~ m/^$/) {
194 # Trailing empty line signals next section.
199 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
201 if (defined $ci{'parents'}) {
202 $ci{'parent'} = @{ $ci{'parents'} }[0];
205 $ci{'parent'} = 0 x 40;
209 while (my $line = shift @{ $dt_ref }) {
210 if ($line =~ m/^$/) {
211 # Trailing empty line signals next section.
215 push @{ $ci{'comment'} }, $line;
219 while (my $line = shift @{ $dt_ref }) {
221 (:+) # number of parents
222 ([^\t]+)\t # modes, sha1, status
225 my $num_parents = length $1;
226 my @tmp = split(" ", $2);
227 my ($file, $file_to) = split("\t", $3);
228 my @mode_from = splice(@tmp, 0, $num_parents);
229 my $mode_to = shift(@tmp);
230 my @sha1_from = splice(@tmp, 0, $num_parents);
231 my $sha1_to = shift(@tmp);
232 my $status = shift(@tmp);
234 if ($file =~ m/^"(.*)"$/) {
235 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
237 $file =~ s/^\Q$prefix\E//;
239 push @{ $ci{'details'} }, {
240 'file' => decode_utf8($file),
241 'sha1_from' => $sha1_from[0],
242 'sha1_to' => $sha1_to,
250 debug("No detail in diff-tree output") if !defined $ci{'details'};
255 sub git_commit_info ($;$) { #{{{
256 # Return an array of commit info hashes of num commits (default: 1)
257 # starting from the given sha1sum.
259 my ($sha1, $num) = @_;
263 my @raw_lines = run_or_die('git', 'log', "--max-count=$num",
264 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
265 '-r', $sha1, '--', '.');
266 my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
269 while (my $parsed = _parse_diff_tree(($prefix or ""), \@raw_lines)) {
273 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
275 return wantarray ? @ci : $ci[0];
278 sub git_sha1 (;$) { #{{{
279 # Return head sha1sum (of given file).
281 my $file = shift || q{--};
283 # Ignore error since a non-existing file might be given.
284 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD', $file);
286 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
287 } else { debug("Empty sha1sum for '$file'.") }
288 return defined $sha1 ? $sha1 : q{};
291 sub rcs_update () { #{{{
292 # Update working directory.
294 if (length $config{gitorigin_branch}) {
295 run_or_cry('git', 'pull', $config{gitorigin_branch});
299 sub rcs_prepedit ($) { #{{{
300 # Return the commit sha1sum of the file when editing begins.
301 # This will be later used in rcs_commit if a merge is required.
305 return git_sha1($file);
308 sub rcs_commit ($$$;$$) { #{{{
309 # Try to commit the page; returns undef on _success_ and
310 # a version of the page with the rcs's conflict markers on
313 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
316 $message = "web commit by $user" .
317 (length $message ? ": $message" : "");
319 elsif (defined $ipaddr) {
320 $message = "web commit from $ipaddr" .
321 (length $message ? ": $message" : "");
324 # XXX: Wiki directory is in the unlocked state when starting this
325 # action. But it takes time for a Git process to finish its job
326 # (especially if a merge required), so we must re-lock to prevent
327 # race conditions. Only when the time of the real commit action
328 # (i.e. git push) comes, we'll unlock the directory.
331 # Check to see if the page has been changed by someone else since
332 # rcs_prepedit was called.
333 my $cur = git_sha1($file);
334 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
336 if (defined $cur && defined $prev && $cur ne $prev) {
337 my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
338 return $conflict if defined $conflict;
341 # git commit returns non-zero if file has not been really changed.
342 # so we should ignore its exit status (hence run_or_non).
343 $message = possibly_foolish_untaint($message);
344 if (run_or_non('git', 'commit', '-q', '-m', $message, '-i', $file)) {
346 if (length $config{gitorigin_branch}) {
347 run_or_cry('git', 'push', $config{gitorigin_branch});
351 return undef; # success
354 sub rcs_add ($) { # {{{
355 # Add file to archive.
359 run_or_cry('git', 'add', $file);
362 sub rcs_recentchanges ($) { #{{{
363 # List of recent changes.
367 eval q{use Date::Parse};
371 foreach my $ci (git_commit_info('HEAD', $num)) {
372 # Skip redundant commits.
373 next if (@{$ci->{'comment'}}[0] eq $dummy_commit_msg);
375 my ($sha1, $when) = (
377 time - $ci->{'author_epoch'}
380 my (@pages, @messages);
381 foreach my $detail (@{ $ci->{'details'} }) {
382 my $file = $detail->{'file'};
384 my $diffurl = $config{'diffurl'};
385 $diffurl =~ s/\[\[file\]\]/$file/go;
386 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
387 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
388 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
391 page => pagename($file),
395 push @messages, { line => $_ } foreach @{$ci->{'comment'}};
397 my ($user, $type) = (q{}, "web");
399 if (defined $messages[0] &&
400 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
401 $user = defined $2 ? "$2" : "$3";
402 $messages[0]->{line} = $4;
406 $user = $ci->{'author_username'};
414 message => [@messages],
418 last if @rets >= $num;
424 sub rcs_notify () { #{{{
425 # Send notification mail to subscribed users.
427 # In usual Git usage, hooks/update script is presumed to send
428 # notification mails (see git-receive-pack(1)). But we prefer
429 # hooks/post-update to support IkiWiki commits coming from a
430 # cloned repository (through command line) because post-update
431 # is called _after_ each ref in repository is updated (update
432 # hook is called _before_ the repository is updated). Since
433 # post-update hook does not accept command line arguments, we
434 # don't have an $ENV variable in this function.
436 # Here, we rely on a simple fact: we can extract all parts of the
437 # notification content by parsing the "HEAD" commit (which also
438 # triggers a refresh of IkiWiki pages).
440 my $ci = git_commit_info('HEAD');
441 return if !defined $ci;
443 my @changed_pages = map { $_->{'file'} } @{ $ci->{'details'} };
445 my ($user, $message);
446 if (@{ $ci->{'comment'} }[0] =~ m/$config{web_commit_regexp}/) {
447 $user = defined $2 ? "$2" : "$3";
451 $user = $ci->{'author_username'};
452 $message = join "\n", @{ $ci->{'comment'} };
455 my $sha1 = $ci->{'sha1'};
457 require IkiWiki::UserInfo;
463 join "\n", run_or_die('git', 'diff', "${sha1}^", $sha1);
464 }, $user, @changed_pages
468 sub rcs_getctime ($) { #{{{
470 # Remove srcdir prefix
471 $file =~ s/^\Q$config{srcdir}\E\/?//;
473 my $sha1 = git_sha1($file);
474 my $ci = git_commit_info($sha1);
475 my $ctime = $ci->{'author_epoch'};
476 debug("ctime for '$file': ". localtime($ctime));