---
title: "API Reference"
desc: "Complete reference of all public functions, types, and error variants in the arctgz library."
---
# API Reference
All public items are exported directly from the crate root.
Import them with:
```rust
use arctgz::{
init, compile, extract, verify, diff, patch,
load_config, save_config, load_recipe, extract_recipe, execute_recipe,
ArctgzConfig, ArctgzManifest, ArctgzRecipe, ArctgzDelta,
FileEntry, RecipeStep, Compression, Encryption, DeltaOp,
ArctgzError,
};
```
---
## Functions
### Project Initialization & Configuration
#### `init`
```rust
pub fn init(project_path: &Path, force: bool) -> Result<(), ArctgzError>
```
Creates a new arctgz project at `project_path`.
**Behaviour:**
- Rejects empty paths immediately.
- Resolves and canonicalizes `project_path`. The final canonical path **must** reside within the user's home directory (checked **before** and **after** directory creation to prevent TOCTOU attacks).
- If `project_path` already exists and is not a directory, an error is returned.
- If `force` is `false` and the directory is not empty, the operation is rejected.
- Creates the directory (and parents) if needed.
- **After** creating the directory, re‑canonicalizes the path to detect symlink‑based redirects. If the final path escapes the home directory, the newly created directory is **rolled back** (deleted) and `PathNotAllowed` is returned.
- Creates an empty `include/` subdirectory.
- Writes a default `arctgz.init` configuration file atomically (using `create_new` to detect pre‑existing files).
**Errors:**
- `InvalidPath` – empty path, or path exists but is a file.
- `PathNotAllowed` – path outside home directory (before or after creation).
- `DirectoryNotEmpty` – directory not empty and `force` is `false`.
- `AlreadyInitialized` – `arctgz.init` already exists in the directory.
- `Io` – other filesystem errors.
---
#### `load_config`
```rust
pub fn load_config(project_path: &Path) -> Result<ArctgzConfig, ArctgzError>
```
Reads and validates the `arctgz.init` file from a project directory.
**Errors:**
- `ConfigNotFound` – file does not exist.
- `ConfigLoadError` – read error or invalid JSON.
- `ConfigValidation` – invalid content (see `ArctgzConfig::validate`).
---
#### `save_config`
```rust
pub fn save_config(project_path: &Path, config: &ArctgzConfig) -> Result<(), ArctgzError>
```
Atomically writes a validated `ArctgzConfig` back to `arctgz.init`.
**Behaviour:**
- Validates the config before writing.
- Writes to a temporary file first, then renames it onto the target. If any step fails, the temporary file is removed.
**Errors:**
- `ConfigValidation` – config fails validation.
- `ConfigSaveError` – write or rename failure.
- `Io` – other I/O errors.
---
### Archive Operations
#### `compile`
```rust
pub fn compile(
project_path: &Path,
output_path: Option<&Path>,
force: bool,
private_key: Option<&[u8]>,
password: Option<&str>,
) -> Result<PathBuf, ArctgzError>
```
Compiles the project into an `.artgz` archive.
**Behaviour:**
1. Loads configuration from `project_path/arctgz.init`.
2. Validates that all `include` glob patterns match at least one file (under `project_path/include/`). If any pattern yields zero matches, returns `IncludeFileNotFound`.
3. Collects files from `include/` using the glob patterns (plus the mandatory `arctgz.init` and optional `recipe.json` from the project root). Symbolic links are rejected (`SymlinkNotAllowed`). Empty directories that match a pattern are preserved as directory entries.
4. Computes SHA‑512 hashes of all files in **parallel** (via `rayon`).
5. Builds a `manifest.json` with size, hash, and directory flags.
6. Optionally signs the manifest with an Ed25519 private key (must be exactly 32 bytes; otherwise `KeyError`).
7. Compresses the tar stream (gzip or zstd, according to configuration).
8. If `config.encryption == Encryption::Aes256Gcm`, encrypts the entire archive with AES‑256‑GCM using the provided password. The password is required in this case.
9. Writes the final file atomically via a temporary file.
**Parameters:**
- `project_path` – root directory of the project.
- `output_path` – if `Some`, the path where the archive will be written; if `None`, defaults to `project_path/archive.artgz`.
- `force` – if `true`, overwrites an existing output file; otherwise returns `Io(AlreadyExists)`.
- `private_key` – 32‑byte Ed25519 signing key for signing the manifest; `None` disables signing.
- `password` – password for encryption (required if `encryption` is `Aes256Gcm`; ignored otherwise).
**Returns:** the actual path of the created archive.
**Errors:**
- `ConfigNotFound`, `ConfigLoadError`, `ConfigValidation` – config issues.
- `Io` – filesystem errors (missing `include/` directory, write failures, etc.).
- `SymlinkNotAllowed` – symbolic link encountered under `include/`.
- `IncludeFileNotFound` – a glob pattern matched no files, or the glob itself is invalid.
- `KeyError` – private key length is not 32 bytes.
- `EncryptionError` – password missing when encryption is required, or encryption operation fails.
- `SignatureError` – signing failure (unlikely).
---
#### `extract`
```rust
pub fn extract(
archive_path: &Path,
output_dir: &Path,
force: bool,
public_key: Option<&[u8]>,
password: Option<&str>,
) -> Result<(), ArctgzError>
```
Extracts and verifies an archive.
**Behaviour:**
- Detects compression (gzip/zstd) and encryption (magic bytes `ARCT`).
- If encrypted, decrypts to a temporary file using the provided password. **Password is mandatory for encrypted archives.**
- Verifies the Ed25519 signature if a public key is given.
- Reads `manifest.json` and verifies every file entry:
- Path safety (no absolute, `..`, empty, or `.`).
- Entry type consistency (file vs directory).
- Actual SHA‑512 hash and size must match the manifest exactly.
- If verification fails for any file, the partially extracted file is removed before returning the error.
- If `force` is `true`, existing files are overwritten; otherwise existing files cause `Io(AlreadyExists)`.
- Creates parent directories as needed.
**Parameters:**
- `archive_path` – path to the `.artgz` file.
- `output_dir` – destination directory.
- `force` – allow overwriting existing files.
- `public_key` – 32‑byte Ed25519 public key for signature verification; `None` skips verification.
- `password` – password for decryption; required if the archive is encrypted.
**Errors:**
- `ManifestNotFound` – archive does not contain `manifest.json`.
- `SignatureError` – signature missing (when key provided) or invalid.
- `EncryptionError` – wrong password, decryption failure, or unsupported archive version (see `decrypt_file` behaviour).
- `ChecksumMismatch` – hash or size mismatch for a file.
- `ExtractError` – unsafe path, type mismatch, or manifest/file count inconsistency.
- `Io` – filesystem errors.
---
#### `verify`
```rust
pub fn verify(
archive_path: &Path,
public_key: Option<&[u8]>,
password: Option<&str>,
) -> Result<(), ArctgzError>
```
Standalone integrity check. Performs the same validation as `extract` but writes no files.
**Parameters:** same as `extract` (without `force` and `output_dir`).
**Errors:** same as `extract` (excluding `Io` related to file creation).
---
### Delta Patching
#### `diff`
```rust
pub fn diff(base_archive: &Path, target_archive: &Path) -> Result<ArctgzDelta, ArctgzError>
```
Computes a binary delta between two archives.
**Behaviour:**
- Reads both manifests.
- Compares file entries by path, size, hash, and directory flag.
- Generates `Add`, `Modify`, or `Delete` operations.
- Ignores metadata file `recipe.json` only; `arctgz.init` is **not** ignored and will be included in the delta if changed.
**Returns:** an `ArctgzDelta` containing the list of operations and manifest hashes.
**Errors:** same as `read_manifest` (I/O, JSON, etc.).
---
#### `patch`
```rust
pub fn patch(
base_archive: &Path,
target_archive: &Path,
delta: &ArctgzDelta,
output_path: &Path,
private_key: Option<&[u8]>,
) -> Result<(), ArctgzError>
```
Applies a previously computed delta to produce a new archive identical to the target.
**Behaviour (security‑hardened):**
1. Reads the base archive manifest and verifies its hash matches `delta.base_manifest_hash`. If not, returns `DeltaError`.
2. Reads the target archive manifest and **also** verifies its hash against `delta.target_manifest_hash`. If mismatch, the operation is rejected – this ensures the delta is applied to the exact intended target.
3. Builds a new manifest from the base entries, keeping unchanged files, deleting removed ones, and taking modified/added entries from the delta.
4. For each file that is _copied from the base archive_ (unchanged):
- Reads exactly `expected.size + 1` bytes to detect hidden trailing data. If the actual length is not exactly `expected.size`, the patch fails.
- Computes SHA‑512 and verifies it against the base manifest. Mismatch results in `ChecksumMismatch`.
5. For each file _copied from the target archive_ (modified or added):
- Verifies the size and **also recomputes SHA‑512** against the entry in the new manifest (which originates from the target). If it does not match, `ChecksumMismatch` is returned. This prevents corrupted or tampered data from being injected during patching.
6. The new manifest is written and optionally signed.
7. The result is written atomically.
**Parameters:**
- `base_archive` – path to the base archive.
- `target_archive` – path to the target archive (used as source for modified/added files).
- `delta` – the delta returned by `diff`.
- `output_path` – where to write the patched archive.
- `private_key` – optional signing key for the new manifest.
**Errors:**
- `DeltaError` – manifest hash mismatch (base or target), missing entries, or unexpected file sizes.
- `ChecksumMismatch` – file content integrity failure.
- `Io`, `KeyError`, `SignatureError` – as in `compile`.
---
### Recipe Management
#### `load_recipe`
```rust
pub fn load_recipe(project_path: &Path) -> Result<Option<ArctgzRecipe>, ArctgzError>
```
Loads and validates `recipe.json` from a project directory. Returns `None` if the file is absent.
**Errors:** `Io`, `Json`, `RecipeInvalid`.
---
#### `extract_recipe`
```rust
pub fn extract_recipe(archive_path: &Path) -> Result<ArctgzRecipe, ArctgzError>
```
Extracts and validates the embedded `recipe.json` from an archive (handles compression and encryption transparently).
**Errors:**
- `RecipeNotFound` – no `recipe.json` in the archive.
- `Io`, `Json`, `RecipeInvalid`.
---
#### `execute_recipe`
```rust
pub fn execute_recipe(
output_dir: &Path,
recipe: &ArctgzRecipe,
force: bool,
) -> Result<(), ArctgzError>
```
Runs the steps of a recipe inside `output_dir`.
**Supported steps:**
- `Copy { from, to }` – copies `from` to `to` (both relative to `output_dir`). Directories are copied recursively.
- `MkDir { path }` – creates a directory (and parents).
- `Chmod { path, mode }` – sets Unix permissions (octal mode). Returns an error on non‑Unix platforms.
- `Remove { path }` – deletes a file or directory (directory must be empty).
All paths are validated against traversal attacks (`..`, absolute, empty, or `.`).
`force` controls whether existing destinations are overwritten or cause an error.
**Errors:**
- `RecipeInvalid` – invalid step or path.
- `RecipeExecutionError` – step failed (e.g., missing source, permission denied).
- `Io` – filesystem errors.
---
## Types
### `ArctgzConfig`
```rust
pub struct ArctgzConfig {
pub name: String,
pub version: String,
pub include: Vec<String>,
pub compression: Compression,
pub encryption: Encryption,
}
```
Project configuration. Serialised as JSON with `deny_unknown_fields`.
**Validation (`validate` method):**
- `name` – alphanumeric plus `-` and `_`, max 255 chars.
- `version` – strict semver.
- `include` – relative glob patterns, max 100 entries, each must be a relative path without `..` and non‑empty after trimming.
- `compression` – `Gzip` or `Zstd`.
- `encryption` – `None` or `Aes256Gcm`.
Default (created by `init`):
`name` = `"untitled"`, `version` = `"0.1.0"`, `include` = `[]`, `compression` = `Gzip`, `encryption` = `None`.
---
### `ArctgzManifest`
```rust
pub struct ArctgzManifest {
pub name: String,
pub version: String,
pub created: DateTime<Utc>,
pub compression: Compression,
pub files: BTreeMap<String, FileEntry>,
pub signature: Option<String>,
}
```
Embedded in every archive as `manifest.json`.
- `signature` – hex‑encoded Ed25519 signature of the manifest computed **without** the `signature` field.
---
### `FileEntry`
```rust
pub struct FileEntry {
pub size: u64,
pub sha512: String,
pub is_dir: bool,
}
```
Describes a file or directory entry in the manifest.
---
### `ArctgzRecipe`
```rust
pub struct ArctgzRecipe {
pub name: String,
pub version: String,
pub steps: Vec<RecipeStep>,
}
```
Post‑extraction recipe.
---
### `RecipeStep`
```rust
pub enum RecipeStep {
Copy { from: String, to: String },
MkDir { path: String },
Chmod { path: String, mode: String },
Remove { path: String },
}
```
Deserialised with `#[serde(tag = "action")]`.
---
### `Compression`
```rust
pub enum Compression {
Gzip,
Zstd,
}
```
Default: `Gzip`.
---
### `Encryption`
```rust
pub enum Encryption {
None,
Aes256Gcm,
}
```
Default: `None`.
---
### `ArctgzDelta`
```rust
pub struct ArctgzDelta {
pub base_name: String,
pub base_version: String,
pub target_name: String,
pub target_version: String,
pub base_manifest_hash: String,
pub target_manifest_hash: String,
pub operations: Vec<DeltaOp>,
}
```
Represents the difference between two archives.
- `base_manifest_hash` / `target_manifest_hash` – hex‑encoded SHA‑512 of the respective manifest (with `signature` field omitted).
---
### `DeltaOp`
```rust
pub enum DeltaOp {
Add { path: String, size: u64, sha512: String, is_dir: bool },
Modify { path: String, size: u64, sha512: String, is_dir: bool },
Delete { path: String },
}
```
Serialised with `#[serde(tag = "op")]`.
---
## Error Types
### `ArctgzError`
All possible errors returned by the library.
```rust
pub enum ArctgzError {
Io(std::io::Error),
Json(serde_json::Error),
AlreadyInitialized,
InvalidPath(String),
PathNotAllowed(String),
DirectoryNotEmpty(String),
ConfigValidation(String),
ConfigNotFound(String),
ConfigLoadError(String),
ConfigSaveError(String),
SymlinkNotAllowed(String),
IncludeFileNotFound(String),
ManifestNotFound,
ChecksumMismatch(String, String, String),
ExtractError(String),
RecipeNotFound,
RecipeInvalid(String),
RecipeExecutionError(String),
VerifyError(String),
SignatureError(String),
KeyError(String),
DeltaError(String),
EncryptionError(String),
}
```
- `Io` and `Json` are transparently converted from the underlying error types via `From`.
- `ChecksumMismatch` contains: `(path, expected_hash_or_description, actual_hash)`.
- `EncryptionError` now also carries version mismatch errors (unsupported archive version) in its message.
---
For practical examples, see the [Usage](usage.html) page. For configuration details, check [Configuration](configuration.html).