Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions messages/rules-command.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ We're continually improving Salesforce Code Analyzer. Tell us what you think! Gi

<%= config.bin %> <%= command.id %> --rule-selector eslint:Recommended

- List Flow Analyzer rules from an authenticated org (required for that engine):

<%= config.bin %> <%= command.id %> --rule-selector flowAnalyzer --target-org my-org

- List all the rules for the "eslint" engine:

<%= config.bin %> <%= command.id %> --rule-selector eslint
Expand Down Expand Up @@ -92,6 +96,16 @@ Each targeted file must live within the workspace specified by the –-workspace

If you specify `--workspace` but not `--target`, then all the files within your workspace are targeted.

# flags.target-org.summary

Target org username or alias for remote analysis engines.

# flags.target-org.description

Specify the username or alias of a Salesforce org when listing rules from engines that require remote connectivity, such as Flow Analyzer. The org must be authenticated with the Salesforce CLI.

Flow Analyzer requires this flag (or `engines.flowAnalyzer.target_org` in your `code-analyzer.yml`). Other engines ignore it.

# flags.rule-selector.summary

Selection of rules, based on engine name, severity level, rule name, tag, or a combination of criteria separated by colons.
Expand Down
8 changes: 7 additions & 1 deletion messages/run-command.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ We're continually improving Salesforce Code Analyzer. Tell us what you think! Gi

<%= config.bin %> <%= command.id %> --rule-selector retire-js:Recommended --target ./other-source --target ./force-app/**/*.cls

- Analyze only specific flows with the "flowAnalyzer" engine; target one flow by path, plus every flow whose file name starts with "Account_" in any folder (quote globs so your shell doesn't expand them). Only the targeted flows are sent to your org:

<%= config.bin %> <%= command.id %> --rule-selector flowAnalyzer --target-org my-org --target ./force-app/main/default/flows/My_Flow.flow-meta.xml --target "./force-app/**/Account_*.flow-meta.xml"

- Specify a custom configuration file and output the results to the "results.csv" file in CSV format; the commands fails if it finds a violation that exceeds the moderate severity level (3):

<%= config.bin %> <%= command.id %> --config-file ./code-analyzer2.yml --output-file results.csv --severity-threshold 3
Expand Down Expand Up @@ -92,7 +96,9 @@ Target org username or alias for remote analysis engines.

# flags.target-org.description

Specify the username or alias of a Salesforce org when using engines that require remote connectivity, such as ApexGuru. The org must be authenticated with the Salesforce CLI.
Specify the username or alias of a Salesforce org when using engines that require remote connectivity, such as ApexGuru or Flow Analyzer. The org must be authenticated with the Salesforce CLI.

Flow Analyzer requires this flag (or `engines.flowAnalyzer.target_org` in your `code-analyzer.yml`).

# flags.rule-selector.summary

Expand Down
31 changes: 31 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"@salesforce/code-analyzer-engine-api": "0.42.0",
"@salesforce/code-analyzer-eslint-engine": "0.47.0",
"@salesforce/code-analyzer-flow-engine": "0.41.0",
"@salesforce/code-analyzer-flow-analyzer-engine": "file:../code-analyzer-core/packages/code-analyzer-flow-analyzer-engine",
"@salesforce/code-analyzer-pmd-engine": "0.46.0",
"@salesforce/code-analyzer-regex-engine": "0.40.0",
"@salesforce/code-analyzer-retirejs-engine": "0.39.0",
Expand Down
9 changes: 8 additions & 1 deletion src/commands/code-analyzer/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ export default class RulesCommand extends SfCommand<void> implements Displayable
multiple: true,
delimiter: ','
}),
'target-org': Flags.string({
summary: getMessage(BundleName.RulesCommand, 'flags.target-org.summary'),
description: getMessage(BundleName.RulesCommand, 'flags.target-org.description'),
// eslint-disable-next-line sf-plugin/dash-o
char: 'o'
}),
'rule-selector': Flags.string({
summary: getMessage(BundleName.RulesCommand, 'flags.rule-selector.summary'),
description: getMessage(BundleName.RulesCommand, 'flags.rule-selector.description'),
Expand Down Expand Up @@ -75,7 +81,8 @@ export default class RulesCommand extends SfCommand<void> implements Displayable
'output-file': outputFiles,
'rule-selector': parsedFlags['rule-selector'].flatMap(s => s.replace(/\s+/g, ' ').trim().split(' ')),
'workspace': parsedFlags['workspace'],
'target': parsedFlags['target']
'target': parsedFlags['target'],
'target-org': parsedFlags['target-org']
};

await action.execute(rulesInput);
Expand Down
29 changes: 24 additions & 5 deletions src/lib/actions/RulesAction.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {SfError} from '@salesforce/core';
import {CodeAnalyzer, CodeAnalyzerConfig, Rule, RuleSelection} from '@salesforce/code-analyzer-core';
import {CodeAnalyzerConfigFactory} from '../factories/CodeAnalyzerConfigFactory.js';
import {EnginePluginsFactory} from '../factories/EnginePluginsFactory.js';
Expand Down Expand Up @@ -29,6 +30,7 @@ export type RulesInput = {
'output-file'?: string[];
workspace?: string[];
target?: string[];
'target-org'?: string;
view?: string;
}

Expand All @@ -40,7 +42,10 @@ export class RulesAction {
}

public async execute(input: RulesInput): Promise<void> {
const config: CodeAnalyzerConfig = this.dependencies.configFactory.create(input['config-file']);
const cliOverrides = input['target-org'] !== undefined || input['rule-selector']?.length
? {targetOrg: input['target-org'], ruleSelectors: input['rule-selector']?.length ? input['rule-selector'] : undefined}
: undefined;
const config: CodeAnalyzerConfig = this.dependencies.configFactory.create(input['config-file'], cliOverrides);
const logWriter: LogFileWriter = await LogFileWriter.fromConfig(config);
this.dependencies.actionSummaryViewer.viewPreExecutionSummary(logWriter.getLogDestination());
// We always add a Logger Listener to the appropriate listeners list, because we should Always Be Logging.
Expand All @@ -51,15 +56,23 @@ export class RulesAction {
this.dependencies.logEventListeners.forEach(listener => listener.listen(core));
const telemetryListener: TelemetryEventListener = new TelemetryEventListener(this.dependencies.telemetryEmitter);
telemetryListener.listen(core);
const enginePlugins = this.dependencies.pluginsFactory.create();
// Flow Analyzer is opt-in: only load if user selected it
const hasFlowAnalyzerSelector = input['rule-selector']?.some(sel =>
sel.toLowerCase().split(/[^a-z0-9_-]+/).includes('flow-analyzer')
) ?? false;
const enginePlugins = this.dependencies.pluginsFactory.create(hasFlowAnalyzerSelector);
const addEnginePromises: Promise<void>[] = [
...enginePlugins.map(enginePlugin => core.addEnginePlugin(enginePlugin))
...enginePlugins.map(enginePlugin =>
core.addEnginePlugin(enginePlugin).catch(err => {
throw this.formatEngineError(err);
})
)
];
await Promise.all(addEnginePromises);
const workspace: string[]|undefined = input.workspace || (input.target ? ['.'] : undefined);
const selectOptions = workspace
? {workspace: await createWorkspace(core, workspace, input.target)}
: undefined;
? {workspace: await createWorkspace(core, workspace, input.target), targetOrg: input['target-org']}
: {targetOrg: input['target-org']};
// EngineProgressListeners should start listening right before we call Core's `.selectRules()` method, since
// that's when progress events can start being emitted.
this.dependencies.progressListeners.forEach(listener => listener.listen(core));
Expand Down Expand Up @@ -100,4 +113,10 @@ export class RulesAction {
});
}
}

private formatEngineError(error: unknown): SfError {
const err = error as Error;
const message = err.message || String(error);
return new SfError(`[error] ${message}`, 'EngineInstantiationError', []);
}
}
23 changes: 19 additions & 4 deletions src/lib/actions/RunAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,11 @@ export class RunAction {
}

public async execute(input: RunInput): Promise<void> {
const cliOverrides = (input['no-suppressions'] !== undefined || input['target-org'] !== undefined)
const cliOverrides = (input['no-suppressions'] !== undefined || input['target-org'] !== undefined || input['rule-selector']?.length)
? {
noSuppressions: input['no-suppressions'],
targetOrg: input['target-org']
targetOrg: input['target-org'],
ruleSelectors: input['rule-selector']?.length ? input['rule-selector'] : undefined
}
: undefined;
const config: CodeAnalyzerConfig = this.dependencies.configFactory.create(
Expand All @@ -74,9 +75,17 @@ export class RunAction {
this.dependencies.logEventListeners.forEach(listener => listener.listen(core));
const telemetryListener: TelemetryEventListener = new TelemetryEventListener(this.dependencies.telemetryEmitter);
telemetryListener.listen(core);
const enginePlugins = this.dependencies.pluginsFactory.create();
// Flow Analyzer is opt-in: only load if user selected it
const hasFlowAnalyzerSelector = input['rule-selector']?.some(sel =>
sel.toLowerCase().split(/[^a-z0-9_-]+/).includes('flow-analyzer')
) ?? false;
const enginePlugins = this.dependencies.pluginsFactory.create(hasFlowAnalyzerSelector);
const addEnginePromises: Promise<void>[] = [
...enginePlugins.map(enginePlugin => core.addEnginePlugin(enginePlugin))
...enginePlugins.map(enginePlugin =>
core.addEnginePlugin(enginePlugin).catch(err => {
throw this.formatEngineError(err);
})
)
];
await Promise.all(addEnginePromises);
const workspace: Workspace = await createWorkspace(core, input.workspace, input.target);
Expand Down Expand Up @@ -132,6 +141,12 @@ export class RunAction {
});
}
}

private formatEngineError(error: unknown): SfError {
const err = error as Error;
const message = err.message || String(error);
return new SfError(`[error] ${message}`, 'EngineInstantiationError', []);
}
}

function throwErrorIfSevThresholdExceeded(threshold: SeverityLevel, results: RunResults): void {
Expand Down
35 changes: 25 additions & 10 deletions src/lib/factories/CodeAnalyzerConfigFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import * as yaml from 'js-yaml';
export type CliOverrides = {
noSuppressions?: boolean;
targetOrg?: string;
// The user's --rule-selector values. Used to keep the opt-in Flow Analyzer engine inactive unless it was asked for.
ruleSelectors?: string[];
// Future CLI flag overrides can be added here
}

Expand Down Expand Up @@ -92,24 +94,41 @@ export class CodeAnalyzerConfigFactoryImpl implements CodeAnalyzerConfigFactory
};
}

// Apply target-org override to apexguru engine config
// Apply target-org override to engines that require an explicit org
if (cliOverrides.targetOrg) {
const enginesSection = mergedConfig.engines as Record<string, Record<string, unknown>> | undefined;
const targetOrgEngines: Record<string, Record<string, unknown>> = this.createTargetOrgEngineOverrides(cliOverrides);
mergedConfig = {
...mergedConfig,
engines: {
...(enginesSection || {}),
apexguru: {
...(enginesSection?.apexguru || {}),
target_org: cliOverrides.targetOrg
}
...Object.fromEntries(Object.entries(targetOrgEngines).map(([engineName, overrides]) =>
[engineName, {...(enginesSection?.[engineName] || {}), ...overrides}]))
}
};
}

return rawYaml ? CodeAnalyzerConfig.fromObject(mergedConfig) : CodeAnalyzerConfig.fromFile(configFilePath);
}

private createTargetOrgEngineOverrides(cliOverrides: CliOverrides): Record<string, Record<string, unknown>> {
const engines: Record<string, Record<string, unknown>> = {
apexguru: {target_org: cliOverrides.targetOrg}
};
// Flow Analyzer is opt-in. Giving it a target org activates it, and an activated engine contacts the org when
// Core gathers rules, so only do this when the user selected Flow Analyzer.
if (CodeAnalyzerConfigFactoryImpl.selectsFlowAnalyzer(cliOverrides.ruleSelectors)) {
engines['flow-analyzer'] = {target_org: cliOverrides.targetOrg};
}
return engines;
}

private static selectsFlowAnalyzer(ruleSelectors: string[] = []): boolean {
return ruleSelectors
.flatMap(selector => selector.toLowerCase().split(/[^a-z0-9_-]+/))
.some(token => token === 'flow-analyzer');
}

private createConfigFromCliOverrides(cliOverrides: CliOverrides): CodeAnalyzerConfig {
// Build config from CLI overrides
const configObject: Record<string, unknown> = {};
Expand All @@ -119,11 +138,7 @@ export class CodeAnalyzerConfigFactoryImpl implements CodeAnalyzerConfigFactory
}

if (cliOverrides?.targetOrg) {
configObject.engines = {
apexguru: {
target_org: cliOverrides.targetOrg
}
};
configObject.engines = this.createTargetOrgEngineOverrides(cliOverrides);
}

// If we have overrides, create config from them; otherwise use defaults
Expand Down
15 changes: 12 additions & 3 deletions src/lib/factories/EnginePluginsFactory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ import * as FlowEngineModule from '@salesforce/code-analyzer-flow-engine';
import * as SfgeEngineModule from '@salesforce/code-analyzer-sfge-engine';
import * as ApexGuruEngineModule from '@salesforce/code-analyzer-apexguru-engine';
import * as UIBundleEngineModule from '@salesforce/code-analyzer-uibundle-engine';
import * as FlowAnalyzerEngineModule from '@salesforce/code-analyzer-flow-analyzer-engine';

export interface EnginePluginsFactory {
create(): EnginePlugin[];
create(includeFlowAnalyzer?: boolean): EnginePlugin[];
}

export class EnginePluginsFactoryImpl implements EnginePluginsFactory {
public create(): EnginePlugin[] {
return [
public create(includeFlowAnalyzer: boolean = false): EnginePlugin[] {
const engines: EnginePlugin[] = [
ESLintEngineModule.createEnginePlugin(),
PmdCpdEnginesModule.createEnginePlugin(),
RetireJSEngineModule.createEnginePlugin(),
Expand All @@ -24,5 +25,13 @@ export class EnginePluginsFactoryImpl implements EnginePluginsFactory {
ApexGuruEngineModule.createEnginePlugin(),
UIBundleEngineModule.createEnginePlugin()
];

// Flow Analyzer is opt-in: only load if explicitly requested
if (includeFlowAnalyzer) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-member-access
engines.push(FlowAnalyzerEngineModule.createEnginePlugin() as EnginePlugin);
}

return engines;
}
}
16 changes: 16 additions & 0 deletions test/commands/code-analyzer/rules.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,22 @@ describe('`code-analyzer rules` unit tests', () => {
});
});

describe('--target-org', () => {
it('Can be supplied with a value', async () => {
const inputValue = 'test-org';
await runRulesCommand(['--target-org', inputValue]);
expect(executeSpy).toHaveBeenCalled();
expect(receivedActionInput).toHaveProperty('target-org', inputValue);
});

it('Can be referenced by its shortname, -o', async () => {
const inputValue = 'my-org';
await runRulesCommand(['-o', inputValue]);
expect(executeSpy).toHaveBeenCalled();
expect(receivedActionInput).toHaveProperty('target-org', inputValue);
});
});

describe.each([
{flag: '--workspace', shortflag: '-w', property: 'workspace'},
{flag: '--target', shortflag: '-t', property: 'target'},
Expand Down
Loading