Skip to main content

workyard_application/actions/init/
action.rs

1use super::{InitInput, InitOutcome, skill};
2use crate::{
3	contracts::{ProblemOutcome, Progress},
4	execution::blocking_action,
5};
6use std::path::Path;
7use trine::{InvocationContext, NativePath};
8use workyard_core::{Control, Problem, ProblemCode};
9use workyard_state::InitOptions;
10
11/// Initialize a workspace with the requested tasks directory.
12pub async fn init(
13	input: InitInput,
14	context: InvocationContext<Progress>,
15) -> Result<InitOutcome, ProblemOutcome> {
16	blocking_action(async move {
17		let cancellation = context.cancellation().clone();
18		let control = Control::new({
19			let cancellation = cancellation.clone();
20			move || cancellation.is_cancelled()
21		});
22
23		let identity = crate::identity::Identity {
24			display_name: input.display_name,
25			invocation_prefix: input.invocation_prefix,
26		};
27		identity.validate().map_err(|error| {
28			workyard_core::Problem::new(ProblemCode::InvalidInput, error.to_string())
29		})?;
30
31		let directory = input
32			.directory
33			.as_ref()
34			.map(NativePath::as_path)
35			.unwrap_or(Path::new("."));
36
37		let workspace = workyard_state::canonical_future(directory)?;
38		if input.tasks.is_some() && input.detached_tasks.is_some() {
39			return Err(Problem::new(
40				ProblemCode::InvalidInput,
41				"Use either --tasks or --detached-tasks.",
42			)
43			.into());
44		}
45		let requested_tasks = input
46			.tasks
47			.as_ref()
48			.or(input.detached_tasks.as_ref())
49			.map(NativePath::as_path);
50		if let Some(tasks) = requested_tasks {
51			skill::check_tasks(&workspace, tasks)?;
52		}
53
54		let track: Vec<_> = input.track.iter().map(NativePath::as_path).collect();
55		let tasks = workyard_state::initialize_workspace_with_options(
56			&workspace,
57			InitOptions {
58				tasks: requested_tasks,
59				detached_tasks: input.detached_tasks.is_some(),
60				tracked_only: input.tracked_only,
61				track: &track,
62			},
63			&control,
64		)
65		.await?;
66
67		identity
68			.save(&workspace)
69			.map_err(|error| Problem::io("Save workspace presentation", error))?;
70
71		skill::install(&workspace).map_err(|error| {
72			Problem::io(
73				format!("Workspace is ready. Could not install {}", skill::LOCATION),
74				error,
75			)
76			.remedy("Check the skill path and rerun workyard init for the same workspace.")
77		})?;
78
79		Ok(InitOutcome {
80			cancellation,
81			workspace: NativePath::new(workspace).expect("workspace path"),
82			tasks_root: NativePath::new(tasks).expect("tasks root path"),
83		})
84	})
85	.await
86}