Skip to content

Commit 3638fb2

Browse files
committedOct 16, 2023
Prettify debug output a bit, consistent context arg
1 parent 8eed4bc commit 3638fb2

File tree

7 files changed

+43
-39
lines changed

7 files changed

+43
-39
lines changed
 

‎src/WorkspaceWorker.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ export class WorkspaceWorker {
130130

131131
const enabledPluginNames = this.enabledPlugins.map(name => plugins[name].NAME);
132132

133-
debugLogObject(`Enabled plugins (${this.name})`, enabledPluginNames);
133+
debugLogObject(this.name, `Enabled plugins (${this.name})`, enabledPluginNames);
134134
}
135135

136136
private async initReferencedDependencies() {
@@ -244,6 +244,7 @@ export class WorkspaceWorker {
244244
}
245245

246246
private async findDependenciesByPlugins() {
247+
const name = this.name;
247248
const cwd = this.dir;
248249
const ignore = this.getIgnorePatterns();
249250

@@ -264,7 +265,7 @@ export class WorkspaceWorker {
264265
get(this.manifest, 'PACKAGE_JSON_PATH' in plugin ? plugin.PACKAGE_JSON_PATH : pluginName)
265266
);
266267

267-
debugLogArray(`Found ${plugin.NAME} config file paths`, configFilePaths);
268+
debugLogArray([name, plugin.NAME], 'config file paths', configFilePaths);
268269

269270
// Bail out, no config files found for this plugin
270271
if (patterns.length > 0 && configFilePaths.length === 0) {
@@ -300,7 +301,7 @@ export class WorkspaceWorker {
300301
});
301302
}
302303

303-
debugLogArray(`Dependencies referenced in ${plugin.NAME}`, pluginDependencies);
304+
debugLogArray([name, plugin.NAME], 'dependencies', pluginDependencies);
304305
}
305306
}
306307
}

‎src/binaries/bash-parser.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ export const getBinariesFromScript = (
7777
const parsed = parse(script);
7878
return parsed?.commands ? getBinariesFromNodes(parsed.commands) : [];
7979
} catch (error) {
80-
debugLogObject('Bash parser error', error);
80+
debugLogObject('*', 'Bash parser error', error);
8181
return [];
8282
}
8383
};

‎src/index.ts

+17-22
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => {
4747
isIncludeEntryExports,
4848
} = unresolvedConfiguration;
4949

50-
debugLogObject('Unresolved configuration (from CLI arguments)', unresolvedConfiguration);
50+
debugLogObject('*', 'Unresolved configuration (from CLI arguments)', unresolvedConfiguration);
5151

5252
const chief = new ConfigurationChief({ cwd, isProduction });
5353
const deputy = new DependencyDeputy({ isStrict });
@@ -75,14 +75,9 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => {
7575
// TODO Organize better
7676
deputy.addIgnored(chief.config.ignoreBinaries, chief.config.ignoreDependencies);
7777

78-
debugLogObject(
79-
'Included workspaces',
80-
workspaces.map(w => w.pkgName)
81-
);
82-
debugLogObject(
83-
'Included workspace configs',
84-
workspaces.map(w => ({ name: w.name, pkgName: w.pkgName, config: w.config, ancestors: w.ancestors }))
85-
);
78+
const o = () => workspaces.map(w => ({ pkgName: w.pkgName, name: w.name, config: w.config, ancestors: w.ancestors }));
79+
debugLogObject('*', 'Included workspaces', () => workspaces.map(w => w.pkgName));
80+
debugLogObject('*', 'Included workspace configs', o);
8681

8782
const handleReferencedDependency = ({
8883
specifier,
@@ -133,7 +128,7 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => {
133128
const { name, dir, config, ancestors, pkgName, manifestPath, manifest } = workspace;
134129
const { paths, ignoreDependencies, ignoreBinaries } = config;
135130

136-
streamer.cast(`Analyzing workspace (${name})...`);
131+
streamer.cast(`Analyzing workspace ${name}...`);
137132

138133
deputy.addWorkspace({ name, dir, manifestPath, manifest, ignoreDependencies, ignoreBinaries });
139134

@@ -157,12 +152,12 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => {
157152
await worker.init();
158153

159154
principal.addEntryPaths(definitionPaths);
160-
debugLogArray(`Found definition paths (${name})`, definitionPaths);
155+
debugLogArray(name, `Definition paths`, definitionPaths);
161156

162157
const sharedGlobOptions = { cwd, workingDir: dir, gitignore, ignore: worker.getIgnorePatterns() };
163158

164159
const entryPathsFromManifest = await getEntryPathFromManifest(cwd, dir, manifest);
165-
debugLogArray(`Found entry paths in package.json (${name})`, entryPathsFromManifest);
160+
debugLogArray(name, 'Entry paths in package.json', entryPathsFromManifest);
166161
principal.addEntryPaths(entryPathsFromManifest);
167162

168163
// Get peerDependencies, installed binaries, entry files gathered through all plugins, and hand over
@@ -193,55 +188,55 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => {
193188
{
194189
const patterns = worker.getProductionEntryFilePatterns(negatedEntryPatterns);
195190
const workspaceEntryPaths = await _glob({ ...sharedGlobOptions, patterns });
196-
debugLogArray(`Found entry paths (${name})`, workspaceEntryPaths);
191+
debugLogArray(name, `Entry paths`, workspaceEntryPaths);
197192
principal.addEntryPaths(workspaceEntryPaths);
198193
}
199194

200195
{
201196
const pluginWorkspaceEntryPaths = await _glob({ ...sharedGlobOptions, patterns: productionEntryFilePatterns });
202-
debugLogArray(`Found production plugin entry paths (${name})`, pluginWorkspaceEntryPaths);
197+
debugLogArray(name, `Production plugin entry paths`, pluginWorkspaceEntryPaths);
203198
principal.addEntryPaths(pluginWorkspaceEntryPaths, { skipExportsAnalysis: true });
204199
}
205200

206201
{
207202
const patterns = worker.getProductionProjectFilePatterns(negatedEntryPatterns);
208203
const workspaceProjectPaths = await _glob({ ...sharedGlobOptions, patterns });
209-
debugLogArray(`Found project paths (${name})`, workspaceProjectPaths);
204+
debugLogArray(name, `Project paths`, workspaceProjectPaths);
210205
workspaceProjectPaths.forEach(projectPath => principal.addProjectPath(projectPath));
211206
}
212207
} else {
213208
{
214209
const patterns = worker.getEntryFilePatterns();
215210
const workspaceEntryPaths = await _glob({ ...sharedGlobOptions, patterns });
216-
debugLogArray(`Found entry paths (${name})`, workspaceEntryPaths);
211+
debugLogArray(name, `Entry paths`, workspaceEntryPaths);
217212
principal.addEntryPaths(workspaceEntryPaths);
218213
}
219214

220215
{
221216
const patterns = worker.getProjectFilePatterns([...productionEntryFilePatterns]);
222217
const workspaceProjectPaths = await _glob({ ...sharedGlobOptions, patterns });
223-
debugLogArray(`Found project paths (${name})`, workspaceProjectPaths);
218+
debugLogArray(name, `Project paths`, workspaceProjectPaths);
224219
workspaceProjectPaths.forEach(projectPath => principal.addProjectPath(projectPath));
225220
}
226221

227222
{
228223
const patterns = [...entryFilePatterns, ...productionEntryFilePatterns];
229224
const pluginWorkspaceEntryPaths = await _glob({ ...sharedGlobOptions, patterns });
230-
debugLogArray(`Found plugin entry paths (${name})`, pluginWorkspaceEntryPaths);
225+
debugLogArray(name, `Plugin entry paths`, pluginWorkspaceEntryPaths);
231226
principal.addEntryPaths(pluginWorkspaceEntryPaths, { skipExportsAnalysis: true });
232227
}
233228

234229
{
235230
const patterns = worker.getPluginProjectFilePatterns();
236231
const pluginWorkspaceProjectPaths = await _glob({ ...sharedGlobOptions, patterns });
237-
debugLogArray(`Found plugin project paths (${name})`, pluginWorkspaceProjectPaths);
232+
debugLogArray(name, `Plugin project paths`, pluginWorkspaceProjectPaths);
238233
pluginWorkspaceProjectPaths.forEach(projectPath => principal.addProjectPath(projectPath));
239234
}
240235

241236
{
242237
const patterns = compact(worker.getPluginConfigPatterns());
243238
const configurationEntryPaths = await _glob({ ...sharedGlobOptions, patterns });
244-
debugLogArray(`Found plugin configuration paths (${name})`, configurationEntryPaths);
239+
debugLogArray(name, `Plugin configuration paths`, configurationEntryPaths);
245240
principal.addEntryPaths(configurationEntryPaths, { skipExportsAnalysis: true });
246241
}
247242
}
@@ -254,7 +249,7 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => {
254249

255250
const principals = factory.getPrincipals();
256251

257-
debugLog(`Installed ${principals.length} principals for ${workspaces.length} workspaces`);
252+
debugLog('*', `Installed ${principals.length} principals for ${workspaces.length} workspaces`);
258253

259254
const analyzedFiles: Set<string> = new Set();
260255
const exportedSymbols: Exports = new Map();
@@ -342,7 +337,7 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => {
342337
const resolvedFiles = principal.getUsedResolvedFiles();
343338
const files = resolvedFiles.filter(filePath => !analyzedFiles.has(filePath));
344339

345-
debugLogArray(`Analyzing used resolved files [P${principals.indexOf(principal) + 1}/${++round}]`, files);
340+
debugLogArray('*', `Analyzing used resolved files [P${principals.indexOf(principal) + 1}/${++round}]`, files);
346341
files.forEach(filePath => {
347342
analyzeSourceFile(filePath);
348343
analyzedFiles.add(filePath);

‎src/typescript/SourceFileManager.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,13 @@ export class SourceFileManager {
2525
if (this.sourceFileCache.has(filePath)) return this.sourceFileCache.get(filePath);
2626
const contents = ts.sys.readFile(filePath);
2727
if (typeof contents !== 'string') {
28-
if (isInternal(filePath)) debugLog(`Unable to read ${filePath}`);
28+
if (isInternal(filePath)) debugLog('*', `Unable to read ${filePath}`);
2929
return this.createSourceFile(filePath, '');
3030
}
3131
const ext = extname(filePath);
3232
const compiler = this.syncCompilers?.get(ext);
3333
const compiled = compiler ? compiler(contents, filePath) : contents;
34-
if (compiler) debugLog(`Compiled ${filePath}`);
34+
if (compiler) debugLog('*', `Compiled ${filePath}`);
3535
return this.createSourceFile(filePath, compiled);
3636
}
3737

@@ -51,7 +51,7 @@ export class SourceFileManager {
5151
const compiler = this.asyncCompilers?.get(ext);
5252
if (compiler) {
5353
const compiled = await compiler(contents, filePath);
54-
debugLog(`Compiled ${filePath}`);
54+
debugLog('*', `Compiled ${filePath}`);
5555
this.createSourceFile(filePath, compiled);
5656
}
5757
}

‎src/util/debug.ts

+16-8
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import util from 'node:util';
2+
import chalk from 'chalk';
23
import parsedArgValues from './cli-arguments.js';
34

45
const { debug, 'debug-file-filter': debugFileFilter } = parsedArgValues;
@@ -8,6 +9,9 @@ const FILE_FILTER = debugFileFilter;
89

910
const inspectOptions = { maxArrayLength: null, depth: null, colors: true };
1011

12+
const ctx = (text: string | [string, string]) =>
13+
typeof text === 'string' ? chalk.yellow(`[${text}]`) : `${chalk.yellow(`[${text[0]}]`)} ${chalk.cyan(text[1])}`;
14+
1115
// Inspect arrays, otherwise Node [will, knip, ...n-100 more items]
1216
const logArray = (collection: string[]) => {
1317
if (FILE_FILTER) {
@@ -19,20 +23,24 @@ const logArray = (collection: string[]) => {
1923
}
2024
};
2125

22-
export const debugLog = (message: string) => {
26+
export const debugLog = (context: string, message: string) => {
2327
if (!IS_ENABLED) return;
24-
console.log(`[knip] ${message}`);
28+
console.log(`${ctx(context)} ${message}`);
2529
};
2630

27-
export const debugLogObject = (name: string, obj: unknown) => {
31+
export const debugLogObject = (context: string, name: string, obj: unknown | (() => unknown)) => {
2832
if (!IS_ENABLED) return;
29-
console.log(`[knip] ${name}`);
30-
console.log(util.inspect(obj, inspectOptions));
33+
console.log(`${ctx(context)} ${name}`);
34+
console.log(util.inspect(typeof obj === 'function' ? obj() : obj, inspectOptions));
3135
};
3236

33-
export const debugLogArray = (name: string, sourceFiles: string[] | Set<string>) => {
37+
export const debugLogArray = (
38+
context: string | [string, string],
39+
message: string,
40+
elements: string[] | Set<string>
41+
) => {
3442
if (!IS_ENABLED) return;
35-
const collection = Array.from(sourceFiles);
36-
console.debug(`[knip] ${name} (${collection.length})`);
43+
const collection = Array.from(elements);
44+
console.debug(`${ctx(context)} ${message} (${collection.length})`);
3745
logArray(collection);
3846
};

‎src/util/glob.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ const glob = async ({ cwd, workingDir = cwd, patterns, ignore = [], gitignore =
4444

4545
const ignorePatterns = compact([...ignore, ...GLOBAL_IGNORE_PATTERNS]);
4646

47-
debugLogObject(`Globbing (${relativePath || ROOT_WORKSPACE_NAME})`, { cwd, globPatterns, ignorePatterns });
47+
debugLogObject(relativePath || ROOT_WORKSPACE_NAME, `Glob options`, { cwd, globPatterns, ignorePatterns });
4848

4949
return globby(globPatterns, {
5050
cwd,

‎src/util/require.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ const tryResolve = (specifier: string, from: string) => {
1515
try {
1616
return resolve(specifier);
1717
} catch {
18-
debugLog(`Unable to resolve ${specifier} (from ${from})`);
18+
debugLog('*', `Unable to resolve ${specifier} (from ${from})`);
1919
}
2020
};
2121

0 commit comments

Comments
 (0)
Please sign in to comment.