Skip to content

Commit a8e9af6

Browse files
committed
add migration file name validation
1 parent 24693bb commit a8e9af6

File tree

3 files changed

+56
-1
lines changed

3 files changed

+56
-1
lines changed

.husky/pre-commit

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11

22
npx lint-staged
33
npm run translations -- --lang fi,en --quiet
4+
npm run migrations
45
npm run tsc

package.json

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@
1717
"prepare": "husky install",
1818
"test:e2e": "playwright test",
1919
"test:record": "playwright codegen -o e2e/recorded.spec.ts localhost:3000",
20-
"translations": "node scripts/analyzeTranslations.js"
20+
"translations": "node scripts/analyzeTranslations.js",
21+
"migrations": "node scripts/analyzeMigrationNames.js"
2122
},
2223
"repository": {
2324
"type": "git",

scripts/analyzeMigrationNames.js

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import fs from 'fs'
2+
import path from 'path'
3+
4+
const Reset = '\x1b[0m'
5+
const Bright = '\x1b[1m'
6+
const FgRed = '\x1b[31m'
7+
const FgYellow = '\x1b[33m'
8+
const FgGreen = '\x1b[32m'
9+
10+
// Matches only the leading date portion with underscore:
11+
// - YYYY = 4 digits
12+
// - MM = 01–12
13+
// - DD = 01–31
14+
// - ends with underscore
15+
const regDate = /^(\d{4})(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])_/
16+
17+
// Matches only the required prefix before the name:
18+
// - 8 digits (YYYYMMDD)
19+
// - underscore
20+
// - 2 digits (NN)
21+
// - underscore
22+
const regPrefix = /^\d{8}_\d{2}_/
23+
24+
// Correct date + prefix and filename snake cased
25+
const regFull = /^(?:\d{4})(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])_\d{2}_[^\\/]+$/
26+
27+
const MIGRATIONS_PATH = './src/server/db/migrations'
28+
const dirPath = path.join(process.cwd(), MIGRATIONS_PATH)
29+
const files = fs.readdirSync(dirPath)
30+
31+
let errors = []
32+
33+
for (const file of files) {
34+
if (!regPrefix.test(file)) {
35+
errors.push(`${FgRed}${Bright}${Reset} ${file} ${FgYellow}→ must start with YYYYMMDD_NN_${Reset}`)
36+
continue
37+
}
38+
if (!regDate.test(file)) {
39+
errors.push(`${FgRed}${Bright}${Reset} ${file} ${FgYellow}→ invalid date format${Reset}`)
40+
continue
41+
}
42+
if (!regFull.test(file)) {
43+
errors.push(`${FgRed}${Bright}${Reset} ${file} ${FgYellow}→ contains invalid characters${Reset}`)
44+
}
45+
}
46+
47+
if (errors.length > 0) {
48+
console.error('Migration file name check failed:')
49+
console.error(errors.join('\n'))
50+
process.exit(1)
51+
} else {
52+
console.log(`${FgGreen}${Bright}Success:${Reset} All migration names ok\n`)
53+
}

0 commit comments

Comments
 (0)