Skip to content

Commit

Permalink
Allow simple regex to be passed in array
Browse files Browse the repository at this point in the history
  • Loading branch information
Mark Molinaro committed Jun 22, 2021
1 parent c651129 commit a05d00d
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 5 deletions.
17 changes: 12 additions & 5 deletions lib/watchpack.js
Expand Up @@ -24,18 +24,25 @@ function addWatchersToSet(watchers, set) {
}
}

const stringToRegexp = ignored => {
const source = globToRegExp(ignored, { globstar: true, extended: true })
.source;
const stringOrRegexpToRegexp = ignored => {
if (ignored instanceof RegExp) {
if (ignored.flags !== "") {
throw new Error(
`Invalid option for 'ignored', regex in list does not support flags ${ignored}`
);
}
return ignored.source;
}
const { source } = globToRegExp(ignored, { globstar: true, extended: true });
const matchingStart = source.slice(0, source.length - 1) + "(?:$|\\/)";
return matchingStart;
};

const ignoredToRegexp = ignored => {
if (Array.isArray(ignored)) {
return new RegExp(ignored.map(i => stringToRegexp(i)).join("|"));
return new RegExp(ignored.map(i => stringOrRegexpToRegexp(i)).join("|"));
} else if (typeof ignored === "string") {
return new RegExp(stringToRegexp(ignored));
return new RegExp(stringOrRegexpToRegexp(ignored));
} else if (ignored instanceof RegExp) {
return ignored;
} else if (ignored) {
Expand Down
36 changes: 36 additions & 0 deletions test/Watchpack.js
Expand Up @@ -14,6 +14,16 @@ describe("Watchpack", function() {
beforeEach(testHelper.before);
afterEach(testHelper.after);

it("should throw on invalid ignore options", function() {
try {
var w = new Watchpack({
ignored: [/\/a$/i]
});
} catch(e) {
e.message.should.startWith("Invalid");
}
});

it("should watch a single file", function(done) {
var w = new Watchpack({
aggregateTimeout: 1000
Expand Down Expand Up @@ -118,6 +128,32 @@ describe("Watchpack", function() {
});
});

it("should not watch a single ignored file (array with regexp and glob)", function(done) {
var w = new Watchpack({
aggregateTimeout: 300,
ignored: [/\/a$/, "**/b"]
});
var changeEvents = 0;
var aggregatedEvents = 0;
w.on("change", () => {
changeEvents++;
});
w.on("aggregated", () => {
aggregatedEvents++;
});
w.watch([path.join(fixtures, "a")], []);
testHelper.tick(() => {
testHelper.file("a");
testHelper.tick(1000, () => {
changeEvents.should.be.eql(0);
aggregatedEvents.should.be.eql(0);
testHelper.getNumberOfWatchers().should.be.eql(0);
w.close();
done();
});
});
});

it("should watch multiple files", function(done) {
var w = new Watchpack({
aggregateTimeout: 1000
Expand Down

0 comments on commit a05d00d

Please sign in to comment.