@nitra/cursor 1.8.170 → 1.8.173

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.
@@ -16,6 +16,7 @@ import { spawnSync } from 'node:child_process'
16
16
  import { basename, dirname } from 'node:path'
17
17
 
18
18
  import { isRunAsCli } from './cli-entry.mjs'
19
+ import { loadCursorIgnorePaths } from './utils/load-cursor-config.mjs'
19
20
  import { resolveCmd } from './utils/resolve-cmd.mjs'
20
21
  import { walkDir } from './utils/walkDir.mjs'
21
22
 
@@ -60,15 +61,19 @@ export function k8sRootFromFile(absFile) {
60
61
  * @param {string} root корінь репозиторію
61
62
  * @returns {Promise<string[]>} відсортовані абсолютні шляхи до каталогів `k8s`
62
63
  */
63
- export async function findK8sRoots(root) {
64
+ export async function findK8sRoots(root, ignorePaths = []) {
64
65
  /** @type {Set<string>} */
65
66
  const roots = new Set()
66
- await walkDir(root, p => {
67
- if (!pathHasK8sSegment(p)) return
68
- if (!YAML_EXT_RE.test(p)) return
69
- const k8sRoot = k8sRootFromFile(p)
70
- if (k8sRoot) roots.add(k8sRoot)
71
- })
67
+ await walkDir(
68
+ root,
69
+ p => {
70
+ if (!pathHasK8sSegment(p)) return
71
+ if (!YAML_EXT_RE.test(p)) return
72
+ const k8sRoot = k8sRootFromFile(p)
73
+ if (k8sRoot) roots.add(k8sRoot)
74
+ },
75
+ ignorePaths
76
+ )
72
77
  return [...roots].toSorted((a, b) => a.localeCompare(b))
73
78
  }
74
79
 
@@ -134,7 +139,8 @@ function runKubescape(dirs) {
134
139
  */
135
140
  async function main() {
136
141
  const root = process.cwd()
137
- const dirs = await findK8sRoots(root)
142
+ const ignorePaths = await loadCursorIgnorePaths(root)
143
+ const dirs = await findK8sRoots(root, ignorePaths)
138
144
 
139
145
  if (dirs.length === 0) {
140
146
  console.log('run-k8s: немає *.yaml під k8s — kubeconform і kubescape пропущено')
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Утиліта читання `.n-cursor.json` у корені репозиторію.
3
+ *
4
+ * Зараз експортує `loadCursorIgnorePaths(root)` — список абсолютних posix-шляхів каталогів,
5
+ * які check-скрипти повністю виключають з обходу (поле `ignore` у конфізі).
6
+ */
7
+ import { existsSync } from 'node:fs'
8
+ import { readFile } from 'node:fs/promises'
9
+ import { isAbsolute, join, resolve, sep } from 'node:path'
10
+
11
+ const CONFIG_FILE = '.n-cursor.json'
12
+
13
+ /**
14
+ * Нормалізує шлях до абсолютного posix-формату без trailing-slash.
15
+ * Відносні шляхи розв'язуються від `root`.
16
+ * @param {string} root абсолютний корінь репозиторію
17
+ * @param {string} p шлях з конфігу (відносний або абсолютний)
18
+ * @returns {string} абсолютний posix-шлях
19
+ */
20
+ function toAbsPosix(root, p) {
21
+ const trimmed = String(p).trim()
22
+ const abs = isAbsolute(trimmed) ? trimmed : resolve(root, trimmed)
23
+ return abs.split(sep).join('/').replace(/\/+$/, '')
24
+ }
25
+
26
+ /**
27
+ * Читає `.n-cursor.json` з кореня та повертає нормалізовані ignore-шляхи.
28
+ * Якщо файлу нема, поле `ignore` відсутнє чи має невалідний формат — повертає порожній масив.
29
+ * Сам конфіг не валідується (це робить v8r/окрема перевірка) — лише поле `ignore`.
30
+ * @param {string} root абсолютний корінь репозиторію
31
+ * @returns {Promise<string[]>} абсолютні posix-шляхи без trailing-slash
32
+ */
33
+ export async function loadCursorIgnorePaths(root) {
34
+ const file = join(root, CONFIG_FILE)
35
+ if (!existsSync(file)) return []
36
+ let raw
37
+ try {
38
+ raw = JSON.parse(await readFile(file, 'utf8'))
39
+ } catch {
40
+ return []
41
+ }
42
+ const list = raw?.ignore
43
+ if (!Array.isArray(list)) return []
44
+ /** @type {string[]} */
45
+ const out = []
46
+ for (const item of list) {
47
+ if (typeof item !== 'string') continue
48
+ const v = item.trim()
49
+ if (v.length === 0) continue
50
+ out.push(toAbsPosix(root, v))
51
+ }
52
+ return out
53
+ }
@@ -2,19 +2,60 @@
2
2
  * Рекурсивний обхід каталогів для скриптів перевірки (Dockerfile, k8s YAML тощо).
3
3
  *
4
4
  * Обходить дерево від заданого кореня; для кожного звичайного файлу викликає переданий callback.
5
- * Каталоги node_modules, .git, dist, coverage, .turbo, .next не заходяться. Якщо readdir для
6
- * каталогу не вдаєтьсятихо виходить без throw.
5
+ * Каталоги node_modules, .git, dist, coverage, .turbo, .next не заходяться.
6
+ * Додатково можна передати `ignorePaths` повні шляхи каталогів (абсолютні posix), які слід
7
+ * пропускати разом з усім вмістом (поле `ignore` у `.n-cursor.json`). Якщо readdir для каталогу
8
+ * не вдається — тихо виходить без throw.
7
9
  */
8
10
  import { readdir } from 'node:fs/promises'
9
- import { join } from 'node:path'
11
+ import { isAbsolute, join, resolve, sep } from 'node:path'
10
12
 
11
13
  /**
12
- * Рекурсивно обходить каталог, пропускає типові артефакти збірки та залежностей.
14
+ * Перетворює довільний шлях у абсолютний posix-формат без trailing-slash.
15
+ * @param {string} p шлях
16
+ * @returns {string} абсолютний posix-шлях
17
+ */
18
+ function toAbsPosix(p) {
19
+ const abs = isAbsolute(p) ? p : resolve(p)
20
+ return abs.split(sep).join('/').replace(/\/+$/, '')
21
+ }
22
+
23
+ /**
24
+ * Чи каталог `dirAbsPosix` входить у список ignore (точний збіг або префікс з '/').
25
+ * Часткові збіги басенейму не враховуються (postgres-master-test ≠ postgres-master).
26
+ * @param {string} dirAbsPosix абсолютний posix-шлях каталогу
27
+ * @param {string[]} ignorePosix вже нормалізовані ignore-шляхи
28
+ * @returns {boolean}
29
+ */
30
+ function isIgnoredDir(dirAbsPosix, ignorePosix) {
31
+ for (const ig of ignorePosix) {
32
+ if (dirAbsPosix === ig) return true
33
+ if (dirAbsPosix.startsWith(`${ig}/`)) return true
34
+ }
35
+ return false
36
+ }
37
+
38
+ /**
39
+ * Рекурсивно обходить каталог, пропускає типові артефакти збірки/залежностей та `ignorePaths`.
13
40
  * @param {string} dir абсолютний шлях
14
41
  * @param {(filePath: string) => void} onFile виклик для кожного файлу
42
+ * @param {string[]} [ignorePaths=[]] шляхи каталогів (відносні від cwd або абсолютні), що повністю виключаються з обходу
43
+ * @returns {Promise<void>}
44
+ */
45
+ export async function walkDir(dir, onFile, ignorePaths = []) {
46
+ const ignorePosix = ignorePaths.map(toAbsPosix)
47
+ await walkDirInner(dir, onFile, ignorePosix)
48
+ }
49
+
50
+ /**
51
+ * Внутрішній рекурсор. ignorePosix вже нормалізовано — не нормалізуємо повторно на кожному рівні.
52
+ * @param {string} dir
53
+ * @param {(filePath: string) => void} onFile
54
+ * @param {string[]} ignorePosix
15
55
  * @returns {Promise<void>}
16
56
  */
17
- export async function walkDir(dir, onFile) {
57
+ async function walkDirInner(dir, onFile, ignorePosix) {
58
+ if (ignorePosix.length > 0 && isIgnoredDir(toAbsPosix(dir), ignorePosix)) return
18
59
  let entries
19
60
  try {
20
61
  entries = await readdir(dir, { withFileTypes: true })
@@ -31,9 +72,9 @@ export async function walkDir(dir, onFile) {
31
72
  e.name === 'coverage' ||
32
73
  e.name === '.turbo' ||
33
74
  e.name === '.next'
34
- if (!skipDir) {
35
- await walkDir(p, onFile)
36
- }
75
+ if (skipDir) continue
76
+ if (ignorePosix.length > 0 && isIgnoredDir(toAbsPosix(p), ignorePosix)) continue
77
+ await walkDirInner(p, onFile, ignorePosix)
37
78
  } else if (e.isFile()) {
38
79
  onFile(p)
39
80
  }