rootfsdiff

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

README

rootfs-diff

rootfs-diff compares two embedded Linux root filesystem (rootfs) archives and shows what changed between releases. Use it as a command-line tool or a Go library.

Supply complete tar or tar.gz archives from Buildroot, Yocto or any build system that produces a supported archive. rootfs-diff reads the file contents and metadata stored in each archive without extracting files or running their contents. It writes text, JSON or Markdown reports. The same logical inputs and options produce identical report bytes.

Reports show added, removed and modified paths, including changes to content hashes, numeric ownership, permissions, link targets and device metadata. To make a change fail CI, enable a check: require specific paths, set a limit on net file-content growth, or fail on any change. By default, finding differences is a successful comparison.

Buildroot release review

The Buildroot example was run against two archives generated by Buildroot. Every archive entry was also inspected independently to check the report. Follow the recipe and reproduction commands to repeat the comparison with the same Buildroot version.

The command reported these controlled changes. Paths are relative to the root filesystem, so etc/device.conf refers to /etc/device.conf on the target device.

Recorded path Controlled change
etc/init.d/S40network Removed
etc/device.conf Mode 0640 to 0666
usr/bin/device-agent Symlink target agent-v1 to agent-v2
usr/lib/libexample.so Grows by 420 KiB (430,080 bytes)

The report contains one removal, three modifications, no additions and no metadata warnings. The 430,080-byte file increase minus the removed 17-byte startup script gives 430,063 bytes of net growth. This measures uncompressed regular-file contents, not flash usage or download size.

The images contain files created for the demonstration: S40network and the agent endpoints are stubs, and libexample.so is a fully written file filled with zero bytes. The demonstration does not run the files or boot either image.

To make CI fail when the startup script is missing, save the following policy as required-paths.json. It checks only that the path is present; it sets no growth limit. Policy paths use the same root-relative spelling as report paths:

{
  "schema_version": 1,
  "required_paths": ["etc/init.d/S40network"]
}
./bin/rootfs-diff --policy required-paths.json before.tar after.tar

For the Buildroot archive pair, this command exits with code 1, writes a complete report and lists one required_path violation. The full example also sets a 409,600-byte net growth limit, so its report lists two violations. Without an enabled check, differences return exit code 0. Invalid input or an operational failure returns exit code 2, and the output may be incomplete. See the CI example for handling these exit codes.

Install and quickstart

Download v0.1.2 binaries and checksums, or build from source with Go 1.27.4. The module requires at least Go 1.27.0. Linux and macOS are supported on amd64 and arm64. Choose the binary for the computer running rootfs-diff, regardless of the firmware's CPU architecture. See the installation guide for binary, source and Go module setup.

git clone https://github.com/Azhovan/rootfs-diff.git
cd rootfs-diff
./scripts/verify.sh

Build the command, then compare your baseline and candidate rootfs archives:

go build -o ./bin/rootfs-diff ./cmd/rootfs-diff
./bin/rootfs-diff baseline.tar candidate.tar.gz
./bin/rootfs-diff --format json baseline.tar candidate.tar.gz > report.json
./bin/rootfs-diff --policy policy.json baseline.tar candidate.tar.gz

For the last command, save the sample policy as policy.json and adapt it to your candidate archive. To try the library without supplying archive files, run the self-contained example:

go run ./examples/library

Put all flags before the two filenames. Exit code 0 means the comparison and all enabled checks passed. Code 1 means a check failed, with a complete report explaining the result. Code 2 means invalid input or an operational failure; treat any output as incomplete.

Documentation

Start with the synthetic example for a small comparison you can reproduce locally. The Buildroot demonstration describes the two-image comparison above, including its prerequisites, controlled changes and observed report.

Scope

v0.1 reads local tar and tar.gz files and compares the contents and metadata recorded in them. It excludes timestamps, user and group names, extended attributes (xattrs), access control lists (ACLs), file capabilities and SELinux labels. Every report lists the excluded metadata. Encountered xattrs, ACLs, capabilities, SELinux labels and unrecognized vendor PAX metadata also produce warnings; timestamps and user or group names do not. Sparse archives and unsupported input formats fail. See semantics and limits.

An archive comparison cannot establish whether firmware boots, runs correctly, supports an over-the-air (OTA) update, is affected by a CVE, meets compliance requirements or is secure. rootfs-diff does not unpack raw firmware, mount filesystems, identify the packages that own files or run target binaries.

Yocto buildhistory records package and image information, including file permissions, ownership, sizes and symlinks. rootfs-diff can provide a similar file-level review from standalone tar archives produced by different build systems, with checks you choose explicitly. If you use buildhistory, keep its package, dependency and build context alongside the archive report. diffoscope provides broader artifact comparisons.

The import path is github.com/Azhovan/rootfs-diff, package rootfsdiff. Development follows the v0.1 contract and delivery issue.

License

rootfs-diff is licensed under the Apache License, Version 2.0 (Apache-2.0). Third-party components, including Go and Buildroot, retain their own licenses and notices.

Documentation

Overview

Package rootfsdiff compares recorded contents and metadata of root filesystem tar archives without extracting or executing their contents.

Scan reads tar and tar.gz streams into manifests. Compare reports changes between a baseline and candidate manifest. ParsePolicy and Evaluate apply user-defined checks for required paths and net payload growth. The separate public report package writes text, JSON and Markdown reports; the CLI calls these operations in sequence. See docs/v0.1-contract.md for the exact behavior.

Call Validate on caller-built models or after decoding model JSON. Validation does not normalize, sort or change the input, print output, or access the filesystem. Caller-built manifests may list entries in any order; the scanner and comparator sort their output. Manifest validation checks that hardlink chains end at existing regular files and have matching effective metadata. A diff need not contain the entry named by a hardlink target, since ignore rules may have removed that entry from the comparison. Nil model slices encode as empty JSON arrays, and absent change sides as null. A warning may use path "." for metadata on an ignored root directory record, even though the manifest has no root entry.

Core functions never extract or execute archive contents. Scan accepts an io.Reader that the caller owns and is responsible for closing. Cancellation is checked between bounded reads; it cannot interrupt an arbitrary reader already blocked inside Read. Independent calls share no mutable global options. Callers must not modify input models while a call is reading them. Sizes, counters and numeric ownership use int64. JSON modes are decimal integers containing the permission and special bits in the 07777 mask; text and Markdown reports show those modes in octal. The contract describes metadata exclusions, limits, error categories and the complete schema.

Index

Examples

Constants

View Source
const (
	WarningUncomparedMetadata WarningCode   = "uncompared_metadata"
	SourceBefore              WarningSource = "before"
	SourceAfter               WarningSource = "after"
)
View Source
const (
	ChangeAdded      ChangeKind = "added"
	ChangeRemoved    ChangeKind = "removed"
	ChangeModified   ChangeKind = "modified"
	FieldKind        Field      = "kind"
	FieldMode        Field      = "mode"
	FieldUID         Field      = "uid"
	FieldGID         Field      = "gid"
	FieldSize        Field      = "size"
	FieldSHA256      Field      = "sha256"
	FieldLinkTarget  Field      = "link_target"
	FieldDeviceMajor Field      = "device_major"
	FieldDeviceMinor Field      = "device_minor"
)
View Source
const (
	DefaultMaxEntries      int64 = 100_000
	DefaultMaxArchiveBytes int64 = 8 << 30
	DefaultMaxFileBytes    int64 = 2 << 30
	DefaultMaxPathBytes    int64 = 4_096
)
View Source
const SchemaVersion = 1

Variables

View Source
var (
	ErrInvalidInput     = errors.New("invalid input")
	ErrUnsupportedInput = errors.New("unsupported input")
	ErrLimitExceeded    = errors.New("limit exceeded")
)

Error categories support errors.Is through wrapping. I/O and cancellation errors retain their original identity through Error.Unwrap.

Functions

func MetadataExclusions

func MetadataExclusions() []string

MetadataExclusions returns a fresh, fixed-order slice for every report.

func ValidatePath

func ValidatePath(p string) error

ValidatePath checks a canonical POSIX root-relative model path. It does not normalize input, impose scan limits, interpret backslashes or glob syntax, or consult the host filesystem. Root records are absent from manifests.

Types

type Change

type Change struct {
	Path          string     `json:"path"`
	Kind          ChangeKind `json:"kind"`
	Before        *Entry     `json:"before"`
	After         *Entry     `json:"after"`
	ChangedFields []Field    `json:"changed_fields"`
}

Change has exactly the applicable sides. Modified fields are complete and in the fixed contract order. Added/removed records use an empty field array.

func (Change) MarshalJSON

func (c Change) MarshalJSON() ([]byte, error)

func (Change) Validate

func (c Change) Validate() error

type ChangeKind

type ChangeKind string

type CompareOptions

type CompareOptions struct {
	IgnorePaths    []string `json:"ignore_paths"`
	IgnorePrefixes []string `json:"ignore_prefixes"`
}

CompareOptions applies literal canonical paths to both sides. Prefixes match themselves and descendants separated by '/', never neighboring names. Input order and duplicate rules are allowed and have no semantic effect.

func (CompareOptions) MarshalJSON

func (o CompareOptions) MarshalJSON() ([]byte, error)

func (CompareOptions) Validate

func (o CompareOptions) Validate() error

type Diff

type Diff struct {
	Summary        Summary   `json:"summary"`
	Changes        []Change  `json:"changes"`
	PositiveGrowth []Growth  `json:"positive_growth"`
	Warnings       []Warning `json:"warnings"`
}

Diff records every retained change and every warning, even for ignored paths. PositiveGrowth is complete, ordered by decreasing bytes then increasing path.

func Compare

func Compare(before, after Manifest, opts CompareOptions) (Diff, error)

Compare returns the complete deterministic difference between two manifests. It validates both complete manifests and opts before applying ignore rules. Entries may arrive in any order. Inputs are never mutated, and returned change sides are independent copies; callers must not mutate inputs during a call.

Exact ignores match only their literal canonical path. A prefix matches itself and descendants separated by '/', so "var/log" does not match "var/logger". Both sides are filtered alike. Every warning survives filtering and receives its before/after source. No implicit directory entries are manufactured.

Changes sort by path and list every differing field in this order: kind, mode, uid, gid, size, sha256, link_target, device_major, device_minor. Type changes are single modified records. Only Entry fields are compared: timestamps, user/group names, directory sizes and excluded metadata are not represented as comparable fields. Hardlinks use their validated effective inode metadata.

Payload totals sum retained regular-entry sizes with checked int64 arithmetic; hardlink aliases and all other kinds contribute zero. Net growth is after minus before, including additions, removals and type transitions. This is uncompressed regular payload, not flash size or filesystem disk usage. PositiveGrowth contains every positive per-path regular-payload delta, sorted by descending bytes then path, without a presentation limit. Failures return a zero Diff and a typed validation error, never a successful partial result.

Example
package main

import (
	"crypto/sha256"
	"fmt"

	rd "github.com/Azhovan/rootfs-diff"
)

func main() {
	file := func(path, contents string) rd.Entry {
		return rd.Entry{
			Path: path, Kind: rd.KindRegular, Mode: 0644,
			Size: int64(len(contents)), SHA256: fmt.Sprintf("%x", sha256.Sum256([]byte(contents))),
		}
	}
	// Caller-built manifests may be unordered. No implicit directories are needed.
	before := rd.Manifest{Entries: []rd.Entry{
		file("usr/bin/agent", "v1"),
		file("var/log/boot", "old log"),
		file("etc/device.conf", "enabled\n"),
	}}
	after := rd.Manifest{
		Entries: []rd.Entry{
			file("usr/bin/agent", "version2"),
			file("etc/new", "x"),
			file("var/log/boot", "new log contents"),
			file("etc/device.conf", "enabled\n"),
		},
		Warnings: []rd.Warning{{
			Path: "var/log/boot", Code: rd.WarningUncomparedMetadata, Key: "SCHILY.xattr.user.build",
		}},
	}
	diff, err := rd.Compare(before, after, rd.CompareOptions{IgnorePrefixes: []string{"var/log"}})
	if err != nil {
		panic(err)
	}
	for _, change := range diff.Changes {
		fmt.Printf("%s %s %v\n", change.Kind, change.Path, change.ChangedFields)
	}
	// Totals count retained regular payloads, not filesystem disk usage.
	fmt.Printf("payload: %d -> %d bytes (%+d)\n", diff.Summary.BeforePayloadBytes,
		diff.Summary.AfterPayloadBytes, diff.Summary.NetGrowthBytes)
	for _, growth := range diff.PositiveGrowth {
		fmt.Printf("growth: %s +%d bytes\n", growth.Path, growth.Bytes)
	}
	// Ignoring changes and payload at a path never suppresses its warnings.
	for _, warning := range diff.Warnings {
		fmt.Printf("warning: %s %s %s\n", warning.Source, warning.Path, warning.Key)
	}
}
Output:
added etc/new []
modified usr/bin/agent [size sha256]
payload: 10 -> 17 bytes (+7)
growth: usr/bin/agent +6 bytes
growth: etc/new +1 bytes
warning: after var/log/boot SCHILY.xattr.user.build

func (Diff) MarshalJSON

func (d Diff) MarshalJSON() ([]byte, error)

func (Diff) Validate

func (d Diff) Validate() error

type Entry

type Entry struct {
	Path        string    `json:"path"`
	Kind        EntryKind `json:"kind"`
	Mode        uint32    `json:"mode"`
	UID         int64     `json:"uid"`
	GID         int64     `json:"gid"`
	Size        int64     `json:"size"`
	SHA256      string    `json:"sha256"`
	LinkTarget  string    `json:"link_target"`
	DeviceMajor int64     `json:"device_major"`
	DeviceMinor int64     `json:"device_minor"`
}

Entry records explicit archive metadata, with numeric mode bits (07777 mask) and lowercase hexadecimal SHA-256. Inapplicable fields are zero or empty. Hardlinks retain their own path/kind/target and use terminal regular-entry mode, ownership, size and digest. UID/GID preserve signed numeric tar IDs.

func (Entry) Validate

func (e Entry) Validate() error

Validate checks one entry. Manifest.Validate additionally checks ancestors, hardlink closure/effective data, uniqueness and aggregate size overflow.

type EntryKind

type EntryKind string
const (
	KindRegular     EntryKind = "regular"
	KindDirectory   EntryKind = "directory"
	KindSymlink     EntryKind = "symlink"
	KindHardlink    EntryKind = "hardlink"
	KindCharDevice  EntryKind = "char_device"
	KindBlockDevice EntryKind = "block_device"
	KindFIFO        EntryKind = "fifo"
)

type Error

type Error struct {
	Op   string
	Path string
	Kind ErrorKind
	Err  error
}

Error adds operation and archive-path context without losing an underlying I/O error. Path is an archive path, never an absolute host filename.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

func (*Error) Unwrap

func (e *Error) Unwrap() error

type ErrorKind

type ErrorKind string

ErrorKind identifies invalid or unsupported input. An empty kind leaves the underlying error's identity intact without assigning an input category.

const (
	ErrorInvalidInput     ErrorKind = "invalid_input"
	ErrorUnsupportedInput ErrorKind = "unsupported_input"
)

type Field

type Field string

type Growth

type Growth struct {
	Path  string `json:"path"`
	Bytes int64  `json:"bytes"`
}

func (Growth) Validate

func (g Growth) Validate() error

type LimitError

type LimitError struct {
	Limit   string
	Maximum int64
	Actual  int64
	Err     error
}

LimitError identifies the exhausted budget. Actual is the first observed value beyond Maximum, not necessarily the full size of an unread input. Err may retain an underlying read error when both facts are known.

func (*LimitError) Error

func (e *LimitError) Error() string

func (*LimitError) Is

func (e *LimitError) Is(target error) bool

func (*LimitError) Unwrap

func (e *LimitError) Unwrap() error

type Manifest

type Manifest struct {
	Entries  []Entry   `json:"entries"`
	Warnings []Warning `json:"warnings"`
}

Manifest contains only explicit entries. Caller-built entries and warnings may have any order; producers return sorted slices. Nil means empty.

Example
package main

import (
	"fmt"

	rd "github.com/Azhovan/rootfs-diff"
)

func main() {
	manifest := rd.Manifest{Entries: []rd.Entry{{
		Path: "etc/device.conf", Kind: rd.KindRegular, Mode: 0640,
		UID: 123, GID: 456, Size: 0,
		SHA256: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
	}}}
	if err := manifest.Validate(); err != nil {
		panic(err)
	}
	fmt.Printf("%s mode=%04o uid=%d gid=%d\n", manifest.Entries[0].Path,
		manifest.Entries[0].Mode, manifest.Entries[0].UID, manifest.Entries[0].GID)
}
Output:
etc/device.conf mode=0640 uid=123 gid=456

func Scan

func Scan(ctx context.Context, r io.Reader, opts ScanOptions) (result Manifest, resultErr error)

Scan reads an uncompressed or gzip-compressed tar stream, detected by magic bytes. It never extracts entries, resolves host links, or closes r. Only explicit entries are returned, sorted by canonical POSIX path. Payloads are hashed in bounded chunks and are not retained.

Zero options select documented defaults. The decoded-byte budget includes headers, extensions and padding; the logical-entry budget includes ignored root directory records. Path limits apply to decoded names before path normalization. Hardlinks retain their canonical target and inherit effective data from their terminal regular entry. Uncompared PAX metadata produces sorted warnings containing keys, never values. Standard metadata exclusions are available through MetadataExclusions for the final report.

Scan checks ctx between reads and during link resolution. Cancellation cannot interrupt an arbitrary reader already blocked in Read. The caller owns any deadline or Close needed to unblock that reader. On error Scan returns a zero Manifest, never a successful partial result. Independent calls share no state.

Example
package main

import (
	"archive/tar"
	"bytes"
	"context"
	"fmt"

	rootfsdiff "github.com/Azhovan/rootfs-diff"
)

func main() {
	// Archive creation is only for this self-contained example. In an
	// application, pass an opened local tar or tar.gz file as the reader.
	var archive bytes.Buffer
	w := tar.NewWriter(&archive)
	if err := w.WriteHeader(&tar.Header{Name: "etc/device.conf", Typeflag: tar.TypeReg, Mode: 0640, Uid: 100, Gid: 200, Size: 5}); err != nil {
		panic(err)
	}
	if _, err := w.Write([]byte("hello")); err != nil {
		panic(err)
	}
	if err := w.Close(); err != nil {
		panic(err)
	}
	manifest, err := rootfsdiff.Scan(context.Background(), &archive, rootfsdiff.ScanOptions{})
	if err != nil {
		panic(err)
	}
	for _, entry := range manifest.Entries {
		fmt.Printf("%s %s %04o %d:%d %d %s\n", entry.Path, entry.Kind, entry.Mode, entry.UID, entry.GID, entry.Size, entry.SHA256)
	}
}
Output:
etc/device.conf regular 0640 100:200 5 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

func (Manifest) MarshalJSON

func (m Manifest) MarshalJSON() ([]byte, error)

func (Manifest) Validate

func (m Manifest) Validate() error

type Policy

type Policy struct {
	SchemaVersion       int      `json:"schema_version"`
	RequiredPaths       []string `json:"required_paths"`
	MaxTotalGrowthBytes *int64   `json:"max_total_growth_bytes,omitempty"`
}

func ParsePolicy

func ParsePolicy(r io.Reader) (Policy, error)

ParsePolicy reads one strict JSON policy of at most 1 MiB (1,048,576 bytes), including whitespace. It does not close the caller-owned reader. The object must contain schema_version (the integer 1) and required_paths (an array of exact canonical paths). The optional max_total_growth_bytes is a nonnegative int64 integer; omission disables the growth rule, while zero forbids positive net growth. Unknown or duplicate object keys, nulls, invalid Unicode, noninteger numbers and trailing values are errors. Duplicate required paths are allowed and have no extra effect. Paths are validated, never normalized.

Invalid JSON or policy values return an error matching ErrInvalidInput. Input over the byte budget returns *LimitError matching ErrLimitExceeded, with Limit "policy_bytes". Underlying reader errors remain reachable through errors.Is or errors.As. Every failure returns a zero Policy, never a partial policy.

Example
package main

import (
	"errors"
	"fmt"
	"strings"

	rd "github.com/Azhovan/rootfs-diff"
)

func main() {
	policy, err := rd.ParsePolicy(strings.NewReader(`{
		"schema_version": 1,
		"required_paths": ["etc/init.d/S40network", "usr/bin/device-agent"],
		"max_total_growth_bytes": 1048576
	}`))
	if err != nil {
		panic(err)
	}
	fmt.Println(policy.SchemaVersion, policy.RequiredPaths)
	fmt.Printf("maximum net growth: %d bytes\n", *policy.MaxTotalGrowthBytes)

	_, err = rd.ParsePolicy(strings.NewReader(`{"schema_version":1,"required_paths":[],"typo":0}`))
	fmt.Println("invalid policy:", errors.Is(err, rd.ErrInvalidInput))
}
Output:
1 [etc/init.d/S40network usr/bin/device-agent]
maximum net growth: 1048576 bytes
invalid policy: true

func (Policy) MarshalJSON

func (p Policy) MarshalJSON() ([]byte, error)

func (Policy) Validate

func (p Policy) Validate() error

type PolicyRule

type PolicyRule string
const (
	RuleRequiredPath        PolicyRule = "required_path"
	RuleMaxTotalGrowthBytes PolicyRule = "max_total_growth_bytes"
)

type Report

type Report struct {
	SchemaVersion      int         `json:"schema_version"`
	Summary            Summary     `json:"summary"`
	Changes            []Change    `json:"changes"`
	PositiveGrowth     []Growth    `json:"positive_growth"`
	Violations         []Violation `json:"violations"`
	Warnings           []Warning   `json:"warnings"`
	MetadataExclusions []string    `json:"metadata_exclusions"`
}

Report is the complete schema-version-1 output. No filenames, timestamps or run-dependent values belong here. A renderer must validate before writing.

Example
package main

import (
	"encoding/json"
	"fmt"

	rd "github.com/Azhovan/rootfs-diff"
)

func main() {
	report := rd.Report{SchemaVersion: rd.SchemaVersion, MetadataExclusions: rd.MetadataExclusions()}
	if err := report.Validate(); err != nil {
		panic(err)
	}
	encoded, err := json.Marshal(report)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(encoded))
}
Output:
{"schema_version":1,"summary":{"before_entries":0,"after_entries":0,"added":0,"removed":0,"modified":0,"unchanged":0,"before_payload_bytes":0,"after_payload_bytes":0,"net_growth_bytes":0},"changes":[],"positive_growth":[],"violations":[],"warnings":[],"metadata_exclusions":["acls","directory_sizes","file_capabilities","selinux_labels","timestamps","unrecognized_pax_metadata","user_group_names","xattrs"]}

func (Report) MarshalJSON

func (r Report) MarshalJSON() ([]byte, error)

func (Report) Validate

func (r Report) Validate() error

type ScanOptions

type ScanOptions struct {
	MaxEntries      int64 `json:"max_entries"`
	MaxArchiveBytes int64 `json:"max_archive_bytes"`
	MaxFileBytes    int64 `json:"max_file_bytes"`
	MaxPathBytes    int64 `json:"max_path_bytes"`
}

ScanOptions limits decoded input, including headers, extensions and padding. Zero fields select defaults. Positive values override them; negatives fail. MaxPathBytes applies independently to final entry paths and link targets.

func (ScanOptions) Validate

func (o ScanOptions) Validate() error

func (ScanOptions) WithDefaults

func (o ScanOptions) WithDefaults() (ScanOptions, error)

WithDefaults validates options and returns an independent effective value.

type Summary

type Summary struct {
	BeforeEntries      int64 `json:"before_entries"`
	AfterEntries       int64 `json:"after_entries"`
	Added              int64 `json:"added"`
	Removed            int64 `json:"removed"`
	Modified           int64 `json:"modified"`
	Unchanged          int64 `json:"unchanged"`
	BeforePayloadBytes int64 `json:"before_payload_bytes"`
	AfterPayloadBytes  int64 `json:"after_payload_bytes"`
	NetGrowthBytes     int64 `json:"net_growth_bytes"`
}

Summary counts entries after ignore filtering, not inode identities. Payload totals count regular entries only. All counts and byte values are int64.

func (Summary) Validate

func (s Summary) Validate() error

type Violation

type Violation struct {
	Rule   PolicyRule `json:"rule"`
	Path   string     `json:"path"`
	Limit  *int64     `json:"limit"`
	Actual *int64     `json:"actual"`
}

Violation has a path only for required_path and numeric values only for the growth rule. Renderers generate descriptions from these stable fields.

func Evaluate

func Evaluate(after Manifest, diff Diff, policy Policy) ([]Violation, error)

Evaluate validates all inputs and returns unique violations sorted by rule, then path. It does not mutate inputs; returned numeric pointers are independent copies. An empty rule set or a passing policy returns an empty slice.

Required paths inspect the full after manifest, including comparison-ignored entries. Only explicit entries count: an implicit parent does not satisfy a required directory. Presence is sufficient for every kind, including symlinks; no links are resolved and no runtime usability or executability is implied. A required_path violation identifies the missing path and has nil numeric data.

The growth rule uses diff.Summary.NetGrowthBytes, the comparison's signed net uncompressed regular-payload growth after ignore filtering. It does not sum PositiveGrowth or recompute totals from the full candidate. Equality with the byte limit and shrinking pass, including a zero-byte baseline. A growth failure has rule max_total_growth_bytes, empty path, Limit and Actual byte values. The caller must supply the diff for its intended comparison and candidate.

Invalid policies, manifests or diffs return a typed ErrInvalidInput error and no partial violations. A violation is a successful evaluation, not an error.

Example
package main

import (
	"fmt"
	"strings"

	rd "github.com/Azhovan/rootfs-diff"
)

func main() {
	// These manifests contain only explicit entries. An implicit "etc" parent
	// is not required here; a symlink's presence is enough, without resolving it.
	before := rd.Manifest{Entries: []rd.Entry{{Path: "obsolete", Kind: rd.KindDirectory}}}
	after := rd.Manifest{Entries: []rd.Entry{
		{Path: "etc/device.conf", Kind: rd.KindSymlink, LinkTarget: "../settings"},
		{Path: "var/log/boot", Kind: rd.KindFIFO},
	}}
	diff, err := rd.Compare(before, after, rd.CompareOptions{IgnorePrefixes: []string{"var/log"}})
	if err != nil {
		panic(err)
	}
	policy, err := rd.ParsePolicy(strings.NewReader(`{
		"schema_version": 1,
		"required_paths": ["var/log/boot", "usr/bin/device-agent", "etc/device.conf"],
		"max_total_growth_bytes": 0
	}`))
	if err != nil {
		panic(err)
	}
	violations, err := rd.Evaluate(after, diff, policy)
	if err != nil {
		panic(err)
	}
	// Ignored var/log/boot still satisfies presence. The symlink also passes.
	// Added/removed nonregular entries have zero payload growth, so zero passes.
	fmt.Printf("net growth: %d bytes\n", diff.Summary.NetGrowthBytes)
	for _, violation := range violations {
		fmt.Println(violation.Rule, violation.Path)
	}
}
Output:
net growth: 0 bytes
required_path usr/bin/device-agent

func (Violation) Validate

func (v Violation) Validate() error

type Warning

type Warning struct {
	Source WarningSource `json:"source"`
	Path   string        `json:"path"`
	Code   WarningCode   `json:"code"`
	Key    string        `json:"key"`
}

Warning identifies a metadata key, never its value. Manifest warnings have empty Source; comparison/report warnings have a before or after Source. Path is canonical, except "." identifies an ignored root directory record.

func (Warning) Validate

func (w Warning) Validate() error

type WarningCode

type WarningCode string

type WarningSource

type WarningSource string

Directories

Path Synopsis
cmd
rootfs-diff command
examples
library command
Command library demonstrates the public rootfsdiff and report packages using tiny in-memory tar inputs.
Command library demonstrates the public rootfsdiff and report packages using tiny in-memory tar inputs.
synthetic
Package synthetic supplies the small, offline release-review demonstration.
Package synthetic supplies the small, offline release-review demonstration.
synthetic/cmd/demo command
Command demo generates deterministic inputs and checks a compiled rootfs-diff.
Command demo generates deterministic inputs and checks a compiled rootfs-diff.
internal
cli
Package cli composes the library and report renderer for the rootfs-diff command.
Package cli composes the library and report renderer for the rootfs-diff command.
testfixture
Package testfixture builds small in-memory archives for tests.
Package testfixture builds small in-memory archives for tests.
Package report renders validated rootfsdiff reports without scanning archives or evaluating policies.
Package report renders validated rootfsdiff reports without scanning archives or evaluating policies.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL