diff --git a/src/WorkspaceWorker.ts b/src/WorkspaceWorker.ts index 7c70eea97..f13b83f91 100644 --- a/src/WorkspaceWorker.ts +++ b/src/WorkspaceWorker.ts @@ -130,7 +130,7 @@ export class WorkspaceWorker { const enabledPluginNames = this.enabledPlugins.map(name => plugins[name].NAME); - debugLogObject(`Enabled plugins (${this.name})`, enabledPluginNames); + debugLogObject(this.name, `Enabled plugins (${this.name})`, enabledPluginNames); } private async initReferencedDependencies() { @@ -244,6 +244,7 @@ export class WorkspaceWorker { } private async findDependenciesByPlugins() { + const name = this.name; const cwd = this.dir; const ignore = this.getIgnorePatterns(); @@ -264,7 +265,7 @@ export class WorkspaceWorker { get(this.manifest, 'PACKAGE_JSON_PATH' in plugin ? plugin.PACKAGE_JSON_PATH : pluginName) ); - debugLogArray(`Found ${plugin.NAME} config file paths`, configFilePaths); + debugLogArray([name, plugin.NAME], 'config file paths', configFilePaths); // Bail out, no config files found for this plugin if (patterns.length > 0 && configFilePaths.length === 0) { @@ -300,7 +301,7 @@ export class WorkspaceWorker { }); } - debugLogArray(`Dependencies referenced in ${plugin.NAME}`, pluginDependencies); + debugLogArray([name, plugin.NAME], 'dependencies', pluginDependencies); } } } diff --git a/src/binaries/bash-parser.ts b/src/binaries/bash-parser.ts index 55c420292..9bedcad3b 100644 --- a/src/binaries/bash-parser.ts +++ b/src/binaries/bash-parser.ts @@ -77,7 +77,7 @@ export const getBinariesFromScript = ( const parsed = parse(script); return parsed?.commands ? getBinariesFromNodes(parsed.commands) : []; } catch (error) { - debugLogObject('Bash parser error', error); + debugLogObject('*', 'Bash parser error', error); return []; } }; diff --git a/src/index.ts b/src/index.ts index 33c4b1c6a..bef08731f 100644 --- a/src/index.ts +++ b/src/index.ts @@ -47,7 +47,7 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => { isIncludeEntryExports, } = unresolvedConfiguration; - debugLogObject('Unresolved configuration (from CLI arguments)', unresolvedConfiguration); + debugLogObject('*', 'Unresolved configuration (from CLI arguments)', unresolvedConfiguration); const chief = new ConfigurationChief({ cwd, isProduction }); const deputy = new DependencyDeputy({ isStrict }); @@ -75,14 +75,9 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => { // TODO Organize better deputy.addIgnored(chief.config.ignoreBinaries, chief.config.ignoreDependencies); - debugLogObject( - 'Included workspaces', - workspaces.map(w => w.pkgName) - ); - debugLogObject( - 'Included workspace configs', - workspaces.map(w => ({ name: w.name, pkgName: w.pkgName, config: w.config, ancestors: w.ancestors })) - ); + const o = () => workspaces.map(w => ({ pkgName: w.pkgName, name: w.name, config: w.config, ancestors: w.ancestors })); + debugLogObject('*', 'Included workspaces', () => workspaces.map(w => w.pkgName)); + debugLogObject('*', 'Included workspace configs', o); const handleReferencedDependency = ({ specifier, @@ -133,7 +128,7 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => { const { name, dir, config, ancestors, pkgName, manifestPath, manifest } = workspace; const { paths, ignoreDependencies, ignoreBinaries } = config; - streamer.cast(`Analyzing workspace (${name})...`); + streamer.cast(`Analyzing workspace ${name}...`); deputy.addWorkspace({ name, dir, manifestPath, manifest, ignoreDependencies, ignoreBinaries }); @@ -157,12 +152,12 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => { await worker.init(); principal.addEntryPaths(definitionPaths); - debugLogArray(`Found definition paths (${name})`, definitionPaths); + debugLogArray(name, `Definition paths`, definitionPaths); const sharedGlobOptions = { cwd, workingDir: dir, gitignore, ignore: worker.getIgnorePatterns() }; const entryPathsFromManifest = await getEntryPathFromManifest(cwd, dir, manifest); - debugLogArray(`Found entry paths in package.json (${name})`, entryPathsFromManifest); + debugLogArray(name, 'Entry paths in package.json', entryPathsFromManifest); principal.addEntryPaths(entryPathsFromManifest); // Get peerDependencies, installed binaries, entry files gathered through all plugins, and hand over @@ -193,55 +188,55 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => { { const patterns = worker.getProductionEntryFilePatterns(negatedEntryPatterns); const workspaceEntryPaths = await _glob({ ...sharedGlobOptions, patterns }); - debugLogArray(`Found entry paths (${name})`, workspaceEntryPaths); + debugLogArray(name, `Entry paths`, workspaceEntryPaths); principal.addEntryPaths(workspaceEntryPaths); } { const pluginWorkspaceEntryPaths = await _glob({ ...sharedGlobOptions, patterns: productionEntryFilePatterns }); - debugLogArray(`Found production plugin entry paths (${name})`, pluginWorkspaceEntryPaths); + debugLogArray(name, `Production plugin entry paths`, pluginWorkspaceEntryPaths); principal.addEntryPaths(pluginWorkspaceEntryPaths, { skipExportsAnalysis: true }); } { const patterns = worker.getProductionProjectFilePatterns(negatedEntryPatterns); const workspaceProjectPaths = await _glob({ ...sharedGlobOptions, patterns }); - debugLogArray(`Found project paths (${name})`, workspaceProjectPaths); + debugLogArray(name, `Project paths`, workspaceProjectPaths); workspaceProjectPaths.forEach(projectPath => principal.addProjectPath(projectPath)); } } else { { const patterns = worker.getEntryFilePatterns(); const workspaceEntryPaths = await _glob({ ...sharedGlobOptions, patterns }); - debugLogArray(`Found entry paths (${name})`, workspaceEntryPaths); + debugLogArray(name, `Entry paths`, workspaceEntryPaths); principal.addEntryPaths(workspaceEntryPaths); } { const patterns = worker.getProjectFilePatterns([...productionEntryFilePatterns]); const workspaceProjectPaths = await _glob({ ...sharedGlobOptions, patterns }); - debugLogArray(`Found project paths (${name})`, workspaceProjectPaths); + debugLogArray(name, `Project paths`, workspaceProjectPaths); workspaceProjectPaths.forEach(projectPath => principal.addProjectPath(projectPath)); } { const patterns = [...entryFilePatterns, ...productionEntryFilePatterns]; const pluginWorkspaceEntryPaths = await _glob({ ...sharedGlobOptions, patterns }); - debugLogArray(`Found plugin entry paths (${name})`, pluginWorkspaceEntryPaths); + debugLogArray(name, `Plugin entry paths`, pluginWorkspaceEntryPaths); principal.addEntryPaths(pluginWorkspaceEntryPaths, { skipExportsAnalysis: true }); } { const patterns = worker.getPluginProjectFilePatterns(); const pluginWorkspaceProjectPaths = await _glob({ ...sharedGlobOptions, patterns }); - debugLogArray(`Found plugin project paths (${name})`, pluginWorkspaceProjectPaths); + debugLogArray(name, `Plugin project paths`, pluginWorkspaceProjectPaths); pluginWorkspaceProjectPaths.forEach(projectPath => principal.addProjectPath(projectPath)); } { const patterns = compact(worker.getPluginConfigPatterns()); const configurationEntryPaths = await _glob({ ...sharedGlobOptions, patterns }); - debugLogArray(`Found plugin configuration paths (${name})`, configurationEntryPaths); + debugLogArray(name, `Plugin configuration paths`, configurationEntryPaths); principal.addEntryPaths(configurationEntryPaths, { skipExportsAnalysis: true }); } } @@ -254,7 +249,7 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => { const principals = factory.getPrincipals(); - debugLog(`Installed ${principals.length} principals for ${workspaces.length} workspaces`); + debugLog('*', `Installed ${principals.length} principals for ${workspaces.length} workspaces`); const analyzedFiles: Set = new Set(); const exportedSymbols: Exports = new Map(); @@ -342,7 +337,7 @@ export const main = async (unresolvedConfiguration: CommandLineOptions) => { const resolvedFiles = principal.getUsedResolvedFiles(); const files = resolvedFiles.filter(filePath => !analyzedFiles.has(filePath)); - debugLogArray(`Analyzing used resolved files [P${principals.indexOf(principal) + 1}/${++round}]`, files); + debugLogArray('*', `Analyzing used resolved files [P${principals.indexOf(principal) + 1}/${++round}]`, files); files.forEach(filePath => { analyzeSourceFile(filePath); analyzedFiles.add(filePath); diff --git a/src/typescript/SourceFileManager.ts b/src/typescript/SourceFileManager.ts index 73b5b6036..0a269fdea 100644 --- a/src/typescript/SourceFileManager.ts +++ b/src/typescript/SourceFileManager.ts @@ -25,13 +25,13 @@ export class SourceFileManager { if (this.sourceFileCache.has(filePath)) return this.sourceFileCache.get(filePath); const contents = ts.sys.readFile(filePath); if (typeof contents !== 'string') { - if (isInternal(filePath)) debugLog(`Unable to read ${filePath}`); + if (isInternal(filePath)) debugLog('*', `Unable to read ${filePath}`); return this.createSourceFile(filePath, ''); } const ext = extname(filePath); const compiler = this.syncCompilers?.get(ext); const compiled = compiler ? compiler(contents, filePath) : contents; - if (compiler) debugLog(`Compiled ${filePath}`); + if (compiler) debugLog('*', `Compiled ${filePath}`); return this.createSourceFile(filePath, compiled); } @@ -51,7 +51,7 @@ export class SourceFileManager { const compiler = this.asyncCompilers?.get(ext); if (compiler) { const compiled = await compiler(contents, filePath); - debugLog(`Compiled ${filePath}`); + debugLog('*', `Compiled ${filePath}`); this.createSourceFile(filePath, compiled); } } diff --git a/src/util/debug.ts b/src/util/debug.ts index 2dba5a352..364702587 100644 --- a/src/util/debug.ts +++ b/src/util/debug.ts @@ -1,4 +1,5 @@ import util from 'node:util'; +import chalk from 'chalk'; import parsedArgValues from './cli-arguments.js'; const { debug, 'debug-file-filter': debugFileFilter } = parsedArgValues; @@ -8,6 +9,9 @@ const FILE_FILTER = debugFileFilter; const inspectOptions = { maxArrayLength: null, depth: null, colors: true }; +const ctx = (text: string | [string, string]) => + typeof text === 'string' ? chalk.yellow(`[${text}]`) : `${chalk.yellow(`[${text[0]}]`)} ${chalk.cyan(text[1])}`; + // Inspect arrays, otherwise Node [will, knip, ...n-100 more items] const logArray = (collection: string[]) => { if (FILE_FILTER) { @@ -19,20 +23,24 @@ const logArray = (collection: string[]) => { } }; -export const debugLog = (message: string) => { +export const debugLog = (context: string, message: string) => { if (!IS_ENABLED) return; - console.log(`[knip] ${message}`); + console.log(`${ctx(context)} ${message}`); }; -export const debugLogObject = (name: string, obj: unknown) => { +export const debugLogObject = (context: string, name: string, obj: unknown | (() => unknown)) => { if (!IS_ENABLED) return; - console.log(`[knip] ${name}`); - console.log(util.inspect(obj, inspectOptions)); + console.log(`${ctx(context)} ${name}`); + console.log(util.inspect(typeof obj === 'function' ? obj() : obj, inspectOptions)); }; -export const debugLogArray = (name: string, sourceFiles: string[] | Set) => { +export const debugLogArray = ( + context: string | [string, string], + message: string, + elements: string[] | Set +) => { if (!IS_ENABLED) return; - const collection = Array.from(sourceFiles); - console.debug(`[knip] ${name} (${collection.length})`); + const collection = Array.from(elements); + console.debug(`${ctx(context)} ${message} (${collection.length})`); logArray(collection); }; diff --git a/src/util/glob.ts b/src/util/glob.ts index 37b2d9419..22192d9c1 100644 --- a/src/util/glob.ts +++ b/src/util/glob.ts @@ -44,7 +44,7 @@ const glob = async ({ cwd, workingDir = cwd, patterns, ignore = [], gitignore = const ignorePatterns = compact([...ignore, ...GLOBAL_IGNORE_PATTERNS]); - debugLogObject(`Globbing (${relativePath || ROOT_WORKSPACE_NAME})`, { cwd, globPatterns, ignorePatterns }); + debugLogObject(relativePath || ROOT_WORKSPACE_NAME, `Glob options`, { cwd, globPatterns, ignorePatterns }); return globby(globPatterns, { cwd, diff --git a/src/util/require.ts b/src/util/require.ts index 2e76f62eb..393f6f48d 100644 --- a/src/util/require.ts +++ b/src/util/require.ts @@ -15,7 +15,7 @@ const tryResolve = (specifier: string, from: string) => { try { return resolve(specifier); } catch { - debugLog(`Unable to resolve ${specifier} (from ${from})`); + debugLog('*', `Unable to resolve ${specifier} (from ${from})`); } };