From af2778076322b14dec6f1164b651beb557994ef4 Mon Sep 17 00:00:00 2001 From: "Lin, Hung-Shin" Date: Wed, 25 Oct 2023 13:34:10 +0800 Subject: [PATCH] feat: buildFileCheckCmd --- packages/utils/commands.js | 16 ++++++++++++++ packages/utils/commands.test.js | 38 +++++++++++++++++++++++++++++++++ packages/utils/index.js | 1 + 3 files changed, 55 insertions(+) create mode 100644 packages/utils/commands.js create mode 100644 packages/utils/commands.test.js diff --git a/packages/utils/commands.js b/packages/utils/commands.js new file mode 100644 index 0000000..45c6a9a --- /dev/null +++ b/packages/utils/commands.js @@ -0,0 +1,16 @@ +const fileTypes = { + file: '-f', + folder: '-d', + link: '-L', + socket: '-S', +} + +// eslint-disable-next-line import/prefer-default-export +export function buildFileCheckCmd(files) { + return files + .map( + ({ path, type, exists }) => + `${exists ? '' : '! '}test ${fileTypes[type] || '-e'} ${path}` + ) + .join(' && ') +} diff --git a/packages/utils/commands.test.js b/packages/utils/commands.test.js new file mode 100644 index 0000000..25c81a6 --- /dev/null +++ b/packages/utils/commands.test.js @@ -0,0 +1,38 @@ +import { buildFileCheckCmd } from './commands.js' + +describe('buildFileCheckCmd function', () => { + it('builds the file check command correctly', () => { + const testcases = [ + { + input: [{ path: '/etc/passwd', type: 'file', exists: true }], + output: 'test -f /etc/passwd', + }, + { + input: [{ path: '/etc', type: 'folder', exists: false }], + output: '! test -d /etc', + }, + { + input: [ + { path: '/etc/passwd', type: 'file', exists: true }, + { path: '/etc', type: 'folder', exists: false }, + ], + output: 'test -f /etc/passwd && ! test -d /etc', + }, + { + input: [ + { path: '/tmp/socket', type: 'socket', exists: true }, + { path: '/tmp/link', type: 'link', exists: false }, + ], + output: 'test -S /tmp/socket && ! test -L /tmp/link', + }, + { + input: [{ path: '/unknown', type: 'unknown', exists: true }], + output: 'test -e /unknown', + }, + ] + + testcases.forEach(({ input, output }) => { + expect(buildFileCheckCmd(input)).toBe(output) + }) + }) +}) diff --git a/packages/utils/index.js b/packages/utils/index.js index ab747e8..8d79493 100644 --- a/packages/utils/index.js +++ b/packages/utils/index.js @@ -1 +1,2 @@ export { isValidEmail, isValidUsername } from './auth.js' +export { buildFileCheckCmd } from './commands.js'