Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,10 @@ streaming import design.
checks are skipped with a note; CI sets `EXT4KIT_REQUIRE_E2FSPROGS=1` so
they fail instead. `oci.rs` holds `#[ignore]`d `--from` tests that need
Docker Hub or a Docker engine. `open.rs` reopens created images through
the library, and `edit.rs` runs sequences of `ext4kit edit` calls.
the library, `edit.rs` runs sequences of `ext4kit edit` calls, and
`tracked.rs` covers folder tracking at create time, skipping with a note
when git is missing (`EXT4KIT_REQUIRE_GIT=1` makes it fail instead, like
the e2fsprogs pattern).
- Build small images in memory with `Ext4ImageBuilder::new(16)`, then call
`create_root_dir()`, `create_lost_and_found()` and `reserve_inodes()`
(`ext4::test_support::fresh_builder()` does this). Assert by reading back
Expand Down
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,42 @@ flags take numeric IDs only, because the user that matters is the one in the
VM the disk is attached to, not one in an image's `/etc/passwd`. A missing GID
defaults to the UID.

### Tracked folders

Tracking is opt-in: pass `--track` and, when every `--add` source lies inside
a git repository and no two additions overlap, `create` records the mapping
beside the image (in `<image>.ext4kit-tracked`) and writes a **baseline
commit** `refs/ext4kit/<label>/base` into each repository, holding exactly
what was imported, normalized and ignore-filtered like every later snapshot
will be. A plain `create` only writes the image. A mapping root that cannot
be read (replaced by a symlink, or unlistable) is skipped rather than
deleted, so a read failure never drops the repository's content from the
baseline; HEAD paths whose names cannot exist on the host are kept from HEAD
instead of being deleted. A single file larger than 100 MiB stays out of the
baseline (HEAD's version is kept where present) and is reported as a note, so
a sparse or crafted image cannot turn the baseline into an unbounded copy.
The label defaults to the image file name; pass `--label` when several images
share one, and `--verbose` to print how long the baseline took to write.

```powershell
cargo run -- create --track --add C:\work\repo:/opt output.img
# tracking baseline: refs/ext4kit/output/base -> <sha> in C:/work/repo
```

Later, `ext4kit snapshot` turns the image's state into commits on
`refs/ext4kit/<label>/head`, so the agent's work can be reviewed with
`git diff` and applied with `git cherry-pick` (that command arrives with the
next release; the create-time recording is in place). `--include-ignored`
puts gitignored paths into the baseline and every snapshot of the label.
Re-creating over a tracked image refuses unless the unsnapshotted changes are
explicitly discarded (`--discard-unsnapshotted`), and never over an image that
is still mounted (`--replace-mounted` exists only for a VM that crashed or was
killed); both refusals hold with or without `--track`, and so does retiring
the previous baseline refs under `refs/ext4kit/<label>/previous/<timestamp>/`.
A sidecar whose recorded image UUID does not match the image is foreign (a
copied sidecar, a wrapper mix-up): it is reported and removed, its refs are
never moved, and a label it happens to use still collides.

### Editing an image

`ext4kit edit` changes an image that `create` wrote, one coreutils-style
Expand Down
35 changes: 35 additions & 0 deletions docs/supported-features.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,41 @@ The demonstration image contains:

`hello.txt` contains `Created by ext4kit` and has `user.creator=ext4kit`.

## Tracked folders

`create --track` records folder tracking when every `--add` source is inside
a git repository and no two additions overlap (image targets or
repo-relative host paths): a sidecar `<image>.ext4kit-tracked` ties the
image's UUID to a label and its mappings, and one baseline commit per
repository lands on
`refs/ext4kit/<label>/base`, parented on HEAD. The baseline holds exactly the
imported content — normalized with git's clean-conversion rules (eol
attributes, `core.autocrlf`, `filter=`/`ident` routes through
`git hash-object`) and filtered with the repository's ignore rules, which a
per-label `--include-ignored` at create turns off. Nested repositories and
submodule pointers are boundaries like they are for git itself: a gitlink is
re-emitted unchanged, a nested clone's files never enter the outer commit. A
mapping root the walk cannot resolve or list (replaced by a symlink,
unlistable) skips the mapping — content the walk could not see is never
deleted from the baseline. HEAD paths whose names cannot exist on the host
(a control byte, a reserved Windows device name) are kept from HEAD with
their raw bytes instead of being deleted, and names the walk classifies as
host-incompatible are reported, never auto-renamed. A single file larger than
100 MiB is left out of the baseline — HEAD's version is kept where present —
and reported as a note, and the run as a whole is bounded by the image size.
The `ext4kit snapshot` command that turns image state into commits on
`refs/ext4kit/<label>/head` follows in the next release.

Re-creating over a tracked image keeps the previous baseline refs under
`refs/ext4kit/<label>/previous/<timestamp>/` and refuses to discard
unsnapshotted work (or a still-mounted image) without the explicit
`--discard-unsnapshotted` / `--replace-mounted` overrides — with or without
`--track`, since those gates protect the old image, not the new one. A
sidecar whose recorded image UUID does not match the image is foreign: it is
reported and removed, its refs are never moved, and a label it happens to
use still collides. Tracking is off by default: a plain `create` writes only
the image.

## Metadata API

Creation methods accept `PosixMetadata`:
Expand Down
138 changes: 137 additions & 1 deletion src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ use ext4kit::{
local::{Engine, LocalImage},
remote::RemoteImage,
},
tracked::create::{
TrackedSource, TrackingFlags, finish_tracking, prepare_tracking, retire_old_tracking,
},
vfs::edit::{EntryAttributes, PathTest},
};
use std::{
Expand Down Expand Up @@ -65,6 +68,38 @@ enum Command {
/// Example: --root-owner 1000:1000
#[arg(long, value_name = "UID[:GID]", value_parser = parse_owner)]
root_owner: Option<(u32, u32)>,

/// Record folder tracking for the --add sources: a sidecar beside
/// the image and a baseline commit in each source's repository,
/// so an agent's work inside a VM can be reviewed with git.
/// Without it, create only writes the image.
#[arg(long)]
track: bool,

/// Label of the tracked-folder refs (default: the image file
/// name). Pass one when several images share a basename.
#[arg(long, value_name = "LABEL", requires = "track")]
label: Option<String>,

/// Include gitignored paths in the tracked baseline and in every
/// snapshot of this image. Fixed per label at create.
#[arg(long, requires = "track")]
include_ignored: bool,

/// Re-create over an old tracked image that is mounted or was not
/// cleanly unmounted. Only for a VM that crashed, was killed, or
/// will never resume.
#[arg(long)]
replace_mounted: bool,

/// Discard agent changes in the old tracked image that were never
/// snapshotted, instead of refusing to re-create over it.
#[arg(long)]
discard_unsnapshotted: bool,

/// Print tracking phase timings.
#[arg(long)]
verbose: bool,
},

/// Change an image created by ext4kit in place, one operation per call.
Expand Down Expand Up @@ -225,7 +260,29 @@ fn main() -> ExitCode {
size,
chown,
root_owner,
} => run_create(add, from, output, size, chown, root_owner).map(|()| ExitCode::SUCCESS),
track,
label,
include_ignored,
replace_mounted,
discard_unsnapshotted,
verbose,
} => run_create(
add,
from,
output,
size,
chown,
root_owner,
TrackingFlags {
track,
label,
include_ignored,
replace_mounted,
discard_unsnapshotted,
verbose,
},
)
.map(|()| ExitCode::SUCCESS),
Command::Edit { image, action } => run_edit(&image, action),
};
result.unwrap_or_else(|error| {
Expand All @@ -241,6 +298,7 @@ fn run_create(
size: Option<usize>,
chown: Option<(u32, u32)>,
root_owner: Option<(u32, u32)>,
tracking_flags: TrackingFlags,
) -> anyhow::Result<()> {
let additions: Vec<Addition> = add
.iter()
Expand All @@ -251,6 +309,21 @@ fn run_create(
if size.is_some_and(|size| size < 16) {
anyhow::bail!("--size must be at least 16 MiB");
}
// The tracking checks (overlap, discovery, dirty, label) all run
// before Ext4ImageBuilder::new_file truncates the output, so a
// refusal leaves the old image, sidecar and refs exactly as they
// were.
let sources: Vec<TrackedSource> = additions
.iter()
.map(|addition| {
Ok(TrackedSource {
source: addition.source.clone(),
target: addition.target(),
is_dir: addition.is_directory()?,
})
})
.collect::<anyhow::Result<_>>()?;
let (tracking, old_tracking) = prepare_tracking(&sources, &output, &tracking_flags)?;
// The runtime only drives engine and registry I/O; image import itself
// runs on this thread and blocks on it.
let base = match from.as_deref() {
Expand All @@ -265,6 +338,13 @@ fn run_create(
.as_ref()
.map(|(_, source)| source.size_mib())
.transpose()?;
// Retiring the old tracking state runs after the network work — a
// registry failure must leave the old image tracked, refs and sidecar
// untouched — but before the host scan: the scan snapshots the tree
// the import later reads from, and retiring between them would delete
// refs the import still expects. Everything after this point until
// `new_file` is local.
retire_old_tracking(&output, old_tracking.as_ref())?;
let (image_size_mb, host_trees) = match size {
Some(size) => {
if let Some(estimate) = base_size.filter(|&estimate| estimate > size) {
Expand Down Expand Up @@ -330,6 +410,15 @@ fn run_create(
})?)?;

println!("Ext4 image successfully generated at: {}", output.display());
if let Some(prepared) = tracking {
finish_tracking(
&output,
builder.superblock.s_uuid,
&prepared,
image_size_mb,
&tracking_flags,
);
}
Ok(())
}

Expand Down Expand Up @@ -843,6 +932,53 @@ mod tests {
assert_eq!(root_owner, Some((1000, 1000)));
}

#[test]
fn tracking_switches_are_opt_in() {
let cli = Cli::try_parse_from([
"ext4kit",
"create",
"--track",
"--label",
"x",
"--include-ignored",
"--verbose",
"--add",
"source",
"output.img",
])
.unwrap();
let Command::Create {
track,
label,
include_ignored,
verbose,
..
} = cli.command
else {
panic!("expected create")
};
assert!(track);
assert_eq!(label.as_deref(), Some("x"));
assert!(include_ignored);
assert!(verbose);

// --label and --include-ignored configure the baseline, so they
// are usage errors without --track.
for flags in [&["--label", "x"][..], &["--include-ignored"][..]] {
let mut full = vec!["ext4kit", "create", "--add", "source"];
full.extend_from_slice(flags);
full.push("output.img");
assert!(Cli::try_parse_from(full).is_err(), "{flags:?}");
}

// The old-image overrides protect an existing image, not the new
// baseline, so they work without --track.
for flag in ["--replace-mounted", "--discard-unsnapshotted"] {
Cli::try_parse_from(["ext4kit", "create", "--add", "source", flag, "output.img"])
.expect("the override parses without --track");
}
}

#[test]
fn accepts_oci_image_without_host_additions() {
let cli = Cli::try_parse_from([
Expand Down
Loading