summaryrefslogtreecommitdiff
path: root/IkiWiki/Plugin/git.pm
blob: 5e302729ea1c26c80c93d4974e94e8a57e444012 (plain)
  1. #!/usr/bin/perl
  2. package IkiWiki::Plugin::git;
  3. use warnings;
  4. use strict;
  5. use IkiWiki;
  6. use Encode;
  7. use open qw{:utf8 :std};
  8. my $sha1_pattern = qr/[0-9a-fA-F]{40}/; # pattern to validate Git sha1sums
  9. my $dummy_commit_msg = 'dummy commit'; # message to skip in recent changes
  10. sub import { #{{{
  11. hook(type => "checkconfig", id => "git", call => \&checkconfig);
  12. hook(type => "getsetup", id => "git", call => \&getsetup);
  13. hook(type => "rcs", id => "rcs_update", call => \&rcs_update);
  14. hook(type => "rcs", id => "rcs_prepedit", call => \&rcs_prepedit);
  15. hook(type => "rcs", id => "rcs_commit", call => \&rcs_commit);
  16. hook(type => "rcs", id => "rcs_commit_staged", call => \&rcs_commit_staged);
  17. hook(type => "rcs", id => "rcs_add", call => \&rcs_add);
  18. hook(type => "rcs", id => "rcs_remove", call => \&rcs_remove);
  19. hook(type => "rcs", id => "rcs_rename", call => \&rcs_rename);
  20. hook(type => "rcs", id => "rcs_recentchanges", call => \&rcs_recentchanges);
  21. hook(type => "rcs", id => "rcs_diff", call => \&rcs_diff);
  22. hook(type => "rcs", id => "rcs_getctime", call => \&rcs_getctime);
  23. } #}}}
  24. sub checkconfig () { #{{{
  25. if (! defined $config{gitorigin_branch}) {
  26. $config{gitorigin_branch}="origin";
  27. }
  28. if (! defined $config{gitmaster_branch}) {
  29. $config{gitmaster_branch}="master";
  30. }
  31. if (defined $config{git_wrapper} && length $config{git_wrapper}) {
  32. push @{$config{wrappers}}, {
  33. wrapper => $config{git_wrapper},
  34. wrappermode => (defined $config{git_wrappermode} ? $config{git_wrappermode} : "06755"),
  35. };
  36. }
  37. } #}}}
  38. sub getsetup () { #{{{
  39. return
  40. git_wrapper => {
  41. type => "string",
  42. example => "/git/wiki.git/hooks/post-update",
  43. description => "git post-update executable to generate",
  44. safe => 0, # file
  45. rebuild => 0,
  46. },
  47. git_wrappermode => {
  48. type => "string",
  49. example => '06755',
  50. description => "mode for git_wrapper (can safely be made suid)",
  51. safe => 0,
  52. rebuild => 0,
  53. },
  54. historyurl => {
  55. type => "string",
  56. example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=history;f=[[file]]",
  57. description => "gitweb url to show file history ([[file]] substituted)",
  58. safe => 1,
  59. rebuild => 1,
  60. },
  61. diffurl => {
  62. type => "string",
  63. example => "http://git.example.com/gitweb.cgi?p=wiki.git;a=blobdiff;h=[[sha1_to]];hp=[[sha1_from]];hb=[[sha1_parent]];f=[[file]]",
  64. description => "gitweb url to show a diff ([[sha1_to]], [[sha1_from]], [[sha1_parent]], and [[file]] substituted)",
  65. safe => 1,
  66. rebuild => 1,
  67. },
  68. gitorigin_branch => {
  69. type => "string",
  70. example => "origin",
  71. description => "where to pull and push changes (set to empty string to disable)",
  72. safe => 0, # paranoia
  73. rebuild => 0,
  74. },
  75. gitmaster_branch => {
  76. type => "string",
  77. example => "master",
  78. description => "branch that the wiki is stored in",
  79. safe => 0, # paranoia
  80. rebuild => 0,
  81. },
  82. } #}}}
  83. sub safe_git (&@) { #{{{
  84. # Start a child process safely without resorting /bin/sh.
  85. # Return command output or success state (in scalar context).
  86. my ($error_handler, @cmdline) = @_;
  87. my $pid = open my $OUT, "-|";
  88. error("Cannot fork: $!") if !defined $pid;
  89. if (!$pid) {
  90. # In child.
  91. # Git commands want to be in wc.
  92. chdir $config{srcdir}
  93. or error("Cannot chdir to $config{srcdir}: $!");
  94. exec @cmdline or error("Cannot exec '@cmdline': $!");
  95. }
  96. # In parent.
  97. my @lines;
  98. while (<$OUT>) {
  99. chomp;
  100. push @lines, $_;
  101. }
  102. close $OUT;
  103. $error_handler->("'@cmdline' failed: $!") if $? && $error_handler;
  104. return wantarray ? @lines : ($? == 0);
  105. }
  106. # Convenient wrappers.
  107. sub run_or_die ($@) { safe_git(\&error, @_) }
  108. sub run_or_cry ($@) { safe_git(sub { warn @_ }, @_) }
  109. sub run_or_non ($@) { safe_git(undef, @_) }
  110. #}}}
  111. sub merge_past ($$$) { #{{{
  112. # Unlike with Subversion, Git cannot make a 'svn merge -rN:M file'.
  113. # Git merge commands work with the committed changes, except in the
  114. # implicit case of '-m' of git checkout(1). So we should invent a
  115. # kludge here. In principle, we need to create a throw-away branch
  116. # in preparing for the merge itself. Since branches are cheap (and
  117. # branching is fast), this shouldn't cost high.
  118. #
  119. # The main problem is the presence of _uncommitted_ local changes. One
  120. # possible approach to get rid of this situation could be that we first
  121. # make a temporary commit in the master branch and later restore the
  122. # initial state (this is possible since Git has the ability to undo a
  123. # commit, i.e. 'git reset --soft HEAD^'). The method can be summarized
  124. # as follows:
  125. #
  126. # - create a diff of HEAD:current-sha1
  127. # - dummy commit
  128. # - create a dummy branch and switch to it
  129. # - rewind to past (reset --hard to the current-sha1)
  130. # - apply the diff and commit
  131. # - switch to master and do the merge with the dummy branch
  132. # - make a soft reset (undo the last commit of master)
  133. #
  134. # The above method has some drawbacks: (1) it needs a redundant commit
  135. # just to get rid of local changes, (2) somewhat slow because of the
  136. # required system forks. Until someone points a more straight method
  137. # (which I would be grateful) I have implemented an alternative method.
  138. # In this approach, we hide all the modified files from Git by renaming
  139. # them (using the 'rename' builtin) and later restore those files in
  140. # the throw-away branch (that is, we put the files themselves instead
  141. # of applying a patch).
  142. my ($sha1, $file, $message) = @_;
  143. my @undo; # undo stack for cleanup in case of an error
  144. my $conflict; # file content with conflict markers
  145. eval {
  146. # Hide local changes from Git by renaming the modified file.
  147. # Relative paths must be converted to absolute for renaming.
  148. my ($target, $hidden) = (
  149. "$config{srcdir}/${file}", "$config{srcdir}/${file}.${sha1}"
  150. );
  151. rename($target, $hidden)
  152. or error("rename '$target' to '$hidden' failed: $!");
  153. # Ensure to restore the renamed file on error.
  154. push @undo, sub {
  155. return if ! -e "$hidden"; # already renamed
  156. rename($hidden, $target)
  157. or warn "rename '$hidden' to '$target' failed: $!";
  158. };
  159. my $branch = "throw_away_${sha1}"; # supposed to be unique
  160. # Create a throw-away branch and rewind backward.
  161. push @undo, sub { run_or_cry('git', 'branch', '-D', $branch) };
  162. run_or_die('git', 'branch', $branch, $sha1);
  163. # Switch to throw-away branch for the merge operation.
  164. push @undo, sub {
  165. if (!run_or_cry('git', 'checkout', $config{gitmaster_branch})) {
  166. run_or_cry('git', 'checkout','-f',$config{gitmaster_branch});
  167. }
  168. };
  169. run_or_die('git', 'checkout', $branch);
  170. # Put the modified file in _this_ branch.
  171. rename($hidden, $target)
  172. or error("rename '$hidden' to '$target' failed: $!");
  173. # _Silently_ commit all modifications in the current branch.
  174. run_or_non('git', 'commit', '-m', $message, '-a');
  175. # ... and re-switch to master.
  176. run_or_die('git', 'checkout', $config{gitmaster_branch});
  177. # Attempt to merge without complaining.
  178. if (!run_or_non('git', 'pull', '--no-commit', '.', $branch)) {
  179. $conflict = readfile($target);
  180. run_or_die('git', 'reset', '--hard');
  181. }
  182. };
  183. my $failure = $@;
  184. # Process undo stack (in reverse order). By policy cleanup
  185. # actions should normally print a warning on failure.
  186. while (my $handle = pop @undo) {
  187. $handle->();
  188. }
  189. error("Git merge failed!\n$failure\n") if $failure;
  190. return $conflict;
  191. } #}}}
  192. sub parse_diff_tree ($@) { #{{{
  193. # Parse the raw diff tree chunk and return the info hash.
  194. # See git-diff-tree(1) for the syntax.
  195. my ($prefix, $dt_ref) = @_;
  196. # End of stream?
  197. return if !defined @{ $dt_ref } ||
  198. !defined @{ $dt_ref }[0] || !length @{ $dt_ref }[0];
  199. my %ci;
  200. # Header line.
  201. while (my $line = shift @{ $dt_ref }) {
  202. return if $line !~ m/^(.+) ($sha1_pattern)/;
  203. my $sha1 = $2;
  204. $ci{'sha1'} = $sha1;
  205. last;
  206. }
  207. # Identification lines for the commit.
  208. while (my $line = shift @{ $dt_ref }) {
  209. # Regexps are semi-stolen from gitweb.cgi.
  210. if ($line =~ m/^tree ([0-9a-fA-F]{40})$/) {
  211. $ci{'tree'} = $1;
  212. }
  213. elsif ($line =~ m/^parent ([0-9a-fA-F]{40})$/) {
  214. # XXX: collecting in reverse order
  215. push @{ $ci{'parents'} }, $1;
  216. }
  217. elsif ($line =~ m/^(author|committer) (.*) ([0-9]+) (.*)$/) {
  218. my ($who, $name, $epoch, $tz) =
  219. ($1, $2, $3, $4 );
  220. $ci{ $who } = $name;
  221. $ci{ "${who}_epoch" } = $epoch;
  222. $ci{ "${who}_tz" } = $tz;
  223. if ($name =~ m/^[^<]+\s+<([^@>]+)/) {
  224. $ci{"${who}_username"} = $1;
  225. }
  226. elsif ($name =~ m/^([^<]+)\s+<>$/) {
  227. $ci{"${who}_username"} = $1;
  228. }
  229. else {
  230. $ci{"${who}_username"} = $name;
  231. }
  232. }
  233. elsif ($line =~ m/^$/) {
  234. # Trailing empty line signals next section.
  235. last;
  236. }
  237. }
  238. debug("No 'tree' seen in diff-tree output") if !defined $ci{'tree'};
  239. if (defined $ci{'parents'}) {
  240. $ci{'parent'} = @{ $ci{'parents'} }[0];
  241. }
  242. else {
  243. $ci{'parent'} = 0 x 40;
  244. }
  245. # Commit message (optional).
  246. while ($dt_ref->[0] =~ /^ /) {
  247. my $line = shift @{ $dt_ref };
  248. $line =~ s/^ //;
  249. push @{ $ci{'comment'} }, $line;
  250. }
  251. shift @{ $dt_ref } if $dt_ref->[0] =~ /^$/;
  252. # Modified files.
  253. while (my $line = shift @{ $dt_ref }) {
  254. if ($line =~ m{^
  255. (:+) # number of parents
  256. ([^\t]+)\t # modes, sha1, status
  257. (.*) # file names
  258. $}xo) {
  259. my $num_parents = length $1;
  260. my @tmp = split(" ", $2);
  261. my ($file, $file_to) = split("\t", $3);
  262. my @mode_from = splice(@tmp, 0, $num_parents);
  263. my $mode_to = shift(@tmp);
  264. my @sha1_from = splice(@tmp, 0, $num_parents);
  265. my $sha1_to = shift(@tmp);
  266. my $status = shift(@tmp);
  267. if ($file =~ m/^"(.*)"$/) {
  268. ($file=$1) =~ s/\\([0-7]{1,3})/chr(oct($1))/eg;
  269. }
  270. $file =~ s/^\Q$prefix\E//;
  271. if (length $file) {
  272. push @{ $ci{'details'} }, {
  273. 'file' => decode_utf8($file),
  274. 'sha1_from' => $sha1_from[0],
  275. 'sha1_to' => $sha1_to,
  276. };
  277. }
  278. next;
  279. };
  280. last;
  281. }
  282. return \%ci;
  283. } #}}}
  284. sub git_commit_info ($;$) { #{{{
  285. # Return an array of commit info hashes of num commits (default: 1)
  286. # starting from the given sha1sum.
  287. my ($sha1, $num) = @_;
  288. $num ||= 1;
  289. my @raw_lines = run_or_die('git', 'log', "--max-count=$num",
  290. '--pretty=raw', '--raw', '--abbrev=40', '--always', '-c',
  291. '-r', $sha1, '--', '.');
  292. my ($prefix) = run_or_die('git', 'rev-parse', '--show-prefix');
  293. my @ci;
  294. while (my $parsed = parse_diff_tree(($prefix or ""), \@raw_lines)) {
  295. push @ci, $parsed;
  296. }
  297. warn "Cannot parse commit info for '$sha1' commit" if !@ci;
  298. return wantarray ? @ci : $ci[0];
  299. } #}}}
  300. sub git_sha1 (;$) { #{{{
  301. # Return head sha1sum (of given file).
  302. my $file = shift || q{--};
  303. # Ignore error since a non-existing file might be given.
  304. my ($sha1) = run_or_non('git', 'rev-list', '--max-count=1', 'HEAD',
  305. '--', $file);
  306. if ($sha1) {
  307. ($sha1) = $sha1 =~ m/($sha1_pattern)/; # sha1 is untainted now
  308. } else { debug("Empty sha1sum for '$file'.") }
  309. return defined $sha1 ? $sha1 : q{};
  310. } #}}}
  311. sub rcs_update () { #{{{
  312. # Update working directory.
  313. if (length $config{gitorigin_branch}) {
  314. run_or_cry('git', 'pull', $config{gitorigin_branch});
  315. }
  316. } #}}}
  317. sub rcs_prepedit ($) { #{{{
  318. # Return the commit sha1sum of the file when editing begins.
  319. # This will be later used in rcs_commit if a merge is required.
  320. my ($file) = @_;
  321. return git_sha1($file);
  322. } #}}}
  323. sub rcs_commit ($$$;$$) { #{{{
  324. # Try to commit the page; returns undef on _success_ and
  325. # a version of the page with the rcs's conflict markers on
  326. # failure.
  327. my ($file, $message, $rcstoken, $user, $ipaddr) = @_;
  328. # Check to see if the page has been changed by someone else since
  329. # rcs_prepedit was called.
  330. my $cur = git_sha1($file);
  331. my ($prev) = $rcstoken =~ /^($sha1_pattern)$/; # untaint
  332. if (defined $cur && defined $prev && $cur ne $prev) {
  333. my $conflict = merge_past($prev, $file, $dummy_commit_msg);
  334. return $conflict if defined $conflict;
  335. }
  336. rcs_add($file);
  337. return rcs_commit_staged($message, $user, $ipaddr);
  338. } #}}}
  339. sub rcs_commit_staged ($$$) {
  340. # Commits all staged changes. Changes can be staged using rcs_add,
  341. # rcs_remove, and rcs_rename.
  342. my ($message, $user, $ipaddr)=@_;
  343. # Set the commit author and email to the web committer.
  344. my %env=%ENV;
  345. if (defined $user || defined $ipaddr) {
  346. my $u=defined $user ? $user : $ipaddr;
  347. $ENV{GIT_AUTHOR_NAME}=$u;
  348. $ENV{GIT_AUTHOR_EMAIL}="$u\@web";
  349. }
  350. # git commit returns non-zero if file has not been really changed.
  351. # so we should ignore its exit status (hence run_or_non).
  352. $message = IkiWiki::possibly_foolish_untaint($message);
  353. if (run_or_non('git', 'commit', '--cleanup=verbatim',
  354. '-q', '-m', $message)) {
  355. if (length $config{gitorigin_branch}) {
  356. run_or_cry('git', 'push', $config{gitorigin_branch});
  357. }
  358. }
  359. %ENV=%env;
  360. return undef; # success
  361. }
  362. sub rcs_add ($) { # {{{
  363. # Add file to archive.
  364. my ($file) = @_;
  365. run_or_cry('git', 'add', $file);
  366. } #}}}
  367. sub rcs_remove ($) { # {{{
  368. # Remove file from archive.
  369. my ($file) = @_;
  370. run_or_cry('git', 'rm', '-f', $file);
  371. } #}}}
  372. sub rcs_rename ($$) { # {{{
  373. my ($src, $dest) = @_;
  374. run_or_cry('git', 'mv', '-f', $src, $dest);
  375. } #}}}
  376. sub rcs_recentchanges ($) { #{{{
  377. # List of recent changes.
  378. my ($num) = @_;
  379. eval q{use Date::Parse};
  380. error($@) if $@;
  381. my @rets;
  382. foreach my $ci (git_commit_info('HEAD', $num)) {
  383. # Skip redundant commits.
  384. next if ($ci->{'comment'} && @{$ci->{'comment'}}[0] eq $dummy_commit_msg);
  385. my ($sha1, $when) = (
  386. $ci->{'sha1'},
  387. $ci->{'author_epoch'}
  388. );
  389. my @pages;
  390. foreach my $detail (@{ $ci->{'details'} }) {
  391. my $file = $detail->{'file'};
  392. my $diffurl = defined $config{'diffurl'} ? $config{'diffurl'} : "";
  393. $diffurl =~ s/\[\[file\]\]/$file/go;
  394. $diffurl =~ s/\[\[sha1_parent\]\]/$ci->{'parent'}/go;
  395. $diffurl =~ s/\[\[sha1_from\]\]/$detail->{'sha1_from'}/go;
  396. $diffurl =~ s/\[\[sha1_to\]\]/$detail->{'sha1_to'}/go;
  397. push @pages, {
  398. page => pagename($file),
  399. diffurl => $diffurl,
  400. };
  401. }
  402. my @messages;
  403. my $pastblank=0;
  404. foreach my $line (@{$ci->{'comment'}}) {
  405. $pastblank=1 if $line eq '';
  406. next if $pastblank && $line=~m/^ *(signed[ \-]off[ \-]by[ :]|acked[ \-]by[ :]|cc[ :])/i;
  407. push @messages, { line => $line };
  408. }
  409. my $user=$ci->{'author_username'};
  410. my $web_commit = ($ci->{'author'} =~ /\@web>/);
  411. # compatability code for old web commit messages
  412. if (! $web_commit &&
  413. defined $messages[0] &&
  414. $messages[0]->{line} =~ m/$config{web_commit_regexp}/) {
  415. $user = defined $2 ? "$2" : "$3";
  416. $messages[0]->{line} = $4;
  417. $web_commit=1;
  418. }
  419. push @rets, {
  420. rev => $sha1,
  421. user => $user,
  422. committype => $web_commit ? "web" : "git",
  423. when => $when,
  424. message => [@messages],
  425. pages => [@pages],
  426. } if @pages;
  427. last if @rets >= $num;
  428. }
  429. return @rets;
  430. } #}}}
  431. sub rcs_diff ($) { #{{{
  432. my $rev=shift;
  433. my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
  434. my @lines;
  435. foreach my $line (run_or_non("git", "show", $sha1)) {
  436. if (@lines || $line=~/^diff --git/) {
  437. push @lines, $line."\n";
  438. }
  439. }
  440. if (wantarray) {
  441. return @lines;
  442. }
  443. else {
  444. return join("", @lines);
  445. }
  446. } #}}}
  447. sub rcs_getctime ($) { #{{{
  448. my $file=shift;
  449. # Remove srcdir prefix
  450. $file =~ s/^\Q$config{srcdir}\E\/?//;
  451. my $sha1 = git_sha1($file);
  452. my $ci = git_commit_info($sha1);
  453. my $ctime = $ci->{'author_epoch'};
  454. debug("ctime for '$file': ". localtime($ctime));
  455. return $ctime;
  456. } #}}}
  457. 1