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.
This commit is contained in:
2025-05-21 02:58:05 +02:00
parent ef2ac416d9
commit 9539fe0532
2 changed files with 31 additions and 0 deletions

View File

@@ -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);
}
});

12
src/utils/misc.ts Normal file
View File

@@ -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, '');
}