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 => "getsetup", id => "git", call => sub { #{{{
19 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
20 description => "gitweb url to show file history ([[file]] substituted)",
27 example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_parent]];f=[[file]]",
28 description => "gitweb url to show a diff ([[sha1_to]], [[sha1_from]], [[sha1_parent]], and [[file]] substituted)",
35 description => "where to pull and push changes (unset to not pull/push)",
42 description => "branch that the wiki is stored in",
48 sub _safe_git (&@) { #{{{
49 # Start a child process safely without resorting /bin/sh.
50 # Return command output or success state (in scalar context).
52 my ($error_handler, @cmdline) = @_;
54 my $pid = open my $OUT, "-|";
56 error("Cannot fork: $!") if !defined $pid;
60 # Git commands want to be in wc.
62 or error("Cannot chdir to $config{srcdir}: $!");
63 exec @cmdline or error("Cannot exec '@cmdline': $!");
75 $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
77 return wantarray ? @lines : ($? == 0);
79 # Convenient wrappers.
80 sub run_or_die ($@) { _safe_git(\&error, @_) }
81 sub run_or_cry ($@) { _safe_git(sub { warn @_ }, @_) }
82 sub run_or_non ($@) { _safe_git(undef, @_) }
85 sub _merge_past ($$$) { #{{{
86 # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
87 # Git merge commands work with the committed changes, except in the
88 # implicit case of '-m' of git checkout(1). So we should invent a
89 # kludge here. In principle, we need to create a throw-away branch
90 # in preparing for the merge itself. Since branches are cheap (and
91 # branching is fast), this shouldn't cost high.
93 # The main problem is the presence of _uncommitted_ local changes. One
94 # possible approach to get rid of this situation could be that we first
95 # make a temporary commit in the master branch and later restore the
96 # initial state (this is possible since Git has the ability to undo a
97 # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
100 # - create a diff of HEAD:current-sha1
102 # - create a dummy branch and switch to it
103 # - rewind to past (reset --hard to the current-sha1)
104 # - apply the diff and commit
105 # - switch to master and do the merge with the dummy branch
106 # - make a soft reset (undo the last commit of master)
108 # The above method has some drawbacks: (1) it needs a redundant commit
109 # just to get rid of local changes, (2) somewhat slow because of the
110 # required system forks. Until someone points a more straight method
111 # (which I would be grateful) I have implemented an alternative method.
112 # In this approach, we hide all the modified files from Git by renaming
113 # them (using the 'rename' builtin) and later restore those files in
114 # the throw-away branch (that is, we put the files themselves instead
115 # of applying a patch).
117 my ($sha1, $file, $message) = @_;
119 my @undo; # undo stack for cleanup in case of an error
120 my $conflict; # file content with conflict markers
123 # Hide local changes from Git by renaming the modified file.
124 # Relative paths must be converted to absolute for renaming.
125 my ($target, $hidden) = (
126 "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
128 rename($target, $hidden)
129 or error("rename '$target' to '$hidden' failed: $!");
130 # Ensure to restore the renamed file on error.
132 return if ! -e "$hidden"; # already renamed
133 rename($hidden, $target)
134 or warn "rename '$hidden' to '$target' failed: $!";
137 my $branch = "throw_away_${sha1}"; # supposed to be unique
139 # Create a throw-away branch and rewind backward.
140 push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
141 run_or_die('git', 'branch', $branch, $sha1);
143 # Switch to throw-away branch for the merge operation.
145 if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
146 run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
149 run_or_die('git', 'checkout', $branch);
151 # Put the modified file in _this_ branch.
152 rename($hidden, $target)
153 or error("rename '$hidden' to '$target' failed: $!");
155 # _Silently_ commit all modifications in the current branch.
156 run_or_non('git', 'commit', '-m', $message, '-a');
157 # ... and re-switch to master.
158 run_or_die('git', 'checkout', $config{gitmaster_branch});
160 # Attempt to merge without complaining.
161 if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
162 $conflict = readfile($target);
163 run_or_die('git', 'reset', '--hard');
168 # Process undo stack (in reverse order). By policy cleanup
169 # actions should normally print a warning on failure.
170 while (my $handle = pop @undo) {
174 error("Git merge failed!\n$failure\n") if $failure;
179 sub _parse_diff_tree ($@) { #{{{
180 # Parse the raw diff tree chunk and return the info hash.
181 # See git-diff-tree(1) for the syntax.
183 my ($prefix, $dt_ref) = @_;
186 return if !defined @{ $dt_ref } ||
187 !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
191 while (my $line = shift @{ $dt_ref }) {
192 return if $line !~ m/^(.+) ($sha1_pattern)/;
199 # Identification lines for the commit.
200 while (my $line = shift @{ $dt_ref }) {
201 # Regexps are semi-stolen from gitweb.cgi.
202 if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
205 elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
206 # XXX: collecting in reverse order
207 push @{ $ci{'parents'} }, $1;
209 elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
210 my ($who, $name, $epoch, $tz) =
214 $ci{ "${who}_epoch" } = $epoch;
215 $ci{ "${who}_tz" } = $tz;
217 if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
218 $ci{"${who}_username"} = $1;
220 elsif ($name =~ m/^([^<]+)\s+<>$/) {
221 $ci{"${who}_username"} = $1;
224 $ci{"${who}_username"} = $name;
227 elsif ($line =~ m/^$/) {
228 # Trailing empty line signals next section.
233 debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
235 if (defined $ci{'parents'}) {
236 $ci{'parent'} = @{ $ci{'parents'} }[0];
239 $ci{'parent'} = 0 x 40;
242 # Commit message (optional).
243 while ($dt_ref->[0] =~ /^ /) {
244 my $line = shift @{ $dt_ref };
246 push @{ $ci{'comment'} }, $line;
248 shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
251 while (my $line = shift @{ $dt_ref }) {
253 (:+) # number of parents
254 ([^\t]+)\t # modes, sha1, status
257 my $num_parents = length $1;
258 my @tmp = split(" ", $2);
259 my ($file, $file_to) = split("\t", $3);
260 my @mode_from = splice(@tmp, 0, $num_parents);
261 my $mode_to = shift(@tmp);
262 my @sha1_from = splice(@tmp, 0, $num_parents);
263 my $sha1_to = shift(@tmp);
264 my $status = shift(@tmp);
266 if ($file =~ m/^"(.*)"$/) {
267 ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
269 $file =~ s/^\Q$prefix\E//;
271 push @{ $ci{'details'} }, {
272 'file' => decode_utf8($file),
273 'sha1_from' => $sha1_from[0],
274 'sha1_to' => $sha1_to,
285 sub git_commit_info ($;$) { #{{{
286 # Return an array of commit info hashes of num commits (default: 1)
287 # starting from the given sha1sum.
289 my ($sha1, $num) = @_;
293 my @raw_lines = run_or_die('git', 'log', "--max-count=$num",
294 '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
295 '-r', $sha1, '--', '.');
296 my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
299 while (my $parsed = _parse_diff_tree(($prefix or ""), \@raw_lines)) {
303 warn "Cannot parse commit info for '$sha1' commit" if !@ci;
305 return wantarray ? @ci : $ci[0];
308 sub git_sha1 (;$) { #{{{
309 # Return head sha1sum (of given file).
311 my $file = shift || q{--};
313 # Ignore error since a non-existing file might be given.
314 my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
317 ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
318 } else { debug("Empty sha1sum for '$file'.") }
319 return defined $sha1 ? $sha1 : q{};
322 sub rcs_update () { #{{{
323 # Update working directory.
325 if (length $config{gitorigin_branch}) {
326 run_or_cry('git', 'pull', $config{gitorigin_branch});
330 sub rcs_prepedit ($) { #{{{
331 # Return the commit sha1sum of the file when editing begins.
332 # This will be later used in rcs_commit if a merge is required.
336 return git_sha1($file);
339 sub rcs_commit ($$$;$$) { #{{{
340 # Try to commit the page; returns undef on _success_ and
341 # a version of the page with the rcs's conflict markers on
344 my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
346 # Check to see if the page has been changed by someone else since
347 # rcs_prepedit was called.
348 my $cur = git_sha1($file);
349 my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
351 if (defined $cur && defined $prev && $cur ne $prev) {
352 my $conflict = _merge_past($prev, $file, $dummy_commit_msg);
353 return $conflict if defined $conflict;
357 return rcs_commit_staged($message, $user, $ipaddr);
360 sub rcs_commit_staged ($$$) {
361 # Commits all staged changes. Changes can be staged using rcs_add,
362 # rcs_remove, and rcs_rename.
363 my ($message, $user, $ipaddr)=@_;
365 # Set the commit author and email to the web committer.
367 if (defined $user || defined $ipaddr) {
368 my $u=defined $user ? $user : $ipaddr;
369 $ENV{GIT_AUTHOR_NAME}=$u;
370 $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
373 # git commit returns non-zero if file has not been really changed.
374 # so we should ignore its exit status (hence run_or_non).
375 $message = possibly_foolish_untaint($message);
376 if (run_or_non('git', 'commit', '--cleanup=verbatim',
377 '-q', '-m', $message)) {
378 if (length $config{gitorigin_branch}) {
379 run_or_cry('git', 'push', $config{gitorigin_branch});
384 return undef; # success
387 sub rcs_add ($) { # {{{
388 # Add file to archive.
392 run_or_cry('git', 'add', $file);
395 sub rcs_remove ($) { # {{{
396 # Remove file from archive.
400 run_or_cry('git', 'rm', '-f', $file);
403 sub rcs_rename ($$) { # {{{
404 my ($src, $dest) = @_;
406 run_or_cry('git', 'mv', '-f', $src, $dest);
409 sub rcs_recentchanges ($) { #{{{
410 # List of recent changes.
414 eval q{use Date::Parse};
418 foreach my $ci (git_commit_info('HEAD', $num)) {
419 # Skip redundant commits.
420 next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
422 my ($sha1, $when) = (
424 $ci->{'author_epoch'}
428 foreach my $detail (@{ $ci->{'details'} }) {
429 my $file = $detail->{'file'};
431 my $diffurl = $config{'diffurl'};
432 $diffurl =~ s/\[\[file\]\]/$file/go;
433 $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
434 $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
435 $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
438 page => pagename($file),
445 foreach my $line (@{$ci->{'comment'}}) {
446 $pastblank=1 if $line eq '';
447 next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
448 push @messages, { line => $line };
451 my $user=$ci->{'author_username'};
452 my $web_commit = ($ci->{'author'} =~ /\@web>/);
454 # compatability code for old web commit messages
456 defined $messages[0] &&
457 $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
458 $user = defined $2 ? "$2" : "$3";
459 $messages[0]->{line} = $4;
466 committype => $web_commit ? "web" : "git",
468 message => [@messages],
472 last if @rets >= $num;
478 sub rcs_diff ($) { #{{{
480 my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
482 foreach my $line (run_or_non("git", "show", $sha1)) {
483 if (@lines || $line=~/^diff --git/) {
484 push @lines, $line."\n";
491 return join("", @lines);
495 sub rcs_getctime ($) { #{{{
497 # Remove srcdir prefix
498 $file =~ s/^\Q$config{srcdir}\E\/?//;
500 my $sha1 = git_sha1($file);
501 my $ci = git_commit_info($sha1);
502 my $ctime = $ci->{'author_epoch'};
503 debug("ctime for '$file': ". localtime($ctime));