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{diffurl}) {
18 if (! defined $config{gitorigin_branch}) {
19 $config{gitorigin_branch}="origin";
21 if (! defined $config{gitmaster_branch}) {
22 $config{gitmaster_branch}="master";
24 if (exists $config{git_wrapper}) {
25 push @{$config{wrappers}}, {
26 wrapper => $config{git_wrapper},
27 wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
32 hook(type => "getsetup", id => "git", call => sub { #{{{
36 example => "/git/wiki.git/hooks/post-update",
37 description => "git post-update executable to generate",
44 description => "mode for git_wrapper (can safely be made suid)",
50 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
51 description => "gitweb url to show file history ([[file]] substituted)",
57 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_parent]];f=[[file]]",
58 description => "gitweb url to show a diff ([[sha1_to]], [[sha1_from]], [[sha1_parent]], and [[file]] substituted)",
65 description => "where to pull and push changes (set to empty string to disable)",
72 description => "branch that the wiki is stored in",
78 sub _safe_git (&@) { #{{{
79 # Start a child process safely without resorting /bin/sh.
80 # Return command output or success state (in scalar context).
82 my ($error_handler, @cmdline) = @_;
84 my $pid = open my $OUT, "-|";
86 error("Cannot fork: $!") if !defined $pid;
90 # Git commands want to be in wc.
92 or error("Cannot chdir to $config{srcdir}: $!");
93 exec @cmdline or error("Cannot exec '@cmdline': $!");
105 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
107 return wantarray ? @lines : ($? == 0);
109 # Convenient wrappers.
110 sub run_or_die ($@) { _safe_git(\&error, @_) }
111 sub run_or_cry ($@) { _safe_git(sub { warn @_ }, @_) }
112 sub run_or_non ($@) { _safe_git(undef, @_) }
115 sub _merge_past ($$$) { #{{{
116 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
117 # Git merge commands work with the committed changes, except in the
118 # implicit case of '-m' of git checkout(1). So we should invent a
119 # kludge here. In principle, we need to create a throw-away branch
120 # in preparing for the merge itself. Since branches are cheap (and
121 # branching is fast), this shouldn't cost high.
123 # The main problem is the presence of _uncommitted_ local changes. One
124 # possible approach to get rid of this situation could be that we first
125 # make a temporary commit in the master branch and later restore the
126 # initial state (this is possible since Git has the ability to undo a
127 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
130 # - create a diff of HEAD:current-sha1
132 # - create a dummy branch and switch to it
133 # - rewind to past (reset --hard to the current-sha1)
134 # - apply the diff and commit
135 # - switch to master and do the merge with the dummy branch
136 # - make a soft reset (undo the last commit of master)
138 # The above method has some drawbacks: (1) it needs a redundant commit
139 # just to get rid of local changes, (2) somewhat slow because of the
140 # required system forks. Until someone points a more straight method
141 # (which I would be grateful) I have implemented an alternative method.
142 # In this approach, we hide all the modified files from Git by renaming
143 # them (using the 'rename' builtin) and later restore those files in
144 # the throw-away branch (that is, we put the files themselves instead
145 # of applying a patch).
147 my ($sha1, $file, $message) = @_;
149 my @undo; # undo stack for cleanup in case of an error
150 my $conflict; # file content with conflict markers
153 # Hide local changes from Git by renaming the modified file.
154 # Relative paths must be converted to absolute for renaming.
155 my ($target, $hidden) = (
156 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
158 rename($target, $hidden)
159 or error("rename '$target' to '$hidden' failed: $!");
160 # Ensure to restore the renamed file on error.
162 return if ! -e "$hidden"; # already renamed
163 rename($hidden, $target)
164 or warn "rename '$hidden' to '$target' failed: $!";
167 my $branch = "throw_away_${sha1}"; # supposed to be unique
169 # Create a throw-away branch and rewind backward.
170 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
171 run_or_die('git', 'branch', $branch, $sha1);
173 # Switch to throw-away branch for the merge operation.
175 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
176 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
179 run_or_die('git', 'checkout', $branch);
181 # Put the modified file in _this_ branch.
182 rename($hidden, $target)
183 or error("rename '$hidden' to '$target' failed: $!");
185 # _Silently_ commit all modifications in the current branch.
186 run_or_non('git', 'commit', '-m', $message, '-a');
187 # ... and re-switch to master.
188 run_or_die('git', 'checkout', $config{gitmaster_branch});
190 # Attempt to merge without complaining.
191 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
192 $conflict = readfile($target);
193 run_or_die('git', 'reset', '--hard');
198 # Process undo stack (in reverse order). By policy cleanup
199 # actions should normally print a warning on failure.
200 while (my $handle = pop @undo) {
204 error("Git merge failed!\n$failure\n") if $failure;
209 sub _parse_diff_tree ($@) { #{{{
210 # Parse the raw diff tree chunk and return the info hash.
211 # See git-diff-tree(1) for the syntax.
213 my ($prefix, $dt_ref) = @_;
216 return if !defined @{ $dt_ref } ||
217 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
221 while (my $line = shift @{ $dt_ref }) {
222 return if $line !~ m/^(.+) ($sha1_pattern)/;
229 # Identification lines for the commit.
230 while (my $line = shift @{ $dt_ref }) {
231 # Regexps are semi-stolen from gitweb.cgi.
232 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
235 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
236 # XXX: collecting in reverse order
237 push @{ $ci{'parents'} }, $1;
239 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
240 my ($who, $name, $epoch, $tz) =
244 $ci{ "${who}_epoch" } = $epoch;
245 $ci{ "${who}_tz" } = $tz;
247 if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
248 $ci{"${who}_username"} = $1;
250 elsif ($name =~ m/^([^<]+)\s+<>$/) {
251 $ci{"${who}_username"} = $1;
254 $ci{"${who}_username"} = $name;
257 elsif ($line =~ m/^$/) {
258 # Trailing empty line signals next section.
263 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
265 if (defined $ci{'parents'}) {
266 $ci{'parent'} = @{ $ci{'parents'} }[0];
269 $ci{'parent'} = 0 x 40;
272 # Commit message (optional).
273 while ($dt_ref->[0] =~ /^ /) {
274 my $line = shift @{ $dt_ref };
276 push @{ $ci{'comment'} }, $line;
278 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
281 while (my $line = shift @{ $dt_ref }) {
283 (:+) # number of parents
284 ([^\t]+)\t # modes, sha1, status
287 my $num_parents = length $1;
288 my @tmp = split(" ", $2);
289 my ($file, $file_to) = split("\t", $3);
290 my @mode_from = splice(@tmp, 0, $num_parents);
291 my $mode_to = shift(@tmp);
292 my @sha1_from = splice(@tmp, 0, $num_parents);
293 my $sha1_to = shift(@tmp);
294 my $status = shift(@tmp);
296 if ($file =~ m/^"(.*)"$/) {
297 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
299 $file =~ s/^\Q$prefix\E//;
301 push @{ $ci{'details'} }, {
302 'file' => decode_utf8($file),
303 'sha1_from' => $sha1_from[0],
304 'sha1_to' => $sha1_to,
315 sub git_commit_info ($;$) { #{{{
316 # Return an array of commit info hashes of num commits (default: 1)
317 # starting from the given sha1sum.
319 my ($sha1, $num) = @_;
323 my @raw_lines = run_or_die('git', 'log', "--max-count=$num",
324 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
325 '-r', $sha1, '--', '.');
326 my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
329 while (my $parsed = _parse_diff_tree(($prefix or ""), \@raw_lines)) {
333 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
335 return wantarray ? @ci : $ci[0];
338 sub git_sha1 (;$) { #{{{
339 # Return head sha1sum (of given file).
341 my $file = shift || q{--};
343 # Ignore error since a non-existing file might be given.
344 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
347 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
348 } else { debug("Empty sha1sum for '$file'.") }
349 return defined $sha1 ? $sha1 : q{};
352 sub rcs_update () { #{{{
353 # Update working directory.
355 if (length $config{gitorigin_branch}) {
356 run_or_cry('git', 'pull', $config{gitorigin_branch});
360 sub rcs_prepedit ($) { #{{{
361 # Return the commit sha1sum of the file when editing begins.
362 # This will be later used in rcs_commit if a merge is required.
366 return git_sha1($file);
369 sub rcs_commit ($$$;$$) { #{{{
370 # Try to commit the page; returns undef on _success_ and
371 # a version of the page with the rcs's conflict markers on
374 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
376 # Check to see if the page has been changed by someone else since
377 # rcs_prepedit was called.
378 my $cur = git_sha1($file);
379 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
381 if (defined $cur && defined $prev && $cur ne $prev) {
382 my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
383 return $conflict if defined $conflict;
387 return rcs_commit_staged($message, $user, $ipaddr);
390 sub rcs_commit_staged ($$$) {
391 # Commits all staged changes. Changes can be staged using rcs_add,
392 # rcs_remove, and rcs_rename.
393 my ($message, $user, $ipaddr)=@_;
395 # Set the commit author and email to the web committer.
397 if (defined $user || defined $ipaddr) {
398 my $u=defined $user ? $user : $ipaddr;
399 $ENV{GIT_AUTHOR_NAME}=$u;
400 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
403 # git commit returns non-zero if file has not been really changed.
404 # so we should ignore its exit status (hence run_or_non).
405 $message = possibly_foolish_untaint($message);
406 if (run_or_non('git', 'commit', '--cleanup=verbatim',
407 '-q', '-m', $message)) {
408 if (length $config{gitorigin_branch}) {
409 run_or_cry('git', 'push', $config{gitorigin_branch});
414 return undef; # success
417 sub rcs_add ($) { # {{{
418 # Add file to archive.
422 run_or_cry('git', 'add', $file);
425 sub rcs_remove ($) { # {{{
426 # Remove file from archive.
430 run_or_cry('git', 'rm', '-f', $file);
433 sub rcs_rename ($$) { # {{{
434 my ($src, $dest) = @_;
436 run_or_cry('git', 'mv', '-f', $src, $dest);
439 sub rcs_recentchanges ($) { #{{{
440 # List of recent changes.
444 eval q{use Date::Parse};
448 foreach my $ci (git_commit_info('HEAD', $num)) {
449 # Skip redundant commits.
450 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
452 my ($sha1, $when) = (
454 $ci->{'author_epoch'}
458 foreach my $detail (@{ $ci->{'details'} }) {
459 my $file = $detail->{'file'};
461 my $diffurl = $config{'diffurl'};
462 $diffurl =~ s/\[\[file\]\]/$file/go;
463 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
464 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
465 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
468 page => pagename($file),
475 foreach my $line (@{$ci->{'comment'}}) {
476 $pastblank=1 if $line eq '';
477 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
478 push @messages, { line => $line };
481 my $user=$ci->{'author_username'};
482 my $web_commit = ($ci->{'author'} =~ /\@web>/);
484 # compatability code for old web commit messages
486 defined $messages[0] &&
487 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
488 $user = defined $2 ? "$2" : "$3";
489 $messages[0]->{line} = $4;
496 committype => $web_commit ? "web" : "git",
498 message => [@messages],
502 last if @rets >= $num;
508 sub rcs_diff ($) { #{{{
510 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
512 foreach my $line (run_or_non("git", "show", $sha1)) {
513 if (@lines || $line=~/^diff --git/) {
514 push @lines, $line."\n";
521 return join("", @lines);
525 sub rcs_getctime ($) { #{{{
527 # Remove srcdir prefix
528 $file =~ s/^\Q$config{srcdir}\E\/?//;
530 my $sha1 = git_sha1($file);
531 my $ci = git_commit_info($sha1);
532 my $ctime = $ci->{'author_epoch'};
533 debug("ctime for '$file': ". localtime($ctime));