Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion crates/cli/src/remedy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,9 @@ fn workspace_remedy(error: &WorkspaceError) -> &'static str {
}

fn configuration_file_remedy(error: &ConfigurationFileError) -> &'static str {
if let Some(message) = plugin_config_remedy(error) {
return message;
}
match error {
ConfigurationFileError::Unreadable(_) => {
"Check that codeint.json is a file you have permission to read, then run codeint again."
Expand Down Expand Up @@ -161,6 +164,15 @@ fn configuration_file_remedy(error: &ConfigurationFileError) -> &'static str {
ConfigurationFileError::MissingKey { .. } => {
"Add the key; the JSON schema that $schema links to describes every key."
}
ConfigurationFileError::NewerSchemaVersion { .. } => {
"Run codeint update (or upgrade the codeint npm package) to match or exceed the $schema version, or lower the $schema tag in codeint.json."
}
_ => "Check codeint.json against the JSON schema that $schema links to.",
}
}

fn plugin_config_remedy(error: &ConfigurationFileError) -> Option<&'static str> {
Some(match error {
ConfigurationFileError::UnknownLanguagePlugin { .. } => {
"Name one of the Language plugins listed, or remove the entry from languages."
}
Expand All @@ -182,7 +194,8 @@ fn configuration_file_remedy(error: &ConfigurationFileError) -> &'static str {
ConfigurationFileError::NonHttpsPluginUrl { .. } => {
"Use an https:// URL for the plugin in codeint.json; plain HTTP and other schemes are refused."
}
}
_ => return None,
})
}

fn plugin_host_remedy(error: &PluginHostError) -> &'static str {
Expand Down
12 changes: 12 additions & 0 deletions crates/cli/tests/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2889,6 +2889,18 @@ fn a_languages_entry_without_include_names_the_missing_key_and_exits_2() {
);
}

#[test]
fn a_codeint_json_with_a_newer_schema_version_exits_2() {
assert_codeint_json_is_rejected(
r#"{ "$schema": "https://raw.githubusercontent.com/avidianity/codeint/v99.0.0/schema/codeint.schema.json", "future_key": true }"#,
&format!(
"codeint.json targets codeint v99.0.0 via $schema, which is newer than this binary (v{})",
env!("CARGO_PKG_VERSION")
),
"Run codeint update (or upgrade the codeint npm package) to match or exceed the $schema version, or lower the $schema tag in codeint.json.",
);
}

#[test]
fn an_invalid_exclude_glob_names_its_key_and_exits_2() {
assert_codeint_json_is_rejected(
Expand Down
84 changes: 84 additions & 0 deletions crates/config/src/codeint_json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,13 @@ pub enum ConfigurationFileError {
name: String,
url: String,
},
#[error(
"{CONFIGURATION_FILE_NAME} targets codeint v{config_version} via $schema, which is newer than this binary (v{binary_version})"
)]
NewerSchemaVersion {
config_version: String,
binary_version: String,
},
}

#[derive(Debug, Clone, Default, Deserialize, Serialize, JsonSchema)]
Expand Down Expand Up @@ -673,6 +680,7 @@ pub fn configuration_schema() -> String {

fn parse(text: &str) -> Result<Configuration, ConfigurationFileError> {
let value: Value = serde_json::from_str(text).map_err(ConfigurationFileError::NotJson)?;
check_schema_version(&value, env!("CARGO_PKG_VERSION"))?;
let schema = schemars::schema_for!(ConfigurationFile);
shape::check_shape(&value, schema.as_value())?;
let file: ConfigurationFile =
Expand Down Expand Up @@ -1007,3 +1015,79 @@ fn any_of(types: &[JsonType]) -> String {
.collect::<Vec<_>>()
.join(" or ")
}

const OFFICIAL_SCHEMA_PREFIX: &str = "https://raw.githubusercontent.com/avidianity/codeint/v";
const OFFICIAL_SCHEMA_SUFFIX: &str = "/schema/codeint.schema.json";

fn check_schema_version(value: &Value, binary_version: &str) -> Result<(), ConfigurationFileError> {
let Some(schema_url) = value.get("$schema").and_then(Value::as_str) else {
return Ok(());
};
let Some(config_version) = extract_official_schema_version(schema_url) else {
return Ok(());
};
let (Some(cfg), Some(bin)) = (parse_semver(config_version), parse_semver(binary_version))
else {
return Ok(());
};
if cfg > bin {
return Err(ConfigurationFileError::NewerSchemaVersion {
config_version: config_version.to_owned(),
binary_version: binary_version.to_owned(),
});
}
Ok(())
}

fn extract_official_schema_version(url: &str) -> Option<&str> {
url.strip_prefix(OFFICIAL_SCHEMA_PREFIX)?
.strip_suffix(OFFICIAL_SCHEMA_SUFFIX)
}

fn parse_semver(raw: &str) -> Option<(u64, u64, u64)> {
let core = raw.split(['-', '+']).next()?;
let mut parts = core.split('.');
let major = parts.next()?.parse().ok()?;
let minor = parts.next()?.parse().ok()?;
let patch = parts.next()?.parse().ok()?;
if parts.next().is_some() {
return None;
}
Some((major, minor, patch))
}

#[cfg(test)]
mod schema_version_tests {
use super::*;

fn schema_json(url: &str) -> Value {
serde_json::json!({ "$schema": url })
}

#[test]
fn rejects_newer_patch_minor_and_major_schema_versions() {
for newer in ["0.4.1", "0.5.0", "1.0.0"] {
let url = format!("{OFFICIAL_SCHEMA_PREFIX}{newer}{OFFICIAL_SCHEMA_SUFFIX}");
let err = check_schema_version(&schema_json(&url), "0.4.0").unwrap_err();
assert!(matches!(
err,
ConfigurationFileError::NewerSchemaVersion {
ref config_version,
ref binary_version
} if config_version == newer && binary_version == "0.4.0"
));
}
}

#[test]
fn accepts_equal_older_missing_and_custom_schemas() {
for ok in ["0.4.0", "0.3.9", "0.1.0"] {
let url = format!("{OFFICIAL_SCHEMA_PREFIX}{ok}{OFFICIAL_SCHEMA_SUFFIX}");
assert!(check_schema_version(&schema_json(&url), "0.4.0").is_ok());
}
assert!(check_schema_version(&serde_json::json!({}), "0.4.0").is_ok());
assert!(
check_schema_version(&schema_json("./schema/codeint.schema.json"), "0.4.0").is_ok()
);
}
}
1 change: 1 addition & 0 deletions docs/guide/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ Without `codeint.json`, codeint measures every supported language with default s

Run `codeint init` to generate a starter file with a versioned `$schema` URL for editor autocomplete.
When you upgrade via `codeint update`, codeint updates that `$schema` tag automatically.
If `codeint.json` pins an official `$schema` tag newer than the running binary, codeint stops with exit code `2` and instructs you to upgrade.

```json
{
Expand Down
2 changes: 1 addition & 1 deletion docs/reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ In the key paths below, `[]` stands for each item of a list, and a name in brace

| Key | Type | Meaning |
| --- | ---- | ------- |
| `$schema` | string | The address of the JSON schema, for editors; codeint does not read it |
| `$schema` | string | The address of the JSON schema, for editors; when it points to a newer official codeint release tag than the running binary, codeint exits with code 2 |
| `source_sets` | object | Globs that put files into a Source set; see [Source sets](#source-sets) |
| `source_sets.{source_set}` | list of strings | Globs of repository-relative paths that belong to this Source set; empty by default |
| `budgets` | object | The Budgets of each Source set; see [Budgets](#budgets) |
Expand Down