workyard_application/
identity.rs1use 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#[derive(Clone, Default, Deserialize, Serialize, PartialEq)]
17pub struct Identity {
18 pub display_name: Option<String>,
20 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 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 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 pub fn name() -> &'static str {
104 CLI.get()
105 .and_then(|identity| identity.display_name.as_deref())
106 .unwrap_or("Workyard")
107 }
108
109 pub fn prefix() -> &'static str {
111 CLI.get()
112 .and_then(|settings| settings.invocation_prefix.as_deref())
113 .unwrap_or("workyard")
114 }
115
116 pub fn managed() -> bool {
118 CLI.get()
119 .is_some_and(|settings| settings.invocation_prefix.is_some())
120 }
121}