Skip to content
Open
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
1 change: 1 addition & 0 deletions crates/pyrefly_config/src/environment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ pub mod environment;
pub(crate) mod interpreter_query;
pub mod interpreters;
pub(crate) mod pixi;
pub mod script;
pub(crate) mod venv;
47 changes: 47 additions & 0 deletions crates/pyrefly_config/src/environment/script.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

//! PEP 723 scripts, which carry their own dependency metadata.

/// Returns the contents of the PEP 723 `script` metadata block in `source`, if it has one.
pub fn metadata(source: &str) -> Option<&str> {
let mut start = None;
let mut offset = 0;
for line in source.split_inclusive('\n') {
let text = line.trim_end_matches(['\n', '\r']);
match start {
None if text == "# /// script" => start = Some(offset + line.len()),
Some(start) if text == "# ///" => return Some(&source[start..offset]),
Some(_) if text != "#" && !text.starts_with("# ") => start = None,
_ => {}
}
offset += line.len();
}
None
}

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

#[test]
fn test_metadata() {
assert_eq!(
metadata(
"#!/usr/bin/env python\n# /// script\n# dependencies = [\"six\"]\n#\n# ///\nimport six\n"
),
Some("# dependencies = [\"six\"]\n#\n"),
);
assert_eq!(
metadata("# /// script\r\n# requires-python = \">=3.12\"\r\n# ///\r\n"),
Some("# requires-python = \">=3.12\"\r\n"),
);
assert_eq!(metadata("# /// script\nimport six\n# ///\n"), None);
assert_eq!(metadata("# /// pyproject\n# ///\n"), None);
assert_eq!(metadata("x = 1\n"), None);
}
}
14 changes: 14 additions & 0 deletions crates/pyrefly_util/src/globs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,15 @@ impl Globs {
res
}

/// The existing files named by patterns without wildcards. [`Globs::files_iter`] yields these
/// paths as they are, without walking for them.
pub fn explicit_files(&self) -> impl Iterator<Item = &Path> {
self.0
.iter()
.filter(|pattern| pattern.is_explicit_file_pattern())
.map(Glob::as_path)
}

/// Returns true if the given file matches any of the contained globs.
/// Directory-style matching is handled by each [`Glob`]'s precomputed
/// `<pattern>/**` variant.
Expand Down Expand Up @@ -1062,6 +1071,11 @@ impl FilteredGlobs {
filter: GlobFilter::new(excludes, ignorefile_search_start, hidden_dir_filter),
}
}

/// Adds `excludes` to the excludes of this [`FilteredGlobs`].
pub fn add_excludes(&mut self, excludes: &[Glob]) {
self.filter.excludes.append(excludes);
}
}

impl Includes for FilteredGlobs {
Expand Down
42 changes: 40 additions & 2 deletions pyrefly/lib/commands/config_finder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,21 @@ pub fn default_config_finder_with_overrides(
)
}

/// A config finder for `pyrefly check --project-dir`. A Python file under one of `dirs` gets the
/// config of the first directory that contains it, so `dirs` must be ordered deepest first. Any
/// other file gets the config that [`default_config_finder_with_overrides`] finds.
pub fn project_dirs_config_finder(
dirs: Vec<(PathBuf, ArcId<ConfigFile>)>,
args: ConfigOverrideArgs,
wrapper: Option<ConfigConfigurerWrapper>,
) -> ConfigFinder {
config_finder_with_dirs(
Arc::new(DefaultConfigConfigurerWithOverrides::new(args, false)),
wrapper,
dirs,
)
}

/// Create a standard `ConfigFinder`, using the provided [`ConfigConfigurer`] to finalize
/// the config before caching/returning it.
///
Expand All @@ -197,6 +212,16 @@ pub fn default_config_finder_with_overrides(
pub fn standard_config_finder(
configure: Arc<dyn ConfigConfigurer>,
wrapper: Option<ConfigConfigurerWrapper>,
) -> ConfigFinder {
config_finder_with_dirs(configure, wrapper, Vec::new())
}

/// [`standard_config_finder`], except that a Python file under one of `dirs` gets the config of
/// the first directory that contains it.
fn config_finder_with_dirs(
configure: Arc<dyn ConfigConfigurer>,
wrapper: Option<ConfigConfigurerWrapper>,
dirs: Vec<(PathBuf, ArcId<ConfigFile>)>,
) -> ConfigFinder {
let configure = match wrapper {
Some(wrap) => wrap(configure),
Expand Down Expand Up @@ -254,10 +279,23 @@ pub fn standard_config_finder(

ConfigFinder::new_custom(
Box::new(move |_, path| {
Ok(GENERATED_FILE_CONFIG_OVERRIDE
if let Some(config) = GENERATED_FILE_CONFIG_OVERRIDE
.read()
.get(&path.module_path_buf())
.cloned())
{
return Ok(Some(config.dupe()));
}
let file = match path.details() {
ModulePathDetails::FileSystem(file) | ModulePathDetails::Memory(file) => file,
ModulePathDetails::Namespace(_)
| ModulePathDetails::BundledTypeshed(_)
| ModulePathDetails::BundledTypeshedThirdParty(_)
| ModulePathDetails::BundledThirdParty(_) => return Ok(None),
};
Ok(dirs
.iter()
.find(|(dir, _)| file.starts_with(dir))
.map(|(_, config)| config.dupe()))
}),
Box::new(move |file| {
let (file_config, parse_errors) = ConfigFile::from_file(file);
Expand Down
Loading
Loading