//! A repository's config frame and the settings resolved through it: reading
//! the frame, the field-preserving write every verb that changes a repository
//! value goes through, and the tiered settings read (versioned file,
//! environment, repository, global file) the verbs share. No CLI.
const std = @import("std");
const logstore = @import("../logstore.zig");
const openLogAdoptingIndex = @import("log_index_store.zig").openLogAdoptingIndex;
const settings = @import("../settings.zig");
const storage = @import("../storage.zig");
const store_open = @import("store_open.zig");
const sync = @import("../sync.zig");
/// The fields a `updateConfig` overlay may change; a null field is left exactly
/// as the stored config has it. Naming a single change site keeps the "copy the
/// whole config, overlay one field" discipline in one place — a caller that
/// means to change only the project code can never silently drop the credential
/// or the saved remote (the class of bug the pre-`updateConfig` re-puts had).
pub const ConfigPatch = struct {
project_code: ?[]const u8 = null,
login: ?sync.Credential = null,
/// Forget the stored login. A login belongs to the saved remote, so a
/// change of remote drops it in the same frame.
clear_login: bool = false,
remote_url: ?[]const u8 = null,
/// draft-fossil-submanifests-00 §6.3/§8.1 and §6.4 — the three
/// project-scope settings sync §9.3's scalar channel carries. Optional for
/// the same reason every field here is: a peer that named only one of them
/// must leave the other two exactly as stored.
enable_submanifests: ?bool = null,
submanifest_k: ?u8 = null,
submanifest_auto_retune: ?bool = null,
/// The autosync setting, stored inverted (true = off). Local, like
/// `remote_url`; only the settings verb writes it.
autosync_off: ?bool = null,
ignore_glob: ?[]const u8 = null,
/// The two signing settings, both LOCAL and both deliberately
/// outside every config group: fossil classifies `pgp-command` sensitive
/// (it is a command line a peer would otherwise get to choose) and puts
/// `clearsign` in no group at all.
clearsign: ?bool = null,
pgp_command: ?[]const u8 = null,
/// The rest of fossil's checkout settings at the repository tier.
crnl_glob: ?[]const u8 = null,
clean_glob: ?[]const u8 = null,
empty_dirs: ?[]const u8 = null,
encoding_glob: ?[]const u8 = null,
dotfiles: ?[]const u8 = null,
mimetypes: ?[]const u8 = null,
attachment_size_limit: ?[]const u8 = null,
/// `zit git export`'s remembered mirror.
git_mirror: ?[]const u8 = null,
git_autopush: ?[]const u8 = null,
git_push_branch: ?[]const u8 = null,
git_email_domain_local: ?[]const u8 = null,
/// The repository's Git email domain, project scope like the three
/// sub-manifest settings above and carried by the same §9.3 channel.
git_email_domain: ?[]const u8 = null,
/// `main-branch`.
default_branch: ?[]const u8 = null,
/// The explicit-set bits, which are what make "this repository has no
/// opinion" representable and therefore let the global tier be reached.
autosync_set: ?bool = null,
clearsign_set: ?bool = null,
repo_cksum_off: ?bool = null,
repo_cksum_set: ?bool = null,
keep_glob: ?[]const u8 = null,
manifest: ?[]const u8 = null,
before_commit: ?[]const u8 = null,
/// The two content-policy globs. Data settings, so a tracked
/// `.zit-settings/` file outranks whatever is stored here.
binary_glob: ?[]const u8 = null,
crlf_glob: ?[]const u8 = null,
/// The consent record. Empty string is a real value here (revoke),
/// so it is written whenever the field is present, not when non-empty.
before_commit_trust: ?[]const u8 = null,
editor: ?[]const u8 = null,
autosync_mode: ?[]const u8 = null,
pub fn any(self: ConfigPatch) bool {
return self.project_code != null or
self.login != null or
self.clear_login or
self.remote_url != null or
self.enable_submanifests != null or
self.submanifest_k != null or
self.submanifest_auto_retune != null or
self.git_email_domain != null or
self.autosync_off != null or
self.ignore_glob != null or
self.clearsign != null or
self.pgp_command != null or
self.autosync_set != null or
self.clearsign_set != null or
self.repo_cksum_off != null or
self.repo_cksum_set != null or
self.keep_glob != null or
self.manifest != null or
self.before_commit != null or
self.before_commit_trust != null or
self.binary_glob != null or
self.crlf_glob != null or
self.editor != null or
self.autosync_mode != null;
}
};
/// Read the live config from an already-open log, overlay `patch`, and append
/// the result while preserving every unnamed field. The caller owns durability,
/// so a clone can combine its origin settings in one config frame and commit
/// its complete result once.
pub fn updateConfigOpen(
gpa: std.mem.Allocator,
log: *logstore.LogStore,
patch: ConfigPatch,
) PersistError!void {
var oc = (log.readConfig(gpa) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
error.Storage => return error.Storage,
error.Corrupt => return error.Corrupt,
}) orelse return error.Corrupt; // init always writes a config frame
defer oc.deinit(gpa);
// Copy every field, then overlay only the named ones. `next`'s string slices
// borrow `oc.backing` / `patch`; both outlive the `putConfig` memcpy below.
var next = oc.config;
if (patch.project_code) |c| next.project_code = c;
std.debug.assert(!(patch.clear_login and patch.login != null));
if (patch.clear_login) {
next.login_user = "";
next.login_secret_hex = "";
}
if (patch.login) |cred| {
next.login_user = cred.user;
// Point at the function-scoped `patch` storage, not the block-local
// capture `cred`: `next` is read by `putConfig` after this block closes.
next.login_secret_hex = &patch.login.?.secret_hex;
}
if (patch.remote_url) |u| next.remote_url = u;
if (patch.enable_submanifests) |v| next.enable_submanifests = v;
if (patch.submanifest_k) |v| next.submanifest_k = v;
if (patch.submanifest_auto_retune) |v| next.submanifest_auto_retune = v;
if (patch.autosync_off) |v| next.autosync_off = v;
if (patch.ignore_glob) |v| next.ignore_glob = v;
if (patch.clearsign) |v| next.clearsign = v;
if (patch.pgp_command) |v| next.pgp_command = v;
if (patch.autosync_set) |v| next.autosync_set = v;
if (patch.clearsign_set) |v| next.clearsign_set = v;
if (patch.repo_cksum_off) |v| next.repo_cksum_off = v;
if (patch.repo_cksum_set) |v| next.repo_cksum_set = v;
if (patch.keep_glob) |v| next.keep_glob = v;
if (patch.manifest) |v| next.manifest = v;
if (patch.before_commit) |v| next.before_commit = v;
if (patch.before_commit_trust) |v| next.before_commit_trust = v;
if (patch.binary_glob) |v| next.binary_glob = v;
if (patch.crlf_glob) |v| next.crlf_glob = v;
if (patch.editor) |v| next.editor = v;
if (patch.autosync_mode) |v| next.autosync_mode = v;
if (patch.crnl_glob) |v| next.crnl_glob = v;
if (patch.clean_glob) |v| next.clean_glob = v;
if (patch.empty_dirs) |v| next.empty_dirs = v;
if (patch.encoding_glob) |v| next.encoding_glob = v;
if (patch.dotfiles) |v| next.dotfiles = v;
if (patch.mimetypes) |v| next.mimetypes = v;
if (patch.attachment_size_limit) |v| next.attachment_size_limit = v;
if (patch.git_mirror) |v| next.git_mirror = v;
if (patch.git_autopush) |v| next.git_autopush = v;
if (patch.git_email_domain) |v| next.git_email_domain = v;
if (patch.git_email_domain_local) |v| next.git_email_domain_local = v;
if (patch.git_push_branch) |v| next.git_push_branch = v;
if (patch.default_branch) |v| next.default_branch = v;
log.putConfig(next) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
error.Storage => return error.Storage,
};
}
/// Open `dir/.zit` for a field-preserving config update, retaining the legacy
/// wrapper for pull, sync, serve, and remote callers that do not already own a
/// writable log.
pub fn updateConfig(
gpa: std.mem.Allocator,
io: std.Io,
dir: std.Io.Dir,
patch: ConfigPatch,
) PersistLockedError!void {
var store_append = store_open.openStoreAppend(io, dir) catch |e| switch (e) {
error.StoreBusy => return error.StoreBusy,
else => return error.Storage,
};
defer store_append.close(io);
const file = store_append.file;
const st = file.stat(io) catch return error.Storage;
var fs = storage.FileStorage.init(io, file, st.size);
var log = logstore.LogStore.open(gpa, fs.storageFile(), 0) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
error.Storage => return error.Storage,
error.Corrupt => return error.Corrupt,
};
defer log.deinit(gpa);
try updateConfigOpen(gpa, &log, patch);
log.commit() catch return error.Storage;
}
/// The closed error set of `persistStore`: memory, a storage write fault, or a
/// corrupt/oversized peer artifact name that will not decode to a log key.
pub const PersistError = error{ OutOfMemory, Storage, Corrupt };
/// The persist paths that take the writer lock themselves. `StoreBusy`:
/// another writer held it past the wait; stderr already names it, so a
/// caller reports nothing more.
pub const PersistLockedError = PersistError || error{StoreBusy};
/// Open this checkout's store, read its config ONCE, and hand back the owned
/// result; null on any failure, exactly as every reader of an optional
/// repository value degrades today. `.read_only`, because the listing verbs
/// are pinned tree-untouching (B-extras-16) and must never mint a sidecar.
/// The `OwnedConfig` owns its backing bytes, so the log and its file are
/// closed here and the config outlives them.
pub fn readRepositoryConfig(
gpa: std.mem.Allocator,
io: std.Io,
root_dir: std.Io.Dir,
) ?logstore.OwnedConfig {
var file = store_open.openStoreRead(io, root_dir) catch return null;
defer file.close(io);
const st = file.stat(io) catch return null;
var fs = storage.FileStorage.init(io, file, st.size);
// Indexed open: this config read rides every extras/clean/
// addremove listing, each of which was paying its own full header scan.
var log = openLogAdoptingIndex(gpa, io, root_dir, fs.storageFile(), .read_only) catch return null;
defer log.deinit(gpa);
return log.readConfig(gpa) catch null;
}
/// What the settings read takes from the process: its environment, which
/// supplies the environment tier and locates the global settings file. The
/// CLI builds it from its `Ambient`.
pub const SettingsAmbient = struct {
environ: std.process.Environ,
};
/// Keep a pending import distinct from storage failure through sync paths.
pub fn storeOpenError(e: anyerror) error{ Storage, ImportRecoveryRequired } {
return if (e == error.ImportRecoveryRequired) error.ImportRecoveryRequired else error.Storage;
}
/// Gather every tier's answer and apply `settings.resolve`. The reads live here
/// -- the model module stays sans-IO so precedence is a pure, tested function.
/// Public so the COMMIT path resolves signing settings through the same
/// precedence a listing reports. They must never disagree: a `zit settings`
/// that says `clearsign on` while the commit quietly does not sign is worse
/// than having no global tier at all.
pub fn resolveSetting(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
root_dir: std.Io.Dir,
amb: SettingsAmbient,
setting: settings.Setting,
) !settings.Resolved {
const repository = try repositorySetting(gpa, io, arena, root_dir, setting);
return resolveSettingWith(io, arena, root_dir, amb, setting, repository);
}
/// The effective `crlf-glob`, with fossil's older `crnl-glob` as the
/// fallback SPELLING of the same setting. fossil reads
/// `db_get("crlf-glob", db_get("crnl-glob",""))` (checkin.c), so `crnl-glob`
/// is consulted only when no tier supplies `crlf-glob` at all -- a stored
/// empty `crlf-glob` is a value and wins, exactly as it does for every other
/// glob list.
///
/// The COMMIT gate only. The wire twin (`sync.PushPolicy`, built from the
/// serve-side snapshot) keeps reading `crlf-glob` alone: fossil's server never
/// gates content, so there is no parity to mirror there.
/// `config` is the caller's already-read frame, as for `localSetting`: the
/// commit gate holds the store's write lock and reads its config once, so both
/// spellings answer from that one frame rather than re-opening the store twice.
pub fn resolveCrlfGlob(
io: std.Io,
arena: std.mem.Allocator,
root_dir: std.Io.Dir,
amb: SettingsAmbient,
config: ?*const logstore.Config,
) error{OutOfMemory}!settings.Resolved {
const crlf = try localSetting(io, arena, root_dir, amb, config, .crlf_glob);
if (crlf.source != .default) return crlf;
return localSetting(io, arena, root_dir, amb, config, .crnl_glob);
}
/// `resolveSetting` with the REPOSITORY tier supplied by the caller instead of
/// read here. `repositorySetting` opens the store and pays a full frame-header
/// scan to reach one config frame -- fine for a one-shot verb, ruinous in the
/// serve loop, where it turned every round of a large-store clone into seconds
/// of dead re-scanning. The server passes the values its per-round
/// snapshot already read; every other tier is a cheap local read and stays
/// here, so the resolution order cannot fork between the two paths.
pub fn resolveSettingWith(
io: std.Io,
arena: std.mem.Allocator,
root_dir: std.Io.Dir,
amb: SettingsAmbient,
setting: settings.Setting,
repository: ?[]const u8,
) !settings.Resolved {
const zset = settings;
var c: zset.Candidates = .{};
// The versioned file is read ONLY for a versionable setting. `resolve`
// enforces the same rule, so this is belt and braces on the boundary that
// keeps a cloned repository from choosing what this machine executes.
if (setting.versionable()) {
// fossil's spelling first, zit's as the fallback -- a mirrored
// Fossil repository's own policy is honoured without adopting zit's
// directory name, and when both exist the fossil file wins.
// Two buffers: the candidates are materialized before the loop, and a
// shared buffer would leave the first slice pointing at the second's
// bytes.
var fossil_buf: [128]u8 = undefined;
var zit_buf: [128]u8 = undefined;
const candidates = .{ setting.fossilVersionedPath(&fossil_buf), setting.versionedPath(&zit_buf) };
const dirs = [_]zset.VersionedDir{ .fossil, .zit };
inline for (candidates, 0..) |maybe_path, i| {
if (c.versioned == null) {
if (maybe_path) |path| {
if (root_dir.readFileAlloc(io, path, arena, .limited(zset.max_versioned_bytes))) |text| {
// fossil's `db_get_versioned` strips `#` lines
// and trims before anything reads the value, so every
// versionable setting -- in either directory -- gets
// the same treatment from the one reader.
c.versioned = zset.stripCommentLines(text);
c.versioned_dir = dirs[i];
} else |_| {}
}
}
}
}
return resolveSettingTiers(io, arena, amb, setting, &c, repository);
}
/// The environment, repository and global tiers on top of an already-read
/// versioned candidate -- the tail both readers above share, so the order the
/// tiers are consulted in cannot fork between them.
pub fn resolveSettingTiers(
io: std.Io,
arena: std.mem.Allocator,
amb: SettingsAmbient,
setting: settings.Setting,
c: *settings.Candidates,
repository: ?[]const u8,
) !settings.Resolved {
if (setting.envVar()) |name| c.environment = amb.environ.getPosix(name);
c.repository = repository;
// A repository-tier setting has no global value to fall back to.
c.global = if (setting.tier() == .repository) null else try globalSetting(io, arena, amb, setting);
return settings.resolve(setting, c.*);
}
/// Open this checkout's store read-only for a one-shot config read, adopting
/// the persisted scan index when the cache holds a fresh one (the CLI
/// half). The plain `openReadOnly` walks every frame header, which `open` and
/// `update` were paying once per setting on every materialization. A
/// refused index (absent, stale, corrupt) falls back to the scan and refreshes
/// the sidecar, as `Repository.logStore` does. The sidecar lives with the
/// STORE, never a worktree, so the cache directory is resolved through the
/// checkout's store pointer first.
const OpenedStoreLog = struct {
file: std.Io.File,
fs: storage.FileStorage,
log: logstore.LogStore,
pub fn close(self: *OpenedStoreLog, gpa: std.mem.Allocator, io: std.Io) void {
self.log.deinit(gpa);
self.file.close(io);
gpa.destroy(self);
}
};
/// Heap-allocated: the log holds a pointer into `fs`, so the record must
/// never move after `storageFile()` is taken.
pub fn openStoreLogForRead(gpa: std.mem.Allocator, io: std.Io, root_dir: std.Io.Dir) !*OpenedStoreLog {
var file = store_open.openStoreRead(io, root_dir) catch |e| return storeOpenError(e);
errdefer file.close(io);
const st = file.stat(io) catch return error.Storage;
const out = gpa.create(OpenedStoreLog) catch return error.OutOfMemory;
errdefer gpa.destroy(out);
out.* = .{ .file = file.file, .fs = storage.FileStorage.init(io, file, st.size), .log = undefined };
out.log = openLogAdoptingIndex(gpa, io, root_dir, out.fs.storageFile(), .refresh_on_scan) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.Storage,
};
return out;
}
/// This repository's stored answer, or null when it has no opinion. The
/// booleans consult their explicit-set bit: without it a repository would
/// always have an opinion and the global tier could never be reached.
fn repositorySetting(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
root_dir: std.Io.Dir,
setting: settings.Setting,
) !?[]const u8 {
const opened = try openStoreLogForRead(gpa, io, root_dir);
defer opened.close(gpa, io);
var oc = (opened.log.readConfig(gpa) catch |e| switch (e) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.Storage,
}) orelse return null;
defer oc.deinit(gpa);
return configValue(arena, &oc.config, setting);
}
/// One config frame's answer for one setting, or null when the frame has no
/// opinion. PURE: the caller supplies the frame, so a verb that has already
/// read `Config` once resolves every name it needs without a second store
/// open (now the rule rather than the exception). The arena
/// dupe is the only way this can fail.
pub fn configValue(
arena: std.mem.Allocator,
config: *const logstore.Config,
setting: settings.Setting,
) error{OutOfMemory}!?[]const u8 {
return switch (setting) {
.autosync => if (config.autosync_set)
(if (config.autosync_off) "off" else if (std.mem.eql(u8, config.autosync_mode, "pullonly")) "pullonly" else "on")
else
null,
.editor => if (config.editor.len == 0) null else try arena.dupe(u8, config.editor),
.clearsign => if (config.clearsign_set)
(if (config.clearsign) "on" else "off")
else
null,
.repo_cksum => if (config.repo_cksum_set)
(if (config.repo_cksum_off) "off" else "on")
else
null,
// A stored empty string is "no opinion" for these: the config frame has
// no separate absent marker for its string fields, and an operator who
// wants the empty value spells it by clearing, which is the same thing.
.ignore_glob => if (config.ignore_glob.len == 0) null else try arena.dupe(u8, config.ignore_glob),
.pgp_command => if (config.pgp_command.len == 0) null else try arena.dupe(u8, config.pgp_command),
.keep_glob => if (config.keep_glob.len == 0) null else try arena.dupe(u8, config.keep_glob),
.manifest => if (config.manifest.len == 0) null else try arena.dupe(u8, config.manifest),
.before_commit => if (config.before_commit.len == 0) null else try arena.dupe(u8, config.before_commit),
.binary_glob => if (config.binary_glob.len == 0) null else try arena.dupe(u8, config.binary_glob),
.crlf_glob => if (config.crlf_glob.len == 0) null else try arena.dupe(u8, config.crlf_glob),
.crnl_glob => if (config.crnl_glob.len == 0) null else try arena.dupe(u8, config.crnl_glob),
.clean_glob => if (config.clean_glob.len == 0) null else try arena.dupe(u8, config.clean_glob),
.empty_dirs => if (config.empty_dirs.len == 0) null else try arena.dupe(u8, config.empty_dirs),
.encoding_glob => if (config.encoding_glob.len == 0) null else try arena.dupe(u8, config.encoding_glob),
.dotfiles => if (config.dotfiles.len == 0) null else try arena.dupe(u8, config.dotfiles),
.mimetypes => if (config.mimetypes.len == 0) null else try arena.dupe(u8, config.mimetypes),
.attachment_size_limit => if (config.attachment_size_limit.len == 0) null else try arena.dupe(u8, config.attachment_size_limit),
// `init` stores the default explicitly, so a stored `trunk` says no
// more than the default does; reporting it as the default keeps
// `--changed` meaning "this repository chose something else".
.main_branch => if (config.default_branch.len == 0 or std.mem.eql(u8, config.default_branch, settings.Setting.main_branch.default())) null else try arena.dupe(u8, config.default_branch),
};
}
/// Resolve one setting from a config the caller already holds. The whole job
/// is to make "resolve a name from the frame in my hand" one call, so a verb
/// that reads `Config` once can answer for every name it needs.
///
/// The error set is written out rather than inferred: `resolveSettingWith`'s
/// own failures are all `catch return null`, so `configValue`'s arena dupe is
/// the only thing left that can fail. The day a read there stops degrading,
/// the compiler names it at this boundary.
pub fn localSetting(
io: std.Io,
arena: std.mem.Allocator,
root_dir: std.Io.Dir,
amb: SettingsAmbient,
config: ?*const logstore.Config,
setting: settings.Setting,
) error{OutOfMemory}!settings.Resolved {
const repository = if (config) |c| try configValue(arena, c, setting) else null;
return resolveSettingWith(io, arena, root_dir, amb, setting, repository);
}
/// The operator-scope answer, or null when there is no global file or it says
/// nothing about this setting. A missing file is never an error: no global
/// tier is the state of every installation that never set one.
fn globalSetting(
io: std.Io,
arena: std.mem.Allocator,
amb: SettingsAmbient,
setting: settings.Setting,
) !?[]const u8 {
const zset = settings;
var path_buf: [1024]u8 = undefined;
const g = zset.globalPath(amb.environ, &path_buf) orelse return null;
const text = std.Io.Dir.cwd().readFileAlloc(io, g.path, arena, .limited(zset.max_versioned_bytes)) catch return null;
const found = zset.globalLookup(text, setting) orelse return null;
return found;
}