Skip to main content

workyard_application/
identity.rs

1//! Workspace-local identity for human command output.
2
3use atomicwrites::{AllowOverwrite, AtomicFile};
4use serde::{Deserialize, Serialize};
5use std::{
6	env, fs,
7	io::{self, Write},
8	path::Path,
9	sync::OnceLock,
10};
11
12const MARKER: &str = ".workyard";
13static CLI: OnceLock<Identity> = OnceLock::new();
14
15/// Optional settings supplied by an embedding application.
16#[derive(Clone, Default, Deserialize, Serialize, PartialEq)]
17pub struct Identity {
18	/// Heading text, without an inferred version.
19	pub display_name: Option<String>,
20	/// Literal command prefix used only in human output.
21	pub invocation_prefix: Option<String>,
22}
23
24impl Identity {
25	fn read(root: &Path) -> io::Result<Self> {
26		match fs::read(root.join(MARKER).join("presentation.json")) {
27			Ok(bytes) => {
28				let settings: Self = serde_json::from_slice(&bytes)?;
29				settings.validate()?;
30				Ok(settings)
31			}
32			Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(Self::default()),
33			Err(error) => Err(error),
34		}
35	}
36
37	pub(crate) fn validate(&self) -> io::Result<()> {
38		for text in [&self.display_name, &self.invocation_prefix]
39			.into_iter()
40			.flatten()
41		{
42			if text.trim().is_empty()
43				|| text
44					.chars()
45					.any(|ch| ch.is_control() || matches!(ch, '\u{2028}' | '\u{2029}'))
46			{
47				return Err(io::Error::other(
48					"Presentation settings must be nonempty, single-line text.",
49				));
50			}
51		}
52		Ok(())
53	}
54
55	pub(crate) fn save(self, root: &Path) -> io::Result<()> {
56		if self == Self::default() {
57			return Ok(());
58		}
59		let state = root.join(MARKER);
60		let guard = fs::OpenOptions::new()
61			.write(true)
62			.create(true)
63			.truncate(false)
64			.open(state.join("presentation.lock"))?;
65		guard.lock()?;
66		let current = Self::read(root)?;
67		let updated = Self {
68			display_name: self.display_name.or_else(|| current.display_name.clone()),
69			invocation_prefix: self
70				.invocation_prefix
71				.or_else(|| current.invocation_prefix.clone()),
72		};
73		if updated == current {
74			return Ok(());
75		}
76		AtomicFile::new(state.join("presentation.json"), AllowOverwrite)
77			.write(|file| {
78				let format = serde_json::ser::PrettyFormatter::with_indent(b"\t");
79				updated.serialize(&mut serde_json::Serializer::with_formatter(
80					&mut *file, format,
81				))?;
82				file.write_all(b"\n")
83			})
84			.map_err(io::Error::from)
85	}
86
87	/// Select presentation once for this CLI process. Protocol servers use their native identity.
88	pub fn select(workspace: Option<&Path>, overrides: Self) -> io::Result<&'static Self> {
89		let cwd = env::current_dir()?;
90		let root = workspace.or_else(|| cwd.ancestors().find(|dir| dir.join(MARKER).is_dir()));
91		let mut settings = root.map(Self::read).transpose()?.unwrap_or_default();
92		// A host can request usage before the first operation prepares local state.
93		if let Ok(prefix) = env::var("WORKYARD_CLI_PREFIX") {
94			settings.invocation_prefix = Some(prefix);
95		}
96		settings.display_name = overrides.display_name.or(settings.display_name);
97		settings.invocation_prefix = overrides.invocation_prefix.or(settings.invocation_prefix);
98		settings.validate()?;
99		Ok(CLI.get_or_init(|| settings))
100	}
101
102	/// Visible command prefix for this invocation.
103	pub fn prefix() -> &'static str {
104		CLI.get()
105			.and_then(|settings| settings.invocation_prefix.as_deref())
106			.unwrap_or("workyard")
107	}
108
109	/// Whether the embedding command selects the workspace for its caller.
110	pub fn managed() -> bool {
111		CLI.get()
112			.is_some_and(|settings| settings.invocation_prefix.is_some())
113	}
114}