9 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 hook(type => "checkconfig", id => "git", call => sub { #{{{
15 if (! defined $config{gitorigin_branch}) {
16 $config{gitorigin_branch}="origin";
18 if (! defined $config{gitmaster_branch}) {
19 $config{gitmaster_branch}="master";
23 hook(type => "getsetup", id => "git", call => sub { #{{{
28 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
29 description => "gitweb url to show file history ([[file]] substituted)",
36 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_parent]];f=[[file]]",
37 description => "gitweb url to show a diff ([[sha1_to]], [[sha1_from]], [[sha1_parent]], and [[file]] substituted)",
44 description => "where to pull and push changes (unset to not pull/push)",
51 description => "branch that the wiki is stored in",
57 sub _safe_git (&@) { #{{{
58 # Start a child process safely without resorting /bin/sh.
59 # Return command output or success state (in scalar context).
61 my ($error_handler, @cmdline) = @_;
63 my $pid = open my $OUT, "-|";
65 error("Cannot fork: $!") if !defined $pid;
69 # Git commands want to be in wc.
71 or error("Cannot chdir to $config{srcdir}: $!");
72 exec @cmdline or error("Cannot exec '@cmdline': $!");
84 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
86 return wantarray ? @lines : ($? == 0);
88 # Convenient wrappers.
89 sub run_or_die ($@) { _safe_git(\&error, @_) }
90 sub run_or_cry ($@) { _safe_git(sub { warn @_ }, @_) }
91 sub run_or_non ($@) { _safe_git(undef, @_) }
94 sub _merge_past ($$$) { #{{{
95 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
96 # Git merge commands work with the committed changes, except in the
97 # implicit case of '-m' of git checkout(1). So we should invent a
98 # kludge here. In principle, we need to create a throw-away branch
99 # in preparing for the merge itself. Since branches are cheap (and
100 # branching is fast), this shouldn't cost high.
102 # The main problem is the presence of _uncommitted_ local changes. One
103 # possible approach to get rid of this situation could be that we first
104 # make a temporary commit in the master branch and later restore the
105 # initial state (this is possible since Git has the ability to undo a
106 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
109 # - create a diff of HEAD:current-sha1
111 # - create a dummy branch and switch to it
112 # - rewind to past (reset --hard to the current-sha1)
113 # - apply the diff and commit
114 # - switch to master and do the merge with the dummy branch
115 # - make a soft reset (undo the last commit of master)
117 # The above method has some drawbacks: (1) it needs a redundant commit
118 # just to get rid of local changes, (2) somewhat slow because of the
119 # required system forks. Until someone points a more straight method
120 # (which I would be grateful) I have implemented an alternative method.
121 # In this approach, we hide all the modified files from Git by renaming
122 # them (using the 'rename' builtin) and later restore those files in
123 # the throw-away branch (that is, we put the files themselves instead
124 # of applying a patch).
126 my ($sha1, $file, $message) = @_;
128 my @undo; # undo stack for cleanup in case of an error
129 my $conflict; # file content with conflict markers
132 # Hide local changes from Git by renaming the modified file.
133 # Relative paths must be converted to absolute for renaming.
134 my ($target, $hidden) = (
135 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
137 rename($target, $hidden)
138 or error("rename '$target' to '$hidden' failed: $!");
139 # Ensure to restore the renamed file on error.
141 return if ! -e "$hidden"; # already renamed
142 rename($hidden, $target)
143 or warn "rename '$hidden' to '$target' failed: $!";
146 my $branch = "throw_away_${sha1}"; # supposed to be unique
148 # Create a throw-away branch and rewind backward.
149 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
150 run_or_die('git', 'branch', $branch, $sha1);
152 # Switch to throw-away branch for the merge operation.
154 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
155 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
158 run_or_die('git', 'checkout', $branch);
160 # Put the modified file in _this_ branch.
161 rename($hidden, $target)
162 or error("rename '$hidden' to '$target' failed: $!");
164 # _Silently_ commit all modifications in the current branch.
165 run_or_non('git', 'commit', '-m', $message, '-a');
166 # ... and re-switch to master.
167 run_or_die('git', 'checkout', $config{gitmaster_branch});
169 # Attempt to merge without complaining.
170 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
171 $conflict = readfile($target);
172 run_or_die('git', 'reset', '--hard');
177 # Process undo stack (in reverse order). By policy cleanup
178 # actions should normally print a warning on failure.
179 while (my $handle = pop @undo) {
183 error("Git merge failed!\n$failure\n") if $failure;
188 sub _parse_diff_tree ($@) { #{{{
189 # Parse the raw diff tree chunk and return the info hash.
190 # See git-diff-tree(1) for the syntax.
192 my ($prefix, $dt_ref) = @_;
195 return if !defined @{ $dt_ref } ||
196 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
200 while (my $line = shift @{ $dt_ref }) {
201 return if $line !~ m/^(.+) ($sha1_pattern)/;
208 # Identification lines for the commit.
209 while (my $line = shift @{ $dt_ref }) {
210 # Regexps are semi-stolen from gitweb.cgi.
211 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
214 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
215 # XXX: collecting in reverse order
216 push @{ $ci{'parents'} }, $1;
218 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
219 my ($who, $name, $epoch, $tz) =
223 $ci{ "${who}_epoch" } = $epoch;
224 $ci{ "${who}_tz" } = $tz;
226 if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
227 $ci{"${who}_username"} = $1;
229 elsif ($name =~ m/^([^<]+)\s+<>$/) {
230 $ci{"${who}_username"} = $1;
233 $ci{"${who}_username"} = $name;
236 elsif ($line =~ m/^$/) {
237 # Trailing empty line signals next section.
242 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
244 if (defined $ci{'parents'}) {
245 $ci{'parent'} = @{ $ci{'parents'} }[0];
248 $ci{'parent'} = 0 x 40;
251 # Commit message (optional).
252 while ($dt_ref->[0] =~ /^ /) {
253 my $line = shift @{ $dt_ref };
255 push @{ $ci{'comment'} }, $line;
257 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
260 while (my $line = shift @{ $dt_ref }) {
262 (:+) # number of parents
263 ([^\t]+)\t # modes, sha1, status
266 my $num_parents = length $1;
267 my @tmp = split(" ", $2);
268 my ($file, $file_to) = split("\t", $3);
269 my @mode_from = splice(@tmp, 0, $num_parents);
270 my $mode_to = shift(@tmp);
271 my @sha1_from = splice(@tmp, 0, $num_parents);
272 my $sha1_to = shift(@tmp);
273 my $status = shift(@tmp);
275 if ($file =~ m/^"(.*)"$/) {
276 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
278 $file =~ s/^\Q$prefix\E//;
280 push @{ $ci{'details'} }, {
281 'file' => decode_utf8($file),
282 'sha1_from' => $sha1_from[0],
283 'sha1_to' => $sha1_to,
294 sub git_commit_info ($;$) { #{{{
295 # Return an array of commit info hashes of num commits (default: 1)
296 # starting from the given sha1sum.
298 my ($sha1, $num) = @_;
302 my @raw_lines = run_or_die('git', 'log', "--max-count=$num",
303 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
304 '-r', $sha1, '--', '.');
305 my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
308 while (my $parsed = _parse_diff_tree(($prefix or ""), \@raw_lines)) {
312 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
314 return wantarray ? @ci : $ci[0];
317 sub git_sha1 (;$) { #{{{
318 # Return head sha1sum (of given file).
320 my $file = shift || q{--};
322 # Ignore error since a non-existing file might be given.
323 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
326 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
327 } else { debug("Empty sha1sum for '$file'.") }
328 return defined $sha1 ? $sha1 : q{};
331 sub rcs_update () { #{{{
332 # Update working directory.
334 if (length $config{gitorigin_branch}) {
335 run_or_cry('git', 'pull', $config{gitorigin_branch});
339 sub rcs_prepedit ($) { #{{{
340 # Return the commit sha1sum of the file when editing begins.
341 # This will be later used in rcs_commit if a merge is required.
345 return git_sha1($file);
348 sub rcs_commit ($$$;$$) { #{{{
349 # Try to commit the page; returns undef on _success_ and
350 # a version of the page with the rcs's conflict markers on
353 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
355 # Check to see if the page has been changed by someone else since
356 # rcs_prepedit was called.
357 my $cur = git_sha1($file);
358 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
360 if (defined $cur && defined $prev && $cur ne $prev) {
361 my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
362 return $conflict if defined $conflict;
366 return rcs_commit_staged($message, $user, $ipaddr);
369 sub rcs_commit_staged ($$$) {
370 # Commits all staged changes. Changes can be staged using rcs_add,
371 # rcs_remove, and rcs_rename.
372 my ($message, $user, $ipaddr)=@_;
374 # Set the commit author and email to the web committer.
376 if (defined $user || defined $ipaddr) {
377 my $u=defined $user ? $user : $ipaddr;
378 $ENV{GIT_AUTHOR_NAME}=$u;
379 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
382 # git commit returns non-zero if file has not been really changed.
383 # so we should ignore its exit status (hence run_or_non).
384 $message = possibly_foolish_untaint($message);
385 if (run_or_non('git', 'commit', '--cleanup=verbatim',
386 '-q', '-m', $message)) {
387 if (length $config{gitorigin_branch}) {
388 run_or_cry('git', 'push', $config{gitorigin_branch});
393 return undef; # success
396 sub rcs_add ($) { # {{{
397 # Add file to archive.
401 run_or_cry('git', 'add', $file);
404 sub rcs_remove ($) { # {{{
405 # Remove file from archive.
409 run_or_cry('git', 'rm', '-f', $file);
412 sub rcs_rename ($$) { # {{{
413 my ($src, $dest) = @_;
415 run_or_cry('git', 'mv', '-f', $src, $dest);
418 sub rcs_recentchanges ($) { #{{{
419 # List of recent changes.
423 eval q{use Date::Parse};
427 foreach my $ci (git_commit_info('HEAD', $num)) {
428 # Skip redundant commits.
429 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
431 my ($sha1, $when) = (
433 $ci->{'author_epoch'}
437 foreach my $detail (@{ $ci->{'details'} }) {
438 my $file = $detail->{'file'};
440 my $diffurl = $config{'diffurl'};
441 $diffurl =~ s/\[\[file\]\]/$file/go;
442 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
443 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
444 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
447 page => pagename($file),
454 foreach my $line (@{$ci->{'comment'}}) {
455 $pastblank=1 if $line eq '';
456 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
457 push @messages, { line => $line };
460 my $user=$ci->{'author_username'};
461 my $web_commit = ($ci->{'author'} =~ /\@web>/);
463 # compatability code for old web commit messages
465 defined $messages[0] &&
466 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
467 $user = defined $2 ? "$2" : "$3";
468 $messages[0]->{line} = $4;
475 committype => $web_commit ? "web" : "git",
477 message => [@messages],
481 last if @rets >= $num;
487 sub rcs_diff ($) { #{{{
489 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
491 foreach my $line (run_or_non("git", "show", $sha1)) {
492 if (@lines || $line=~/^diff --git/) {
493 push @lines, $line."\n";
500 return join("", @lines);
504 sub rcs_getctime ($) { #{{{
506 # Remove srcdir prefix
507 $file =~ s/^\Q$config{srcdir}\E\/?//;
509 my $sha1 = git_sha1($file);
510 my $ci = git_commit_info($sha1);
511 my $ctime = $ci->{'author_epoch'};
512 debug("ctime for '$file': ". localtime($ctime));