1. 1. Introduction

hg4j is a pure Java implementation of the Mercurial (hg) SCM. It is modelled on the decoupled design of JGit: a plumbing layer that reads and writes the repository formats, and a porcelain layer of command objects on top of it.

The reference for every behaviour is the real Mercurial. The library is checked against hg 7.2 (pure Python), the Rust build 7.2.4 and the development build of the same line, by running the same scenario with hg4j and with the real hg and comparing the repositories, the output and the exit status. Older Mercurial releases are not part of the test matrix; see 8. Known Issues and Remaining Work.

This guide describes the architecture, the command surface, the locking and transaction rules, the supported repository formats, the places where hg4j deliberately differs from hg, and the known issues.

2. 2. Core Architecture

2.1. 2.1 Plumbing API

  • HgRepository: the central coordinator of the .hg/ layout. It takes the working copy lock (wlock) and the store lock (lock), opens revlogs, owns the dirstate contexts (4.1 Dirstate contexts) and runs the work that is postponed until the locks are released (afterLock).

  • Dirstate: the working copy state. It reads dirstate-v1 and dirstate-v2. A v2 file is memory mapped and looked up in place; changed entries are kept as an overlay and are written by appending to the data file, as the original does (4.2 Dirstate storage).

  • Revlog: index (.i) and data (.d) files, inline and split, generaldelta, revlog-v2 (docket) and changelog-v2 with sidedata. Compression: zlib and zstd.

  • TreeWalk and ChangesetGraph: traversal of manifests and working copies (package treewalk) and of the revision graph (package revwalk). There is no class named RevWalk; the revision graph is walked with ChangesetGraph, RevFilter and SortOrder.

  • match and fileset packages: the pattern matcher (path:, glob:, re:, rootfilesin: …​), the fileset language (parser, analysis, optimiser, 24 predicates) and the -I/-X/set: selection that the porcelain commands share.

2.1.1. Contracts by class

Each item states what the Javadoc promises. "Lock" means the lock the caller must already hold; the plumbing classes check it only where it says so.

Repository and HgRepository (package lib)
  • Repository.open(File) returns an HgRepository and throws HgRepositoryNotFoundException when there is no .hg directory. new HgRepository(File) reads requires and ignores read errors, leaving the defaults.

  • Thread safety: the class Javadoc calls it thread-safe for parallel reads; most methods are synchronized. The lock methods lockWorkingCopy and lockStore deliberately are not, so that a thread waiting for a lock does not block the other methods of the object.

  • getDirstate() takes no lock and reads the file on every call, unless a changing context is open on the current thread; then the context’s instance is returned. writeDirstate(Dirstate) writes at once when no context is open, otherwise it only marks the context’s dirstate to be written when the outermost context ends normally. The caller is expected to hold wlock.

  • getRevlog(idx, dat) caches revlogs by the canonical path of the index file (100 at most, least recently used dropped), so repeated calls return the same object. After the store was changed behind the object’s back, call clearRevlogCache(); refreshIfChangedOnDisk() does this for long-lived handles when 00changelog.i changed and the cached changelog has not written locally.

  • getPhaseRoots() returns a new PhaseRoots that has read .hg/store/phaseroots at that moment.

  • getRequirements() returns the union of .hg/requires and .hg/store/requires.

  • Shared repositories (hg share): getStoreDir() follows .hg/sharedpath, which is absolute or, with the relshared requirement, relative to .hg (rcutil.get_shared_vfs). getSharedHgDir() returns the .hg directory that holds the store, or null when the repository is not shared. A share-safe working copy reads the .hg/hgrc of that directory before its own.

  • Shared bookmarks: isBookmarksShared() is true when .hg/shared lists bookmarks (hg share -B) and the bookmarks are not in the store. getBookmarksFile() is then the shared repository’s .hg/bookmarks. A command that writes the file calls mirrorSharedBookmarks() afterwards, so that the working copy’s own .hg/bookmarks has the same content, as hgext/share.py writes both (the own file is what remains after unshare).

HgLock (package lib)
  • A lock file taken atomically (a symlink on POSIX systems, a newly created file elsewhere), tracked per JVM by path, so it excludes both other threads and the real hg. close() releases it; a second close() of the same instance does nothing.

  • Taking a lock again on the thread that already holds it succeeds (isReentrant() is then true) and counts one more level; the file is removed when the last level closes. HgLock(File) fails at once; HgLock(File, timeoutMs) waits that long.

  • afterLock actions of HgRepository run once, when the last lock this thread holds on that repository is closed, or at once when none is held. A failing action is logged, never thrown.

  • The owner written in the lock file is the original’s: host/<pid namespace inode>:pid on Linux (lock._getlockprefix), host:pid where there is no pid namespace. Only a lock whose owner has this host’s prefix and a dead pid is broken; a lock with another prefix is waited for until the timeout, as the original does (a lock of the older form host:pid that earlier hg4j versions wrote has to be removed by hand once).

  • A thread that waits for a lock that another thread of the same JVM holds is woken when that lock is released; a lock held by another process is polled every 50 ms. The order of the waiters is not fair.

  • HgLock.noOp() is a lock that does nothing.

NodeId (package lib)
  • An immutable 20-byte node id. The constructor and getBytes() copy the array; NodeId.NULL is 20 zero bytes; fromHex needs exactly 40 hex digits. toString() is the first 12 hex digits only; use toHex() for the full id.

ProgressMonitor (package lib)
  • start(title, totalWork) (UNKNOWN = -1), then update(completed) with the work done since the previous call (not a running total), then end(). Long operations poll isCancelled() and stop early. message(String) is ignored unless overridden.

Dirstate (package dirstate)
  • Lock: reading and writing take none; hold wlock (inside changingFiles or changingParents, HgRepository calls write once at the end).

  • addEntry, removeEntry, addCopy, setParents, setV2 and every change through getEntries() or getCopyMap() (both return the live maps) are in memory only until write(File).

  • read(File) maps a v2 data file read-only and uses it in place; a lookup through getEntries() can throw UncheckedIOException when that file cannot be read. read(byte[]) parses v1 only and does not clear the copy map first.

  • write(File) for v1 replaces the file atomically. For v2 it appends the changes to the data file and then replaces the docket atomically; it writes a new data file (new uid) and deletes the old one when the file on disk is no longer the one that was read or at least half of the data file is unreachable.

  • serialize() always gives the v1 form and does not store the nanosecond part. DirstateV2Serializer.serialize produces only the data file (no docket, no copy records); Dirstate.write is the way to get a complete v2 dirstate. DirstateV2Node is the fixed 44-byte node layout over a ByteBuffer; LazyEntryMap is package private, reached only through getEntries().

  • Dirstate.Entry is an immutable record; time must be 0 to 0xFFFFFFFF (AMBIGUOUS_TIME marks an untrusted mtime) and a negative size means "compare the content" (isStatAmbiguous()).

  • No thread safety is stated for Dirstate; the changing contexts of HgRepository are per thread.

Revlog and RevlogIndex (package storage)
  • Thread safety: the public methods are synchronized per instance. They take no repository lock.

  • Reading needs no lock. getRevisionContent(rev) strips the leading metadata block (copy information), keeps the 100 most recently used results and returns a copy; getRawRevisionContent(rev) returns the stored text as written. rev = -1 gives an empty array; a revision number out of range throws HgRevisionNotFoundException; a censored revision throws HgCensoredContentException from getRevisionContent.

  • Writing needs the store lock (HgRepository.lockStore()): appendRevision(…​) and its overloads, appendRawRevision, appendOptimizedRevision, truncate. The methods do not take it and do not check it.

  • appendRevision writes and syncs the files, updates the in-memory index and the persistent nodemap, and splits an inline revlog into index and data files at 131072 bytes. Revisions are stored as a delta against parent1 when that is smaller and the chain is shorter than 100; the first revision and manifest and changelog revisions are stored whole.

  • Node id rule: SHA-1 over the two parent node ids in ascending byte order, then the stored text (the content preceded by the metadata block when there is metadata). When a revision with that node id exists, nothing is written and the existing node id is returned. For an externally stored (LFS) revision the hash can be computed over other bytes (hashBasisOverride).

  • appendRawRevision and appendOptimizedRevision keep the node id the caller gives, write a version 1 record (no version 2 handling), do not check that the node matches the content and do not look for duplicates. They exist for restoring and rewriting revlogs.

  • truncate(keepCount) shortens the files. Call it on a Revlog loaded from the untruncated files, once per instance; the instance is stale afterwards, so clear the repository’s revlog cache before reopening. The caller holds the store lock and journals the cut.

  • Index records are numbered from 0; getRevisionCount() re-checks the index file for changes made by other writers. findRevision(byte[]) uses the first 20 bytes and returns -1 when the node is unknown. The node field of an IndexRecord is a 32-byte field whose first 20 bytes are the node id.

TreeWalk, TreeIterator, ManifestWalk, WorkingDirWalk (package treewalk)
  • None of them is thread-safe and none takes a lock. All of them hand out paths in ascending UTF-8 order.

  • TreeWalk visits the union of its trees once per path; addTree resets the tree at once and the index of a tree is the order of adding. getNodeId(i) is null for a tree without node ids (the working copy); isSymlink(i) is true only for a ManifestTreeIterator.

  • ManifestWalk and WorkingDirWalk read nothing until the first traversal. The first next() loads the whole manifest (or scans the whole working copy) and caches it, so the walk is a snapshot taken at that moment; reset() rewinds the cursor and does not re-read. The cursor (next(), getEntry()) and the lazy view (lazyEntries(), getEntries()) share one reader: use one style per instance.

  • Treemanifest subdirectories are expanded by ManifestWalk, so only files come out. A null, empty, -1 or null revision gives an empty walk.

  • WorkingDirTreeIterator reports files on disk plus every path of the dirstate; paths unknown to the dirstate have state ?.

ChangesetGraph, RevFilter, SortOrder (package revwalk)
  • A ChangesetGraph reads parent links from the changelog index. Its settings are not synchronized and the instance caches ancestor answers per pair of revisions (cache access is synchronized), so use one parent lookup consistently and one instance per thread.

  • lazyAncestors(rev) returns a single-use iterator that is not thread-safe. With SortOrder.DEFAULT it is breadth first and lazy; with SortOrder.TOPO the whole ancestry is computed first and every revision comes before its parents. A revision is -1 for "no parent". getAllAncestors, isAncestor and getLcaCandidates ignore the filter; a revision is its own ancestor.

  • MaxCountRevFilter is stateful: use a new instance (or reset()) for each traversal.

Merge3 and MergeState (package merge)
  • Merge3.merge(base, yours, theirs) is a pure function on lists of lines; a conflicting block gets conflict markers and isConflicted() is true.

  • MergeState reads and writes .hg/merge/state2 in the format the real hg resolve uses. read takes no lock and gives an inactive state for a missing file. write overwrites in place without a temporary file; hold wlock while a merge state changes. Changes by addMergedFile, markResolved and markUnresolved are in memory until write.

PhaseRoots (package phase)
  • new PhaseRoots(File) reads the file once. setPhase changes the roots and writes the file at once; no lock is taken. The file lives in .hg/store/phaseroots, so hold the store lock when another process may write.

  • getRoots(phase) returns the recorded boundary nodes, not every changeset in that phase; getPhase computes the effective phase through the ancestors, using a parent lookup function or a changelog. A null node or the null node is public.

ObsStore, ObsUtil, HgObsMarker, HgObsolescenceParser (package obsolete)
  • ObsStore.read understands both obsstore versions (0 and 1); HgObsolescenceParser.parse understands version 1 only. HgObsMarker is an immutable marker with defensive copies.

  • ObsUtil.successorsSets ports obsutil.successorssets (the latest successors of a changeset: a replacement, a split, a divergence, a pruned changeset); UpdateCommand uses it for the destination of a bare update.

  • ObsStore.pushMarker takes the store lock itself. HgObsMarker.writeMarker(storeDir, …​) appends a version 1 marker to obsstore and takes no lock.

2.1.2. Examples

Change the dirstate while holding the working copy lock. The lock is taken first; the dirstate is written once when the outermost context ends without an exception. A change reaches the disk only if writeDirstate is called inside the context.

import io.github.search5.hg4j.dirstate.Dirstate;
import io.github.search5.hg4j.lib.HgLock;
import io.github.search5.hg4j.lib.HgRepository;
import java.io.File;

HgRepository repo = new HgRepository(new File("/path/to/repo"));
try (HgLock wlock = repo.lockWorkingCopy()) {
    repo.changingFiles(() -> {
        Dirstate dirstate = repo.getDirstate();       // the context's instance
        dirstate.addEntry("docs/new.txt",
                new Dirstate.Entry('a', 0100644, -1, Dirstate.Entry.AMBIGUOUS_TIME));
        repo.writeDirstate(dirstate);                  // deferred until the context ends
        return null;
    });                                                // the dirstate is written here
}

Read the history with Revlog and ChangesetGraph. No lock is needed for reading.

import io.github.search5.hg4j.lib.HgRepository;
import io.github.search5.hg4j.lib.NodeId;
import io.github.search5.hg4j.revwalk.ChangesetGraph;
import io.github.search5.hg4j.revwalk.MaxCountRevFilter;
import io.github.search5.hg4j.revwalk.SortOrder;
import io.github.search5.hg4j.storage.Revlog;
import java.io.File;
import java.util.Arrays;
import java.util.Iterator;

HgRepository repo = new HgRepository(new File("/path/to/repo"));
Revlog changelog = repo.getRevlog(
        new File(repo.getStoreDir(), "00changelog.i"),
        new File(repo.getStoreDir(), "00changelog.d"));
int tip = changelog.getRevisionCount() - 1;

ChangesetGraph graph = new ChangesetGraph(changelog);
graph.setSortOrder(SortOrder.TOPO);
graph.setRevFilter(new MaxCountRevFilter(10));          // a new filter for every traversal
for (Iterator<Integer> it = graph.lazyAncestors(tip); it.hasNext(); ) {
    int rev = it.next();
    Revlog.IndexRecord rec = changelog.getIndexRecord(rev);
    String node = new NodeId(Arrays.copyOf(rec.getNodeId(), 20)).toHex();
    byte[] text = changelog.getRevisionContent(rev);
    System.out.println(rev + " " + node + " parents " + rec.getParent1() + "," + rec.getParent2()
            + " (" + text.length + " bytes)");
}

2.2. 2.2 Porcelain API

Every workflow is a command object created from the Hg facade or directly from its class, configured with setters and run with call().

// Initialize a repository
HgRepository repo = Hg.init().setDirectory(new File("/path/to/repo")).call();

// Add files and commit
Hg.add(repo).addFile(new File(repo.getDirectory(), "README.md")).call();
Hg.commit(repo).setMessage("Initial commit").setAuthor("dev <dev@example.org>").call();

// Inspect
Status status = Hg.status(repo).call();

Commands that change the repository take the locks themselves, in the order the original takes them (4. Locking and Transactions). A caller does not have to lock anything around a command.

3. 3. Command Surface

The names below are the classes of the api package (suffix Command left out).

Area Commands

Working copy

Init, Add, Addremove, Remove, Forget, Copy, Rename, Revert, Purge, Status, Diff, Resolve, Update, Merge, Summary, Root, Worktree

History

Commit, Amend, Log, Tip, Heads, Parents, Identify, Describe, Annotate, Grep, Cat, Files, Locate, Manifest, Tree, Revset, Bisect

Rewriting

Rebase, Graft, Backout, Histedit, Shelve, Strip, Phase, Censor

Names

Branch, Branches, Tag, Tags, Bookmark

Exchange

Clone, Pull, Push, Fetch, Incoming, Outgoing, Bundle, Unbundle, Archive, Clonebundles, NarrowClone, ShardedStreamBundles, Unshare, Paths

Maintenance

Verify, Recover, Rollback, Gc, AdminVerify, NarrowServerAdmin

Signing and extensions

Sign, Sigs, SigCheck, Subrepo, LfsUpload

Transports: local paths, HTTP(S) and SSH, with the [auth] configuration sent after a 401 challenge, and the server side of the wire protocol (HgHttpWireServer, HgSshWireServer). The wire protocol is version 1; the HTTP version 2 was removed. The SSH client has an experimental upgrade to version 2 that stays off unless the JVM property hg4j.ssh.v2.enabled=true is set.

4. Command Reference

Each command below lists its setters, its execution method, the locks it takes, and the differences from Mercurial that its source documents. Everything is taken from the source of the api package; a missing item means the source does not state it.

4.1. Working copy commands

4.1.1. Init

Creates a new repository (hg init). Writes .hg/requires, creates .hg/store and the legacy .hg/00changelog.i guard file, and returns an HgRepository. The baseline requirements dotencode, fncache, generaldelta, revlogv1 and store are always written; the setters below add to them. Every setter defaults to false.

Method Meaning

setDirectory(File)

Directory in which the repository is created (.hg is created inside it). Created with its parents if missing. No default; call() fails if it is not set.

setDirstateV2(boolean)

Adds the dirstate-v2 requirement.

setUseZstd(boolean)

Adds the revlog-compression-zstd requirement.

setChangelogV2(boolean)

format.exp-use-changelog-v2: adds exp-changelog-v2 (the changelog uses the docket-based revlog v2 format).

setSidedataCopies(boolean)

format.exp-use-copies-side-data-changeset: adds exp-copies-sidedata-changeset (commits carry a SD_FILES sidedata record). Implies setChangelogV2.

setTreemanifest(boolean)

experimental.treemanifest: adds treemanifest (manifests are split recursively per directory).

setPersistentNodemap(boolean)

format.use-persistent-nodemap: adds persistent-nodemap (a <radix>.n nodemap trie is maintained).

setFileIndexV1(boolean)

format.use-fileindex-v1: adds fileindex-v1 (a radix-trie file index replaces the fncache store layout) and drops fncache/dotencode. Implies setPersistentNodemap.

setGeneralV2(boolean)

experimental.revlogv2: adds exp-revlogv2.2 (manifests and filelogs use the general revlog v2 format) and drops revlogv1. Implies setFileIndexV1 and setPersistentNodemap.

Execution: HgRepository call() throws IOException. Throws IllegalStateException if no directory is set; HgRepositoryNotFoundException if a directory cannot be created, a path is not a directory, or .hg/requires/.hg/00changelog.i cannot be written; HgValidationException for treemanifest combined with fileindex-v1 or general-v2.

Locks and dirstate: no lock is taken; no changing_files/changing_parents context.

Differences from hg: the single-file, non-share-safe .hg/requires layout is always used (no .hg/store/requires split); the javadoc states that real hg accepts this layout. The implication rules and the treemanifest abort message mirror real hg.

HgRepository repo = new InitCommand()
        .setDirectory(new File("/work/proj"))
        .setDirstateV2(true)
        .call();

4.1.2. Add

Starts tracking files (hg add).

Method Meaning

addFile(String)

Queues one exact repository-relative path of an existing file or symlink (backslashes become /; null or empty is ignored). When any addFile path is given, call() adds exactly these paths and the pattern selection is not used.

setPatterns(String…​)

hg add [FILE]…​: patterns (kind:pattern, set:EXPRESSION).

setInclude(String…​)

hg add -I.

setExclude(String…​)

hg add -X.

setCwd(String)

Current directory relative to the repository root, used to read relative patterns.

setSubrepos(boolean)

hg add -S: also add unknown files of hg subrepositories. Without it only files named exactly reach into a subrepository.

getSubrepoMessages()

Messages about subrepositories (for example skipping missing subrepository).

Execution: void call() throws IOException, HgLockException. Throws HgValidationException when an explicit path does not exist or is neither a regular file nor a symlink (a dangling symlink is accepted). With no addFile paths and no selection, every untracked file from scanWorkingCopy() is added. With a selection: unknown files that match, removed files that are back on disk, and ignored files only when named exactly.

Locks and dirstate: lockWorkingCopy(), then changingFiles(…​) around adding the files and the subrepository pass. Each subrepository is added under its own working copy lock while the parent lock is held.

Differences from hg: none noted in the source beyond mirroring commands.add. A path that already has a dirstate entry that is not state a is restored to state n with an ambiguous stat (as real hg’s normallookup); an entry already in state a is left alone.

new AddCommand(repo)
        .setPatterns("src/**.java")
        .setExclude("glob:**/Test*.java")
        .call();

4.1.3. Addremove

Adds all untracked files and marks all missing tracked files as removed (hg addremove).

Method Meaning

setSubrepos(boolean)

hg addremove -S: also add and remove in hg subrepositories. A subrepository always recurses into its own subrepositories.

getMessages()

What the last call said besides the changed files (for example skipping missing subrepository).

Execution: List<String> call() throws IOException, HgLockException. Returns status-style lines such as A path/new.txt and R path/gone.txt.

Locks and dirstate: lockWorkingCopy(timeout) with the timeout from resolvePushLockTimeoutMs(), taken before any repository state is read. With subrepositories enabled, they are processed first, each under its own lock. The additions and removals are delegated to AddCommand.call() and RemoveCommand.call() (forced), which take the same lock again and use their own changing_files context. AddremoveCommand itself does not open changing_files.

Differences from hg: no pattern, include, exclude, similarity or dry-run options are present in the source.

List<String> changes = new AddremoveCommand(repo).call();

4.1.4. Remove

Untracks files and deletes them from the working directory (hg remove).

Method Meaning

setFile(String)

Single path used by call().

setForce(boolean)

Remove files with uncommitted changes (added or modified) anyway, like hg remove -f. Default false, which refuses them.

setPatterns(String…​)

Patterns for callSelected().

setInclude(String…​)

-I: only files matching these patterns (globs by default).

setExclude(String…​)

-X: not the files matching these patterns (globs by default).

setCwd(String)

Current directory relative to the repository root, against which relative patterns are read.

setSubrepos(boolean)

-S: also remove in every hg subrepository the patterns reach. Without it only named subrepositories are entered.

getWarnings()

What the last callSelected() left undone, in Mercurial’s words.

Execution:

  • boolean call() throws IOException, HgLockException: removes the single file and returns true when it was removed. Throws IllegalStateException without a file, HgValidationException if the file is not tracked, or (without force) is added or modified.

  • List<String> callSelected() throws IOException, HgLockException: removes the tracked files the patterns select and returns the removed paths. Throws HgValidationException("no files specified") without patterns. Files that cannot be removed safely (marked for add, modified) are left and reported in getWarnings() unless forced; the others are removed.

Locks and dirstate: lockWorkingCopy() then changingFiles(…​) in both methods. Subrepositories take their own working copy lock. A file removed with force while in state a is only forgotten and stays on disk; other files are deleted from disk and marked r.

Differences from hg: none noted beyond the above.

new RemoveCommand(repo)
        .setPatterns("old/*.txt")
        .callSelected();

4.1.5. Forget

Stops tracking files without touching the working copy (hg forget).

Method Meaning

setFile(String)

Single path used by call().

setPatterns(String…​)

Patterns for callSelected().

setInclude(String…​)

-I.

setExclude(String…​)

-X.

setCwd(String)

Current directory relative to the repository root.

getWarnings()

What the last callSelected() left undone.

Execution:

  • void call() throws IOException, HgLockException: forgets one file (setFile is required). A file that was only added is dropped from the dirstate; a committed file is marked removed for the next commit. The file on disk is never touched. Throws IllegalStateException without a file, HgValidationException("File is not tracked: …​").

  • List<String> callSelected() throws IOException, HgLockException: forgets the selected files and returns them. Throws HgValidationException("no files specified") without patterns. A file in state a becomes unknown; a committed one is marked r.

Locks and dirstate: lockWorkingCopy() then changingFiles(…​). Subrepositories forget only files the parent’s matcher names inside them, each under its own lock; what a subrepository forgot is reported with its path in front, and a missing subrepository is skipped with a warning.

Differences from hg: none noted.

List<String> gone = new ForgetCommand(repo)
        .setPatterns("build/**")
        .callSelected();

4.1.6. Copy

Copies a tracked file and records the copy source (hg copy).

Method Meaning

setSource(String)

Repository-relative path of the tracked source for call(). Required there.

setDestination(String)

Repository-relative destination path for call(). Required there.

setForce(boolean)

Overwrite an existing destination (--force). Default false.

setPatterns(String…​)

SOURCE…​ DEST for callPatterns(), as on the command line. Each is a pattern (kind:pattern; plain names are relative to setCwd); the destination must be an existing directory with several sources.

setAfter(boolean)

--after: record a copy that already happened on disk.

setDryRun(boolean)

--dry-run: only report what would be done.

setForget(boolean)

--forget: unmark the destinations as copies; files stay.

setAtRev(String)

--at-rev REV: record (or with forget, remove) the copy in changeset REV, which is replaced by a changed copy. Needs setAfter or setForget; REV must be a draft without children.

setInclude(String…​)

-I.

setExclude(String…​)

-X.

setCwd(String)

Current directory relative to the repository root.

Execution:

  • void call() throws IOException, HgLockException: single copy. Copies the source to the destination, marks the destination as added and records the copy source when real hg would; the source is left unchanged. Throws IllegalStateException without source and destination, HgRepositoryNotFoundException if the source does not exist on disk, HgValidationException if the destination exists without force or the source is not tracked (or is state r). The constructor throws IllegalArgumentException for a null repository.

  • PatternResult callPatterns() throws IOException, HgLockException: returns record PatternResult(boolean failed, List<String> warnings, List<String> status). Takes all of the options above. Like real hg it warns and continues on files it cannot handle; warnings and status are the lines real hg prints, and failed() is true when a file was not handled (exit status 1).

Locks and dirstate: call() takes lockWorkingCopy() then changingFiles(…​); the dirstate is written once when the context ends and not at all on failure. callPatterns() (through CopyEngine) takes lockWorkingCopy() and then changingFiles(…​), writing the dirstate unless dry run. With atRev it takes the working copy lock but no dirstate changing context.

Differences from hg: the class javadoc lists verified behavior: a copy chain collapses to the earlier source only while the immediate source is an uncommitted add (state a); copying a freshly added file that was never a copy stores no copy metadata; symlinks are copied as links.

new CopyCommand(repo)
        .setSource("a.txt")
        .setDestination("b.txt")
        .call();

4.1.7. Rename

Moves a file and records the rename (hg rename / hg mv).

Method Meaning

setSource(String)

Repository-relative path of an existing file or symlink (a dangling symlink is allowed) for call(). Required there.

setTarget(String)

Repository-relative target path for call(). Required there.

setPatterns(String…​)

SOURCE…​ DEST for callPatterns(), as on the command line. Each is a pattern (kind:pattern; plain names are relative to setCwd); the destination must be an existing directory with several sources.

setForce(boolean)

-f/--force: overwrite an existing destination (only for callPatterns()).

setAfter(boolean)

--after: record a rename that already happened on disk.

setDryRun(boolean)

--dry-run: only report what would be done.

setForget(boolean)

--forget: unmark the destinations as copies (the files stay).

setAtRev(String)

--at-rev REV: the rename is recorded in (or, with setForget, removed from) the changeset REV, which is replaced by a changed copy of itself. Needs setAfter or setForget; REV must be a draft without children.

setInclude(String…​)

-I.

setExclude(String…​)

-X.

setCwd(String)

Current directory relative to the repository root.

Execution:

  • void call() throws IOException, HgLockException: single rename. Throws IllegalStateException without source and target, HgRepositoryNotFoundException if the source does not exist. Moves the file (replacing an existing target and creating parent directories), marks the source r, the target a, and records the copy. The dirstate is written once at the end and not at all if anything fails (the moved file is not moved back).

  • PatternResult callPatterns() throws IOException, HgLockException: hg rename [OPTION]…​ SOURCE…​ DEST with all of the options. Returns the same PatternResult record as CopyCommand (real hg warns and goes on for a file it cannot handle; failed() says so).

Locks and dirstate: same as CopyCommand. call() and callPatterns() both run CopyEngine, which takes lockWorkingCopy() and then changingFiles(…​).

Differences from hg: none for call(). It runs the same engine as callPatterns() and refuses what hg rename refuses (checked against hg 7.2): a source that is not tracked (not copying - file is not managed), a source marked for removal (not copying - file has been marked for remove) and an existing target without setForce(true) (not overwriting - file exists), each as HgValidationException carrying the warning and no files to copy. A source that was only added is moved without a copy record, and renaming a renamed file keeps the first source as the copy source. Before 2026-11 call() skipped these checks and replaced an existing target silently.

new RenameCommand(repo)
        .setSource("old.txt")
        .setTarget("new.txt")
        .call();

4.1.8. Revert

Restores files to a revision (hg revert). Default target is the first parent.

Method Meaning

setFile(String)

Single path for call().

setRevision(String)

Revision to revert to (-r), resolved against the changelog. null or empty (the default) means the first parent of the working directory.

setPatterns(String…​)

Patterns for callSelected() (kind:pattern, set:EXPRESSION; a bare name is relative to the current directory).

setInclude(String…​)

-I: only files matching these patterns (globs by default).

setExclude(String…​)

-X: not the files matching these patterns (globs by default).

setCwd(String)

Current directory relative to the repository root, against which relative patterns are read.

setAll(boolean)

--all: every changed file.

getWarnings()

What the last callSelected() left undone.

getSubrepoMessages()

Subrepository messages (reverting subrepo NAME).

Execution:

  • boolean call() throws IOException, HgLockException: reverts one file to its state in the target revision and returns true when it was reverted. Throws IllegalStateException without a file; HgValidationException when the repository has no parent commit and the file is not an added file.

  • List<String> callSelected() throws IOException, HgLockException: reverts modified, added, removed and deleted files that match; returns the reverted paths, sorted. getWarnings() and getSubrepoMessages() are reset at the start of each call. Throws HgValidationException when no files, patterns or setAll are given (with a hint), with an uncommitted merge and no revision, or when a matching subrepository does not exist in the target revision; HgRevisionNotFoundException when the revision cannot be resolved.

Locks and dirstate: call() takes lockWorkingCopy() then changingFiles(…​). callSelected() reads parents and resolves the revision before the lock, then holds lockWorkingCopy() for the status read and for the per-file call() invocations (which re-enter the lock and their own changingFiles). Subrepositories matched by the selection are reverted and then updated to the recorded revision.

Differences from hg (class javadoc): a modified file is backed up to <file>.orig before overwrite, a clean file is not; reverting an added, never committed file only untracks it and leaves it on disk; a file absent from the target revision is deleted and marked r.

new RevertCommand(repo)
        .setPatterns("a.txt")
        .setRevision("tip")
        .callSelected();

4.1.9. Purge

Deletes untracked, non-ignored files and empty directories (hg purge, hg clean).

Method Meaning

setPurgeIgnored(boolean)

--all: ignored files and the directories they leave empty are removed too.

setPurgeFiles(boolean)

--files, on by default. When false, files stay and only empty directories can be removed.

setPurgeDirectories(boolean)

Remove untracked directories that end up empty. Default true; false leaves them (restricting the purge like hg purge --files).

Execution: void call() throws IOException. Every entry under the repository root that is not in the dirstate is a candidate; ignored paths are kept unless setPurgeIgnored is set. Files are deleted if setPurgeFiles is on, then untracked directories that are empty are deleted if setPurgeDirectories is on.

Locks and dirstate: no lock is taken; the dirstate is only read and not written; no changing_files/changing_parents context.

Differences from hg (class javadoc): a directory symlink is treated as one opaque entry and never traversed; dangling symlinks are deleted; declared subrepository paths and .hg are never entered. The default removes empty directories, as real hg does.

new PurgeCommand(repo)
        .setPurgeIgnored(true)
        .call();

4.1.10. Status

Compares the working directory with the dirstate and the parent commit (hg status).

Method Meaning

setTreeFilter(HgTreeFilter)

Restricts the paths examined (narrow support); null is ignored. The default HgTreeFilter.ALL uses the faster dirstate-based scan.

setPatterns(String…​)

Files to report (patterns, kind:pattern, set:EXPRESSION).

setInclude(String…​)

-I.

setExclude(String…​)

-X.

setCwd(String)

Current directory relative to the repository root.

Execution: Status call() throws IOException. Computes the status against the first parent; only paths matching the patterns, include and exclude options are reported. Never returns null. Status has getAdded(), getModified(), getRemoved(), getClean() and getUntracked(), each a Set<String>.

Locks and dirstate: the status itself takes no lock. When it finds entries whose stat can be refreshed, it applies them with lockWorkingCopy(0) (never waited for; the fixes are dropped if the lock is not free at that moment), following _poststatusfixup. No changing_files/changing_parents context.

Differences from hg: none stated.

Status s = new StatusCommand(repo)
        .setPatterns("src")
        .call();
Set<String> modified = s.getModified();

4.1.11. Diff

Computes per-file unified diffs between two revisions (hg diff -r OLD -r NEW). The working directory is not compared in this class.

Method Meaning

setOldRevision(int)

Old revision number (hg diff -r OLD:NEW). Default is the first parent of the new revision; -1 compares against an empty manifest.

setOldRevision(NodeId)

Old revision by node. null restores the default (first parent of the new revision); a node not found in the changelog is treated as an empty manifest.

setNewRevision(int)

New revision number. Default is tip; -1 compares against an empty manifest.

setNewRevision(NodeId)

New revision by node. null restores the default (tip); a node not found in the changelog is treated as an empty manifest.

setTreeFilter(HgTreeFilter)

Restricts the diff to paths the filter accepts, in addition to any pattern selection. null is ignored and the previous filter (initially accept-all) stays.

setPatterns(String…​)

Files to diff (kind:pattern, set:EXPRESSION).

setInclude(String…​)

-I.

setExclude(String…​)

-X.

setCwd(String)

Current directory relative to the repository root.

Execution: List<DiffEntry> call() throws IOException. Each DiffEntry has getPath(), getChangeType() (ADD, MODIFY, DELETE) and getDiffContent() (unified diff text). One entry is returned per differing file that passes the tree filter and the pattern selection. Without further settings it diffs the tip against its first parent. Returns an empty list when the repository has no changesets.

Locks and dirstate: none; it writes nothing and uses no dirstate context. It calls refreshIfChangedOnDisk() first.

Differences from hg: the javadoc notes that an explicit -1 new revision means an empty manifest rather than tip (sentinel NOT_SET).

List<DiffCommand.DiffEntry> d = new DiffCommand(repo)
        .setOldRevision(1)
        .setNewRevision(2)
        .call();

4.1.12. Resolve

Reads and updates merge conflict state (hg resolve), the counterpart of MergeCommand. Works on .hg/merge/state2.

Method Meaning

setFile(String)

Repository-relative path of a file in the current merge state to mark. null (the default) marks nothing; it only has an effect together with markResolved or markUnresolved.

markResolved(boolean)

Mark the file resolved (hg resolve --mark). Default false.

markUnresolved(boolean)

Mark the file unresolved (hg resolve --unmark). Default false; ignored if markResolved is also true.

list(boolean)

Return the state of every file of the merge state (hg resolve --list) even when a file was marked. Default false. Without a marking, all files are returned either way.

Execution: Map<String, Boolean> call() throws IOException, HgLockException. The map goes from path to resolved (true) or unresolved (false). When marking without list, only the marked file is returned. Throws HgValidationException when marking outside a merge ("resolve command not applicable when not merging") or for a path not in the merge. The constructor throws IllegalArgumentException for a null repository.

Locks and dirstate: lockWorkingCopy(timeout) with resolvePushLockTimeoutMs(), taken before the merge state is read. No changing_files/changing_parents context.

Differences from hg: none stated. Re-running merge tools is not present in this class (source does not show it).

Map<String, Boolean> m = new ResolveCommand(repo)
        .setFile("a.txt")
        .markResolved(true)
        .call();

4.1.13. Update

Checks out a revision into the working copy (hg update).

Method Meaning

setRevision(String)

Target revision: "null" (empties the working copy), a bookmark name, a revision number, a node hex or prefix, or a named branch, which selects the highest-numbered revision on it, looked up in this order. Unresolvable or ambiguous values throw. Without a revision (null or empty) the update is a bare hg update and goes where destutil.destupdate goes: the successors of an obsolete working directory parent without children (its closest live ancestor when it was pruned), then the active bookmark when it is away from the parent, then the tipmost open head of the current branch that descends from the parent, then the same with closed heads, then the tip.

setForce(boolean)

Update even with uncommitted changes, like hg update -C. Default false: added, modified or removed files make the update fail.

setTreeFilter(HgTreeFilter)

Restricts which paths are checked out (narrow support); null is ignored. If left at the default ALL, the repository’s narrowspec is used.

registerPreUpdateHook(HgHook)

Hook run before the update (context keys repository, targetRevision, force); returning false rejects it. null is ignored.

registerPostUpdateHook(HgHook)

Hook run after the update (context keys targetNode, repository); failures are logged and ignored. null is ignored.

setProgressMonitor(ProgressMonitor)

Receives the progress of LFS downloads and the lines Mercurial prints about them.

Execution: byte[] call() throws IOException, HgLockException. Returns the 20-byte node id of the revision that is now checked out. Throws HgValidationException ("Working directory has uncommitted changes. Use force to update.", "Repository is empty, cannot update.", "Update rejected by PRE_UPDATE hook"), HgRevisionNotFoundException (revision cannot be resolved or is ambiguous), HgRepositoryNotFoundException (a filelog index is missing for a tracked file).

Locks and dirstate: lockWorkingCopy(), then changingParents(…​) around the whole update (dirstate written when it ends well). After checkout it sets the working copy’s branch to that of the revision (default for null), recurses into subrepositories and sets the active bookmark as update_totally does: a bookmark’s name activates it, any other name deactivates the active bookmark, and a bare update leaves it, or moves it along when it was on the working directory parent (to a descendant or, with obsolescence markers, a successor; divergent name@x bookmarks that the move passes are deleted; a non-linear update deactivates it).

Differences from hg: hook support is an hg4j addition. The status lines (updating bookmark m, (leaving bookmark m)) are not printed.

byte[] node = new UpdateCommand(repo)
        .setRevision("default")
        .setForce(false)
        .call();

4.1.14. Merge

Merges a target revision into the working copy (hg merge), and aborts an unfinished merge (hg merge --abort).

Method Meaning

setNodeId(byte[])

Target by 20-byte node id. Takes precedence over setRevision. null clears it.

setNodeId(NodeId)

Target by node id. Takes precedence over setRevision. null clears it.

setRevision(int)

Target by changelog revision number. Used only when no node id was set. Default -1 (not set).

registerPreMergeHook(HgHook)

Hook run before the merge touches the working copy, with the working copy lock held (context keys repository, targetRev, targetNodeId). Returning false aborts the merge. null is ignored.

registerPostMergeHook(HgHook)

Hook run after the merge, while the dirstate is still being updated (context keys conflicted, conflicts, repository). Its return value is ignored and an exception it throws is logged as a warning. null is ignored.

getMessages()

What abort() printed (aborting the merge, updating back to …​).

Execution:

  • MergeResult call() throws IOException, HgLockException. MergeResult has isConflicted() (true when files have unresolved conflicts; their contents then contain conflict markers) and getConflicts() (repository-relative paths, empty when clean). Conflicts are reported in the result, not as an exception. If the target is the current parent or an ancestor of it, nothing changes; if the current parent is an ancestor of the target, the working copy is advanced to the target (fast-forward); otherwise a three-way merge is done file by file. Throws HgValidationException ("Merge rejected by PRE_MERGE hook"), IllegalStateException in an empty repository, IllegalArgumentException if neither a node id nor a valid revision number was set, HgRevisionNotFoundException if the target or the current parent is not in the changelog or no common ancestor exists.

  • void abort() throws IOException, HgLockException. Throws HgValidationException("no merge in progress") when the dirstate has no second parent, IllegalStateException when the repository has no first parent, and HgRevisionNotFoundException when the revision to go back to is not in the changelog. Restores the working copy to p1 (or the local side recorded in the merge state), resets to a single parent and clears .hg/merge/state2.

Locks and dirstate: call() takes lockWorkingCopy(), clears the revlog cache, then changingParents(…​) around the merge. abort() reads the dirstate and merge state before the lock, then takes lockWorkingCopy() and changingParents(…​). Subrepository state in .hgsubstate is merged or checked out when it changes.

Differences from hg (abort javadoc): abort rewrites every path against p1’s manifest instead of a manifest diff, because after call() the dirstate parent 1 already is p1.

MergeCommand.MergeResult r = new MergeCommand(repo)
        .setRevision(5)
        .call();
boolean conflicts = r.isConflicted();

4.1.15. Summary

Condensed overview of the working copy (hg summary). Returns a structured record instead of text.

Method Meaning

(none)

Only the constructor SummaryCommand(HgRepository); there are no public setters.

Execution: SummaryInfo call() throws IOException. Never returns null. SummaryInfo is a record: parents (none, one, or two during a merge; each ParentInfo(revision, node, description) with the local revision number or -1 if the changelog is missing or the node is unknown, the 40-character hex node id, and the full commit message or an empty string if it cannot be read), branch (current branch name), activeBookmark (null if none), modified, added, removed, unknown (counts of files), mergeInProgress (true if there are two parents), currentPhase (PhaseRoots.Phase of the first parent; public if it cannot be determined or there is no parent).

Locks and dirstate: takes no lock itself; it uses ParentsCommand, BookmarkCommand.getActiveBookmark() and StatusCommand, so the status fix-up lock behavior described under Status applies.

Differences from hg: a structured record instead of terminal text (javadoc).

SummaryCommand.SummaryInfo s = new SummaryCommand(repo).call();
String branch = s.branch();
int dirty = s.modified() + s.added() + s.removed();

4.1.16. Root

Returns the repository root (hg root).

Method Meaning

(none)

Only the constructor RootCommand(HgRepository); there are no public setters.

Execution: String call(). Returns the absolute path of the working directory. No checked exceptions.

Locks and dirstate: none.

Differences from hg: none.

String root = new RootCommand(repo).call();

4.1.17. Worktree

Creates a new working copy that shares the store of the main repository (hg share, described in the javadoc as Git-like worktree).

Method Meaning

setNewWorktreeDir(File)

Directory of the new working copy. Must not exist or be empty. Required before call().

setShareBookmarks(boolean)

hg share -B: the working copy shares the bookmarks of the source (.hg/shared lists bookmarks). They are then read from the source’s .hg/bookmarks, and every write goes to the source’s file and to the working copy’s own file. Default false.

setRelative(boolean)

hg share --relative: .hg/sharedpath holds the path of the store relative to the new .hg and requires gets relshared instead of shared. Default false.

setUpdate(boolean)

false is hg share -U: the working copy stays empty and has no dirstate. Default true.

setCheckout(String)

The revision checked out first (the branch of hg share SOURCE#BRANCH). If it cannot be found, the head of the branch default and then the tip are tried. Default null: default, then the tip.

Execution: HgRepository call() throws IOException, HgLockException. Throws IllegalStateException without a directory, IOException if the directory is not empty or if directory creation, linking or the post-share checkout fails, and HgLockException if the post-share checkout cannot acquire the locks. Writes .hg/sharedpath (canonical path of the store’s .hg; a share of a share points at the store itself), the sorted requires of the source plus shared (or relshared), .hg/shared, .hg/wcache, and .hg/hgrc with the source’s paths.default (its repository configuration, else the user’s), then returns the new HgRepository. For a narrow source (narrowhg-experimental) it writes .hg/narrowspec.dirstate from the store’s narrowspec under the working copy lock and the store lock, and leaves the rollback information of the narrow-share transaction (an empty store/undo, store/undo.backupfiles, .hg/undo.desc, .hg/undo.backup.branch.bck) as the original does, replacing the store’s own.

Locks and dirstate: lockWorkingCopy() of the new working copy during the checkout. When the store has revisions and the update is not turned off, it runs UpdateCommand (setForce(true); the checkout revision, else default, else tip, the way the original’s _post_share_update looks them up) without touching the bookmarks, which itself uses lockWorkingCopy() and changingParents(…​). The lock of the shared store is not taken, as in the original (only a narrow source takes it). For an empty store it writes a 40-byte parent stub dirstate. changing_files is not used here.

Differences from hg: none in what is written, checked file by file against hg 7.2. The empty-store stub dirstate is kept for existing test expectations.

HgRepository wt = new WorktreeCommand(repo)
        .setNewWorktreeDir(new File("/work/proj-wt"))
        .setShareBookmarks(true)
        .call();

4.1.18. Unshare

Turns a shared repository into a normal one by copying the shared store into it (hg unshare).

Method Meaning

(none)

Only the constructor UnshareCommand(HgRepository); there are no public setters.

Execution: HgRepository call() throws IOException, HgLockException. Returns a new repository object; the one passed in must not be used afterward. Throws HgValidationException("this is not a shared repo") when .hg/sharedpath is absent. Moves sharedpath to sharedpath.old, removes shared/relshared from requires, prepends the source hgrc for share-safe repositories, then unshares shared subrepositories.

Locks and dirstate: holds the shared store lock (lockStoreWithoutRecovery(timeout)) for the whole operation, plus the lock of the new store (returned by StoreCopy.copyStore) while the share is cut off. Does not take the working copy lock and does not use changing_files/changing_parents.

Differences from hg: the javadoc says it follows cmd_impls.clone.unshare; no deviation is stated.

HgRepository normal = new UnshareCommand(sharedRepo).call();

4.2. History commands

4.2.1. Commit

Commits the tracked changes of the working copy as a new changeset. Corresponds to hg commit.

Method Meaning

setMessage(String)

Commit message (hg commit -m), written as given. Required: call() throws IllegalStateException if null or empty.

setAuthor(String)

Author (hg commit -u), for example Name <mail>. Null or empty keeps the current value; the default is user <user@example.com>.

setDate(long secs, int offsetSeconds)

hg commit -d: forces the commit time. secs is seconds since the Unix epoch (UTC); offsetSeconds is the time zone offset in Mercurial’s convention, positive west of UTC, so UTC+9 is -32400. When not set, the current time and the default time zone are used.

setPatterns(String…​)

hg commit [FILE]…​: commits only the files the patterns select. The other files keep the parent’s content in the new revision and stay modified, added or removed in the working copy. Not allowed for a merge.

setInclude(String…​)

hg commit -I.

setExclude(String…​)

hg commit -X.

setCwd(String)

Current directory relative to the repository root, for relative patterns.

setExtra(String key, String value)

Adds an extra field to the new changeset (repo.commit(extra=…​)), as rebase and graft record their source.

setCloseBranch(boolean)

hg commit --close-branch: marks the new commit as closing the named branch head it becomes.

setSubrepos(boolean)

hg commit -S/--subrepos: allows a recursive commit when a subrepo declared in .hgsub has uncommitted local changes: the subrepo is committed first, then its new tip is recorded in .hgsubstate. Without it the parent commit aborts (uncommitted changes in subrepository "…​").

registerPreCommitHook(HgHook)

Registers a hook that runs inside the commit, before anything is written. It receives a map with the keys author, message and repository. A hook returning false aborts the commit with HgValidationException. null is ignored.

registerPostCommitHook(HgHook)

Registers a hook that runs after a successful commit, once the repository locks are released. It receives a map with the keys author, message, commitNode (the new 20-byte node id) and repository. A hook that throws is logged and does not fail the commit. null is ignored.

setSkipLockAndJournal(boolean)

When true, call() takes no working copy or store lock and writes no crash journal, for callers that already hold the locks and manage rollback themselves. Default false.

Execution

byte[] call() throws IOException, HgLockException. Commits the working copy changes (or only the files the pattern methods select) as a new changeset on the current branch. It writes the filelog, manifest and changelog revisions, updates the dirstate, advances the active bookmark and records undo information for rollback. If the commit fails, the store files are restored to their previous state. Returns the 20-byte node id of the new commit.

Main exceptions

HgValidationException (nothing to commit ("nothing changed"), a pre-commit hook rejects the commit, or the working copy is in a state that cannot be committed, for example unresolved merge conflicts or a partial commit of a merge), HgRevisionNotFoundException, HgRepositoryNotFoundException, IllegalStateException (no message), HgLockException (a lock cannot be acquired).

Locks and dirstate
  • Takes repository.lockWorkingCopy() first, then repository.lockStore(), then opens repository.openChangingParents() (the dirstate change context, the equivalent of dirstate.changing_parents), all in one try-with-resources. The source comment says the locks are taken before any repository state is read and released when the command ends.

  • With setSkipLockAndJournal(true) both locks become no-ops, and openChangingParents() is opened only if the working copy lock is held (holdsWorkingCopyLock()); otherwise no dirstate context is opened.

  • openChangingFiles and changingFiles are not called. ChangingFiles is only used to encode the changed-files sidedata (SD_FILES) of the new changeset.

  • Per the source comment, the dirstate is written when the context ends, after the store transaction closes, and is not touched when the commit fails.

Differences from hg

Not stated in the javadoc. The code comments say it mirrors hg’s locking and dirstate order.

byte[] node = new CommitCommand(repo)
    .setAuthor("Jane <jane@example.com>")
    .setMessage("Fix bug")
    .call();

4.2.2. Amend

Replaces the tip commit with a new commit and records an obsolescence marker. Corresponds to hg commit --amend.

Method Meaning

setAuthor(String)

hg commit --amend -u: overrides the author, for example Name <mail>. When not set, or null, the amended-away commit’s author is reused.

setMessage(String)

hg commit --amend -m: overrides the message. When not set, or null, the amended-away commit’s message is reused.

setCloseBranch(boolean)

hg commit --amend --close-branch: overrides whether the amended commit closes its branch. When not called, the old commit’s close state is kept.

Execution

byte[] call() throws IOException, HgLockException. Returns the node id of the new amended commit. Throws IllegalStateException for an empty repository ("No commits exist to amend"). The constructor throws IllegalArgumentException for a null repository.

Locks and dirstate
  • lockWorkingCopy(timeout) then lockStore(timeout), where the timeout is repository.resolvePushLockTimeoutMs(). Both are released when the command ends.

  • It then runs a CommitCommand inside these locks. That CommitCommand is not told to skip locking in the source of AmendCommand; whether the nested lock calls are reentrant is not confirmed in the source read.

  • openChangingFiles, openChangingParents, changingFiles, changingParents are not called directly by AmendCommand. The dirstate context comes from the nested CommitCommand (see Commit).

  • Writes the marker with HgObsMarker.writeMarker(storeDir, oldNode, [newNode], "amend") into .hg/store/obsstore.

Differences from hg

Mirrors hg commit --amend (cmdutil.amend()): the new commit is a sibling of the old one on the same parent(s) (base = old.p1()), not its child. Author, message and close-branch default to the old commit’s values (javadoc cites verification against hg 7.2.2). It always amends the last revision of the changelog (count - 1).

byte[] node = new AmendCommand(repo)
    .setMessage("Better message")
    .call();

4.2.3. Log

Reads the changelog and returns commit history, newest first. Corresponds to hg log.

Method Meaning

setPatterns(String…​)

hg log [FILE]…​: only the revisions that touch files matching these patterns.

setInclude(String…​)

hg log -I.

setExclude(String…​)

hg log -X.

setCwd(String)

Current directory relative to the repository root, for relative patterns.

setTreeFilter(HgTreeFilter)

Keeps only commits that have at least one changed file accepted by the filter. Default HgTreeFilter.ALL (no restriction). Null is ignored and the previous value is kept.

setFollowAncestors(boolean)

Restricts the log to the start revision and its ancestors. Only effective when a start revision is set with setStartRev. Default false.

setStartRev(String)

Revision from which ancestors are followed, resolved against the changelog when call() runs. Used only together with setFollowAncestors or setFollowPath, otherwise ignored. Default null (the tip).

setFollowPath(String)

hg log --follow <path>: starting from the path at the starting revision (setStartRev, or the tip), walks back through changelog ancestry over the revisions that touched the file, crossing rename and copy boundaries. Implies setFollowAncestors(true).

Execution

List<HgCommit> call() throws IOException. Returns the matching changesets, highest revision number first, restricted by the follow options, the tree filter and the file patterns when set; never null. Returns an empty list if the repository has no changelog (00changelog.i does not exist). Commits with malformed text are skipped with a logged warning.

Locks and dirstate

No locks and no changing_files/changing_parents. call() only calls repository.refreshIfChangedOnDisk() first, to avoid serving a stale cached changelog-v2 revlog.

Differences from hg

The javadoc says setFollowPath crosses renames through the copy/copyrev metadata in the filelog’s revision 0, the way hg does by default, not through the changelog SD_FILES sidedata.

List<HgCommit> log = new LogCommand(repo)
    .setFollowPath("src/Main.java")
    .setStartRev("tip")
    .call();

4.2.4. Tip

Returns the highest-numbered changelog revision. Corresponds to hg tip.

Setters

None.

Execution
  • byte[] call() throws IOException: node id (20 bytes) of the tip, or null if the repository has no revisions.

  • int getRevisionNumber() throws IOException: revision number of the tip, or -1 if empty.

Locks and dirstate

No locks, no changing_files/changing_parents.

Differences from hg

Tip is by revision number, not by wall clock, matching hg (javadoc).

TipCommand tip = new TipCommand(repo);
byte[] node = tip.call();
int rev = tip.getRevisionNumber();

4.2.5. Heads

Lists repository heads. Corresponds to hg heads.

Method Meaning

setBranch(String)

hg heads <branch>: every revision on that branch with no same-branch child, not just the repository-wide topological leaves. A branch with several such heads (an internal fork) returns all of them. Open heads only unless setIncludeClosed is set. An unknown branch gives an empty result instead of an exception.

setIncludeClosed(boolean)

hg heads --closed: also includes heads closed with --close-branch, both in the default mode (each branch’s closed heads are added to its open ones) and with setBranch. No effect together with setTopo(true), where a closed head without children is a topological leaf and always included.

setTopo(boolean)

hg heads --topo: pure repository-wide topological leaves (revisions with no children anywhere in the repository), ignoring named-branch mechanics. Default false, as plain hg heads is branch-aware.

Execution

List<String> call() throws IOException. Head node ids in hex, highest revision first (in the default mode, across all branches combined, not grouped by branch). Empty list for an empty repository.

Modes

With setBranch, that branch’s heads. Otherwise with setTopo(true), topological leaves. Otherwise (default) every branch’s own open heads, as plain hg heads.

Locks and dirstate

No locks, no changing_files/changing_parents.

Differences from hg

Real hg aborts with unknown revision '<name>' for an unknown branch at the CLI layer; this API returns an empty list (javadoc). The default mode reproduces plain hg heads (verified against hg 7.2.2 per the javadoc).

List<String> heads = new HeadsCommand(repo)
    .setBranch("default")
    .setIncludeClosed(true)
    .call();

4.2.6. Parents

Returns the working directory’s parent revisions. Corresponds to hg parents.

Setters

None.

Execution

List<String> call() throws IOException. Parent node ids in hex, excluding the null parent. Size 1 normally, 2 during a merge, 0 for a brand-new empty repository. Reads the dirstate parents.

Locks and dirstate

No locks, no changing_files/changing_parents. Only reads repository.getDirstate().

Differences from hg

Source does not state any.

List<String> parents = new ParentsCommand(repo).call();

4.2.7. Identify

Returns a one-line summary of a revision: id, branch, tags and bookmarks. Corresponds to hg identify (hg id).

Method Meaning

setRevision(String)

hg identify -r REV: identifies a fixed revision (hex prefix, decimal revision number or tip) instead of the working directory’s parents. No dirty marker is added.

Execution

String call() throws IOException. Output of the default (no template) hg identify.

Output rules (javadoc)
  • Id is the 12-digit short node of the working copy parent(s), joined by + during a merge, plus a trailing + if the working copy is dirty (modified, added or removed files, or an unresolved merge). An empty repository gives 000000000000.

  • The branch is shown in parentheses only when it is not default.

  • Tags and bookmarks of every current parent (not only p1) are shown, sorted alphabetically and joined by /. During an uncommitted merge a tag or bookmark that points only at p2 still appears. The pseudo-tag tip sorts where its name falls (mytag/tip, but tip/zzz).

  • With setRevision, exactly one id is shown and no dirty marker is added.

Locks and dirstate

No locks, no changing_files/changing_parents. Without a revision it reads the dirstate parents and runs StatusCommand to compute the dirty marker. Tags come from TagsCommand, bookmarks from BookmarkCommand.

Differences from hg

Javadoc says the output was verified against hg 7.2.2. With -r the branch is that revision’s own branch, not the working directory’s. An unresolvable revision is treated as the null node and shows 000000000000 (read from the code, not stated in javadoc).

String id = new IdentifyCommand(repo)
    .setRevision("tip")
    .call();

4.2.8. Describe

Describes the working directory’s parent relative to the nearest ancestor tag. Corresponds to no hg command: the format is Git-describe style (tag-distance-gShortNode). The javadoc names no hg equivalent.

Setters

None.

Execution

String call() throws IOException. Returns empty-repository for a repository without commits, the tag name when the current revision is tagged, tag-distance-g<12 hex> otherwise, and v0.0-<distance>-g<12 hex> when no ancestor tag is found. Tags are read from .hgtags in the repository directory; the walk follows first parents.

Locks and dirstate

No locks, no changing_files/changing_parents. Calls repository.refreshIfChangedOnDisk() first (a code comment explains it fixes stale reads of a changelog-v2 revlog after an external append). Reads the dirstate parent 1.

Differences from hg

There is no hg original in the source; the format is borrowed from Git.

String desc = new DescribeCommand(repo).call();

4.2.9. Annotate

Line-by-line blame of a file. Corresponds to hg annotate.

Method Meaning

setPath(String)

Repository-relative path of the file to annotate, with / separators. Required for call() (IllegalStateException if null).

setRevision(int)

Filelog revision number, a revision of the file’s own revlog (not a changelog revision). Default -1 means the file’s latest revision.

setPatterns(String…​)

hg annotate [FILE]…​: files to annotate, used by callSelected.

setInclude(String…​)

hg annotate -I.

setExclude(String…​)

hg annotate -X.

setCwd(String)

Current directory relative to the repository root, for relative patterns.

Execution
  • List<BlameLine> call() throws IOException. Each BlameLine has getLineNumber() (1-based), getRevision() (changelog revision that introduced the line), getAuthor() (unknown when it could not be read), getContent(). Returns an empty list if the revision is out of range. Throws HgRevisionNotFoundException if the filelog does not exist.

  • Map<String, List<BlameLine>> callSelected(String changeset) throws IOException: hg annotate -r REV [FILE]…​ over every file the patterns select (changeset null means tip). Needs at least one pattern, as the command line does, else HgValidationException("invalid arguments"); a named file missing from the revision gives HgValidationException; an unresolvable revision gives HgRevisionNotFoundException. Result is in path order.

Locks and dirstate

No locks, no changing_files/changing_parents.

Differences from hg

The constructor throws IllegalArgumentException for a null repository. Follows rename and copy boundaries by default, as hg does (hg has no separate --follow flag for annotate), through the copy/copyrev metadata of the filelog’s revision 0 (not the changelog sidedata). LFS content is resolved to the real bytes before diffing. A trailing newline does not create an extra empty line, as in hg.

List<AnnotateCommand.BlameLine> lines = new AnnotateCommand(repo)
    .setPath("src/Main.java")
    .call();

4.2.10. Grep

Searches a regular expression in file contents. Corresponds to hg grep.

Method Meaning

setQuery(String)

Regular expression (Java Pattern), searched for within each line with find() semantics, not as a full-line match. No default; null or empty makes call() return an empty list.

setCaseInsensitive(boolean)

hg grep -i: case-insensitive matching. Default false.

setPatterns(String…​)

hg grep PATTERN [FILE]…​: only the files these patterns select are searched.

setInclude(String…​)

hg grep -I.

setExclude(String…​)

hg grep -X.

setCwd(String)

Current directory relative to the repository root, for relative patterns.

setRevisions(String)

hg grep -r REVS: searches the files as they are in each of the given revisions (a revision set such as all() or 0:2), not the file history. Binary files are skipped. Without it, the whole history of every file is searched.

Execution

List<GrepResult> call() throws IOException. GrepResult has public fields path (repository-relative, forward slashes), hexNode (hex node id of the file revision, empty string in setRevisions mode), lineNumber (1-based), lineContent (without the line terminator), linkRevision (the changeset that introduced the file revision; in setRevisions mode the revision searched; -1 if unknown). An invalid regex throws the standard PatternSyntaxException.

Locks and dirstate

No locks, no changing_files/changing_parents.

Differences from hg

Without setRevisions it scans every revision of every tracked filelog (enumerated from fncache, or by walking store/data when fncache is absent, for example with fileindex-v1 or general-v2 repositories). LFS content is read through HgLfsFactory.

List<GrepCommand.GrepResult> hits = new GrepCommand(repo)
    .setQuery("TODO")
    .setCaseInsensitive(true)
    .setRevisions("all()")
    .call();

4.2.11. Cat

Returns the content of a file at a revision. Corresponds to hg cat.

Method Meaning

setFile(String)

Repository-relative path of the tracked file, with / separators. Required for call().

setRevision(String)

hg cat -r: revision identifier (number, hex node or prefix, tip, …​). null or empty (the default) selects the tip.

setRevision(NodeId)

Same, with a node id; null selects the tip.

setPatterns(String…​)

hg cat [FILE]…​: files to print, used by callAll.

setInclude(String…​)

hg cat -I.

setExclude(String…​)

hg cat -X.

setCwd(String)

Current directory relative to the repository root, for relative patterns.

Execution
  • byte[] call() throws IOException: content of the file. IllegalStateException if no file is set; HgRevisionNotFoundException if the revision cannot be resolved or the file is not tracked at that revision (also if the file version is not in the filelog); HgCorruptDataException if the filelog is missing.

  • Map<String, byte[]> callAll() throws IOException: path to content for every file of the revision that the patterns select, in path order. Without any pattern it throws HgValidationException("invalid arguments").

Locks and dirstate

No locks, no changing_files/changing_parents. call() starts with repository.clearRevlogCache().

Differences from hg

Content is read through HgLfsFactory, so LFS files return the real bytes. With no revision set (or null/empty), the tip is used. call() and callAll() are read-only and take no lock.

byte[] data = new CatCommand(repo)
    .setFile("README.md")
    .setRevision("tip")
    .call();

4.2.12. Files

Lists tracked files. Corresponds to hg files.

Method Meaning

setRevision(String)

Revision to list (number, hex id or prefix, tip). When unset, the working copy’s tracked set from the dirstate is listed.

setRevision(NodeId)

Revision by node id; null selects the working copy.

setTreeFilter(HgTreeFilter)

Explicit tree filter used to match paths, for example one built with HgTreeFilter.createPathPrefixFilter or wrapping a SparsePathFilter. Null resets to HgTreeFilter.ALL.

setPattern(String…​)

Glob patterns with directory-prefix semantics (through SparsePathFilter). A single set:EXPR argument is treated as a fileset.

setFileset(String)

hg files "set:EXPR": restricts the listing to the files a fileset expression selects. Supported are the MiniFileset expressions (patterns **.ext and path:, all(), none(), size(), and/or/not) plus lfs(), the files stored in LFS. A set:EXPR given to setPattern means the same.

setPatterns(String…​)

hg files [FILE]…​: patterns (relpath by default), kind:pattern and set:EXPRESSION.

setInclude(String…​)

hg files -I: only the files matching these patterns (globs by default).

setExclude(String…​)

hg files -X: not the files matching these patterns (globs by default).

setCwd(String)

Current directory relative to the repository root, for relative patterns.

Execution

List<String> call() throws IOException. Lists the tracked files that pass the tree filter and the pattern selection. Forward-slash paths sorted with NodeIdUtil.UTF8_STRING_COMPARATOR. HgRevisionNotFoundException if the revision cannot be resolved; an empty list for a repository without commits.

Locks and dirstate

No locks, no changing_files/changing_parents. Without a revision it reads the dirstate entries and excludes state r (removed); added files are included.

Differences from hg

The javadoc says the default describes the working copy, not the tip commit, as real hg files does.

List<String> files = new FilesCommand(repo)
    .setRevision("tip")
    .setPattern("src/**")
    .call();

4.2.13. Locate

Lists files under version control whose names match a pattern. Corresponds to hg locate.

Method Meaning

setPattern(String)

Single relglob pattern: an unrooted glob matched against any directory level (.txt matches a.txt and sub/b.txt; sub/.txt matches only sub/b.txt). A path must match it and also any patterns set with setPatterns. Supports , * and ? only. Null or empty means no filtering.

setPatterns(String…​)

hg locate [PATTERN]…​: patterns of any kind; a bare pattern is relglob.

setInclude(String…​)

hg locate -I.

setExclude(String…​)

hg locate -X.

setCwd(String)

Current directory relative to the repository root, for relative patterns.

setRevision(String)

hg locate -r REV: revision whose manifest is searched. When unset, null or empty, the working copy (dirstate) is searched.

Execution

List<String> call() throws IOException. Repository-relative paths, sorted by UTF-8 byte order (NodeIdUtil.UTF8_STRING_COMPARATOR); never null. With no pattern, every candidate path is returned. HgRevisionNotFoundException if the revision cannot be resolved.

Locks and dirstate

No locks, no changing_files/changing_parents. Starts with repository.clearRevlogCache(). Without a revision it reads all dirstate entries.

Differences from hg

Documented in the javadoc: unlike hg files, the working copy search includes files in state r (removed but not committed), as hg’s locate does. […​] character classes and {a,b} alternation are not translated and are treated as literal characters.

List<String> found = new LocateCommand(repo)
    .setPattern("*.txt")
    .setRevision("tip")
    .call();

4.2.14. Manifest

Lists the files of a revision’s manifest with node ids and flags. Corresponds to hg manifest.

Method Meaning

setRevision(String)

Revision in any form NodeIdUtil.resolveRevision accepts (number, hex id or prefix, tip). When unset, null or empty, the working directory’s first parent is used, as hg manifest with no -r (not necessarily the tip).

setDebug(boolean)

Advisory flag recording that --debug style rendering is wanted. It does not change what call() returns, which always carries the full node hex and flags. isDebug() reads it back; the default is false.

Execution

List<ManifestEntry> call() throws IOException. Each ManifestEntry has getPath(), getNodeHex() (full 40-character hex node id of the file’s content), isExecutable(), isSymlink(). The entries are sorted by path. Empty list for a repository with no commits or with no checked-out revision.

Locks and dirstate

No locks, no changing_files/changing_parents. Without a revision it reads dirstate parent 1. Reads through ManifestTreeIterator.

Differences from hg

Returns data instead of pre-formatted text; --debug rendering is left to the caller (real hg prints `755 * ` for executable, `644 @ ` for symlink and `644 ` otherwise). An empty repository gives an empty result, never an error, as in hg (javadoc).

List<ManifestCommand.ManifestEntry> entries = new ManifestCommand(repo)
    .setRevision("0")
    .call();

4.2.15. Tree

Lists all files of a revision with node ids and mode. Corresponds to no hg command: the javadoc says only that it lists the file structure at a revision.

Method Meaning

setRevision(int)

0-based changelog revision number. Default -1 means the tip.

setNodeId(byte[])

Revision by 20-byte node id. Takes precedence over setRevision. null (the default) uses the revision number; a node that is not in the changelog lists the tip.

setNodeId(NodeId)

Same, with a NodeId; null clears it.

Execution

List<TreeEntry> call() throws IOException. Each TreeEntry has getPath(), getNodeId() (40-character hex node id of the file revision in the manifest), getNode() (the same as a NodeId, or null if there is none), getMode() (0644 normal, 0755 executable, 0120000 symlink). Uses the tip if the revision is -1 or the node is not found. Returns an empty list if there is no changelog or the revision number is out of range.

Locks and dirstate

No locks, no changing_files/changing_parents.

Differences from hg

No hg original is named in the source.

List<TreeCommand.TreeEntry> tree = new TreeCommand(repo)
    .setRevision(0)
    .call();

4.2.16. Revset

Evaluates a revset expression and returns matching changesets. The javadoc names no specific hg command; it mirrors hg’s revset queries (for example hg log -r), which is an inference, not stated in the source.

Method Meaning

setExpression(String)

Revset expression, for example all(), tip or parents(tip). Required: call() throws IllegalArgumentException if null or empty.

Execution

List<String> call() throws IOException. Node ids in hex. all()/all and tip are handled directly; for parents(X) the symbolic X is first resolved to a node; anything else goes to HgRevsetEngine.query. If the engine throws, the expression is tried as a single revision identifier, and an empty list results if it does not resolve.

Locks and dirstate

No locks, no changing_files/changing_parents. Calls repository.refreshIfChangedOnDisk() first.

Differences from hg

The engine failure fallback to a single revision lookup is specific to this class. The supported revset language is that of HgRevsetEngine, whose javadoc describes it as evaluating composite expressions such as draft(), author(tester), parents(rev) and AND/OR combinations (for example draft() and author(tester)); a null or blank query gives an empty result. tag(name) reads the tags the way hg tags does, from the .hgtags of the heads and not from the working copy, so it also works in a repository without working files; tip is not matched, the name is exact and case-sensitive, re: and literal: prefixes work, and an unknown name gives an empty result (the original aborts).

List<String> hexes = new RevsetCommand(repo)
    .setExpression("parents(tip)")
    .call();

4.2.17. Bisect

Binary search over history: picks the next revision to test between a good and a bad revision and checks it out. Corresponds to hg bisect.

Method Meaning

setGood(byte[])

20-byte binary node id of the revision known to be good (not yet showing the regression). Required before next().

setBad(byte[])

20-byte binary node id of the revision known to be bad (showing the regression). Required before next().

Execution

byte[] next() throws IOException, HgLockException. Returns the node id of the next candidate to test, updating the working directory parents and physically restoring the candidate’s files into the workspace. Throws IllegalStateException if good or bad is unset; IOException ("Bisect error: …​") if a node is not in the changelog, good equals bad, or no topological path exists.

Locks and dirstate
  • Takes repository.lockWorkingCopy(timeout) only (no store lock), with timeout = repository.resolvePushLockTimeoutMs(), before the first repository read; released when the command ends.

  • Then calls refreshIfChangedOnDisk(), writes the candidate’s files into the working directory, and sets the dirstate parents with repository.changingParents(() → …​) (parent 1 = candidate, parent 2 = null), followed by repository.setBranch(…​) and clearRevlogCache().

  • changingFiles and openChangingFiles are not called.

Differences from hg

Candidate selection mirrors hbisect.bisect() (best split of the remaining DAG, with the root-side endpoint excluded). The javadoc says hg’s "poisoning" optimization is omitted because it never changes the result. Only next() exists; the source of this class has no good/bad/skip/reset state handling.

byte[] next = new BisectCommand(repo)
    .setGood(goodNode)
    .setBad(badNode)
    .next();

4.2.18. SidedataChangedFiles

Reads the stored changed-files sidedata record of a committed changeset. Corresponds to hg debugchangedfiles REV (without --compute).

Method Meaning

setRevision(int)

Changelog revision number to inspect (0-based, as reported by hg log -r N). Required; the default -1 makes call() throw IllegalStateException.

Execution

ChangingFiles call() throws IOException. Decodes the SD_FILES sidedata of the revision, giving the files it changed (added, removed, merged, salvaged, copied, touched, with copy information), without walking any ancestor history. IllegalStateException if the revision was not set to a non-negative number. IllegalArgumentException if the revision does not exist. Returns ChangingFiles.empty() when the repository has no copies-sidedata (plain v1 changelog, or v2 without the requirement), as hg does.

Locks and dirstate

No locks. This is the committed-history counterpart of CopyCommand and uses neither the dirstate nor changing_files/changing_parents. Calls repository.refreshIfChangedOnDisk() first.

Differences from hg

Works only on repositories whose changelog was written with copies-sidedata support (changelog-v2 and the exp-copies-sidedata-changeset requirement). Reads stored data only and never recomputes.

ChangingFiles files = new SidedataChangedFilesCommand(repo)
    .setRevision(3)
    .call();

4.3. Rewriting and naming commands

4.3.1. Rebase

Moves changesets onto another destination by cherry-picking them (hg rebase). When the rebase is finished the original changesets are removed (stripped, with a backup bundle under .hg/strip-backup) unless setKeep(true) is set; no obsolescence markers are written, because evolution is not supported. The cherry-pick path does a real 3-way merge (Merge3, the engine of MergeCommand). A rebase of changesets that have descendants outside the rebased set is refused (with the hint use --keep to keep original changesets) unless setKeep(true) is set. Related classes: RebasePlanner, RebaseState (state file .hg/rebasestate).

Table 1. Setters
Method Meaning

setSource(byte[]) / setTarget(byte[])

Node-style source and target (20-byte node ids; null is the default and means the revset options are used). When both are set, the source changeset and its descendants are rebased onto the target (like hg rebase -s SRC -d DEST); both must exist in the changelog, else HgRevisionNotFoundException.

addSourceRevset(String)

-s REV: the changesets and their descendants (repeatable).

addBaseRevset(String)

-b REV: the branches that contain these changesets (repeatable).

addRevisionRevset(String)

-r REV: exactly these changesets (repeatable).

setDestination(String)

-d REV: the destination. May use SRC and ALLSRC. When omitted, the destination is derived (destutil.destmerge).

setCollapse(boolean)

--collapse: the rebased changesets become one.

setMessage(String)

-m: message of the collapsed changeset (default Collapsed revision plus one line per changeset).

setEdit(boolean)

-e/--edit: pass each new message through the editor before committing.

setMessageEditor(UnaryOperator<String>)

Commit message editor. An empty result aborts with empty commit message. A collapse without -m always runs it. Without an editor the proposal is used as is.

setKeep(boolean)

--keep: keep the original changesets.

setKeepBranches(boolean)

--keepbranches: new changesets keep the branch of the originals.

setSingleTransaction(boolean)

rebase.singletransaction: all commits in one transaction. Default is the hgrc setting, else off.

setDryRun(boolean)

-n/--dry-run: done in memory and undone; repository and working copy are left as they were.

setConfirm(BooleanSupplier)

--confirm: done in memory first; the supplier’s answer decides whether it is applied for real.

registerPreRebaseHook(HgHook) / registerPostRebaseHook(HgHook)

Register hooks; null is ignored. A pre hook runs before the rebase changes anything and gets a context map with repository, sourceNode and targetNode; if it returns false call() fails with HgValidationException (Rebase rejected by PRE_REBASE hook). A post hook runs after a rebase has completed and gets sourceNode, targetNode, rebasedTipNode (hex of the last new changeset, or null) and repository; its return value is ignored and exceptions it throws are logged and swallowed.

getMessages()

What the command printed (rebasing …​, notes), in order.

Table 2. Execution
Method Returns / throws

call()

byte[]: new node of the last rebased changeset, null when there was nothing to rebase. As in Mercurial, the working copy lock and then the store lock are taken once for the whole command; each changeset is merged in the working copy and committed in a transaction of its own, and the state is written to .hg/rebasestate before the first changeset and after each one. Throws IOException, HgLockException, HgMergeConflictException. IllegalStateException when neither node-style source/target nor any revset is given. HgValidationException for validation failures, for example uncommitted changes, outstanding uncommitted merge, rebase in progress (use --continue or --abort), you must specify a destination, empty revision set, source is ancestor of destination, empty commit message, a rejecting pre hook, or originals with descendants outside the rebased set without setKeep(true).

continueRebase()

byte[], same throws as call(). Takes the locks first, then reads .hg/rebasestate under them. Commits the stopped changeset from the working copy (the one still to do whose destination is the working copy parent), then goes on with the rest. HgValidationException no rebase in progress or when .hg/merge/state2 still has unresolved files.

stop()

void; IOException, HgLockException. Only allowed with --keep (setKeep(true)) and not with collapse; restores the original parent (clearing the interrupted merge) and finishes the rebase with what was done so far. Otherwise HgValidationException: no rebase in progress, cannot stop in --collapse session, or cannot remove original changesets with unrebased descendants.

abort()

void; IOException, HgLockException. Strips the rebased changesets (not when one of them is public or has gained descendants that are not part of the rebase), returns the working copy to the original parent, removes state files. HgValidationException no rebase in progress.

On conflict, call() throws HgMergeConflictException and leaves the rebase paused (conflict markers in the file, bookkeeping in .hg/merge/state2). Resolve the files (for example with ResolveCommand), then call continueRebase(), or abort().

Locks and dirstate
  • call(), continueRebase(), stop(), abort(): lockWorkingCopy() then lockStore(), once for the whole command, released at the end.

  • Dirstate: uses repository.changingParents(…​) internally (merge of a revision, finishing the rebase, restoring the working copy). openChangingParents, openChangingFiles, changingFiles are not used in this class (source not confirmed beyond this).

Differences from hg
  • Like the original without evolution: the originals are stripped unless setKeep(true); no obsolescence marker is written.

  • stop() requires --keep because without obsolescence markers removal would orphan unrebased descendants.

  • Merge-conflict pause/continue/abort protocol is hg4j-private; only the end state (.hg/merge/state2) is meant to be readable by real hg.

Example
byte[] last = new RebaseCommand(repo)
        .addSourceRevset("feature-start")
        .setDestination("default")
        .setKeepBranches(true)
        .call();

4.3.2. Graft

Copies changes of a revision onto the current working copy parent (hg graft, similar to git cherry-pick). Performs a real 3-way merge through RebaseCommand#attemptThreeWayMerge when both sides changed the same file. No obsolescence marker is written (graft is a copy). Related class: GraftInMemory is a separate command, hg graft --to REV (experimental): the changesets are grafted onto REV in memory without touching the working copy or dirstate, under the store lock only, and a conflict aborts everything. call() returns the hex nodes and throws on a conflict, as the command line aborts; execute() returns a GraftResult instead: the conflicting files, or the new changesets as nodes in order, and nothing is written for a conflict. With setDryRun(true), call() only prints what would be grafted (like hg graft -n) while execute() merges every revision in memory and rolls back, so it tells whether the graft works and which nodes the changesets would get. New file revisions of files that the lfs extension tracks are written as pointers.

Table 3. Setters
Method Meaning

setSource(String)

Revision to graft (the REV of hg graft REV: a revision number, node hex prefix or other form the changelog lookup accepts), resolved when call() runs. No default. Required: call() throws IllegalArgumentException when null or empty.

registerPostGraftHook(HgHook)

Register a hook that runs after the grafted changeset has been committed; null is ignored. Its context map holds sourceRevision (hex node of the graft source), graftedNode (hex node of the new commit) and repository. Its return value is ignored and an exception it throws is logged as a warning, not propagated, so a post-graft hook cannot abort the graft.

Table 4. Execution
Method Returns / throws

call()

String: hex node of the new grafted commit. Throws IOException, HgLockException, HgMergeConflictException (destination and source diverged on a file and the merge was not clean).

continueGraft()

String: hex node of the grafted commit. Resumes a graft paused on a conflict, after every unresolved file was resolved and the resolution staged on disk (as with hg resolve --mark); completes the paused revision’s commit. IOException, HgLockException. HgValidationException when no graft is in progress or unresolved files remain.

abort()

void; IOException, HgLockException. Discards every working copy and dirstate change the paused attempt staged and restores both to what was checked out before call() started; nothing had been appended to the changelog, manifest or filelogs for a paused graft. HgValidationException no graft in progress.

On conflict, call continueGraft() after resolving and staging the files, or abort().

Locks and dirstate
  • call(): lockWorkingCopy() and openChangingParents() for the working copy update (the context ends and writes the dirstate before the commit step). The commit step (commitGraftedRevision) takes lockStore(). It delegates to CommitCommand with setSkipLockAndJournal(true) and writes its own journal/backup for crash safety.

  • continueGraft(), abort(): lockWorkingCopy() only (in the code shown); the commit in continueGraft() goes through the same store-lock step.

  • changingFiles is not used.

Differences from hg
  • Pause/continue/abort protocol is hg4j-private; interop with real hg graft --continue bookkeeping is not a goal.

  • No obsmarker is written, as in real hg 7.2.

Example
String node = new GraftCommand(repo)
        .setSource("3f2a1b")
        .call();

4.3.3. Backout

Creates a new changeset that undoes a revision without altering history (hg backout REV). Only single-parent changesets and the non---merge mode are supported; the working copy must be clean and REV must be an ancestor of the working copy parent.

Table 5. Setters
Method Meaning

setRevision(String)

Revision to back out (hg backout -r REV), any identifier the revision resolver understands. Required: call() throws IllegalStateException when it was not set.

setMessage(String)

Commit message of the backout changeset (hg backout -m). When null or empty the message is Backed out changeset followed by the 12-digit short hash of the backed-out revision.

setAuthor(String)

Author of the backout changeset (hg backout -u); default hg4j.

Table 6. Execution
Method Returns / throws

call()

byte[]: the 20-byte node of the new backout changeset. Applies the inverse of the change to the working copy and commits it through CommitCommand. Throws IllegalStateException if no revision was set; HgValidationException if the revision is unknown, is a merge or a root changeset, is not an ancestor of the working copy parent, or the working copy has uncommitted changes or an uncommitted merge; HgMergeConflictException if the inverse change conflicts with later changes (nothing is committed); IOException when reading or writing the repository fails; HgLockException when a lock cannot be acquired.

If REV is the working copy parent, its diff is applied directly (cannot conflict). If REV is an older ancestor, a 3-way merge runs (ancestor = REV, local = working copy, other = REV’s parent). On conflict it throws HgMergeConflictException and does not commit; conflict state is written to .hg/merge/state2. There is no --continue: resolve with ResolveCommand (or real hg resolve), then commit normally.

Locks and dirstate
  • call(): lockWorkingCopy(), lockStore(), then openChangingParents(), in this order. The working copy update ends (and writes the dirstate) before the commit, which opens its own context.

  • changingFiles is not used.

Differences from hg
  • --parent (backing out a merge) and --merge are not exposed.

  • Dirstate parent stays single after a conflict (not a two-parent merge state).

Example
byte[] node = new BackoutCommand(repo)
        .setRevision("tip")
        .setMessage("Back out bad change")
        .call();

4.3.4. Histedit

Rule-based history editing (hg histedit) with actions PICK, DROP, FOLD, ROLL. The class implements AutoCloseable (close() holds no resources and does nothing). The rules, in the order added, describe the contiguous range of history to rewrite, oldest first; the range is rebuilt on top of the first parent of the first rule’s changeset.

  • PICK: start a new rewritten commit that reuses the changeset’s message and author.

  • FOLD: merge the changeset’s changes into the preceding rewritten commit and append its message to that commit’s message.

  • ROLL: like FOLD, but the changeset’s message is discarded.

  • DROP: omit the changeset from the rewritten history. It is marked pruned with an obsolescence marker, not physically removed.

The author and branch of a rewritten commit stay those of the group’s first changeset (the pick). Every original changeset folded into a rewritten commit gets a histedit obsolescence marker pointing to it.

Table 7. Setters
Method Meaning

addRule(Action, String hexNode)

Append a rule (HisteditCommand.Action: PICK, DROP, FOLD, ROLL) for the changeset with this full 40-character hex node id. Ignored when the action is null or the node is null or empty. Rules are also available as HisteditCommand.Rule(action, hexNode) with public final fields.

Table 8. Execution
Method Returns / throws

call()

void. Does nothing when no rule was added. Rewrites the history, then moves the working copy and dirstate to the last rewritten commit and sets the working branch to that commit’s branch; files of dropped commits disappear from the working directory and the dirstate. If an error occurs, the revlogs and dirstate are restored to their previous state. Throws IOException when a rule’s changeset is not in the changelog (Histedit failed: Revision not found for node …​) or reading or writing the repository fails, and HgLockException when a lock cannot be acquired.

There are no continue or abort methods: the class has no paused state. It recommits the content of the listed changesets cleanly, and the javadoc and code describe no conflict handling; a failure restores the repository as described above.

Locks and dirstate
  • call(): the working copy lock and the store lock are held for the whole operation (lockWorkingCopy(), lockStore(), openChangingParents() in this order). The dirstate is written when the context ends well; a failure restores the revlogs and leaves the dirstate file on disk alone.

  • changingFiles is not used.

Differences from hg
  • Unlike RebaseCommand, histedit never strips: dropped and replaced changesets are hidden by obsolescence markers (prune for DROP, histedit for the rewritten ones), matching real hg under experimental.evolution.

  • Rules take full hex node ids only; there is no interactive editor or --continue protocol.

Example
try (HisteditCommand h = new HisteditCommand(repo)) {
    h.addRule(HisteditCommand.Action.PICK, hexA)
     .addRule(HisteditCommand.Action.FOLD, hexB)
     .call();
}

4.3.5. Shelve

Shelves and unshelves working copy changes (hg shelve, hg unshelve, --delete, --cleanup). Unshelve follows hg’s _dounshelve(): the shelved changegroup is restored as a throwaway commit, rebased with RebaseCommand onto the current parent, then uncommitted onto the working copy; the throwaway commits are stripped outright.

Table 9. Setters
Method Meaning

setName(String)

Shelf name to create or restore (default default; null or empty is ignored and leaves the current value).

setUnshelve(boolean)

Run unshelve (restore the shelf, like hg unshelve) instead of shelve. Default false shelves the pending changes.

setDelete(boolean)

--delete NAME…​: move the named shelves to .hg/shelve-backup.

setNames(String…​)

Shelves removed by --delete (real hg takes them as the command’s arguments). An empty list gives HgValidationException no shelved changes specified!; an unknown name gives shelved change '<name>' not found.

setCleanup(boolean)

--cleanup: move every shelf to .hg/shelve-backup (keeps the newest shelve.maxbackups, 10).

Table 10. Execution
Method Returns / throws

call()

void; IOException, HgLockException, HgMergeConflictException. Dispatches to delete/cleanup, unshelve, or shelve; shelf files live in .hg/shelved. IOException also covers refusals: a shelf that does not exist, no shelf names given to delete, or an unshelve onto a working copy with pending changes or an unresolved merge (HgValidationException). HgMergeConflictException means the unshelve rebase conflicted; the unshelve is left in progress and can be finished or abandoned (below).

unshelveContinue()

void; IOException, HgLockException, HgMergeConflictException. Runs RebaseCommand#continueRebase(), then finishes the uncommit and cleanup. HgValidationException no unshelve in progress or unresolved files remain. The resume is driven only by .hg/rebasestate-hg4j, using a fresh RebaseCommand.

unshelveAbort()

void; IOException, HgLockException. Discards the throwaway restore and rebase commits this attempt created, restores the working copy and dirstate to exactly their pre-unshelve state, and (unlike a completed unshelve) leaves the shelf untouched so a later unshelve can still use it. HgValidationException no unshelve in progress.

On an unshelve conflict, resolve the files and call unshelveContinue(), or unshelveAbort().

Locks and dirstate
  • Delete/cleanup: lockWorkingCopy() only.

  • Shelve: lockWorkingCopy(), then lockStore() (taken after the working copy is read, before deciding that there is nothing to shelve). Going back to the parent of the working copy after the temporary commit runs in changingParents(…​).

  • Unshelve (performUnshelve): lockWorkingCopy(), lockStore(), openChangingParents().

  • unshelveContinue(), unshelveAbort(): lockWorkingCopy() then lockStore() (nested).

  • changingFiles is not used; the dirstate is written with writeDirstate.

Differences from hg
  • Unshelve strips the throwaway commits outright instead of leaving obsolete revisions, matching hg’s aborted transaction.

  • hg4j adds a per-shelf .state file and a private unshelve state file (.hg/rebasestate-hg4j driven rebase).

Example
new ShelveCommand(repo).setName("wip").call();           // shelve
new ShelveCommand(repo).setName("wip").setUnshelve(true).call();

4.3.6. Strip

Removes changesets and their descendants completely from the repository revlogs (hg strip). Other revisions above the cut are saved in a bundle and re-added. A backup bundle goes to .hg/strip-backup/.

Table 11. Setters
Method Meaning

setRevision(String)

Revision to strip; it and all its descendants are removed. A revision identifier or revset.

addRevision(String)

Another revision to strip (hg strip REV REV …​); a revset expression is read like a revision set.

addBookmark(String)

-B BOOKMARK: strip changesets only that bookmark reaches, then delete the bookmark.

setBackup(boolean)

--no-backup when false: no bundle of the removed changesets is saved (default true, a bundle is saved).

setTopic(String)

The word at the end of the backup bundle’s name (backup for strip, copy, rebase, …​; default backup).

setForce(boolean)

--force: discard uncommitted changes instead of refusing.

setKeep(boolean)

--keep: leave working copy files alone; only the parent follows the strip.

setSoft(boolean)

--soft: not available. call() throws HgValidationException (strip --soft needs the archived phase (a repository with the internal-phase requirement), which this repository does not have).

setPermitEmptyRevset(boolean)

An empty revision set is a success instead of an abort.

getMessages(), getBackupBundle()

Printed messages (saved backup bundle to …​ and the warnings of a failed strip); the bundle file that call() saved (or null).

Table 12. Execution
Method Returns / throws

call()

void; IOException (for example Strip target revision not found), HgLockException, IllegalArgumentException when no revision or bookmark is given, HgValidationException (empty revision set, unknown bookmark, the --soft refusal, and, when a working copy parent would be stripped without setForce(true), outstanding uncommitted merge or uncommitted changes). Under the working copy lock the revision set is worked out (-B names included); a bookmark that is not the only one on its node is only deleted, then strip() takes the store lock and does the work.

Locks and dirstate
  • call(): lockWorkingCopy(), then inside stripRevisions lockWorkingCopy() again plus lockStore() (as hg strip(): with repo.wlock(), repo.lock()). Only bookmark deletion with nothing to strip takes lockStore() alone under the working copy lock.

  • Dirstate: repository.changingParents(…​) when a working copy parent is stripped (with --keep, only the dirstate parents are reset). changingFiles is not used.

Differences from hg
  • --soft is unsupported.

  • The strip cut is at the lowest requested revision; later non-stripped revisions are bundled and re-added (as repair.strip).

Example
StripCommand s = new StripCommand(repo).setRevision("tip").setBackup(false);
s.call();

4.3.7. Phase

Shows or changes the phase of a revision (hg phase), stored as minimal roots in .hg/store/phaseroots.

Table 13. Setters
Method Meaning

setRevision(String)

Revision to query or move, resolved against the changelog as hg’s revision argument. Must be set before call(), which fails with IOException if it cannot be resolved.

setPhase(int)

Target phase: 0 public, 1 draft, 2 secret. The default -1 means query only (hg phase without a phase option).

setForce(boolean)

--force: allow moving to a higher phase number (more secret). Without it such a move is refused (cannot move N changesets to a higher phase, use --force).

getNotes(), getMessages(), getExitCode()

Verbose notes, other printed messages, and ret (1 when a changeset could not be moved without --force).

Table 14. Execution
Method Returns / throws

call()

int: the effective phase of the revision after the call (0 public, 1 draft, 2 secret); when a move to a higher phase was refused, the unchanged current phase. Requesting the phase a revision already has changes nothing. A refused move is not an exception: nothing is changed, getExitCode() becomes 1 and a message is added to getMessages(). Notes and messages of an earlier call are cleared at the start of each call. Throws IOException (revision cannot be resolved, I/O failure; the lock cannot be acquired).

Moving toward public affects the revision and all ancestors; moving toward secret affects it and all descendants. Roots are recomputed from scratch after each move.

Locks and dirstate
  • Query: no lock. Change: lockStore() only, with the repository’s push lock timeout, while .hg/store/phaseroots is rewritten. No working copy lock, no dirstate context.

Differences from hg

Line order and minimal-roots format match hg; the older per-node format was replaced.

Example
int p = new PhaseCommand(repo)
        .setRevision("tip")
        .setPhase(0)
        .call();

4.3.8. Censor

Erases a file revision’s content in place and replaces it with a tombstone (hg censor), keeping node, parents and linkrev.

Table 15. Setters
Method Meaning

setFile(String)

Repository-relative path of the tracked file (required, else HgValidationException).

setRevision(String)

Full 40-digit hex node id of the file revision in the file’s filelog (not a changeset revision). Required, else HgValidationException.

setTombstone(String)

Free-text reason stored in the tombstone (default empty, as in real hg). The tombstone is the \x01\ncensored: <message>\n\x01\n metadata header.

setCheckHeads(boolean)

--check-heads (default true). When true, refuses to censor a revision still live at a head or a working directory parent. false is --no-check-heads.

Table 16. Execution
Method Returns / throws

call()

void. Replaces the selected file revision in its filelog with the tombstone (marking it REVIDX_ISCENSORED), rewriting the filelog in place and clearing the revlog cache. Throws HgValidationException if the file or the revision was not set, or the revision is live at a head or in the working directory (cannot censor file in heads, cannot censor working directory), HgRepositoryNotFoundException if the file has no filelog, HgRevisionNotFoundException if the revision is not in the filelog, IOException if the filelog cannot be read or rewritten, and HgLockException if a lock cannot be acquired.

Locks and dirstate
  • lockWorkingCopy() then lockStore(). No dirstate context.

Differences from hg
  • Targets a filelog node rather than a changeset revision (-r), so the heads guard compares the filenode against each head’s and parent’s manifest entry.

Example
new CensorCommand(repo)
        .setFile("secret.txt")
        .setRevision(fileNodeHex)
        .setTombstone("removed by request")
        .call();

4.3.9. Branch

Shows or sets the working directory branch, resets it, or renames the branch of changesets (hg branch).

Table 17. Setters
Method Meaning

setBranchName(String)

Branch name to switch the working directory to (hg branch NAME); surrounding whitespace is stripped and the label is checked like scmutil.checknewlabel (reserved names, integers and invalid characters give HgValidationException). Empty (non-null) is IllegalArgumentException. Without a name call() only reports the current branch.

setClean(boolean)

--clean: go back to the branch of the first parent.

setForce(boolean)

--force: allow reusing an existing branch name.

setRevisions(String…​)

--rev REV…​ NAME: replace each changeset with a copy on the new branch (linear draft stack ending in a head, clean working directory).

getChangedChangesets(), getBackupBundles()

How many changesets --rev replaced (changed branch on N changesets); the bundles of the replaced changesets that --rev saved.

Table 18. Execution
Method Returns / throws

call()

String: the branch of the working directory afterwards (or now, when only showing, or with clean and no name). Throws IOException, HgLockException, HgValidationException (for example a branch of the same name already exists; for --rev also no branch name specified for the revisions, outstanding uncommitted merge, uncommitted changes, empty revision set, cannot change branch of non-linear revisions, cannot change branch in middle of a stack, and --rev is not supported for treemanifest or changeset-centric copy repositories).

Locks and dirstate
  • Showing: no lock. Setting or clean: lockWorkingCopy(). --rev: additionally lockStore() taken inside changeBranch, kept until the old changesets are gone. No changing_parents or changing_files context is used in this class.

Differences from hg
  • Follows commands.branch: the name check and the test for a branch of the same name happen under the working copy lock. --rev follows cmdutil.changebranch. No difference from hg is listed in the javadoc.

Example
String b = new BranchCommand(repo).setBranchName("stable").call();

4.3.10. Branches

Lists named branches with their current head (hg branches).

Table 19. Setters
Method Meaning

setIncludeClosed(boolean)

hg branches -c/--closed: also list branches whose heads are all closed (hidden by default, default false).

Table 20. Execution
Method Returns / throws

call()

List<BranchesCommand.BranchHead>, one entry per named branch; empty for an empty repository. Each entry has getBranch(), getNode() (20-byte node of the reported head), getRev() (changelog revision of the head), isClosed() (every head of the branch closes it), isActive(). Takes no lock and writes nothing. Throws IOException if the changelog cannot be read.

Reported head: highest-revision open head, else highest closed. Order: active branches first (descending revision), then inactive, ties by reverse name and open before closed. isActive() means the head is a repository-wide topological head.

Locks and dirstate
  • No lock, no dirstate context (read only).

Differences from hg

Ordering and head selection were verified against hg 7.2.2 (branchmap.branches_info, commands.branches); sorting by revision alone, as an earlier version did, diverged from hg and was fixed. No known differences are listed.

Example
for (var h : new BranchesCommand(repo).setIncludeClosed(true).call()) {
    System.out.println(h.getBranch() + " " + h.getRev() + (h.isActive() ? "" : " (inactive)"));
}

4.3.11. Tag

Creates, moves, or removes a tag (hg tag).

Table 21. Setters
Method Meaning

setTagName(String)

Name of the tag to create, move or remove. Null or empty (the default) makes call() list the tags instead.

setNodeId(byte[])

Target node (at least 20 bytes; the first 40 hex digits of it are used). Required when creating a tag, ignored when setRemove(true).

setCommit(boolean)

Commit the .hgtags change right after it is updated (default true); false leaves .hgtags changed but uncommitted. No effect for local tags, which are never committed.

setLocal(boolean)

--local: write .hg/localtags (untracked, no commit).

setRemove(boolean)

--remove: append a nullid entry (40 zeros); no node needed.

setForce(boolean)

-f: allow moving a tag name that already resolves to a non-null revision. Otherwise tag '<name>' already exists (use -f to force), for both global and local tags. Irrelevant with setRemove(true): an existing tag can always be removed.

registerPreTagHook(HgHook) / registerPostTagHook(HgHook)

Hooks; null is ignored. A pre hook runs before anything is written and can veto: a false result raises HgValidationException (Tag creation rejected by PRE_TAG hook). A post hook runs last, after the tag was written (and committed), and exceptions from it propagate. The context map holds repository, tag and node.

Table 22. Execution
Method Returns / throws

call()

Map<String,String>. When a tag name was set: a single entry, tag name to the 40-character hex node written (all zeros for a removal). Otherwise (listing): the tag name to hex node pairs of .hgtags in file order, later lines replacing earlier ones, and an empty map if the file does not exist. A global tag adds .hgtags to the dirstate and, with setCommit(true), commits it with author hg4j <hg4j@google.com> and message Added tag NAME for changeset SHORT (or Removed tag NAME). Throws IllegalArgumentException if a tag is to be created and no node of at least 20 bytes was set, HgValidationException (an IOException) if the tag already exists and neither force nor remove is set or a pre hook returns false, IOException if reading or writing the tag files or committing fails, and HgLockException if a lock cannot be acquired within the push lock timeout.

Locks and dirstate
  • lockWorkingCopy() then lockStore() (waiting up to the repository’s push lock timeout) before the first read. The commit goes through CommitCommand. changingParents/changingFiles are not called in this class itself.

Differences from hg
  • The existing-tag check spans local and global tags together (verified against hg 7.2.2).

  • TagCommand follows hg tag: it checks the names (tip, null, ., integers, : and line breaks are refused), an existing, already removed or other-kind tag, a working copy that is not at a branch head (setForce overrides), an uncommitted merge, the null revision and a changed .hgtags, reading the tags from the heads and .hg/localtags like hg tags. A moved or removed tag writes its previous node as a line of its own first, as the original does.

Example
new TagCommand(repo)
        .setTagName("v1.0")
        .setNodeId(nodeBytes)
        .call();

4.3.12. Tags

Lists tags (hg tags).

Table 23. Setters
Setter Meaning

setReadFromHeads(boolean)

true reads the global tags like hg tags does: the .hgtags of every head of the repository, from the changesets, not from the working copy. A repository without working files (a server repository filled by push or pull) shows its tags only this way. The heads are read oldest first so that a later line wins, a .hgtags file with the same file revision is read once, and an uncommitted .hgtags is ignored (as in hg). Default false: the working copy .hgtags.

setRevision(String)

Reads the .hgtags of this one changeset only (a revision number, a node or node prefix, or tip; null clears it), not the working copy and not the other heads. Implies setReadFromHeads(true). A changeset without .hgtags has no global tags.

Table 24. Execution
Method Returns / throws

call()

List<TagsCommand.Tag>, never null. Each Tag has getName() (never null), getNode() (20-byte node; all zeros for tip of an empty repository), getRev() (revision number; -1 for tip of an empty repository) and isLocal() (defined in .hg/localtags rather than .hgtags). Reads .hgtags (from the working copy, or from the heads or the given revision, see the setters) and .hg/localtags, and always adds the pseudo tag tip. Throws IOException if reading the tag files or the changelog fails.

Rules: .hg/localtags wins over .hgtags; last line wins; nullid means deleted; tags with unknown nodes are omitted; tip always names the real tip; order is highest revision first, then reverse alphabetical.

Locks and dirstate
  • No lock, no dirstate context.

Differences from hg
  • By default global tags are read from the working copy .hgtags only. With setReadFromHeads(true) they are read from the heads as hg tags does (findglobaltags: the heads oldest first, a .hgtags file read once per file revision, later lines win, history is merged as in _updatetags).

Example
for (var t : new TagsCommand(repo).call()) {
    System.out.println(t.getName() + " " + t.getRev() + (t.isLocal() ? " local" : ""));
}

4.3.13. Bookmark

Lists, creates, moves, deletes, activates bookmarks (hg bookmarks, hg bookmark).

Table 25. Setters
Method Meaning

setBookmarkName(String)

The bookmark to create, move, delete or activate. Without a name (and without delete or active) call() only lists the bookmarks.

setNodeId(byte[])

Target changeset (hg bookmark -r REV) as a binary node id. When not set (or null) the first parent of the working copy is used and a new bookmark also becomes the active one; an explicit target does not activate it.

setRevision(String)

Same as setNodeId but takes the full 40-digit hex node id (converted with NodeIdUtil.fromHex); null or empty leaves the target unchanged, other revision spellings are not resolved here.

setDelete(boolean)

hg bookmark -d: remove the bookmark named by setBookmarkName (and deactivate it if it was the active one). Default false.

setActive(boolean)

Activate the existing bookmark named by setBookmarkName, or deactivate the current bookmark when no name is set (hg bookmark -i). Default false.

setCurrentOnly(boolean)

Marks setActive as the internal switch of the active bookmark that hg update performs: changes only bookmarks.current and needs just the working copy lock. Without it, activating or deactivating is the hg bookmark -i command, which takes both locks and a transaction.

setForce(boolean)

-f: allow moving an existing bookmark to a revision that is not a descendant of its current target (a backward or divergent move). Otherwise bookmark '<name>' already exists (use -f to force). A forward move (new target a descendant of the current one, including across an obsolescence successor) is allowed without it, like a new name. Irrelevant to delete and to setActive.

Table 26. Execution
Method Returns / throws

call()

Map<String,String> of bookmarks and their targets. Listing needs no lock. Every change (add, move, delete, activate, deactivate) reads .hg/bookmarks, decides and writes it again while holding the locks (see below), so that two writers cannot silently drop each other’s change. Throws IOException, HgLockException.

list()

Map<String,String>; read only, no lock.

getActiveBookmark()

The active bookmark name read from .hg/bookmarks.current, or null when there is none or the file cannot be read.

mergeFromRemote(HgRepository, Map, String) (static)

Merges remote bookmarks on pull/fetch (new, equal, fast-forward, keep local when it is ahead, else a divergent name@remotePathName). remotePathName is the suffix, for example the remote path alias; null uses 1 (like hg’s name@1 fallback). Returns nothing when the remote map is null or empty. Throws IOException, HgLockException.

Locks and dirstate
  • Listing: no lock. Changes: lockWorkingCopy() then lockStore(), waiting for both. The file is HgRepository.getBookmarksFile(): .hg/bookmarks, the store’s bookmarks with the bookmarksinstore requirement, or the shared repository’s file in a hg share -B working copy, which every write then mirrors into the working copy’s own .hg/bookmarks. With setCurrentOnly(true) and setActive(true) (not delete): lockWorkingCopy() only. No dirstate context.

Differences from hg
  • A new bookmark with no explicit target (setNodeId/setRevision) points to the working copy parent and becomes active; an explicit target does not activate it.

  • mergeFromRemote simplifies hg’s comparebookmarks/validdest.

Example
Map<String,String> all = new BookmarkCommand(repo)
        .setBookmarkName("feature")
        .setRevision(nodeHex)
        .call();

4.4. Transports

Commands that talk to another repository open a connection through HgRemoteConnectionFactory.createConnection(url, config). The factory picks the first registered TransportProtocol that can handle the address. Custom protocols added with HgRemoteConnectionFactory.register(…​) are tried first.

Address form Client class and behavior

ssh://…​

HgSshClient: Mercurial SSH wire protocol. user[:pass]@host[:port] is parsed from the address (default port 22). Key or password credentials come from a CredentialsProvider (SshKeyCredentialsProvider for key path and passphrase, UsernamePasswordCredentialsProvider for user and password). SSH wire protocol v2 is off unless the JVM property hg4j.ssh.v2.enabled=true is set.

file://…​; or a path of an existing local directory

HgLocalClient: reads and writes the other repository directly in Java, without running an hg process.

http://…​; or https://…​;

HgRemoteClient: HTTP wire protocol v1. Credentials may be embedded as https://user:pass@host/path.

anything else

Falls back to HgRemoteClient.

4.4.1. Refusing an SSH connection

HgSshWireServer.rejectConnection(InputStream in, OutputStream out, String reason) is for a server front end that decides on access before it has a repository. A real hg SSH client sends hello and between together and reads nothing, not even an error line, until the answer to between arrives, so writing only an error and closing leaves it waiting for ever. The method answers both handshake commands as an empty server would (the default capabilities, one empty line for each pair of between) and then sends reason as the out-of-band error that the client’s next command receives. No repository is opened. It is static and throws IOException if the streams fail or the client closes before the handshake is complete.

4.4.2. Authentication for HTTP(S)

  • Credentials in the address, or set through setCredentialsProvider(…​) on a command that offers it, are used for HTTP Basic authentication. As in Mercurial, they are sent only after the server answered 401 with a Basic challenge, and then on later requests at once.

  • When the address carries no password, the [auth] section is consulted (HgAuthConfig; HgAuthConfig.userConfig() is the public reader of the user and system configuration: HGRCPATH, else /etc/mercurial/hgrc, ~/.hgrc and ~/.config/hg/hgrc). Entries are <group>.<setting> = value with the settings prefix, username, password and schemes (default https). The group with the longest matching prefix wins, a group that names a user must match the user of the address, and * as a prefix matches every host. cert and key are not used.

  • The [auth] section is read from the user level files first (HGRCPATH if set, otherwise /etc/mercurial/hgrc, ~/.hgrc and ~/.config/hg/hgrc) and then from the repository configuration, which overrides it.

  • Only commands that call createConnection(url, repository.getConfig()) apply [auth]. This holds for Fetch, Pull, Push, Incoming and Outgoing. The command classes below that expose setCredentialsProvider are Fetch and Pull. Commands without that setter rely on credentials in the address or on [auth].

Locking terms used below: lockWorkingCopy() is the working copy lock (wlock), lockStore() is the store lock (lock). changingParents(…​) / openChangingParents is the dirstate changing_parents context.

4.4.3. Clone

Clones a repository into a new directory. Corresponds to hg clone.

Setter Meaning

setSource(String)

Source address (required): a local path or a remote URL that PullCommand accepts.

setDirectory(File)

Destination directory (required). Created if missing, must be empty if it exists.

setStream(Boolean)

hg clone --stream / --no-stream. null follows the remote’s stream-preferred.

setPull(boolean)

hg clone --pull: always pull the changesets, even from a local source. Without it a local source is cloned by copying its store, hard linked where possible.

setUpdate(boolean)

hg clone -U when false: no working files are created; the working directory parent stays the null revision and there is no .hg/dirstate file. Default true (check out the tip).

setProgressMonitor(ProgressMonitor)

Progress receiver and cancellation poll; a null argument is ignored and the previous monitor (initially a no-op) stays.

Also public: getMessages() returns what the clone reported (for example streaming all changes).

Execution: HgRepository call() throws IOException, HgLockException. It initializes the destination, records the source as the default path, brings in the changesets (copying the store of a local source, or pulling), checks out the tip and clones hg subrepositories declared there recursively. Returns the new repository; the caller must close it. Throws IllegalStateException when source or directory is missing, HgValidationException when the destination directory exists and is not empty, IOException when pulling or the checkout fails, and HgLockException when the destination lock cannot be acquired. When the source has no changesets the repository is returned empty, without a checkout.

Locks and dirstate: the destination working copy lock is taken right after init and held until the last update (destrepo.wlock()). For a local source copy, the source store lock is only tried (lockStore(0)); if it is busy the copy is given up and the changesets are pulled instead. A source with secret changesets is never copied. The destination store lock is taken for the copy. The checkout runs inside changingParents(…​), which sets the dirstate parents and writes the entries. Subrepositories declared in .hgsub are checked out afterwards (UpdateCommand.recursiveSubrepoCheckout).

Differences from hg: the source is written to .hg/hgrc as [paths] default (a local path as an absolute path). The javadoc describes this as the layout real hg clone uses.

HgRepository repo = new CloneCommand()
    .setSource("https://example.org/repo")
    .setDirectory(new File("work"))
    .setStream(null)
    .call();

4.4.4. Pull

Pulls changesets from a remote repository into the local one. Corresponds to hg pull. It delegates the transfer to FetchCommand, like hg pull without -u: it leaves the working directory and its dirstate alone.

Setter Meaning

setSource(String)

Source address or [paths] alias: a value without :// that names a [paths] entry is replaced by that entry’s URL. When unset or empty (the default), paths.default is used. IllegalStateException from call() if no source was set and no default path exists.

setRevisions(List<String>)

hg pull -r REV: only these revisions and their ancestors.

setStream(Boolean)

--stream / --no-stream: into an empty repository, take the remote’s store files as they are instead of the changesets one by one. null (the default) follows the remote’s stream-preferred.

setTreeFilter(HgTreeFilter)

Restricts which paths are pulled (narrow clone support); null is ignored. By default, and when set to HgTreeFilter.ALL, the underlying fetch uses the repository’s own narrowspec if it has one.

setProgressMonitor(ProgressMonitor)

Progress receiver; a null argument is ignored.

setCredentialsProvider(CredentialsProvider)

Credentials asked for when the remote requires authentication; null (the default) sets none on the connection.

setStoreFingerprints(List<String>)

Shape fingerprints (text) the clone asks for; they pick the clone bundles (store_fingerprints).

setShardsSets(List<Set<String>>)

Sets of shard fingerprints (text) that make a usable group of sharded clone bundles (shards_sets).

Also public: getMessages(), and applyBundle(ChangegroupParser.ChangegroupBundle) plus the overloads (bundle, int lockTimeoutMs) and (bundle, int lockTimeoutMs, FetchCommand.PostLockValidator), which apply an already parsed bundle.

Execution: List<byte[]> call() throws IOException, HgLockException. Returns the 20-byte node ids of the imported changesets (possibly empty), from FetchCommand.call(). Working copy files and the dirstate are not touched: a repository without working files that is filled by call() keeps the null parent and has no .hg/dirstate file (as after hg pull; hg verify passes on it). getMessages() is reset at the start of each call. Throws IOException when the connection, the transfer or writing the repository fails, HgLockException when a lock cannot be acquired, and IllegalStateException when no source was set and no default path is configured. applyBundle(…​) returns the imported node ids with the same throws, except that it waits for locks up to the repository’s push lock timeout (or lockTimeoutMs; 0 fails at once).

Locks and dirstate: call() takes lockWorkingCopy() and then runs FetchCommand.call(), which itself takes the working copy lock and then the store lock (see Fetch). It does not change the dirstate. applyBundle(…​) takes lockWorkingCopy(lockTimeoutMs) (default timeout repository.resolvePushLockTimeoutMs()) and leaves the dirstate alone as well. Bookmark merging happens inside FetchCommand (BookmarkCommand.mergeFromRemote()).

List<byte[]> pulled = new PullCommand(repo)
    .setSource("default")
    .setRevisions(List.of("tip"))
    .call();

4.4.5. Push

Pushes local changesets to a remote repository. Corresponds to hg push.

Setter Meaning

setDestination(String)

Destination address or [paths] alias: a value without :// that names a [paths] entry is replaced by that entry’s URL. When unset or empty (the default), paths.default-push is used, then paths.default. IllegalStateException from call() if none is configured.

setForce(boolean)

hg push --force: bypasses the whole "creates new remote head(s)" check (real hg skips discovery.checkheads() entirely), which in practice also covers the new-branch check. It does not imply setAllowNewBranch in real hg.

setAllowNewBranch(boolean)

hg push --new-branch: permits pushing a named branch the remote lacks. Without it the push aborts with "push creates new remote branches".

setBookmarks(String…​)

hg push -B NAME …​: pushes, moves or (when absent locally) deletes the named bookmarks on the remote, and only the ancestors of these bookmarks are pushed.

registerPrePushHook(HgHook)

Hook run before anything is pushed. Its context map holds destinationUrl (the resolved URL) and repository. If any hook returns false, call() fails with HgValidationException. null is ignored.

registerPostPushHook(HgHook)

Hook run after a successful push of changesets, after the locks are released. Its context map holds destinationUrl, response and repository. Its return value is ignored and exceptions it throws are swallowed. null is ignored.

setProgressMonitor(ProgressMonitor)

Receives the progress of the LFS uploads and the lines Mercurial prints about them (see HgLfsProgress).

Also public: getBookmarkResult() (0 fine, 1 a bookmark update failed, 2 a bookmark was refused) and getMessages() (for example cannot lock source repo, skipping local public phase update).

Execution: String call() throws IOException, HgLockException. Returns a status text: the remote’s response after sending changesets, or a line starting with No changesets to push (plus bookmark lines, if any) when there is nothing to send, for example No changesets to push (empty local repository). Throws IOException when the connection or transfer fails, HgLockException when the store lock cannot be acquired, and IllegalStateException when no destination was set and neither default-push nor default is configured. HgValidationException (an IOException) is thrown when a pre-push hook returns false, the repositories are unrelated, the push would create new remote heads or branches, or an LFS repository is pushed to a remote without LFS support, with messages such as abort: repository is unrelated, abort: push creates new remote branches: …​, abort: push creates new remote head …​, and the LFS requirement message required features are not supported in the destination: lfs.

Locks and dirstate: the connection is opened first, then lockSourceRepository() runs. The store lock of the local repository is held from after the connection is made until the end; post-push hooks run after the locks are released. It takes lockStore(resolvePushLockTimeoutMs()) and, only when experimental.bundle2.pushback is true, lockWorkingCopy(…​) before it. The lock is held through changesets, phases and bookmarks. If the source cannot be locked the push continues and only the local public phase update is skipped (a message is added); an abandoned transaction still aborts. No changingParents use was found.

Differences from hg: no setCredentialsProvider exists; [auth] and address credentials apply.

PushCommand push = new PushCommand(repo)
    .setDestination("default")
    .setAllowNewBranch(true);
String result = push.call();

4.4.6. Fetch

Low level network sync that downloads changesets into the store. Javadoc: updates the revlog store, bookmarks and phases atomically but does not modify the working copy dirstate. PullCommand is built on it.

Setter Meaning

setSource(String)

Source address (required, IllegalStateException from call() otherwise): a URL or path accepted by the remote connection factory (http, https, ssh or a local repository path). No [paths] resolution happens here.

setRevisions(List<String>)

Only these revisions and their ancestors. Each is looked up on the remote, so a node prefix, bookmark, tag or branch name works; the remote must support lookup.

setStream(Boolean)

--stream / --no-stream; null follows stream-preferred.

setTreeFilter(HgTreeFilter)

Path filter (narrow fetch); null is ignored. When left at the default accept-all filter, the repository’s own narrowspec, if any, is used.

setProgressMonitor(ProgressMonitor)

Progress receiver; a null argument is ignored.

setCredentialsProvider(CredentialsProvider)

Provider asked for credentials when the remote requires authentication. Default: none; null allowed.

setWorkingCopyLock(boolean)

Whether applyBundle also takes the working copy lock. true by default (pull, as real hg’s exchange.pull); false for unbundle (real hg’s unbundle_files takes only the store lock), and then the dirstate stays alone.

setStoreFingerprints(List<String>)

Shape fingerprints for a shaped clone.

setShardsSets(List<Set<String>>)

Shard fingerprint sets for sharded clone bundles.

Also public: getMessages(), applyBundle(bundle), applyBundle(bundle, int lockTimeoutMs), applyBundle(bundle, int lockTimeoutMs, PostLockValidator) and the functional interface PostLockValidator, whose validate() runs after the locks are held and before any part of the bundle is applied (for push race re-validation, like check:heads of real hg). Throwing there aborts the apply with nothing written and the locks released.

Execution: List<byte[]> call() throws IOException, HgLockException. It fetches the changesets, bookmarks and phases the remote has and the local repository lacks, and returns the 20-byte node ids added (empty when nothing was new). Throws IllegalStateException when no source was set, HgValidationException when the remote cannot satisfy the request (for example an unsupported lookup or narrow request), IOException when the remote connection or the local store fails, and HgLockException when a lock cannot be acquired. applyBundle(…​) applies an already parsed changegroup as hg unbundle or the second half of a pull does, returns the added node ids (an empty bundle returns an empty list), and rolls back a failed apply (IOException). The one-argument form fails at once if a lock is held elsewhere; lockTimeoutMs makes it wait (0 keeps the fail-fast behavior).

Locks and dirstate: call() takes lockWorkingCopy() and then lockStore() before reading repository state. applyBundle(…​) takes lockWorkingCopy(lockTimeoutMs) (a no-op lock when setWorkingCopyLock(false)) and then lockStore(lockTimeoutMs). It backs up dirstate and fncache after the locks are held, writes the transaction journal in the original’s format first (for a version 2 revlog the docket is backed up whole and its companion files are cut back; see 4. Locking and Transactions), and rolls back a failed apply while the locks are still held. No changingParents use was found in this class.

List<byte[]> nodes = new FetchCommand(repo)
    .setSource("ssh://hg@example.org/repo")
    .setRevisions(List.of("default"))
    .call();

4.4.7. Incoming

Lists changesets that exist on the remote but not locally. Corresponds to hg incoming (the output has the form of the plain log lines changeset:, user: and summary:).

Setter Meaning

setSource(String)

Source address (required): URL of the remote repository. No default and no [paths] alias resolution; call() throws IllegalArgumentException when it is null or empty.

Execution: List<String> call() throws IOException. Contacts the remote through the standard heads protocol and compares the graph ancestors. Returns lines: three per incoming changeset (changeset: <12 hex>, user: …​, summary: …​), or the single line no incoming changes found. A failed first connection throws IOException("Remote connection failed for …​"). If fetching the changegroup details fails, the result falls back to the missing head ids with a failure text instead of throwing.

Locks and dirstate: none taken; no changingParents.

List<String> lines = new IncomingCommand(repo)
    .setSource("https://example.org/repo")
    .call();

4.4.8. Outgoing

Lists local changesets the remote does not have. Corresponds to hg outgoing.

Setter Meaning

setDestination(String)

Destination address (required): URL of the remote repository. No default and no [paths] alias resolution; call() throws IllegalArgumentException when it is null or empty.

Execution: List<String> call() throws IOException. Finds the local commits that are not ancestors of the remote heads. Returns lines changeset: <rev>:<12 hex>, user: …​, summary: …​ for each changeset the remote heads do not cover, or no outgoing changes found. Connection failure throws IOException("Remote connection failed for …​").

Locks and dirstate: none taken; no changingParents.

List<String> lines = new OutgoingCommand(repo)
    .setDestination("default-push-url")
    .call();

4.4.9. Bundle

Writes changesets to a local bundle file. Corresponds to hg bundle.

Setter Meaning

setOutputFile(File)

Bundle file to write (required; call() throws IllegalStateException if unset).

setBaseRevision(String)

hg bundle --base REV: this revision and its ancestors are excluded. "null" (case-insensitive), "" or "-1" bundles everything (-a). Ignored when setAll(true); incompatible with a destination (IllegalStateException).

setAll(boolean)

hg bundle -a/--all: bundle everything. Incompatible with a destination (IllegalStateException: abort: --all is incompatible with specifying destinations).

setDestination(String)

hg bundle FILE DEST: the bundle holds what the repository at DEST does not have. A path to a local repository or a [paths] name. Unset (and no base and no setAll): paths.default-push, then paths.default, else IllegalStateException("config error: default repository not configured!"). A remote URL is not supported. An unrelated destination fails with IOException("repository is unrelated").

setForce(boolean)

hg bundle -f: bundle everything for an unrelated destination.

setRevision(String)

hg bundle -r REV: restrict to this revision and its ancestors. Unset means all revisions.

setType(BundleType) / setType(String)

--type. Values: none-v1 (default), gzip-v1, bzip2-v1, none-v3, gzip-v3, bzip2-v3. The string form is case-insensitive and throws IllegalArgumentException for unknown names. BundleType.cliName() gives the spelling real hg bundle --type uses and BundleType.fromCliName(String) the case-insensitive lookup. The -v3 types are the only ones real hg can use on a treemanifest repository; compression is applied at the bundle2 stream level.

Execution: int call() throws IOException, HgLockException. Returns the number of changesets written. When the selected set is empty (or the repository is empty) no file is written and 0 is returned. A revision that cannot be found throws IOException. A treemanifest or LFS repository with a -v1 type throws IllegalStateException("abort: repository does not support bundle version 01 …​").

Locks and dirstate: none ("like real hg, bundle only reads: no lock"); no changingParents.

Differences from hg (from the javadoc): the destination must be a repository that can be opened from this machine (no http or ssh discovery). The -v3 family produces an HG20 bundle2 envelope with a cg3 changegroup. Sidedata (cg5) is deliberately not negotiated, which the javadoc describes as a limitation of the real hg bundle as well. The blobs of bundled LFS revisions are uploaded first to the LFS store of the default path or [lfs] url.

int n = new BundleCommand(repo)
    .setOutputFile(new File("all.hg"))
    .setBaseRevision("null")
    .setType("gzip-v1")
    .call();

4.4.10. Unbundle

Applies a local bundle file to the repository. Corresponds to hg unbundle. Reads HG10UN, HG10GZ, HG10BZ and HG20 (bundle2) files.

Setter Meaning

setBundleFile(File)

The bundle file to apply (required, must exist; IllegalStateException otherwise).

Execution: List<byte[]> call() throws IOException, HgLockException. Returns the 20-byte node ids of the imported changesets from FetchCommand.applyBundle. Throws IllegalStateException when no bundle file was set or it does not exist, HgCorruptDataException (an IOException) when the file header or the bundle1 compression is not recognized, IOException when reading the file or writing the repository fails, and HgLockException when the store lock cannot be acquired within the repository’s push lock timeout.

Locks and dirstate: calls FetchCommand.setWorkingCopyLock(false) ("real hg: unbundle holds only the store lock"), so only lockStore(…​) is taken and the dirstate is left alone. No changingParents.

List<byte[]> imported = new UnbundleCommand(repo)
    .setBundleFile(new File("all.hg"))
    .call();

4.4.11. Archive

Extracts an unversioned snapshot of a revision. Corresponds to hg archive.

Setter Meaning

setDestination(File)

Output directory (type files) or archive file (other types). Required: call() throws IllegalArgumentException without it.

setRevision(String)

Revision to archive; default tip. IOException when not found.

setType(String)

files, zip, uzip, tar, tgz or tbz2. Unset: detected from the destination extension (.tbz2/.tar.bz2, .tgz/.tar.gz, .tar, .zip, otherwise files). Unknown names throw IllegalArgumentException.

setPrefix(String)

Directory prefix for every member of a zip or tar archive. Ignored for files. Default is the destination basename with its type suffix removed.

setInclude(String…​)

hg archive -I: only files matching these patterns (globs by default).

setExclude(String…​)

hg archive -X: skip files matching these patterns.

setCwd(String)

Current directory relative to the repository root, against which relative patterns are read.

Execution: void call() throws IOException. If include/exclude patterns match no file, it throws HgValidationException("no files match the archive pattern").

Locks and dirstate: none taken; no changingParents.

Differences from hg (from the javadoc): txz (lzma) is deliberately not implemented. A .hg_archival.txt member is written, zip and tar members get the directory prefix, executable bits and symlinks are kept, and tree manifests are read through HgRepository.getManifestAtCommit.

new ArchiveCommand(repo)
    .setRevision("tip")
    .setDestination(new File("snapshot.tar.gz"))
    .call();

4.4.12. Clonebundles

Downloads a clone bundle from a URL and applies it. This is the client half of Mercurial’s clone bundles mechanism. It is a final class with a private constructor and two static methods, so there are no setters.

Method Meaning

downloadAndApply(HgRepository, String url)

Downloads the bundle at url with a plain HTTP(S) GET (no wire protocol framing, timeouts 10 s connect and 60 s read) and applies it through UnbundleCommand.

applyEntries(HgRepository, HgRemoteConnection peer, List<ClonebundleSelection.Entry> entries, List<String> messages)

Applies the bundles chosen by best_clonebundles. Each is fetched over HTTP or, for a peer-bundle-cache:// entry, from the server’s cache through peer; checked against its DIGEST (sha256 first, then sha512); and applied as a stream (a stream2 part) or as a changegroup bundle. Progress lines are appended to messages.

Return and throws: both return List<byte[]> (commits a changegroup bundle imported; empty when only stream bundles were applied) and throw IOException, HgLockException. A non-200 response throws HgProtocolException. A fetch error or a digest mismatch becomes HgValidationException (applyEntries reports error applying bundle and points to ui.clonebundles=false).

Locks and dirstate: both methods hold lockStore() for the whole download and apply. No working copy lock and no changingParents in this class (the inner UnbundleCommand takes the store lock again through FetchCommand.applyBundle).

Differences from hg: it never falls back to a normal pull when the download fails; any failure propagates. The caller must do the final incremental pull itself.

List<byte[]> imported = ClonebundlesCommand
    .downloadAndApply(repo, "https://cdn.example.org/bundle.hg");

4.4.13. NarrowClone

Clones only part of a repository using include and exclude patterns, or a store shape. Corresponds to hg clone with the narrow extension (--include, --exclude) and --shape.

Setter Meaning

NarrowCloneCommand()

Constructor takes no repository; the destination is created by call().

setSource(String)

Source URL (required; call() throws IllegalStateException if unset).

setDirectory(File)

Directory in which the new repository is created (required; call() throws IllegalStateException if unset).

addIncludePath(String)

Adds an include pattern for hg clone --include; null is ignored. A pattern without a kind prefix is a path: pattern. Patterns are normalized and validated when call() runs, like narrowspec.normalizepattern(): trailing / stripped, unsupported kinds and invalid components (., .., empty) rejected.

addExcludePath(String)

Adds an exclude pattern for hg clone --exclude, same normalization and validation. If only excludes are given, path:. is included.

setShape(String)

hg clone --shape NAMES: comma separated store shape names of a server that advertises exp-shape-1. The server is asked for the shape’s patterns and fingerprint first (store_shape); the patterns become the narrowspec (replacing includes and excludes added with the two methods above), the names are kept in store-shape, and every later pull names the shape and its fingerprint instead of sending patterns.

Also public: getMessages() (what the clone reported, such as the clone bundles applied).

Execution: Hg call() throws IOException, HgLockException. Returns an Hg facade of the cloned repository. IOException for network or narrowspec file failures. IllegalStateException if source or directory is missing; HgValidationException when --shape is used against a remote without exp-shape-1. The shape is requested before anything is created, so a refusal leaves no repository.

Locks and dirstate: holds lockWorkingCopy() on the new repository from after init to the end. Inside it, writes .hg/requires (adds narrowhg-experimental), then writes .hg/store/narrowspec under a short lockStore() scope, and .hg/narrowspec.dirstate. For a shape, store-shape is also written under lockStore(). After that it runs PullCommand with the narrow filter, clears the revlog cache, and runs UpdateCommand with the same filter. No direct changingParents call in this class.

Hg hg = new NarrowCloneCommand()
    .setSource("https://example.org/repo")
    .setDirectory(new File("narrow"))
    .addIncludePath("src")
    .addExcludePath("src/gen")
    .call();

4.4.14. ShardedStreamBundles

Writes one streaming bundle for every shard of the store. Corresponds to hg debug::sharded-stream-bundles. The bundles go to server.peer-bundle-cache-root (relative to .hg, bundle-cache by default) as hg-sharded-<group>-<shard fingerprint>.hg. It is a final class.

Setter Meaning

setGroupId(String)

Group id (eight hex digits). A fresh random id is used when unset; all bundles of one run share it.

Execution: List<File> call() throws IOException, HgLockException. Returns the files written, shard by shard in the order of their names. Throws HgValidationException("server does not support narrow stream clones") unless experimental.server.stream-narrow-clones is true or 1.

Locks and dirstate: takes lockWorkingCopy() and then lockStore() and holds both for the whole run, so every shard is taken in lockstep from one state of the repository. No changingParents.

List<File> files = new ShardedStreamBundlesCommand(repo)
    .setGroupId("0a1b2c3d")
    .call();

4.4.15. Paths

Lists the [paths] aliases of the repository configuration. Corresponds to hg paths.

Setters: none.

Execution: Map<String, String> call(). Returns alias to URL, sorted alphabetically by alias, empty and never null when no [paths] section exists. It declares no checked exceptions.

Locks and dirstate: none.

Differences from hg (from the javadoc): per-path sub-options such as default:pushurl are out of scope; only the base name = url entries are exposed.

Map<String, String> paths = new PathsCommand(repo).call();
String url = paths.get("default");

4.4.16. LfsUpload

Uploads the LFS blobs that given revisions introduced. Corresponds to hg debuglfsupload -r REV. The target is the LFS store of the default path or [lfs] url, the same upload a push or bundle does.

Method Meaning

addRevision(String)

Adds a revision whose blobs are uploaded. With none added, the first dirstate parent is used.

Execution: int call() throws IOException. Returns the number of distinct blobs considered (the server skips those it already has). A revision that cannot be found throws IOException("Revision not found: …​").

Locks and dirstate: none taken; it only reads the dirstate parent when no revision is given. No changingParents.

int blobs = new LfsUploadCommand(repo)
    .addRevision("tip")
    .call();

4.5. Maintenance and integrity commands

4.5.1. VerifyCommand

Checks the integrity of the repository store. Corresponds to hg verify. The javadoc calls it a "simplified verifier": it checks node id hash consistency of the changelog, the manifest, treemanifest submanifests under meta/ and every filelog, and it does not cross-check changelog, manifest and filelog linkage.

Method Meaning

VerifyCommand(HgRepository)

Constructor. A null repository raises IllegalArgumentException.

setSkipLfs(boolean)

hg verify --no-lfs: do not read (so do not fetch) an LFS blob that is not stored locally. The config verify.skipflags with the EXTSTORED bit (0x2000) has the same effect.

Execution

List<String> call() throws HgLockException. Returns the error messages; an empty list means the checks found nothing. Read failures inside the check are reported as the message critical repository read failure: …​ and are not thrown. A failure while releasing the lock is rethrown as HgLockException. A repository without 00changelog.i counts as an empty changelog (0 revisions), as in real hg. A missing 00manifest.i is an error only when the changelog has revisions. Filelogs are discovered from fncache plus a walk of data/; an fncache entry whose index file is missing is reported.

Locking

The store lock only, via lockStoreWithoutRecovery, held around the whole check ("Like real hg (verify.verify)"). No working copy lock. dirstate is not touched.

Differences from hg

Simplified verifier as described above (no linkage cross-checks). Otherwise not stated in the source.

try (Hg hg = Hg.open("/path/to/repo")) {
    List<String> errors = hg.verify().setSkipLfs(true).call();
    if (!errors.isEmpty()) errors.forEach(System.err::println);
}

4.5.2. RecoverCommand

Rolls back an interrupted transaction (a leftover .hg/store/journal). Corresponds to hg recover (and hg recover --verify).

Method Meaning

RecoverCommand(HgRepository)

Constructor. A null repository raises IllegalArgumentException.

setVerify(boolean)

hg recover --verify: only when an interrupted transaction was found and rolled back, additionally run VerifyCommand and report its errors on the result.

Execution

RecoverResult call() throws HgLockException. The result has wasInterrupted() (a journal was found; false is real hg’s "no interrupted transaction available"), isSuccess() (nothing to recover, or rolled back; false means the rollback could not complete and the journal is kept for a retry) and getVerifyErrors() (null unless verify ran; an empty list means verify found nothing). "Nothing to recover" is returned as a result, not thrown.

Locking

The store lock only, via lockStoreWithoutRecovery (the lock does not recover by itself). No working copy lock is taken. The rollback is delegated to HgRepository.checkAndPerformAutoRollback(), which restores the store files from the journal and never touches the dirstate (it reads the original’s journal format, so it rolls back an interrupted real hg as well as an interrupted hg4j, and a journal of an older hg4j version) (the code notes that recovering a transaction does not change it, because the dirstate is written after the transaction). The lock wait uses the repository’s push lock timeout. When setVerify(true) applies, VerifyCommand.call() runs under the same held lock. Without a journal nothing is done.

Differences from hg

Returns a RecoverResult instead of an exit code or message, and "nothing to recover" (real hg: no interrupted transaction available, exit 1) is a normal result, not an error, so a library caller can run it as a health check before opening.

RecoverCommand.RecoverResult r = hg.recover().setVerify(true).call();
if (r.wasInterrupted() && !r.isSuccess()) {
    System.err.println("journal kept for retry");
}

4.5.3. RollbackCommand

Undoes the last transaction using the undo* files. Corresponds to hg rollback.

Method Meaning

RollbackCommand(HgRepository)

Constructor. There are no setters.

Execution

void call() throws IOException, HgLockException. Also reachable as Hg.rollback() (same throws). Takes the working copy lock and the store lock, waiting up to the repository’s push lock timeout. Throws IllegalStateException("No rollback information available (undo file not found)") when store/undo does not exist, IOException when restoring the files fails, and HgLockException when a lock cannot be acquired within the timeout. Steps: (1) read undo and truncate or delete store files (trunc lines truncate only, backup lines restore full file bytes for v2 docket revlogs, plain lines truncate to the recorded size or delete on size 0); (2) restore .hg/dirstate from .hg/undo.backup.dirstate (or delete dirstate when no backup exists), and restore the dirstate-v2 data file from .hg/undo.backup.dirstate.data when the docket’s uid file is missing; (3) restore .hg/bookmarks from .hg/undo.backup.bookmarks (or delete it) and delete .hg/bookmarks.current; (4) in a finally, delete all undo* info files and the consumed docket backups, and clear the revlog cache.

Locking

lockWorkingCopy(timeout) first, then lockStore(timeout) (the version that, per HgRepository.lockStore, refuses with HgAbandonedTransactionException when a journal exists and the lock is not re-entrant), both taken before the first read and released at the end. Rollback does modify dirstate and bookmarks.

Differences from hg

Not stated beyond the conformance note in the class javadoc to the undo.* layout.

hg.rollback();
// or
new RollbackCommand(hg.getRepository()).call();

4.5.4. GcCommand

Store compaction and cleanup. No exact hg command; the source says the nearest real operations are debugupgraderepo and debugrebuildfncache.

Method Meaning

GcCommand(HgRepository)

Constructor. There are no setters.

Execution

String call() throws IOException, HgLockException. Returns a summary string of the form GC / Compaction complete: defragmented and re-delta optimized N store revlogs, cleaned M orphaned temp files. Throws IOException when the store directory does not exist (checked first, because taking a lock would create it). Steps: clear the revlog cache; delete .backup, .tmp and journal files in the store root; rewrite the changelog, the manifest and every .i revlog under data/ and meta/ revision by revision into temp files and swap them in atomically (empty revlogs and v2/docket revlogs are skipped and left untouched); rebuild fncache with atomic IO (entries for data/ and meta/ revlogs only, plus .d entries for split revlogs), skipped for fileindex-v1 repositories or when nothing was found; call System.gc().

Locking

lockWorkingCopy(timeout) first, then lockStoreWithoutRecovery(timeout), because the command removes leftovers including a stale journal (journal, journal.backupfiles, journal.truncateonly) itself and counts them.

Differences from hg

No direct counterpart. v2/docket revlogs (changelog-v2, general-v2) are never rewritten because the source says real hg has no compaction for them and rewriting would be destructive.

String summary = hg.gc().call();
System.out.println(summary);

4.5.5. AdminVerifyCommand

Runs named repository checks. Corresponds to hg admin::verify (admin/verify.py). Mercurial 7.2 registers one check here, working-copy.dirstate (alias dirstate), which compares the dirstate with the manifests of its parents.

Method Meaning

AdminVerifyCommand(HgRepository)

Constructor.

addCheck(String)

-c/--check: a check to run. A name is a qualified name, an alias, a prefix of a qualified name (working-copy runs everything below it) or full. With none, the call fails.

addOption(String)

-o/--option: check:option=value. The check has to accept the option; the only registered check accepts none.

getOutput()

The lines ui.status printed.

getWarnings()

The lines ui.warn printed: findings, and the warning abandoned transaction found - run hg recover when a journal exists.

Execution

Map<String, Integer> call() throws IOException. Returns the number of errors per check (qualified name) for each check that found some. Throws HgValidationException (an IOException) for an unknown check, an invalid option, an option for an unselected check, an option the check does not have, and when no check was selected ( checks required ).

Locking

None. The class javadoc says "Nothing is locked: it only reads."

Differences from hg

Not stated beyond the single registered check.

AdminVerifyCommand v = new AdminVerifyCommand(hg.getRepository()).addCheck("dirstate");
Map<String, Integer> found = v.call();
v.getWarnings().forEach(System.err::print);

4.5.6. NarrowServerAdmin

Administration of the shards and shapes of a server repository. Corresponds to hg admin::narrow-server and admin::narrow-client (--store-fingerprint). The class is final and has no call(); each option is its own method. The source points to llm-wiki/concepts/store-shapes.md sections 10 and 11 for the analysis.

Method Meaning

NarrowServerAdmin(HgRepository)

Constructor.

getWarnings()

What the last call warned about (ui.warn), for example a store shapes update in progress.

shapeFingerprints()

--shape-fingerprints: <fingerprint> <names> for every shape.

storeShardsListing()

--store-shards: the id of every shard, then read-write-access=a,b when it has some.

shapePatterns(String names)

--shape-patterns NAMES: inc:/path and exc:/path lines in zero path order.

shapeNarrowPatterns(String names)

--shape-narrow-patterns NAMES: the legacy [include] and [exclude] sections without the root.

shapeFiles(String names, boolean hiddenOnly)

--shape-files / --shape-files-hidden: sorted filelogs of the store covered by the shape; with hiddenOnly, only those not in the working copy.

shapeUpdate(byte[] newContents, UpdateOptions options)

--shape-update: replaces the server-shapes file after validation. A header comment is prepended when missing.

shapeClearPrevious()

--shape-clear-previous: removes the saved previous configs; returns cleared N saved server-shapes.

static storeFingerprint(Set<String> includes, Set<String> excludes)

admin::narrow-client --store-fingerprint: the fingerprint of a narrow clone’s store narrowspec, with a trailing newline.

UpdateOptions(overrideReshapeAndReshardCheck, overrideFingerprintChangeCheck, overrideSavedConfigsCheck)

Record of the three override-* flags of --shape-update; UpdateOptions.strict() has all false.

Execution

Listing methods return List<String> and throw IOException. shapeUpdate returns void and throws IOException, HgLockException. shapeClearPrevious returns String and throws IOException, HgLockException. Every instance method first throws HgValidationException("repo is narrowed, this is a server command") when narrowhg-experimental is in .hg/requires or store/requires. An unknown shape name gives HgValidationException("shape '…​' not found"). shapeUpdate validation (HgValidationException) refuses redefining the fingerprint of an existing shape, reshaping and resharding in one update, and reshaping while previous configs are still saved, each unless its override flag is set.

Locking

Listing methods take no lock and only warn when an update is in progress. shapeUpdate: the store shapes lock without waiting (lockStoreShapes(0)), read the old config, parse and validate the new one (a bad document aborts before anything is written), then the store lock (lockStoreWithoutRecovery) only for the write, saving the old config first when shards changed, then an atomic write. shapeClearPrevious: shapes lock then store lock together. No working copy lock.

Differences from hg

Not stated.

NarrowServerAdmin admin = new NarrowServerAdmin(hg.getRepository());
admin.shapeFingerprints().forEach(System.out::println);
admin.shapeUpdate(Files.readAllBytes(Path.of("server-shapes")), NarrowServerAdmin.UpdateOptions.strict());

4.5.7. ChainsawUpdateCommand

Pulls and updates to a revision no matter what. Corresponds to hg admin::chainsaw-update (mercurial/admin/chainsaw.py). The javadoc marks it DANGEROUS: a non-repository directory at the destination is removed, locks left by anybody are broken, local changes and unknown files are thrown away. Intended for unattended use with exclusive access.

Method Meaning

setRevision(String)

--rev: the target revision. Required.

setSource(String)

--source: where to pull from. Required.

setDestination(String)

--dest: the repository to update; it is cloned (created) when it does not exist. Required.

setPurgeUnknown(boolean)

--purge-unknown, default on.

setPurgeIgnored(boolean)

--purge-ignored, default on.

setInitialCloneMinimal(boolean)

--initial-clone-minimal: pull only the revision when the repository is created (so no clone bundle is used).

getMessages()

What the command told the user, line by line as hg prints it.

Execution

void call() throws IOException, HgLockException. Throws HgValidationException when revision, source or destination is empty, IOException when any step fails, and HgLockException when the locks cannot be taken after the old ones were broken. If <dest>/.hg exists the repository is loaded; otherwise whatever is at the destination is deleted, a repository is created with Hg.init() and the repository is pulled in full unless setInitialCloneMinimal(true). Then: break the locks, recover, pull, purge, force update.

Locking

As in the original, in this order: the lock files store/lock and .hg/wlock are deleted without taking anything (messages had to break store lock and had to break working copy lock); then lockWorkingCopy() and lockStoreWithoutRecovery(timeout) are taken together for recovery (RecoverCommand), pull, purge (PurgeCommand with directories, files = purge unknown, ignored = purge ignored) and update (UpdateCommand with force). The pull and the update take the same locks again (re-entrant); purge takes none of its own.

Differences from hg

Not stated beyond the danger notice above.

ChainsawUpdateCommand c = new ChainsawUpdateCommand()
    .setSource("https://example.org/repo").setDestination("/srv/checkout").setRevision("default");
c.call();
c.getMessages().forEach(System.out::print);

4.6. Signing commands

These use the gpg extension format (hgext/gpg.py). All three need a GpgKeyring (set with setKeyring).

4.6.1. SignCommand

Signs changesets with a GPG key. Corresponds to hg sign. The signature is recorded in .hgsigs (committed) or, with setLocal, in .hg/localsigs (never committed). The format and signed text are those of the gpg extension, so hg sigcheck accepts what is written.

Method Meaning

setNodeId(byte[])

The changeset to sign (20-byte node). Default: the working directory’s parent.

setKeyring(GpgKeyring)

The keys to sign with; must contain a secret key (GpgKeyring.withSecretKeys). Required.

setKeySpec(String)

hg sign --key: part of a user id, or a key id / fingerprint (suffix).

setPassphrase(char[])

The key’s passphrase; null or empty for an unprotected key.

setLocal(boolean)

--local: write .hg/localsigs, which is not versioned and never committed.

setCommit(boolean)

--no-commit is setCommit(false): write and track .hgsigs but do not commit. Default true.

setForce(boolean)

--force: sign even though .hgsigs has uncommitted changes.

setMessage(String)

The commit message; default is one line Added signature for changeset <short> per signed changeset.

setAuthor(String)

Commit author of the .hgsigs commit, normally Name <email>. Default hg4j <hg4j@google.com>. Unused with setLocal or when setCommit(false).

setSigningTime(Instant)

The signature creation time; default now.

Execution

List<HgSigEntry> call() throws IOException, HgLockException; returns the signature lines that were recorded. Throws IllegalStateException without a keyring; HgValidationException for no usable signing key, an uncommitted merge, a repository with no changeset, or a changed or untracked .hgsigs (unless forced); HgRevisionNotFoundException for an unknown node. All checks that can refuse run before .hgsigs is written.

Locking

The working copy lock only, lockWorkingCopy(), for the whole command. The commit (CommitCommand with match=.hgsigs) takes the store lock itself and releases it. Signing, the write of .hgsigs and the add happen under the working copy lock alone.

Differences from hg

hg sign --force crashes in the original with UnboundLocalError; setForce works here. Like the original, a failure after .hgsigs was written leaves the file as it is. The commit holds .hgsigs only; other changes stay uncommitted.

List<HgSigEntry> entries = hg.sign()
    .setKeyring(keyring).setKeySpec("alice@example.org")
    .setPassphrase("secret".toCharArray()).setCommit(true).call();

4.6.2. SigsCommand

Lists signed changesets, newest revision first, with each valid signer. Corresponds to hg sigs.

Method Meaning

setKeyring(GpgKeyring)

The keyring to verify against. Required.

setNow(Instant)

The time expiry is judged against; default now.

Execution

Result call() throws IOException. Result is a record (List<Signed> signatures, List<String> warnings); Signed is a record (int revision, String nodeHex, HgSigResult signature, String source). Signatures are sorted highest revision first. Invalid signatures are not listed; their reasons are collected in warnings with the same wording and the <file>:<line> prefix hg would have printed (keyring notes stay in GpgKeyring.getNotes()). A signature of a node that does not exist gives the warning node does not exist. A line that is not a signature line at all is an IOException (HgSigFormatException). Throws IllegalStateException without a keyring. Expiry is judged at the time of setNow (default now). IOException also covers a failure to read the repository.

Locking

None taken; it calls refreshIfChangedOnDisk() and reads.

Differences from hg

Warnings are returned instead of printed; a malformed line is an exception instead of being skipped.

SigsCommand.Result r = hg.sigs().setKeyring(keyring).call();
r.signatures().forEach(s -> System.out.println(s.revision() + " " + s.nodeHex()));
r.warnings().forEach(System.err::println);

4.6.3. SigCheckCommand

Verifies every signature recorded for one changeset. Corresponds to hg sigcheck REV.

Method Meaning

setNodeId(byte[])

The changeset to check (20-byte node). Required.

setKeyring(GpgKeyring)

The keyring to verify against. Required.

setNow(Instant)

The time expiry is judged against; default now.

Execution

Result call() throws IOException. Result is a record (String nodeHex, List<HgSigResult> validSignatures, List<String> warnings) with isSigned(). An empty validSignatures() is what real hg reports as no valid signature for <short>. It reads every signature from the signature files (committed and local), picks those for the node and verifies each against the keyring at the time of setNow. Throws IllegalStateException when the node or keyring is missing, HgRevisionNotFoundException (an IOException) when the node is not in the changelog, and IOException when reading the repository fails.

Locking

None taken; it calls refreshIfChangedOnDisk() and reads.

Differences from hg

Warnings are returned instead of printed.

SigCheckCommand.Result r = hg.sigcheck().setNodeId(nodeBytes).setKeyring(keyring).call();
System.out.println(r.isSigned() ? "signed" : "no valid signature");

4.7. Subrepo and merge preview

4.7.1. SubrepoCommand

Adds, initializes or updates subrepositories through .hgsub and .hgsubstate. The javadoc names it "submoduleAdd / Init / Update". No single hg command; update and init do what hg update -S does for each entry, per the comments in the source.

Method Meaning

setAction(String)

add (append an entry to .hgsub and .hgsubstate), or init or update (clone or update every subrepository listed in .hgsub to the revision in .hgsubstate); case-insensitive. Must be set before call(); null raises IllegalArgumentException.

setSubrepoPath(String)

Subrepo path relative to the repository root, written to .hgsub. Required for add.

setSubrepoUrl(String)

Subrepo source written to .hgsub. Required for add.

setRevision(String)

Revision string written to .hgsubstate by add; null (the default) records the all-zero node (40 zeros). Not used by init or update, which read the revision from .hgsubstate.

Execution

void call() throws IOException, HgLockException. add appends path = url to .hgsub and <rev> path to .hgsubstate (no commit). init and update behave the same: for each .hgsub entry, find the pinned revision in .hgsubstate, then for a plain hg subrepo clone it when absent (with a forced update to the pin), or when it already is a checkout pull the source if the pin is not present locally (best effort) and force-update to the pin; an existing non-hg directory is left untouched. [git] and [svn] prefixed entries use the git and svn helpers (GitSubrepoUtil, SvnSubrepoUtil). If .hgsub is missing, init and update return silently. Throws IOException when subrepo parsing or network cloning fails, including a subrepo URL that is empty for a path that must be cloned.

Locking

This class takes no lock itself (no lockWorkingCopy or lockStore call). Locks taken by the nested clone, pull and UpdateCommand calls are not described in this class.

Differences from hg

Not stated.

hg.subrepo().setAction("add").setSubrepoPath("libs/core")
    .setSubrepoUrl("https://example.org/core").call();
hg.subrepo().setAction("update").call();

4.7.2. TreeMergeCommand

A working-copy-free 3-way merge computation (the javadoc says JGit ThreeWayMerger parity). Takes two commit nodes, computes their common ancestor and the per-file merge purely from the changelog, manifest and filelog store, and returns the merge as data (for example for a pull request merge preview, or a server-side merge that commits its result without a working copy). It does not write to disk or touch dirstate or the working directory. MergeCommand stays the porcelain command for real hg merge.

Method Meaning

setOurs(byte[])

The "ours" commit node (20 bytes); the result is expressed relative to it. Required before call().

setTheirs(byte[])

The "theirs" commit node (20 bytes), the changeset merged in. Required before call().

setBase(byte[])

The ancestor to merge against instead of the common ancestor; graft uses the parent of the grafted changeset. null or the null node means an empty ancestor.

Execution

TreeMergeResult call() throws IOException. TreeMergeResult has isConflicted(), getConflicts() (paths whose merged content still has conflict markers), getChangedFiles() (path to final content, relative to "ours"), getChangedModes() (path to POSIX mode: 0644, 0755, 0120000) and getRemovedFiles(). The result is never null. Throws HgRevisionNotFoundException (an IOException) when ours, theirs or a given base is not in the changelog, and IOException when reading the store fails.

Locking

None. Pure reads of the changelog, manifest and filelogs; MergeCommand.call() is never invoked, only its already verified LCA and criss-cross base resolution and the per-file Merge3 logic are reused.

Differences from hg

It is a computation, not a working copy merge. A file that one side deleted and the other changed is a conflict (listed in getConflicts() without content in getChangedFiles()), as in hg merge. For a path merged by content, the mode is taken from "ours" when both sides have it, following the convention of the rebase merge logic.

TreeMergeCommand.TreeMergeResult r = hg.treeMerge().setOurs(a).setTheirs(b).call();
if (r.isConflicted()) System.out.println(r.getConflicts());
r.getChangedFiles().forEach((path, bytes) -> apply(path, bytes));

4.7.3. MergeCommitCommand

Merges two heads and commits the result as one changeset with two parents, without a working copy: hg merge -r P2 followed by hg commit, for a server repository that has no checkout. The merge is computed by TreeMergeCommand; the new file revisions, manifest and changeset are written the way the original’s commit writes them. A file the merge takes unchanged from the second parent keeps that parent’s file revision, a file both sides changed gets a new file revision with two parents, and the changeset lists only the files that were really touched. For the same two heads, user, date and message the result is the same changeset (same node) that hg merge and hg commit create; the interop tests compare the nodes. Repositories with changeset sidedata (changelog-v2) get the changed-files sidedata, equal to what the original stores.

Method Meaning

setP1(byte[]), setP1(String)

The first parent: the head the merge is committed on (the receiving side). A node, or a revision identifier. Required.

setP2(byte[]), setP2(String)

The second parent: the head merged in (the sending side). Required.

setBase(byte[]), setBase(String)

The ancestor to merge against instead of the common ancestor of the parents (optional).

setUser(String)

The committer as stored in the changeset. Required.

setMessage(String)

The message; trailing white space of each line and empty lines at both ends are removed, as hg commit does. Required, not blank.

setDate(String)

"<unix seconds> <offset>", the offset in seconds west of UTC. Default: now, local time zone. A malformed date throws HgValidationException.

setBranch(String)

The named branch of the merge changeset. Default: the branch of the first parent.

putExtra(String, String)

An extra entry of the changeset. The key branch is refused (IllegalArgumentException); use setBranch.

setAllowAncestorMerge(boolean)

Allows a merge in which one parent is an ancestor of the other, like git merge --no-ff. Default false.

Execution

MergeCommitResult call() throws IOException, HgLockException. MergeCommitResult has isConflicted(), getConflicts() (sorted paths), getNode() (20 bytes, null when conflicted) and getNodeHex(). A conflict is a value, not an exception, and nothing has been written then. Throws HgValidationException for a missing user or message, an invalid date, the same changeset on both sides, one parent being an ancestor of the other (unless allowed) and a treemanifest repository; HgRevisionNotFoundException when a parent or the base is not in the changelog; HgLockException when the store lock cannot be taken; IOException for store errors, after which the repository is rolled back.

Locking

Only the store lock (lockStore) and a rollback transaction, no wlock and no dirstate, as for GraftInMemory. The lock is held for the whole call: the merge computation and the writes. Waits up to [ui] timeout for another holder.

Differences from hg

A file one side deleted and the other changed is a conflict (the original asks the user). Copies and renames are followed: a file one side copied or renamed and the other side changed under its old name gets the change merged into the new name, and the new file revision records the copy; the interop tests compare the resulting changesets with the real hg (rename on either side, copy, rename with its own edit, divergent renames, rename against deletion). Directory renames are not followed: a file the other side added to a directory that was renamed away is reported as a conflict, where the original moves it to the new directory. Treemanifest repositories are refused. A file whose content hg4j has to merge is merged by line (Merge3); no external merge tool is run. A file that the lfs extension tracks (lfs.track, .hglfs) is written as a pointer with the external-storage flag, and its node is the hash of the real content, as the original’s lfs wrapper does for every new file revision; a file taken unchanged from the other parent keeps its pointer revision. setAllowAncestorMerge(true) creates a merge the original refuses ("nothing to merge"); its tree is the tree of the descendant.

setSquash(true) needs no working copy: it writes the changeset straight into the store, which is why a server repository without working files uses it. The same result by the original’s commands (update, merge, debugsetparents, commit) needs a working copy, for example one made by WorktreeCommand; hg4j has no debugsetparents command, and a composition of public commands is deliberately not offered (decision of 2026-11-17).

setSquash(true) commits the merged tree as one changeset with p1 as its only parent, the way hg merge, hg debugsetparents P1 and hg commit do (the interop tests compare the nodes with the real hg: different files, one file edited on both sides, deletion, executable bit, symlink, renames, a descendant as p2 with setAllowAncestorMerge(true), changelog-v2 sidedata). Files the merge takes from p2 are added or modified relative to p1, a followed rename is recorded as a copy of p1’s file, and every deletion is recorded. An ancestor relation is refused as `hg merge refuses it ("nothing to merge"), unless setAllowAncestorMerge(true) is set; a result equal to p1’s tree fails with "nothing changed" as `hg commit does.

MergeCommitResult r = hg.mergeCommit()
    .setP1(receivingHead).setP2(sendingHead)
    .setUser("Name <mail@example.org>").setMessage("Merge pull request #12")
    .call();
if (r.isConflicted()) {
    show(r.getConflicts());
} else {
    publish(r.getNodeHex());
}

4.8. Facade, hooks and exceptions

4.8.1. Hg (facade)

Hg is the porcelain entry point, similar to JGit’s Git. It implements AutoCloseable. The javadoc states that instances are thread-safe for concurrent reads and writes, and that runTransaction gives thread and process atomicity for a sequence of operations (for example status followed by commit). Each command factory returns a fresh, unconfigured command object bound to the repository.

Method Meaning

static Hg open(String path) / static Hg open(File directory)

Opens an existing repository. Checks the requirements in both .hg/requires and .hg/store/requires against the supported list. Throws IOException when the repository is not found or invalid (HgRepositoryNotFoundException when .hg is missing).

static Hg wrap(HgRepository)

Wraps an existing repository handle. A null raises IllegalArgumentException.

static InitCommand init()

Command to initialize a repository.

static CloneCommand cloneRepository()

Command to clone a repository.

static NarrowCloneCommand narrowClone()

Command to make a narrow clone with a narrowed set of paths. Not tied to an existing repository.

Hg registerHook(HgHookType, HgHook)

Registers a Java hook for a phase (several per phase are kept in order); returns this for chaining. Null type or hook is ignored.

List<HgHook> getHooks(HgHookType)

The hooks registered for a phase.

void runTransaction(Runnable) throws Exception

Runs the action while holding lockWorkingCopy() then lockStore() (exclusive, so no concurrent writer gets in between), and releases both when it ends. Lock failures and anything the action throws propagate.

HgRepository getRepository()

The wrapped repository handle; never null.

HgRcConfig config()

Config loaded in Mercurial’s priority order: the system hgrc (/etc/mercurial/hgrc), the user hgrc (~/.hgrc or ~/mercurial.ini), then the repository .hg/hgrc.

List<byte[]> clonebundle(String url) throws IOException, HgLockException

Downloads a clone bundle by plain HTTP(S) GET and applies it (ClonebundlesCommand); returns the imported commits. A failure here never falls back silently to a normal pull.

SparseConfig sparseConfig(int changelogRev)

Resolves the effective .hg/sparse rules (including %include profiles tracked at that revision) into an include/exclude pattern set, as sparse.patternsforrev does.

getDiff(int, int) / getDiff(NodeId, NodeId)

Diff entries between two revisions.

getTree(int) / getTree(NodeId)

File tree of a revision.

walkManifest(String), walkWorkingDir(), walkTree()

New walkers: over the manifest of a revision (ManifestWalk), over the files of the working directory (WorkingDirWalk), and a TreeWalk for parallel sorted traversal of several trees.

void rollback()

Runs RollbackCommand (hg rollback) under the working copy lock and the store lock. Throws IOException when the undo information cannot be read or applied, HgLockException when a lock cannot be acquired, IllegalStateException when no rollback information is available.

close()

Closes the facade.

Command factories (each returns a new command bound to the repository; those marked with hooks also attach the registered hooks): add(), commit() (PRE_COMMIT, POST_COMMIT), status(), log(), branch(), sign(), sigs(), sigcheck(), tag() (PRE_TAG, POST_TAG), bookmark(), merge() (PRE_MERGE, POST_MERGE), pull(), fetch(), worktree(), shelve(), rebase() (PRE_REBASE, POST_REBASE), update() (PRE_UPDATE, POST_UPDATE), push() (PRE_PUSH, POST_PUSH), cat(), revert(), remove(), diff(), tree(), rename(), annotate(), resolve(), amend(), bisect(), grep(), histedit(), export(), importPatch(), graft() (POST_GRAFT), purge(), archive(), gc(), subrepo(), incoming(), outgoing(), describe(), phase(), revset(), heads(), identify(), strip(), verify(), root(), tip(), parents(), summary(), forget(), addremove(), backout(), unbundle(), branches(), treeMerge(), censor(), tags(), paths(), files(), locate(), manifest(), copy(), bundle(), recover(). There are no factories for AdminVerifyCommand, NarrowServerAdmin or ChainsawUpdateCommand in Hg; construct them directly.

4.8.2. Serving several repositories (base path)

HgHttpWireServer.setBasePath("/owner/project") makes the server answer only under that path: the prefix is removed before the LFS endpoints (.git/info/lfs/objects/batch, .hg/lfs/objects/…​) are recognized, the wire protocol (?cmd=) is served there too, and every request outside the prefix gets 404. The transfer links (href) in a batch response start with the prefix too (http://host/owner/project/.hg/lfs/objects/<oid>;), as real hg builds them from req.baseurl, so a real hg client uploads and downloads under it. The prefix is matched against the request URI as the container reports it, so it includes the context path. A missing leading slash and a trailing slash are ignored; the default is the root, where nothing changes.

HgHttpWireServer.setLfsServing(Boolean) turns the LFS endpoints on or off for every repository the server handles, without a restart: false answers like [experimental] lfs.serve=false (the LFS requests are not served), true serves them whatever the hgrc says, and null (the default) leaves it to the hgrc of each repository. It is read on every request.

4.8.3. Refusing a push with a reason

A server hook that only returns false refuses a push without a reason: the client sees abort: pretxnchangegroup hook failed. A hook that throws HgHookAbortException("protected branch: default") (like a Python hook of the original raising error.Abort) makes the server print error: pretxnchangegroup hook failed: protected branch: default for the client, then transaction abort! and rollback completed (only for pretxnchangegroup, which runs after the changegroup is appended but inside the transaction, with the journal still on disk: a server that dies there leaves the journal for hg recover, and a refusing hook rolls the whole apply back), and the push fails with abort: protected branch: default. The wire sessions (HTTP and SSH, bundle2 and bundle1, prechangegroup and pretxnchangegroup) are compared byte for byte with the real server in the interop tests. The hook name is the hook type; the original also appends the name given in the hook configuration (pretxnchangegroup.name), which a Java hook does not have. What a hook prints itself (the output of an external hook) is not forwarded.

4.8.4. HgHook and HgHookType

HgHook is a @FunctionalInterface: boolean run(Map<String, Object> context) throws IOException. Returning true allows the operation; returning false blocks it and aborts the transaction by raising an exception. It may throw IOException for an I/O error or a failed hook. The javadoc lists example context keys author, message, commitNode, repository; the keys actually passed differ by command. In CommitCommand the pre-commit context contains author, message and repository, and a false result throws HgValidationException("Pre-commit hook execution rejected the commit txn").

The hooks that the wire servers and HgLocalClient.pushWithHooks run on the server side get these context keys (always repository, the changed HgRepository). The changegroup hooks (prechangegroup, pretxnchangegroup, changegroup) get nodes, a List<String> of 40-character hex node ids in the order they are applied; the first and last node and the count are read from the list. pretxnchangegroup and changegroup run only if at least one changeset is new to the repository, as in the original, and list the new changesets only; prechangegroup lists every changeset of the bundle. The changegroup hook runs after the locks are released and its result is ignored. The pushkey hooks (prepushkey, pushkey) get namespace (for example bookmarks), key (the name), old and new (hex node ids; the empty string, never null, for a bookmark that is created or deleted); the post hook runs only after a successful update. A refusal by a pre-hook is the answer 0 to a pushkey command, and the same inside a bundle2 push: a mandatory pushkey part then fails with error:pushkey and an advisory one is answered with return=0; for a bookmarks part the refusal aborts the push (prepushkey hook failed). In a bundle2 push the pre-hooks run after the changegroup of the same push was applied, so they can read its changesets; a refusal undoes the push. HgSshWireServer and HgHttpWireServer support the same hooks.

Context keys and failure behavior of the other commands, from their javadoc and code: PushCommand passes destinationUrl and repository to pre hooks (false gives HgValidationException) and destinationUrl, response and repository to post hooks (return value ignored, exceptions swallowed, run after the locks are released, only after changesets were pushed). RebaseCommand passes repository, sourceNode and targetNode to pre hooks (false gives HgValidationException, message Rebase rejected by PRE_REBASE hook) and sourceNode, targetNode, rebasedTipNode (hex of the last new changeset, or null) and repository to post hooks (return value ignored, exceptions logged and swallowed). GraftCommand passes sourceRevision, graftedNode and repository to post hooks (return value ignored, exceptions logged as a warning, so a post-graft hook cannot abort the graft). TagCommand passes repository, tag and node; a pre hook returning false gives HgValidationException (Tag creation rejected by PRE_TAG hook), and exceptions from post hooks propagate.

Register with hg.registerHook(HgHookType.PRE_COMMIT, ctx → …​); the hook is attached to a command when it is created through the Hg factory method for that command. A command built with new XCommand(repo) does not receive the registered hooks. ProcessHook (class in the same package) is an HgHook that runs an external process and maps context entries to environment variables named HG_<KEY>. The command line is split on unquoted whitespace (single or double quotes group words; no shell is involved, so there is no expansion or redirection). Constructors take a command string, or a list with an optional working directory; without one the directory of the repository context entry is used, then the current directory of the JVM. A null, blank or empty command is accepted without running anything. Exit code 0 allows the operation; any other exit code logs a warning and rejects it (returns false).

HgHookType Meaning (from the javadoc) and wiring

PRE_COMMIT

Before a commit transaction; aborting cancels the commit. Wired by Hg.commit().

POST_COMMIT

After a commit. Wired by Hg.commit().

PRE_PUSH

Before a remote push; aborting cancels it. Wired by Hg.push().

POST_PUSH

After a push. Wired by Hg.push().

POST_GRAFT

After a graft. Wired by Hg.graft().

POST_REBASE

After a rebase. Wired by Hg.rebase().

POST_MERGE

After a merge. Wired by Hg.merge().

POST_UPDATE

After an update (checkout). Wired by Hg.update().

PRE_MERGE

Before a merge, can be rejected. Wired by Hg.merge().

PRE_UPDATE

Before an update, can be rejected. Wired by Hg.update().

PRE_REBASE

Before a rebase, can be rejected. Wired by Hg.rebase().

POST_STRIP

After a strip. No wiring found in Hg.java.

POST_AMEND

After an amend. No wiring found in Hg.java.

PRE_TAG

Before tag creation, can be rejected. Wired by Hg.tag().

POST_TAG

After tag creation. Wired by Hg.tag().

CHANGEGROUP

After a changegroup is received. No wiring found in Hg.java.

4.8.5. Exceptions (package io.github.search5.hg4j.errors)

Class and parent When thrown (from the javadoc and code), and what the caller should do

HgException extends Exception

Checked base class for Mercurial domain and operational exceptions (a constructor takes a message and optionally a cause). Not thrown by itself. Catch it only to handle HgLockException and HgMergeConflictException together.

HgLockException extends HgException

A repository lock cannot be acquired, or lock contention occurs (also when releasing the lock fails). The message is Failed to acquire lock '<name>': …​; getLockName() gives the lock name (for example store.lock, wlock). Commands that wait use the repository’s push lock timeout; 0 fails at once. Caller action: retry later, or find and stop the other process. Do not delete lock files unless nothing else is running (ChainsawUpdateCommand breaks them on purpose).

HgAbandonedTransactionException extends HgLockException

An interrupted transaction (store/journal) is waiting: message abandoned transaction found, hint run 'hg recover' to clean up transaction, lock name lock. Thrown by HgRepository.lockStore(int) when a journal exists and the lock is not re-entrant. Nothing is recovered implicitly. Caller action: run RecoverCommand (hg.recover().call()), then retry. lockStoreWithoutRecovery does not raise it, which is why VerifyCommand, RecoverCommand and GcCommand use it.

HgMergeConflictException extends HgException

A 3-way merge left unresolved conflicts: MergeCommand, the cherry-pick path of RebaseCommand (also ShelveCommand unshelve), GraftCommand and BackoutCommand. getConflictPath() is the first conflicting file and getConflictPaths() all of them. Conflict markers are in the working files and the bookkeeping is in .hg/merge/state2. Caller action: resolve the files (for example with ResolveCommand), then continue (continueRebase(), continueGraft(), unshelveContinue()) or abort (abort(), unshelveAbort()); after a BackoutCommand conflict nothing is committed, so resolve and commit normally.

HgValidationException extends IOException

A precondition or integrity check on repository state or the working directory failed. This is the general "refused" signal of the commands, for example uncommitted changes, outstanding uncommitted merge, no rebase in progress, empty revision set, an unsupported option, or a hook that returned false. Caller action: read the message, fix the state (commit or revert changes, resolve the merge, correct the argument), and call again. Nothing has been changed when it is raised before the work starts.

HgPushRacedException extends HgValidationException

Server-side push/unbundle apply (local file:// peer and bundle2 push): the repository heads, or a bookmark or phase, changed between the client’s computation and the moment the store lock was taken, so the push lost a concurrent race. The message is remote repository changed while pushing - please try again (with details for bookmarks and phases). Nothing was applied. Caller action: catch it by type, pull the new changes, and retry the push.

HgCorruptDataException extends IOException

Data integrity failure: a revlog checksum mismatch, a corrupted delta restoration or index, or unreadable dirstate, sidedata, obsolescence or LFS pointer data. UnbundleCommand also raises it for an unknown bundle header or unsupported bundle1 compression. Caller action: do not retry blindly. Run VerifyCommand, restore from a backup or clone again; for an interrupted write, run RecoverCommand.

HgCensoredContentException extends IOException

Reading the content of a censored file revision through Revlog (mirrors error.CensoredNodeError) instead of silently returning the tombstone. getTombstone() returns the tombstone bytes (may be null). Caller action: treat the content as deliberately removed; use the tombstone text, or getRawRevisionContent on the revlog if the raw bytes are really wanted.

HgHookRejectedException extends IOException

A hook refused the operation. Raised by the local peer apply for a failing pretxnchangegroup hook (message pretxnchangegroup hook failed) and turned into a rejection reply by the server code. isRolledBack() is true when the hook ran after the changes were made and they were undone, false when it refused before anything changed. Caller action: the repository is back in its previous state when isRolledBack() is true; fix what the hook complained about and retry.

HgRepositoryNotFoundException extends IOException

A repository (or a required file such as a shelf or a filelog) cannot be found because of an invalid path or corruption; getPath() gives the path. Raised by Hg.open, InitCommand (a repository directory cannot be created), ShelveCommand for a missing shelf file and CensorCommand for a file with no filelog. Caller action: check the path and that .hg exists, or create the repository with Hg.init().

HgRevisionNotFoundException extends IOException

A revision is not found by node id or revision number (the message names the 40-hex node or the revision number). Raised by commands that resolve revisions (for example CensorCommand, SigCheckCommand, TreeMergeCommand, SignCommand). Caller action: check the identifier; the changeset may be in another repository, stripped, or not pulled yet.

HgTransportException extends IOException

Base of network and wire protocol errors in the HTTP/SSH transport layer; the message is Transport error for '<url>': …​ and getRemoteUrl() gives the URL. HgRemoteClient raises it itself for a malformed URL. Caller action: check the address and network; catch the base class to handle all transport failures.

HgAuthException extends HgTransportException

SSH or HTTP credential authentication failure: an HTTP 401 or 403 answer (the user name is anonymous when none was given), or an SSH authentication failure. getUsername() gives the user name that failed. Caller action: supply correct credentials (address, [auth] section, or setCredentialsProvider on PullCommand/FetchCommand) and retry.

HgProtocolException extends HgTransportException

Wire protocol error: capability negotiation fails, the server answers something the protocol does not allow, or a clone bundle download gets a non-200 response (ClonebundlesCommand). Caller action: check that the server supports the protocol version and capabilities in use (for example the SSH v2 switch), and that the URL points to a Mercurial server; retrying the same request will usually fail the same way.

Note: HgException and HgLockException are checked exceptions that do not extend IOException; most others extend IOException.

5. 4. Locking and Transactions

hg4j follows the order and the scope of the original localrepo.wlock() and localrepo.lock(). The rules are covered by tests that start two actors at once (LockScopeConcurrencyTest) and by tests against the real hg (RealHgLockContentionInteropTest).

  • A command that changes the working copy takes wlock first and, when it writes the store, lock after it. It holds them for the whole command, not only for the writes, and releases them in reverse order. The plumbing does not enforce this order; a caller that uses lockWorkingCopy() and lockStore() itself must follow it.

  • lockWorkingCopy() never recovers anything. lockStore() and lockStore(int) refuse with HgAbandonedTransactionException when store/journal exists and the thread did not already hold the lock; the lock is released again before the exception is thrown. Run RecoverCommand (hg recover). lockStoreWithoutRecovery(int) takes the store lock without that check, for recover and verify, which must look at the journal while they hold the lock. Only the explicit commands recover and rollback repair the store, and neither touches the dirstate.

  • A lock that another process (or thread) holds is waited for up to [ui] timeout (600 seconds by default), then HgLockException is thrown. ui.timeout = 0 fails at once. The system property hg4j.ui.timeout changes only the default; an explicit [ui] timeout always wins. lockWorkingCopy(int) and lockStore(int) take the wait in milliseconds. A lock is re-entrant for the thread that holds it.

  • Work that must run after the locks are released (post-commit hooks and similar) is registered with afterLock and runs once, after the last lock the thread holds on that repository is closed (or at once when it holds none). A failure in such an action is logged and does not fail the operation.

  • The lock files are the ones the original uses (.hg/wlock, .hg/store/lock), so hg4j and the real hg exclude each other. A server-shapes update uses a third file, .hg/store/store-shapes-lock (lockStoreShapes(int)), taken before the store lock.

  • A command that writes the store records what it is about to write in the original’s transaction journal (StoreRollback): store/journal holds <path relative to the store>\0<size> lines and store/journal.backupfiles the files that are rewritten rather than appended to (fncache, phaseroots, the docket of a version 2 revlog), so the real hg recover can roll back what an interrupted hg4j left and the other way round. The companion files of a version 2 docket are listed in journal.truncateonly (hg4j only), which cuts them back and never removes them. A rollback also removes the files that the transaction created, including the companion and nodemap files of a new version 2 revlog. commit, graft, strip, histedit, pull, unbundle and the apply of a push use it. On a push to a server the pretxnchangegroup hooks run inside the transaction, with the journal on disk; a hook that refuses rolls the whole apply back.

  • Which lock an operation needs: reading revlogs, manifests and the dirstate needs none; Revlog appends and truncate need the store lock; changing the dirstate and the merge state needs the working copy lock; the phase roots and the obsolescence markers live in the store (see Contracts by class).

5.1. 4.1 Dirstate contexts

Like dirstate.changing_files() and dirstate.changing_parents() of the original. They are used as repo.changingFiles(body) and repo.changingParents(body) or, when the body cannot be a lambda, as repo.openChangingFiles() and repo.openChangingParents(), which return a DirstateChange to close.

  • Both need the working copy lock and are mutually exclusive: opening one kind while the other is open throws IllegalStateException. They can be nested (the kind must be the same) and are per thread.

  • The dirstate is written once, when the outermost context ends normally, and only if writeDirstate was called inside it. getDirstate() returns the same instance for the whole context.

  • Any exception inside changingFiles or changingParents invalidates the whole context and nothing is written; the next read goes back to the disk. With openChanging…​() you must call DirstateChange.failed() before close() when the work failed; a plain close() writes the dirstate, even from a try-with-resources block that is left because of an exception.

  • The dirstate is not journaled: a command that changes it in memory writes it once at the end. A command that opens a store transaction (for example commit) writes it after the transaction is closed, as the original does with a post-finalize file generator, and writes nothing when the command fails.

  • The commands that change tracked files use changing_files: add, forget, remove, copy/rename, revert. The commands that change the parents use changing_parents: commit, update, merge, backout, graft, histedit, rebase, strip, bisect, pull, clone, unshelve.

  • Code that changes the dirstate directly must hold the working copy lock; opening a context without it throws IllegalStateException ("trying to change the dirstate without holding the wlock"). Calling Dirstate.write yourself, outside a context, takes no lock and checks nothing.

5.2. 4.2 Dirstate storage

dirstate-v2 is stored as in Mercurial: a docket file (dirstate) naming a data file (dirstate.<uid>). Dirstate.write appends new entries to the data file and replaces the docket last (atomically), so a reader sees either the old state or the new one. When the file on disk is no longer the one that was read, or at least half of the data file is unreachable, a new data file is written under a new uid, the docket is replaced and the old data file is removed. A v1 dirstate is replaced atomically as a whole. HgRepository.writeDirstate chooses the format from the repository’s dirstate-v2 requirement on every write.

6. 5. Repository Formats

Every requirement name below was checked with a search of the code (the names that HgRepository, InitCommand, Hg.open and NarrowCloneCommand read or write).

  • Store: store, fncache, dotencode, generaldelta, revlogv1, share-safe, shared repositories (shared, relshared, sharedpath), fileindex-v1. sparserevlog is accepted by Hg.open and by clone bundle selection, but InitCommand does not write it and no hg4j code acts on it.

  • Revlog: revlog-v1, exp-revlogv2.2 (docket), exp-changelog-v2 with exp-copies-sidedata-changeset (the changed files of a changeset are kept in sidedata), persistent-nodemap, revlog-compression-zstd.

  • Working copy: dirstate-v1 and dirstate-v2.

  • Other: treemanifest; narrow clones, which write the requirement narrowhg-experimental and the files narrowspec and narrowspec.dirstate; shapes and shards, which are not a requirement but the wire capability exp-shape-1; lfs, which hg4j only reads (getRequirements().contains("lfs")) and never writes.

  • Changegroups 01 to 05 (05 carries sidedata), bundle2 (HG20) with GZ, BZ and ZS compression, stream clone, clone bundles.

Not implemented: internal-phase (so strip --soft is refused, see the deliberate differences) and dirstate-tracked-hint-v1 (it is only tolerated in the clone bundle requirement lists).

Hg.open(File) checks every line of .hg/requires and .hg/store/requires against an allowlist and throws HgValidationException ("unsupported repository requirement") for any other name. The list is: dotencode, fncache, generaldelta, revlogv1, store, dirstate-v2, share-safe, sparserevlog, revlog-compression-zstd, exp-changelog-v2, exp-revlogv2.2, persistent-nodemap, fileindex-v1, treemanifest, exp-copies-sidedata-changeset, narrowhg-experimental, lfs, shared, relshared. Repository.open and new HgRepository(File) do not apply this check.

InitCommand creates the conservative set (revlogv1, store, fncache, dotencode, generaldelta). Newer formats are switched on through setters, as in hg they are switched on through configuration. Mercurial 7.2 made dirstate-v2 and the file index stable but recommends them only together with the Rust extensions; hg4j has no such restriction.

7. 6. Interoperability and Testing

  • ./gradlew test runs the unit tests. ./gradlew interopTest runs the tests tagged interop, which need a real hg (on PATH, and the Rust builds under ~/.cache/hg4j/ for the dirstate-v2 and shape tests). The interop run takes about an hour and a half.

  • The requirement matrix runs a command across 36 combinations of repository formats, once with hg4j and once with the real hg, and compares the results. The wire matrix does the same for HTTP and SSH (hg4j or real client against hg4j or real server).

  • Lock contention tests run hg4j and the real hg on one repository at the same moment. Every scenario runs twice: with the locks (nothing may be damaged), and with hg4j’s locks switched off by a test hook while the real hg keeps its own (the damage must show). A scenario that passes without the locks does not test them.

  • The build gates coverage: 70% for the whole bundle and 90% per class for the core classes (jacocoTestCoverageVerification). Unit and interop executions are merged for the report. -PignoreTestFailures lets a full run reach the coverage report although a test failed.

8. 7. Deliberate Differences from Mercurial

  • shelve: like the original, the shelving step has no context spanning the whole command: the temporary commit opens its own, and the return to the parent of the working copy runs in changing_parents (the original does it with update). unshelve uses changing_parents. Wrapping the whole shelving step in one context would leave the parent of the temporary commit behind and break unshelve.

  • status: the stat fix-ups (files found clean whose recorded stat is out of date) are written under wlock(wait=False) without a changing_* context, as poststatusfixup does: the original runs status in a running_status context, which is not exclusive with changing* and needs no lock, and then tries the lock without waiting. hg4j has no running_status object; its steps are the same: the fix-ups are applied only to entries that still hold what the status saw (the original drops them when the dirstate changed on disk while the lock was taken), they are written when the lock is free, and they are dropped when it is not (LockError). Other failures are not swallowed.

  • sign --force works. In the original it ends with an UnboundLocalError.

  • strip --soft is refused with a clear message. In a default repository the original fails with an exception, because the archived phase needs the internal-phase requirement.

  • upgrade (debugupgraderepo) is not provided. It is planned for the next major version, together with a command line front end.

  • store_shape with an empty shard name gets no answer, as with the original (which fails).

  • Behaviour that follows the original and that a caller may notice: .orig files are left after rebase --abort, unshelve --abort and a conflicting backout; rebase without evolution strips the originals; reusing a branch name that exists on another line of history needs -f; phase refuses to move changesets to a higher phase with exit status 1 and the text cannot move N changesets to a higher phase, use --force; sign commits .hgsigs only.

9. API Changes for Callers

These changes need an action from code written against the earlier API. HgLockException is a checked exception (HgException extends Exception), so a caller of a changed method has to catch or declare it.

Element Change What to do

BisectCommand.next(), BookmarkCommand.call(), BranchCommand.call(), CensorCommand.call(), GcCommand.call(), RecoverCommand.call(), ResolveCommand.call(), RollbackCommand.call(), VerifyCommand.call(), Hg.rollback()

Now declare throws HgLockException (they take the locks themselves).

Catch or declare HgLockException. HgAbandonedTransactionException is a subclass: it means a journal of an interrupted transaction was found.

HgRepository.lockStore(int)

Never recovers an interrupted transaction any more; it throws HgAbandonedTransactionException when a journal is left by another holder.

Run RecoverCommand, then lock again. lockStoreWithoutRecovery(int) is the variant that recover and verify use to look at the journal while holding the lock.

HgRepository.getDirstate() and a direct Dirstate change

Changing the dirstate needs the working copy lock; the write is made when the dirstate context ends.

Use changingFiles(…​) or changingParents(…​) (or openChangingFiles() / openChangingParents() with try-with-resources) while holding lockWorkingCopy(). Without the lock an IllegalStateException is thrown.

HgRepository.DirstateBody<T>

New functional interface; its run() may throw IOException and HgLockException.

Pass it to changingFiles / changingParents.

HgRepository.afterLock(AfterLockAction)

New: work that runs after the outermost lock is released.

Use it for follow-ups that must not run under the locks.

dirstate.backup, dirstate journal entry

Removed. A journal that still carries the entry is read without error.

Tools that read the backup file have to stop doing so.

RebaseCommand

Now follows rebase.py: call() runs the rebase from revset setters (addSourceRevset, addBaseRevset, addRevisionRevset, setDestination) as well as from setSource(byte[]) and setTarget(byte[]); originals are stripped unless setKeep(true); .hg/rebasestate is the state file.

Replace code that expected the originals to stay readable.

PhaseCommand.call()

Refuses a move to a higher phase through the exit status (getExitCode() is 1) and getMessages(), not through an exception.

Check getExitCode().

SignCommand

Commits .hgsigs only and does not restore it when the commit fails.

Commit other changes yourself.

BranchCommand

setForce(boolean) is needed to reuse a branch name that exists on another line of history.

Pass true where the original needs -f.

New commands and options that need no migration: AdminVerifyCommand, ChainsawUpdateCommand, GraftInMemory (graft --to), NarrowServerAdmin, ShardedStreamBundlesCommand, UnshareCommand; setSubrepos on AddCommand and AddremoveCommand; setPull, setStream and getMessages() on CloneCommand, PullCommand and FetchCommand; the pattern, include, exclude and cwd setters of the file commands.

10. 8. Known Issues and Remaining Work

10.1. 8.1 Limits

  • Mercurial versions: tested against 7.2 and 7.2.4 only. A repository created with the default settings uses old requirements and is expected to open with older 7.x releases, but this was not tested. Newer formats need the Mercurial release that introduced them.

  • Sidedata of applied changegroups: a changegroup without sidedata (versions 01 to 04) brought into a repository that keeps changed-file sidedata gets the changed files computed from the manifests. Copy information cannot be derived that way and is not recorded. A changegroup 05 keeps its own sidedata, copies included.

  • Not implemented: wire protocol version 2 over HTTP, largefiles, dirstate-tracked-hint, and upgrade.

10.2. 8.2 Open points

  • One real-client/real-server case of TransportE2EMatrixInteropTest ("a push that creates a head is refused") failed in two of four full runs and passed every time it was run alone. Both ends are the real hg, so hg4j code is not involved as far as is known. The cause has not been found.

10.3. 8.3 Important defects found and fixed

  • Rebasing in a repository with changelog-v2 and sidedata produced changesets without changed-file sidedata, which hg verify reported as an integrity error. The re-applied changesets now get it.

  • Recomputing the sidedata of a bundle that already carried it (changegroup 05) dropped the copy information. The computation now runs only for changesets that arrived without sidedata.

  • strip in a repository with LFS revisions lost the LFS flag of the kept changesets (the temporary bundle was changegroup 01) and failed with a hash mismatch. LFS repositories use changegroup 03 for it.

  • unshelve left the rebased restore commit in the store, and unshelve --abort did not remove .hg/rebasestate or the merge state.

  • Locks that covered only the writes allowed a rejected push to undo a push that arrived at the same time, and allowed two tag commands to lose one of the tags. The locks now cover the whole command.

  • The dirstate was written in the middle of a command and put back from a backup file when the command failed. It is now written once, after the transaction, and not at all on failure.

  • The class-by-class list, with the cause and the fix of each defect, is kept in llm-wiki/known-bugs-registry.md. The state of the locking work is in llm-wiki/lock-parity-matrix.md.

11. 9. Building and Running Documentation

./gradlew asciidoctor     # this guide: build/docs/asciidoc/{en,ko}/index.html
./gradlew javadoc         # API reference (en_US): build/docs/javadoc/index.html
./gradlew javadocKo       # API reference (ko_KR): build/docs/javadoc-ko/index.html

The history of changes is in CHANGELOG.md.