use anyhow::{Result, anyhow, bail};
use semver::Version;
const UNRELEASED: &str = "0.0.0";
struct ModuleLine<'a> {
path: &'a str,
path_end: usize,
line_end: usize,
comment: Option<&'a str>,
deprecated: bool,
}
pub(crate) fn read(raw: &str) -> Result<String> {
let line = module_line(raw)?;
line.comment
.map_or_else(|| Ok(UNRELEASED.to_owned()), version_in)
}
pub(crate) fn write(raw: &str, new_version: &str) -> Result<String> {
let line = module_line(raw)?;
refuse_deprecated(&line)?;
if let Some(comment) = line.comment {
version_in(comment)?;
}
Ok(format!(
"{} // v{new_version}{}",
&raw[..line.path_end],
&raw[line.line_end..]
))
}
pub(crate) fn accepts(raw: &str, new_version: &str) -> Result<()> {
let line = module_line(raw)?;
refuse_deprecated(&line)?;
if line.path.starts_with("gopkg.in/") {
return Ok(());
}
let major = Version::parse(new_version)?.major;
let (base, suffix) = split_major(line.path);
let wanted = (major >= 2).then_some(major);
if suffix == wanted {
return Ok(());
}
let needed = wanted.map_or_else(|| base.to_owned(), |major| format!("{base}/v{major}"));
bail!(
"go.mod declares module {}, but version {new_version} needs module {needed}: Go resolves a module from v2 on only at a path ending in /v<major>; change the module path in the same pull request",
line.path
)
}
fn refuse_deprecated(line: &ModuleLine<'_>) -> Result<()> {
if line.deprecated {
bail!(
"go.mod has a `Deprecated:` comment directly above its module line, and Go would read the `// vX.Y.Z` comment as part of that notice; keep this module's version in a VERSION file, or declare a driver"
);
}
Ok(())
}
fn deprecated_above(above: &str) -> bool {
let mut top_down: Vec<&str> = above
.lines()
.rev()
.map(str::trim)
.map_while(|line| line.strip_prefix("//"))
.map(str::trim)
.collect();
top_down.reverse();
let paragraphs: Vec<&[&str]> = top_down.split(|text| text.is_empty()).collect();
let notice = paragraphs.iter().position(|paragraph| {
paragraph
.first()
.is_some_and(|text| text.starts_with("Deprecated:"))
});
notice.is_some() && notice == paragraphs.len().checked_sub(1)
}
fn version_in(comment: &str) -> Result<String> {
if let Some(version) = comment.strip_prefix('v')
&& Version::parse(version).is_ok()
{
return Ok(version.to_owned());
}
bail!(
"the go.mod module line carries the comment {comment:?}, which is not a version; write `// vX.Y.Z` there, or declare a driver"
)
}
fn split_major(path: &str) -> (&str, Option<u64>) {
if let Some((base, last)) = path.rsplit_once('/')
&& let Some(digits) = last.strip_prefix('v')
&& let Ok(major) = digits.parse::<u64>()
&& major >= 2
&& !digits.starts_with('0')
{
return (base, Some(major));
}
(path, None)
}
fn module_line(raw: &str) -> Result<ModuleLine<'_>> {
let mut start = 0;
for line in raw.split_inclusive('\n') {
let content = line.trim_end_matches(['\n', '\r']);
let line_end = start + content.len();
let indent = content.len() - content.trim_start().len();
if let Some(rest) = content.trim_start().strip_prefix("module")
&& rest.starts_with([' ', '\t', '"', '`', '('])
{
let rest_start = start + indent + "module".len();
let mut module = parse_module(raw, rest_start, line_end)?;
module.deprecated = deprecated_above(&raw[..start]);
return Ok(module);
}
start += line.len();
}
bail!("go.mod has no module line")
}
fn parse_module(raw: &str, rest_start: usize, line_end: usize) -> Result<ModuleLine<'_>> {
let rest = &raw[rest_start..line_end];
let lead = rest.len() - rest.trim_start().len();
let token = &rest[lead..];
let (path, token_len) = match token.chars().next() {
Some('(') => bail!("go.mod declares its module in a block; declare a driver"),
Some(quote @ ('"' | '`')) => {
let close = token[1..]
.find(quote)
.map(|at| at + 1)
.ok_or_else(|| anyhow!("go.mod module path has no closing quote"))?;
(&token[1..close], close + 1)
}
Some(_) | None => {
let len = path_len(token);
(&token[..len], len)
}
};
if path.is_empty() {
bail!("go.mod module line names no path");
}
let path_end = rest_start + lead + token_len;
let tail = raw[path_end..line_end].trim();
let comment = match tail.strip_prefix("//") {
Some(comment) => Some(comment.trim()),
None if tail.is_empty() => None,
None => bail!("go.mod module line has {tail:?} after its path"),
};
Ok(ModuleLine {
path,
path_end,
line_end,
comment,
deprecated: false,
})
}
fn path_len(token: &str) -> usize {
let space = token.find(char::is_whitespace).unwrap_or(token.len());
let comment = token.find("//").unwrap_or(token.len());
space.min(comment)
}
#[cfg(test)]
mod tests;