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, projects::initial_roots,
4};
5use crate::{Lock, LockMode, canonical_future, documents::publish, exists};
6use std::{
7	collections::BTreeSet,
8	fs::{self, FileType},
9	path::{Path, PathBuf},
10};
11use workyard_core::{Control, Problem, ProblemCode};
12
13/// Task placement and project selection policy requested at initialization.
14#[derive(Default)]
15pub struct InitOptions<'a> {
16	/// Relative tasks path, with placement determined by detached_tasks.
17	pub tasks: Option<&'a Path>,
18	/// Require an external tasks directory.
19	pub detached_tasks: bool,
20	/// Limit task participants to discovered repositories.
21	pub tracked_only: bool,
22	/// Initial discovery roots. Relative paths are anchored at the workspace.
23	pub track: &'a [&'a Path],
24}
25
26/// Create an initialized workspace, or return its configured tasks directory.
27pub fn initialize_workspace(target: &Path, tasks: Option<&Path>) -> Result<PathBuf, Problem> {
28	smol::block_on(initialize_workspace_with_control(
29		target,
30		tasks,
31		&Control::default(),
32	))
33}
34
35/// Initialize a workspace while observing the caller's cancellation policy.
36pub async fn initialize_workspace_with_control(
37	target: &Path,
38	tasks: Option<&Path>,
39	control: &Control,
40) -> Result<PathBuf, Problem> {
41	initialize_workspace_with_options(
42		target,
43		InitOptions {
44			tasks,
45			..InitOptions::default()
46		},
47		control,
48	)
49	.await
50}
51
52/// Initialize a workspace with explicitly selected task and project policies.
53pub async fn initialize_workspace_with_options(
54	target: &Path,
55	options: InitOptions<'_>,
56	control: &Control,
57) -> Result<PathBuf, Problem> {
58	if options.detached_tasks && options.tasks.is_none() {
59		return Err(Problem::new(
60			ProblemCode::InvalidInput,
61			"Supply a detached tasks path.",
62		));
63	}
64	control.check()?;
65	let workspace = canonical_future(target)?;
66	let requested_roots = initial_roots(&workspace, options.track)?;
67	let state = workspace.join(MARKER);
68	if !exists(&state)? {
69		select_tasks(&workspace, &options)?;
70		control.check()?;
71		fs::create_dir_all(&workspace)
72			.map_err(|error| Problem::io("Create workspace directory", error))?;
73		stage_marker(&workspace, &state)?;
74	}
75
76	checked_marker(&state)?;
77	let pending = state.join(PENDING);
78	let gate_path = state.join("workspace.lock");
79	check_entry(&gate_path, FileType::is_file)?;
80	let mode = if exists(&pending)? {
81		LockMode::Exclusive
82	} else {
83		LockMode::Shared
84	};
85	let gate = Lock::wait_existing_with_control(&gate_path, mode, control).await?;
86
87	// Recheck under the gate. Another initializer may already have activated its layout.
88	if exists(&pending)? {
89		let root = select_tasks(&workspace, &options)?;
90		control.check()?;
91		let roots = requested_roots.unwrap_or_else(|| BTreeSet::from([PathBuf::from("projects")]));
92		activate_layout(&workspace, &state, &root, &options, &roots, &gate)?;
93		return Ok(root);
94	}
95
96	let layout = Layout::read(&state)?;
97	let project_conflict = if let Some(roots) = requested_roots {
98		layout.project_roots()? != roots
99	} else {
100		false
101	};
102	if (options.tasks.is_some() && options.detached_tasks != layout.detached_tasks)
103		|| (options.tracked_only && !layout.tracked_only)
104		|| project_conflict
105	{
106		return Err(Problem::new(
107			ProblemCode::WorkspaceBindingConflict,
108			"Workspace already uses a different tasks or project policy.",
109		));
110	}
111	let requested = options
112		.tasks
113		.map(|path| resolve_tasks(&workspace, path, options.detached_tasks))
114		.transpose()?;
115	let root = Workspace::configured_root(&state, requested.as_deref())?;
116	control.check()?;
117	create_tasks(&root)?;
118	gate.verify()?;
119	Ok(root)
120}
121
122fn select_tasks(workspace: &Path, options: &InitOptions<'_>) -> Result<PathBuf, Problem> {
123	let root = resolve_tasks(
124		workspace,
125		options.tasks.unwrap_or(Path::new("tasks")),
126		options.detached_tasks,
127	)?;
128
129	for directory in root
130		.ancestors()
131		.take_while(|directory| *directory != workspace)
132	{
133		if exists(directory)? && !directory.is_dir() {
134			return Err(Problem::new(
135				ProblemCode::InvalidInput,
136				format!("Tasks path is not a directory: {directory:?}."),
137			));
138		}
139		if exists(&directory.join(MARKER))? {
140			return Err(Problem::new(
141				ProblemCode::PathOverlap,
142				format!("The tasks directory crosses a nested workspace at {directory:?}."),
143			));
144		}
145	}
146	Ok(root)
147}
148
149fn activate_layout(
150	workspace: &Path,
151	state: &Path,
152	root: &Path,
153	options: &InitOptions<'_>,
154	roots: &BTreeSet<PathBuf>,
155	gate: &Lock,
156) -> Result<(), Problem> {
157	let pending = state.join(PENDING);
158	let manifest = state.join("workspace.json");
159	check_entry(&pending, FileType::is_file)?;
160	super::check_directories(state)?;
161	if exists(&manifest)? {
162		return Err(crate::damage::damaged(
163			"Workspace contains both a published and a pending layout.",
164		));
165	}
166
167	create_tasks(root)?;
168	let tasks = if options.detached_tasks {
169		options
170			.tasks
171			.expect("detached initialization requires an explicit tasks path")
172	} else {
173		root.strip_prefix(workspace)
174			.expect("validated tasks directory")
175	};
176	let layout = Layout::new(
177		workspace,
178		tasks,
179		options.detached_tasks,
180		options.tracked_only,
181		roots,
182	);
183	publish(&pending, &layout)?;
184	gate.verify()?;
185	fs::rename(pending, manifest).map_err(|error| Problem::io("Activate workspace layout", error))
186}
187
188fn create_tasks(root: &Path) -> Result<(), Problem> {
189	fs::create_dir_all(root)
190		.map_err(|error| Problem::io(format!("Create tasks directory {root:?}"), error))
191}
192
193fn stage_marker(workspace: &Path, state: &Path) -> Result<(), Problem> {
194	// Install the gate and its directories together. The pending file is renamed
195	// to workspace.json only after the winning initializer establishes the tasks dir.
196	let staging = tempfile::Builder::new()
197		.prefix(".workyard-init-")
198		.tempdir_in(workspace)
199		.map_err(|error| Problem::io("Stage workspace marker", error))?;
200	for name in DIRECTORIES {
201		fs::create_dir(staging.path().join(name))
202			.map_err(|error| Problem::io("Stage workspace directory", error))?;
203	}
204	for name in ["workspace.lock", PENDING] {
205		fs::File::create_new(staging.path().join(name))
206			.map_err(|error| Problem::io("Stage workspace files", error))?;
207	}
208
209	match fs::rename(staging.path(), state) {
210		Ok(()) => Ok(()),
211		Err(_) if exists(state)? => Ok(()),
212		Err(error) => Err(Problem::io("Publish workspace marker", error)),
213	}
214}