From e24ca0eb3d57067c1a81c6cb018b769c9b57f070 Mon Sep 17 00:00:00 2001
From: Adam Setch <adam.setch@outlook.com>
Date: Mon, 24 Jul 2023 16:07:52 -0400
Subject: [PATCH] feat: add minimatch wrapper to support caching (#23515)

---
 lib/util/minimatch.spec.ts | 18 ++++++++++++++++++
 lib/util/minimatch.ts      | 24 ++++++++++++++++++++++++
 2 files changed, 42 insertions(+)
 create mode 100644 lib/util/minimatch.spec.ts
 create mode 100644 lib/util/minimatch.ts

diff --git a/lib/util/minimatch.spec.ts b/lib/util/minimatch.spec.ts
new file mode 100644
index 0000000000..5414aacdc7
--- /dev/null
+++ b/lib/util/minimatch.spec.ts
@@ -0,0 +1,18 @@
+import { minimatch } from './minimatch';
+
+describe('util/minimatch', () => {
+  it('caches minimatch', () => {
+    expect(minimatch('foo')).toBe(minimatch('foo'));
+    expect(minimatch('foo', { dot: true })).toBe(
+      minimatch('foo', { dot: true })
+    );
+  });
+
+  it('does not cache minimatch', () => {
+    expect(minimatch('foo', undefined, false)).not.toBe(
+      minimatch('foo', undefined, false)
+    );
+    expect(minimatch('foo')).not.toBe(minimatch('foo', undefined, false));
+    expect(minimatch('foo', { dot: true })).not.toBe(minimatch('foo'));
+  });
+});
diff --git a/lib/util/minimatch.ts b/lib/util/minimatch.ts
new file mode 100644
index 0000000000..0d915d8be9
--- /dev/null
+++ b/lib/util/minimatch.ts
@@ -0,0 +1,24 @@
+import { Minimatch, MinimatchOptions } from 'minimatch';
+
+const cache = new Map<string, Minimatch>();
+
+export function minimatch(
+  pattern: string,
+  options?: MinimatchOptions,
+  useCache = true
+): Minimatch {
+  const key = options ? `${pattern}:${JSON.stringify(options)}` : pattern;
+
+  if (useCache) {
+    const cachedResult = cache.get(key);
+    if (cachedResult) {
+      return cachedResult;
+    }
+  }
+
+  const instance = new Minimatch(pattern, options);
+  if (useCache) {
+    cache.set(key, instance);
+  }
+  return instance;
+}
-- 
GitLab