Skip to main content

workyard_state/workspace/
initialize.rs

1use super::{
2	DIRECTORIES, Layout, MARKER, PENDING, Workspace, check_entry, checked_marker,
3	layout::resolve_tasks,
4};
5use crate::{Lock, LockMode, canonical_future, documents::publish, exists};
6use std::{
7	fs::{self, FileType},
8	path::{Path, PathBuf},
9};
10use workyard_core::{Control, Problem, ProblemCode};
11
12/// Create an initialized workspace, or return its configured tasks directory.
13pub fn initialize_workspace(target: &Path, tasks: Option<&Path>) -> Result<PathBuf, Problem> {
14	smol::block_on(initialize_workspace_with_control(
15		target,
16		tasks,
17		&Control::default(),
18	))
19}
20
21/// Initialize a workspace while observing the caller's cancellation policy.
22pub async fn initialize_workspace_with_control(
23	target: &Path,
24	tasks: Option<&Path>,
25	control: &Control,
26) -> Result<PathBuf, Problem> {
27	control.check()?;
28	let workspace = canonical_future(target)?;
29	let state = workspace.join(MARKER);
30	if !exists(&state)? {
31		select_tasks(&workspace, tasks)?;
32		control.check()?;
33		fs::create_dir_all(&workspace)
34			.map_err(|error| Problem::io("Create workspace directory", error))?;
35		stage_marker(&workspace, &state)?;
36	}
37
38	checked_marker(&state)?;
39	let pending = state.join(PENDING);
40	let gate_path = state.join("workspace.lock");
41	check_entry(&gate_path, FileType::is_file)?;
42	let mode = if exists(&pending)? {
43		LockMode::Exclusive
44	} else {
45		LockMode::Shared
46	};
47	let gate = Lock::wait_existing_with_control(&gate_path, mode, control).await?;
48
49	// Recheck under the gate. Another initializer may already have activated its layout.
50	if exists(&pending)? {
51		let root = select_tasks(&workspace, tasks)?;
52		control.check()?;
53		activate_layout(&workspace, &state, &root, &gate)?;
54		return Ok(root);
55	}
56
57	let requested = tasks
58		.map(|path| resolve_tasks(&workspace, path))
59		.transpose()?;
60	let root = Workspace::configured_root(&state, requested.as_deref())?;
61	control.check()?;
62	create_tasks(&root)?;
63	gate.verify()?;
64	Ok(root)
65}
66
67fn select_tasks(workspace: &Path, tasks: Option<&Path>) -> Result<PathBuf, Problem> {
68	let root = resolve_tasks(workspace, tasks.unwrap_or(Path::new("tasks")))?;
69
70	for directory in root
71		.ancestors()
72		.take_while(|directory| *directory != workspace)
73	{
74		if exists(directory)? && !directory.is_dir() {
75			return Err(Problem::new(
76				ProblemCode::InvalidInput,
77				format!("Tasks path is not a directory: {directory:?}."),
78			));
79		}
80		if exists(&directory.join(MARKER))? {
81			return Err(Problem::new(
82				ProblemCode::PathOverlap,
83				format!("The tasks directory crosses a nested workspace at {directory:?}."),
84			));
85		}
86	}
87	Ok(root)
88}
89
90fn activate_layout(
91	workspace: &Path,
92	state: &Path,
93	root: &Path,
94	gate: &Lock,
95) -> Result<(), Problem> {
96	let pending = state.join(PENDING);
97	let manifest = state.join("workspace.json");
98	check_entry(&pending, FileType::is_file)?;
99	super::check_directories(state)?;
100	if exists(&manifest)? {
101		return Err(crate::damage::damaged(
102			"Workspace contains both a published and a pending layout.",
103		));
104	}
105
106	create_tasks(root)?;
107	let relative = root
108		.strip_prefix(workspace)
109		.expect("validated tasks directory");
110	publish(&pending, &Layout::new(workspace, relative))?;
111	gate.verify()?;
112	fs::rename(pending, manifest).map_err(|error| Problem::io("Activate workspace layout", error))
113}
114
115fn create_tasks(root: &Path) -> Result<(), Problem> {
116	fs::create_dir_all(root)
117		.map_err(|error| Problem::io(format!("Create tasks directory {root:?}"), error))
118}
119
120fn stage_marker(workspace: &Path, state: &Path) -> Result<(), Problem> {
121	// Install the gate and its directories together. The pending file is renamed
122	// to workspace.json only after the winning initializer establishes the tasks dir.
123	let staging = tempfile::Builder::new()
124		.prefix(".workyard-init-")
125		.tempdir_in(workspace)
126		.map_err(|error| Problem::io("Stage workspace marker", error))?;
127	for name in DIRECTORIES {
128		fs::create_dir(staging.path().join(name))
129			.map_err(|error| Problem::io("Stage workspace directory", error))?;
130	}
131	for name in ["workspace.lock", PENDING] {
132		fs::File::create_new(staging.path().join(name))
133			.map_err(|error| Problem::io("Stage workspace files", error))?;
134	}
135
136	match fs::rename(staging.path(), state) {
137		Ok(()) => Ok(()),
138		Err(_) if exists(state)? => Ok(()),
139		Err(error) => Err(Problem::io("Publish workspace marker", error)),
140	}
141}