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
3 changes: 2 additions & 1 deletion crates/cli/src/check.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,12 +202,13 @@ fn check_loaded(
) -> Result<Report, CheckError> {
let tree = repository.working_tree()?;
let languages = measure_with(&tree, plugins, configuration)?;
Ok(Report::summarize_with_metrics(
Ok(Report::summarize_with_metrics_and_boundaries(
languages,
tree.submodules().to_vec(),
findings,
&configuration.budgets,
metric_plugins,
configuration.boundaries.as_ref(),
)?)
}

Expand Down
3 changes: 2 additions & 1 deletion crates/cli/src/commit_measurement.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,9 @@ pub(crate) fn measure_all_languages(
let named = plugins.as_named();
let metric_plugins = plugins.metric_plugins();
let languages = measure_with(tree, &named, configuration)?;
Ok(CommitMeasurement::of_with_metrics(
Ok(CommitMeasurement::of_with_metrics_and_boundaries(
CodeModel::merge(languages.into_iter().map(|language| language.model)),
&metric_plugins,
configuration.boundaries.as_ref(),
)?)
}
132 changes: 132 additions & 0 deletions crates/cli/src/guard.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
use std::path::{Component, Path, PathBuf};

use codeint_config::{ConfigurationFileError, read_configuration};
use codeint_git::{GitError, Repository};
use codeint_model::{InvalidRepoPath, RepoPath};
use codeint_report::GuardReport;

#[derive(Debug, thiserror::Error)]
pub(crate) enum GuardError {
#[error(transparent)]
Git(#[from] GitError),
#[error(transparent)]
Configuration(#[from] ConfigurationFileError),
#[error("{} is outside the Git repository at {}", path.display(), root.display())]
OutsideRepository { path: PathBuf, root: PathBuf },
#[error("{} is not a valid UTF-8 repository path", path.display())]
NonUtf8Path { path: PathBuf },
#[error("{} is not a valid repository path: {source}", path.display())]
InvalidPath {
path: PathBuf,
#[source]
source: InvalidRepoPath,
},
}

pub(crate) fn guard(folder: &Path, target: &Path) -> Result<GuardReport, GuardError> {
let absolute_target = normalize_lexically(&if target.is_absolute() {
target.to_path_buf()
} else {
folder.join(target)
});
let discovery_start = nearest_existing_ancestor(&absolute_target).unwrap_or(folder);
let repository = match Repository::discover(discovery_start) {
Ok(repo) => repo,
Err(_) if discovery_start != folder => Repository::discover(folder)?,
Err(err) => return Err(GuardError::Git(err)),
};

let canonical_root = std::fs::canonicalize(repository.root())
.unwrap_or_else(|_| repository.root().to_path_buf());
let resolved_target = canonicalize_with_tail(&absolute_target);
let relative = resolved_target
.strip_prefix(&canonical_root)
.or_else(|_| resolved_target.strip_prefix(repository.root()))
.map_err(|_| GuardError::OutsideRepository {
path: target.to_path_buf(),
root: repository.root().to_path_buf(),
})?;

let repo_path = to_repo_path(relative, target)?;
let exists = resolved_target.exists();
let configuration = read_configuration(repository.root())?;
Ok(GuardReport::evaluate(
&repo_path,
exists,
configuration.boundaries.as_ref(),
))
}

fn nearest_existing_ancestor(path: &Path) -> Option<&Path> {
let mut cursor = Some(path);
while let Some(candidate) = cursor {
if candidate.exists() {
if candidate.is_dir() {
return Some(candidate);
}
return candidate.parent();
}
cursor = candidate.parent();
}
None
}

fn canonicalize_with_tail(path: &Path) -> PathBuf {
let mut missing = Vec::new();
let mut cursor = path;
loop {
if cursor.exists() {
let mut base = std::fs::canonicalize(cursor).unwrap_or_else(|_| cursor.to_path_buf());
for segment in missing.into_iter().rev() {
base.push(segment);
}
return base;
}
match (cursor.parent(), cursor.file_name()) {
(Some(parent), Some(name)) => {
missing.push(name.to_os_string());
cursor = parent;
}
_ => return path.to_path_buf(),
}
}
}

fn normalize_lexically(path: &Path) -> PathBuf {
let mut normalized = PathBuf::new();
for component in path.components() {
match component {
Component::CurDir => {}
Component::ParentDir => {
normalized.pop();
}
other => normalized.push(other.as_os_str()),
}
}
normalized
}

fn to_repo_path(relative: &Path, original: &Path) -> Result<RepoPath, GuardError> {
let mut segments = Vec::new();
for component in relative.components() {
match component {
Component::Normal(part) => {
let text = part.to_str().ok_or_else(|| GuardError::NonUtf8Path {
path: original.to_path_buf(),
})?;
segments.push(text);
}
Component::CurDir => {}
_ => {
return Err(GuardError::NonUtf8Path {
path: original.to_path_buf(),
});
}
}
}
let joined = segments.join("/");
RepoPath::new(&joined).map_err(|source| GuardError::InvalidPath {
path: original.to_path_buf(),
source,
})
}
23 changes: 21 additions & 2 deletions crates/cli/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
mod check;
mod commit_measurement;
mod diff;
mod guard;
mod init;
mod mcp;
mod remedy;
Expand All @@ -20,9 +21,10 @@ use codeint_git::ResultCache;
use codeint_report::ReportError;

pub use codeint_config::{
CalendarDay, FindingsShown, PluginHostConfig, ReportFormat, TrendFormat, TrendRange,
CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat,
TrendRange,
};
pub use codeint_report::{DiffReport, Report, TrendReport};
pub use codeint_report::{DiffReport, GuardReport, Report, TrendReport};

const DEFAULT_WORST_FINDINGS: usize = 20;
const DEFAULT_TREND_COMMITS: usize = 20;
Expand Down Expand Up @@ -182,13 +184,19 @@ pub fn init(folder: &Path) -> Result<PathBuf, CodeintError> {
init::init(folder).map_err(|err| CodeintError::from_cli_error(CliError::Init(err)))
}

pub fn guard(folder: &Path, target: &Path) -> Result<GuardReport, CodeintError> {
guard::guard(folder, target).map_err(|err| CodeintError::from_cli_error(CliError::Guard(err)))
}

#[derive(Debug, thiserror::Error)]
enum CliError {
#[error(transparent)]
Config(#[from] ConfigError),
#[error(transparent)]
Check(#[from] check::CheckError),
#[error(transparent)]
Guard(#[from] guard::GuardError),
#[error(transparent)]
Init(#[from] init::InitError),
#[error(transparent)]
Update(#[from] update::UpdateError),
Expand Down Expand Up @@ -291,9 +299,20 @@ fn run() -> Result<Outcome, CliError> {
result_cache,
plugin_host,
} => run_mcp(&folder, result_cache, plugin_host),
Command::Guard {
folder,
target,
format,
} => run_guard(&folder, &target, format),
}
}

fn run_guard(folder: &Path, target: &Path, format: GuardFormat) -> Result<Outcome, CliError> {
let report = guard::guard(folder, target)?;
print_report(&format!("{}\n", report.render(format)?))?;
Ok(Outcome::Passed)
}

fn run_init(folder: &Path) -> Result<Outcome, CliError> {
let written = init::init(folder)?;
print_report(&format!("Wrote {}\n", written.display()))?;
Expand Down
69 changes: 55 additions & 14 deletions crates/cli/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ use std::path::{Path, PathBuf};
use std::str::FromStr;

use codeint_config::{
CalendarDay, FindingsShown, PluginHostConfig, ReportFormat, TrendFormat, TrendRange,
CalendarDay, FindingsShown, GuardFormat, PluginHostConfig, ReportFormat, TrendFormat,
TrendRange,
};
use serde_json::{Value, json};

use crate::{CheckOptions, DiffOptions, TrendOptions, check, diff, trend};
use crate::{CheckOptions, DiffOptions, TrendOptions, check, diff, guard, trend};

const DEFAULT_PROTOCOL_VERSION: &str = "2024-11-05";

Expand Down Expand Up @@ -157,6 +158,18 @@ fn handle_tools_list() -> Value {
"since": { "type": "string", "description": "UTC date YYYY-MM-DD to start the trend from." }
}
}
},
{
"name": "guard",
"description": "Query the architectural boundary zone, allowed and denied target zones, public_files constraints, and allowed importers for an existing or planned file path.",
"inputSchema": {
"type": "object",
"required": ["file"],
"properties": {
"file": { "type": "string", "description": "Repository-relative or absolute path to the existing or planned file." },
"path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }
}
}
}
]
})
Expand All @@ -175,6 +188,7 @@ fn handle_tools_call(
"check" => Ok(call_check(args, ctx)),
"diff" => Ok(call_diff(args, ctx)),
"trend" => Ok(call_trend(args, ctx)),
"guard" => Ok(call_guard(args, ctx)),
other => Err((-32602, format!("Unknown tool: {other}"))),
}
}
Expand All @@ -196,8 +210,9 @@ fn call_check(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value {
}

fn call_diff(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value {
let Some(base_ref) = args.and_then(|a| a.get("base_ref")).and_then(Value::as_str) else {
return tool_err("Missing required argument: base_ref");
let base_ref = match required_str_arg(args, "base_ref") {
Ok(value) => value,
Err(err) => return err,
};
let folder = resolve_folder(args, ctx.default_folder);
let options = DiffOptions {
Expand Down Expand Up @@ -237,6 +252,28 @@ fn render_outcome(
}
}

fn render_json_tool<T, E: std::fmt::Display>(
result: Result<T, E>,
render: impl FnOnce(T) -> Result<String, codeint_report::ReportError>,
) -> Value {
match result {
Ok(report) => match render(report) {
Ok(rendered) => {
let payload: Value = serde_json::from_str(&rendered).unwrap_or(Value::Null);
tool_ok(payload)
}
Err(err) => tool_err(&err.to_string()),
},
Err(err) => tool_err(&err.to_string()),
}
}

fn required_str_arg<'a>(args: Option<&'a Value>, name: &str) -> Result<&'a str, Value> {
args.and_then(|a| a.get(name))
.and_then(Value::as_str)
.ok_or_else(|| tool_err(&format!("Missing required argument: {name}")))
}

fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value {
let folder = resolve_folder(args, ctx.default_folder);
let range = match args.and_then(|a| a.get("since")).and_then(Value::as_str) {
Expand All @@ -251,16 +288,20 @@ fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value {
result_cache: ctx.result_cache.clone(),
plugin_host: ctx.plugin_host.clone(),
};
match trend(&folder, &options) {
Ok(report) => match report.render(TrendFormat::Json) {
Ok(rendered) => {
let payload: Value = serde_json::from_str(&rendered).unwrap_or(Value::Null);
tool_ok(payload)
}
Err(err) => tool_err(&err.to_string()),
},
Err(err) => tool_err(&err.to_string()),
}
render_json_tool(trend(&folder, &options), |report| {
report.render(TrendFormat::Json)
})
}

fn call_guard(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value {
let file = match required_str_arg(args, "file") {
Ok(value) => value,
Err(err) => return err,
};
let folder = resolve_folder(args, ctx.default_folder);
render_json_tool(guard(&folder, Path::new(file)), |report| {
report.render(GuardFormat::Json)
})
}

fn resolve_folder(args: Option<&Value>, default_folder: &Path) -> PathBuf {
Expand Down
Loading