cache-cmd 0.2.0-dev.4a662091d40f9510cff02e70023e5919708daa8f → 0.2.0-dev.7098ba3784d94f8515529435c60343ac3e724316

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.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # cache-cmd
2
2
 
3
- Cache a command based on
3
+ Run and cache a command based on
4
4
 
5
5
  - time since last run
6
6
  - file change
@@ -8,38 +8,40 @@ Cache a command based on
8
8
  ## Install
9
9
 
10
10
  ```sh
11
+ # Using npm
12
+ npm add --save-dev cache-cmd
13
+ # Using pnpm
14
+ pnpm add --save-dev cache-cmd
15
+ # Using yarn
11
16
  yarn add --dev cache-cmd
12
17
  ```
13
18
 
14
- or
15
-
16
- ```sh
17
- npm install --save-dev cache-cmd
18
- ```
19
-
20
19
  ## Usage
21
20
 
22
21
  ```sh
23
22
  # Shows help
24
- yarn cache-cmd --help
23
+ npm exec -- cache-cmd --help
25
24
 
26
25
  # Runs command if it was not run in the last 20s
27
- yarn cache-cmd "echo ran this command" --time 20s
26
+ npm exec -- cache-cmd "echo ran this command" --time 20s
28
27
 
29
- # Runs comand if yarn.lock in current directory changed since last run
30
- yarn cache-cmd "yarn install" --file yarn.lock
28
+ # Runs command if package-lock.json in current directory changed since last run
29
+ npm exec -- cache-cmd "npm install" --file package-lock.json
31
30
 
32
31
  # Additionally uses custom cache directory instead of default in node_modules
33
- yarn cache-cmd "yarn install" --file yarn.lock --cache-dir .config/cache
32
+ npm exec -- cache-cmd "npm install" --file package-lock.json --cache-dir .config/cache
34
33
 
35
34
  # Runs command if it was not run in a month or any of the files changed
36
- yarn cache-cmd "yarn install" --time 1mo --file yarn.lock --file package.json
35
+ npm exec -- cache-cmd "npm install" --time 1mo --file package-lock.json --file package.json
37
36
 
38
37
  # Shows path to cache directory
39
- yarn cache-cmd cache dir
38
+ npm exec -- cache-cmd cache dir
40
39
 
41
40
  # Clear cache
42
- yarn cache-cmd cache clear
41
+ npm exec -- cache-cmd cache clear
42
+
43
+ # You can also run it with npx to skip the install step
44
+ npx cache-cmd "echo ran this command" --time 20s
43
45
  ```
44
46
 
45
47
  You can use it to execute commands conditionally in `package.json` scripts.
@@ -47,7 +49,7 @@ You can use it to execute commands conditionally in `package.json` scripts.
47
49
  ```json
48
50
  {
49
51
  "scripts": {
50
- "dev": "cache-cmd \"yarn\" --file yarn.lock && start-dev-server"
52
+ "start-dev": "cache-cmd \"npm install\" --file package-lock.json && start-dev-server"
51
53
  }
52
54
  }
53
55
  ```
package/dist/cli.cjs CHANGED
@@ -144,6 +144,7 @@ async function runCommand({
144
144
  shouldCacheOnError
145
145
  }) {
146
146
  if (!cacheByTime && cacheByFiles.length === 0) {
147
+ console.log(`Executing command "${command}" due to no caching options provided`);
147
148
  await execSh__default["default"].promise(command);
148
149
  return;
149
150
  }
@@ -176,28 +177,31 @@ async function runCommand({
176
177
  })();
177
178
 
178
179
  if (areFileHashesEqual && isWithinCacheTime) {
180
+ console.log([`Skipping command "${command}" due to`, [fileHashes && 'unchanged files', duration && 'being within cache time'].filter(Boolean).join(' and ')].join(' '));
179
181
  return;
180
182
  }
181
183
 
184
+ console.log([`Executing command "${command}" due to`, [fileHashes && 'changed files', duration && 'cache time passing'].filter(Boolean).join(' and ')].join(' '));
182
185
  let execPromise = execSh__default["default"].promise(command);
183
186
 
187
+ function setCache() {
188
+ cache.setKey(cacheKey, {
189
+ lastRun: currentDate,
190
+ fileHashes
191
+ });
192
+ cache.save(true);
193
+ console.log(`Cache saved for command "${command}"`);
194
+ }
195
+
184
196
  if (shouldCacheOnError) {
185
197
  execPromise = execPromise.catch(error => {
186
- cache.setKey(cacheKey, {
187
- lastRun: currentDate,
188
- fileHashes
189
- });
190
- cache.save(true);
198
+ setCache();
191
199
  throw error;
192
200
  });
193
201
  }
194
202
 
195
203
  await execPromise;
196
- cache.setKey(cacheKey, {
197
- lastRun: currentDate,
198
- fileHashes
199
- });
200
- cache.save(true);
204
+ setCache();
201
205
  }
202
206
 
203
207
  hardRejection__default["default"]();
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.cjs","sources":["../src/utils/get-cache-dir.ts","../src/cache-clear.ts","../src/cache-dir.ts","../src/utils/get-cache-key.ts","../src/utils/get-duration.ts","../src/utils/get-file-hashes.ts","../src/utils/get-file-paths.ts","../src/run.ts","../src/cli.ts"],"sourcesContent":["import path from 'path'\n\nimport findCacheDir from 'find-cache-dir'\nimport makeDir from 'make-dir'\n\nimport { name } from '../../package.json'\n\nexport function getCacheDirectoryPath(relativeCacheDirectoryPath: string | undefined) {\n if (relativeCacheDirectoryPath) {\n return path.resolve(process.cwd(), relativeCacheDirectoryPath)\n }\n\n const resolvedCacheDirectory = findCacheDir({ name })\n\n if (!resolvedCacheDirectory) {\n throw Error('Could not find cache directory. Please provide a cache directory manually.')\n }\n\n return resolvedCacheDirectory\n}\n\nexport function createCache(relativeCacheDirectoryPath: string | undefined) {\n if (relativeCacheDirectoryPath) {\n const absoluteCacheDirectoryPath = makeDir.sync(relativeCacheDirectoryPath)\n\n return absoluteCacheDirectoryPath\n }\n\n const resolvedCachePath = findCacheDir({ name, create: true })\n\n if (!resolvedCachePath) {\n throw Error('Could not find cache directory. Please provide a cache directory manually.')\n }\n\n return resolvedCachePath\n}\n","import del from 'del'\n\nimport { getCacheDirectoryPath } from './utils/get-cache-dir'\n\nexport function clearCacheDirectory(relativeCacheDirectory: string | undefined) {\n const deletedPaths = del.sync(getCacheDirectoryPath(relativeCacheDirectory))\n\n if (deletedPaths.length === 0) {\n console.log('No cache to clear')\n } else if (deletedPaths.length === 1) {\n console.log(`Deleted: ${deletedPaths[0]}`)\n } else {\n console.log('Deleted:\\n', deletedPaths.join('\\n'))\n }\n}\n","import { getCacheDirectoryPath } from './utils/get-cache-dir'\n\nexport function showCacheDirectory(relativeCacheDirectory: string | undefined) {\n console.log(getCacheDirectoryPath(relativeCacheDirectory))\n}\n","interface GetCacheKeyProps {\n duration: Duration | undefined\n filePaths: string[]\n command: string\n}\n\ninterface Duration {\n years: number | undefined\n months: number | undefined\n weeks: number | undefined\n days: number | undefined\n hours: number | undefined\n minutes: number | undefined\n seconds: number | undefined\n}\n\nexport function getCacheKey({ duration, filePaths, command }: GetCacheKeyProps) {\n return [\n 'cwd:' + process.cwd(),\n 'cmd:' + command,\n duration && 'time:' + JSON.stringify(duration),\n filePaths.length !== 0 && 'files:' + filePaths.join(','),\n ]\n .filter(Boolean)\n .join(' ---')\n}\n","export function getDuration(durationString: string) {\n if (!/^(\\d+[a-z]+)+$/gi.test(durationString)) {\n throw Error(`Invalid duration: ${durationString}`)\n }\n\n const duration = {\n years: undefined as undefined | number,\n months: undefined as undefined | number,\n weeks: undefined as undefined | number,\n days: undefined as undefined | number,\n hours: undefined as undefined | number,\n minutes: undefined as undefined | number,\n seconds: undefined as undefined | number,\n }\n\n durationString.match(/\\d+[a-z]+/gi)!.forEach((durationPart) => {\n const [, stringQuantity, unitShort] = /(\\d+)([a-z]+)/gi.exec(durationPart)!\n const quantity = Number(stringQuantity)\n\n const unitLong = (\n {\n y: 'years',\n mo: 'months',\n w: 'weeks',\n d: 'days',\n h: 'hours',\n m: 'minutes',\n s: 'seconds',\n } as const\n )[unitShort!]\n\n if (Number.isNaN(quantity) || !unitLong) {\n throw Error(`Invalid duration part: ${durationPart}`)\n }\n\n if (duration[unitLong] !== undefined) {\n throw Error(`Duration with unit ${unitLong} was supplied multiple times`)\n }\n\n duration[unitLong] = quantity\n })\n\n return duration\n}\n","import hasha from 'hasha'\n\nexport async function getFileHashes(filePaths: string[]) {\n return Object.fromEntries(\n await Promise.all(\n filePaths.map((filePath) =>\n hasha\n .fromFile(filePath, { algorithm: 'md5' })\n .then((hash) => [filePath, hash] as const)\n )\n )\n )\n}\n","import path from 'path'\n\nexport function getFilePaths(relativeFilePaths: string[]) {\n const cwd = process.cwd()\n\n return relativeFilePaths.map((file) => path.resolve(cwd, file)).sort()\n}\n","import { add, isAfter } from 'date-fns'\nimport execSh from 'exec-sh'\nimport flatCache from 'flat-cache'\nimport { isEqual } from 'lodash'\n\nimport { createCache } from './utils/get-cache-dir'\nimport { getCacheKey } from './utils/get-cache-key'\nimport { getDuration } from './utils/get-duration'\nimport { getFileHashes } from './utils/get-file-hashes'\nimport { getFilePaths } from './utils/get-file-paths'\n\ninterface RunCommandProps {\n relativeCacheDirectory: string | undefined\n command: string\n cacheByTime: string | undefined\n cacheByFiles: string[]\n shouldCacheOnError: boolean | undefined\n}\n\nexport async function runCommand({\n relativeCacheDirectory,\n command,\n cacheByTime: cacheByTime,\n cacheByFiles: cacheByFiles,\n shouldCacheOnError,\n}: RunCommandProps) {\n if (!cacheByTime && cacheByFiles.length === 0) {\n await execSh.promise(command)\n return\n }\n\n const cache = flatCache.load('commands-cache.json', createCache(relativeCacheDirectory))\n const filePaths = getFilePaths(cacheByFiles)\n const duration = cacheByTime ? getDuration(cacheByTime) : undefined\n\n const cacheKey = getCacheKey({ duration, filePaths, command })\n\n const cacheData: unknown = cache.getKey(cacheKey)\n\n const fileHashes = filePaths.length === 0 ? undefined : await getFileHashes(filePaths)\n const currentDate = new Date()\n\n const areFileHashesEqual = isEqual((cacheData as any)?.fileHashes, fileHashes)\n const isWithinCacheTime = (() => {\n if (!duration) {\n return true\n }\n\n const lastRun = (cacheData as any)?.lastRun\n\n if (!lastRun) {\n return false\n }\n\n return isAfter(add(new Date(lastRun), duration), currentDate)\n })()\n\n if (areFileHashesEqual && isWithinCacheTime) {\n return\n }\n\n let execPromise = execSh.promise(command)\n\n if (shouldCacheOnError) {\n execPromise = execPromise.catch((error: unknown) => {\n cache.setKey(cacheKey, {\n lastRun: currentDate,\n fileHashes,\n })\n cache.save(true)\n\n throw error\n })\n }\n\n await execPromise\n\n cache.setKey(cacheKey, {\n lastRun: currentDate,\n fileHashes,\n })\n cache.save(true)\n}\n","#!/usr/bin/env node\n\nimport hardRejection from 'hard-rejection'\nimport sade from 'sade'\n\nimport { version } from '../package.json'\n\nimport { clearCacheDirectory } from './cache-clear'\nimport { showCacheDirectory } from './cache-dir'\nimport { runCommand } from './run'\n\nhardRejection()\n\nconst program = sade('cache-cmd')\n\nprogram\n .version(version)\n .describe('Run and cache a command based on various factors')\n .option(\n '-c, --cache-dir',\n 'Cache directory to use (default: .cache/cache-cmd in nearest node_modules)'\n )\n\nprogram\n .command(\n 'run <command>',\n 'Run cached command (if no <command> provided, this is the default)',\n { default: true }\n )\n .option('-f, --file', 'Run command only when file content changes')\n .option('-t, --time', 'Run command only after specified time (unit with s,m,h,d,w,mo,y)')\n .option('--cache-on-error', 'Cache command run even when command exits with non-zero exit code')\n .example('run \"echo ran this command\" --time 20s')\n .example('run \"./may-fail\" --time 20s --cache-on-error')\n .example('run \"yarn install\" --file yarn.lock')\n .example('run \"yarn install\" --file yarn.lock --cache-dir .config/cache')\n .example('run \"yarn install\" --time 1mo --file yarn.lock --file package.json')\n .action((command: unknown, options: Record<string, unknown>) => {\n const cacheDirectory = options['cache-dir']\n const time = options.time\n const file = options.file\n const shouldCacheOnError = options['cache-on-error']\n const files: unknown[] = file === undefined ? [] : Array.isArray(file) ? file : [file]\n\n if (typeof command !== 'string') {\n throw Error('Invalid <command> supplied')\n }\n\n if (cacheDirectory !== undefined && typeof cacheDirectory !== 'string') {\n throw Error('Invalid --cache-dir supplied')\n }\n\n if (time !== undefined && typeof time !== 'string') {\n throw Error('Invalid --time supplied')\n }\n\n if (files.some((file) => typeof file !== 'string')) {\n throw Error('Invalid --file supplied')\n }\n\n if (shouldCacheOnError !== undefined && typeof shouldCacheOnError !== 'boolean') {\n throw Error('Invalid --cache-on-error supplied')\n }\n\n runCommand({\n relativeCacheDirectory: cacheDirectory,\n command,\n cacheByTime: time,\n cacheByFiles: files as string[],\n shouldCacheOnError,\n })\n })\n\nprogram\n .command('cache dir', 'Show cache directory path used by cache-cmd')\n .action((options: Record<string, unknown>) => {\n const cacheDirectory = options['cache-dir']\n\n if (cacheDirectory !== undefined && typeof cacheDirectory !== 'string') {\n throw Error('Invalid --cache-dir supplied')\n }\n\n showCacheDirectory(cacheDirectory)\n })\n\nprogram\n .command('cache clear', 'Clear cache used by cache-cmd')\n .action((options: Record<string, unknown>) => {\n const cacheDirectory = options['cache-dir']\n\n if (cacheDirectory !== undefined && typeof cacheDirectory !== 'string') {\n throw Error('Invalid --cache-dir supplied')\n }\n\n clearCacheDirectory(cacheDirectory)\n })\n\nprogram.parse(process.argv)\n"],"names":["getCacheDirectoryPath","relativeCacheDirectoryPath","path","resolve","process","cwd","resolvedCacheDirectory","findCacheDir","name","Error","createCache","absoluteCacheDirectoryPath","makeDir","sync","resolvedCachePath","create","clearCacheDirectory","relativeCacheDirectory","deletedPaths","del","length","console","log","join","showCacheDirectory","getCacheKey","duration","filePaths","command","JSON","stringify","filter","Boolean","getDuration","durationString","test","years","undefined","months","weeks","days","hours","minutes","seconds","match","forEach","durationPart","stringQuantity","unitShort","exec","quantity","Number","unitLong","y","mo","w","d","h","m","s","isNaN","getFileHashes","Object","fromEntries","Promise","all","map","filePath","hasha","fromFile","algorithm","then","hash","getFilePaths","relativeFilePaths","file","sort","runCommand","cacheByTime","cacheByFiles","shouldCacheOnError","execSh","promise","cache","flatCache","load","cacheKey","cacheData","getKey","fileHashes","currentDate","Date","areFileHashesEqual","isEqual","isWithinCacheTime","lastRun","isAfter","add","execPromise","catch","error","setKey","save","hardRejection","program","sade","version","describe","option","default","example","action","options","cacheDirectory","time","files","Array","isArray","some","parse","argv"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAOgBA,sBAAsBC;AAClC,MAAIA,0BAAJ,EAAgC;AAC5B,WAAOC,wBAAI,CAACC,OAAL,CAAaC,OAAO,CAACC,GAAR,EAAb,EAA4BJ,0BAA5B,CAAP;AACH;;AAED,QAAMK,sBAAsB,GAAGC,gCAAY,CAAC;AAAEC,IAAAA;AAAF,GAAD,CAA3C;;AAEA,MAAI,CAACF,sBAAL,EAA6B;AACzB,UAAMG,KAAK,CAAC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,CAACoH,IAAtB;;"}
1
+ {"version":3,"file":"cli.cjs","sources":["../src/utils/get-cache-dir.ts","../src/cache-clear.ts","../src/cache-dir.ts","../src/utils/get-cache-key.ts","../src/utils/get-duration.ts","../src/utils/get-file-hashes.ts","../src/utils/get-file-paths.ts","../src/run.ts","../src/cli.ts"],"sourcesContent":["import path from 'path'\n\nimport findCacheDir from 'find-cache-dir'\nimport makeDir from 'make-dir'\n\nimport { name } from '../../package.json'\n\nexport function getCacheDirectoryPath(relativeCacheDirectoryPath: string | undefined) {\n if (relativeCacheDirectoryPath) {\n return path.resolve(process.cwd(), relativeCacheDirectoryPath)\n }\n\n const resolvedCacheDirectory = findCacheDir({ name })\n\n if (!resolvedCacheDirectory) {\n throw Error('Could not find cache directory. Please provide a cache directory manually.')\n }\n\n return resolvedCacheDirectory\n}\n\nexport function createCache(relativeCacheDirectoryPath: string | undefined) {\n if (relativeCacheDirectoryPath) {\n const absoluteCacheDirectoryPath = makeDir.sync(relativeCacheDirectoryPath)\n\n return absoluteCacheDirectoryPath\n }\n\n const resolvedCachePath = findCacheDir({ name, create: true })\n\n if (!resolvedCachePath) {\n throw Error('Could not find cache directory. Please provide a cache directory manually.')\n }\n\n return resolvedCachePath\n}\n","import del from 'del'\n\nimport { getCacheDirectoryPath } from './utils/get-cache-dir'\n\nexport function clearCacheDirectory(relativeCacheDirectory: string | undefined) {\n const deletedPaths = del.sync(getCacheDirectoryPath(relativeCacheDirectory))\n\n if (deletedPaths.length === 0) {\n console.log('No cache to clear')\n } else if (deletedPaths.length === 1) {\n console.log(`Deleted: ${deletedPaths[0]}`)\n } else {\n console.log('Deleted:\\n', deletedPaths.join('\\n'))\n }\n}\n","import { getCacheDirectoryPath } from './utils/get-cache-dir'\n\nexport function showCacheDirectory(relativeCacheDirectory: string | undefined) {\n console.log(getCacheDirectoryPath(relativeCacheDirectory))\n}\n","interface GetCacheKeyProps {\n duration: Duration | undefined\n filePaths: string[]\n command: string\n}\n\ninterface Duration {\n years: number | undefined\n months: number | undefined\n weeks: number | undefined\n days: number | undefined\n hours: number | undefined\n minutes: number | undefined\n seconds: number | undefined\n}\n\nexport function getCacheKey({ duration, filePaths, command }: GetCacheKeyProps) {\n return [\n 'cwd:' + process.cwd(),\n 'cmd:' + command,\n duration && 'time:' + JSON.stringify(duration),\n filePaths.length !== 0 && 'files:' + filePaths.join(','),\n ]\n .filter(Boolean)\n .join(' ---')\n}\n","export function getDuration(durationString: string) {\n if (!/^(\\d+[a-z]+)+$/gi.test(durationString)) {\n throw Error(`Invalid duration: ${durationString}`)\n }\n\n const duration = {\n years: undefined as undefined | number,\n months: undefined as undefined | number,\n weeks: undefined as undefined | number,\n days: undefined as undefined | number,\n hours: undefined as undefined | number,\n minutes: undefined as undefined | number,\n seconds: undefined as undefined | number,\n }\n\n durationString.match(/\\d+[a-z]+/gi)!.forEach((durationPart) => {\n const [, stringQuantity, unitShort] = /(\\d+)([a-z]+)/gi.exec(durationPart)!\n const quantity = Number(stringQuantity)\n\n const unitLong = (\n {\n y: 'years',\n mo: 'months',\n w: 'weeks',\n d: 'days',\n h: 'hours',\n m: 'minutes',\n s: 'seconds',\n } as const\n )[unitShort!]\n\n if (Number.isNaN(quantity) || !unitLong) {\n throw Error(`Invalid duration part: ${durationPart}`)\n }\n\n if (duration[unitLong] !== undefined) {\n throw Error(`Duration with unit ${unitLong} was supplied multiple times`)\n }\n\n duration[unitLong] = quantity\n })\n\n return duration\n}\n","import hasha from 'hasha'\n\nexport async function getFileHashes(filePaths: string[]) {\n return Object.fromEntries(\n await Promise.all(\n filePaths.map((filePath) =>\n hasha\n .fromFile(filePath, { algorithm: 'md5' })\n .then((hash) => [filePath, hash] as const)\n )\n )\n )\n}\n","import path from 'path'\n\nexport function getFilePaths(relativeFilePaths: string[]) {\n const cwd = process.cwd()\n\n return relativeFilePaths.map((file) => path.resolve(cwd, file)).sort()\n}\n","import { add, isAfter } from 'date-fns'\nimport execSh from 'exec-sh'\nimport flatCache from 'flat-cache'\nimport { isEqual } from 'lodash'\n\nimport { createCache } from './utils/get-cache-dir'\nimport { getCacheKey } from './utils/get-cache-key'\nimport { getDuration } from './utils/get-duration'\nimport { getFileHashes } from './utils/get-file-hashes'\nimport { getFilePaths } from './utils/get-file-paths'\n\ninterface RunCommandProps {\n relativeCacheDirectory: string | undefined\n command: string\n cacheByTime: string | undefined\n cacheByFiles: string[]\n shouldCacheOnError: boolean | undefined\n}\n\nexport async function runCommand({\n relativeCacheDirectory,\n command,\n cacheByTime: cacheByTime,\n cacheByFiles: cacheByFiles,\n shouldCacheOnError,\n}: RunCommandProps) {\n if (!cacheByTime && cacheByFiles.length === 0) {\n console.log(`Executing command \"${command}\" due to no caching options provided`)\n await execSh.promise(command)\n return\n }\n\n const cache = flatCache.load('commands-cache.json', createCache(relativeCacheDirectory))\n const filePaths = getFilePaths(cacheByFiles)\n const duration = cacheByTime ? getDuration(cacheByTime) : undefined\n\n const cacheKey = getCacheKey({ duration, filePaths, command })\n\n const cacheData: unknown = cache.getKey(cacheKey)\n\n const fileHashes = filePaths.length === 0 ? undefined : await getFileHashes(filePaths)\n const currentDate = new Date()\n\n const areFileHashesEqual = isEqual((cacheData as any)?.fileHashes, fileHashes)\n const isWithinCacheTime = (() => {\n if (!duration) {\n return true\n }\n\n const lastRun = (cacheData as any)?.lastRun\n\n if (!lastRun) {\n return false\n }\n\n return isAfter(add(new Date(lastRun), duration), currentDate)\n })()\n\n if (areFileHashesEqual && isWithinCacheTime) {\n console.log(\n [\n `Skipping command \"${command}\" due to`,\n [fileHashes && 'unchanged files', duration && 'being within cache time']\n .filter(Boolean)\n .join(' and '),\n ].join(' ')\n )\n return\n }\n\n console.log(\n [\n `Executing command \"${command}\" due to`,\n [fileHashes && 'changed files', duration && 'cache time passing']\n .filter(Boolean)\n .join(' and '),\n ].join(' ')\n )\n let execPromise = execSh.promise(command)\n\n function setCache() {\n cache.setKey(cacheKey, {\n lastRun: currentDate,\n fileHashes,\n })\n cache.save(true)\n console.log(`Cache saved for command \"${command}\"`)\n }\n\n if (shouldCacheOnError) {\n execPromise = execPromise.catch((error: unknown) => {\n setCache()\n\n throw error\n })\n }\n\n await execPromise\n\n setCache()\n}\n","#!/usr/bin/env node\n\nimport hardRejection from 'hard-rejection'\nimport sade from 'sade'\n\nimport { version } from '../package.json'\n\nimport { clearCacheDirectory } from './cache-clear'\nimport { showCacheDirectory } from './cache-dir'\nimport { runCommand } from './run'\n\nhardRejection()\n\nconst program = sade('cache-cmd')\n\nprogram\n .version(version)\n .describe('Run and cache a command based on various factors')\n .option(\n '-c, --cache-dir',\n 'Cache directory to use (default: .cache/cache-cmd in nearest node_modules)'\n )\n\nprogram\n .command(\n 'run <command>',\n 'Run cached command (if no <command> provided, this is the default)',\n { default: true }\n )\n .option('-f, --file', 'Run command only when file content changes')\n .option('-t, --time', 'Run command only after specified time (unit with s,m,h,d,w,mo,y)')\n .option('--cache-on-error', 'Cache command run even when command exits with non-zero exit code')\n .example('run \"echo ran this command\" --time 20s')\n .example('run \"./may-fail\" --time 20s --cache-on-error')\n .example('run \"yarn install\" --file yarn.lock')\n .example('run \"yarn install\" --file yarn.lock --cache-dir .config/cache')\n .example('run \"yarn install\" --time 1mo --file yarn.lock --file package.json')\n .action((command: unknown, options: Record<string, unknown>) => {\n const cacheDirectory = options['cache-dir']\n const time = options.time\n const file = options.file\n const shouldCacheOnError = options['cache-on-error']\n const files: unknown[] = file === undefined ? [] : Array.isArray(file) ? file : [file]\n\n if (typeof command !== 'string') {\n throw Error('Invalid <command> supplied')\n }\n\n if (cacheDirectory !== undefined && typeof cacheDirectory !== 'string') {\n throw Error('Invalid --cache-dir supplied')\n }\n\n if (time !== undefined && typeof time !== 'string') {\n throw Error('Invalid --time supplied')\n }\n\n if (files.some((file) => typeof file !== 'string')) {\n throw Error('Invalid --file supplied')\n }\n\n if (shouldCacheOnError !== undefined && typeof shouldCacheOnError !== 'boolean') {\n throw Error('Invalid --cache-on-error supplied')\n }\n\n runCommand({\n relativeCacheDirectory: cacheDirectory,\n command,\n cacheByTime: time,\n cacheByFiles: files as string[],\n shouldCacheOnError,\n })\n })\n\nprogram\n .command('cache dir', 'Show cache directory path used by cache-cmd')\n .action((options: Record<string, unknown>) => {\n const cacheDirectory = options['cache-dir']\n\n if (cacheDirectory !== undefined && typeof cacheDirectory !== 'string') {\n throw Error('Invalid --cache-dir supplied')\n }\n\n showCacheDirectory(cacheDirectory)\n })\n\nprogram\n .command('cache clear', 'Clear cache used by cache-cmd')\n .action((options: Record<string, unknown>) => {\n const cacheDirectory = options['cache-dir']\n\n if (cacheDirectory !== undefined && typeof cacheDirectory !== 'string') {\n throw Error('Invalid --cache-dir supplied')\n }\n\n clearCacheDirectory(cacheDirectory)\n })\n\nprogram.parse(process.argv)\n"],"names":["getCacheDirectoryPath","relativeCacheDirectoryPath","path","resolve","process","cwd","resolvedCacheDirectory","findCacheDir","name","Error","createCache","absoluteCacheDirectoryPath","makeDir","sync","resolvedCachePath","create","clearCacheDirectory","relativeCacheDirectory","deletedPaths","del","length","console","log","join","showCacheDirectory","getCacheKey","duration","filePaths","command","JSON","stringify","filter","Boolean","getDuration","durationString","test","years","undefined","months","weeks","days","hours","minutes","seconds","match","forEach","durationPart","stringQuantity","unitShort","exec","quantity","Number","unitLong","y","mo","w","d","h","m","s","isNaN","getFileHashes","Object","fromEntries","Promise","all","map","filePath","hasha","fromFile","algorithm","then","hash","getFilePaths","relativeFilePaths","file","sort","runCommand","cacheByTime","cacheByFiles","shouldCacheOnError","execSh","promise","cache","flatCache","load","cacheKey","cacheData","getKey","fileHashes","currentDate","Date","areFileHashesEqual","isEqual","isWithinCacheTime","lastRun","isAfter","add","execPromise","setCache","setKey","save","catch","error","hardRejection","program","sade","version","describe","option","default","example","action","options","cacheDirectory","time","files","Array","isArray","some","parse","argv"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;SAOgBA,sBAAsBC;AAClC,MAAIA,0BAAJ,EAAgC;AAC5B,WAAOC,wBAAI,CAACC,OAAL,CAAaC,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MAFL,CAEaC,OAAD;AACJ,QAAMC,cAAc,GAAGD,OAAO,CAAC,WAAD,CAA9B;;AAEA,MAAIC,cAAc,KAAK7E,SAAnB,IAAgC,OAAO6E,cAAP,KAA0B,QAA9D,EAAwE;AACpE,UAAMzG,KAAK,CAAC,8BAAD,CAAX;AACH;;AAEDe,EAAAA,kBAAkB,CAAC0F,cAAD,CAAlB;AACH,CAVL;AAYAT,OAAO,CACF7E,OADL,CACa,aADb,EAC4B,+BAD5B,EAEKoF,MAFL,CAEaC,OAAD;AACJ,QAAMC,cAAc,GAAGD,OAAO,CAAC,WAAD,CAA9B;;AAEA,MAAIC,cAAc,KAAK7E,SAAnB,IAAgC,OAAO6E,cAAP,KAA0B,QAA9D,EAAwE;AACpE,UAAMzG,KAAK,CAAC,8BAAD,CAAX;AACH;;AAEDO,EAAAA,mBAAmB,CAACkG,cAAD,CAAnB;AACH,CAVL;AAYAT,OAAO,CAACe,KAAR,CAAcpH,OAAO,CAACqH,IAAtB;;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cache-cmd",
3
- "version": "0.2.0-dev.4a662091d40f9510cff02e70023e5919708daa8f",
3
+ "version": "0.2.0-dev.7098ba3784d94f8515529435c60343ac3e724316",
4
4
  "description": "Cache a command based on various factors",
5
5
  "keywords": [
6
6
  "cache",
package/src/run.ts CHANGED
@@ -25,6 +25,7 @@ export async function runCommand({
25
25
  shouldCacheOnError,
26
26
  }: RunCommandProps) {
27
27
  if (!cacheByTime && cacheByFiles.length === 0) {
28
+ console.log(`Executing command "${command}" due to no caching options provided`)
28
29
  await execSh.promise(command)
29
30
  return
30
31
  }
@@ -56,18 +57,39 @@ export async function runCommand({
56
57
  })()
57
58
 
58
59
  if (areFileHashesEqual && isWithinCacheTime) {
60
+ console.log(
61
+ [
62
+ `Skipping command "${command}" due to`,
63
+ [fileHashes && 'unchanged files', duration && 'being within cache time']
64
+ .filter(Boolean)
65
+ .join(' and '),
66
+ ].join(' ')
67
+ )
59
68
  return
60
69
  }
61
70
 
71
+ console.log(
72
+ [
73
+ `Executing command "${command}" due to`,
74
+ [fileHashes && 'changed files', duration && 'cache time passing']
75
+ .filter(Boolean)
76
+ .join(' and '),
77
+ ].join(' ')
78
+ )
62
79
  let execPromise = execSh.promise(command)
63
80
 
81
+ function setCache() {
82
+ cache.setKey(cacheKey, {
83
+ lastRun: currentDate,
84
+ fileHashes,
85
+ })
86
+ cache.save(true)
87
+ console.log(`Cache saved for command "${command}"`)
88
+ }
89
+
64
90
  if (shouldCacheOnError) {
65
91
  execPromise = execPromise.catch((error: unknown) => {
66
- cache.setKey(cacheKey, {
67
- lastRun: currentDate,
68
- fileHashes,
69
- })
70
- cache.save(true)
92
+ setCache()
71
93
 
72
94
  throw error
73
95
  })
@@ -75,9 +97,5 @@ export async function runCommand({
75
97
 
76
98
  await execPromise
77
99
 
78
- cache.setKey(cacheKey, {
79
- lastRun: currentDate,
80
- fileHashes,
81
- })
82
- cache.save(true)
100
+ setCache()
83
101
  }