file-entry-cache 8.0.0 → 9.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +6 -5
  2. package/cache.js +264 -237
  3. package/package.json +22 -19
package/README.md CHANGED
@@ -1,6 +1,5 @@
1
1
  # file-entry-cache
2
- > Super simple cache for file metadata, useful for process that work on a given series of files
3
- > and that only need to repeat the job on the changed ones since the previous run of the process — Edit
2
+ > Super simple cache for file metadata, useful for process that work on a given series of files and that only need to repeat the job on the changed ones since the previous run of the process
4
3
 
5
4
  [![NPM Version](https://img.shields.io/npm/v/file-entry-cache.svg?style=flat)](https://npmjs.org/package/file-entry-cache)
6
5
  [![tests](https://github.com/jaredwray/file-entry-cache/actions/workflows/tests.yaml/badge.svg?branch=master)](https://github.com/jaredwray/file-entry-cache/actions/workflows/tests.yaml)
@@ -18,14 +17,16 @@ npm i --save file-entry-cache
18
17
 
19
18
  The module exposes two functions `create` and `createFromFile`.
20
19
 
21
- ## `create(cacheName, [directory, useCheckSum])`
20
+ ## `create(cacheName, [directory, useCheckSum, currentWorkingDir])`
22
21
  - **cacheName**: the name of the cache to be created
23
22
  - **directory**: Optional the directory to load the cache from
24
23
  - **usecheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file.
24
+ - **currentWorkingDir**: Optional the current working directory to use when resolving relative paths
25
25
 
26
- ## `createFromFile(pathToCache, [useCheckSum])`
26
+ ## `createFromFile(pathToCache, [useCheckSum, currentWorkingDir])`
27
27
  - **pathToCache**: the path to the cache file (this combines the cache name and directory)
28
28
  - **useCheckSum**: Whether to use md5 checksum to verify if file changed. If false the default will be to use the mtime and size of the file.
29
+ - **currentWorkingDir**: Optional the current working directory to use when resolving relative paths
29
30
 
30
31
  ```js
31
32
  // loads the cache, if one does not exists for the given
@@ -110,6 +111,6 @@ In the worst case scenario all the files will be processed. In the best case sce
110
111
 
111
112
  ## License
112
113
 
113
- MIT
114
+ MIT (c) Jared Wray
114
115
 
115
116
 
package/cache.js CHANGED
@@ -1,64 +1,76 @@
1
- var path = require('path');
2
- var crypto = require('crypto');
1
+ /* eslint-disable unicorn/no-this-assignment, func-names, no-multi-assign */
2
+ const path = require('node:path');
3
+ const crypto = require('node:crypto');
3
4
 
4
5
  module.exports = {
5
- createFromFile: function (filePath, useChecksum) {
6
- var fname = path.basename(filePath);
7
- var dir = path.dirname(filePath);
8
- return this.create(fname, dir, useChecksum);
9
- },
10
-
11
- create: function (cacheId, _path, useChecksum) {
12
- var fs = require('fs');
13
- var flatCache = require('flat-cache');
14
- var cache = flatCache.load(cacheId, _path);
15
- var normalizedEntries = {};
16
-
17
- var removeNotFoundFiles = function removeNotFoundFiles() {
18
- const cachedEntries = cache.keys();
19
- // remove not found entries
20
- cachedEntries.forEach(function remover(fPath) {
21
- try {
22
- fs.statSync(fPath);
23
- } catch (err) {
24
- if (err.code === 'ENOENT') {
25
- cache.removeKey(fPath);
26
- }
27
- }
28
- });
29
- };
30
-
31
- removeNotFoundFiles();
32
-
33
- return {
34
- /**
35
- * the flat cache storage used to persist the metadata of the `files
6
+ createFromFile(filePath, useChecksum, currentWorkingDir) {
7
+ const fname = path.basename(filePath);
8
+ const dir = path.dirname(filePath);
9
+ return this.create(fname, dir, useChecksum, currentWorkingDir);
10
+ },
11
+
12
+ create(cacheId, _path, useChecksum, currentWorkingDir) {
13
+ const fs = require('node:fs');
14
+ const flatCache = require('flat-cache');
15
+ const cache = flatCache.load(cacheId, _path);
16
+ let normalizedEntries = {};
17
+
18
+ const removeNotFoundFiles = function removeNotFoundFiles() {
19
+ const cachedEntries = cache.keys();
20
+ // Remove not found entries
21
+ for (const fPath of cachedEntries) {
22
+ try {
23
+ let filePath = fPath;
24
+ if (currentWorkingDir) {
25
+ filePath = path.join(currentWorkingDir, fPath);
26
+ }
27
+
28
+ fs.statSync(filePath);
29
+ } catch (error) {
30
+ if (error.code === 'ENOENT') {
31
+ cache.removeKey(fPath);
32
+ }
33
+ }
34
+ }
35
+ };
36
+
37
+ removeNotFoundFiles();
38
+
39
+ return {
40
+ /**
41
+ * The flat cache storage used to persist the metadata of the `files
36
42
  * @type {Object}
37
43
  */
38
- cache: cache,
44
+ cache,
39
45
 
40
- /**
46
+ /**
47
+ * To enable relative paths as the key with current working directory
48
+ * @type {string}
49
+ */
50
+ currentWorkingDir: currentWorkingDir ?? undefined,
51
+
52
+ /**
41
53
  * Given a buffer, calculate md5 hash of its content.
42
54
  * @method getHash
43
55
  * @param {Buffer} buffer buffer to calculate hash on
44
56
  * @return {String} content hash digest
45
57
  */
46
- getHash: function (buffer) {
47
- return crypto.createHash('md5').update(buffer).digest('hex');
48
- },
58
+ getHash(buffer) {
59
+ return crypto.createHash('md5').update(buffer).digest('hex');
60
+ },
49
61
 
50
- /**
62
+ /**
51
63
  * Return whether or not a file has changed since last time reconcile was called.
52
64
  * @method hasFileChanged
53
65
  * @param {String} file the filepath to check
54
66
  * @return {Boolean} wheter or not the file has changed
55
67
  */
56
- hasFileChanged: function (file) {
57
- return this.getFileDescriptor(file).changed;
58
- },
68
+ hasFileChanged(file) {
69
+ return this.getFileDescriptor(file).changed;
70
+ },
59
71
 
60
- /**
61
- * given an array of file paths it return and object with three arrays:
72
+ /**
73
+ * Given an array of file paths it return and object with three arrays:
62
74
  * - changedFiles: Files that changed since previous run
63
75
  * - notChangedFiles: Files that haven't change
64
76
  * - notFoundFiles: Files that were not found, probably deleted
@@ -66,103 +78,114 @@ module.exports = {
66
78
  * @param {Array} files the files to analyze and compare to the previous seen files
67
79
  * @return {[type]} [description]
68
80
  */
69
- analyzeFiles: function (files) {
70
- var me = this;
71
- files = files || [];
72
-
73
- var res = {
74
- changedFiles: [],
75
- notFoundFiles: [],
76
- notChangedFiles: [],
77
- };
78
-
79
- me.normalizeEntries(files).forEach(function (entry) {
80
- if (entry.changed) {
81
- res.changedFiles.push(entry.key);
82
- return;
83
- }
84
- if (entry.notFound) {
85
- res.notFoundFiles.push(entry.key);
86
- return;
87
- }
88
- res.notChangedFiles.push(entry.key);
89
- });
90
- return res;
91
- },
92
-
93
- getFileDescriptor: function (file) {
94
- var fstat;
95
-
96
- try {
97
- fstat = fs.statSync(file);
98
- } catch (ex) {
99
- this.removeEntry(file);
100
- return { key: file, notFound: true, err: ex };
101
- }
102
-
103
- if (useChecksum) {
104
- return this._getFileDescriptorUsingChecksum(file);
105
- }
106
-
107
- return this._getFileDescriptorUsingMtimeAndSize(file, fstat);
108
- },
109
-
110
- _getFileDescriptorUsingMtimeAndSize: function (file, fstat) {
111
- var meta = cache.getKey(file);
112
- var cacheExists = !!meta;
113
-
114
- var cSize = fstat.size;
115
- var cTime = fstat.mtime.getTime();
116
-
117
- var isDifferentDate;
118
- var isDifferentSize;
119
-
120
- if (!meta) {
121
- meta = { size: cSize, mtime: cTime };
122
- } else {
123
- isDifferentDate = cTime !== meta.mtime;
124
- isDifferentSize = cSize !== meta.size;
125
- }
126
-
127
- var nEntry = (normalizedEntries[file] = {
128
- key: file,
129
- changed: !cacheExists || isDifferentDate || isDifferentSize,
130
- meta: meta,
131
- });
132
-
133
- return nEntry;
134
- },
135
-
136
- _getFileDescriptorUsingChecksum: function (file) {
137
- var meta = cache.getKey(file);
138
- var cacheExists = !!meta;
139
-
140
- var contentBuffer;
141
- try {
142
- contentBuffer = fs.readFileSync(file);
143
- } catch (ex) {
144
- contentBuffer = '';
145
- }
146
-
147
- var isDifferent = true;
148
- var hash = this.getHash(contentBuffer);
149
-
150
- if (!meta) {
151
- meta = { hash: hash };
152
- } else {
153
- isDifferent = hash !== meta.hash;
154
- }
155
-
156
- var nEntry = (normalizedEntries[file] = {
157
- key: file,
158
- changed: !cacheExists || isDifferent,
159
- meta: meta,
160
- });
161
-
162
- return nEntry;
163
- },
164
-
165
- /**
81
+ analyzeFiles(files) {
82
+ const me = this;
83
+ files ||= [];
84
+
85
+ const res = {
86
+ changedFiles: [],
87
+ notFoundFiles: [],
88
+ notChangedFiles: [],
89
+ };
90
+
91
+ for (const entry of me.normalizeEntries(files)) {
92
+ if (entry.changed) {
93
+ res.changedFiles.push(entry.key);
94
+ continue;
95
+ }
96
+
97
+ if (entry.notFound) {
98
+ res.notFoundFiles.push(entry.key);
99
+ continue;
100
+ }
101
+
102
+ res.notChangedFiles.push(entry.key);
103
+ }
104
+
105
+ return res;
106
+ },
107
+
108
+ getFileDescriptor(file) {
109
+ let fstat;
110
+
111
+ try {
112
+ fstat = fs.statSync(file);
113
+ } catch (error) {
114
+ this.removeEntry(file);
115
+ return {key: file, notFound: true, err: error};
116
+ }
117
+
118
+ if (useChecksum) {
119
+ return this._getFileDescriptorUsingChecksum(file);
120
+ }
121
+
122
+ return this._getFileDescriptorUsingMtimeAndSize(file, fstat);
123
+ },
124
+
125
+ _getFileKey(file) {
126
+ if (this.currentWorkingDir) {
127
+ return file.split(this.currentWorkingDir).pop();
128
+ }
129
+
130
+ return file;
131
+ },
132
+
133
+ _getFileDescriptorUsingMtimeAndSize(file, fstat) {
134
+ let meta = cache.getKey(this._getFileKey(file));
135
+ const cacheExists = Boolean(meta);
136
+
137
+ const cSize = fstat.size;
138
+ const cTime = fstat.mtime.getTime();
139
+
140
+ let isDifferentDate;
141
+ let isDifferentSize;
142
+
143
+ if (meta) {
144
+ isDifferentDate = cTime !== meta.mtime;
145
+ isDifferentSize = cSize !== meta.size;
146
+ } else {
147
+ meta = {size: cSize, mtime: cTime};
148
+ }
149
+
150
+ const nEntry = (normalizedEntries[this._getFileKey(file)] = {
151
+ key: this._getFileKey(file),
152
+ changed: !cacheExists || isDifferentDate || isDifferentSize,
153
+ meta,
154
+ });
155
+
156
+ return nEntry;
157
+ },
158
+
159
+ _getFileDescriptorUsingChecksum(file) {
160
+ let meta = cache.getKey(this._getFileKey(file));
161
+ const cacheExists = Boolean(meta);
162
+
163
+ let contentBuffer;
164
+ try {
165
+ contentBuffer = fs.readFileSync(file);
166
+ } catch {
167
+ contentBuffer = '';
168
+ }
169
+
170
+ let isDifferent = true;
171
+ const hash = this.getHash(contentBuffer);
172
+
173
+ if (meta) {
174
+ isDifferent = hash !== meta.hash;
175
+ } else {
176
+ meta = {hash};
177
+ }
178
+
179
+ const nEntry = (normalizedEntries[this._getFileKey(file)] = {
180
+ key: this._getFileKey(file),
181
+ changed: !cacheExists || isDifferent,
182
+ meta,
183
+ });
184
+
185
+ return nEntry;
186
+ },
187
+
188
+ /**
166
189
  * Return the list o the files that changed compared
167
190
  * against the ones stored in the cache
168
191
  *
@@ -170,122 +193,126 @@ module.exports = {
170
193
  * @param files {Array} the array of files to compare against the ones in the cache
171
194
  * @returns {Array}
172
195
  */
173
- getUpdatedFiles: function (files) {
174
- var me = this;
175
- files = files || [];
176
-
177
- return me
178
- .normalizeEntries(files)
179
- .filter(function (entry) {
180
- return entry.changed;
181
- })
182
- .map(function (entry) {
183
- return entry.key;
184
- });
185
- },
186
-
187
- /**
188
- * return the list of files
196
+ getUpdatedFiles(files) {
197
+ const me = this;
198
+ files ||= [];
199
+
200
+ return me
201
+ .normalizeEntries(files)
202
+ .filter(entry => entry.changed)
203
+ .map(entry => entry.key);
204
+ },
205
+
206
+ /**
207
+ * Return the list of files
189
208
  * @method normalizeEntries
190
209
  * @param files
191
210
  * @returns {*}
192
211
  */
193
- normalizeEntries: function (files) {
194
- files = files || [];
212
+ normalizeEntries(files) {
213
+ files ||= [];
195
214
 
196
- var me = this;
197
- var nEntries = files.map(function (file) {
198
- return me.getFileDescriptor(file);
199
- });
215
+ const me = this;
216
+ const nEntries = files.map(file => me.getFileDescriptor(file));
200
217
 
201
- //normalizeEntries = nEntries;
202
- return nEntries;
203
- },
218
+ // NormalizeEntries = nEntries;
219
+ return nEntries;
220
+ },
204
221
 
205
- /**
222
+ /**
206
223
  * Remove an entry from the file-entry-cache. Useful to force the file to still be considered
207
224
  * modified the next time the process is run
208
225
  *
209
226
  * @method removeEntry
210
227
  * @param entryName
211
228
  */
212
- removeEntry: function (entryName) {
213
- delete normalizedEntries[entryName];
214
- cache.removeKey(entryName);
215
- },
229
+ removeEntry(entryName) {
230
+ delete normalizedEntries[this._getFileKey(entryName)];
231
+ cache.removeKey(this._getFileKey(entryName));
232
+ },
216
233
 
217
- /**
234
+ /**
218
235
  * Delete the cache file from the disk
219
236
  * @method deleteCacheFile
220
237
  */
221
- deleteCacheFile: function () {
222
- cache.removeCacheFile();
223
- },
238
+ deleteCacheFile() {
239
+ cache.removeCacheFile();
240
+ },
224
241
 
225
- /**
226
- * remove the cache from the file and clear the memory cache
242
+ /**
243
+ * Remove the cache from the file and clear the memory cache
227
244
  */
228
- destroy: function () {
229
- normalizedEntries = {};
230
- cache.destroy();
231
- },
232
-
233
- _getMetaForFileUsingCheckSum: function (cacheEntry) {
234
- var contentBuffer = fs.readFileSync(cacheEntry.key);
235
- var hash = this.getHash(contentBuffer);
236
- var meta = Object.assign(cacheEntry.meta, { hash: hash });
237
- delete meta.size;
238
- delete meta.mtime;
239
- return meta;
240
- },
241
-
242
- _getMetaForFileUsingMtimeAndSize: function (cacheEntry) {
243
- var stat = fs.statSync(cacheEntry.key);
244
- var meta = Object.assign(cacheEntry.meta, {
245
- size: stat.size,
246
- mtime: stat.mtime.getTime(),
247
- });
248
- delete meta.hash;
249
- return meta;
250
- },
251
-
252
- /**
245
+ destroy() {
246
+ normalizedEntries = {};
247
+ cache.destroy();
248
+ },
249
+
250
+ _getMetaForFileUsingCheckSum(cacheEntry) {
251
+ let filePath = cacheEntry.key;
252
+ if (this.currentWorkingDir) {
253
+ filePath = path.join(this.currentWorkingDir, filePath);
254
+ }
255
+
256
+ const contentBuffer = fs.readFileSync(filePath);
257
+ const hash = this.getHash(contentBuffer);
258
+ const meta = Object.assign(cacheEntry.meta, {hash});
259
+ delete meta.size;
260
+ delete meta.mtime;
261
+ return meta;
262
+ },
263
+
264
+ _getMetaForFileUsingMtimeAndSize(cacheEntry) {
265
+ let filePath = cacheEntry.key;
266
+ if (currentWorkingDir) {
267
+ filePath = path.join(currentWorkingDir, filePath);
268
+ }
269
+
270
+ const stat = fs.statSync(filePath);
271
+ const meta = Object.assign(cacheEntry.meta, {
272
+ size: stat.size,
273
+ mtime: stat.mtime.getTime(),
274
+ });
275
+ delete meta.hash;
276
+ return meta;
277
+ },
278
+
279
+ /**
253
280
  * Sync the files and persist them to the cache
254
281
  * @method reconcile
255
282
  */
256
- reconcile: function (noPrune) {
257
- removeNotFoundFiles();
258
-
259
- noPrune = typeof noPrune === 'undefined' ? true : noPrune;
260
-
261
- var entries = normalizedEntries;
262
- var keys = Object.keys(entries);
263
-
264
- if (keys.length === 0) {
265
- return;
266
- }
267
-
268
- var me = this;
269
-
270
- keys.forEach(function (entryName) {
271
- var cacheEntry = entries[entryName];
272
-
273
- try {
274
- var meta = useChecksum
275
- ? me._getMetaForFileUsingCheckSum(cacheEntry)
276
- : me._getMetaForFileUsingMtimeAndSize(cacheEntry);
277
- cache.setKey(entryName, meta);
278
- } catch (err) {
279
- // if the file does not exists we don't save it
280
- // other errors are just thrown
281
- if (err.code !== 'ENOENT') {
282
- throw err;
283
- }
284
- }
285
- });
286
-
287
- cache.save(noPrune);
288
- },
289
- };
290
- },
283
+ reconcile(noPrune) {
284
+ removeNotFoundFiles();
285
+
286
+ noPrune = noPrune === undefined ? true : noPrune;
287
+
288
+ const entries = normalizedEntries;
289
+ const keys = Object.keys(entries);
290
+
291
+ if (keys.length === 0) {
292
+ return;
293
+ }
294
+
295
+ const me = this;
296
+
297
+ for (const entryName of keys) {
298
+ const cacheEntry = entries[entryName];
299
+
300
+ try {
301
+ const meta = useChecksum
302
+ ? me._getMetaForFileUsingCheckSum(cacheEntry)
303
+ : me._getMetaForFileUsingMtimeAndSize(cacheEntry);
304
+ cache.setKey(this._getFileKey(entryName), meta);
305
+ } catch (error) {
306
+ // If the file does not exists we don't save it
307
+ // other errors are just thrown
308
+ if (error.code !== 'ENOENT') {
309
+ throw error;
310
+ }
311
+ }
312
+ }
313
+
314
+ cache.save(noPrune);
315
+ },
316
+ };
317
+ },
291
318
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "file-entry-cache",
3
- "version": "8.0.0",
3
+ "version": "9.1.0",
4
4
  "description": "Super simple cache for file metadata, useful for process that work o a given series of files and that only need to repeat the job on the changed ones since the previous run of the process",
5
5
  "repository": "jaredwray/file-entry-cache",
6
6
  "license": "MIT",
@@ -13,21 +13,20 @@
13
13
  "cache.js"
14
14
  ],
15
15
  "engines": {
16
- "node": ">=16.0.0"
16
+ "node": ">=18"
17
17
  },
18
18
  "scripts": {
19
- "eslint": "eslint --cache --cache-location=node_modules/.cache/ 'cache.js' 'test/**/*.js' 'perf.js'",
20
- "autofix": "npm run eslint -- --fix",
21
- "clean": "rimraf ./node_modules ./package-lock.json ./yarn.lock",
22
- "test": "npm run eslint --silent && c8 mocha -R spec test/specs",
23
- "test:ci": "npm run eslint --silent && c8 --reporter=lcov mocha -R spec test/specs",
19
+ "clean": "rimraf ./coverage /node_modules ./package-lock.json ./yarn.lock ./pnpm-lock.yaml",
20
+ "test": "xo --fix && c8 mocha -R spec test/specs/cache.js test/relative.js",
21
+ "test:relative": "rimraf ./rfixtures ./tfixtures && mocha test/relative.js",
22
+ "test:ci": "xo && c8 --reporter=lcov mocha -R spec test/specs/cache.js test/relative.js",
24
23
  "perf": "node perf.js"
25
24
  },
26
25
  "prepush": [
27
- "npm run eslint --silent"
26
+ "npm run test"
28
27
  ],
29
28
  "precommit": [
30
- "npm run eslint --silent"
29
+ "npm run test"
31
30
  ],
32
31
  "keywords": [
33
32
  "file cache",
@@ -38,19 +37,23 @@
38
37
  "cache"
39
38
  ],
40
39
  "devDependencies": {
41
- "c8": "^8.0.1",
40
+ "c8": "^10.1.2",
42
41
  "chai": "^4.3.10",
43
- "eslint": "^8.56.0",
44
- "eslint-config-prettier": "^9.1.0",
45
- "eslint-plugin-mocha": "^10.2.0",
46
- "eslint-plugin-prettier": "^5.0.1",
47
42
  "glob-expand": "^0.2.1",
48
- "mocha": "^10.2.0",
49
- "prettier": "^3.1.1",
50
- "rimraf": "^5.0.5",
51
- "write": "^2.0.0"
43
+ "mocha": "^10.5.1",
44
+ "rimraf": "^5.0.7",
45
+ "webpack": "^5.92.1",
46
+ "write": "^2.0.0",
47
+ "xo": "^0.58.0"
52
48
  },
53
49
  "dependencies": {
54
- "flat-cache": "^4.0.0"
50
+ "flat-cache": "^5.0.0"
51
+ },
52
+ "xo": {
53
+ "rules": {
54
+ "unicorn/prefer-module": "off",
55
+ "n/prefer-global/process": "off",
56
+ "unicorn/prevent-abbreviations": "off"
57
+ }
55
58
  }
56
59
  }