-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathprocessComparisonFile.ts
More file actions
228 lines (205 loc) · 6.62 KB
/
processComparisonFile.ts
File metadata and controls
228 lines (205 loc) · 6.62 KB
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import fs from 'fs';
import { parseEnvFile } from './parseEnvFile.js';
import { filterIgnoredKeys } from '../core/filterIgnoredKeys.js';
import { compareWithEnvFiles } from '../core/scan/compareScan.js';
import { findDuplicateKeys } from '../core/duplicates.js';
import { applyFixes } from '../core/fixEnv.js';
import { toUpperSnakeCase } from '../core/helpers/toUpperSnakeCase.js';
import { resolveFromCwd } from '../core/helpers/resolveFromCwd.js';
import { detectEnvExpirations } from './detectEnvExpirations.js';
import { detectInconsistentNaming } from '../core/detectInconsistentNaming.js';
import type {
ScanUsageOptions,
ScanResult,
DuplicateResult,
UppercaseWarning,
Duplicate,
ComparisonFile,
ExpireWarning,
InconsistentNamingWarning,
FixContext,
} from '../config/types.js';
/**
* Result of processing comparison file
*/
export interface ProcessComparisonResult {
scanResult: ScanResult;
envVariables: Record<string, string | undefined>;
comparedAgainst: string;
duplicatesFound: boolean;
dupsEnv: Duplicate[];
dupsEx: Duplicate[];
fix: FixContext;
exampleFull?: Record<string, string> | undefined;
uppercaseWarnings?: UppercaseWarning[];
expireWarnings?: ExpireWarning[];
inconsistentNamingWarnings?: InconsistentNamingWarning[];
error?: { message: string; shouldExit: boolean };
}
/**
* Process comparison file: parse env, check duplicates, check missing keys, apply fixes
* @param scanResult - Current scan result
* @param compareFile - File to compare against
* @param opts - Scan options
* @returns Processed comparison result
*/
export function processComparisonFile(
scanResult: ScanResult,
compareFile: ComparisonFile,
opts: ScanUsageOptions,
): ProcessComparisonResult {
let envVariables: Record<string, string | undefined> = {};
let comparedAgainst = '';
let duplicatesFound = false;
let dupsEnv: Duplicate[] = [];
let dupsEx: Duplicate[] = [];
let exampleFull: Record<string, string> | undefined = undefined;
let uppercaseWarnings: UppercaseWarning[] = [];
let expireWarnings: ExpireWarning[] = [];
let inconsistentNamingWarnings: InconsistentNamingWarning[] = [];
const fix: FixContext = {
fixApplied: false,
removedDuplicates: [],
addedEnv: [],
gitignoreUpdated: false,
};
try {
// Load .env.example (if exists)
if (opts.examplePath) {
const examplePath = resolveFromCwd(opts.cwd, opts.examplePath);
if (fs.existsSync(examplePath)) {
exampleFull = parseEnvFile(examplePath);
}
}
// Parse and filter env file
const envFull = parseEnvFile(compareFile.path);
const envKeys = filterIgnoredKeys(
Object.keys(envFull),
opts.ignore,
opts.ignoreRegex,
);
envVariables = Object.fromEntries(envKeys.map((k) => [k, envFull[k]]));
scanResult = compareWithEnvFiles(
scanResult,
envVariables,
opts.ignore,
opts.ignoreRegex,
);
comparedAgainst = compareFile.name;
// Detect uppercase keys
if (opts.uppercaseKeys) {
for (const key of envKeys) {
if (!/^[A-Z0-9_]+$/.test(key)) {
uppercaseWarnings.push({ key, suggestion: toUpperSnakeCase(key) });
}
}
}
// Find duplicates
if (!opts.allowDuplicates) {
const duplicateResults = checkDuplicates(compareFile, opts);
dupsEnv = duplicateResults.dupsEnv;
dupsEx = duplicateResults.dupsEx;
duplicatesFound = dupsEnv.length > 0 || dupsEx.length > 0;
}
if (opts.expireWarnings) {
expireWarnings = detectEnvExpirations(compareFile.path);
}
// Check for inconsistent naming across env + example keys
if (opts.inconsistentNamingWarnings) {
const envKeysList = Object.keys(envFull);
const exampleKeysList = exampleFull ? Object.keys(exampleFull) : [];
// Combine all keys for naming analysis
const allKeys = [...envKeysList, ...exampleKeysList];
inconsistentNamingWarnings = detectInconsistentNaming(allKeys);
}
// Apply fixes (both duplicates + missing keys + gitignore)
if (opts.fix) {
const { changed, result } = applyFixes({
envPath: compareFile.path,
missingKeys: scanResult.missing,
duplicateKeys: dupsEnv.map((d) => d.key),
ensureGitignore: true,
});
if (changed) {
// Update state based on what was actually fixed
fix.fixApplied = true;
fix.removedDuplicates = result.removedDuplicates;
fix.addedEnv = result.addedEnv;
fix.gitignoreUpdated = result.gitignoreUpdated;
// clear the issues that were fixed
scanResult.missing = [];
dupsEnv = [];
dupsEx = [];
duplicatesFound = false;
}
}
// Keep duplicates for output if not fixed
if (duplicatesFound && (!opts.fix || !fix.fixApplied)) {
if (!scanResult.duplicates) scanResult.duplicates = {};
if (dupsEnv.length > 0) scanResult.duplicates.env = dupsEnv;
if (dupsEx.length > 0) scanResult.duplicates.example = dupsEx;
}
} catch (error) {
const errorMessage = `Could not read ${compareFile.name}: ${compareFile.path} - ${error}`;
return {
scanResult,
envVariables,
comparedAgainst,
duplicatesFound,
dupsEnv,
dupsEx,
fix,
exampleFull,
uppercaseWarnings,
expireWarnings,
inconsistentNamingWarnings,
error: {
message: errorMessage,
shouldExit: opts.isCiMode ?? false,
},
};
}
return {
scanResult,
envVariables,
comparedAgainst,
duplicatesFound,
dupsEnv,
dupsEx,
fix,
exampleFull,
uppercaseWarnings,
expireWarnings,
inconsistentNamingWarnings,
};
}
/**
* Check for duplicate keys in env and example files
* @param compareFile - The file to compare against
* @param opts - Scan options
* @returns Object containing duplicate keys in env and example files
*/
function checkDuplicates(
compareFile: ComparisonFile,
opts: ScanUsageOptions,
): DuplicateResult {
const isIgnored = (key: string) =>
!opts.ignore.includes(key) && !opts.ignoreRegex.some((rx) => rx.test(key));
// Duplicates in main env file
const dupsEnv = findDuplicateKeys(compareFile.path).filter(({ key }) =>
isIgnored(key),
);
// Duplicates in example file
let dupsEx: Duplicate[] = [];
if (opts.examplePath) {
const examplePath = resolveFromCwd(opts.cwd, opts.examplePath);
const exampleIsDifferentFile =
fs.existsSync(examplePath) && examplePath !== compareFile.path;
if (exampleIsDifferentFile) {
dupsEx = findDuplicateKeys(examplePath).filter(({ key }) =>
isIgnored(key),
);
}
}
return { dupsEnv, dupsEx } satisfies DuplicateResult;
}