Skip to content

Commit 177ebca

Browse files
refactor: improve file config handling
fix ast-grep#1553
1 parent e6c87dd commit 177ebca

File tree

5 files changed

+36
-33
lines changed

5 files changed

+36
-33
lines changed

crates/cli/src/config.rs

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -53,20 +53,27 @@ pub struct AstGrepConfig {
5353
pub language_injections: Vec<SerializableInjection>,
5454
}
5555

56+
#[derive(Clone)]
5657
pub struct ProjectConfig {
5758
pub project_dir: PathBuf,
5859
pub sg_config: AstGrepConfig,
5960
}
6061

6162
impl ProjectConfig {
63+
pub fn by_config_path_must(config_path: Option<PathBuf>) -> Result<Self> {
64+
Self::discover_project(config_path, None)?.ok_or_else(|| anyhow::anyhow!(EC::ProjectNotExist))
65+
}
6266
pub fn by_config_path(config_path: Option<PathBuf>) -> Result<Option<Self>> {
63-
Self::find(config_path, None)
67+
Self::discover_project(config_path, None)
6468
}
6569
pub fn by_project_dir(project_dir: &Path) -> Result<Option<Self>> {
66-
Self::find(None, Some(project_dir))
70+
Self::discover_project(None, Some(project_dir))
6771
}
6872
// return None if config file does not exist
69-
pub fn find(config_path: Option<PathBuf>, base: Option<&Path>) -> Result<Option<Self>> {
73+
pub fn discover_project(
74+
config_path: Option<PathBuf>,
75+
base: Option<&Path>,
76+
) -> Result<Option<Self>> {
7077
let config_path =
7178
find_config_path_with_default(config_path, base).context(EC::ReadConfiguration)?;
7279
// NOTE: if config file does not exist, return None
@@ -85,16 +92,14 @@ impl ProjectConfig {
8592
sg_config,
8693
}))
8794
}
88-
}
8995

90-
pub fn find_rules(
91-
config_path: Option<PathBuf>,
92-
rule_overwrite: RuleOverwrite,
93-
) -> Result<(RuleCollection<SgLang>, RuleTrace)> {
94-
let project_config =
95-
ProjectConfig::by_config_path(config_path)?.ok_or(anyhow::anyhow!(EC::ProjectNotExist))?;
96-
let global_rules = find_util_rules(&project_config)?;
97-
read_directory_yaml(&project_config, global_rules, rule_overwrite)
96+
pub fn find_rules(
97+
&self,
98+
rule_overwrite: RuleOverwrite,
99+
) -> Result<(RuleCollection<SgLang>, RuleTrace)> {
100+
let global_rules = find_util_rules(self)?;
101+
read_directory_yaml(self, global_rules, rule_overwrite)
102+
}
98103
}
99104

100105
pub fn register_custom_language(project_config: Option<ProjectConfig>) -> Result<()> {
@@ -218,7 +223,7 @@ pub fn read_config_from_dir<P: AsRef<Path>>(path: P) -> Result<Option<ProjectCon
218223

219224
const CONFIG_FILE: &str = "sgconfig.yml";
220225

221-
pub fn find_config_path_with_default(
226+
fn find_config_path_with_default(
222227
config_path: Option<PathBuf>,
223228
base: Option<&Path>,
224229
) -> Result<PathBuf> {

crates/cli/src/lsp.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::config::{find_rules, register_custom_language, ProjectConfig};
1+
use crate::config::{register_custom_language, ProjectConfig};
22
use crate::utils::ErrorContext as EC;
33
use anyhow::{Context, Result};
44
use ast_grep_lsp::{Backend, LspService, Server};
@@ -14,14 +14,12 @@ pub struct LspArg {
1414

1515
async fn run_language_server_impl(arg: LspArg) -> Result<()> {
1616
// env_logger::init();
17-
let project_config = ProjectConfig::by_config_path(arg.config.clone())?;
1817
// TODO: move this error to client
19-
let project_config = project_config.ok_or_else(|| anyhow::anyhow!(EC::ProjectNotExist))?;
20-
let config_base = project_config.project_dir.clone();
21-
register_custom_language(Some(project_config))?;
18+
let project_config = ProjectConfig::by_config_path_must(arg.config.clone())?;
19+
register_custom_language(Some(project_config.clone()))?;
2220
let stdin = tokio::io::stdin();
2321
let stdout = tokio::io::stdout();
24-
let config_result = find_rules(arg.config, Default::default());
22+
let config_result = project_config.find_rules(Default::default());
2523
let config_result_std: std::result::Result<_, String> = config_result
2624
.map_err(|e| {
2725
// convert anyhow::Error to String with chain of causes
@@ -31,6 +29,7 @@ async fn run_language_server_impl(arg: LspArg) -> Result<()> {
3129
.join(". ")
3230
})
3331
.map(|r| r.0);
32+
let config_base = project_config.project_dir;
3433
let (service, socket) =
3534
LspService::build(|client| Backend::new(client, config_base, config_result_std)).finish();
3635
Server::new(stdin, stdout, socket).serve(service).await;

crates/cli/src/scan.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ use ast_grep_core::{NodeMatch, StrDoc};
99
use clap::Args;
1010
use ignore::WalkParallel;
1111

12-
use crate::config::{find_rules, read_rule_file, register_custom_language, ProjectConfig};
12+
use crate::config::{read_rule_file, register_custom_language, ProjectConfig};
1313
use crate::lang::SgLang;
1414
use crate::print::{
1515
CloudPrinter, ColoredPrinter, Diff, InteractivePrinter, JSONPrinter, Platform, Printer,
@@ -110,7 +110,7 @@ struct ScanWithConfig<Printer> {
110110
trace: ScanTrace,
111111
}
112112
impl<P: Printer> ScanWithConfig<P> {
113-
fn try_new(mut arg: ScanArg, printer: P) -> Result<Self> {
113+
fn try_new(arg: ScanArg, printer: P) -> Result<Self> {
114114
let mut rule_trace = RuleTrace::default();
115115
let configs = if let Some(path) = &arg.rule {
116116
let rules = read_rule_file(path, None)?;
@@ -120,8 +120,9 @@ impl<P: Printer> ScanWithConfig<P> {
120120
.with_context(|| EC::ParseRule("INLINE_RULES".into()))?;
121121
RuleCollection::try_new(rules).context(EC::GlobPattern)?
122122
} else {
123+
let project_config = ProjectConfig::by_config_path_must(arg.config.clone())?;
123124
let overwrite = RuleOverwrite::new(&arg.overwrite)?;
124-
let (configs, r_stats) = find_rules(arg.config.take(), overwrite)?;
125+
let (configs, r_stats) = project_config.find_rules(overwrite)?;
125126
rule_trace = r_stats;
126127
configs
127128
};

crates/cli/src/verify.rs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ mod reporter;
44
mod snapshot;
55
mod test_case;
66

7-
use crate::config::{find_rules, register_custom_language, ProjectConfig};
7+
use crate::config::{register_custom_language, ProjectConfig};
88
use crate::lang::SgLang;
99
use crate::utils::ErrorContext;
1010
use anyhow::{anyhow, Result};
@@ -57,7 +57,8 @@ where
5757
}
5858

5959
fn run_test_rule_impl<R: Reporter + Send>(arg: TestArg, reporter: R) -> Result<()> {
60-
let collections = &find_rules(arg.config.clone(), Default::default())?.0;
60+
let project_config = ProjectConfig::by_config_path_must(arg.config.clone())?;
61+
let collections = &project_config.find_rules(Default::default())?.0;
6162
let TestHarness {
6263
test_cases,
6364
snapshots,

crates/cli/src/verify/find_file.rs

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use super::{SnapshotCollection, TestCase, TestSnapshots};
2-
use crate::config::{find_config_path_with_default, AstGrepConfig};
2+
use crate::config::ProjectConfig;
33
use crate::utils::ErrorContext as EC;
44

55
use anyhow::{Context, Result};
@@ -90,16 +90,13 @@ pub fn find_tests(
9090
config_path: Option<PathBuf>,
9191
regex_filter: Option<&Regex>,
9292
) -> Result<TestHarness> {
93-
let config_path =
94-
find_config_path_with_default(config_path, None).context(EC::ReadConfiguration)?;
95-
let config_str = read_to_string(&config_path).context(EC::ReadConfiguration)?;
96-
let sg_config: AstGrepConfig = from_str(&config_str).context(EC::ParseConfiguration)?;
97-
let base_dir = config_path
98-
.parent()
99-
.expect("config file must have parent directory");
93+
let ProjectConfig {
94+
project_dir,
95+
sg_config,
96+
} = ProjectConfig::by_config_path_must(config_path)?;
10097
let test_configs = sg_config.test_configs.unwrap_or_default();
10198
let mut builder = HarnessBuilder {
102-
base_dir: base_dir.to_path_buf(),
99+
base_dir: project_dir,
103100
regex_filter,
104101
dest: TestHarness::default(),
105102
};

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy