use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use crate::apply::{ApplyEnv, ApplyReport, Touched, instant_apply};
use crate::env::Env;
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::layering::manifest::manifest_dir;
use crate::layering::{
LOCAL_FILE, Project, ProjectRepo, SHARED_FILE, TrustStore, discover, same_folder, same_path,
};
use crate::model::TomlDocument;
use crate::model::ids::{self, IdKind};
use crate::model::machine::{MachineOverlay, MachineProject};
use crate::model::project::ProjectManifest;
use crate::secrets::catalog::overlay_path;
use crate::store::{CommitId, Machine, Operation, Scope, Store, StoreRead, Transaction};
pub const GITIGNORE: &str = ".gitignore";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Layout {
Private,
Shared,
SharedAndLocal,
}
impl Layout {
pub const fn as_str(self) -> &'static str {
match self {
Layout::Private => "private",
Layout::Shared => "shared",
Layout::SharedAndLocal => "shared+local",
}
}
}
pub fn layout(fs: &dyn Fs, root: &Path) -> Option<Layout> {
let dir = manifest_dir(fs, root);
match (
fs.exists(&dir.join(SHARED_FILE)),
fs.exists(&dir.join(LOCAL_FILE)),
) {
(true, true) => Some(Layout::SharedAndLocal),
(true, false) => Some(Layout::Shared),
(false, true) => Some(Layout::Private),
(false, false) => None,
}
}
#[derive(Debug, Clone)]
pub struct InitPlan {
pub root: PathBuf,
pub id: String,
pub(crate) text: String,
}
#[derive(Debug)]
pub struct Initialized {
pub id: String,
pub file: PathBuf,
pub excluded: Option<PathBuf>,
pub report: Option<ApplyReport>,
pub commit: Option<CommitId>,
}
pub fn prepare_init(
env: &Env,
fs: &dyn Fs,
root: &Path,
name: Option<&str>,
) -> Result<InitPlan, CoreError> {
if same_folder(fs, root, env.home()) {
return Err(CoreError::new(
ErrorCode::InvalidPath,
"a manifest in the home folder would apply to every folder; pick a project folder",
)
.with_path(root));
}
if !fs.is_dir(root) {
return Err(
CoreError::new(ErrorCode::NotFound, "the project folder does not exist")
.with_path(root),
);
}
let dir = manifest_dir(fs, root);
for file in [SHARED_FILE, LOCAL_FILE] {
let existing = dir.join(file);
if fs.exists(&existing) {
return Err(CoreError::new(
ErrorCode::AlreadyExists,
"this folder already has a project manifest; use `project add` or `project trust`",
)
.with_path(existing));
}
}
let folder_name = root
.file_name()
.map(|name| name.to_string_lossy().into_owned())
.unwrap_or_default();
let id = new_project_id(env, &folder_name)?;
let mut manifest = ProjectManifest::new(Some(id.clone()));
manifest.name = Some(
name.map(str::to_owned)
.filter(|name| !name.trim().is_empty())
.unwrap_or_else(|| {
if folder_name.is_empty() {
id.clone()
} else {
folder_name.clone()
}
}),
);
let text = TomlDocument::new(manifest).to_text()?;
Ok(InitPlan {
root: root.to_path_buf(),
id,
text,
})
}
pub fn init(
store: &Store<'_>,
ax: &ApplyEnv<'_>,
plan: InitPlan,
shared: bool,
) -> Result<Initialized, CoreError> {
let fs = ax.fs;
let InitPlan { root, id, text } = plan;
let dir = manifest_dir(fs, &root);
let dir_existed = fs.is_dir(&dir);
let file = dir.join(if shared { SHARED_FILE } else { LOCAL_FILE });
let mut created = vec![file.clone()];
create_dir(fs, &dir)?;
write_file(fs, &file, text.as_bytes())?;
let mut excluded = None;
let staged = (|| {
if shared {
let ignore = dir.join(GITIGNORE);
if !fs.exists(&ignore) {
created.push(ignore.clone());
}
ensure_line(fs, &ignore, LOCAL_FILE)?;
} else {
excluded = exclude_manifest_dir(fs, &root)?;
}
let project = load_project(fs, &root)?;
let summary = format!("project: init {id}");
let touched = Touched::Project(root.clone());
commit_project(
store,
ax,
"project.init",
summary,
&id,
Some(touched),
|tx| {
set_known(tx, fs, &project.id, &root)?;
mirror(tx, &project)?;
save_trust(ax, &project)
},
)
})();
let (report, commit) = match staged {
Ok(done) => done,
Err(err) => {
for path in &created {
let _ = fs.remove_file(path);
}
if !dir_existed && fs.read_dir(&dir).is_ok_and(|entries| entries.is_empty()) {
let _ = fs.remove_dir_all(&dir);
}
return Err(err);
}
};
Ok(Initialized {
id,
file,
excluded,
report,
commit,
})
}
pub fn add(
store: &Store<'_>,
ax: &ApplyEnv<'_>,
project: &Project,
) -> Result<Option<CommitId>, CoreError> {
let id = project.id.clone();
let summary = format!("project: add {id}");
let (_, commit) = commit_project(store, ax, "project.add", summary, &id, None, |tx| {
set_known(tx, ax.fs, &id, &project.root)
})?;
Ok(commit)
}
#[derive(Debug)]
pub struct Removed {
pub root: Option<PathBuf>,
pub report: Option<ApplyReport>,
pub commit: Option<CommitId>,
}
pub fn remove(store: &Store<'_>, ax: &ApplyEnv<'_>, id: &str) -> Result<Removed, CoreError> {
ids::check(IdKind::Project, id)?;
let summary = format!("project: remove {id}");
let mut root = None;
let touched = Some(Touched::All);
let (report, commit) =
commit_project(store, ax, "project.remove", summary, id, touched, |tx| {
let mut doc = overlay_doc(tx)?;
let projects = &mut doc.value_mut().projects;
let known = projects.as_mut().and_then(|map| map.remove(id));
let Some(known) = known else {
return Err(unknown_project(id));
};
if projects.as_ref().is_some_and(BTreeMap::is_empty) {
*projects = None;
}
root = Some(PathBuf::from(known.path));
let relative = overlay_path(&tx.machine().id)?;
tx.write(&relative, doc.to_text()?)?;
let state = ax.home.state_dir();
let mut trust = TrustStore::load(ax.fs, &state)?;
if trust.forget(id) {
trust.save(ax.fs, &state)?;
}
Ok(())
})?;
Ok(Removed {
root,
report,
commit,
})
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ManifestChange {
New,
Changed,
Unchanged,
Removed,
}
impl ManifestChange {
pub const fn as_str(self) -> &'static str {
match self {
ManifestChange::New => "new",
ManifestChange::Changed => "changed",
ManifestChange::Unchanged => "unchanged",
ManifestChange::Removed => "removed",
}
}
}
#[derive(Debug, Clone)]
pub struct ManifestReview {
pub file: &'static str,
pub path: PathBuf,
pub change: ManifestChange,
pub content: Option<String>,
pub diff: Option<String>,
}
pub fn review(
store: &dyn StoreRead,
project: &Project,
trust: &TrustStore,
) -> Result<Vec<ManifestReview>, CoreError> {
let trusted_here = trust.knows(project);
let dir = project.dir();
let mut reviews = Vec::new();
for (file, manifest) in [
(SHARED_FILE, project.shared.as_ref()),
(LOCAL_FILE, project.local.as_ref()),
] {
let trusted = if trusted_here {
store.read_file(&mirror_path(&project.id, file))?
} else {
None
};
let current = manifest.map(|m| String::from_utf8_lossy(&m.bytes).into_owned());
let path = dir.join(file);
let (change, diff) = match (&trusted, ¤t) {
(None, None) => continue,
(None, Some(_)) => (ManifestChange::New, None),
(Some(_), None) => (ManifestChange::Removed, None),
(Some(old), Some(new)) if old == new => (ManifestChange::Unchanged, None),
(Some(old), Some(new)) => {
let diff = similar::TextDiff::from_lines(old.as_str(), new.as_str())
.unified_diff()
.header(&format!("trusted {file}"), &path.display().to_string())
.to_string();
(ManifestChange::Changed, Some(diff))
}
};
reviews.push(ManifestReview {
file,
path,
change,
content: current,
diff,
});
}
Ok(reviews)
}
pub fn trust(
store: &Store<'_>,
ax: &ApplyEnv<'_>,
project: &Project,
expected: Option<&str>,
) -> Result<(Option<ApplyReport>, Option<CommitId>), CoreError> {
if let Some(expected) = expected
&& project.hash() != expected
{
return Err(CoreError::new(
ErrorCode::TrustRequired,
format!(
"the manifests of project {:?} changed after the review; review them again",
project.name()
),
)
.with_path(project.dir()));
}
let id = project.id.clone();
let summary = format!("project: trust {id}");
let touched = Some(Touched::Project(project.root.clone()));
commit_project(store, ax, "project.trust", summary, &id, touched, |tx| {
set_known(tx, ax.fs, &id, &project.root)?;
mirror(tx, project)?;
save_trust(ax, project)
})
}
pub fn commit_project(
store: &Store<'_>,
ax: &ApplyEnv<'_>,
op: &str,
summary: String,
id: &str,
apply: Option<Touched>,
stage: impl FnOnce(&mut Transaction<'_>) -> Result<(), CoreError>,
) -> Result<(Option<ApplyReport>, Option<CommitId>), CoreError> {
let operation = Operation::new(op, summary)
.entity(format!("project/{id}"))
.scope(Scope::Project(id.to_owned()));
let state = ax.home.state_dir();
let previous = TrustStore::load(ax.fs, &state).ok();
let committed = store.transaction(operation, |tx| {
stage(tx)?;
match &apply {
Some(touched) => instant_apply(tx, ax, touched),
None => Ok(None),
}
});
match committed {
Ok(committed) => Ok((committed.value, committed.commit)),
Err(err) => {
if let Some(previous) = previous
&& let Err(restore) = previous.save(ax.fs, &state)
{
let message = format!(
"{}; also, the trust file cannot be restored: {restore}",
err.message()
);
let mut combined = CoreError::new(err.code(), message);
if let Some(path) = err.path() {
combined = combined.with_path(path);
}
return Err(combined);
}
Err(err)
}
}
}
pub fn overlay_doc(tx: &Transaction<'_>) -> Result<TomlDocument<MachineOverlay>, CoreError> {
let machine = tx.machine().clone();
let relative = overlay_path(&machine.id)?;
match tx.read_file(&relative)? {
Some(text) => TomlDocument::parse(&text)
.map_err(|diagnostic| diagnostic.to_core_error(Some(Path::new(&relative)))),
None => Ok(TomlDocument::new(MachineOverlay::new(
&machine.id,
&machine.label,
tx.store().env().os(),
))),
}
}
pub fn set_known(
tx: &mut Transaction<'_>,
fs: &dyn Fs,
id: &str,
root: &Path,
) -> Result<(), CoreError> {
let mut doc = overlay_doc(tx)?;
let projects = doc.value_mut().projects.get_or_insert_with(BTreeMap::new);
if let Some(known) = projects.get(id) {
let other = Path::new(&known.path);
let checkout = !same_path(other, root)
&& matches!(Project::load(fs, other), Ok(Some(project)) if project.id == id);
if checkout {
return Err(CoreError::new(
ErrorCode::AlreadyExists,
format!(
"project {id:?} is already known at {}, which still holds its manifest; \
one machine applies a project from one folder. To use {} instead, run \
`{} project rm {id}` first",
other.display(),
root.display(),
crate::brand::BIN_NAME,
),
)
.with_path(root));
}
}
projects.retain(|known, project| known == id || !same_path(Path::new(&project.path), root));
let path = root.to_string_lossy().into_owned();
projects
.entry(id.to_owned())
.and_modify(|project| project.path.clone_from(&path))
.or_insert_with(|| MachineProject {
path,
extra: toml::Table::new(),
});
let relative = overlay_path(&tx.machine().id)?;
tx.write(&relative, doc.to_text()?)
}
pub fn this_overlay(
store: &Store<'_>,
fs: &dyn Fs,
state_dir: &Path,
) -> Result<Option<MachineOverlay>, CoreError> {
let Some(machine) = Machine::load(fs, state_dir)? else {
return Ok(None);
};
let relative = overlay_path(&machine.id)?;
let Some(text) = store.read_to_string(&relative)? else {
return Ok(None);
};
TomlDocument::<MachineOverlay>::parse(&text)
.map(|doc| Some(doc.into_value()))
.map_err(|diagnostic| diagnostic.to_core_error(Some(Path::new(&relative))))
}
fn mirror_path(id: &str, file: &str) -> String {
format!("projects/{id}/{file}")
}
pub fn mirror(tx: &mut Transaction<'_>, project: &Project) -> Result<(), CoreError> {
for (file, manifest) in [
(SHARED_FILE, project.shared.as_ref()),
(LOCAL_FILE, project.local.as_ref()),
] {
let relative = mirror_path(&project.id, file);
match manifest {
Some(manifest) => tx.write(&relative, manifest.bytes.clone())?,
None if tx.exists(&relative)? => tx.remove(&relative)?,
None => {}
}
}
Ok(())
}
pub fn save_trust(ax: &ApplyEnv<'_>, project: &Project) -> Result<(), CoreError> {
let state = ax.home.state_dir();
let mut trust = TrustStore::load(ax.fs, &state)?;
trust.trust(project);
trust.save(ax.fs, &state)
}
pub fn load_project(fs: &dyn Fs, root: &Path) -> Result<Project, CoreError> {
Project::load(fs, root)?.ok_or_else(|| {
CoreError::new(ErrorCode::NotFound, "the folder has no project manifest")
.with_path(manifest_dir(fs, root))
})
}
pub fn project_root(
store: Option<&Store<'_>>,
ax: &ApplyEnv<'_>,
folder: &Path,
) -> Result<PathBuf, CoreError> {
let root = discover(ax.env, ax.fs, folder).ok_or_else(|| {
CoreError::new(
ErrorCode::NotFound,
"no project manifest (.surjection/project.toml or .surjection/project.local.toml) at or \
above this folder",
)
.with_path(folder)
})?;
let overlay = match store {
Some(store) => this_overlay(store, ax.fs, &ax.home.state_dir())?,
None => None,
};
let known = overlay
.iter()
.flat_map(|overlay| overlay.projects.iter().flatten())
.map(|(_, project)| PathBuf::from(&project.path))
.find(|known| same_path(known, &root));
Ok(known.unwrap_or(root))
}
pub fn new_project_id(env: &Env, folder_name: &str) -> Result<String, CoreError> {
let mut slug = String::new();
for ch in folder_name.chars().flat_map(char::to_lowercase) {
if ch.is_ascii_lowercase() || ch.is_ascii_digit() {
slug.push(ch);
} else if !slug.is_empty() && !slug.ends_with('-') {
slug.push('-');
}
}
slug.truncate(ids::MAX_ID_LEN - 5);
let slug = slug.trim_end_matches('-');
let slug = if slug.is_empty() { "project" } else { slug };
let random = ids::new_ulid(env.now())?;
let suffix = random[random.len() - 4..].to_ascii_lowercase();
let id = format!("{slug}-{suffix}");
ids::check(IdKind::Project, &id)?;
Ok(id)
}
pub fn exclude_manifest_dir(fs: &dyn Fs, root: &Path) -> Result<Option<PathBuf>, CoreError> {
let Some((repo, pattern)) = manifest_dir_pattern(fs, root)? else {
return Ok(None);
};
if repo.is_ignored(&manifest_dir(fs, root).join(LOCAL_FILE))? {
return Ok(None);
}
let file = repo.exclude_file();
Ok(ensure_line(fs, &file, &pattern)?.then_some(file))
}
pub fn unexclude_manifest_dir(fs: &dyn Fs, root: &Path) -> Result<Option<String>, CoreError> {
let Some((repo, pattern)) = manifest_dir_pattern(fs, root)? else {
return Ok(None);
};
let file = repo.exclude_file();
if let Some(text) = read_optional(fs, &file)?
&& text.lines().any(|line| line.trim() == pattern)
{
let kept: String = text
.lines()
.filter(|line| line.trim() != pattern)
.map(|line| format!("{line}\n"))
.collect();
write_file(fs, &file, kept.as_bytes())?;
}
let shared = manifest_dir(fs, root).join(SHARED_FILE);
Ok(Some(if repo.is_ignored(&shared)? {
format!(
"{} is ignored by git; change the ignore rules to commit it",
shared.display()
)
} else {
format!("commit {} with the project", shared.display())
}))
}
fn manifest_dir_pattern(
fs: &dyn Fs,
root: &Path,
) -> Result<Option<(ProjectRepo, String)>, CoreError> {
let Some(repo) = ProjectRepo::discover(root)? else {
return Ok(None);
};
Ok(repo
.relative(&manifest_dir(fs, root))
.map(|relative| (repo, format!("/{relative}/"))))
}
pub fn ensure_line(fs: &dyn Fs, path: &Path, line: &str) -> Result<bool, CoreError> {
let mut text = read_optional(fs, path)?.unwrap_or_default();
if text.lines().any(|existing| existing.trim() == line) {
return Ok(false);
}
if !text.is_empty() && !text.ends_with('\n') {
text.push('\n');
}
text.push_str(line);
text.push('\n');
if let Some(dir) = path.parent() {
create_dir(fs, dir)?;
}
write_file(fs, path, text.as_bytes())?;
Ok(true)
}
pub fn read_optional(fs: &dyn Fs, path: &Path) -> Result<Option<String>, CoreError> {
if !fs.exists(path) {
return Ok(None);
}
fs.read_to_string(path).map(Some).map_err(|err| {
CoreError::new(ErrorCode::IoError, format!("cannot read file: {err}")).with_path(path)
})
}
pub fn write_file(fs: &dyn Fs, path: &Path, bytes: &[u8]) -> Result<(), CoreError> {
fs.write(path, bytes)
.map_err(|err| crate::access::write_error(fs, "cannot write file", path, &err))
}
pub(crate) fn create_dir(fs: &dyn Fs, dir: &Path) -> Result<(), CoreError> {
fs.create_dir_all(dir)
.map_err(|err| crate::access::write_error(fs, "cannot create directory", dir, &err))
}
pub fn unknown_project(id: &str) -> CoreError {
CoreError::new(
ErrorCode::NotFound,
format!("project {id:?} is not known on this machine"),
)
}