I submitted some changes that added 5 "Yes"es and 2 "Fast"s to Mercurial at [[/rcs]], but some functionality is still missing as compared to e.g. `git.pm`, with which it should be able to be equivalent.
To do this, a more basic rewrite would simplify things. I inline the complete file below with comments. I don't expect anyone to take the time to read it all at once, but I'd be glad if those interested in the Mercurial backend could do some beta testing.
* [This specific revision at my hg repo](http://46.239.104.5:81/hg/program/ikiwiki/file/4994ba5e36fa/Plugin/mercurial.pm) ([raw version](http://46.239.104.5:81/hg/program/ikiwiki/raw-file/4994ba5e36fa/Plugin/mercurial.pm)).
* [My default branch](http://510x.se/hg/program/ikiwiki/file/default/Plugin/mercurial.pm) (where updates will be made, will mention here if anything happens) ([raw version](http://510x.se/hg/program/ikiwiki/raw-file/default/Plugin/mercurial.pm)).
To handle uncommited local changes ("ULC"s for short), I use logic similar to the (non-standard) "shelve" extension to Mercurial. By taking a diff before resetting to last commit, making changes and then applying diff again, one can do things Mercurial otherwise refuses, which is necessary later.
This function creates this diff.
sub hg_local_dirstate_shelve ($) {
# Creates a diff snapshot of uncommited changes existing the srcdir.
# Takes a string (preferably revision) as input to create a unique and
# identifiable diff name.
my $tempdiffname = "diff_".shift;
my $tempdiffpath;
if (my @tempdiff = run_or_die('hg', 'diff', '-g')) {
This makes online diffing possible. A similar approach as in `git.pm`, which is [discussed to some length in a comment there](http://source.ikiwiki.branchable.com/?p=source.git;a=blob;f=IkiWiki/Plugin/git.pm;h=cf7fbe9b7c43ee53180612d0411e6202074fb9e0;hb=refs/heads/master#l211), is taken.
# Hide local changes from Mercurial by renaming the modified
# file. Relative paths must be converted to absolute for
# renaming.
my ($target, $hidden) = (
"$config{srcdir}/${file}",
"$config{srcdir}/${file}.${sha1}"
);
rename($target, $hidden)
or error("rename '$target' to '$hidden' failed: $!");
# Ensure to restore the renamed file on error.
push @undo, sub {
return if ! -e "$hidden"; # already renamed
rename($hidden, $target)
or warn "rename '$hidden' to '$target' failed: $!";
};
Take a snapshot of srcdir to be able to restore uncommited local changes ("ULCs") afterwards.
* This must happen _after_ the merging commit in Mercurial, there is no way around it. By design hg refuses to commit merges if there are other changes to tracked content present, no matter how much you beg.
* ULCs to the file being edited are special: they can't be diffed here since `editpage.pm` already has overwritten the file. When the web edit session started though, the ULC version (not the commited
version) was read into the form, so in a way, the web user _has already merged_ with the ULC. It is not saved in commit history, but that is the exact consequence of "uncommited" changes. If an ULC is done between the time the web edit started and was submitted, then it is lost, though. All in all, one shouldn't be editing the srcdir directly when web edits of the same file are allowed. Clone the repo and push changes instead.
Much of these issues disappear, I believe, if one works with a master repo which only is pushed to.
my $tempdiffpath = hg_local_dirstate_shelve($sha1);
# Ensure uniqueness of bookmarks.
my $bookmark_upstream_head = "current_head_$sha1";
my $bookmark_edit_base = "edit_base_$sha1";
# Git and Mercurial differ in the branch concept. Mercurial's
# "bookmarks" are closer in function in this regard.
Bookmarks aren't standard until Mercurial 1.8 ([2011--02--10](http://selenic.com/hg/rev/d4ab9486e514)), but they've been bundled with Mercurial since ~2008, so they can be enabled by writing a `hgrc`, which is also being worked on.
# Create a bookmark at current tip.
push @undo, sub { run_or_cry('hg', 'bookmark', '--delete',
...but this requires the same amount of forks as the
above method, and confuses other parts of ikiwiki
since the upstream head is now the third newest
revision. Maybe that particular problem is solvable
by setting a global default bookmark that follows the
main tip. It will leave clutter in the revision
history, though. Two extra commits that in practice
don't hold relevant information will be recorded for
each failed merge attempt.
To only create one extra commit, one could imagine
adding `--close-branch` to the commit that initially
created the new head (since there is no problem
merging with closed heads), but it's not possible to
close and create a head at the same time, apparently.
}
};
my $failure = $@;
# Process undo stack (in reverse order). By policy, cleanup actions
# should normally print a warning on failure.
while (my $handle = pop @undo) {
$handle->();
}
error("Mercurial merge failed!\n$failure\n") if $failure;
return ($conflict, $tempdiffpath);
}
sub hg_commit_info ($;$;$) {
# Return an array of commit info hashes of num commits starting from
# the given sha1sum.
#
This could be optimized by using a lookup cache similar to
`findtimes()`. By adding `KeyAttr => ['node']` to `XMLin()` options, one
could use the revision ID as key and do a single massive history
lookup and later just check if the given revision already exists as a
key. Right now I'm at the "don't optimize it yet" stage, though.
This uses Mercurial's built-in `--style xml` and parses it with `XML::Simple`. Mercurial's log output is otherwise somewhat cumbersome to get good stuff out of, so this XML solution is quite good, I think. It adds module dependency, but XML::Simple seems fairly standard (but what do I know, I've used 1 Perl installation in my life).
# Mercurial itself parses out and stores an email address if
# present in author name. If not, hg sets email to author name.
if ( $rev->{author}{content} ne $rev->{author}{email} &&
$rev->{author}{email} =~ m/^([^\@]+)\@(.*)$/ ) {
if ($2 eq "web") {
$c_info{nickname} = $1;
$c_info{web_commit} = "1";
}
}
# Mercurial gives date in ISO 8601, well handled by str2time().
$c_info{when} = str2time($rev->{date});
# Mercurial doesn't allow empty commit messages, so there
# should always be a single defined message.
$c_info{message} = $rev->{msg}{content};
# Inside "paths" sits a single array "path" that contains
# multiple paths. Crystal clear :-)
foreach my $path (@{$rev->{paths}{path}}) {
push @{$c_info{files}}, {
# Mercurial doesn't track file permissions as
# Git do, so that's missing here.
'file' => $path->{content},
'status' => $path->{action},
};
}
# There also exists an XML branch "copies"->"copy", containing
# source and dest of files that have been copied with "hg cp".
# The copy action is also registered in "paths" as a removal of
# source and addition of dest, so it's not needed here.
push @c_infos, {%c_info};
use Data::Dumper;
}
return wantarray ? @c_infos : $c_infos[0];
}
sub hg_sha1 (;$) {
# Return head sha1sum (of given file).
my $file = shift || q{--};
# Non-existing file doesn't give error, just empty string.
my $f_info = hg_commit_info(undef, 1, $file);
my $sha1;
if ($f_info->{rev}) {
($sha1) = $f_info->{rev} =~ m/($sha1_pattern)/;
}
else {
debug("Empty sha1sum for '$file'.");
}
return defined $sha1 ? $sha1 : q{};
}
sub rcs_update () {
run_or_cry('hg', '-q', 'update');
}
sub rcs_prepedit ($) {
# Return the commit sha1sum of the file when editing begins.
# This will be later used in rcs_commit if a merge is required.
my ($file) = @_;
return hg_sha1($file);
}
sub rcs_commit (@) {
# Try to commit the page; returns undef on _success_ and
# a version of the page with the rcs's conflict markers on
# failure.
my %params=@_;
# Check to see if the page has been changed by someone else since
# rcs_prepedit was called.
my $cur = hg_sha1($params{file});
my ($prev) = $params{token} =~ /^($sha1_pattern)$/; # untaint
if (defined $cur && defined $prev && $cur ne $prev) {
If there was a conflict, the file with conflict markers is returned. Else, the path to the tempdiff, which is to be run to restore previous local state after `rcs_commit_staged`, is returned.
This is an upstream change I did a week ago or so. Perhaps it can be merged in some clever way with the updated `hg_commit_info` to make one shared lookup cache. Don't know how much would be gained.
sub findtimes ($$) {
my $file=shift;
my $id=shift; # 0 = mtime ; 1 = ctime
if (! keys %time_cache) {
my $date;
# It doesn't seem possible to specify the format wanted for the
# changelog (same format as is generated in git.pm:findtimes(),
# though the date differs slightly) without using a style
# _file_. There is a "hg log" switch "--template" to directly
# control simple output formatting, but in this case, the
# {file} directive must be redefined, which can only be done
# with "--style".
#
# If {file} is not redefined, all files are output on a single
# line separated with a space. It is not possible to conclude
# if the space is part of a filename or just a separator, and
# thus impossible to use in this case.
#
# Some output filters are available in hg, but they are not fit
# for this cause (and would slow down the process
# unnecessarily).
eval q{use File::Temp};
error $@ if $@;
my ($tmpl_fh, $tmpl_filename) = File::Temp::tempfile(UNLINK => 1);
The comment just below the function declaration below is taken from `git.pm`. Is it true? Should ikiwiki support sharing its repo with other things? Mercurial-wise that sounds like a world of pain.
*TODO:* I don't know what's happening here. I've changed the code to adhere to this file's variables and functions, but it refers to a srcdir _and_ a default repo, which currently isn't available in the Mercurial setup.
`rcs_receive` is optional and only runs when running a pre-receive hook. Where `$_` comes from and its format are mysteries to me.
Also, a comment in `git.pm` mentions that we don't want to chdir to a subdir "and only see changes in it" - but this isn't true for either Git or Mercurial to my knowledge. It only seems to happen in `git.pm` since the `git log` command in `git_commit_info` ends with "`-- .`" - if it didn't do that, one wouldn't have to chdir for this reason, I believe.
In this case we need to stay in default repo instead of srcdir though, so `hg_dir="."` _is_ needed, but not for the abovementioned reason :-) (maybe there's more to it, though).
my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
The below 4 lines of code are from `git.pm`, but I can't see what they actually do there. Neither Git nor Mercurial only lists changes in working directory when given a command - they always traverse to repository root by themselves. I keep it here for comments, in case I'm missing something.
*UPDATE:* See earlier note about `git log` ending in "`-- .`".
## Examine changes from root of git repo, not from any subdir,
## in order to see all changes.
#my ($subdir, $rootdir) = git_find_root();
#$git_dir=$rootdir;
my $c_info=hg_commit_info($sha1, 1, undef) or error "unknown commit";
# hg revert will fail on merge commits. Add a nice message.
if (exists $c_info->{parents} && $c_info->{parents} > 1) {
error gettext("you are not allowed to revert a merge");
}
my @c_info_ret=hg_parse_changes($c_info);
### Probably not needed, if earlier comment is correct.
#$hg_dir=undef;
return @c_info_ret;
}
sub rcs_revert ($) {
# Try to revert the given rev; returns undef on _success_.
my $rev = shift;
my ($sha1) = $rev =~ /^($sha1_pattern)$/; # untaint
# Save uncommited local changes to diff file. Attempt to restore later.
my $tempdiffpath = hg_local_dirstate_shelve($sha1);
# Clean dir to latest commit.
run_or_die('hg', 'update', '-C');
Some voodoo is needed here. `hg backout --tool internal:local -r $sha1` is *almost* good, but if the reversion is done to the directly previous revision, hg automatically commits, which is bad in this case. Instead I generate a reverse diff and pipe it to `import --no-commit`.
if ($tempdiffpath) { hg_local_dirstate_unshelve($tempdiffpath) }
return undef;
}
else {
if ($tempdiffpath) { hg_local_dirstate_unshelve($tempdiffpath) }
return sprintf(gettext("Failed to revert commit %s"), $sha1);
}
}
Below follows code regarding [[Auto-setup and maintain Mercurial wrapper hooks]]. Will try to solve it in another place later, but the code in itself is working.
Should perhaps add initiation of the bookmark extension here, to support older Mercurial versions.
sub rcs_wrapper_postcall($) {
# Update hgrc if it exists. Change post-commit/incoming hooks with the
# .ikiwiki suffix to point to the wrapper path given in the setup file.
# Work with a tempfile to not delete hgrc if the loop is interrupted
# midway.
# I believe there is a better way to solve this than creating new hooks
# and callbacks. Will await discussion on ikiwiki.info.
my $hgrc=$config{srcdir}.'/.hg/hgrc';
my $backup_suffix='.ikiwiki.bak';
if (-e $hgrc) {
use File::Spec;
my $mercurial_wrapper_abspath=File::Spec->rel2abs($config{mercurial_wrapper}, $config{srcdir});