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