From 9539fe053245e9fea10ceda0e46fe61e9de80797 Mon Sep 17 00:00:00 2001 From: "Max P." Date: Wed, 21 May 2025 02:58:05 +0200 Subject: [PATCH] feat(utils): add function to derive sanitized job names - Introduces a utility function to extract and sanitize job names from executable paths by removing paths, extensions, and special characters. - Adds unit tests to validate function behavior with various inputs. --- src/utils/__tests__/misc.test.ts | 19 +++++++++++++++++++ src/utils/misc.ts | 12 ++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 src/utils/__tests__/misc.test.ts create mode 100644 src/utils/misc.ts diff --git a/src/utils/__tests__/misc.test.ts b/src/utils/__tests__/misc.test.ts new file mode 100644 index 0000000..ee5af75 --- /dev/null +++ b/src/utils/__tests__/misc.test.ts @@ -0,0 +1,19 @@ +import { assertEquals } from 'https://deno.land/std@0.224.0/assert/mod.ts'; +import { deriveNameFromExec } from '../mod.ts'; + +Deno.test('deriveNameFromExec - entfernt Pfad, Endung und Sonderzeichen', () => { + const tests: Array<[string, string]> = [ + ['/usr/local/bin/backup.sh', 'backup'], + ['/usr/bin/python3 /home/user/myscript.py', 'python3'], + ['./my-job.ts', 'my-job'], + ['node ./tools/start.js', 'node'], + ['/bin/custom-script.rb', 'custom-script'], + [' /usr/bin/something-strange!.bin ', 'something-strange'], + ['weird:name?.sh', 'weird-name'], + ['', 'job'], + ]; + + for (const [input, expected] of tests) { + assertEquals(deriveNameFromExec(input), expected); + } +}); diff --git a/src/utils/misc.ts b/src/utils/misc.ts new file mode 100644 index 0000000..37aa9cc --- /dev/null +++ b/src/utils/misc.ts @@ -0,0 +1,12 @@ +export function deriveNameFromExec(exec: string): string { + const parts = exec.trim().split(' '); + const base = parts[0].split('/').pop() || 'job'; + + // remove the file extension + const withoutExt = base.replace(/\.(sh|py|ts|js|pl|rb|exe|bin)$/, ''); + + // replace illegal chars, then trim leading/trailing hyphens + return withoutExt + .replaceAll(/[^a-zA-Z0-9_-]/g, '-') + .replace(/^-+|-+$/g, ''); +}