Mercurial SCM

7.2.1 · active · verified Wed Apr 15

Mercurial is a fast, scalable, and distributed revision control (version control) system designed for efficient handling of projects of any size. It is primarily implemented in Python, with performance-critical parts in C and Rust. The library is actively maintained with regular releases, with version 7.2.1 being the latest stable release as of April 1, 2026.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically initialize a Mercurial repository, create a file, and commit it using the internal `mercurial` Python API. This approach is typically used for developing Mercurial extensions or deeply embedded functionality. For simpler command-line interactions from Python, external libraries like `hglib` (for command server) or `hgapi` (wrapping CLI) might be considered as they offer a more stable API than the internal `mercurial` modules.

import os
import shutil
from mercurial import ui, hg

# Create a dummy directory for the repository
repo_path = 'my_test_repo'
if os.path.exists(repo_path):
    shutil.rmtree(repo_path)
os.makedirs(repo_path)

# Initialize a new Mercurial repository
repo = hg.repository(ui.ui(), repo_path, create=True)
print(f"Repository initialized at: {repo_path}")

# Create a file
file_path = os.path.join(repo_path, 'hello.txt')
with open(file_path, 'w') as f:
    f.write('Hello, Mercurial!')
print(f"Created file: {file_path}")

# Add and commit the file
# Note: Mercurial's internal API for add/commit can be complex.
# This example uses `add` and then `commit` via the repo object.
# For simpler CLI-like interaction, consider `hglib` or `hgapi`.
# The 'add' command is implicitly handled by `commit` for untracked files in newer versions/contexts, 
# but explicitly adding first is generally safer for robust scripts.
repo.add([file_path])
repo.commit(text='Initial commit', user='Test User <test@example.com>')

print("File committed.")

# Verify the commit (optional: run hg log in the directory to confirm)
# You would typically interact with changesets, manifests, etc. for more complex verification.
logs = repo.changelog.read() # Read changelog to get revision info
if logs:
    latest_rev = repo.changelog.tip()
    print(f"Latest revision: {latest_rev.node()[:12]}")
    print(f"Commit message: {latest_rev.description()}")

# Clean up the test repository (optional)
shutil.rmtree(repo_path)
print(f"Cleaned up {repo_path}")

view raw JSON →