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
11 changes: 9 additions & 2 deletions crates/sem-cli/src/commands/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,11 @@ fn find_entity<'a>(
std::process::exit(1);
});

let mut matching: Vec<_> = graph.entities.values().filter(|e| e.name == name).collect();
let mut matching: Vec<_> = graph
.entities
.values()
.filter(|e| super::entity_matches_query(e, name))
.collect();

if matching.is_empty() {
eprintln!("{} Entity '{}' not found", "error:".red().bold(), name);
Expand All @@ -155,7 +159,10 @@ fn find_entity<'a>(
matching.sort_by_key(|e| (&e.file_path, e.start_line));
eprintln!("{} Entity name '{}' is ambiguous ({} matches). Specify --file or --entity-id:", "error:".red().bold(), name, matching.len());
for m in &matching {
eprintln!(" {} ({}:L{})", m.id, m.file_path, m.start_line);
eprintln!(
" {} {} ({}:L{})",
m.entity_type, m.id, m.file_path, m.start_line
);
}
std::process::exit(1);
}
11 changes: 9 additions & 2 deletions crates/sem-cli/src/commands/impact.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,11 @@ fn find_entity<'a>(
std::process::exit(1);
});

let mut matching: Vec<_> = graph.entities.values().filter(|e| e.name == name).collect();
let mut matching: Vec<_> = graph
.entities
.values()
.filter(|e| super::entity_matches_query(e, name))
.collect();

if matching.is_empty() {
eprintln!("{} Entity '{}' not found", "error:".red().bold(), name);
Expand Down Expand Up @@ -108,7 +112,10 @@ fn find_entity<'a>(
matching.sort_by_key(|e| (&e.file_path, e.start_line));
eprintln!("{} Entity name '{}' is ambiguous ({} matches). Specify --file or --entity-id:", "error:".red().bold(), name, matching.len());
for m in &matching {
eprintln!(" {} ({}:L{})", m.id, m.file_path, m.start_line);
eprintln!(
" {} {} ({}:L{})",
m.entity_type, m.id, m.file_path, m.start_line
);
}
std::process::exit(1);
}
Expand Down
55 changes: 54 additions & 1 deletion crates/sem-cli/src/commands/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,27 @@ fn normalize_existing_prefix(path: &Path) -> Option<PathBuf> {
None
}

pub fn entity_matches_query(entity: &sem_core::parser::graph::EntityInfo, query: &str) -> bool {
if entity.name == query {
return true;
}

let Some((entity_type, name)) = split_type_qualified_query(query) else {
return false;
};

entity.entity_type == entity_type && entity.name == name
}

fn split_type_qualified_query(query: &str) -> Option<(&str, &str)> {
let (entity_type, name) = query.split_once(' ')?;
if entity_type.is_empty() || name.is_empty() {
return None;
}

Some((entity_type, name))
}

/// Truncate a string to `max_chars` Unicode scalar values (codepoints), appending "..." if
/// truncated. Safe for multibyte encodings (CJK, simple emoji). Note: does not split on grapheme
/// cluster boundaries — ZWJ emoji sequences may render incorrectly at the truncation point.
Expand Down Expand Up @@ -141,9 +162,41 @@ pub fn truncate_str(s: &str, max_chars: usize) -> String {

#[cfg(test)]
mod tests {
use super::{normalize_existing_prefix, normalize_lexical, normalize_repo_relative_path, truncate_str};
use super::{
entity_matches_query, normalize_existing_prefix, normalize_lexical,
normalize_repo_relative_path, truncate_str,
};
use sem_core::parser::graph::EntityInfo;
use std::path::Path;

fn entity(entity_type: &str, name: &str) -> EntityInfo {
EntityInfo {
id: format!("a.ts::{entity_type}::{name}"),
name: name.to_string(),
entity_type: entity_type.to_string(),
file_path: "a.ts".to_string(),
parent_id: None,
start_line: 1,
end_line: 1,
}
}

#[test]
fn entity_query_matches_exact_name() {
let entity = entity("function", "getter value");

assert!(entity_matches_query(&entity, "getter value"));
}

#[test]
fn entity_query_matches_type_qualified_name() {
let entity = entity("getter", "value");

assert!(entity_matches_query(&entity, "getter value"));
assert!(!entity_matches_query(&entity, "setter value"));
assert!(!entity_matches_query(&entity, "method value"));
}

#[test]
fn ascii_short_string_unchanged() {
assert_eq!(truncate_str("hello", 10), "hello");
Expand Down
4 changes: 2 additions & 2 deletions crates/sem-cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ enum Commands {
},
/// Show impact of changing an entity (deps, dependents, transitive impact, tests)
Impact {
/// Name of the entity to analyze
/// Name of the entity to analyze, optionally as "type name"
#[arg(required_unless_present = "entity_id")]
entity: Option<String>,

Expand Down Expand Up @@ -242,7 +242,7 @@ enum Commands {
},
/// Show token-budgeted context for an entity
Context {
/// Name of the entity
/// Name of the entity, optionally as "type name"
#[arg(required_unless_present = "entity_id")]
entity: Option<String>,

Expand Down
99 changes: 99 additions & 0 deletions crates/sem-cli/tests/accessor_cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
use std::fs;
use std::process::Command;

use tempfile::TempDir;

fn git(repo: &TempDir, args: &[&str]) {
let status = Command::new("git")
.current_dir(repo.path())
.args(args)
.status()
.unwrap();
assert!(status.success(), "git {:?} failed", args);
}

fn sem(repo: &TempDir, home: &TempDir, args: &[&str]) -> std::process::Output {
Command::new(env!("CARGO_BIN_EXE_sem"))
.current_dir(repo.path())
.env("HOME", home.path())
.args(args)
.output()
.expect("sem should run")
}

#[test]
fn context_and_impact_accept_type_qualified_accessor_queries() {
let repo = TempDir::new().unwrap();
let home = TempDir::new().unwrap();
git(&repo, &["init", "-q"]);

fs::write(
repo.path().join("box.ts"),
r#"export class Box {
private _v = 0;
get value(): number { return this._v; }
set value(n: number) { this._v = n; }
}
"#,
)
.unwrap();

let context = sem(
&repo,
&home,
&[
"context",
"getter value",
"--file",
"box.ts",
"--json",
"--no-cache",
],
);
assert!(
context.status.success(),
"sem context failed\nstdout: {}\nstderr: {}",
String::from_utf8_lossy(&context.stdout),
String::from_utf8_lossy(&context.stderr)
);
let context_json: serde_json::Value = serde_json::from_slice(&context.stdout).unwrap();
assert_eq!(context_json["entity"].as_str(), Some("value"));
assert_eq!(
context_json["entries"][0]["type"].as_str(),
Some("getter"),
"{context_json:?}"
);
assert!(
context_json["entityId"]
.as_str()
.is_some_and(|id| id.contains("::value@L3")),
"{context_json:?}"
);

let impact = sem(
&repo,
&home,
&[
"impact",
"setter value",
"--file",
"box.ts",
"--json",
"--no-cache",
],
);
assert!(
impact.status.success(),
"sem impact failed\nstdout: {}\nstderr: {}",
String::from_utf8_lossy(&impact.stdout),
String::from_utf8_lossy(&impact.stderr)
);
let impact_json: serde_json::Value = serde_json::from_slice(&impact.stdout).unwrap();
assert_eq!(impact_json["entity"]["type"].as_str(), Some("setter"));
assert!(
impact_json["entity"]["entityId"]
.as_str()
.is_some_and(|id| id.contains("::value@L4")),
"{impact_json:?}"
);
}
Loading
Loading