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. -
TreeWalkandChangesetGraph: traversal of manifests and working copies (packagetreewalk) and of the revision graph (packagerevwalk). There is no class namedRevWalk; the revision graph is walked withChangesetGraph,RevFilterandSortOrder. -
matchandfilesetpackages: 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.
RepositoryandHgRepository(packagelib)-
-
Repository.open(File)returns anHgRepositoryand throwsHgRepositoryNotFoundExceptionwhen there is no.hgdirectory.new HgRepository(File)readsrequiresand ignores read errors, leaving the defaults. -
Thread safety: the class Javadoc calls it thread-safe for parallel reads; most methods are
synchronized. The lock methodslockWorkingCopyandlockStoredeliberately 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 holdwlock. -
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, callclearRevlogCache();refreshIfChangedOnDisk()does this for long-lived handles when00changelog.ichanged and the cached changelog has not written locally. -
getPhaseRoots()returns a newPhaseRootsthat has read.hg/store/phaserootsat that moment. -
getRequirements()returns the union of.hg/requiresand.hg/store/requires. -
Shared repositories (
hg share):getStoreDir()follows.hg/sharedpath, which is absolute or, with therelsharedrequirement, relative to.hg(rcutil.get_shared_vfs).getSharedHgDir()returns the.hgdirectory that holds the store, ornullwhen the repository is not shared. A share-safe working copy reads the.hg/hgrcof that directory before its own. -
Shared bookmarks:
isBookmarksShared()is true when.hg/sharedlistsbookmarks(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 callsmirrorSharedBookmarks()afterwards, so that the working copy’s own.hg/bookmarkshas the same content, ashgext/share.pywrites both (the own file is what remains afterunshare).
-
HgLock(packagelib)-
-
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 secondclose()of the same instance does nothing. -
Taking a lock again on the thread that already holds it succeeds (
isReentrant()is thentrue) 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. -
afterLockactions ofHgRepositoryrun 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>:pidon Linux (lock._getlockprefix),host:pidwhere 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 formhost:pidthat 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(packagelib)-
-
An immutable 20-byte node id. The constructor and
getBytes()copy the array;NodeId.NULLis 20 zero bytes;fromHexneeds exactly 40 hex digits.toString()is the first 12 hex digits only; usetoHex()for the full id.
-
ProgressMonitor(packagelib)-
-
start(title, totalWork)(UNKNOWN= -1), thenupdate(completed)with the work done since the previous call (not a running total), thenend(). Long operations pollisCancelled()and stop early.message(String)is ignored unless overridden.
-
Dirstate(packagedirstate)-
-
Lock: reading and writing take none; hold
wlock(insidechangingFilesorchangingParents,HgRepositorycallswriteonce at the end). -
addEntry,removeEntry,addCopy,setParents,setV2and every change throughgetEntries()orgetCopyMap()(both return the live maps) are in memory only untilwrite(File). -
read(File)maps a v2 data file read-only and uses it in place; a lookup throughgetEntries()can throwUncheckedIOExceptionwhen 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.serializeproduces only the data file (no docket, no copy records);Dirstate.writeis the way to get a complete v2 dirstate.DirstateV2Nodeis the fixed 44-byte node layout over aByteBuffer;LazyEntryMapis package private, reached only throughgetEntries(). -
Dirstate.Entryis an immutable record;timemust be 0 to0xFFFFFFFF(AMBIGUOUS_TIMEmarks an untrusted mtime) and a negativesizemeans "compare the content" (isStatAmbiguous()). -
No thread safety is stated for
Dirstate; the changing contexts ofHgRepositoryare per thread.
-
RevlogandRevlogIndex(packagestorage)-
-
Thread safety: the public methods are
synchronizedper 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 throwsHgRevisionNotFoundException; a censored revision throwsHgCensoredContentExceptionfromgetRevisionContent. -
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. -
appendRevisionwrites 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 againstparent1when 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). -
appendRawRevisionandappendOptimizedRevisionkeep 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 aRevlogloaded 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 anIndexRecordis a 32-byte field whose first 20 bytes are the node id.
-
TreeWalk,TreeIterator,ManifestWalk,WorkingDirWalk(packagetreewalk)-
-
None of them is thread-safe and none takes a lock. All of them hand out paths in ascending UTF-8 order.
-
TreeWalkvisits the union of its trees once per path;addTreeresets the tree at once and the index of a tree is the order of adding.getNodeId(i)isnullfor a tree without node ids (the working copy);isSymlink(i)istrueonly for aManifestTreeIterator. -
ManifestWalkandWorkingDirWalkread nothing until the first traversal. The firstnext()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,-1ornullrevision gives an empty walk. -
WorkingDirTreeIteratorreports files on disk plus every path of the dirstate; paths unknown to the dirstate have state?.
-
ChangesetGraph,RevFilter,SortOrder(packagerevwalk)-
-
A
ChangesetGraphreads 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. WithSortOrder.DEFAULTit is breadth first and lazy; withSortOrder.TOPOthe whole ancestry is computed first and every revision comes before its parents. A revision is-1for "no parent".getAllAncestors,isAncestorandgetLcaCandidatesignore the filter; a revision is its own ancestor. -
MaxCountRevFilteris stateful: use a new instance (orreset()) for each traversal.
-
Merge3andMergeState(packagemerge)-
-
Merge3.merge(base, yours, theirs)is a pure function on lists of lines; a conflicting block gets conflict markers andisConflicted()istrue. -
MergeStatereads and writes.hg/merge/state2in the format the realhg resolveuses.readtakes no lock and gives an inactive state for a missing file.writeoverwrites in place without a temporary file; holdwlockwhile a merge state changes. Changes byaddMergedFile,markResolvedandmarkUnresolvedare in memory untilwrite.
-
PhaseRoots(packagephase)-
-
new PhaseRoots(File)reads the file once.setPhasechanges 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;getPhasecomputes 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(packageobsolete)-
-
ObsStore.readunderstands both obsstore versions (0 and 1);HgObsolescenceParser.parseunderstands version 1 only.HgObsMarkeris an immutable marker with defensive copies. -
ObsUtil.successorsSetsportsobsutil.successorssets(the latest successors of a changeset: a replacement, a split, a divergence, a pruned changeset);UpdateCommanduses it for the destination of a bare update. -
ObsStore.pushMarkertakes the store lock itself.HgObsMarker.writeMarker(storeDir, …)appends a version 1 marker toobsstoreand 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 |
|
History |
|
Rewriting |
|
Names |
|
Exchange |
|
Maintenance |
|
Signing and extensions |
|
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 |
|---|---|
|
Directory in which the repository is created ( |
|
Adds the |
|
Adds the |
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|---|---|
|
Queues one exact repository-relative path of an existing file or symlink (backslashes become |
|
|
|
|
|
|
|
Current directory relative to the repository root, used to read relative patterns. |
|
|
|
Messages about subrepositories (for example |
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 |
|---|---|
|
|
|
What the last call said besides the changed files (for example |
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 |
|---|---|
|
Single path used by |
|
Remove files with uncommitted changes (added or modified) anyway, like |
|
Patterns for |
|
|
|
|
|
Current directory relative to the repository root, against which relative patterns are read. |
|
|
|
What the last |
Execution:
-
boolean call() throws IOException, HgLockException: removes the single file and returnstruewhen it was removed. ThrowsIllegalStateExceptionwithout a file,HgValidationExceptionif 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. ThrowsHgValidationException("no files specified")without patterns. Files that cannot be removed safely (marked for add, modified) are left and reported ingetWarnings()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 |
|---|---|
|
Single path used by |
|
Patterns for |
|
|
|
|
|
Current directory relative to the repository root. |
|
What the last |
Execution:
-
void call() throws IOException, HgLockException: forgets one file (setFileis 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. ThrowsIllegalStateExceptionwithout a file,HgValidationException("File is not tracked: …"). -
List<String> callSelected() throws IOException, HgLockException: forgets the selected files and returns them. ThrowsHgValidationException("no files specified")without patterns. A file in stateabecomes unknown; a committed one is markedr.
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 |
|---|---|
|
Repository-relative path of the tracked source for |
|
Repository-relative destination path for |
|
Overwrite an existing destination ( |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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. ThrowsIllegalStateExceptionwithout source and destination,HgRepositoryNotFoundExceptionif the source does not exist on disk,HgValidationExceptionif the destination exists without force or the source is not tracked (or is stater). The constructor throwsIllegalArgumentExceptionfor anullrepository. -
PatternResult callPatterns() throws IOException, HgLockException: returnsrecord 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;warningsandstatusare the lines real hg prints, andfailed()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 |
|---|---|
|
Repository-relative path of an existing file or symlink (a dangling symlink is allowed) for |
|
Repository-relative target path for |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Current directory relative to the repository root. |
Execution:
-
void call() throws IOException, HgLockException: single rename. ThrowsIllegalStateExceptionwithout source and target,HgRepositoryNotFoundExceptionif the source does not exist. Moves the file (replacing an existing target and creating parent directories), marks the sourcer, the targeta, 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… DESTwith all of the options. Returns the samePatternResultrecord asCopyCommand(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 |
|---|---|
|
Single path for |
|
Revision to revert to ( |
|
Patterns for |
|
|
|
|
|
Current directory relative to the repository root, against which relative patterns are read. |
|
|
|
What the last |
|
Subrepository messages ( |
Execution:
-
boolean call() throws IOException, HgLockException: reverts one file to its state in the target revision and returnstruewhen it was reverted. ThrowsIllegalStateExceptionwithout a file;HgValidationExceptionwhen 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()andgetSubrepoMessages()are reset at the start of each call. ThrowsHgValidationExceptionwhen no files, patterns orsetAllare given (with a hint), with an uncommitted merge and no revision, or when a matching subrepository does not exist in the target revision;HgRevisionNotFoundExceptionwhen 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 |
|---|---|
|
|
|
|
|
Remove untracked directories that end up empty. Default true; false leaves them (restricting the purge like |
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 |
|---|---|
|
Restricts the paths examined (narrow support); |
|
Files to report (patterns, |
|
|
|
|
|
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 |
|---|---|
|
Old revision number ( |
|
Old revision by node. |
|
New revision number. Default is tip; -1 compares against an empty manifest. |
|
New revision by node. |
|
Restricts the diff to paths the filter accepts, in addition to any pattern selection. |
|
Files to diff ( |
|
|
|
|
|
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 |
|---|---|
|
Repository-relative path of a file in the current merge state to mark. |
|
Mark the file resolved ( |
|
Mark the file unresolved ( |
|
Return the state of every file of the merge state ( |
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 |
|---|---|
|
Target revision: |
|
Update even with uncommitted changes, like |
|
Restricts which paths are checked out (narrow support); |
|
Hook run before the update (context keys |
|
Hook run after the update (context keys |
|
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 |
|---|---|
|
Target by 20-byte node id. Takes precedence over |
|
Target by node id. Takes precedence over |
|
Target by changelog revision number. Used only when no node id was set. Default -1 (not set). |
|
Hook run before the merge touches the working copy, with the working copy lock held (context keys |
|
Hook run after the merge, while the dirstate is still being updated (context keys |
|
What |
Execution:
-
MergeResult call() throws IOException, HgLockException.MergeResulthasisConflicted()(true when files have unresolved conflicts; their contents then contain conflict markers) andgetConflicts()(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. ThrowsHgValidationException("Merge rejected by PRE_MERGE hook"),IllegalStateExceptionin an empty repository,IllegalArgumentExceptionif neither a node id nor a valid revision number was set,HgRevisionNotFoundExceptionif the target or the current parent is not in the changelog or no common ancestor exists. -
void abort() throws IOException, HgLockException. ThrowsHgValidationException("no merge in progress")when the dirstate has no second parent,IllegalStateExceptionwhen the repository has no first parent, andHgRevisionNotFoundExceptionwhen 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 |
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 |
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 |
|---|---|
|
Directory of the new working copy. Must not exist or be empty. Required before |
|
|
|
|
|
|
|
The revision checked out first (the branch of |
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 |
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 |
|---|---|
|
Commit message ( |
|
Author ( |
|
|
|
|
|
|
|
|
|
Current directory relative to the repository root, for relative patterns. |
|
Adds an extra field to the new changeset ( |
|
|
|
|
|
Registers a hook that runs inside the commit, before anything is written. It receives a map with the keys |
|
Registers a hook that runs after a successful commit, once the repository locks are released. It receives a map with the keys |
|
When true, |
- 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, thenrepository.lockStore(), then opensrepository.openChangingParents()(the dirstate change context, the equivalent ofdirstate.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, andopenChangingParents()is opened only if the working copy lock is held (holdsWorkingCopyLock()); otherwise no dirstate context is opened. -
openChangingFilesandchangingFilesare not called.ChangingFilesis 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 |
|---|---|
|
|
|
|
|
|
- Execution
-
byte[] call() throws IOException, HgLockException. Returns the node id of the new amended commit. ThrowsIllegalStateExceptionfor an empty repository ("No commits exist to amend"). The constructor throwsIllegalArgumentExceptionfor anullrepository. - Locks and dirstate
-
-
lockWorkingCopy(timeout)thenlockStore(timeout), where the timeout isrepository.resolvePushLockTimeoutMs(). Both are released when the command ends. -
It then runs a
CommitCommandinside these locks. ThatCommitCommandis not told to skip locking in the source ofAmendCommand; whether the nested lock calls are reentrant is not confirmed in the source read. -
openChangingFiles,openChangingParents,changingFiles,changingParentsare not called directly byAmendCommand. The dirstate context comes from the nestedCommitCommand(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 |
|---|---|
|
|
|
|
|
|
|
Current directory relative to the repository root, for relative patterns. |
|
Keeps only commits that have at least one changed file accepted by the filter. Default |
|
Restricts the log to the start revision and its ancestors. Only effective when a start revision is set with |
|
Revision from which ancestors are followed, resolved against the changelog when |
|
|
- 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; nevernull. Returns an empty list if the repository has no changelog (00changelog.idoes 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 callsrepository.refreshIfChangedOnDisk()first, to avoid serving a stale cached changelog-v2 revlog. - Differences from hg
-
The javadoc says
setFollowPathcrosses renames through thecopy/copyrevmetadata in the filelog’s revision 0, the way hg does by default, not through the changelogSD_FILESsidedata.
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, ornullif 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 |
|---|---|
|
|
|
|
|
|
- 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 withsetTopo(true), topological leaves. Otherwise (default) every branch’s own open heads, as plainhg 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 plainhg 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 |
|---|---|
|
|
- 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 gives000000000000. -
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-tagtipsorts where its name falls (mytag/tip, buttip/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
StatusCommandto compute the dirty marker. Tags come fromTagsCommand, bookmarks fromBookmarkCommand. - Differences from hg
-
Javadoc says the output was verified against hg 7.2.2. With
-rthe branch is that revision’s own branch, not the working directory’s. An unresolvable revision is treated as the null node and shows000000000000(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. Returnsempty-repositoryfor a repository without commits, the tag name when the current revision is tagged,tag-distance-g<12 hex>otherwise, andv0.0-<distance>-g<12 hex>when no ancestor tag is found. Tags are read from.hgtagsin 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 |
|---|---|
|
Repository-relative path of the file to annotate, with |
|
Filelog revision number, a revision of the file’s own revlog (not a changelog revision). Default -1 means the file’s latest revision. |
|
|
|
|
|
|
|
Current directory relative to the repository root, for relative patterns. |
- Execution
-
-
List<BlameLine> call() throws IOException. EachBlameLinehasgetLineNumber()(1-based),getRevision()(changelog revision that introduced the line),getAuthor()(unknownwhen it could not be read),getContent(). Returns an empty list if the revision is out of range. ThrowsHgRevisionNotFoundExceptionif 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 (changesetnullmeans tip). Needs at least one pattern, as the command line does, elseHgValidationException("invalid arguments"); a named file missing from the revision givesHgValidationException; an unresolvable revision givesHgRevisionNotFoundException. Result is in path order.
-
- Locks and dirstate
-
No locks, no changing_files/changing_parents.
- Differences from hg
-
The constructor throws
IllegalArgumentExceptionfor anullrepository. Follows rename and copy boundaries by default, as hg does (hg has no separate--followflag for annotate), through thecopy/copyrevmetadata 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 |
|---|---|
|
Regular expression (Java |
|
|
|
|
|
|
|
|
|
Current directory relative to the repository root, for relative patterns. |
|
|
- Execution
-
List<GrepResult> call() throws IOException.GrepResulthas public fieldspath(repository-relative, forward slashes),hexNode(hex node id of the file revision, empty string insetRevisionsmode),lineNumber(1-based),lineContent(without the line terminator),linkRevision(the changeset that introduced the file revision; insetRevisionsmode the revision searched; -1 if unknown). An invalid regex throws the standardPatternSyntaxException. - Locks and dirstate
-
No locks, no changing_files/changing_parents.
- Differences from hg
-
Without
setRevisionsit scans every revision of every tracked filelog (enumerated fromfncache, or by walkingstore/datawhenfncacheis absent, for example with fileindex-v1 or general-v2 repositories). LFS content is read throughHgLfsFactory.
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 |
|---|---|
|
Repository-relative path of the tracked file, with |
|
|
|
Same, with a node id; |
|
|
|
|
|
|
|
Current directory relative to the repository root, for relative patterns. |
- Execution
-
-
byte[] call() throws IOException: content of the file.IllegalStateExceptionif no file is set;HgRevisionNotFoundExceptionif the revision cannot be resolved or the file is not tracked at that revision (also if the file version is not in the filelog);HgCorruptDataExceptionif 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 throwsHgValidationException("invalid arguments").
-
- Locks and dirstate
-
No locks, no changing_files/changing_parents.
call()starts withrepository.clearRevlogCache(). - Differences from hg
-
Content is read through
HgLfsFactory, so LFS files return the real bytes. With no revision set (ornull/empty), the tip is used.call()andcallAll()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 |
|---|---|
|
Revision to list (number, hex id or prefix, |
|
Revision by node id; |
|
Explicit tree filter used to match paths, for example one built with |
|
Glob patterns with directory-prefix semantics (through |
|
|
|
|
|
|
|
|
|
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 withNodeIdUtil.UTF8_STRING_COMPARATOR.HgRevisionNotFoundExceptionif 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 filesdoes.
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 |
|---|---|
|
Single |
|
|
|
|
|
|
|
Current directory relative to the repository root, for relative patterns. |
|
|
- Execution
-
List<String> call() throws IOException. Repository-relative paths, sorted by UTF-8 byte order (NodeIdUtil.UTF8_STRING_COMPARATOR); nevernull. With no pattern, every candidate path is returned.HgRevisionNotFoundExceptionif 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 stater(removed but not committed), as hg’slocatedoes.[…]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 |
|---|---|
|
Revision in any form |
|
Advisory flag recording that |
- Execution
-
List<ManifestEntry> call() throws IOException. EachManifestEntryhasgetPath(),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;
--debugrendering 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 |
|---|---|
|
0-based changelog revision number. Default -1 means the tip. |
|
Revision by 20-byte node id. Takes precedence over |
|
Same, with a |
- Execution
-
List<TreeEntry> call() throws IOException. EachTreeEntryhasgetPath(),getNodeId()(40-character hex node id of the file revision in the manifest),getNode()(the same as aNodeId, ornullif there is none),getMode()(0644normal,0755executable,0120000symlink). 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 |
|---|---|
|
Revset expression, for example |
- Execution
-
List<String> call() throws IOException. Node ids in hex.all()/allandtipare handled directly; forparents(X)the symbolic X is first resolved to a node; anything else goes toHgRevsetEngine.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 asdraft(),author(tester),parents(rev)and AND/OR combinations (for exampledraft() and author(tester)); a null or blank query gives an empty result.tag(name)reads the tags the wayhg tagsdoes, from the.hgtagsof the heads and not from the working copy, so it also works in a repository without working files;tipis not matched, the name is exact and case-sensitive,re:andliteral: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 |
|---|---|
|
20-byte binary node id of the revision known to be good (not yet showing the regression). Required before |
|
20-byte binary node id of the revision known to be bad (showing the regression). Required before |
- 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. ThrowsIllegalStateExceptionif 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), withtimeout = 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 withrepository.changingParents(() → …)(parent 1 = candidate, parent 2 = null), followed byrepository.setBranch(…)andclearRevlogCache(). -
changingFilesandopenChangingFilesare 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. Onlynext()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 |
|---|---|
|
Changelog revision number to inspect (0-based, as reported by |
- Execution
-
ChangingFiles call() throws IOException. Decodes theSD_FILESsidedata of the revision, giving the files it changed (added, removed, merged, salvaged, copied, touched, with copy information), without walking any ancestor history.IllegalStateExceptionif the revision was not set to a non-negative number.IllegalArgumentExceptionif the revision does not exist. ReturnsChangingFiles.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
CopyCommandand uses neither the dirstate nor changing_files/changing_parents. Callsrepository.refreshIfChangedOnDisk()first. - Differences from hg
-
Works only on repositories whose changelog was written with copies-sidedata support (changelog-v2 and the
exp-copies-sidedata-changesetrequirement). 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).
| Method | Meaning |
|---|---|
|
Node-style source and target (20-byte node ids; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Commit message editor. An empty result aborts with |
|
|
|
|
|
|
|
|
|
|
|
Register hooks; |
|
What the command printed ( |
| Method | Returns / throws |
|---|---|
|
|
|
|
|
|
|
|
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().
-
call(),continueRebase(),stop(),abort():lockWorkingCopy()thenlockStore(), 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,changingFilesare not used in this class (source not confirmed beyond this).
-
Like the original without evolution: the originals are stripped unless
setKeep(true); no obsolescence marker is written. -
stop()requires--keepbecause 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.
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.
| Method | Meaning |
|---|---|
|
Revision to graft (the |
|
Register a hook that runs after the grafted changeset has been committed; |
| Method | Returns / throws |
|---|---|
|
|
|
|
|
|
On conflict, call continueGraft() after resolving and staging the files, or abort().
-
call():lockWorkingCopy()andopenChangingParents()for the working copy update (the context ends and writes the dirstate before the commit step). The commit step (commitGraftedRevision) takeslockStore(). It delegates toCommitCommandwithsetSkipLockAndJournal(true)and writes its own journal/backup for crash safety. -
continueGraft(),abort():lockWorkingCopy()only (in the code shown); the commit incontinueGraft()goes through the same store-lock step. -
changingFilesis not used.
-
Pause/continue/abort protocol is hg4j-private; interop with real
hg graft --continuebookkeeping is not a goal. -
No obsmarker is written, as in real hg 7.2.
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.
| Method | Meaning |
|---|---|
|
Revision to back out ( |
|
Commit message of the backout changeset ( |
|
Author of the backout changeset ( |
| Method | Returns / throws |
|---|---|
|
|
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.
-
call():lockWorkingCopy(),lockStore(), thenopenChangingParents(), in this order. The working copy update ends (and writes the dirstate) before the commit, which opens its own context. -
changingFilesis not used.
-
--parent(backing out a merge) and--mergeare not exposed. -
Dirstate parent stays single after a conflict (not a two-parent merge state).
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: likeFOLD, 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.
| Method | Meaning |
|---|---|
|
Append a rule ( |
| Method | Returns / throws |
|---|---|
|
|
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.
-
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. -
changingFilesis not used.
-
Unlike
RebaseCommand, histedit never strips: dropped and replaced changesets are hidden by obsolescence markers (pruneforDROP,histeditfor the rewritten ones), matching real hg underexperimental.evolution. -
Rules take full hex node ids only; there is no interactive editor or
--continueprotocol.
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.
| Method | Meaning |
|---|---|
|
Shelf name to create or restore (default |
|
Run unshelve (restore the shelf, like |
|
|
|
Shelves removed by |
|
|
| Method | Returns / throws |
|---|---|
|
|
|
|
|
|
On an unshelve conflict, resolve the files and call unshelveContinue(), or unshelveAbort().
-
Delete/cleanup:
lockWorkingCopy()only. -
Shelve:
lockWorkingCopy(), thenlockStore()(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 inchangingParents(…). -
Unshelve (
performUnshelve):lockWorkingCopy(),lockStore(),openChangingParents(). -
unshelveContinue(),unshelveAbort():lockWorkingCopy()thenlockStore()(nested). -
changingFilesis not used; the dirstate is written withwriteDirstate.
-
Unshelve strips the throwaway commits outright instead of leaving obsolete revisions, matching hg’s aborted transaction.
-
hg4j adds a per-shelf
.statefile and a private unshelve state file (.hg/rebasestate-hg4jdriven rebase).
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/.
| Method | Meaning |
|---|---|
|
Revision to strip; it and all its descendants are removed. A revision identifier or revset. |
|
Another revision to strip ( |
|
|
|
|
|
The word at the end of the backup bundle’s name ( |
|
|
|
|
|
|
|
An empty revision set is a success instead of an abort. |
|
Printed messages ( |
| Method | Returns / throws |
|---|---|
|
|
-
call():lockWorkingCopy(), then insidestripRevisionslockWorkingCopy()again pluslockStore()(as hgstrip():with repo.wlock(), repo.lock()). Only bookmark deletion with nothing to strip takeslockStore()alone under the working copy lock. -
Dirstate:
repository.changingParents(…)when a working copy parent is stripped (with--keep, only the dirstate parents are reset).changingFilesis not used.
-
--softis unsupported. -
The strip cut is at the lowest requested revision; later non-stripped revisions are bundled and re-added (as
repair.strip).
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.
| Method | Meaning |
|---|---|
|
Revision to query or move, resolved against the changelog as hg’s revision argument. Must be set before |
|
Target phase: 0 public, 1 draft, 2 secret. The default |
|
|
|
Verbose notes, other printed messages, and |
| Method | Returns / throws |
|---|---|
|
|
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.
-
Query: no lock. Change:
lockStore()only, with the repository’s push lock timeout, while.hg/store/phaserootsis rewritten. No working copy lock, no dirstate context.
Line order and minimal-roots format match hg; the older per-node format was replaced.
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.
| Method | Meaning |
|---|---|
|
Repository-relative path of the tracked file (required, else |
|
Full 40-digit hex node id of the file revision in the file’s filelog (not a changeset revision). Required, else |
|
Free-text reason stored in the tombstone (default empty, as in real hg). The tombstone is the |
|
|
| Method | Returns / throws |
|---|---|
|
|
-
lockWorkingCopy()thenlockStore(). No dirstate context.
-
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.
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).
| Method | Meaning |
|---|---|
|
Branch name to switch the working directory to ( |
|
|
|
|
|
|
|
How many changesets |
| Method | Returns / throws |
|---|---|
|
|
-
Showing: no lock. Setting or clean:
lockWorkingCopy().--rev: additionallylockStore()taken insidechangeBranch, kept until the old changesets are gone. No changing_parents or changing_files context is used in this class.
-
Follows
commands.branch: the name check and the test for a branch of the same name happen under the working copy lock.--revfollowscmdutil.changebranch. No difference from hg is listed in the javadoc.
String b = new BranchCommand(repo).setBranchName("stable").call();
4.3.10. Branches
Lists named branches with their current head (hg branches).
| Method | Meaning |
|---|---|
|
|
| Method | Returns / throws |
|---|---|
|
|
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.
-
No lock, no dirstate context (read only).
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.
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).
| Method | Meaning |
|---|---|
|
Name of the tag to create, move or remove. Null or empty (the default) makes |
|
Target node (at least 20 bytes; the first 40 hex digits of it are used). Required when creating a tag, ignored when |
|
Commit the |
|
|
|
|
|
|
|
Hooks; |
| Method | Returns / throws |
|---|---|
|
|
-
lockWorkingCopy()thenlockStore()(waiting up to the repository’s push lock timeout) before the first read. The commit goes throughCommitCommand.changingParents/changingFilesare not called in this class itself.
-
The existing-tag check spans local and global tags together (verified against hg 7.2.2).
-
TagCommandfollowshg 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 (setForceoverrides), an uncommitted merge, the null revision and a changed.hgtags, reading the tags from the heads and.hg/localtagslikehg tags. A moved or removed tag writes its previous node as a line of its own first, as the original does.
new TagCommand(repo)
.setTagName("v1.0")
.setNodeId(nodeBytes)
.call();
4.3.12. Tags
Lists tags (hg tags).
| Setter | Meaning |
|---|---|
|
|
|
Reads the |
| Method | Returns / throws |
|---|---|
|
|
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.
-
No lock, no dirstate context.
-
By default global tags are read from the working copy
.hgtagsonly. WithsetReadFromHeads(true)they are read from the heads ashg tagsdoes (findglobaltags: the heads oldest first, a.hgtagsfile read once per file revision, later lines win, history is merged as in_updatetags).
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).
| Method | Meaning |
|---|---|
|
The bookmark to create, move, delete or activate. Without a name (and without delete or active) |
|
Target changeset ( |
|
Same as |
|
|
|
Activate the existing bookmark named by |
|
Marks |
|
|
| Method | Returns / throws |
|---|---|
|
|
|
|
|
The active bookmark name read from |
|
Merges remote bookmarks on pull/fetch (new, equal, fast-forward, keep local when it is ahead, else a divergent |
-
Listing: no lock. Changes:
lockWorkingCopy()thenlockStore(), waiting for both. The file isHgRepository.getBookmarksFile():.hg/bookmarks, the store’sbookmarkswith thebookmarksinstorerequirement, or the shared repository’s file in ahg share -Bworking copy, which every write then mirrors into the working copy’s own.hg/bookmarks. WithsetCurrentOnly(true)andsetActive(true)(not delete):lockWorkingCopy()only. No dirstate context.
-
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. -
mergeFromRemotesimplifies hg’scomparebookmarks/validdest.
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 |
|---|---|
|
|
|
|
|
|
anything else |
Falls back to |
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,~/.hgrcand~/.config/hg/hgrc). Entries are<group>.<setting> = valuewith the settingsprefix,username,passwordandschemes(defaulthttps). 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.certandkeyare not used. -
The
[auth]section is read from the user level files first (HGRCPATHif set, otherwise/etc/mercurial/hgrc,~/.hgrcand~/.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 exposesetCredentialsProviderare 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 |
|---|---|
|
Source address (required): a local path or a remote URL that |
|
Destination directory (required). Created if missing, must be empty if it exists. |
|
|
|
|
|
|
|
Progress receiver and cancellation poll; a |
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 |
|---|---|
|
Source address or |
|
|
|
|
|
Restricts which paths are pulled (narrow clone support); |
|
Progress receiver; a |
|
Credentials asked for when the remote requires authentication; |
|
Shape fingerprints (text) the clone asks for; they pick the clone bundles ( |
|
Sets of shard fingerprints (text) that make a usable group of sharded clone bundles ( |
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 |
|---|---|
|
Destination address or |
|
|
|
|
|
|
|
Hook run before anything is pushed. Its context map holds |
|
Hook run after a successful push of changesets, after the locks are released. Its context map holds |
|
Receives the progress of the LFS uploads and the lines Mercurial prints about them (see |
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 |
|---|---|
|
Source address (required, |
|
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 |
|
|
|
Path filter (narrow fetch); |
|
Progress receiver; a |
|
Provider asked for credentials when the remote requires authentication. Default: none; |
|
Whether |
|
Shape fingerprints for a shaped clone. |
|
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 |
|---|---|
|
Source address (required): URL of the remote repository. No default and no |
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 |
|---|---|
|
Destination address (required): URL of the remote repository. No default and no |
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 |
|---|---|
|
Bundle file to write (required; |
|
|
|
|
|
|
|
|
|
|
|
|
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 |
|---|---|
|
The bundle file to apply (required, must exist; |
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 |
|---|---|
|
Output directory (type |
|
Revision to archive; default |
|
|
|
Directory prefix for every member of a zip or tar archive. Ignored for |
|
|
|
|
|
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 |
|---|---|
|
Downloads the bundle at |
|
Applies the bundles chosen by |
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 |
|---|---|
|
Constructor takes no repository; the destination is created by |
|
Source URL (required; |
|
Directory in which the new repository is created (required; |
|
Adds an include pattern for |
|
Adds an exclude pattern for |
|
|
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 |
|---|---|
|
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 |
|---|---|
|
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 |
|---|---|
|
Constructor. A null repository raises |
|
|
- 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 messagecritical repository read failure: …and are not thrown. A failure while releasing the lock is rethrown asHgLockException. A repository without00changelog.icounts as an empty changelog (0 revisions), as in real hg. A missing00manifest.iis an error only when the changelog has revisions. Filelogs are discovered fromfncacheplus a walk ofdata/; anfncacheentry 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 |
|---|---|
|
Constructor. A null repository raises |
|
|
- Execution
-
RecoverResult call() throws HgLockException. The result haswasInterrupted()(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) andgetVerifyErrors()(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 toHgRepository.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 realhgas 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. WhensetVerify(true)applies,VerifyCommand.call()runs under the same held lock. Without a journal nothing is done. - Differences from hg
-
Returns a
RecoverResultinstead 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 |
|---|---|
|
Constructor. There are no setters. |
- Execution
-
void call() throws IOException, HgLockException. Also reachable asHg.rollback()(same throws). Takes the working copy lock and the store lock, waiting up to the repository’s push lock timeout. ThrowsIllegalStateException("No rollback information available (undo file not found)")whenstore/undodoes not exist,IOExceptionwhen restoring the files fails, andHgLockExceptionwhen a lock cannot be acquired within the timeout. Steps: (1) readundoand truncate or delete store files (trunclines truncate only,backuplines restore full file bytes for v2 docket revlogs, plain lines truncate to the recorded size or delete on size 0); (2) restore.hg/dirstatefrom.hg/undo.backup.dirstate(or deletedirstatewhen no backup exists), and restore the dirstate-v2 data file from.hg/undo.backup.dirstate.datawhen the docket’s uid file is missing; (3) restore.hg/bookmarksfrom.hg/undo.backup.bookmarks(or delete it) and delete.hg/bookmarks.current; (4) in afinally, delete allundo*info files and the consumed docket backups, and clear the revlog cache. - Locking
-
lockWorkingCopy(timeout)first, thenlockStore(timeout)(the version that, perHgRepository.lockStore, refuses withHgAbandonedTransactionExceptionwhen 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 |
|---|---|
|
Constructor. There are no setters. |
- Execution
-
String call() throws IOException, HgLockException. Returns a summary string of the formGC / Compaction complete: defragmented and re-delta optimized N store revlogs, cleaned M orphaned temp files.ThrowsIOExceptionwhen the store directory does not exist (checked first, because taking a lock would create it). Steps: clear the revlog cache; delete.backup,.tmpandjournalfiles in the store root; rewrite the changelog, the manifest and every.irevlog underdata/andmeta/revision by revision into temp files and swap them in atomically (empty revlogs and v2/docket revlogs are skipped and left untouched); rebuildfncachewith atomic IO (entries fordata/andmeta/revlogs only, plus.dentries for split revlogs), skipped forfileindex-v1repositories or when nothing was found; callSystem.gc(). - Locking
-
lockWorkingCopy(timeout)first, thenlockStoreWithoutRecovery(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 |
|---|---|
|
Constructor. |
|
|
|
|
|
The lines |
|
The lines |
- Execution
-
Map<String, Integer> call() throws IOException. Returns the number of errors per check (qualified name) for each check that found some. ThrowsHgValidationException(anIOException) 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 ().checksrequired - 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 |
|---|---|
|
Constructor. |
|
What the last call warned about ( |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Record of the three |
- Execution
-
Listing methods return
List<String>and throwIOException.shapeUpdatereturns void and throwsIOException, HgLockException.shapeClearPreviousreturnsStringand throwsIOException, HgLockException. Every instance method first throwsHgValidationException("repo is narrowed, this is a server command")whennarrowhg-experimentalis in.hg/requiresorstore/requires. An unknown shape name givesHgValidationException("shape '…' not found").shapeUpdatevalidation (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 |
|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
|
What the command told the user, line by line as hg prints it. |
- Execution
-
void call() throws IOException, HgLockException. ThrowsHgValidationExceptionwhen revision, source or destination is empty,IOExceptionwhen any step fails, andHgLockExceptionwhen the locks cannot be taken after the old ones were broken. If<dest>/.hgexists the repository is loaded; otherwise whatever is at the destination is deleted, a repository is created withHg.init()and the repository is pulled in full unlesssetInitialCloneMinimal(true). Then: break the locks, recover, pull, purge, force update. - Locking
-
As in the original, in this order: the lock files
store/lockand.hg/wlockare deleted without taking anything (messageshad to break store lockandhad to break working copy lock); thenlockWorkingCopy()andlockStoreWithoutRecovery(timeout)are taken together for recovery (RecoverCommand), pull, purge (PurgeCommandwith directories, files = purge unknown, ignored = purge ignored) and update (UpdateCommandwith 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 |
|---|---|
|
The changeset to sign (20-byte node). Default: the working directory’s parent. |
|
The keys to sign with; must contain a secret key ( |
|
|
|
The key’s passphrase; null or empty for an unprotected key. |
|
|
|
|
|
|
|
The commit message; default is one line |
|
Commit author of the |
|
The signature creation time; default now. |
- Execution
-
List<HgSigEntry> call() throws IOException, HgLockException; returns the signature lines that were recorded. ThrowsIllegalStateExceptionwithout a keyring;HgValidationExceptionfor no usable signing key, an uncommitted merge, a repository with no changeset, or a changed or untracked.hgsigs(unless forced);HgRevisionNotFoundExceptionfor an unknown node. All checks that can refuse run before.hgsigsis written. - Locking
-
The working copy lock only,
lockWorkingCopy(), for the whole command. The commit (CommitCommandwithmatch=.hgsigs) takes the store lock itself and releases it. Signing, the write of.hgsigsand the add happen under the working copy lock alone. - Differences from hg
-
hg sign --forcecrashes in the original withUnboundLocalError;setForceworks here. Like the original, a failure after.hgsigswas written leaves the file as it is. The commit holds.hgsigsonly; 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 |
|---|---|
|
The keyring to verify against. Required. |
|
The time expiry is judged against; default now. |
- Execution
-
Result call() throws IOException.Resultis a record(List<Signed> signatures, List<String> warnings);Signedis 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 inwarningswith the same wording and the<file>:<line>prefix hg would have printed (keyring notes stay inGpgKeyring.getNotes()). A signature of a node that does not exist gives the warningnode does not exist. A line that is not a signature line at all is anIOException(HgSigFormatException). ThrowsIllegalStateExceptionwithout a keyring. Expiry is judged at the time ofsetNow(default now).IOExceptionalso 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 |
|---|---|
|
The changeset to check (20-byte node). Required. |
|
The keyring to verify against. Required. |
|
The time expiry is judged against; default now. |
- Execution
-
Result call() throws IOException.Resultis a record(String nodeHex, List<HgSigResult> validSignatures, List<String> warnings)withisSigned(). An emptyvalidSignatures()is what real hg reports asno 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 ofsetNow. ThrowsIllegalStateExceptionwhen the node or keyring is missing,HgRevisionNotFoundException(anIOException) when the node is not in the changelog, andIOExceptionwhen 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 |
|---|---|
|
|
|
Subrepo path relative to the repository root, written to |
|
Subrepo source written to |
|
Revision string written to |
- Execution
-
void call() throws IOException, HgLockException.addappendspath = urlto.hgsuband<rev> pathto.hgsubstate(no commit).initandupdatebehave the same: for each.hgsubentry, 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.hgsubis missing,initandupdatereturn silently. ThrowsIOExceptionwhen 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
lockWorkingCopyorlockStorecall). Locks taken by the nested clone, pull andUpdateCommandcalls 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 |
|---|---|
|
The "ours" commit node (20 bytes); the result is expressed relative to it. Required before |
|
The "theirs" commit node (20 bytes), the changeset merged in. Required before |
|
The ancestor to merge against instead of the common ancestor; |
- Execution
-
TreeMergeResult call() throws IOException.TreeMergeResulthasisConflicted(),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) andgetRemovedFiles(). The result is nevernull. ThrowsHgRevisionNotFoundException(anIOException) when ours, theirs or a given base is not in the changelog, andIOExceptionwhen 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-fileMerge3logic 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 ingetChangedFiles()), as inhg 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 |
|---|---|
|
The first parent: the head the merge is committed on (the receiving side). A node, or a revision identifier. Required. |
|
The second parent: the head merged in (the sending side). Required. |
|
The ancestor to merge against instead of the common ancestor of the parents (optional). |
|
The committer as stored in the changeset. Required. |
|
The message; trailing white space of each line and empty lines at both ends are removed, as |
|
|
|
The named branch of the merge changeset. Default: the branch of the first parent. |
|
An |
|
Allows a merge in which one parent is an ancestor of the other, like |
- Execution
-
MergeCommitResult call() throws IOException, HgLockException.MergeCommitResulthasisConflicted(),getConflicts()(sorted paths),getNode()(20 bytes,nullwhen conflicted) andgetNodeHex(). A conflict is a value, not an exception, and nothing has been written then. ThrowsHgValidationExceptionfor 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;HgRevisionNotFoundExceptionwhen a parent or the base is not in the changelog;HgLockExceptionwhen the store lock cannot be taken;IOExceptionfor store errors, after which the repository is rolled back. - Locking
-
Only the store lock (
lockStore) and a rollback transaction, nowlockand no dirstate, as forGraftInMemory. The lock is held for the whole call: the merge computation and the writes. Waits up to[ui] timeoutfor 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 |
|---|---|
|
Opens an existing repository. Checks the requirements in both |
|
Wraps an existing repository handle. A null raises |
|
Command to initialize a repository. |
|
Command to clone a repository. |
|
Command to make a narrow clone with a narrowed set of paths. Not tied to an existing repository. |
|
Registers a Java hook for a phase (several per phase are kept in order); returns this for chaining. Null type or hook is ignored. |
|
The hooks registered for a phase. |
|
Runs the action while holding |
|
The wrapped repository handle; never null. |
|
Config loaded in Mercurial’s priority order: the system hgrc ( |
|
Downloads a clone bundle by plain HTTP(S) GET and applies it ( |
|
Resolves the effective |
|
Diff entries between two revisions. |
|
File tree of a revision. |
|
New walkers: over the manifest of a revision ( |
|
Runs |
|
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 |
|---|---|
|
Before a commit transaction; aborting cancels the commit. Wired by |
|
After a commit. Wired by |
|
Before a remote push; aborting cancels it. Wired by |
|
After a push. Wired by |
|
After a graft. Wired by |
|
After a rebase. Wired by |
|
After a merge. Wired by |
|
After an update (checkout). Wired by |
|
Before a merge, can be rejected. Wired by |
|
Before an update, can be rejected. Wired by |
|
Before a rebase, can be rejected. Wired by |
|
After a strip. No wiring found in |
|
After an amend. No wiring found in |
|
Before tag creation, can be rejected. Wired by |
|
After tag creation. Wired by |
|
After a changegroup is received. No wiring found in |
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 |
|---|---|
|
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 |
|
A repository lock cannot be acquired, or lock contention occurs (also when releasing the lock fails). The message is |
|
An interrupted transaction ( |
|
A 3-way merge left unresolved conflicts: |
|
A precondition or integrity check on repository state or the working directory failed. This is the general "refused" signal of the commands, for example |
|
Server-side push/unbundle apply (local |
|
Data integrity failure: a revlog checksum mismatch, a corrupted delta restoration or index, or unreadable dirstate, sidedata, obsolescence or LFS pointer data. |
|
Reading the content of a censored file revision through |
|
A hook refused the operation. Raised by the local peer apply for a failing |
|
A repository (or a required file such as a shelf or a filelog) cannot be found because of an invalid path or corruption; |
|
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 |
|
Base of network and wire protocol errors in the HTTP/SSH transport layer; the message is |
|
SSH or HTTP credential authentication failure: an HTTP 401 or 403 answer (the user name is |
|
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 ( |
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
wlockfirst and, when it writes the store,lockafter 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 useslockWorkingCopy()andlockStore()itself must follow it. -
lockWorkingCopy()never recovers anything.lockStore()andlockStore(int)refuse withHgAbandonedTransactionExceptionwhenstore/journalexists and the thread did not already hold the lock; the lock is released again before the exception is thrown. RunRecoverCommand(hg recover).lockStoreWithoutRecovery(int)takes the store lock without that check, forrecoverandverify, which must look at the journal while they hold the lock. Only the explicit commandsrecoverandrollbackrepair 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), thenHgLockExceptionis thrown.ui.timeout = 0fails at once. The system propertyhg4j.ui.timeoutchanges only the default; an explicit[ui] timeoutalways wins.lockWorkingCopy(int)andlockStore(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
afterLockand 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 realhgexclude 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/journalholds<path relative to the store>\0<size>lines andstore/journal.backupfilesthe files that are rewritten rather than appended to (fncache,phaseroots, the docket of a version 2 revlog), so the realhg recovercan roll back what an interrupted hg4j left and the other way round. The companion files of a version 2 docket are listed injournal.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,unbundleand the apply of a push use it. On a push to a server thepretxnchangegrouphooks 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;
Revlogappends andtruncateneed 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
writeDirstatewas called inside it.getDirstate()returns the same instance for the whole context. -
Any exception inside
changingFilesorchangingParentsinvalidates the whole context and nothing is written; the next read goes back to the disk. WithopenChanging…()you must callDirstateChange.failed()beforeclose()when the work failed; a plainclose()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 usechanging_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"). CallingDirstate.writeyourself, 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.sparserevlogis accepted byHg.openand by clone bundle selection, butInitCommanddoes not write it and no hg4j code acts on it. -
Revlog: revlog-v1,
exp-revlogv2.2(docket),exp-changelog-v2withexp-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 requirementnarrowhg-experimentaland the filesnarrowspecandnarrowspec.dirstate; shapes and shards, which are not a requirement but the wire capabilityexp-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 testruns the unit tests../gradlew interopTestruns the tests taggedinterop, which need a realhg(onPATH, 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
hgon 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 realhgkeeps 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.-PignoreTestFailureslets 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 inchanging_parents(the original does it withupdate).unshelveuseschanging_parents. Wrapping the whole shelving step in one context would leave the parent of the temporary commit behind and breakunshelve. -
status: the stat fix-ups (files found clean whose recorded stat is out of date) are written underwlock(wait=False)without achanging_*context, aspoststatusfixupdoes: the original runs status in arunning_statuscontext, which is not exclusive withchanging*and needs no lock, and then tries the lock without waiting. hg4j has norunning_statusobject; 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 --forceworks. In the original it ends with anUnboundLocalError. -
strip --softis refused with a clear message. In a default repository the original fails with an exception, because the archived phase needs theinternal-phaserequirement. -
upgrade(debugupgraderepo) is not provided. It is planned for the next major version, together with a command line front end. -
store_shapewith an empty shard name gets no answer, as with the original (which fails). -
Behaviour that follows the original and that a caller may notice:
.origfiles are left afterrebase --abort,unshelve --abortand a conflictingbackout;rebasewithout evolution strips the originals; reusing a branch name that exists on another line of history needs-f;phaserefuses to move changesets to a higher phase with exit status 1 and the textcannot move N changesets to a higher phase, use --force;signcommits.hgsigsonly.
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 |
|---|---|---|
|
Now declare |
Catch or declare |
|
Never recovers an interrupted transaction any more; it throws |
Run |
|
Changing the dirstate needs the working copy lock; the write is made when the dirstate context ends. |
Use |
|
New functional interface; its |
Pass it to |
|
New: work that runs after the outermost lock is released. |
Use it for follow-ups that must not run under the locks. |
|
Removed. A journal that still carries the entry is read without error. |
Tools that read the backup file have to stop doing so. |
|
Now follows |
Replace code that expected the originals to stay readable. |
|
Refuses a move to a higher phase through the exit status ( |
Check |
|
Commits |
Commit other changes yourself. |
|
|
Pass |
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, andupgrade.
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 realhg, 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 verifyreported 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.
-
stripin 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. -
unshelveleft the rebased restore commit in the store, andunshelve --abortdid not remove.hg/rebasestateor 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 inllm-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.