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, process};
11
12mod gomod;
13mod marker;
14
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17#[non_exhaustive]
18pub enum Format {
19 Toml,
21 Json,
23}
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28#[non_exhaustive]
29pub enum Text {
30 GoMod,
32 Version,
34 Marker,
36}
37
38impl Text {
39 fn read(self, raw: &str) -> Result<String> {
40 match self {
41 Self::GoMod => gomod::read(raw),
42 Self::Version => read_version_file(raw),
43 Self::Marker => marker::read(raw),
44 }
45 }
46
47 fn write(self, raw: &str, new_version: &str) -> Result<String> {
48 match self {
49 Self::GoMod => gomod::write(raw, new_version),
50 Self::Marker => marker::write(raw, new_version),
51 Self::Version => {
52 read_version_file(raw)?;
53 Ok(format!("{new_version}\n"))
54 }
55 }
56 }
57
58 fn accepts(self, raw: &str, new_version: &str) -> Result<()> {
59 match self {
60 Self::GoMod => gomod::accepts(raw, new_version),
61 Self::Version | Self::Marker => Ok(()),
62 }
63 }
64}
65
66fn read_version_file(raw: &str) -> Result<String> {
70 let line = raw
71 .strip_suffix('\n')
72 .map_or(raw, |line| line.strip_suffix('\r').unwrap_or(line));
73 if line.is_empty() {
74 return Ok("0.0.0".to_owned());
75 }
76 if semver::Version::parse(line).is_ok() {
77 return Ok(line.to_owned());
78 }
79 bail!("contains {raw:?}, not one version and a newline")
80}
81
82#[derive(Debug, Clone, PartialEq, Eq)]
84#[non_exhaustive]
85pub enum Driver {
86 Text {
88 text: Text,
90 after: Option<String>,
92 },
93 Path {
95 format: Format,
97 keys: Vec<String>,
100 after: Option<String>,
102 },
103 Command {
105 read: CommandSpec,
107 write: CommandSpec,
109 after: Option<String>,
111 },
112}
113
114#[derive(Debug, Clone, PartialEq, Eq)]
116#[non_exhaustive]
117pub enum CommandSpec {
118 Mise(String),
121 Argv(Vec<String>),
123}
124
125impl Driver {
126 pub fn cargo() -> Result<Self> {
133 config::stock_driver("cargo")
134 }
135
136 pub fn npm() -> Result<Self> {
143 config::stock_driver("npm")
144 }
145
146 pub fn source(&self, path: &Path) -> Result<String> {
163 match fs::read_to_string(path) {
164 Ok(raw) => Ok(raw),
165 Err(error)
166 if error.kind() == ErrorKind::NotFound
167 && path.parent().is_some_and(Path::is_dir)
168 && matches!(
169 self,
170 Self::Text {
171 text: Text::Version,
172 after: _
173 }
174 ) =>
175 {
176 Ok(String::new())
177 }
178 Err(error) => Err(error).with_context(|| path.display().to_string()),
179 }
180 }
181
182 #[must_use]
184 pub fn after(&self) -> Option<&str> {
185 match self {
186 Self::Text { after, text: _ }
187 | Self::Path {
188 after,
189 format: _,
190 keys: _,
191 }
192 | Self::Command {
193 after,
194 read: _,
195 write: _,
196 } => after.as_deref(),
197 }
198 }
199
200 pub fn accepts(&self, raw: &str, new_version: &str) -> Result<()> {
208 match self {
209 Self::Text { text, after: _ } => text.accepts(raw, new_version),
210 Self::Path {
211 format: _,
212 keys: _,
213 after: _,
214 }
215 | Self::Command {
216 read: _,
217 write: _,
218 after: _,
219 } => Ok(()),
220 }
221 }
222
223 pub fn read(&self, raw: &str) -> Result<String> {
232 match self {
233 Self::Text { text, after: _ } => text.read(raw),
234 Self::Path {
235 format,
236 keys,
237 after: _,
238 } => match format {
239 Format::Toml => read_toml(raw, keys),
240 Format::Json => read_json(raw, keys),
241 },
242 Self::Command {
243 read,
244 write: _,
245 after: _,
246 } => run_filter(read, raw, None),
247 }
248 }
249
250 pub fn write(&self, raw: &str, new_version: &str) -> Result<String> {
257 match self {
258 Self::Text { text, after: _ } => text.write(raw, new_version),
259 Self::Path {
260 format,
261 keys,
262 after: _,
263 } => match format {
264 Format::Toml => write_toml(raw, keys, new_version),
265 Format::Json => write_json(raw, keys, new_version),
266 },
267 Self::Command {
268 write,
269 read: _,
270 after: _,
271 } => run_filter(write, raw, Some(new_version)),
272 }
273 }
274}
275
276fn read_toml(raw: &str, keys: &[String]) -> Result<String> {
277 let doc: DocumentMut = raw.parse().context("parse TOML")?;
278 for key in keys {
279 if let Some(item) = toml_get(&doc, key)
280 && let Some(version) = item.as_str()
281 {
282 return Ok(version.to_owned());
283 }
284 }
285 Err(missing_toml_keys(&doc, keys))
286}
287
288fn write_toml(raw: &str, keys: &[String], new_version: &str) -> Result<String> {
289 let mut doc: DocumentMut = raw.parse().context("parse TOML")?;
290 for key in keys {
291 if toml_get(&doc, key).and_then(Item::as_str).is_some() {
292 let item = toml_get_mut(&mut doc, key).context(key.clone())?;
293 let decor = item.as_value().map(|old| old.decor().clone());
294 *item = value(new_version);
295 if let (Some(decor), Some(new)) = (decor, item.as_value_mut()) {
296 *new.decor_mut() = decor;
297 }
298 return Ok(doc.to_string());
299 }
300 }
301 Err(missing_toml_keys(&doc, keys))
302}
303
304fn missing_toml_keys(doc: &DocumentMut, keys: &[String]) -> anyhow::Error {
313 let dynamic_version = toml_get(doc, "project.dynamic")
314 .and_then(Item::as_array)
315 .is_some_and(|fields| fields.iter().any(|field| field.as_str() == Some("version")));
316 if dynamic_version {
317 return anyhow!(
318 "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"
319 );
320 }
321 anyhow!("none of these TOML keys exist: {}", keys.join(", "))
322}
323
324fn toml_get<'a>(doc: &'a DocumentMut, path: &str) -> Option<&'a Item> {
325 let mut item: Option<&Item> = None;
326 for (index, part) in path.split('.').enumerate() {
327 item = if index == 0 {
328 doc.get(part)
329 } else {
330 item.and_then(|item| item.get(part))
331 };
332 }
333 item
334}
335
336fn toml_get_mut<'a>(doc: &'a mut DocumentMut, path: &str) -> Option<&'a mut Item> {
337 let mut parts = path.split('.');
338 let first = parts.next()?;
339 let mut item = doc.get_mut(first)?;
340 for part in parts {
341 item = item.get_mut(part)?;
342 }
343 Some(item)
344}
345
346fn read_json(raw: &str, keys: &[String]) -> Result<String> {
347 let root = parse_json(raw)?;
348 for key in keys {
349 if let Some(version) = json_string_at(&root, key) {
350 return Ok(version);
351 }
352 }
353 bail!("none of these JSON keys exist: {}", keys.join(", "))
354}
355
356fn write_json(raw: &str, keys: &[String], new_version: &str) -> Result<String> {
357 let root = parse_json(raw)?;
358 for key in keys {
359 if json_set_string(&root, key, new_version) {
360 return Ok(root.to_string());
361 }
362 }
363 bail!("none of these JSON keys exist: {}", keys.join(", "))
364}
365
366fn parse_json(raw: &str) -> Result<CstRootNode> {
367 CstRootNode::parse(raw, &ParseOptions::default()).context("parse JSON")
368}
369
370fn json_object_at(object: &CstObject, path: &str) -> Option<CstObject> {
371 let mut current = object.clone();
372 for part in path.split('.') {
373 current = current.object_value(part)?;
374 }
375 Some(current)
376}
377
378fn json_string_at(root: &CstRootNode, path: &str) -> Option<String> {
379 let object = root.object_value()?;
380 let (parent_path, field) = split_json_path(path);
381 let parent = match parent_path {
382 Some(parent) => json_object_at(&object, parent)?,
383 None => object,
384 };
385 parent
386 .get(field)?
387 .value()?
388 .as_string_lit()?
389 .decoded_value()
390 .ok()
391}
392
393fn json_set_string(root: &CstRootNode, path: &str, new_version: &str) -> bool {
394 let Some(object) = root.object_value() else {
395 return false;
396 };
397 let (parent_path, field) = split_json_path(path);
398 let parent = match parent_path {
399 Some(parent) => match json_object_at(&object, parent) {
400 Some(parent) => parent,
401 None => return false,
402 },
403 None => object,
404 };
405 let Some(prop) = parent.get(field) else {
406 return false;
407 };
408 if prop
409 .value()
410 .and_then(|value| value.as_string_lit())
411 .is_none()
412 {
413 return false;
414 }
415 prop.set_value(CstInputValue::String(new_version.to_owned()));
416 true
417}
418
419fn split_json_path(path: &str) -> (Option<&str>, &str) {
420 match path.rsplit_once('.') {
421 Some((parent, field)) => (Some(parent), field),
422 None => (None, path),
423 }
424}
425
426fn run_filter(spec: &CommandSpec, stdin: &str, new_version: Option<&str>) -> Result<String> {
427 let argv = match spec {
428 CommandSpec::Mise(task) => vec!["mise".into(), "run".into(), task.clone()],
429 CommandSpec::Argv(argv) => argv.clone(),
430 };
431 let env = new_version.map_or_else(Vec::new, |version| vec![("VERCTL_VERSION", version)]);
432 let stdout = process::filter(&argv, stdin, &env)?;
433 if new_version.is_some() {
434 Ok(stdout)
435 } else {
436 Ok(stdout.trim().to_owned())
437 }
438}