-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
188 lines (166 loc) · 5.4 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import * as fs from 'fs'
import { LockfileDictionariesConfig, defaultConfig } from './config.js'
import { extractWordsFromFile } from './extractors.js'
import { detectLockfileType } from './lockfileTypes.js'
/**
* Debug logger that only logs when debug is enabled
*/
export function debugLog(
config: LockfileDictionariesConfig,
...args: unknown[]
): void {
if (config.debug) {
console.log(...args)
}
}
/**
* Generate a dictionary from lockfiles
* @param config Configuration options
* @returns Array of words extracted from lockfiles
*/
export async function generateDictionary(
config: LockfileDictionariesConfig = {}
): Promise<string[]> {
const mergedConfig = { ...defaultConfig, ...config }
debugLog(
mergedConfig,
'🔍 generateDictionary called with config:',
JSON.stringify(config, null, 2)
)
debugLog(
mergedConfig,
'🔍 Merged config:',
JSON.stringify(mergedConfig, null, 2)
)
if (!mergedConfig.enabled) {
debugLog(
mergedConfig,
'❌ Dictionary generation disabled, returning empty array'
)
return []
}
const lockfilePaths: string[] = []
// Add explicitly specified lockfiles
if (mergedConfig.lockfiles && mergedConfig.lockfiles.length > 0) {
debugLog(
mergedConfig,
'📋 Using explicitly specified lockfiles:',
mergedConfig.lockfiles
)
// Check that all specified lockfiles exist
const missingFiles: string[] = []
for (const lockfile of mergedConfig.lockfiles) {
if (fs.existsSync(lockfile)) {
lockfilePaths.push(lockfile)
debugLog(mergedConfig, `✅ Found specified lockfile: ${lockfile}`)
} else {
missingFiles.push(lockfile)
debugLog(mergedConfig, `❌ Specified lockfile not found: ${lockfile}`)
}
}
// Throw error if any specified lockfiles were not found
if (missingFiles.length > 0) {
throw new Error(
`Specified lockfile(s) not found: ${missingFiles.join(', ')}`
)
}
}
// Auto-detect lockfiles if enabled
if (mergedConfig.autoDetect && mergedConfig.autoDetectPatterns) {
debugLog(
mergedConfig,
'🔎 Auto-detecting lockfiles with patterns:',
mergedConfig.autoDetectPatterns
)
// In a real implementation, we would use glob to find files matching the patterns
// For now, we'll just check if the files exist in the current directory
for (const pattern of mergedConfig.autoDetectPatterns) {
const filename = pattern.replace(/^\*\*\//, '')
debugLog(mergedConfig, `🔍 Checking if ${filename} exists...`)
if (fs.existsSync(filename)) {
debugLog(mergedConfig, `✅ Found lockfile: ${filename}`)
lockfilePaths.push(filename)
} else {
debugLog(mergedConfig, `❌ Lockfile not found: ${filename}`)
}
}
}
debugLog(
mergedConfig,
'📋 Final list of lockfiles to process:',
lockfilePaths
)
// Extract words from all lockfiles
const allWords = new Set<string>()
const wordsBySource: Record<string, string[]> = {}
for (const lockfilePath of lockfilePaths) {
try {
debugLog(mergedConfig, `🔍 Processing lockfile: ${lockfilePath}`)
const fileType = detectLockfileType(lockfilePath)
if (fileType) {
debugLog(
mergedConfig,
`✅ Detected file type: ${fileType} for ${lockfilePath}`
)
const words = await extractWordsFromFile(
lockfilePath,
fileType,
mergedConfig.debug
)
debugLog(
mergedConfig,
`📝 Extracted ${words.length} words from ${lockfilePath}`
)
words.forEach((word) => allWords.add(word))
wordsBySource[lockfilePath] = words
} else {
debugLog(
mergedConfig,
`❌ Could not detect file type for ${lockfilePath}`
)
}
} catch (error) {
debugLog(mergedConfig, `❌ Error processing ${lockfilePath}:`, error)
}
}
const result = Array.from(allWords).sort()
debugLog(mergedConfig, `✅ Final dictionary contains ${result.length} words`)
// Save the dictionary with source comments
if (result.length > 0) {
saveDictionary(wordsBySource, mergedConfig)
}
return result
}
/**
* Save a dictionary to a file
* @param wordsBySource Words grouped by source file
* @param config Configuration options
*/
export function saveDictionary(
wordsBySource: Record<string, string[]>,
config: LockfileDictionariesConfig = {}
): string {
const mergedConfig = { ...defaultConfig, ...config }
const dictionaryPath =
mergedConfig.dictionaryPath || '.cspell/lockfile-words.txt'
// Ensure the directory exists
const dirPath = dictionaryPath.substring(0, dictionaryPath.lastIndexOf('/'))
if (dirPath && !fs.existsSync(dirPath)) {
debugLog(mergedConfig, `📁 Creating directory: ${dirPath}`)
fs.mkdirSync(dirPath, { recursive: true })
}
// Create the dictionary content with comments
let content = '# CSpell Lockfile Words\n\n'
// Add words by source
for (const [source, sourceWords] of Object.entries(wordsBySource)) {
if (sourceWords.length > 0) {
content += `# Words from ${source} (${sourceWords.length} words)\n`
content += '# ' + '-'.repeat(40) + '\n'
content += sourceWords.sort().join('\n') + '\n\n'
}
}
// Write the file
fs.writeFileSync(dictionaryPath, content)
debugLog(mergedConfig, `📝 Dictionary saved to ${dictionaryPath}`)
return dictionaryPath
}