@chengzhao-dev/dsh-cpp-workflow 0.7.9 → 0.7.11

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.
Files changed (126) hide show
  1. package/README.en.md +8 -7
  2. package/README.md +5 -4
  3. package/cordis.patch.yml +2 -2
  4. package/icon.svg +5 -5
  5. package/lib/client.js +542 -538
  6. package/lib/comment-policy.js +37 -33
  7. package/lib/workspace.js +8 -10
  8. package/locale/en.json +4 -4
  9. package/locale/zh.json +4 -4
  10. package/package.json +100 -100
  11. package/skills/building-cpp/SKILL.md +5 -5
  12. package/skills/building-cpp/assets/config/.clang-tidy +4 -5
  13. package/skills/building-cpp/assets/config/.clangd +5 -7
  14. package/skills/building-cpp/assets/config/.vscode/extensions.json +5 -5
  15. package/skills/building-cpp/assets/config/.vscode/settings.json +56 -58
  16. package/skills/building-cpp/examples/environment.md +13 -102
  17. package/skills/building-cpp/references/01-build-script.md +3 -3
  18. package/skills/building-cpp/references/02-environment.md +8 -8
  19. package/skills/building-cpp/scripts/checking-environment.mjs +424 -424
  20. package/skills/building-cpp/steps/01-build.md +10 -10
  21. package/skills/building-cpp/steps/02-tooling.md +6 -6
  22. package/skills/building-cpp/steps/03-check.md +2 -2
  23. package/skills/building-cpp/steps/04-vscode.md +4 -6
  24. package/skills/developing-cpp/SKILL.md +8 -9
  25. package/skills/developing-cpp/references/comments/01-comment-rules.md +50 -26
  26. package/skills/developing-cpp/references/comments/02-style.md +33 -25
  27. package/skills/developing-cpp/references/comments/examples/03-declaration-enum.md +14 -14
  28. package/skills/developing-cpp/references/comments/examples/04-declaration-file.md +12 -8
  29. package/skills/developing-cpp/references/comments/examples/05-declaration-function.md +20 -10
  30. package/skills/developing-cpp/references/comments/examples/06-declaration-member.md +4 -4
  31. package/skills/developing-cpp/references/comments/examples/07-declaration-predicate.md +2 -2
  32. package/skills/developing-cpp/references/comments/examples/08-declaration-struct.md +6 -6
  33. package/skills/developing-cpp/references/comments/examples/09-implementation-body.md +41 -41
  34. package/skills/developing-cpp/references/comments/glossary/01-comment-terms.md +17 -16
  35. package/skills/developing-cpp/references/design/01-project-design.md +21 -10
  36. package/skills/developing-cpp/references/design/02-raii.md +5 -4
  37. package/skills/developing-cpp/references/design/03-third-party.md +2 -2
  38. package/skills/developing-cpp/references/design/examples/02-coordinate-table.md +12 -12
  39. package/skills/developing-cpp/references/design/examples/03-header-place.md +1 -1
  40. package/skills/developing-cpp/references/design/examples/04-library-boundary.md +6 -6
  41. package/skills/developing-cpp/references/design/examples/06-move-result.md +29 -28
  42. package/skills/developing-cpp/references/design/examples/07-preview-read.md +24 -23
  43. package/skills/developing-cpp/references/design/examples/08-screen-enter-exit.md +19 -18
  44. package/skills/developing-cpp/references/design/examples/09-option-menu.md +6 -6
  45. package/skills/developing-cpp/references/design/session-layer.md +13 -22
  46. package/skills/developing-cpp/references/exceptions/01-exception-rules.md +57 -57
  47. package/skills/developing-cpp/references/exceptions/examples/01-throw-boundary.md +7 -20
  48. package/skills/developing-cpp/references/exceptions/examples/02-throw-build-mode.md +10 -11
  49. package/skills/developing-cpp/references/exceptions/examples/03-throw-catch.md +4 -4
  50. package/skills/developing-cpp/references/exceptions/examples/04-throw-destructor.md +9 -5
  51. package/skills/developing-cpp/references/exceptions/examples/07-throw-when.md +2 -2
  52. package/skills/developing-cpp/references/index.md +32 -35
  53. package/skills/developing-cpp/references/language/glossary/01-language-terms.md +3 -2
  54. package/skills/developing-cpp/references/language/language-basics/02-initialization.md +1 -1
  55. package/skills/developing-cpp/references/language/language-basics/05-expressions.md +9 -2
  56. package/skills/developing-cpp/references/language/language-basics/06-functions.md +2 -3
  57. package/skills/developing-cpp/references/language/language-basics/09-templates.md +3 -3
  58. package/skills/developing-cpp/references/language/language-basics/10-language-checklist.md +9 -9
  59. package/skills/developing-cpp/references/language/performance/03-memory.md +1 -1
  60. package/skills/developing-cpp/references/language/performance/07-checklist.md +6 -6
  61. package/skills/developing-cpp/references/language/standard-library/01-containers.md +4 -5
  62. package/skills/developing-cpp/references/language/standard-library/02-access.md +2 -5
  63. package/skills/developing-cpp/references/language/standard-library/05-string.md +1 -1
  64. package/skills/developing-cpp/references/language/standard-library/06-format.md +22 -20
  65. package/skills/developing-cpp/references/language/standard-library/{11-format-ecosystem.md → 07-format-ecosystem.md} +2 -11
  66. package/skills/developing-cpp/references/language/standard-library/{07-time.md → 08-time.md} +1 -1
  67. package/skills/developing-cpp/references/language/standard-library/{09-files.md → 10-files.md} +1 -1
  68. package/skills/developing-cpp/references/language/standard-library/11-library-checklist.md +8 -0
  69. package/skills/developing-cpp/references/language/value-types/02-signed.md +7 -7
  70. package/skills/developing-cpp/references/language/value-types/03-integer-roles.md +14 -2
  71. package/skills/developing-cpp/references/language/value-types/05-strong-type.md +2 -2
  72. package/skills/developing-cpp/references/language/value-types/06-const-method.md +5 -5
  73. package/skills/developing-cpp/references/language/value-types/07-nodiscard.md +1 -1
  74. package/skills/developing-cpp/references/language/value-types/08-comparison.md +1 -1
  75. package/skills/developing-cpp/references/language/value-types/09-subscript.md +1 -1
  76. package/skills/developing-cpp/references/language/value-types/11-checklist.md +7 -7
  77. package/skills/developing-cpp/references/layout/01-source-layout.md +13 -13
  78. package/skills/developing-cpp/references/layout/02-file-template.md +10 -10
  79. package/skills/developing-cpp/references/layout/03-declaration-order.md +83 -42
  80. package/skills/developing-cpp/references/naming/01-identifier-names.md +32 -30
  81. package/skills/developing-cpp/references/naming/examples/06-naming-lower-layer.md +15 -15
  82. package/skills/developing-cpp/references/naming/examples/07-naming-multiple-return.md +2 -2
  83. package/skills/developing-cpp/references/naming/examples/13-naming-state-change.md +24 -23
  84. package/skills/developing-cpp/references/naming/glossary/01-naming-terms.md +3 -3
  85. package/skills/developing-cpp/references/naming/glossary/02-position.md +9 -9
  86. package/skills/developing-cpp/references/naming/glossary/03-selection.md +5 -1
  87. package/skills/developing-cpp/references/naming/glossary/04-square.md +3 -3
  88. package/skills/developing-cpp/references/naming/glossary/05-scoring.md +2 -2
  89. package/skills/developing-cpp/references/naming/glossary/06-difficulty.md +7 -7
  90. package/skills/developing-cpp/references/naming/glossary/07-stream.md +1 -1
  91. package/skills/developing-cpp/references/style/01-google-cpp-style.md +13 -23
  92. package/skills/developing-cpp/scripts/checking-comments.mjs +961 -755
  93. package/skills/developing-cpp/scripts/checking-declaration-order.mjs +512 -515
  94. package/skills/developing-cpp/steps/01-behavior.md +0 -1
  95. package/skills/developing-cpp/steps/02-boundary.md +2 -3
  96. package/skills/developing-cpp/steps/03-declaration.md +9 -10
  97. package/skills/developing-cpp/steps/04-implementation.md +7 -8
  98. package/skills/engineering/SKILL.md +9 -10
  99. package/skills/engineering/references/cmake/assets/LinkSettings.cmake +1 -1
  100. package/skills/engineering/references/cmake/linking/02-rpath.md +5 -6
  101. package/skills/engineering/references/cmake/modules/01-functions.md +9 -9
  102. package/skills/engineering/references/cmake/standards/01-cxx-standard.md +6 -6
  103. package/skills/engineering/references/cmake/standards/index.md +8 -29
  104. package/skills/engineering/references/cmake/targets/01-target-rules.md +14 -13
  105. package/skills/engineering/references/cmake/targets/examples/01-rpath.md +1 -1
  106. package/skills/engineering/references/cmake/testing/01-ctest.md +3 -3
  107. package/skills/engineering/references/formatting/01-encoding.md +5 -5
  108. package/skills/engineering/references/formatting/02-clang-format.md +2 -2
  109. package/skills/engineering/references/formatting/03-clang-tidy.md +5 -5
  110. package/skills/engineering/references/formatting/04-clangd.md +32 -39
  111. package/skills/engineering/references/formatting/05-config-comments.md +88 -0
  112. package/skills/engineering/references/formatting/examples/02-clang-tidy.md +6 -6
  113. package/skills/engineering/references/formatting/examples/03-clangd.md +17 -17
  114. package/skills/engineering/references/index.md +5 -4
  115. package/skills/engineering/scripts/checking-encoding.mjs +369 -369
  116. package/skills/engineering/steps/01-targets.md +3 -3
  117. package/skills/engineering/steps/02-modules.md +1 -2
  118. package/skills/engineering/steps/03-check.md +2 -3
  119. package/templates/cpp-workflow-project/SKILL.md +1 -1
  120. package/templates/cpp-workflow-project/environment.json +4 -4
  121. package/skills/developing-cpp/references/design/examples/05-library-split.md +0 -8
  122. package/skills/developing-cpp/references/language/standard-library/10-library-checklist.md +0 -10
  123. package/skills/developing-cpp/references/naming/examples/02-naming-basic.md +0 -4
  124. package/skills/developing-cpp/references/naming/examples/10-naming-rename.md +0 -6
  125. package/skills/engineering/references/formatting/examples/04-config-comments.md +0 -70
  126. /package/skills/developing-cpp/references/language/standard-library/{08-random.md → 09-random.md} +0 -0
@@ -28,13 +28,13 @@ const UTF32_BE = [0x00, 0x00, 0xfe, 0xff]
28
28
 
29
29
  const CRLF_REQUIRED = new Set(['.bat', '.cmd'])
30
30
  const MSVC_SOURCE = new Set([
31
- '.c', '.cc', '.cpp', '.cxx', '.h', '.hh', '.hpp', '.hxx', '.inl', '.ixx', '.cppm', '.rc',
31
+ '.c', '.cc', '.cpp', '.cxx', '.h', '.hh', '.hpp', '.hxx', '.inl', '.ixx', '.cppm', '.rc',
32
32
  ])
33
33
  const ALWAYS_LF = new Set([
34
- '.md', '.qmd', '.txt', '.rst', '.yml', '.yaml', '.json', '.jsonc', '.json5', '.toml',
35
- '.ini', '.cfg', '.conf', '.sh', '.bash', '.zsh', '.fish', '.ps1', '.py', '.mjs', '.cjs',
36
- '.js', '.jsx', '.ts', '.tsx', '.css', '.scss', '.sass', '.less', '.html', '.htm', '.xml',
37
- '.svg', '.cmake', '.lua', '.sql', '.gitignore', '.gitattributes', '.editorconfig',
34
+ '.md', '.qmd', '.txt', '.rst', '.yml', '.yaml', '.json', '.jsonc', '.json5', '.toml',
35
+ '.ini', '.cfg', '.conf', '.sh', '.bash', '.zsh', '.fish', '.ps1', '.py', '.mjs', '.cjs',
36
+ '.js', '.jsx', '.ts', '.tsx', '.css', '.scss', '.sass', '.less', '.html', '.htm', '.xml',
37
+ '.svg', '.cmake', '.lua', '.sql', '.gitignore', '.gitattributes', '.editorconfig',
38
38
  ])
39
39
  const NO_EXTENSION_LF = new Set(['CMakeLists.txt', 'Makefile', 'Justfile', 'Dockerfile', 'LICENSE'])
40
40
  // .editorconfig 里不是 UTF-8 的 charset:工作树编码由别的工具负责,本脚本不判。
@@ -42,465 +42,465 @@ const NON_UTF8_CHARSETS = new Set(['latin1', 'utf-16be', 'utf-16le'])
42
42
  const EOL_VALUES = new Set(['lf', 'crlf', 'cr'])
43
43
 
44
44
  function usage(message) {
45
- if (message) process.stderr.write(`错误:${message}\n`)
46
- process.stderr.write('用法:node checking-encoding.mjs [--root DIR] [--profile portable|msvc] [--json] [--quiet]\n')
47
- return EXIT.usage
45
+ if (message) process.stderr.write(`错误:${message}\n`)
46
+ process.stderr.write('用法:node checking-encoding.mjs [--root DIR] [--profile portable|msvc] [--json] [--quiet]\n')
47
+ return EXIT.usage
48
48
  }
49
49
 
50
50
  function parseArgs(argv) {
51
- const options = { root: undefined, profile: 'portable', json: false, quiet: false }
52
- for (let index = 0; index < argv.length; index += 1) {
53
- const arg = argv[index]
54
- if (arg === '--root') {
55
- options.root = argv[index + 1]
56
- index += 1
57
- } else if (arg === '--profile') {
58
- options.profile = argv[index + 1]
59
- index += 1
60
- } else if (arg === '--json') {
61
- options.json = true
62
- } else if (arg === '--quiet') {
63
- options.quiet = true
64
- } else if (arg === '--help' || arg === '-h') {
65
- options.help = true
66
- } else {
67
- throw new Error(`未知参数 ${arg}`)
51
+ const options = { root: undefined, profile: 'portable', json: false, quiet: false }
52
+ for (let index = 0; index < argv.length; index += 1) {
53
+ const arg = argv[index]
54
+ if (arg === '--root') {
55
+ options.root = argv[index + 1]
56
+ index += 1
57
+ } else if (arg === '--profile') {
58
+ options.profile = argv[index + 1]
59
+ index += 1
60
+ } else if (arg === '--json') {
61
+ options.json = true
62
+ } else if (arg === '--quiet') {
63
+ options.quiet = true
64
+ } else if (arg === '--help' || arg === '-h') {
65
+ options.help = true
66
+ } else {
67
+ throw new Error(`未知参数 ${arg}`)
68
+ }
69
+ }
70
+ if (options.profile !== 'portable' && options.profile !== 'msvc') {
71
+ throw new Error(`--profile 只能是 portable 或 msvc,收到 ${options.profile}`)
68
72
  }
69
- }
70
- if (options.profile !== 'portable' && options.profile !== 'msvc') {
71
- throw new Error(`--profile 只能是 portable 或 msvc,收到 ${options.profile}`)
72
- }
73
- return options
73
+ return options
74
74
  }
75
75
 
76
76
  function gitRoot(from) {
77
- try {
78
- return execFileSync('git', ['-C', from, 'rev-parse', '--show-toplevel'], {
79
- encoding: 'utf8',
80
- stdio: ['ignore', 'pipe', 'ignore'],
81
- }).trim()
82
- } catch {
83
- return undefined
84
- }
77
+ try {
78
+ return execFileSync('git', ['-C', from, 'rev-parse', '--show-toplevel'], {
79
+ encoding: 'utf8',
80
+ stdio: ['ignore', 'pipe', 'ignore'],
81
+ }).trim()
82
+ } catch {
83
+ return undefined
84
+ }
85
85
  }
86
86
 
87
87
  function listFiles(root) {
88
- const output = execFileSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
89
- encoding: 'utf8',
90
- maxBuffer: 64 * 1024 * 1024,
91
- })
92
- return output
93
- .split('\0')
94
- .filter(Boolean)
95
- .map((item) => path.join(root, item))
96
- .filter((file) => {
97
- try {
98
- return statSync(file).isFile()
99
- } catch {
100
- return false
101
- }
88
+ const output = execFileSync('git', ['-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], {
89
+ encoding: 'utf8',
90
+ maxBuffer: 64 * 1024 * 1024,
102
91
  })
92
+ return output
93
+ .split('\0')
94
+ .filter(Boolean)
95
+ .map((item) => path.join(root, item))
96
+ .filter((file) => {
97
+ try {
98
+ return statSync(file).isFile()
99
+ } catch {
100
+ return false
101
+ }
102
+ })
103
103
  }
104
104
 
105
105
  function startsWith(buffer, bytes) {
106
- return bytes.every((byte, index) => buffer[index] === byte)
106
+ return bytes.every((byte, index) => buffer[index] === byte)
107
107
  }
108
108
 
109
109
  function bomOf(buffer) {
110
- if (startsWith(buffer, UTF32_LE)) return 'UTF-32 LE'
111
- if (startsWith(buffer, UTF32_BE)) return 'UTF-32 BE'
112
- if (startsWith(buffer, UTF8_BOM)) return 'UTF-8'
113
- if (startsWith(buffer, UTF16_LE)) return 'UTF-16 LE'
114
- if (startsWith(buffer, UTF16_BE)) return 'UTF-16 BE'
115
- return undefined
110
+ if (startsWith(buffer, UTF32_LE)) return 'UTF-32 LE'
111
+ if (startsWith(buffer, UTF32_BE)) return 'UTF-32 BE'
112
+ if (startsWith(buffer, UTF8_BOM)) return 'UTF-8'
113
+ if (startsWith(buffer, UTF16_LE)) return 'UTF-16 LE'
114
+ if (startsWith(buffer, UTF16_BE)) return 'UTF-16 BE'
115
+ return undefined
116
116
  }
117
117
 
118
118
  function isBinary(buffer) {
119
- const limit = Math.min(buffer.length, 8192)
120
- for (let index = 0; index < limit; index += 1) {
121
- if (buffer[index] === 0) return true
122
- }
123
- return false
119
+ const limit = Math.min(buffer.length, 8192)
120
+ for (let index = 0; index < limit; index += 1) {
121
+ if (buffer[index] === 0) return true
122
+ }
123
+ return false
124
124
  }
125
125
 
126
126
  function readText(file) {
127
- try {
128
- return readFileSync(file, 'utf8')
129
- } catch {
130
- return undefined
131
- }
127
+ try {
128
+ return readFileSync(file, 'utf8')
129
+ } catch {
130
+ return undefined
131
+ }
132
132
  }
133
133
 
134
134
  function escapeRegExp(text) {
135
- return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
135
+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
136
136
  }
137
137
 
138
138
  // 把 .gitattributes / .editorconfig 的 glob 片段翻成正则源码。
139
139
  // * 与 ? 不跨目录,** 跨目录,[...] 是字符类,反斜杠转义下一个字符。
140
140
  function globSource(pattern) {
141
- let source = ''
142
- for (let index = 0; index < pattern.length; index += 1) {
143
- const char = pattern[index]
144
- if (char === '\\' && index + 1 < pattern.length) {
145
- index += 1
146
- source += escapeRegExp(pattern[index])
147
- } else if (char === '*') {
148
- if (pattern[index + 1] === '*') {
149
- index += 1
150
- if (pattern[index + 1] === '/') {
151
- index += 1
152
- source += '(?:.*/)?'
141
+ let source = ''
142
+ for (let index = 0; index < pattern.length; index += 1) {
143
+ const char = pattern[index]
144
+ if (char === '\\' && index + 1 < pattern.length) {
145
+ index += 1
146
+ source += escapeRegExp(pattern[index])
147
+ } else if (char === '*') {
148
+ if (pattern[index + 1] === '*') {
149
+ index += 1
150
+ if (pattern[index + 1] === '/') {
151
+ index += 1
152
+ source += '(?:.*/)?'
153
+ } else {
154
+ source += '.*'
155
+ }
156
+ } else {
157
+ source += '[^/]*'
158
+ }
159
+ } else if (char === '?') {
160
+ source += '[^/]'
161
+ } else if (char === '[') {
162
+ let close = index + 1
163
+ if (pattern[close] === '!' || pattern[close] === '^') close += 1
164
+ if (pattern[close] === ']') close += 1
165
+ while (close < pattern.length && pattern[close] !== ']') close += 1
166
+ if (close >= pattern.length) {
167
+ source += '\\['
168
+ } else {
169
+ let body = pattern.slice(index + 1, close)
170
+ if (body.startsWith('!')) body = `^${body.slice(1)}`
171
+ source += `[${body.replace(/\\/g, '\\\\')}]`
172
+ index = close
173
+ }
153
174
  } else {
154
- source += '.*'
175
+ source += escapeRegExp(char)
155
176
  }
156
- } else {
157
- source += '[^/]*'
158
- }
159
- } else if (char === '?') {
160
- source += '[^/]'
161
- } else if (char === '[') {
162
- let close = index + 1
163
- if (pattern[close] === '!' || pattern[close] === '^') close += 1
164
- if (pattern[close] === ']') close += 1
165
- while (close < pattern.length && pattern[close] !== ']') close += 1
166
- if (close >= pattern.length) {
167
- source += '\\['
168
- } else {
169
- let body = pattern.slice(index + 1, close)
170
- if (body.startsWith('!')) body = `^${body.slice(1)}`
171
- source += `[${body.replace(/\\/g, '\\\\')}]`
172
- index = close
173
- }
174
- } else {
175
- source += escapeRegExp(char)
176
177
  }
177
- }
178
- return source
178
+ return source
179
179
  }
180
180
 
181
181
  function splitBraces(body) {
182
- const parts = []
183
- let depth = 0
184
- let start = 0
185
- for (let index = 0; index < body.length; index += 1) {
186
- const char = body[index]
187
- if (char === '{') depth += 1
188
- else if (char === '}') depth -= 1
189
- else if (char === ',' && depth === 0) {
190
- parts.push(body.slice(start, index))
191
- start = index + 1
182
+ const parts = []
183
+ let depth = 0
184
+ let start = 0
185
+ for (let index = 0; index < body.length; index += 1) {
186
+ const char = body[index]
187
+ if (char === '{') depth += 1
188
+ else if (char === '}') depth -= 1
189
+ else if (char === ',' && depth === 0) {
190
+ parts.push(body.slice(start, index))
191
+ start = index + 1
192
+ }
192
193
  }
193
- }
194
- parts.push(body.slice(start))
195
- return parts
194
+ parts.push(body.slice(start))
195
+ return parts
196
196
  }
197
197
 
198
198
  // EditorConfig 的 {a,b} 写法;展开后每条再翻正则。
199
199
  function expandBraces(pattern) {
200
- const open = pattern.indexOf('{')
201
- if (open === -1) return [pattern]
202
- let depth = 0
203
- let close = -1
204
- for (let index = open; index < pattern.length; index += 1) {
205
- if (pattern[index] === '{') depth += 1
206
- else if (pattern[index] === '}') {
207
- depth -= 1
208
- if (depth === 0) {
209
- close = index
210
- break
211
- }
200
+ const open = pattern.indexOf('{')
201
+ if (open === -1) return [pattern]
202
+ let depth = 0
203
+ let close = -1
204
+ for (let index = open; index < pattern.length; index += 1) {
205
+ if (pattern[index] === '{') depth += 1
206
+ else if (pattern[index] === '}') {
207
+ depth -= 1
208
+ if (depth === 0) {
209
+ close = index
210
+ break
211
+ }
212
+ }
213
+ }
214
+ if (close === -1) return [pattern]
215
+ const before = pattern.slice(0, open)
216
+ const after = pattern.slice(close + 1)
217
+ const expanded = []
218
+ for (const part of splitBraces(pattern.slice(open + 1, close))) {
219
+ expanded.push(...expandBraces(before + part + after))
212
220
  }
213
- }
214
- if (close === -1) return [pattern]
215
- const before = pattern.slice(0, open)
216
- const after = pattern.slice(close + 1)
217
- const expanded = []
218
- for (const part of splitBraces(pattern.slice(open + 1, close))) {
219
- expanded.push(...expandBraces(before + part + after))
220
- }
221
- return expanded
221
+ return expanded
222
222
  }
223
223
 
224
224
  function compilePattern(pattern) {
225
- const anchored = pattern.includes('/')
226
- const body = pattern.startsWith('/') ? pattern.slice(1) : pattern
227
- return { anchored, regex: new RegExp(`^${globSource(body)}$`) }
225
+ const anchored = pattern.includes('/')
226
+ const body = pattern.startsWith('/') ? pattern.slice(1) : pattern
227
+ return { anchored, regex: new RegExp(`^${globSource(body)}$`) }
228
228
  }
229
229
 
230
230
  function compilePatterns(pattern) {
231
- return expandBraces(pattern).map(compilePattern)
231
+ return expandBraces(pattern).map(compilePattern)
232
232
  }
233
233
 
234
234
  function matchesAny(compiled, relativePath) {
235
- const name = path.posix.basename(relativePath)
236
- return compiled.some((item) => item.regex.test(item.anchored ? relativePath : name))
235
+ const name = path.posix.basename(relativePath)
236
+ return compiled.some((item) => item.regex.test(item.anchored ? relativePath : name))
237
237
  }
238
238
 
239
239
  function parseAttributes(text) {
240
- const rules = []
241
- for (const raw of text.split(/\r?\n/)) {
242
- const line = raw.trim()
243
- if (!line || line.startsWith('#') || line.startsWith('[attr]')) continue
244
- const [pattern, ...pairs] = line.split(/\s+/)
245
- if (!pattern || pattern.startsWith('!')) continue
246
- const attributes = new Map()
247
- for (const pair of pairs) {
248
- if (pair.startsWith('-')) {
249
- attributes.set(pair.slice(1).toLowerCase(), 'false')
250
- } else {
251
- const equals = pair.indexOf('=')
252
- if (equals === -1) {
253
- attributes.set(pair.toLowerCase(), 'true')
254
- } else {
255
- attributes.set(pair.slice(0, equals).toLowerCase(), pair.slice(equals + 1).toLowerCase())
240
+ const rules = []
241
+ for (const raw of text.split(/\r?\n/)) {
242
+ const line = raw.trim()
243
+ if (!line || line.startsWith('#') || line.startsWith('[attr]')) continue
244
+ const [pattern, ...pairs] = line.split(/\s+/)
245
+ if (!pattern || pattern.startsWith('!')) continue
246
+ const attributes = new Map()
247
+ for (const pair of pairs) {
248
+ if (pair.startsWith('-')) {
249
+ attributes.set(pair.slice(1).toLowerCase(), 'false')
250
+ } else {
251
+ const equals = pair.indexOf('=')
252
+ if (equals === -1) {
253
+ attributes.set(pair.toLowerCase(), 'true')
254
+ } else {
255
+ attributes.set(pair.slice(0, equals).toLowerCase(), pair.slice(equals + 1).toLowerCase())
256
+ }
257
+ }
256
258
  }
257
- }
259
+ if (attributes.has('binary')) attributes.set('text', 'false')
260
+ rules.push({ pattern, compiled: compilePatterns(pattern), attributes })
258
261
  }
259
- if (attributes.has('binary')) attributes.set('text', 'false')
260
- rules.push({ pattern, compiled: compilePatterns(pattern), attributes })
261
- }
262
- return rules
262
+ return rules
263
263
  }
264
264
 
265
265
  // 逐级读取 .gitattributes:根目录先应用,子目录的规则后覆盖。
266
266
  function attributesFor(root, relative, cache) {
267
- const directories = []
268
- let directory = path.posix.dirname(relative)
269
- while (true) {
270
- directories.push(directory === '.' ? '' : directory)
271
- if (directory === '.' || directory === '') break
272
- directory = path.posix.dirname(directory)
273
- }
274
- directories.reverse()
275
-
276
- const result = new Map()
277
- for (const prefix of directories) {
278
- const file = path.join(root, prefix, '.gitattributes')
279
- let rules = cache.get(file)
280
- if (rules === undefined) {
281
- const text = readText(file)
282
- rules = text === undefined ? [] : parseAttributes(text)
283
- cache.set(file, rules)
267
+ const directories = []
268
+ let directory = path.posix.dirname(relative)
269
+ while (true) {
270
+ directories.push(directory === '.' ? '' : directory)
271
+ if (directory === '.' || directory === '') break
272
+ directory = path.posix.dirname(directory)
284
273
  }
285
- const within = relative.slice(prefix ? prefix.length + 1 : 0)
286
- for (const rule of rules) {
287
- if (!matchesAny(rule.compiled, within)) continue
288
- for (const [name, value] of rule.attributes) result.set(name, value)
274
+ directories.reverse()
275
+
276
+ const result = new Map()
277
+ for (const prefix of directories) {
278
+ const file = path.join(root, prefix, '.gitattributes')
279
+ let rules = cache.get(file)
280
+ if (rules === undefined) {
281
+ const text = readText(file)
282
+ rules = text === undefined ? [] : parseAttributes(text)
283
+ cache.set(file, rules)
284
+ }
285
+ const within = relative.slice(prefix ? prefix.length + 1 : 0)
286
+ for (const rule of rules) {
287
+ if (!matchesAny(rule.compiled, within)) continue
288
+ for (const [name, value] of rule.attributes) result.set(name, value)
289
+ }
289
290
  }
290
- }
291
- return result
291
+ return result
292
292
  }
293
293
 
294
294
  function parseEditorConfig(text) {
295
- const sections = []
296
- let root = false
297
- let current
298
- for (const raw of text.split(/\r?\n/)) {
299
- const line = raw.trim()
300
- if (!line || line.startsWith('#') || line.startsWith(';')) continue
301
- if (line.startsWith('[') && line.endsWith(']')) {
302
- current = { compiled: compilePatterns(line.slice(1, -1)), properties: new Map() }
303
- sections.push(current)
304
- continue
305
- }
306
- const equals = line.indexOf('=')
307
- if (equals === -1) continue
308
- const key = line.slice(0, equals).trim().toLowerCase()
309
- const value = line.slice(equals + 1).trim().toLowerCase()
310
- if (!current) {
311
- if (key === 'root' && value === 'true') root = true
312
- continue
295
+ const sections = []
296
+ let root = false
297
+ let current
298
+ for (const raw of text.split(/\r?\n/)) {
299
+ const line = raw.trim()
300
+ if (!line || line.startsWith('#') || line.startsWith(';')) continue
301
+ if (line.startsWith('[') && line.endsWith(']')) {
302
+ current = { compiled: compilePatterns(line.slice(1, -1)), properties: new Map() }
303
+ sections.push(current)
304
+ continue
305
+ }
306
+ const equals = line.indexOf('=')
307
+ if (equals === -1) continue
308
+ const key = line.slice(0, equals).trim().toLowerCase()
309
+ const value = line.slice(equals + 1).trim().toLowerCase()
310
+ if (!current) {
311
+ if (key === 'root' && value === 'true') root = true
312
+ continue
313
+ }
314
+ current.properties.set(key, value)
313
315
  }
314
- current.properties.set(key, value)
315
- }
316
- return { root, sections }
316
+ return { root, sections }
317
317
  }
318
318
 
319
319
  // 从文件所在目录向上找 .editorconfig,遇到 root = true 停止;
320
320
  // 远的先应用,近的后覆盖,同一文件内后面的节覆盖前面的节。
321
321
  function editorConfigFor(root, relative, cache) {
322
- const chain = []
323
- let directory = path.posix.dirname(relative)
324
- while (true) {
325
- const prefix = directory === '.' ? '' : directory
326
- const file = path.join(root, prefix, '.editorconfig')
327
- let config = cache.get(file)
328
- if (config === undefined) {
329
- const text = readText(file)
330
- config = text === undefined ? null : parseEditorConfig(text)
331
- cache.set(file, config)
332
- }
333
- if (config) {
334
- chain.push({ prefix, config })
335
- if (config.root) break
322
+ const chain = []
323
+ let directory = path.posix.dirname(relative)
324
+ while (true) {
325
+ const prefix = directory === '.' ? '' : directory
326
+ const file = path.join(root, prefix, '.editorconfig')
327
+ let config = cache.get(file)
328
+ if (config === undefined) {
329
+ const text = readText(file)
330
+ config = text === undefined ? null : parseEditorConfig(text)
331
+ cache.set(file, config)
332
+ }
333
+ if (config) {
334
+ chain.push({ prefix, config })
335
+ if (config.root) break
336
+ }
337
+ if (directory === '.' || directory === '') break
338
+ directory = path.posix.dirname(directory)
336
339
  }
337
- if (directory === '.' || directory === '') break
338
- directory = path.posix.dirname(directory)
339
- }
340
- chain.reverse()
341
-
342
- const properties = new Map()
343
- for (const { prefix, config } of chain) {
344
- const within = relative.slice(prefix ? prefix.length + 1 : 0)
345
- for (const section of config.sections) {
346
- if (!matchesAny(section.compiled, within)) continue
347
- for (const [key, value] of section.properties) properties.set(key, value)
340
+ chain.reverse()
341
+
342
+ const properties = new Map()
343
+ for (const { prefix, config } of chain) {
344
+ const within = relative.slice(prefix ? prefix.length + 1 : 0)
345
+ for (const section of config.sections) {
346
+ if (!matchesAny(section.compiled, within)) continue
347
+ for (const [key, value] of section.properties) properties.set(key, value)
348
+ }
348
349
  }
349
- }
350
- return properties
350
+ return properties
351
351
  }
352
352
 
353
353
  function configuredLineEnding(editor, attributes) {
354
- const editorEol = editor.get('end_of_line')
355
- if (EOL_VALUES.has(editorEol)) return editorEol
356
- const attributeEol = attributes.get('eol')
357
- if (EOL_VALUES.has(attributeEol)) return attributeEol
358
- return undefined
354
+ const editorEol = editor.get('end_of_line')
355
+ if (EOL_VALUES.has(editorEol)) return editorEol
356
+ const attributeEol = attributes.get('eol')
357
+ if (EOL_VALUES.has(attributeEol)) return attributeEol
358
+ return undefined
359
359
  }
360
360
 
361
361
  function inspect(file, root, profile, caches) {
362
- const rel = path.relative(root, file).split(path.sep).join('/')
363
- const base = path.basename(file).toLowerCase()
364
- const extension = base.startsWith('.') ? base : path.extname(file).toLowerCase()
365
- const source = MSVC_SOURCE.has(extension)
366
- const alwaysLf = ALWAYS_LF.has(extension) || NO_EXTENSION_LF.has(path.basename(file))
367
- const issues = []
368
- const add = (kind, message) => issues.push({ path: rel, kind, message })
369
-
370
- const attributes = attributesFor(root, rel, caches.gitAttributes)
371
- const editor = editorConfigFor(root, rel, caches.editorConfig)
372
-
373
- let buffer
374
- try {
375
- buffer = readFileSync(file)
376
- } catch (error) {
377
- add('read', `无法读取(${error.message})`)
378
- return { rel, issues }
379
- }
362
+ const rel = path.relative(root, file).split(path.sep).join('/')
363
+ const base = path.basename(file).toLowerCase()
364
+ const extension = base.startsWith('.') ? base : path.extname(file).toLowerCase()
365
+ const source = MSVC_SOURCE.has(extension)
366
+ const alwaysLf = ALWAYS_LF.has(extension) || NO_EXTENSION_LF.has(path.basename(file))
367
+ const issues = []
368
+ const add = (kind, message) => issues.push({ path: rel, kind, message })
369
+
370
+ const attributes = attributesFor(root, rel, caches.gitAttributes)
371
+ const editor = editorConfigFor(root, rel, caches.editorConfig)
372
+
373
+ let buffer
374
+ try {
375
+ buffer = readFileSync(file)
376
+ } catch (error) {
377
+ add('read', `无法读取(${error.message})`)
378
+ return { rel, issues }
379
+ }
380
380
 
381
- if (attributes.get('binary') === 'true' || attributes.get('text') === 'false') {
382
- return { rel, issues }
383
- }
381
+ if (attributes.get('binary') === 'true' || attributes.get('text') === 'false') {
382
+ return { rel, issues }
383
+ }
384
384
 
385
- const charset = editor.get('charset') ?? 'utf-8'
386
- const workingTreeEncoding = attributes.get('working-tree-encoding')
387
- const transcoded = workingTreeEncoding !== undefined && !/^utf-?8$/i.test(workingTreeEncoding)
388
- if (transcoded || NON_UTF8_CHARSETS.has(charset)) {
389
- return { rel, issues }
390
- }
385
+ const charset = editor.get('charset') ?? 'utf-8'
386
+ const workingTreeEncoding = attributes.get('working-tree-encoding')
387
+ const transcoded = workingTreeEncoding !== undefined && !/^utf-?8$/i.test(workingTreeEncoding)
388
+ if (transcoded || NON_UTF8_CHARSETS.has(charset)) {
389
+ return { rel, issues }
390
+ }
391
391
 
392
- const bom = bomOf(buffer)
393
- const bomAllowed = charset === 'utf-8-bom' || (profile === 'msvc' && source)
394
- if (bom === 'UTF-8') {
395
- if (!bomAllowed) {
396
- add('bom', profile === 'msvc' && !source ? '只有 MSVC 编译的 C/C++ 源码可以带 BOM' : '不应带 BOM')
392
+ const bom = bomOf(buffer)
393
+ const bomAllowed = charset === 'utf-8-bom' || (profile === 'msvc' && source)
394
+ if (bom === 'UTF-8') {
395
+ if (!bomAllowed) {
396
+ add('bom', profile === 'msvc' && !source ? '只有 MSVC 编译的 C/C++ 源码可以带 BOM' : '不应带 BOM')
397
+ }
398
+ } else if (bom) {
399
+ add('bom', `发现 ${bom} BOM;只接受 UTF-8`)
397
400
  }
398
- } else if (bom) {
399
- add('bom', `发现 ${bom} BOM;只接受 UTF-8`)
400
- }
401
401
 
402
- if (bom && bom !== 'UTF-8') {
403
- return { rel, issues }
404
- }
405
- if (isBinary(buffer)) {
406
- return { rel, issues }
407
- }
402
+ if (bom && bom !== 'UTF-8') {
403
+ return { rel, issues }
404
+ }
405
+ if (isBinary(buffer)) {
406
+ return { rel, issues }
407
+ }
408
+
409
+ let text
410
+ try {
411
+ text = new TextDecoder('utf-8', { fatal: true }).decode(buffer)
412
+ } catch {
413
+ add('utf8', '不是合法 UTF-8')
414
+ return { rel, issues }
415
+ }
416
+
417
+ const body = text.startsWith('\uFEFF') ? text.slice(1) : text
418
+ if (body.includes('\uFEFF')) {
419
+ add('bom', '文件中间含 U+FEFF')
420
+ }
421
+
422
+ if (buffer.length > 0 && !body.endsWith('\n') && editor.get('insert_final_newline') !== 'false') {
423
+ add('newline', '缺少末尾换行')
424
+ }
425
+
426
+ const crlf = (body.match(/\r\n/g) ?? []).length
427
+ const lf = (body.match(/(?<!\r)\n/g) ?? []).length
428
+ const cr = (body.match(/\r(?!\n)/g) ?? []).length
429
+
430
+ const expected = configuredLineEnding(editor, attributes)
431
+ if (expected === 'crlf') {
432
+ if (crlf === 0 || lf > 0 || cr > 0) add('eol', '应为 CRLF')
433
+ } else if (expected === 'cr') {
434
+ if (cr === 0 || lf > 0 || crlf > 0) add('eol', '应为 CR')
435
+ } else if (expected === 'lf') {
436
+ if (crlf > 0 || cr > 0) add('eol', '应为 LF')
437
+ } else if (profile === 'msvc' && source && !alwaysLf) {
438
+ if ((crlf > 0 && lf > 0) || cr > 0) add('eol', '不要混用 CRLF 与 LF')
439
+ } else if (CRLF_REQUIRED.has(extension)) {
440
+ if (crlf === 0 || lf > 0 || cr > 0) add('eol', '应为 CRLF')
441
+ } else if (crlf > 0 || cr > 0) {
442
+ add('eol', '应为 LF')
443
+ }
408
444
 
409
- let text
410
- try {
411
- text = new TextDecoder('utf-8', { fatal: true }).decode(buffer)
412
- } catch {
413
- add('utf8', '不是合法 UTF-8')
414
445
  return { rel, issues }
415
- }
416
-
417
- const body = text.startsWith('\uFEFF') ? text.slice(1) : text
418
- if (body.includes('\uFEFF')) {
419
- add('bom', '文件中间含 U+FEFF')
420
- }
421
-
422
- if (buffer.length > 0 && !body.endsWith('\n') && editor.get('insert_final_newline') !== 'false') {
423
- add('newline', '缺少末尾换行')
424
- }
425
-
426
- const crlf = (body.match(/\r\n/g) ?? []).length
427
- const lf = (body.match(/(?<!\r)\n/g) ?? []).length
428
- const cr = (body.match(/\r(?!\n)/g) ?? []).length
429
-
430
- const expected = configuredLineEnding(editor, attributes)
431
- if (expected === 'crlf') {
432
- if (crlf === 0 || lf > 0 || cr > 0) add('eol', '应为 CRLF')
433
- } else if (expected === 'cr') {
434
- if (cr === 0 || lf > 0 || crlf > 0) add('eol', '应为 CR')
435
- } else if (expected === 'lf') {
436
- if (crlf > 0 || cr > 0) add('eol', '应为 LF')
437
- } else if (profile === 'msvc' && source && !alwaysLf) {
438
- if ((crlf > 0 && lf > 0) || cr > 0) add('eol', '不要混用 CRLF 与 LF')
439
- } else if (CRLF_REQUIRED.has(extension)) {
440
- if (crlf === 0 || lf > 0 || cr > 0) add('eol', '应为 CRLF')
441
- } else if (crlf > 0 || cr > 0) {
442
- add('eol', '应为 LF')
443
- }
444
-
445
- return { rel, issues }
446
446
  }
447
447
 
448
448
  export function checkEncoding(root, profile = 'portable') {
449
- const files = listFiles(root)
450
- const caches = { gitAttributes: new Map(), editorConfig: new Map() }
451
- const results = []
452
- for (const file of files) {
453
- results.push(inspect(file, root, profile, caches))
454
- }
455
- const issues = results.flatMap((result) => result.issues)
456
- const counts = { files: results.length, issues: issues.length, bom: 0, eol: 0, utf8: 0, newline: 0, read: 0 }
457
- for (const issue of issues) counts[issue.kind] = (counts[issue.kind] ?? 0) + 1
458
- return { root, profile, files: results.length, issues, counts }
449
+ const files = listFiles(root)
450
+ const caches = { gitAttributes: new Map(), editorConfig: new Map() }
451
+ const results = []
452
+ for (const file of files) {
453
+ results.push(inspect(file, root, profile, caches))
454
+ }
455
+ const issues = results.flatMap((result) => result.issues)
456
+ const counts = { files: results.length, issues: issues.length, bom: 0, eol: 0, utf8: 0, newline: 0, read: 0 }
457
+ for (const issue of issues) counts[issue.kind] = (counts[issue.kind] ?? 0) + 1
458
+ return { root, profile, files: results.length, issues, counts }
459
459
  }
460
460
 
461
461
  function main() {
462
- let options
463
- try {
464
- options = parseArgs(process.argv.slice(2))
465
- } catch (error) {
466
- return usage(error.message)
467
- }
468
- if (options.help) {
469
- process.stdout.write('检查 Git 工作树的 UTF-8/BOM、行尾与末尾换行;默认 portable。\n')
470
- return EXIT.ok
471
- }
472
-
473
- const base = options.root ? path.resolve(options.root) : process.cwd()
474
- if (!existsSync(base)) return usage(`根目录不存在:${base}`)
475
- const root = gitRoot(base)
476
- if (!root) return usage(`不是 Git 工作树:${base}`)
477
-
478
- let report
479
- try {
480
- report = checkEncoding(root, options.profile)
481
- } catch (error) {
482
- process.stderr.write(`错误:${error.message}\n`)
483
- return EXIT.usage
484
- }
485
-
486
- if (options.json) {
487
- process.stdout.write(`${JSON.stringify(report, null, 2)}\n`)
488
- } else if (!options.quiet || report.issues.length > 0) {
489
- if (report.issues.length === 0) {
490
- process.stdout.write(`编码检查:${report.files} 个文件,未发现问题(profile ${report.profile})。\n`)
491
- } else {
492
- process.stdout.write(`编码检查:${report.files} 个文件,发现 ${report.issues.length} 个问题(profile ${report.profile})。\n`)
493
- for (const issue of report.issues) {
494
- process.stdout.write(` ${issue.path}: [${issue.kind}] ${issue.message}\n`)
495
- }
496
- process.stdout.write(
497
- `汇总:BOM ${report.counts.bom},行尾 ${report.counts.eol},UTF-8 ${report.counts.utf8},末尾换行 ${report.counts.newline}\n`,
498
- )
462
+ let options
463
+ try {
464
+ options = parseArgs(process.argv.slice(2))
465
+ } catch (error) {
466
+ return usage(error.message)
467
+ }
468
+ if (options.help) {
469
+ process.stdout.write('检查 Git 工作树的 UTF-8/BOM、行尾与末尾换行;默认 portable。\n')
470
+ return EXIT.ok
471
+ }
472
+
473
+ const base = options.root ? path.resolve(options.root) : process.cwd()
474
+ if (!existsSync(base)) return usage(`根目录不存在:${base}`)
475
+ const root = gitRoot(base)
476
+ if (!root) return usage(`不是 Git 工作树:${base}`)
477
+
478
+ let report
479
+ try {
480
+ report = checkEncoding(root, options.profile)
481
+ } catch (error) {
482
+ process.stderr.write(`错误:${error.message}\n`)
483
+ return EXIT.usage
484
+ }
485
+
486
+ if (options.json) {
487
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`)
488
+ } else if (!options.quiet || report.issues.length > 0) {
489
+ if (report.issues.length === 0) {
490
+ process.stdout.write(`编码检查:${report.files} 个文件,未发现问题(profile ${report.profile})。\n`)
491
+ } else {
492
+ process.stdout.write(`编码检查:${report.files} 个文件,发现 ${report.issues.length} 个问题(profile ${report.profile})。\n`)
493
+ for (const issue of report.issues) {
494
+ process.stdout.write(` ${issue.path}: [${issue.kind}] ${issue.message}\n`)
495
+ }
496
+ process.stdout.write(
497
+ `汇总:BOM ${report.counts.bom},行尾 ${report.counts.eol},UTF-8 ${report.counts.utf8},末尾换行 ${report.counts.newline}\n`,
498
+ )
499
+ }
499
500
  }
500
- }
501
- return report.issues.length === 0 ? EXIT.ok : EXIT.issues
501
+ return report.issues.length === 0 ? EXIT.ok : EXIT.issues
502
502
  }
503
503
 
504
504
  if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
505
- process.exitCode = main()
505
+ process.exitCode = main()
506
506
  }