Skip to content

Commit bb360ab

Browse files
fix(cli): address custom language trust review
1 parent 8ba0011 commit bb360ab

6 files changed

Lines changed: 132 additions & 10 deletions

File tree

‎Cargo.lock‎

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎crates/cli/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ clap = { version = "4.5.4", features = ["derive"] }
3939
codespan-reporting = "0.13.0"
4040
crossterm = "0.29.0"
4141
directories = "6.0.0"
42+
fs2 = "0.4.3"
4243
ignore.workspace = true
4344
regex.workspace = true
4445
dashmap.workspace = true

‎crates/cli/src/config.rs‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ impl ProjectConfig {
7676
let Some(config_path) = config_path else {
7777
return Ok(None);
7878
};
79+
let config_path = config_path.canonicalize().context(EC::ReadConfiguration)?;
7980
let config_str = read_to_string(&config_path).context(EC::ReadConfiguration)?;
8081
let sg_config: AstGrepConfig = from_str(&config_str).context(EC::ParseConfiguration)?;
8182
let project_dir = config_path
@@ -324,6 +325,8 @@ pub(crate) fn find_config_path_with_default(
324325
#[cfg(test)]
325326
mod tests {
326327
use super::*;
328+
use std::fs;
329+
use tempfile::TempDir;
327330

328331
#[test]
329332
fn custom_language_outline_rules_are_project_relative() {
@@ -343,4 +346,31 @@ customLanguages:
343346

344347
assert_eq!(paths, vec![PathBuf::from("/project/outline/blade.yml")]);
345348
}
349+
350+
#[cfg(unix)]
351+
#[test]
352+
fn symlinked_config_uses_canonical_project_directory() {
353+
use std::os::unix::fs::symlink;
354+
355+
let root = TempDir::new().expect("temporary directory should be created");
356+
let project = root.path().join("project");
357+
let links = root.path().join("links");
358+
fs::create_dir_all(&project).expect("project directory should be created");
359+
fs::create_dir_all(&links).expect("link directory should be created");
360+
let config = project.join("sgconfig.yml");
361+
fs::write(&config, "ruleDirs: []\n").expect("configuration should be written");
362+
let linked_config = links.join("sgconfig.yml");
363+
symlink(&config, &linked_config).expect("configuration symlink should be created");
364+
365+
let (project_dir, _) = ProjectConfig::discover_project(Some(linked_config))
366+
.expect("configuration should be discovered")
367+
.expect("project should exist");
368+
369+
assert_eq!(
370+
project_dir,
371+
project
372+
.canonicalize()
373+
.expect("project directory should be canonicalized")
374+
);
375+
}
346376
}

‎crates/cli/src/custom_language.rs‎

Lines changed: 51 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@ use crate::utils::ErrorContext as EC;
44
use anyhow::{Context, Result};
55
use clap::ValueEnum;
66
use directories::ProjectDirs;
7+
use fs2::FileExt;
78
use std::collections::BTreeSet;
8-
use std::fs;
9+
use std::fs::{self, OpenOptions};
910
use std::io::{IsTerminal, Write};
1011
use std::path::{Path, PathBuf};
1112

@@ -113,36 +114,53 @@ fn confirm_trust(config_path: Option<&Path>) -> Result<()> {
113114

114115
fn is_trusted(config_path: Option<&Path>) -> bool {
115116
canonical_config_path(config_path)
116-
.and_then(|path| load_store().map(|store| store.contains(&path)))
117+
.and_then(|path| {
118+
let store_path = trust_store_path()?;
119+
load_store(&store_path).map(|store| store.contains(&path))
120+
})
117121
.unwrap_or(false)
118122
}
119123

120124
fn set_trusted(config_path: Option<&Path>, trusted: bool) -> Result<()> {
121-
let config_path = canonical_config_path(config_path)?;
122-
let mut store = load_store()?;
125+
let config_path = if trusted {
126+
canonical_config_path(config_path)?
127+
} else {
128+
config_path_for_revoke(config_path)?
129+
};
130+
let store_path = trust_store_path()?;
131+
let parent = store_path.parent().expect("trust store path has a parent");
132+
fs::create_dir_all(parent).context("Cannot create the ast-grep configuration directory")?;
133+
let lock = OpenOptions::new()
134+
.read(true)
135+
.write(true)
136+
.create(true)
137+
.truncate(false)
138+
.open(parent.join("trusted-configs.lock"))
139+
.context("Cannot open the ast-grep trust store lock")?;
140+
FileExt::lock_exclusive(&lock).context("Cannot lock the ast-grep trust store")?;
141+
142+
let mut store = load_store(&store_path)?;
123143
let changed = if trusted {
124144
store.insert(config_path)
125145
} else {
126146
store.remove(&config_path)
127147
};
128148
if changed {
129-
save_store(&store)?;
149+
save_store(&store_path, &store)?;
130150
}
131151
Ok(())
132152
}
133153

134-
fn load_store() -> Result<BTreeSet<PathBuf>> {
135-
match fs::read(trust_store_path()?) {
154+
fn load_store(path: &Path) -> Result<BTreeSet<PathBuf>> {
155+
match fs::read(path) {
136156
Ok(json) => serde_json::from_slice(&json).context("Cannot parse the ast-grep trust store"),
137157
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(BTreeSet::new()),
138158
Err(error) => Err(error).context("Cannot read the ast-grep trust store"),
139159
}
140160
}
141161

142-
fn save_store(store: &BTreeSet<PathBuf>) -> Result<()> {
143-
let path = trust_store_path()?;
162+
fn save_store(path: &Path, store: &BTreeSet<PathBuf>) -> Result<()> {
144163
let parent = path.parent().expect("trust store path has a parent");
145-
fs::create_dir_all(parent).context("Cannot create the ast-grep configuration directory")?;
146164
let mut temp = tempfile::NamedTempFile::new_in(parent)?;
147165
temp.write_all(&serde_json::to_vec_pretty(store)?)?;
148166
temp.persist(path).map_err(|error| error.error)?;
@@ -164,6 +182,29 @@ fn canonical_config_path(config_path: Option<&Path>) -> Result<PathBuf> {
164182
fs::canonicalize(config_path).context("Cannot resolve the ast-grep configuration path")
165183
}
166184

185+
fn config_path_for_revoke(config_path: Option<&Path>) -> Result<PathBuf> {
186+
let config_path = find_config_path_with_default(config_path.map(Path::to_path_buf))?
187+
.context("Cannot find the ast-grep configuration file")?;
188+
match fs::canonicalize(&config_path) {
189+
Ok(path) => Ok(path),
190+
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
191+
let file_name = config_path
192+
.file_name()
193+
.context("Configuration path must have a file name")?;
194+
let parent = config_path
195+
.parent()
196+
.filter(|parent| !parent.as_os_str().is_empty())
197+
.unwrap_or_else(|| Path::new("."));
198+
Ok(
199+
fs::canonicalize(parent)
200+
.context("Cannot resolve the ast-grep configuration directory")?
201+
.join(file_name),
202+
)
203+
}
204+
Err(error) => Err(error).context("Cannot resolve the ast-grep configuration path"),
205+
}
206+
}
207+
167208
#[cfg(test)]
168209
mod test {
169210
use super::*;

‎crates/cli/src/lib.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,9 @@ fn setup_project_is_possible(
113113
let mut config = None;
114114
for i in 0..args.len() {
115115
let arg = &args[i];
116+
if arg == "--" {
117+
break;
118+
}
116119
if let Some(config_file) = arg.strip_prefix("-c").filter(|path| !path.is_empty()) {
117120
config = Some(config_file.strip_prefix('=').unwrap_or(config_file).into());
118121
break;

‎crates/cli/tests/custom_language_policy_test.rs‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -191,3 +191,39 @@ fn remembered_trust_uses_attached_config_path() -> Result<()> {
191191
.stderr(contains("Cannot load custom language library"));
192192
Ok(())
193193
}
194+
195+
#[test]
196+
fn config_path_after_delimiter_is_not_used_for_project_setup() -> Result<()> {
197+
let dir = create_test_files([
198+
("sgconfig.yml", CUSTOM_LANGUAGE_CONFIG),
199+
("other.yml", CUSTOM_LANGUAGE_CONFIG),
200+
])?;
201+
let trust_dir = TempDir::new()?;
202+
remember_project(dir.path().join("other.yml"), &trust_dir)?;
203+
204+
command_with_trust_store(&dir, &trust_dir)
205+
.args(["-p", "foo", "--", "-cother.yml"])
206+
.assert()
207+
.failure()
208+
.stderr(contains("Cannot load custom language library").not());
209+
Ok(())
210+
}
211+
212+
#[test]
213+
fn deleted_config_can_be_revoked() -> Result<()> {
214+
let dir = create_test_files([("project.yml", CUSTOM_LANGUAGE_CONFIG)])?;
215+
let trust_dir = TempDir::new()?;
216+
let config = dir.path().join("project.yml");
217+
remember_project(config.clone(), &trust_dir)?;
218+
fs::remove_file(&config)?;
219+
220+
command_with_trust_store(&dir, &trust_dir)
221+
.args(["scan", "--custom-languages", "revoke", "-cproject.yml"])
222+
.assert()
223+
.failure();
224+
225+
let stored: BTreeSet<PathBuf> =
226+
serde_json::from_slice(&fs::read(trust_dir.path().join("trusted-configs.json"))?)?;
227+
assert!(stored.is_empty());
228+
Ok(())
229+
}

0 commit comments

Comments
 (0)