Infer package roots when running via stdin (#1321)

This commit is contained in:
Charlie Marsh
2022-12-21 20:30:10 -05:00
committed by GitHub
parent 5c70f5044b
commit 66a6c81ebf
3 changed files with 15 additions and 6 deletions

View File

@@ -114,16 +114,19 @@ fn read_from_stdin() -> Result<String> {
/// Run the linter over a single file, read from `stdin`.
pub fn run_stdin(
filename: Option<&Path>,
strategy: &PyprojectDiscovery,
filename: &Path,
autofix: fixer::Mode,
) -> Result<Diagnostics> {
let package_root = filename
.and_then(std::path::Path::parent)
.and_then(packages::detect_package_root);
let stdin = read_from_stdin()?;
let settings = match strategy {
PyprojectDiscovery::Fixed(settings) => settings,
PyprojectDiscovery::Hierarchical(settings) => settings,
};
let mut diagnostics = lint_stdin(filename, &stdin, settings, autofix)?;
let mut diagnostics = lint_stdin(filename, package_root, &stdin, settings, autofix)?;
diagnostics.messages.sort_unstable();
Ok(diagnostics)
}

View File

@@ -260,7 +260,8 @@ pub fn autoformat_path(path: &Path, _settings: &Settings) -> Result<()> {
/// Generate a list of `Check` violations from source code content derived from
/// stdin.
pub fn lint_stdin(
path: &Path,
path: Option<&Path>,
package: Option<&Path>,
stdin: &str,
settings: &Settings,
autofix: fixer::Mode,
@@ -269,7 +270,13 @@ pub fn lint_stdin(
let contents = stdin.to_string();
// Lint the file.
let (contents, fixed, messages) = lint(contents, path, None, settings, autofix)?;
let (contents, fixed, messages) = lint(
contents,
path.unwrap_or_else(|| Path::new("-")),
package,
settings,
autofix,
)?;
// Write the fixed contents to stdout.
if matches!(autofix, fixer::Mode::Apply) {

View File

@@ -224,8 +224,7 @@ fn inner_main() -> Result<ExitCode> {
// Generate lint violations.
let diagnostics = if is_stdin {
let path = cli.stdin_filename.unwrap_or_else(|| PathBuf::from("-"));
commands::run_stdin(&pyproject_strategy, &path, autofix)?
commands::run_stdin(cli.stdin_filename.as_deref(), &pyproject_strategy, autofix)?
} else {
commands::run(
&cli.files,