Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move to ignore for ignoring files #640

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
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
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/taplo-cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ codespan-reporting = "0.11.1"
futures = "0.3"
glob = "0.3"
hex = "0.4"
ignore = "0.4.22"
itertools = "0.10.3"
once_cell = "1.4"
regex = "1.4"
Expand Down
2 changes: 1 addition & 1 deletion crates/taplo-cli/src/commands/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ impl<E: Environment> Taplo<E> {
.ok_or_else(|| anyhow!("could not figure the current working directory"))?;

let files = self
.collect_files(&cwd, &config, mem::take(&mut cmd.files).into_iter())
.files_iter(&cwd, &config, mem::take(&mut cmd.files).into_iter())
.await?;

let mut result = Ok(());
Expand Down
2 changes: 1 addition & 1 deletion crates/taplo-cli/src/commands/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ impl<E: Environment> Taplo<E> {
.ok_or_else(|| anyhow!("could not figure the current working directory"))?;

let files = self
.collect_files(&cwd, &config, cmd.files.into_iter())
.files_iter(&cwd, &config, cmd.files.into_iter())
.await?;

let mut result = Ok(());
Expand Down
5 changes: 4 additions & 1 deletion crates/taplo-cli/src/commands/lsp.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use taplo_common::environment::{native::NativeEnvironment, Environment};

use crate::{args::{LspCommand, LspCommandIo}, Taplo};
use crate::{
args::{LspCommand, LspCommandIo},
Taplo,
};

impl<E: Environment> Taplo<E> {
pub async fn execute_lsp(&mut self, cmd: LspCommand) -> Result<(), anyhow::Error> {
Expand Down
99 changes: 71 additions & 28 deletions crates/taplo-cli/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use anyhow::{anyhow, Context};
use args::GeneralArgs;
use itertools::Itertools;
use std::{
path::{Path, PathBuf},
str,
Expand All @@ -12,6 +11,8 @@ pub mod args;
pub mod commands;
pub mod printing;

pub type EntryIter<'a, F> = std::iter::FilterMap<ignore::Walk, F>;

pub struct Taplo<E: Environment> {
env: E,
colors: bool,
Expand Down Expand Up @@ -84,17 +85,25 @@ impl<E: Environment> Taplo<E> {
}

#[tracing::instrument(skip_all, fields(?cwd))]
async fn collect_files(
async fn files_iter(
&self,
cwd: &Path,
config: &Config,
arg_patterns: impl Iterator<Item = String>,
) -> Result<Vec<PathBuf>, anyhow::Error> {
) -> Result<
EntryIter<'_, Box<dyn FnMut(Result<ignore::DirEntry, ignore::Error>) -> Option<PathBuf>>>,
anyhow::Error,
> {
tracing::trace!("Nomarlizing patterns to absolute ones...");

let mut patterns: Vec<String> = arg_patterns
.map(|pat| {
if !self.env.is_absolute(Path::new(&pat)) {
cwd.join(&pat).normalize().to_string_lossy().into_owned()
let pat = cwd.join(&pat).normalize().to_string_lossy().into_owned();
tracing::debug!("Arg(abs) {} ", &pat);
pat
} else {
tracing::debug!("Arg(rel) {} ", &pat);
pat
}
})
Expand All @@ -111,33 +120,67 @@ impl<E: Environment> Taplo<E> {
};
};

let patterns = patterns
.into_iter()
.unique()
.map(|p| glob::Pattern::new(&p).map(|_| p))
.collect::<Result<Vec<_>, _>>()?;

let files = patterns
.into_iter()
.map(|pat| self.env.glob_files_normalized(&pat))
.collect::<Result<Vec<_>, _>>()
.into_iter()
.flatten()
.flatten()
.collect::<Vec<_>>();

let total = files.len();
tracing::trace!("Compiled patterns");

let files = files
.into_iter()
.filter(|path| config.is_included(path))
.collect::<Vec<_>>();
let mut skip_patterns = vec![];
let mut keep_patterns = vec![];

let excluded = total - files.len();

tracing::info!(total, excluded, "found files");
let opts = glob::MatchOptions {
case_sensitive: true,
..Default::default()
};

Ok(files)
let cwd = cwd.to_path_buf();

let mut bldr = ignore::WalkBuilder::new(&cwd);
bldr.git_ignore(true)
.git_exclude(true)
.git_global(true)
.ignore(true)
.hidden(false)
.same_file_system(true);

for skip_pattern in config.exclude.iter().cloned().flatten() {
if let Ok(pat) = glob::Pattern::new(&skip_pattern) {
tracing::trace!("Compiling pattern: {skip_pattern}");
skip_patterns.push(pat.clone());
bldr.filter_entry(move |entry| !pat.matches_path_with(entry.path(), opts));
}
}
for keep_pattern in config
.include
.iter()
.cloned()
.flatten()
.map(|x| x.to_owned())
.chain(patterns.into_iter())
{
if let Ok(pat) = glob::Pattern::new(&keep_pattern) {
tracing::trace!("Compiling pattern: {pat}");
keep_patterns.push(pat.clone());
bldr.filter_entry(move |entry| pat.matches_path_with(entry.path(), opts));
}
}
let walker = bldr.build();

Ok(walker.filter_map(Box::new(
move |entry: Result<ignore::DirEntry, ignore::Error>| -> Option<PathBuf> {
let entry = entry.ok()?;
debug_assert!(!skip_patterns
.iter()
.any(|pat| pat.matches_path_with(entry.path(), opts.clone())));
debug_assert!(keep_patterns
.iter()
.any(|pat| pat.matches_path_with(entry.path(), opts)));
if entry.path() == cwd {
None
} else {
let p = entry.path().to_path_buf();
tracing::debug!("Path passed filters: {}", p.display());
Some(p)
}
},
)))
}
}

Expand Down
5 changes: 3 additions & 2 deletions crates/taplo-lsp/src/world.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,8 +246,9 @@ impl<E: Environment> WorkspaceState<E> {
};

if let Some(config_path) = config_path {
tracing::info!(path = ?config_path, "using config file");
self.taplo_config = toml::from_str(str::from_utf8(&env.read_file(&config_path).await?)?)?;
tracing::debug!(path = ?config_path, "using config file");
self.taplo_config =
toml::from_str(str::from_utf8(&env.read_file(&config_path).await?)?)?;
}
}

Expand Down
4 changes: 3 additions & 1 deletion crates/taplo/src/formatter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -681,7 +681,9 @@
entry.value.clear();

if let Some(c) = value.trailing_comment() {
debug_assert!(entry.comment.is_none() || entry.comment.clone().unwrap() == c);
debug_assert!(
entry.comment.is_none() || entry.comment.clone().unwrap() == c
);
entry.comment = Some(c);
}

Expand Down Expand Up @@ -1183,7 +1185,7 @@
}

trait FormattedItem {
fn syntax(&self) -> SyntaxElement;

Check warning on line 1188 in crates/taplo/src/formatter/mod.rs

View workflow job for this annotation

GitHub Actions / Test on Rust stable

method `syntax` is never used
#[allow(clippy::ptr_arg)]
fn write_to(&self, formatted: &mut String, options: &Options);
fn trailing_comment(&self) -> Option<String>;
Expand Down
Loading