1use std::collections::BTreeMap;
13use std::path::{Path, PathBuf};
14
15use crate::apply::{ApplyEnv, ApplyReport, Touched, instant_apply};
16use crate::env::Env;
17use crate::error::{CoreError, ErrorCode};
18use crate::fs::Fs;
19use crate::layering::manifest::manifest_dir;
20use crate::layering::{
21 LOCAL_FILE, Project, ProjectRepo, SHARED_FILE, TrustStore, discover, same_folder, same_path,
22};
23use crate::model::TomlDocument;
24use crate::model::ids::{self, IdKind};
25use crate::model::machine::{MachineOverlay, MachineProject};
26use crate::model::project::ProjectManifest;
27use crate::secrets::catalog::overlay_path;
28use crate::store::{CommitId, Machine, Operation, Scope, Store, StoreRead, Transaction};
29
30pub const GITIGNORE: &str = ".gitignore";
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Layout {
37 Private,
39 Shared,
41 SharedAndLocal,
43}
44
45impl Layout {
46 pub const fn as_str(self) -> &'static str {
47 match self {
48 Layout::Private => "private",
49 Layout::Shared => "shared",
50 Layout::SharedAndLocal => "shared+local",
51 }
52 }
53}
54
55pub fn layout(fs: &dyn Fs, root: &Path) -> Option<Layout> {
57 let dir = manifest_dir(fs, root);
58 match (
59 fs.exists(&dir.join(SHARED_FILE)),
60 fs.exists(&dir.join(LOCAL_FILE)),
61 ) {
62 (true, true) => Some(Layout::SharedAndLocal),
63 (true, false) => Some(Layout::Shared),
64 (false, true) => Some(Layout::Private),
65 (false, false) => None,
66 }
67}
68
69#[derive(Debug, Clone)]
71pub struct InitPlan {
72 pub root: PathBuf,
73 pub id: String,
74 pub(crate) text: String,
75}
76
77#[derive(Debug)]
79pub struct Initialized {
80 pub id: String,
81 pub file: PathBuf,
83 pub excluded: Option<PathBuf>,
86 pub report: Option<ApplyReport>,
87 pub commit: Option<CommitId>,
88}
89
90pub fn prepare_init(
93 env: &Env,
94 fs: &dyn Fs,
95 root: &Path,
96 name: Option<&str>,
97) -> Result<InitPlan, CoreError> {
98 if same_folder(fs, root, env.home()) {
99 return Err(CoreError::new(
100 ErrorCode::InvalidPath,
101 "a manifest in the home folder would apply to every folder; pick a project folder",
102 )
103 .with_path(root));
104 }
105 if !fs.is_dir(root) {
106 return Err(
107 CoreError::new(ErrorCode::NotFound, "the project folder does not exist")
108 .with_path(root),
109 );
110 }
111 let dir = manifest_dir(fs, root);
112 for file in [SHARED_FILE, LOCAL_FILE] {
113 let existing = dir.join(file);
114 if fs.exists(&existing) {
115 return Err(CoreError::new(
116 ErrorCode::AlreadyExists,
117 "this folder already has a project manifest; use `project add` or `project trust`",
118 )
119 .with_path(existing));
120 }
121 }
122 let folder_name = root
123 .file_name()
124 .map(|name| name.to_string_lossy().into_owned())
125 .unwrap_or_default();
126 let id = new_project_id(env, &folder_name)?;
127 let mut manifest = ProjectManifest::new(Some(id.clone()));
128 manifest.name = Some(
129 name.map(str::to_owned)
130 .filter(|name| !name.trim().is_empty())
131 .unwrap_or_else(|| {
132 if folder_name.is_empty() {
133 id.clone()
134 } else {
135 folder_name.clone()
136 }
137 }),
138 );
139 let text = TomlDocument::new(manifest).to_text()?;
140 Ok(InitPlan {
141 root: root.to_path_buf(),
142 id,
143 text,
144 })
145}
146
147pub fn init(
153 store: &Store<'_>,
154 ax: &ApplyEnv<'_>,
155 plan: InitPlan,
156 shared: bool,
157) -> Result<Initialized, CoreError> {
158 let fs = ax.fs;
159 let InitPlan { root, id, text } = plan;
160 let dir = manifest_dir(fs, &root);
161 let dir_existed = fs.is_dir(&dir);
162 let file = dir.join(if shared { SHARED_FILE } else { LOCAL_FILE });
163 let mut created = vec![file.clone()];
164 create_dir(fs, &dir)?;
165 write_file(fs, &file, text.as_bytes())?;
166 let mut excluded = None;
167 let staged = (|| {
168 if shared {
169 let ignore = dir.join(GITIGNORE);
170 if !fs.exists(&ignore) {
171 created.push(ignore.clone());
172 }
173 ensure_line(fs, &ignore, LOCAL_FILE)?;
174 } else {
175 excluded = exclude_manifest_dir(fs, &root)?;
176 }
177 let project = load_project(fs, &root)?;
178 let summary = format!("project: init {id}");
179 let touched = Touched::Project(root.clone());
180 commit_project(
181 store,
182 ax,
183 "project.init",
184 summary,
185 &id,
186 Some(touched),
187 |tx| {
188 set_known(tx, fs, &project.id, &root)?;
189 mirror(tx, &project)?;
190 save_trust(ax, &project)
191 },
192 )
193 })();
194 let (report, commit) = match staged {
195 Ok(done) => done,
196 Err(err) => {
197 for path in &created {
199 let _ = fs.remove_file(path);
200 }
201 if !dir_existed && fs.read_dir(&dir).is_ok_and(|entries| entries.is_empty()) {
202 let _ = fs.remove_dir_all(&dir);
203 }
204 return Err(err);
205 }
206 };
207 Ok(Initialized {
208 id,
209 file,
210 excluded,
211 report,
212 commit,
213 })
214}
215
216pub fn add(
219 store: &Store<'_>,
220 ax: &ApplyEnv<'_>,
221 project: &Project,
222) -> Result<Option<CommitId>, CoreError> {
223 let id = project.id.clone();
224 let summary = format!("project: add {id}");
225 let (_, commit) = commit_project(store, ax, "project.add", summary, &id, None, |tx| {
226 set_known(tx, ax.fs, &id, &project.root)
227 })?;
228 Ok(commit)
229}
230
231#[derive(Debug)]
233pub struct Removed {
234 pub root: Option<PathBuf>,
236 pub report: Option<ApplyReport>,
237 pub commit: Option<CommitId>,
238}
239
240pub fn remove(store: &Store<'_>, ax: &ApplyEnv<'_>, id: &str) -> Result<Removed, CoreError> {
243 ids::check(IdKind::Project, id)?;
244 let summary = format!("project: remove {id}");
245 let mut root = None;
246 let touched = Some(Touched::All);
249 let (report, commit) =
250 commit_project(store, ax, "project.remove", summary, id, touched, |tx| {
251 let mut doc = overlay_doc(tx)?;
252 let projects = &mut doc.value_mut().projects;
253 let known = projects.as_mut().and_then(|map| map.remove(id));
254 let Some(known) = known else {
255 return Err(unknown_project(id));
256 };
257 if projects.as_ref().is_some_and(BTreeMap::is_empty) {
258 *projects = None;
259 }
260 root = Some(PathBuf::from(known.path));
261 let relative = overlay_path(&tx.machine().id)?;
262 tx.write(&relative, doc.to_text()?)?;
263 let state = ax.home.state_dir();
264 let mut trust = TrustStore::load(ax.fs, &state)?;
265 if trust.forget(id) {
266 trust.save(ax.fs, &state)?;
267 }
268 Ok(())
269 })?;
270 Ok(Removed {
271 root,
272 report,
273 commit,
274 })
275}
276
277#[derive(Debug, Clone, Copy, PartialEq, Eq)]
279pub enum ManifestChange {
280 New,
281 Changed,
282 Unchanged,
283 Removed,
284}
285
286impl ManifestChange {
287 pub const fn as_str(self) -> &'static str {
288 match self {
289 ManifestChange::New => "new",
290 ManifestChange::Changed => "changed",
291 ManifestChange::Unchanged => "unchanged",
292 ManifestChange::Removed => "removed",
293 }
294 }
295}
296
297#[derive(Debug, Clone)]
299pub struct ManifestReview {
300 pub file: &'static str,
302 pub path: PathBuf,
303 pub change: ManifestChange,
304 pub content: Option<String>,
306 pub diff: Option<String>,
309}
310
311pub fn review(
314 store: &dyn StoreRead,
315 project: &Project,
316 trust: &TrustStore,
317) -> Result<Vec<ManifestReview>, CoreError> {
318 let trusted_here = trust.knows(project);
322 let dir = project.dir();
323 let mut reviews = Vec::new();
324 for (file, manifest) in [
325 (SHARED_FILE, project.shared.as_ref()),
326 (LOCAL_FILE, project.local.as_ref()),
327 ] {
328 let trusted = if trusted_here {
329 store.read_file(&mirror_path(&project.id, file))?
330 } else {
331 None
332 };
333 let current = manifest.map(|m| String::from_utf8_lossy(&m.bytes).into_owned());
334 let path = dir.join(file);
335 let (change, diff) = match (&trusted, ¤t) {
336 (None, None) => continue,
337 (None, Some(_)) => (ManifestChange::New, None),
338 (Some(_), None) => (ManifestChange::Removed, None),
339 (Some(old), Some(new)) if old == new => (ManifestChange::Unchanged, None),
340 (Some(old), Some(new)) => {
341 let diff = similar::TextDiff::from_lines(old.as_str(), new.as_str())
342 .unified_diff()
343 .header(&format!("trusted {file}"), &path.display().to_string())
344 .to_string();
345 (ManifestChange::Changed, Some(diff))
346 }
347 };
348 reviews.push(ManifestReview {
349 file,
350 path,
351 change,
352 content: current,
353 diff,
354 });
355 }
356 Ok(reviews)
357}
358
359pub fn trust(
364 store: &Store<'_>,
365 ax: &ApplyEnv<'_>,
366 project: &Project,
367 expected: Option<&str>,
368) -> Result<(Option<ApplyReport>, Option<CommitId>), CoreError> {
369 if let Some(expected) = expected
370 && project.hash() != expected
371 {
372 return Err(CoreError::new(
373 ErrorCode::TrustRequired,
374 format!(
375 "the manifests of project {:?} changed after the review; review them again",
376 project.name()
377 ),
378 )
379 .with_path(project.dir()));
380 }
381 let id = project.id.clone();
382 let summary = format!("project: trust {id}");
383 let touched = Some(Touched::Project(project.root.clone()));
384 commit_project(store, ax, "project.trust", summary, &id, touched, |tx| {
385 set_known(tx, ax.fs, &id, &project.root)?;
386 mirror(tx, project)?;
387 save_trust(ax, project)
388 })
389}
390
391pub fn commit_project(
397 store: &Store<'_>,
398 ax: &ApplyEnv<'_>,
399 op: &str,
400 summary: String,
401 id: &str,
402 apply: Option<Touched>,
403 stage: impl FnOnce(&mut Transaction<'_>) -> Result<(), CoreError>,
404) -> Result<(Option<ApplyReport>, Option<CommitId>), CoreError> {
405 let operation = Operation::new(op, summary)
406 .entity(format!("project/{id}"))
407 .scope(Scope::Project(id.to_owned()));
408 let state = ax.home.state_dir();
409 let previous = TrustStore::load(ax.fs, &state).ok();
410 let committed = store.transaction(operation, |tx| {
411 stage(tx)?;
412 match &apply {
413 Some(touched) => instant_apply(tx, ax, touched),
414 None => Ok(None),
415 }
416 });
417 match committed {
418 Ok(committed) => Ok((committed.value, committed.commit)),
419 Err(err) => {
420 if let Some(previous) = previous
421 && let Err(restore) = previous.save(ax.fs, &state)
422 {
423 let message = format!(
424 "{}; also, the trust file cannot be restored: {restore}",
425 err.message()
426 );
427 let mut combined = CoreError::new(err.code(), message);
428 if let Some(path) = err.path() {
429 combined = combined.with_path(path);
430 }
431 return Err(combined);
432 }
433 Err(err)
434 }
435 }
436}
437
438pub fn overlay_doc(tx: &Transaction<'_>) -> Result<TomlDocument<MachineOverlay>, CoreError> {
440 let machine = tx.machine().clone();
441 let relative = overlay_path(&machine.id)?;
442 match tx.read_file(&relative)? {
443 Some(text) => TomlDocument::parse(&text)
444 .map_err(|diagnostic| diagnostic.to_core_error(Some(Path::new(&relative)))),
445 None => Ok(TomlDocument::new(MachineOverlay::new(
446 &machine.id,
447 &machine.label,
448 tx.store().env().os(),
449 ))),
450 }
451}
452
453pub fn set_known(
459 tx: &mut Transaction<'_>,
460 fs: &dyn Fs,
461 id: &str,
462 root: &Path,
463) -> Result<(), CoreError> {
464 let mut doc = overlay_doc(tx)?;
465 let projects = doc.value_mut().projects.get_or_insert_with(BTreeMap::new);
466 if let Some(known) = projects.get(id) {
467 let other = Path::new(&known.path);
468 let checkout = !same_path(other, root)
469 && matches!(Project::load(fs, other), Ok(Some(project)) if project.id == id);
470 if checkout {
471 return Err(CoreError::new(
472 ErrorCode::AlreadyExists,
473 format!(
474 "project {id:?} is already known at {}, which still holds its manifest; \
475 one machine applies a project from one folder. To use {} instead, run \
476 `{} project rm {id}` first",
477 other.display(),
478 root.display(),
479 crate::brand::BIN_NAME,
480 ),
481 )
482 .with_path(root));
483 }
484 }
485 projects.retain(|known, project| known == id || !same_path(Path::new(&project.path), root));
486 let path = root.to_string_lossy().into_owned();
487 projects
488 .entry(id.to_owned())
489 .and_modify(|project| project.path.clone_from(&path))
490 .or_insert_with(|| MachineProject {
491 path,
492 extra: toml::Table::new(),
493 });
494 let relative = overlay_path(&tx.machine().id)?;
495 tx.write(&relative, doc.to_text()?)
496}
497
498pub fn this_overlay(
500 store: &Store<'_>,
501 fs: &dyn Fs,
502 state_dir: &Path,
503) -> Result<Option<MachineOverlay>, CoreError> {
504 let Some(machine) = Machine::load(fs, state_dir)? else {
505 return Ok(None);
506 };
507 let relative = overlay_path(&machine.id)?;
508 let Some(text) = store.read_to_string(&relative)? else {
509 return Ok(None);
510 };
511 TomlDocument::<MachineOverlay>::parse(&text)
512 .map(|doc| Some(doc.into_value()))
513 .map_err(|diagnostic| diagnostic.to_core_error(Some(Path::new(&relative))))
514}
515
516fn mirror_path(id: &str, file: &str) -> String {
517 format!("projects/{id}/{file}")
518}
519
520pub fn mirror(tx: &mut Transaction<'_>, project: &Project) -> Result<(), CoreError> {
523 for (file, manifest) in [
524 (SHARED_FILE, project.shared.as_ref()),
525 (LOCAL_FILE, project.local.as_ref()),
526 ] {
527 let relative = mirror_path(&project.id, file);
528 match manifest {
529 Some(manifest) => tx.write(&relative, manifest.bytes.clone())?,
530 None if tx.exists(&relative)? => tx.remove(&relative)?,
531 None => {}
532 }
533 }
534 Ok(())
535}
536
537pub fn save_trust(ax: &ApplyEnv<'_>, project: &Project) -> Result<(), CoreError> {
539 let state = ax.home.state_dir();
540 let mut trust = TrustStore::load(ax.fs, &state)?;
541 trust.trust(project);
542 trust.save(ax.fs, &state)
543}
544
545pub fn load_project(fs: &dyn Fs, root: &Path) -> Result<Project, CoreError> {
547 Project::load(fs, root)?.ok_or_else(|| {
548 CoreError::new(ErrorCode::NotFound, "the folder has no project manifest")
549 .with_path(manifest_dir(fs, root))
550 })
551}
552
553pub fn project_root(
557 store: Option<&Store<'_>>,
558 ax: &ApplyEnv<'_>,
559 folder: &Path,
560) -> Result<PathBuf, CoreError> {
561 let root = discover(ax.env, ax.fs, folder).ok_or_else(|| {
562 CoreError::new(
563 ErrorCode::NotFound,
564 "no project manifest (.surjection/project.toml or .surjection/project.local.toml) at or \
565 above this folder",
566 )
567 .with_path(folder)
568 })?;
569 let overlay = match store {
570 Some(store) => this_overlay(store, ax.fs, &ax.home.state_dir())?,
571 None => None,
572 };
573 let known = overlay
574 .iter()
575 .flat_map(|overlay| overlay.projects.iter().flatten())
576 .map(|(_, project)| PathBuf::from(&project.path))
577 .find(|known| same_path(known, &root));
578 Ok(known.unwrap_or(root))
579}
580
581pub fn new_project_id(env: &Env, folder_name: &str) -> Result<String, CoreError> {
583 let mut slug = String::new();
584 for ch in folder_name.chars().flat_map(char::to_lowercase) {
585 if ch.is_ascii_lowercase() || ch.is_ascii_digit() {
586 slug.push(ch);
587 } else if !slug.is_empty() && !slug.ends_with('-') {
588 slug.push('-');
589 }
590 }
591 slug.truncate(ids::MAX_ID_LEN - 5);
592 let slug = slug.trim_end_matches('-');
593 let slug = if slug.is_empty() { "project" } else { slug };
594 let random = ids::new_ulid(env.now())?;
597 let suffix = random[random.len() - 4..].to_ascii_lowercase();
598 let id = format!("{slug}-{suffix}");
599 ids::check(IdKind::Project, &id)?;
600 Ok(id)
601}
602
603pub fn exclude_manifest_dir(fs: &dyn Fs, root: &Path) -> Result<Option<PathBuf>, CoreError> {
607 let Some((repo, pattern)) = manifest_dir_pattern(fs, root)? else {
608 return Ok(None);
609 };
610 if repo.is_ignored(&manifest_dir(fs, root).join(LOCAL_FILE))? {
611 return Ok(None);
612 }
613 let file = repo.exclude_file();
614 Ok(ensure_line(fs, &file, &pattern)?.then_some(file))
615}
616
617pub fn unexclude_manifest_dir(fs: &dyn Fs, root: &Path) -> Result<Option<String>, CoreError> {
621 let Some((repo, pattern)) = manifest_dir_pattern(fs, root)? else {
622 return Ok(None);
623 };
624 let file = repo.exclude_file();
625 if let Some(text) = read_optional(fs, &file)?
626 && text.lines().any(|line| line.trim() == pattern)
627 {
628 let kept: String = text
629 .lines()
630 .filter(|line| line.trim() != pattern)
631 .map(|line| format!("{line}\n"))
632 .collect();
633 write_file(fs, &file, kept.as_bytes())?;
634 }
635 let shared = manifest_dir(fs, root).join(SHARED_FILE);
636 Ok(Some(if repo.is_ignored(&shared)? {
637 format!(
638 "{} is ignored by git; change the ignore rules to commit it",
639 shared.display()
640 )
641 } else {
642 format!("commit {} with the project", shared.display())
643 }))
644}
645
646fn manifest_dir_pattern(
649 fs: &dyn Fs,
650 root: &Path,
651) -> Result<Option<(ProjectRepo, String)>, CoreError> {
652 let Some(repo) = ProjectRepo::discover(root)? else {
653 return Ok(None);
654 };
655 Ok(repo
656 .relative(&manifest_dir(fs, root))
657 .map(|relative| (repo, format!("/{relative}/"))))
658}
659
660pub fn ensure_line(fs: &dyn Fs, path: &Path, line: &str) -> Result<bool, CoreError> {
663 let mut text = read_optional(fs, path)?.unwrap_or_default();
664 if text.lines().any(|existing| existing.trim() == line) {
665 return Ok(false);
666 }
667 if !text.is_empty() && !text.ends_with('\n') {
668 text.push('\n');
669 }
670 text.push_str(line);
671 text.push('\n');
672 if let Some(dir) = path.parent() {
673 create_dir(fs, dir)?;
674 }
675 write_file(fs, path, text.as_bytes())?;
676 Ok(true)
677}
678
679pub fn read_optional(fs: &dyn Fs, path: &Path) -> Result<Option<String>, CoreError> {
681 if !fs.exists(path) {
682 return Ok(None);
683 }
684 fs.read_to_string(path).map(Some).map_err(|err| {
685 CoreError::new(ErrorCode::IoError, format!("cannot read file: {err}")).with_path(path)
686 })
687}
688
689pub fn write_file(fs: &dyn Fs, path: &Path, bytes: &[u8]) -> Result<(), CoreError> {
693 fs.write(path, bytes)
694 .map_err(|err| crate::access::write_error(fs, "cannot write file", path, &err))
695}
696
697pub(crate) fn create_dir(fs: &dyn Fs, dir: &Path) -> Result<(), CoreError> {
698 fs.create_dir_all(dir)
699 .map_err(|err| crate::access::write_error(fs, "cannot create directory", dir, &err))
700}
701
702pub fn unknown_project(id: &str) -> CoreError {
704 CoreError::new(
705 ErrorCode::NotFound,
706 format!("project {id:?} is not known on this machine"),
707 )
708}