streetsidesoftware / cspell

A Spell Checker for Code!
https://cspell.org
MIT License
1.24k stars 92 forks source link

[Bug]: Incorrect handling of negate rules in .gitignore #5104

Open gdlol opened 9 months ago

gdlol commented 9 months ago

Info

Which Version

Version: 8.2.1

Issue with supporting library?

Bug Description

Describe the bug

When using the useGitignore option, patterns in .gitignore seems not being processed in order. The issue seems to be that in this line where positive rules and negative rules are handled separately, hence not handling scenarios like ignore-then-unignore/unignore-then-ignore correctly according to Git behavior.

To Reproduce A minimal script to reproduce the bug: package.json

{
  "private": true,
  "type": "module",
  "dependencies": {
    "cspell-glob": "8.2.1"
  }
}

index.js

import { GlobMatcher } from "cspell-glob";

const globMatcher = new GlobMatcher(["*ignored/", "!un-ignored/", "node_modules/"], {
  root: "/test",
});

const check = (path, expected) => {
  const ignored = globMatcher.match(path);
  console.log(`path: ${path}, ignored: ${ignored}, expected: ${expected}`);
};

check("/test/test.txt", false);
check("/test/ignored/test.txt", true);
check("/test/node_modules/test.txt", true);
check("/test/un-ignored/test.txt", false);
check("/test/un-ignored/node_modules/test.txt", true);

Output (node index.js):

path: /test/test.txt, ignored: false, expected: false
path: /test/ignored/test.txt, ignored: true, expected: true
path: /test/node_modules/test.txt, ignored: true, expected: true
path: /test/un-ignored/test.txt, ignored: false, expected: false
path: /test/un-ignored/node_modules/test.txt, ignored: false, expected: true

By the way, please check the ignore package which should be more suitable for handling gitignore patterns than micromatch used in cspell-glob.

Jason3S commented 9 months ago

@gdlol,

Thank you for pointing out the exact issue.

I'll take another look at ignore. It previously wasn't suitable for a couple of reasons:

In any case, I think the current implementation of GlobMather needs to be improved.

Jason3S commented 9 months ago

@gdlol,

I was wrong in my comments above, node-ignore is not the package I had earlier evaluated. Thank you for the pointer.