Skip to content

Commit

Permalink
Prettify debug output a bit, consistent context arg
Browse files Browse the repository at this point in the history
  • Loading branch information
webpro committed Oct 16, 2023
1 parent 8eed4bc commit 3638fb2
Show file tree
Hide file tree
Showing 7 changed files with 43 additions and 39 deletions.
7 changes: 4 additions & 3 deletions src/WorkspaceWorker.ts
Expand Up @@ -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() {
Expand Down Expand Up @@ -244,6 +244,7 @@ export class WorkspaceWorker {
}

private async findDependenciesByPlugins() {
const name = this.name;
const cwd = this.dir;
const ignore = this.getIgnorePatterns();

Expand All @@ -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) {
Expand Down Expand Up @@ -300,7 +301,7 @@ export class WorkspaceWorker {
});
}

debugLogArray(`Dependencies referenced in ${plugin.NAME}`, pluginDependencies);
debugLogArray([name, plugin.NAME], 'dependencies', pluginDependencies);
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/binaries/bash-parser.ts
Expand Up @@ -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 [];
}
};
39 changes: 17 additions & 22 deletions src/index.ts
Expand Up @@ -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 });
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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 });

Expand All @@ -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
Expand Down Expand Up @@ -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 });
}
}
Expand All @@ -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<string> = new Set();
const exportedSymbols: Exports = new Map();
Expand Down Expand Up @@ -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);
Expand Down
6 changes: 3 additions & 3 deletions src/typescript/SourceFileManager.ts
Expand Up @@ -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);
}

Expand All @@ -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);
}
}
Expand Down
24 changes: 16 additions & 8 deletions 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;
Expand All @@ -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) {
Expand All @@ -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<string>) => {
export const debugLogArray = (
context: string | [string, string],
message: string,
elements: string[] | Set<string>
) => {
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);
};
2 changes: 1 addition & 1 deletion src/util/glob.ts
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/util/require.ts
Expand Up @@ -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})`);
}
};

Expand Down

0 comments on commit 3638fb2

Please sign in to comment.