Skip to content
codedaptivePublic

About

Code Chi VCS library (ccvcslib): the one Rust library through which Code Chi tools read and write version control. MIT.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Code Chi VCS: one library for every tool that talks to git. The foundation under the Code Chi tools.

Code Chi VCS library (ccvcslib)

Ask git a question from Rust and get a value back, not text to parse.

Install · Quick start · git and ccvcslib side by side · Features · The questions · Documentation · Contributing

A tool that works on a repository has to ask git things: which files are tracked, what changed since a commit, what a file held last week. The usual way is to start git yourself and read what it prints. That works until a file name has a space in it, a branch is named -n, git waits for a password nobody will type, or the user's shell has GIT_DIR set and your tool reads the wrong repository. Every tool that talks to git meets these one at a time, and each fixes them in its own copy of the code.

The Code Chi VCS library (ccvcslib) holds those fixes once. It is for anyone writing a Rust tool that reads or changes a git repository: a linter, a code indexer, a test runner, a harness for coding agents. Your tool asks questions, not git commands. The questions are the methods of one trait, Vcs, each named for what a tool wants to know: files, dirty_paths, changed_between, file_at_revision. GitVcs answers them by running git. Your code holds paths, revision ids and enums, and never sees a command line or a line of git's output.

It works with the git you already have. ccvcslib runs the git program installed on the machine and links no git library. The repository stays an ordinary git repository, and every other git tool keeps working on it.

release ci platforms license

Where the ideas come from

ccvcslib is a Rust crate, and little in it is new:

  • Git's own plumbing. Git has commands and output formats made for programs rather than people: fields separated by NUL bytes, status codes that do not change between versions. The library uses those and nothing else.
  • Compare-and-swap on refs. Git can move a ref only if it still holds an expected value. move_refs always asks it to.
  • An interface apart from the system behind it. The questions say nothing that is particular to git, so another version-control system could answer the same trait. Git is the only one that does.

What it takes off your hands

Each of these removes something that goes wrong when a tool runs git by hand.

  • Parsing git's output. changed_between answers a list of paths, each Added, Changed or Deleted. You match on an enum. You never split a line of git diff on tabs.
  • File names that break parsers. Paths are read from git separated by NUL bytes, so a space or a line break in a file name is one path, not two.
  • Guessing what an error meant. Every question answers with a Result, and the error is one of four things: the folder is not in a working copy, git could not be run, git ran and failed (with git's message and exit code), or you stopped the call with a deadline or a cancel handle. You never search error text for "not a git repository".
  • Names that git reads as options. A revision or path beginning with - could be taken by git as a flag. Such a name either gets "nothing there" without git being run, or is passed so that git can only read it as a name.
  • A git that hangs. A read stops after 10 seconds without progress, or 60 seconds in all, and answers Unavailable. Git's terminal password prompt is turned off, so nothing waits on a terminal that is not there. Any call, a network one included, can also run under a deadline and a cancel handle you choose (GitVcs::under(CallControl)). A call that is stopped ends git with its whole process group and answers VcsError::Stopped, which names every lock file the stopped git left in your repository; the library removes none.
  • The wrong git, or the wrong repository. The library runs the git found on absolute PATH entries only, so a program named git inside the repository being read is never run. Variables such as GIT_DIR that would point git somewhere else are removed before each call.
  • Two writers overwriting each other. A ref moves only if it still has the value you expected. If it does not, nothing moves and you are told which ref was stale.
  • Commit hooks that run when you did not ask. Staging and committing turn every git hook off. One commit, commit_with_hooks, runs the repository's pre-commit and commit-msg hooks, and only those, and commits what the pre-commit hook staged, as git does.
  • Too many git processes at once. However many tools and threads ask, at most min(CPUs, 8) git processes started by the library run at a time for each user.

Getting started

Install

You need Rust 1.89 or later, and git on an absolute PATH entry. The writes need git 2.46.0 or later.

Pin a tag in your Cargo.toml. A tagged version never changes.

[dependencies]
ccvcslib = { git = "https://github.com/codedaptive/ccvcslib", tag = "v0.6.1" }

Platforms. ccvcslib builds on macOS, Linux and Windows, and its whole test suite and lint pass on all three at the commit v0.6.1 tags (run 47156439335); the same checks run on GitHub Actions at every push. A few tests do not run on Windows because Windows cannot hold what they make, such as a file name with a * or \ in it; each says why in the test.

Quick start

Five questions say where a tool is and what it is looking at:

Question What it answers
1 working_copy_root(dir) The top of the working copy dir is in
2 revision(dir) The revision checked out there
3 files(dir) The tracked files and the untracked files
4 dirty_paths(dir) The paths that differ from the last commit
5 system_version(dir) Which git was found, and whether it is new enough for the writes

In a program:

use ccvcslib::{GitVcs, Vcs, VcsError};
use std::path::Path;

fn main() -> Result<(), VcsError> {
    let vcs = GitVcs::default();
    let dir = Path::new(".");

    let root = vcs.working_copy_root(dir)?;
    let head = vcs.revision(dir)?;
    println!("working copy {} at {}", root.display(), head.0);

    let files = vcs.files(dir)?;
    println!("{} tracked, {} untracked", files.tracked.len(), files.untracked.len());
    for path in vcs.dirty_paths(dir)? {
        println!("changed: {path}");
    }

    let version = vcs.system_version(dir)?;
    if !version.meets_write_floor {
        println!("git {} is older than the writes need", version.found);
    }
    Ok(())
}

GitVcs::default() makes the thing that answers; it is small and cheap to copy, so make one wherever you need it. Every question takes the folder to ask about first, and that folder does not have to be the top of the working copy. Ask system_version once, before the first write.

The same program is in this repository. Clone it and run the program inside any git working copy:

git clone https://github.com/codedaptive/ccvcslib.git
cd ccvcslib
cargo run --example quick_start

git and ccvcslib side by side

You want to With git, run and parse With ccvcslib, ask
Find the top of the working copy git rev-parse --show-toplevel working_copy_root
Know what is checked out git rev-parse HEAD revision
Turn a name a user typed into a revision git rev-parse --verify <name> resolve_revision
List the files git ls-files, then git ls-files --others --exclude-standard files
See what is not committed git status --porcelain dirty_paths, working_copy_changes
See what changed between two commits git diff --name-status <a> <b> changed_between
Read a file as it was git show <rev>:<path> file_at_revision, file_bytes_at_revision
List everything a commit holds git ls-tree -r <rev> files_at_revision
Ask whether a path is ignored git check-ignore <path> is_ignored
Find where two histories meet git merge-base <a> <b> merge_base
Ask whether one commit holds another git merge-base --is-ancestor <a> <b>, and read the exit code is_ancestor
List the commits on a branch since a base git rev-list <base>..<tip> commits_between
Read a commit's author and message git cat-file commit <rev> commit_details
List the worktrees git worktree list --porcelain sibling_working_copies
List branches or tags git for-each-ref <prefix> refs_under
Move a branch, only if nobody else has git update-ref <ref> <new> <old> move_refs
See what a remote has git ls-remote <remote> remote_refs
Fetch and push git fetch, git push, and read the refusals fetch_ref, push_refs
Make a commit without touching the folder git commit-tree, git merge-tree commit_tree, merge_trees
Check git is new enough git --version, and compare the numbers system_version

Help

Every question is documented where it is declared, in src/vcs.rs: what it takes, what it answers and what it refuses. To read the same text as API pages:

cargo doc --open

Features in depth

Each picture below is the output of a program in examples/, run in a small repository with two commits.

Answers you can match on

what_changed asks which paths differ between two revisions, who made the later commit, and how long one file was at each. Nothing in it reads git's text.

for change in vcs.changed_between(dir, &from, &to)? {
    match change.kind {
        ChangeKind::Added => println!("  added    {}", change.path),
        ChangeKind::Changed => println!("  changed  {}", change.path),
        ChangeKind::Deleted => println!("  deleted  {}", change.path),
        ChangeKind::Renamed { from } => println!("  renamed  {from} -> {}", change.path),
    }
}

The what_changed example: one commit's subject and author, five paths marked changed, deleted or added, and the line count of README.md at each revision.

changed_between reports a moved file as a delete and an add, as above. changes is the question that follows renames.

cargo run --example what_changed -- HEAD~1 HEAD

A plain answer when there is none

refusals asks five things that have no ordinary answer: a folder outside any working copy, a revision and a path that begin with -, a commit id that is too short, and the version of git. Each comes back as a value your code can act on. The two names that begin with - never reach git as options.

match vcs.working_copy_root(&outside) {
    Err(VcsError::NotAWorkingCopy) => println!("{}: not a working copy", outside.display()),
    Ok(root) => println!("{}: in the working copy {}", outside.display(), root.display()),
    Err(other) => return Err(other),
}

The refusals example: /tmp is not a working copy, a revision and a path beginning with a dash get no answer, a short commit id is refused as not a revision id, and git 2.56.0 is new enough for the writes.

cargo run --example refusals -- /tmp

Writes that cannot overwrite someone else's

guarded_move makes a ref, saying it must not exist yet. A second writer who believes the same thing is now wrong: nothing moves, and the answer names the stale ref. Several refs can move in one call, and then all move or none does.

let make = [RefMove { name: NAME.to_string(), expected: Expected::MustNotExist, new: Some(head.clone()) }];
match vcs.move_refs(dir, &make, None)? {
    MoveRefsOutcome::Moved => println!("moved"),
    MoveRefsOutcome::Stale { name } => println!("nothing moved, {name} was not as expected"),
}

The guarded_move example: the first writer's move succeeds, the second writer's does not and is told refs/demo/pointer was not as expected, and the ref is then removed by naming the value it holds.

cargo run --example guarded_move

The questions

ccvcslib is a library, so it has no commands of its own. Its surface is the methods of Vcs. These are the main groups; src/vcs.rs documents every one.

Vcs is the union of five smaller traits: VcsReads, VcsWrites, VcsWorkingCopies, VcsRemotes and VcsHooks. Every Vcs (so GitVcs) is each of them. Code that needs only one kind of question bounds on that trait (fn f(vcs: &impl VcsReads)), and a test double implements just that trait: every method defaults to Unavailable. Where you call a method on a concrete GitVcs, import Vcs or a capability trait, not both: rustc cannot tell which trait's method you mean (E0034).

Group Some of the questions
Where am I working_copy_root, own_repository, shared_store, sibling_working_copies, checked_out
Revisions revision, resolve_revision, merge_base, is_ancestor, commits_between, commit_details
Files files, files_at_revision, file_at_revision, file_bytes_at_revision, tracked_entries
Changes dirty_paths, changed_between, changes, uncommitted_paths, uncommitted_diff, added_lines
Ignore rules is_ignored, ignored_folders, ignore_rule_files
Refs and remotes ref_value, refs_under, remote_refs, move_refs, fetch_ref, push_refs, push_refs_atomic
Commits and trees stage_all, commit_index, commit_with_hooks, commit_tree, merge_trees, replay_onto
The index and objects index_entries, write_blob, tree_of_entries, commit_signature
Working copies make_working_copy_at, set_index, move_working_copy, choose_paths, remove_working_copy
The system system_version, can_replay, pack_store

Things to know before you call them:

  • Check the version before the first write. Ask system_version once and read meets_write_floor.
  • Reads are bounded; long work is not, unless you bound it. Copies, writes and network calls take as long as they need; give one a deadline with GitVcs::under(CallControl) to stop it sooner.
  • Revisions are full ids. Most questions take the id a revision has, not a name. resolve_revision turns a name into one.

What ccvcslib is not

  • Not an implementation of git. It needs the git program on the machine and runs it for every answer.
  • Not a way to run any git command. No public function runs a git command of the caller's choosing. A question the library does not have is a question to add.
  • Not a workflow. It never decides how a team uses version control. Which branch to land on, when to rebase and what may be pushed are the caller's decisions.
  • Not a sandbox. Git reads the repository's config and the user's config as usual. See SECURITY.md for what the design guarantees and what it does not.

How it fits Code Chi

Code Chi is a family of small tools for people and coding agents, each with one job. Each one that needs version control asks through this library.

Tool Program Its job
Code Chi Dan ccdan Turns a repository into a working team of coding agents, and connects the other tools
Code Chi Ting ccting Reads the code into an index and answers questions about it
Code Chi Tao cctao Checks code against the rules a repository has chosen
Code Chi Jin ccjin Runs a repository's tests and builds and keeps a receipt of each run
Code Chi Wuji ccwuji Writes the version-control history: folders, saves, joins, landings, the guard
Code Chi Xiu ccxiu Changes source code by name
Code Chi VCS library ccvcslib The one Rust library through which Code Chi tools read and write version control

You do not need the rest of the family to use ccvcslib. It is an ordinary Rust crate with one dependency.

Related work

  • git2 binds libgit2, an implementation of git in C. It gives a program git's objects, refs and index to work with directly, with no git program on the machine.
  • gitoxide is an implementation of git in Rust, with the same reach.
  • Running git yourself with std::process::Command is where most tools start.

git2 and gitoxide are git, as a library. ccvcslib is smaller in aim: it runs the git that is installed and offers the questions a tool asks, with the parsing, the limits and the safety rules written once and tested against real git.

What is in this repository

Path What
src/ The crate: one public symbol per file, its unit tests in a *_tests.rs sibling
tests/ Integration tests that run real git in temporary repositories
examples/ quick_start.rs, what_changed.rs, refusals.rs, guarded_move.rs: the programs shown above
docs/ docs/README.md, the documentation index; the third-party licences; this page's pictures
.github/workflows/ci.yml The whole suite and the lint on macOS, Windows and Linux at every push
scripts/check-public.sh A release check: no private names, paths or secrets in the tree

To run the tests:

cargo test
cargo clippy --all-targets -- -D warnings

The tests that run git make a throwaway repository in a temporary folder and remove it. The ssh signing tests need ssh-keygen; on a system without it they return early. On Windows the rows that need what Windows cannot hold (a file name with a *, ?, : or \, a name ending in a space) are left out, each with its reason in the test, and Windows has its own rows where its behaviour differs.

Documentation

Security

A tool trusts ccvcslib to run the real git, to pass names and paths to git as data, and to answer about the repository it was asked about. SECURITY.md says what the design guarantees, what it does not defend against, and how to report a vulnerability privately.

Contributing

CONTRIBUTING.md says how to file an issue or send a pull request.

License

MIT; see LICENSE.

About

Code Chi VCS library (ccvcslib): the one Rust library through which Code Chi tools read and write version control. MIT.

Topics

Resources

Contributing

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages