1use std::fs;
2use std::io::ErrorKind;
3use std::path::Path;
4
5use anyhow::{Context, Result, anyhow, bail};
6use jsonc_parser::ParseOptions;
7use jsonc_parser::cst::{CstInputValue, CstObject, CstRootNode};
8use toml_edit::{DocumentMut, Item, value};
9
10use crate::{config, gomod, marker, process};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum Format {
16 Toml,
18 Json,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25#[non_exhaustive]
26pub enum Text {
27 GoMod,
29 Version,
31 Marker,
33}
34
35impl Text {
36 fn read(self, raw: &str) -> Result<String> {
37 match self {
38 Self::GoMod => gomod::read(raw),
39 Self::Version => read_version_file(raw),
40 Self::Marker => marker::read(raw),
41 }
42 }
43
44 fn write(self, raw: &str, new_version: &str) -> Result<String> {
45 match self {
46 Self::GoMod => gomod::write(raw, new_version),
47 Self::Marker => marker::write(raw, new_version),
48 Self::Version => {
49 read_version_file(raw)?;
50 Ok(format!("{new_version}\n"))
51 }
52 }
53 }
54
55 fn accepts(self, raw: &str, new_version: &str) -> Result<()> {
56 match self {
57 Self::GoMod => gomod::accepts(raw, new_version),
58 Self::Version | Self::Marker => Ok(()),
59 }
60 }
61}
62
63fn read_version_file(raw: &str) -> Result<String> {
67 let line = raw
68 .strip_suffix('\n')
69 .map_or(raw, |line| line.strip_suffix('\r').unwrap_or(line));
70 if line.is_empty() {
71 return Ok("0.0.0".to_owned());
72 }
73 if semver::Version::parse(line).is_ok() {
74 return Ok(line.to_owned());
75 }
76 bail!("contains {raw:?}, not one version and a newline")
77}
78
79#[derive(Debug, Clone, PartialEq, Eq)]
81#[non_exhaustive]
82pub enum Driver {
83 Text {
85 text: Text,
87 after: Option<String>,
89 },
90 Path {
92 format: Format,
94 keys: Vec<String>,
97 after: Option<String>,
99 },
100 Command {
102 read: CommandSpec,
104 write: CommandSpec,
106 after: Option<String>,
108 },
109}
110
111#[derive(Debug, Clone, PartialEq, Eq)]
113#[non_exhaustive]
114pub enum CommandSpec {
115 Mise(String),
118 Argv(Vec<String>),
120}
121
122impl Driver {
123 pub fn cargo() -> Result<Self> {
130 config::stock_driver("cargo")
131 }
132
133 pub fn npm() -> Result<Self> {
140 config::stock_driver("npm")
141 }
142
143 pub fn source(&self, path: &Path) -> Result<String> {
160 match fs::read_to_string(path) {
161 Ok(raw) => Ok(raw),
162 Err(error)
163 if error.kind() == ErrorKind::NotFound
164 && path.parent().is_some_and(Path::is_dir)
165 && matches!(
166 self,
167 Self::Text {
168 text: Text::Version,
169 after: _
170 }
171 ) =>
172 {
173 Ok(String::new())
174 }
175 Err(error) => Err(error).with_context(|| path.display().to_string()),
176 }
177 }
178
179 #[must_use]
181 pub fn after(&self) -> Option<&str> {
182 match self {
183 Self::Text { after, text: _ }
184 | Self::Path {
185 after,
186 format: _,
187 keys: _,
188 }
189 | Self::Command {
190 after,
191 read: _,
192 write: _,
193 } => after.as_deref(),
194 }
195 }
196
197 pub fn accepts(&self, raw: &str, new_version: &str) -> Result<()> {
205 match self {
206 Self::Text { text, after: _ } => text.accepts(raw, new_version),
207 Self::Path {
208 format: _,
209 keys: _,
210 after: _,
211 }
212 | Self::Command {
213 read: _,
214 write: _,
215 after: _,
216 } => Ok(()),
217 }
218 }
219
220 pub fn read(&self, raw: &str) -> Result<String> {
229 match self {
230 Self::Text { text, after: _ } => text.read(raw),
231 Self::Path {
232 format,
233 keys,
234 after: _,
235 } => match format {
236 Format::Toml => read_toml(raw, keys),
237 Format::Json => read_json(raw, keys),
238 },
239 Self::Command {
240 read,
241 write: _,
242 after: _,
243 } => run_filter(read, raw, None),
244 }
245 }
246
247 pub fn write(&self, raw: &str, new_version: &str) -> Result<String> {
254 match self {
255 Self::Text { text, after: _ } => text.write(raw, new_version),
256 Self::Path {
257 format,
258 keys,
259 after: _,
260 } => match format {
261 Format::Toml => write_toml(raw, keys, new_version),
262 Format::Json => write_json(raw, keys, new_version),
263 },
264 Self::Command {
265 write,
266 read: _,
267 after: _,
268 } => run_filter(write, raw, Some(new_version)),
269 }
270 }
271}
272
273fn read_toml(raw: &str, keys: &[String]) -> Result<String> {
274 let doc: DocumentMut = raw.parse().context("parse TOML")?;
275 for key in keys {
276 if let Some(item) = toml_get(&doc, key)
277 && let Some(version) = item.as_str()
278 {
279 return Ok(version.to_owned());
280 }
281 }
282 Err(missing_toml_keys(&doc, keys))
283}
284
285fn write_toml(raw: &str, keys: &[String], new_version: &str) -> Result<String> {
286 let mut doc: DocumentMut = raw.parse().context("parse TOML")?;
287 for key in keys {
288 if toml_get(&doc, key).and_then(Item::as_str).is_some() {
289 let item = toml_get_mut(&mut doc, key).context(key.clone())?;
290 let decor = item.as_value().map(|old| old.decor().clone());
291 *item = value(new_version);
292 if let (Some(decor), Some(new)) = (decor, item.as_value_mut()) {
293 *new.decor_mut() = decor;
294 }
295 return Ok(doc.to_string());
296 }
297 }
298 Err(missing_toml_keys(&doc, keys))
299}
300
301fn missing_toml_keys(doc: &DocumentMut, keys: &[String]) -> anyhow::Error {
310 let dynamic_version = toml_get(doc, "project.dynamic")
311 .and_then(Item::as_array)
312 .is_some_and(|fields| fields.iter().any(|field| field.as_str() == Some("version")));
313 if dynamic_version {
314 return anyhow!(
315 "project.dynamic lists version, so the build backend sets it and verctl cannot; write a static project.version, keep the version in a VERSION file, or declare a driver"
316 );
317 }
318 anyhow!("none of these TOML keys exist: {}", keys.join(", "))
319}
320
321fn toml_get<'a>(doc: &'a DocumentMut, path: &str) -> Option<&'a Item> {
322 let mut item: Option<&Item> = None;
323 for (index, part) in path.split('.').enumerate() {
324 item = if index == 0 {
325 doc.get(part)
326 } else {
327 item.and_then(|item| item.get(part))
328 };
329 }
330 item
331}
332
333fn toml_get_mut<'a>(doc: &'a mut DocumentMut, path: &str) -> Option<&'a mut Item> {
334 let mut parts = path.split('.');
335 let first = parts.next()?;
336 let mut item = doc.get_mut(first)?;
337 for part in parts {
338 item = item.get_mut(part)?;
339 }
340 Some(item)
341}
342
343fn read_json(raw: &str, keys: &[String]) -> Result<String> {
344 let root = parse_json(raw)?;
345 for key in keys {
346 if let Some(version) = json_string_at(&root, key) {
347 return Ok(version);
348 }
349 }
350 bail!("none of these JSON keys exist: {}", keys.join(", "))
351}
352
353fn write_json(raw: &str, keys: &[String], new_version: &str) -> Result<String> {
354 let root = parse_json(raw)?;
355 for key in keys {
356 if json_set_string(&root, key, new_version) {
357 return Ok(root.to_string());
358 }
359 }
360 bail!("none of these JSON keys exist: {}", keys.join(", "))
361}
362
363fn parse_json(raw: &str) -> Result<CstRootNode> {
364 CstRootNode::parse(raw, &ParseOptions::default()).context("parse JSON")
365}
366
367fn json_object_at(object: &CstObject, path: &str) -> Option<CstObject> {
368 let mut current = object.clone();
369 for part in path.split('.') {
370 current = current.object_value(part)?;
371 }
372 Some(current)
373}
374
375fn json_string_at(root: &CstRootNode, path: &str) -> Option<String> {
376 let object = root.object_value()?;
377 let (parent_path, field) = split_json_path(path);
378 let parent = match parent_path {
379 Some(parent) => json_object_at(&object, parent)?,
380 None => object,
381 };
382 parent
383 .get(field)?
384 .value()?
385 .as_string_lit()?
386 .decoded_value()
387 .ok()
388}
389
390fn json_set_string(root: &CstRootNode, path: &str, new_version: &str) -> bool {
391 let Some(object) = root.object_value() else {
392 return false;
393 };
394 let (parent_path, field) = split_json_path(path);
395 let parent = match parent_path {
396 Some(parent) => match json_object_at(&object, parent) {
397 Some(parent) => parent,
398 None => return false,
399 },
400 None => object,
401 };
402 let Some(prop) = parent.get(field) else {
403 return false;
404 };
405 if prop
406 .value()
407 .and_then(|value| value.as_string_lit())
408 .is_none()
409 {
410 return false;
411 }
412 prop.set_value(CstInputValue::String(new_version.to_owned()));
413 true
414}
415
416fn split_json_path(path: &str) -> (Option<&str>, &str) {
417 match path.rsplit_once('.') {
418 Some((parent, field)) => (Some(parent), field),
419 None => (None, path),
420 }
421}
422
423fn run_filter(spec: &CommandSpec, stdin: &str, new_version: Option<&str>) -> Result<String> {
424 let argv = match spec {
425 CommandSpec::Mise(task) => vec!["mise".into(), "run".into(), task.clone()],
426 CommandSpec::Argv(argv) => argv.clone(),
427 };
428 let env = new_version.map_or_else(Vec::new, |version| vec![("VERCTL_VERSION", version)]);
429 let stdout = process::filter(&argv, stdin, &env)?;
430 if new_version.is_some() {
431 Ok(stdout)
432 } else {
433 Ok(stdout.trim().to_owned())
434 }
435}