From 5118e512e5fed2b21b3981a84b81b77d1be0a508 Mon Sep 17 00:00:00 2001 From: Aaron Butler Date: Mon, 9 Nov 2026 09:26:19 -0500 Subject: [PATCH 1/4] CM-77192: add Project/Diff/File scan scope Add a scan scope selector (Project, Diff and File) to the Cycode tool window, ported from the VS Code extension (CM-73887). - Diff scans the changes between two revisions or a revision and the local directory (commit ranges use the merge base and full SHAs); IaC falls back to a full project scan; Diff needs a git repository and CLI 3.25.0 or later - File scans the file open in the editor - The scope is persisted per project, the revisions are session-only - Require Cycode CLI 3.25.0 (CM-72985) - Bump the foojay toolchain resolver to 1.0.0 for Gradle 9 Co-Authored-By: Claude Sonnet 5.5 --- CHANGELOG.md | 2 + README.md | 18 ++ settings.gradle.kts | 2 +- src/main/kotlin/com/cycode/plugin/Consts.kt | 3 +- .../kotlin/com/cycode/plugin/cli/DiffScan.kt | 65 ++++++ .../kotlin/com/cycode/plugin/cli/Helpers.kt | 13 ++ .../actions/RunAllAction.kt | 19 +- .../scanContentTab/ScanContentTab.kt | 181 +++++++++++++-- .../com/cycode/plugin/git/DiffRefsCache.kt | 12 + .../com/cycode/plugin/git/DiffScanPlanner.kt | 50 ++++ .../com/cycode/plugin/git/GitRepository.kt | 196 ++++++++++++++++ .../com/cycode/plugin/services/CliService.kt | 51 +++-- .../services/CycodeProjectStateService.kt | 24 ++ .../cycode/plugin/services/CycodeService.kt | 15 +- .../services/CycodeTemporaryStateService.kt | 26 +++ .../plugin/services/ScanScopeService.kt | 213 ++++++++++++++++++ .../com/cycode/plugin/services/Services.kt | 4 + .../messages/CycodeBundle.properties | 22 +- .../com/cycode/plugin/DiffScanPlannerTest.kt | 111 +++++++++ .../kotlin/com/cycode/plugin/DiffScanTest.kt | 86 +++++++ .../com/cycode/plugin/GitRepositoryTest.kt | 197 ++++++++++++++++ .../kotlin/com/cycode/plugin/GitTestBase.kt | 50 ++++ .../com/cycode/plugin/ScanScopeLogicTest.kt | 74 ++++++ 23 files changed, 1357 insertions(+), 77 deletions(-) create mode 100644 src/main/kotlin/com/cycode/plugin/cli/DiffScan.kt create mode 100644 src/main/kotlin/com/cycode/plugin/git/DiffRefsCache.kt create mode 100644 src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt create mode 100644 src/main/kotlin/com/cycode/plugin/git/GitRepository.kt create mode 100644 src/main/kotlin/com/cycode/plugin/services/CycodeProjectStateService.kt create mode 100644 src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt create mode 100644 src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt create mode 100644 src/test/kotlin/com/cycode/plugin/DiffScanTest.kt create mode 100644 src/test/kotlin/com/cycode/plugin/GitRepositoryTest.kt create mode 100644 src/test/kotlin/com/cycode/plugin/GitTestBase.kt create mode 100644 src/test/kotlin/com/cycode/plugin/ScanScopeLogicTest.kt diff --git a/CHANGELOG.md b/CHANGELOG.md index dbf07f6..4a1378a 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ ## [Unreleased] +- Add scan scope selector: Project, Diff (between two revisions or the local directory) and File +- Increase required CLI version to 3.25.0 - Update extension icon to the new Cycode brand logo ## [3.1.1] - 2026-08-30 diff --git a/README.md b/README.md index 5845316..3ec1889 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ The extension provides functionalities such as: * Company’s Custom Remediation Guidelines - If your company has set custom remediation guidelines via the Cycode portal, you'll see a field for "Company Guidelines" that contains those guidelines. * Running a new scan from your IDE even before committing the code. * Triggering a scan automatically whenever a file is saved. +* Choosing the scan scope: the whole project, only the changes between two revisions (Diff), or the open file. * Highlighting vulnerable code in the editor - syntax highlighting for Cycode-specific code and configuration files, making it easy for users to identify and work with these files in their projects. * Removing a detected secret or ignoring it by secret value, rule (type) or by path. @@ -82,6 +83,23 @@ To use the Cycode IntelliJ Platform Plugin, follow these steps: 4. Also applies for auto-save. 5. Wait for the scan to complete and to display a success message. +### Scan Scope + +In the Cycode tool window, choose what the scan buttons and **Scan all** run on: + +* **Project** - scans the entire project. +* **Diff** - scans only what changed. Pick two revisions in **From** and **To** (HEAD, branches, tags or recent + commits), or choose **Local directory** on one side to include your uncommitted changes. The default is + Local directory compared with HEAD. Two different revisions are required. + * Scanning only the changes is faster, but vulnerabilities that need the surrounding code may be less accurate. + * Infrastructure As Code scans do not support diffs and always scan the full project. + * The project must be inside a Git repository (otherwise Diff is disabled), and Cycode CLI 3.25.0 or later is + required (otherwise the Diff option is hidden). +* **File** - scans only the file open in the editor. Package vulnerability and Infrastructure As Code scans only run + for the file types they support. + +The scope is remembered for each project between sessions. The selected revisions are kept for the current session only. + ## Viewing Scan Results ### Handling Detected Secrets diff --git a/settings.gradle.kts b/settings.gradle.kts index 9060895..99b4c22 100755 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -1,5 +1,5 @@ rootProject.name = "Cycode plugin for IntelliJ Platform" plugins { - id("org.gradle.toolchains.foojay-resolver-convention") version("0.7.0") + id("org.gradle.toolchains.foojay-resolver-convention") version("1.0.0") } diff --git a/src/main/kotlin/com/cycode/plugin/Consts.kt b/src/main/kotlin/com/cycode/plugin/Consts.kt index 03efcaa..96903e1 100644 --- a/src/main/kotlin/com/cycode/plugin/Consts.kt +++ b/src/main/kotlin/com/cycode/plugin/Consts.kt @@ -20,7 +20,8 @@ class Consts { companion object { val PLUGIN_PATH = PathManager.getPluginsPath() + "/cycode-intellij-platform-plugin" val DEFAULT_CLI_PATH = getDefaultCliPath() - const val REQUIRED_CLI_VERSION = "3.21.0" + const val REQUIRED_CLI_VERSION = "3.25.0" + const val MIN_CLI_VERSION_FOR_DIFF_SCAN = "3.25.0" const val CYCODE_DOMAIN = "cycode.com" diff --git a/src/main/kotlin/com/cycode/plugin/cli/DiffScan.kt b/src/main/kotlin/com/cycode/plugin/cli/DiffScan.kt new file mode 100644 index 0000000..7a1d8c4 --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/cli/DiffScan.kt @@ -0,0 +1,65 @@ +package com.cycode.plugin.cli + +import com.cycode.plugin.Consts + +enum class ScanScope { + Project, Diff, File +} + +enum class DiffScanMode { + CommitRange, LocalDiff +} + +/** Describes what a single CLI scan invocation should scan. */ +sealed class ScanTarget { + data class Paths(val paths: List) : ScanTarget() + data class Diff(val mode: DiffScanMode, val ref: String, val path: String) : ScanTarget() +} + +fun ScanTarget.toCliArgs(): Array = when (this) { + is ScanTarget.Paths -> arrayOf("path", *paths.toTypedArray()) + is ScanTarget.Diff -> getDiffScanArgs(mode, ref, path) +} + +// IaC is not supported by the CLI's commit-history and pre-commit diff flavours +fun supportsDiffScan(scanType: CliScanType): Boolean = scanType != CliScanType.Iac + +fun getDiffScanArgs(mode: DiffScanMode, ref: String, path: String): Array { + assertSafeRefArg(ref) + + return when (mode) { + DiffScanMode.CommitRange -> arrayOf("commit-history", "--commit-range", ref, path) + DiffScanMode.LocalDiff -> arrayOf("pre-commit", "--include-unstaged", "--base-ref", ref, "--path", path) + } +} + +/** + * Refs are passed to git and the CLI as separate arguments (no shell), but a value like "--output=x" + * would still be parsed as an option. Reject those and anything containing control characters. + */ +fun assertSafeRefArg(ref: String) { + require(isSafeRefArg(ref)) { "Unsafe revision: must be non-empty, not start with '-' and have no control characters" } +} + +fun isSafeRefArg(ref: String): Boolean = ref.isNotEmpty() && !ref.startsWith("-") && ref.none { it.isISOControl() } + +/** Compares only the first three numeric segments; dev builds look like `0.0.1.dev498`. */ +fun isVersionAtLeast(version: String, minVersion: String): Boolean { + fun parse(value: String) = value.trim().removePrefix("v").split(".").take(3) + .map { segment -> segment.takeWhile { it.isDigit() }.toIntOrNull() ?: 0 } + .let { it + List(3 - it.size) { 0 } } + + val actual = parse(version) + val required = parse(minVersion) + for (i in 0 until 3) { + if (actual[i] != required[i]) { + return actual[i] > required[i] + } + } + + return true +} + +fun isDiffScanSupportedByCli(cliVersion: String?): Boolean { + return cliVersion != null && isVersionAtLeast(cliVersion, Consts.MIN_CLI_VERSION_FOR_DIFF_SCAN) +} diff --git a/src/main/kotlin/com/cycode/plugin/cli/Helpers.kt b/src/main/kotlin/com/cycode/plugin/cli/Helpers.kt index 498eafe..adea8c6 100644 --- a/src/main/kotlin/com/cycode/plugin/cli/Helpers.kt +++ b/src/main/kotlin/com/cycode/plugin/cli/Helpers.kt @@ -102,6 +102,19 @@ fun isSupportedLockFile(filename: String): Boolean { return false } +fun isFileSupportedByScanType(filePath: String, scanType: CliScanType): Boolean { + return when (scanType) { + CliScanType.Sca -> isSupportedPackageFile(filePath) + CliScanType.Iac -> isSupportedIacFile(filePath) + else -> true + } +} + +/** Splits [scanTypes] (keeping their order) into the ones that can scan the file and the ones that cannot. */ +fun partitionByFileSupport(filePath: String, scanTypes: List): Pair, List> { + return scanTypes.partition { isFileSupportedByScanType(filePath, it) } +} + fun getPackageFileForLockFile(filename: String): String { val lowercaseFilename = filename.lowercase() return SCA_CONFIGURATION_SCAN_LOCK_FILE_TO_PACKAGE_FILE.getOrDefault(lowercaseFilename, "package") diff --git a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/cycodeActionToolBar/actions/RunAllAction.kt b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/cycodeActionToolBar/actions/RunAllAction.kt index 8509bc4..0e098a5 100644 --- a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/cycodeActionToolBar/actions/RunAllAction.kt +++ b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/cycodeActionToolBar/actions/RunAllAction.kt @@ -1,9 +1,8 @@ package com.cycode.plugin.components.toolWindow.components.cycodeActionToolBar.actions import com.cycode.plugin.CycodeBundle -import com.cycode.plugin.cli.CliScanType -import com.cycode.plugin.services.cycode import com.cycode.plugin.services.pluginLocalState +import com.cycode.plugin.services.scanScope import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent @@ -26,21 +25,7 @@ class RunAllAction : // TODO(MarshalX): we should tracks all running scans and use pub-sub messaging to update UI // we can provide "stop" action only after that val project = e.project ?: return - val service = cycode(project) - val pluginLocalState = pluginLocalState(project) - - if (pluginLocalState.isSecretScanningEnabled) { - service.startScanForCurrentProject(CliScanType.Secret) - } - if (pluginLocalState.isScaScanningEnabled) { - service.startScanForCurrentProject(CliScanType.Sca) - } - if (pluginLocalState.isIacScanningEnabled) { - service.startScanForCurrentProject(CliScanType.Iac) - } - if (pluginLocalState.isSastScanningEnabled) { - service.startScanForCurrentProject(CliScanType.Sast) - } + scanScope(project).startAllScansForCurrentScope() } override fun update(e: AnActionEvent) { diff --git a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt index b3b0d1d..290b547 100644 --- a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt +++ b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt @@ -2,16 +2,32 @@ package com.cycode.plugin.components.toolWindow.components.scanContentTab import com.cycode.plugin.CycodeBundle import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.ScanScope import com.cycode.plugin.components.Component import com.cycode.plugin.components.common.createClickableLabel +import com.cycode.plugin.components.toolWindow.updateToolWindowState +import com.cycode.plugin.git.HEAD_REF +import com.cycode.plugin.git.LOCAL_DIRECTORY_REF +import com.cycode.plugin.git.RefOption import com.cycode.plugin.services.CycodeService import com.cycode.plugin.services.pluginLocalState +import com.cycode.plugin.services.scanScope +import com.intellij.icons.AllIcons +import com.intellij.openapi.ui.ComboBox +import com.intellij.ui.SimpleListCellRenderer +import com.intellij.ui.components.JBLabel +import com.intellij.ui.components.JBRadioButton import com.intellij.util.ui.JBUI +import java.awt.FlowLayout import java.awt.GridBagConstraints import java.awt.GridBagLayout +import javax.swing.Box +import javax.swing.ButtonGroup +import javax.swing.DefaultComboBoxModel import javax.swing.JButton import javax.swing.JComponent import javax.swing.JPanel +import javax.swing.SwingConstants class ScanContentTab : Component() { private val panel = JPanel(GridBagLayout()) @@ -21,6 +37,7 @@ class ScanContentTab : Component() { anchor = GridBagConstraints.NORTHWEST fill = GridBagConstraints.HORIZONTAL } + private var updatingCombos = false private fun addComponentToPanel(component: JComponent) { gbc.gridy++ @@ -32,34 +49,150 @@ class ScanContentTab : Component() { val pluginLocalState = pluginLocalState(service.project) addComponentToPanel(createClickableLabel(CycodeBundle.message("scanTabTitleLabel"))) - addComponentToPanel( - JButton(CycodeBundle.message("scanTabSecretsBtn")).apply { - isEnabled = pluginLocalState.isSecretScanningEnabled - addActionListener { service.startScanForCurrentProject(CliScanType.Secret) } - }, - ) - addComponentToPanel( - JButton(CycodeBundle.message("scanTabScaBtn")).apply { - isEnabled = pluginLocalState.isScaScanningEnabled - addActionListener { service.startScanForCurrentProject(CliScanType.Sca) } - }, - ) - addComponentToPanel( - JButton(CycodeBundle.message("scanTabIacBtn")).apply { - isEnabled = pluginLocalState.isIacScanningEnabled - addActionListener { service.startScanForCurrentProject(CliScanType.Iac) } - }, - ) - addComponentToPanel( - JButton(CycodeBundle.message("scanTabSastBtn")).apply { - isEnabled = pluginLocalState.isSastScanningEnabled - addActionListener { service.startScanForCurrentProject(CliScanType.Sast) } - }, - ) + addScopeControls(service) + addComponentToPanel(createScanButton(service, CliScanType.Secret, "scanTabSecretsBtn") { + pluginLocalState.isSecretScanningEnabled + }) + addComponentToPanel(createScanButton(service, CliScanType.Sca, "scanTabScaBtn") { + pluginLocalState.isScaScanningEnabled + }) + addComponentToPanel(createScanButton(service, CliScanType.Iac, "scanTabIacBtn") { + pluginLocalState.isIacScanningEnabled + }) + addComponentToPanel(createScanButton(service, CliScanType.Sast, "scanTabSastBtn") { + pluginLocalState.isSastScanningEnabled + }) addComponentToPanel(createClickableLabel(CycodeBundle.message("scanTabOnSaveTip"))) addComponentToPanel(createClickableLabel(CycodeBundle.message("howToUseLabel"))) return panel } + + private fun createScanButton( + service: CycodeService, + scanType: CliScanType, + key: String, + isModuleEnabled: () -> Boolean + ): JButton { + return JButton(CycodeBundle.message(key)).apply { + isEnabled = isModuleEnabled() + addActionListener { scanScope(service.project).startScanForCurrentScope(scanType) } + } + } + + private fun createNote(text: String, icon: javax.swing.Icon? = null): JBLabel { + return JBLabel("$text").apply { + setAllowAutoWrapping(true) + icon?.let { + this.icon = it + iconTextGap = JBUI.scale(6) + verticalTextPosition = SwingConstants.TOP + } + } + } + + private fun addScopeControls(service: CycodeService) { + val scopeService = scanScope(service.project) + val pluginLocalState = pluginLocalState(service.project) + val effectiveScope = scopeService.getEffectiveScanScope() + val isGitRepository = scopeService.isGitRepository() + val scopes = ScanScope.entries.filter { it != ScanScope.Diff || scopeService.isDiffScanSupported() } + + // Diff is disabled when this turns out not to be a git repository; the tab is rebuilt if that changes + scopeService.refreshGitRepositoryState() + + addComponentToPanel(createClickableLabel(CycodeBundle.message("scanScopeLabel"))) + + val group = ButtonGroup() + val radioPanel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0)) + scopes.forEach { scope -> + val radio = JBRadioButton(CycodeBundle.message("scanScope${scope.name}"), scope == effectiveScope).apply { + // Diff cannot work without a git repository + isEnabled = scope != ScanScope.Diff || isGitRepository != false + addActionListener { + if (scope != scopeService.getScanScope()) { + scopeService.setScanScope(scope) + updateToolWindowState(service.project) + } + } + } + group.add(radio) + radioPanel.add(radio) + radioPanel.add(Box.createHorizontalStrut(JBUI.scale(12))) + } + addComponentToPanel(radioPanel) + addComponentToPanel(createNote(CycodeBundle.message("scanScope${effectiveScope.name}Hint"))) + if (scopes.contains(ScanScope.Diff) && isGitRepository == false) { + addComponentToPanel(createNote(CycodeBundle.message("scanScopeDiffNoGitNote"), AllIcons.General.Warning)) + } + + if (effectiveScope != ScanScope.Diff) { + return + } + + val fromCombo = createRefCombo(service, true) + val toCombo = createRefCombo(service, false) + addComponentToPanel(JPanel(GridBagLayout()).apply { + val c = GridBagConstraints().apply { fill = GridBagConstraints.HORIZONTAL; gridy = 0 } + add(JBLabel(CycodeBundle.message("scanScopeDiffFromLabel")), c.apply { gridx = 0; weightx = 0.0 }) + add(fromCombo, c.apply { gridx = 1; weightx = 1.0; insets = JBUI.insets(0, 4, 0, 8) }) + add(JBLabel(CycodeBundle.message("scanScopeDiffToLabel")), c.apply { gridx = 2; weightx = 0.0; insets = JBUI.emptyInsets() }) + add(toCombo, c.apply { gridx = 3; weightx = 1.0; insets = JBUI.insetsLeft(4) }) + }) + addComponentToPanel(createNote(CycodeBundle.message("scanScopeDiffIacNote"), AllIcons.General.Warning)) + + // lists are reloaded in the background and the combos updated in place (never while a popup is open) + scopeService.refreshDiffRefs { + populateRefCombo(fromCombo, true, pluginLocalState.diffFromRef, pluginLocalState.diffRefs) + populateRefCombo(toCombo, false, pluginLocalState.diffToRef, pluginLocalState.diffRefs) + } + } + + private fun createRefCombo(service: CycodeService, isFrom: Boolean): ComboBox { + val pluginLocalState = pluginLocalState(service.project) + return ComboBox().apply { + // long labels are truncated instead of widening the tool window + setMinimumAndPreferredWidth(JBUI.scale(REF_COMBO_WIDTH)) + maximumRowCount = REF_COMBO_VISIBLE_ROWS + renderer = SimpleListCellRenderer.create("") { it.label } + populateRefCombo( + this, + isFrom, + if (isFrom) pluginLocalState.diffFromRef else pluginLocalState.diffToRef, + pluginLocalState.diffRefs + ) + addActionListener { + if (updatingCombos) return@addActionListener + val selected = selectedItem as? RefOption ?: return@addActionListener + if (isFrom) { + scanScope(service.project).setDiffRefs(selected.value, pluginLocalState.diffToRef) + } else { + scanScope(service.project).setDiffRefs(pluginLocalState.diffFromRef, selected.value) + } + } + } + } + + private fun populateRefCombo(combo: ComboBox, isFrom: Boolean, selectedValue: String, refs: List) { + // replacing the model closes an open popup + if (combo.isPopupVisible) return + + val items = mutableListOf(RefOption(LOCAL_DIRECTORY_REF, CycodeBundle.message("scanScopeDiffLocalDirectory"))) + items.addAll(refs.ifEmpty { listOf(RefOption(HEAD_REF, HEAD_REF)) }) + + updatingCombos = true + try { + combo.model = DefaultComboBoxModel(items.toTypedArray()) + combo.selectedItem = items.firstOrNull { it.value == selectedValue } + ?: items.first { it.value == if (isFrom) LOCAL_DIRECTORY_REF else HEAD_REF } + } finally { + updatingCombos = false + } + } + + companion object { + private const val REF_COMBO_WIDTH = 110 + private const val REF_COMBO_VISIBLE_ROWS = 12 + } } diff --git a/src/main/kotlin/com/cycode/plugin/git/DiffRefsCache.kt b/src/main/kotlin/com/cycode/plugin/git/DiffRefsCache.kt new file mode 100644 index 0000000..e0d6030 --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/git/DiffRefsCache.kt @@ -0,0 +1,12 @@ +package com.cycode.plugin.git + +/** + * The revision lists together with the git state they were built for. Kept as one immutable object so a list can + * never be paired with the fingerprint of a different state. + */ +data class DiffRefsCache(val fingerprint: String?, val refs: List) { + /** Reusable only when git state is known, unchanged since the lists were built, and there is something to show. */ + fun canReuse(currentFingerprint: String?): Boolean { + return currentFingerprint != null && currentFingerprint == fingerprint && refs.isNotEmpty() + } +} diff --git a/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt b/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt new file mode 100644 index 0000000..df2cbc7 --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt @@ -0,0 +1,50 @@ +package com.cycode.plugin.git + +import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.DiffScanMode +import com.cycode.plugin.cli.ScanTarget +import com.cycode.plugin.cli.isSafeRefArg +import com.cycode.plugin.cli.supportsDiffScan + +sealed class DiffScanPlan { + data class Run(val target: ScanTarget) : DiffScanPlan() + + /** The scan must not start; [messageKey] is the bundle key of the message to show. */ + data class Refused(val messageKey: String) : DiffScanPlan() +} + +/** + * Decides what a diff scan of [scanType] should run, without touching the IDE. Runs git, so call it on a + * background thread. + */ +fun planDiffScan(scanType: CliScanType, from: String, to: String, projectRoot: String, git: GitRepository): DiffScanPlan { + if (from == to) { + return DiffScanPlan.Refused("diffSameRevisionNotification") + } + + // IaC does not support diffs in the CLI: run it as a normal project scan + if (!supportsDiffScan(scanType)) { + return DiffScanPlan.Run(ScanTarget.Paths(listOf(projectRoot))) + } + + if (!git.isGitRepository()) { + return DiffScanPlan.Refused("diffNotGitRepositoryNotification") + } + + if (from == LOCAL_DIRECTORY_REF || to == LOCAL_DIRECTORY_REF) { + val ref = if (from == LOCAL_DIRECTORY_REF) to else from + if (!isSafeRefArg(ref)) { + return DiffScanPlan.Refused("diffUnknownRevisionNotification") + } + return DiffScanPlan.Run(ScanTarget.Diff(DiffScanMode.LocalDiff, ref, projectRoot)) + } + + return when (val result = git.getCommitRange(from, to)) { + is CommitRangeResult.Range -> DiffScanPlan.Run(ScanTarget.Diff(DiffScanMode.CommitRange, result.range, projectRoot)) + CommitRangeResult.SameCommit -> DiffScanPlan.Refused("diffSameCommitNotification") + CommitRangeResult.NoCommonHistory -> DiffScanPlan.Refused("diffNoCommonHistoryNotification") + CommitRangeResult.UnknownRevision -> DiffScanPlan.Refused("diffUnknownRevisionNotification") + CommitRangeResult.NotARepository -> DiffScanPlan.Refused("diffNotGitRepositoryNotification") + CommitRangeResult.GitFailure -> DiffScanPlan.Refused("diffGitFailureNotification") + } +} diff --git a/src/main/kotlin/com/cycode/plugin/git/GitRepository.kt b/src/main/kotlin/com/cycode/plugin/git/GitRepository.kt new file mode 100644 index 0000000..253809b --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/git/GitRepository.kt @@ -0,0 +1,196 @@ +package com.cycode.plugin.git + +import com.cycode.plugin.cli.isSafeRefArg +import com.intellij.execution.configurations.GeneralCommandLine +import com.intellij.execution.process.CapturingProcessHandler +import com.intellij.openapi.diagnostic.thisLogger +import java.io.File +import java.nio.charset.StandardCharsets + +const val LOCAL_DIRECTORY_REF = "\u0000local" +const val HEAD_REF = "HEAD" +const val LABEL_SEPARATOR = " │ " + +/** [value] is what gets passed to git/CLI; [label] is what the user sees. */ +data class RefOption(val value: String, val label: String) { + override fun toString() = label +} + +sealed class CommitRangeResult { + data class Range(val range: String) : CommitRangeResult() + object SameCommit : CommitRangeResult() + object NoCommonHistory : CommitRangeResult() + object UnknownRevision : CommitRangeResult() + object NotARepository : CommitRangeResult() + object GitFailure : CommitRangeResult() +} + +data class GitOutput(val exitCode: Int, val stdout: String, val stderr: String) + +/** + * Thin wrapper over the git executable. Always run on a background thread. + * Git is invoked with an argv list (never a shell string); exit codes keep their git semantics + * because the user-facing messages depend on them. + */ +class GitRepository(private val workDirectory: String) { + fun run(vararg args: String): GitOutput? { + return try { + val commandLine = GeneralCommandLine("git") + .withParameters(*args) + .withWorkDirectory(File(workDirectory)) + .withCharset(StandardCharsets.UTF_8) + val output = CapturingProcessHandler(commandLine).runProcess(GIT_TIMEOUT_MS) + if (output.isTimeout || output.isCancelled) { + thisLogger().warn("git ${args.joinToString(" ")} timed out or was cancelled") + return null + } + GitOutput(output.exitCode, output.stdout.trim(), output.stderr.trim()) + } catch (e: Exception) { + // git is missing or could not be started + thisLogger().warn("Failed to run git ${args.joinToString(" ")}", e) + null + } + } + + fun isGitAvailable(): Boolean { + val output = run("--version") + return output != null && output.exitCode == 0 + } + + /** + * Changes when the checked out branch changes or a commit is created on it. Null if git could not tell. + * Used to cache the revision lists, which are expensive to build. + */ + fun getHeadFingerprint(): String? { + val sha = run("rev-parse", "HEAD")?.takeIf { it.exitCode == 0 }?.stdout ?: return null + val branch = run("symbolic-ref", "-q", "HEAD")?.takeIf { it.exitCode == 0 }?.stdout ?: HEAD_REF + return "$branch@$sha" + } + + /** Only an explicit "not a git repository" answer returns false; other failures are left to later steps. */ + fun isGitRepository(): Boolean { + val output = run("rev-parse", "--is-inside-work-tree") ?: return true + if (output.exitCode == 0) { + return output.stdout == "true" + } + + return !output.stderr.contains("not a git repository", ignoreCase = true) + } + + private fun resolveCommit(rev: String): Pair { + val output = run("rev-parse", "--verify", "--quiet", "$rev^{commit}") + return when { + output == null -> null to CommitRangeResult.GitFailure + output.exitCode == 0 -> output.stdout to null + output.exitCode == 1 -> null to CommitRangeResult.UnknownRevision + output.stderr.contains("not a git repository", ignoreCase = true) -> + null to CommitRangeResult.NotARepository + + else -> null to CommitRangeResult.GitFailure + } + } + + /** + * Resolves a "what did [to] add relative to [from]" range as `..` of full SHAs. + * Plain `from..to` is empty when picked newest-first, and `from...to` would also scan commits + * that landed on the other branch since divergence. + */ + fun getCommitRange(from: String, to: String): CommitRangeResult { + if (!isSafeRefArg(from) || !isSafeRefArg(to)) { + return CommitRangeResult.UnknownRevision + } + + val (fromSha, fromError) = resolveCommit(from) + if (fromSha == null) return fromError!! + val (toSha, toError) = resolveCommit(to) + if (toSha == null) return toError!! + + if (fromSha == toSha) { + return CommitRangeResult.SameCommit + } + + val mergeBase = run("merge-base", fromSha, toSha) + ?: return CommitRangeResult.GitFailure + if (mergeBase.exitCode == 1) { + return CommitRangeResult.NoCommonHistory + } + if (mergeBase.exitCode != 0 || mergeBase.stdout.isEmpty()) { + return CommitRangeResult.GitFailure + } + + val base = mergeBase.stdout + // "to" is an ancestor of "from": the user picked newest-first + return if (base == toSha) { + CommitRangeResult.Range("$toSha..$fromSha") + } else { + CommitRangeResult.Range("$base..$toSha") + } + } + + /** + * HEAD first, then branches/tags, then recent commits, plus any [pinnedRefs] (the user's selection) + * that scrolled out of the lists but still resolve. The caps are deliberate for now. + */ + fun getAvailableRefs(pinnedRefs: List = emptyList()): List { + val options = mutableListOf() + val listedValues = mutableSetOf() + val listedShas = mutableSetOf() + + fun add(option: RefOption, sha: String? = null) { + if (listedValues.add(option.value)) { + options.add(option) + sha?.let { listedShas.add(it) } + } + } + + add(RefOption(HEAD_REF, HEAD_REF)) + + val branchOutput = run("rev-parse", "--abbrev-ref", "HEAD") + val currentBranch = branchOutput?.takeIf { it.exitCode == 0 && it.stdout != HEAD_REF }?.stdout + + val refs = run( + "for-each-ref", "--sort=-committerdate", "--count=$MAX_REFS", + "--format=%(refname:short)%09%(objectname)%09%(objectname:short)%09%(contents:subject)", + "refs/heads", "refs/tags", "refs/remotes" + ) + if (refs != null && refs.exitCode == 0) { + for (line in refs.stdout.lines().filter { it.isNotBlank() }) { + val parts = line.split("\t", limit = 4) + if (parts.size < 3 || parts[0].endsWith("/HEAD") || !isSafeRefArg(parts[0])) continue + add(RefOption(parts[0], buildLabel(parts[0], parts[2], parts.getOrElse(3) { "" })), parts[1]) + } + } + + val log = run("log", "-n", "$MAX_COMMITS", "--format=%H%x09%h%x09%s") + if (log != null && log.exitCode == 0) { + for (line in log.stdout.lines().filter { it.isNotBlank() }) { + val parts = line.split("\t", limit = 3) + // a commit that is also a branch/tag tip is listed once, under the ref name + if (parts.size < 2 || parts[0] in listedShas) continue + // every commit of `git log` is an ancestor of HEAD, so labelling it with the current branch is accurate + add(RefOption(parts[0], buildLabel(currentBranch, parts[1], parts.getOrElse(2) { "" }))) + } + } + + for (pinned in pinnedRefs) { + if (pinned == LOCAL_DIRECTORY_REF || pinned in listedValues || !isSafeRefArg(pinned)) continue + val (sha, _) = resolveCommit(pinned) + if (sha == null) continue + val subject = run("log", "-n", "1", "--format=%h%x09%s", sha)?.stdout?.split("\t", limit = 2) + add(RefOption(pinned, buildLabel(pinned, subject?.getOrNull(0) ?: sha.take(7), subject?.getOrNull(1) ?: ""))) + } + + return options + } + + companion object { + const val MAX_REFS = 20 + const val MAX_COMMITS = 20 + private const val GIT_TIMEOUT_MS = 30_000 + + fun buildLabel(refName: String?, shortHash: String, subject: String): String { + return listOfNotNull(refName?.takeIf { it.isNotEmpty() }, shortHash, subject.takeIf { it.isNotEmpty() }) + .joinToString(LABEL_SEPARATOR) + } + } +} diff --git a/src/main/kotlin/com/cycode/plugin/services/CliService.kt b/src/main/kotlin/com/cycode/plugin/services/CliService.kt index 7660b0a..54008cb 100644 --- a/src/main/kotlin/com/cycode/plugin/services/CliService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/CliService.kt @@ -179,8 +179,8 @@ class CliService(private val project: Project) { return options.toTypedArray() } - private inline fun scanPaths( - paths: List, + private inline fun runScan( + target: ScanTarget, scanType: CliScanType, noinline cancelledCallback: TaskCancelledCallback = null ): CliResult? { @@ -191,26 +191,35 @@ class CliService(private val project: Project) { "-t", scanTypeString, *getCliScanOptions(scanType), - "path", - *getPathsAsArguments(paths), + *target.toCliArgs(), cancelledCallback = cancelledCallback ) return processResult(result) } - private fun getPathsAsArguments(paths: List): Array { - return paths.toTypedArray() - } - - fun scanPathsSecrets( - paths: List, + /** + * One runner for every kind of scan (paths, commit range, local diff). + * Do not add one method per mode. + */ + fun scan( + scanType: CliScanType, + target: ScanTarget, onDemand: Boolean = true, cancelledCallback: TaskCancelledCallback = null ) { - val results = scanPaths(paths, CliScanType.Secret, cancelledCallback) + when (scanType) { + CliScanType.Secret -> scanSecrets(target, onDemand, cancelledCallback) + CliScanType.Sca -> scanSca(target, onDemand, cancelledCallback) + CliScanType.Iac -> scanIac(target, onDemand, cancelledCallback) + CliScanType.Sast -> scanSast(target, onDemand, cancelledCallback) + } + } + + private fun scanSecrets(target: ScanTarget, onDemand: Boolean, cancelledCallback: TaskCancelledCallback) { + val results = runScan(target, CliScanType.Secret, cancelledCallback) if (results == null) { - thisLogger().warn("Failed to scan Secret paths: $paths") + thisLogger().warn("Failed to scan Secret: $target") return } @@ -225,10 +234,10 @@ class CliService(private val project: Project) { rerunAnnotators() } - fun scanPathsSca(paths: List, onDemand: Boolean = true, cancelledCallback: TaskCancelledCallback = null) { - val results = scanPaths(paths, CliScanType.Sca, cancelledCallback) + private fun scanSca(target: ScanTarget, onDemand: Boolean, cancelledCallback: TaskCancelledCallback) { + val results = runScan(target, CliScanType.Sca, cancelledCallback) if (results == null) { - thisLogger().warn("Failed to scan SCA paths: $paths") + thisLogger().warn("Failed to scan SCA: $target") return } @@ -255,10 +264,10 @@ class CliService(private val project: Project) { } } - fun scanPathsIac(paths: List, onDemand: Boolean = true, cancelledCallback: TaskCancelledCallback = null) { - var results = scanPaths(paths, CliScanType.Iac, cancelledCallback) + private fun scanIac(target: ScanTarget, onDemand: Boolean, cancelledCallback: TaskCancelledCallback) { + var results = runScan(target, CliScanType.Iac, cancelledCallback) if (results == null) { - thisLogger().warn("Failed to IaC scan paths: $paths") + thisLogger().warn("Failed to IaC scan: $target") return } @@ -281,10 +290,10 @@ class CliService(private val project: Project) { rerunAnnotators() } - fun scanPathsSast(paths: List, onDemand: Boolean = true, cancelledCallback: TaskCancelledCallback = null) { - val results = scanPaths(paths, CliScanType.Sast, cancelledCallback) + private fun scanSast(target: ScanTarget, onDemand: Boolean, cancelledCallback: TaskCancelledCallback) { + val results = runScan(target, CliScanType.Sast, cancelledCallback) if (results == null) { - thisLogger().warn("Failed to SAST scan paths: $paths") + thisLogger().warn("Failed to SAST scan: $target") return } diff --git a/src/main/kotlin/com/cycode/plugin/services/CycodeProjectStateService.kt b/src/main/kotlin/com/cycode/plugin/services/CycodeProjectStateService.kt new file mode 100644 index 0000000..9b6bcc6 --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/services/CycodeProjectStateService.kt @@ -0,0 +1,24 @@ +package com.cycode.plugin.services + +import com.cycode.plugin.cli.ScanScope +import com.intellij.openapi.components.PersistentStateComponent +import com.intellij.openapi.components.Service +import com.intellij.openapi.components.State +import com.intellij.openapi.components.Storage +import com.intellij.openapi.components.StoragePathMacros +import com.intellij.util.xmlb.XmlSerializerUtil + +/** Settings that belong to one project; stored in the project's workspace file (not shared through VCS). */ +@Service(Service.Level.PROJECT) +@State(name = "CycodeProjectStateService", storages = [Storage(StoragePathMacros.WORKSPACE_FILE)]) +class CycodeProjectStateService : PersistentStateComponent { + var scanScope: String = ScanScope.Project.name + + override fun getState(): CycodeProjectStateService { + return this + } + + override fun loadState(state: CycodeProjectStateService) { + XmlSerializerUtil.copyBean(state, this) + } +} diff --git a/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt b/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt index a8fcd80..a453db0 100755 --- a/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt @@ -1,8 +1,7 @@ package com.cycode.plugin.services import com.cycode.plugin.CycodeBundle -import com.cycode.plugin.cli.CliIgnoreType -import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.* import com.cycode.plugin.cli.models.AiRemediationResultData import com.cycode.plugin.components.toolWindow.CycodeToolWindowFactory import com.cycode.plugin.components.toolWindow.updateToolWindowState @@ -63,7 +62,7 @@ class CycodeService(val project: Project) : Disposable { } } - private fun getBackgroundScanningLabel(scanType: CliScanType) = when (scanType) { + fun getBackgroundScanningLabel(scanType: CliScanType) = when (scanType) { CliScanType.Secret -> CycodeBundle.message("secretScanning") CliScanType.Sca -> CycodeBundle.message("scaScanning") CliScanType.Iac -> CycodeBundle.message("iacScanning") @@ -90,15 +89,7 @@ class CycodeService(val project: Project) : Disposable { } thisLogger().debug("[$scanType] Start scanning paths: $pathsToScan") - - val cancelledCallback = { indicator.isCanceled } - when (scanType) { - CliScanType.Secret -> cliService.scanPathsSecrets(pathsToScan, onDemand, cancelledCallback) - CliScanType.Sca -> cliService.scanPathsSca(pathsToScan, onDemand, cancelledCallback) - CliScanType.Iac -> cliService.scanPathsIac(pathsToScan, onDemand, cancelledCallback) - CliScanType.Sast -> cliService.scanPathsSast(pathsToScan, onDemand, cancelledCallback) - } - + cliService.scan(scanType, ScanTarget.Paths(pathsToScan), onDemand) { indicator.isCanceled } thisLogger().debug("[$scanType] Finish scanning paths: $pathsToScan") } } diff --git a/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt b/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt index ad641c7..b2a785a 100755 --- a/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt @@ -1,6 +1,10 @@ package com.cycode.plugin.services import com.cycode.plugin.cli.models.StatusResult +import com.cycode.plugin.git.DiffRefsCache +import com.cycode.plugin.git.HEAD_REF +import com.cycode.plugin.git.LOCAL_DIRECTORY_REF +import com.cycode.plugin.git.RefOption import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.thisLogger @@ -15,6 +19,28 @@ class CycodeTemporaryStateService { thisLogger().info("cliStatus set") } + // the "git is not available" message is shown once per session + @Volatile + var gitUnavailableNotified: Boolean = false + + // per-repository and therefore session-only; persisting them globally leaks picks between projects + @Volatile + var diffFromRef: String = LOCAL_DIRECTORY_REF + + @Volatile + var diffToRef: String = HEAD_REF + + // the revision lists and the git state they were built for (see GitRepository.getHeadFingerprint) + @Volatile + var diffRefsCache: DiffRefsCache? = null + + val diffRefs: List + get() = diffRefsCache?.refs ?: emptyList() + + // null until known; only an explicit "not a git repository" answer makes it false + @Volatile + var isGitRepository: Boolean? = null + val isSecretScanningEnabled: Boolean get() = cliStatus?.supportedModules?.secretScanning == true diff --git a/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt b/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt new file mode 100644 index 0000000..109a651 --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt @@ -0,0 +1,213 @@ +package com.cycode.plugin.services + +import com.cycode.plugin.CycodeBundle +import com.cycode.plugin.cli.ScanScope +import com.cycode.plugin.cli.ScanTarget +import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.getScanTypeDisplayName +import com.cycode.plugin.cli.isDiffScanSupportedByCli +import com.cycode.plugin.cli.isFileSupportedByScanType +import com.cycode.plugin.cli.partitionByFileSupport +import com.cycode.plugin.components.toolWindow.updateToolWindowState +import com.cycode.plugin.git.DiffRefsCache +import com.cycode.plugin.git.DiffScanPlan +import com.cycode.plugin.git.GitRepository +import com.cycode.plugin.git.HEAD_REF +import com.cycode.plugin.git.LOCAL_DIRECTORY_REF +import com.cycode.plugin.git.planDiffScan +import com.cycode.plugin.utils.CycodeNotifier +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.components.Service +import com.intellij.openapi.diagnostic.thisLogger +import com.intellij.openapi.fileEditor.FileEditorManager +import com.intellij.openapi.project.Project +import java.util.concurrent.atomic.AtomicLong + +/** + * The scan scope (Project / Diff / File): which scope is selected, the revisions of a diff scan and starting + * scans for the selected scope. + */ +@Service(Service.Level.PROJECT) +class ScanScopeService(private val project: Project) { + private val cliService = cli(project) + private val cycodeService = cycode(project) + private val pluginLocalState = pluginLocalState(project) + private val projectState = projectState(project) + private val refreshRequestId = AtomicLong() + + fun getScanScope(): ScanScope { + return ScanScope.entries.firstOrNull { it.name == projectState.scanScope } ?: ScanScope.Project + } + + fun setScanScope(scope: ScanScope) { + projectState.scanScope = scope.name + if (scope == ScanScope.Diff) { + refreshDiffRefs() + } + } + + fun isDiffScanSupported(): Boolean = isDiffScanSupportedByCli(pluginLocalState.cliStatus?.version) + + /** False only when the project folder is known not to be inside a git repository. */ + fun isGitRepository(): Boolean? = pluginLocalState.isGitRepository + + /** Diff needs a new enough CLI and a git repository. */ + fun isDiffScanAvailable(): Boolean = isDiffScanSupported() && isGitRepository() != false + + /** Until the CLI status is known (or if the CLI is too old or there is no repository), Diff behaves as Project. */ + fun getEffectiveScanScope(): ScanScope { + val scope = getScanScope() + return if (scope == ScanScope.Diff && !isDiffScanAvailable()) ScanScope.Project else scope + } + + /** Checks in the background whether the project is a git repository; rebuilds the scan tab if that changed. */ + fun refreshGitRepositoryState() { + val projectRoot = cliService.getProjectRootDirectory() ?: return + + ApplicationManager.getApplication().executeOnPooledThread { + val isRepository = GitRepository(projectRoot).isGitRepository() + if (!project.isDisposed && isRepository != pluginLocalState.isGitRepository) { + pluginLocalState.isGitRepository = isRepository + updateToolWindowState(project) + } + } + } + + fun setDiffRefs(from: String, to: String) { + pluginLocalState.diffFromRef = from + pluginLocalState.diffToRef = to + } + + /** + * Reloads the revision lists in the background and resets stale picks to the defaults. + * A request id drops results of superseded requests. + */ + fun refreshDiffRefs(onDone: (() -> Unit)? = null) { + val projectRoot = cliService.getProjectRootDirectory() ?: return + val requestId = refreshRequestId.incrementAndGet() + val pinned = listOf(pluginLocalState.diffFromRef, pluginLocalState.diffToRef) + + ApplicationManager.getApplication().executeOnPooledThread { + val git = GitRepository(projectRoot) + + // the lists are rebuilt only when the branch changes or a commit is created + val fingerprint = git.getHeadFingerprint() + if (fingerprint == null && !pluginLocalState.gitUnavailableNotified && !git.isGitAvailable()) { + pluginLocalState.gitUnavailableNotified = true + CycodeNotifier.notifyInfo(project, CycodeBundle.message("diffGitUnavailableNotification")) + } + + val cache = pluginLocalState.diffRefsCache + val reuse = cache != null && cache.canReuse(fingerprint) + val refs = if (reuse) cache!!.refs else git.getAvailableRefs(pinned) + if (requestId != refreshRequestId.get() || project.isDisposed) { + return@executeOnPooledThread + } + + val values = refs.map { it.value }.toSet() + LOCAL_DIRECTORY_REF + if (pluginLocalState.diffFromRef !in values) pluginLocalState.diffFromRef = LOCAL_DIRECTORY_REF + if (pluginLocalState.diffToRef !in values) pluginLocalState.diffToRef = HEAD_REF + // only a request that is still current may publish lists, together with the state they were built for + if (!reuse) pluginLocalState.diffRefsCache = DiffRefsCache(fingerprint, refs) + + if (onDone != null) { + ApplicationManager.getApplication().invokeLater({ onDone() }, project.disposed) + } + } + } + + /** + * Scans according to the selected scope. + */ + fun startScanForCurrentScope(scanType: CliScanType) { + when (getEffectiveScanScope()) { + ScanScope.Project -> cycodeService.startScanForCurrentProject(scanType) + ScanScope.File -> startScanForCurrentFile(scanType) + ScanScope.Diff -> startDiffScan(scanType) + } + } + + /** Runs every scan type enabled for the tenant, according to the selected scope. */ + fun startAllScansForCurrentScope() { + // without an open file every scan type would show the same message: say it once + if (getEffectiveScanScope() == ScanScope.File && currentLocalFilePath() == null) { + CycodeNotifier.notifyInfo(project, CycodeBundle.message("noOpenFileErrorNotification")) + return + } + + val local = pluginLocalState + val scanTypes = listOf( + CliScanType.Secret to local.isSecretScanningEnabled, + CliScanType.Sca to local.isScaScanningEnabled, + CliScanType.Sast to local.isSastScanningEnabled, + CliScanType.Iac to local.isIacScanningEnabled, + ).filter { it.second }.map { it.first } + + if (getEffectiveScanScope() != ScanScope.File) { + scanTypes.forEach { startScanForCurrentScope(it) } + return + } + + // one combined message for the types that cannot scan the open file, instead of one per type + val filePath = currentLocalFilePath() ?: return + val (supported, unsupported) = partitionByFileSupport(filePath, scanTypes) + supported.forEach { cycodeService.startScan(it, listOf(filePath)) } + if (unsupported.isNotEmpty()) { + val names = unsupported.joinToString(", ") { getScanTypeDisplayName(it) } + CycodeNotifier.notifyInfo(project, CycodeBundle.message("scanFileUnsupportedNotification", names)) + } + } + + private fun currentLocalFilePath(): String? { + val file = FileEditorManager.getInstance(project).selectedFiles.firstOrNull() + return file?.takeIf { it.isInLocalFileSystem }?.canonicalPath + } + + private fun startScanForCurrentFile(scanType: CliScanType) { + val filePath = currentLocalFilePath() + if (filePath == null) { + CycodeNotifier.notifyInfo(project, CycodeBundle.message("noOpenFileErrorNotification")) + return + } + + if (!isFileSupportedByScanType(filePath, scanType)) { + CycodeNotifier.notifyInfo( + project, + CycodeBundle.message("scanFileUnsupportedNotification", getScanTypeDisplayName(scanType)) + ) + return + } + + cycodeService.startScan(scanType, listOf(filePath)) + } + + private fun startDiffScan(scanType: CliScanType) { + val from = pluginLocalState.diffFromRef + val to = pluginLocalState.diffToRef + + val projectRoot = cliService.getProjectRootDirectory() + if (projectRoot == null) { + CycodeNotifier.notifyInfo(project, CycodeBundle.message("noProjectRootErrorNotification")) + return + } + + cycodeService.runBackgroundTask(cycodeService.getBackgroundScanningLabel(scanType)) { indicator -> + if (!pluginLocalState.cliAuthed) { + CycodeNotifier.notifyInfo(project, CycodeBundle.message("authorizationRequiredNotification")) + return@runBackgroundTask + } + + val target = when (val plan = planDiffScan(scanType, from, to, projectRoot, GitRepository(projectRoot))) { + is DiffScanPlan.Run -> plan.target + is DiffScanPlan.Refused -> { + CycodeNotifier.notifyInfo(project, CycodeBundle.message(plan.messageKey)) + return@runBackgroundTask + } + } + + thisLogger().debug("[$scanType] Start diff scan: $target") + cliService.scan(scanType, target, true) { indicator.isCanceled } + thisLogger().debug("[$scanType] Finish diff scan: $target") + } + } +} diff --git a/src/main/kotlin/com/cycode/plugin/services/Services.kt b/src/main/kotlin/com/cycode/plugin/services/Services.kt index 4800f6a..99ccc3f 100644 --- a/src/main/kotlin/com/cycode/plugin/services/Services.kt +++ b/src/main/kotlin/com/cycode/plugin/services/Services.kt @@ -30,3 +30,7 @@ fun download(project: Project? = null): DownloadService = getCycodeService(proje fun githubReleases(project: Project? = null): GithubReleaseService = getCycodeService(project) fun cycode(project: Project? = null): CycodeService = getCycodeService(project) + +fun projectState(project: Project): CycodeProjectStateService = getCycodeService(project) + +fun scanScope(project: Project? = null): ScanScopeService = getCycodeService(project) diff --git a/src/main/resources/messages/CycodeBundle.properties b/src/main/resources/messages/CycodeBundle.properties index 5adb03c..ce31124 100755 --- a/src/main/resources/messages/CycodeBundle.properties +++ b/src/main/resources/messages/CycodeBundle.properties @@ -34,6 +34,14 @@ noProjectRootErrorNotification=Cycode scans the project that is currently opened authorizationRequiredNotification=You are not authenticated in Cycode. Please authenticate scanFileResultNotification=Cycode has detected {0} {1} issues in your file. Check out your "Cycode" tab to analyze. scanFileNoResultNotification=No {0} issues were found. +scanFileUnsupportedNotification={0}: scanning is not supported for the open file. +diffSameRevisionNotification=Select two different revisions to compare. +diffSameCommitNotification=The selected revisions point to the same commit, so there is nothing to compare. +diffNoCommonHistoryNotification=The selected revisions have no common history, so they cannot be compared. +diffUnknownRevisionNotification=One of the selected revisions could not be found in the repository. Refresh the list and select it again. +diffNotGitRepositoryNotification=Diff scanning requires the project to be inside a Git repository. +diffGitUnavailableNotification=Git could not be run, so the list of revisions is limited. Check that Git is installed and available in the PATH. +diffGitFailureNotification=Could not compare the selected revisions. See the IDE log for details. aiRemediationNotAvailableNotification=AI remediation is not available for this detection openProblemsTabAction=Open "Cycode" tab # tool window @@ -58,6 +66,18 @@ loadingTabLoadingText=\ authBtn=Authenticate # scan content tab scanTabTitleLabel=Ready to scan. +scanScopeLabel=Scan scope: +scanScopeProject=Project +scanScopeDiff=Diff +scanScopeFile=File +scanScopeProjectHint=Scans the entire project. +scanScopeDiffHint=Compares the two selected revisions. Scanning only the changes is faster but may be less accurate. +scanScopeFileHint=Scans only the file open in the editor. +scanScopeDiffNoGitNote=Diff is disabled because the project is not inside a Git repository. +scanScopeDiffIacNote=Infrastructure As Code does not support diff scans and always scans the full project. +scanScopeDiffFromLabel=From: +scanScopeDiffToLabel=To: +scanScopeDiffLocalDirectory=Local directory scanTabOnSaveTip=To easily scan your edited files, enable Scan on Save in settings (enabled by default). scanTabSecretsBtn=Scan for hardcoded secrets scanTabScaBtn=Scan for package vulnerabilities @@ -137,4 +157,4 @@ toolbarHomeAction=Return to Home Screen toolbarFilterBySeverityAction=Filter by {0} severity toolbarClearAction=Clear results toolbarHelpAction=Open documentation -toolbarRunAllAction=Run all scans types for the entire project +toolbarRunAllAction=Run all scan types for the selected scope diff --git a/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt b/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt new file mode 100644 index 0000000..b549903 --- /dev/null +++ b/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt @@ -0,0 +1,111 @@ +package com.cycode.plugin + +import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.DiffScanMode +import com.cycode.plugin.cli.ScanTarget +import com.cycode.plugin.git.DiffScanPlan +import com.cycode.plugin.git.GitRepository +import com.cycode.plugin.git.LOCAL_DIRECTORY_REF +import com.cycode.plugin.git.planDiffScan +import org.junit.Assert.assertEquals +import org.junit.Assert.assertTrue +import org.junit.Before +import org.junit.Test +import java.io.File + +class DiffScanPlannerTest : GitTestBase() { + @Before + fun addBranchAndCommit() { + sh("branch", "other") + commit("b") + } + + private fun plan(type: CliScanType, from: String, to: String, repo: GitRepository = git) = + planDiffScan(type, from, to, dir.path, repo) + + private val secret = CliScanType.Secret + + @Test + fun localDiffInBothOrders() { + val expected = DiffScanPlan.Run( + ScanTarget.Diff(DiffScanMode.LocalDiff, "main", dir.path) + ) + assertEquals(expected, plan(secret, LOCAL_DIRECTORY_REF, "main")) + assertEquals(expected, plan(secret, "main", LOCAL_DIRECTORY_REF)) + } + + @Test + fun commitRangeIsResolved() { + val plan = plan(secret, "other", "main") as DiffScanPlan.Run + val target = plan.target as ScanTarget.Diff + assertEquals(DiffScanMode.CommitRange, target.mode) + assertTrue(target.ref.matches(Regex("[0-9a-f]{40}\\.\\.[0-9a-f]{40}"))) + } + + @Test + fun iacFallsBackToFullScanEvenOutsideGit() { + val plain = createPlainDirectory() + try { + val expected = DiffScanPlan.Run(ScanTarget.Paths(listOf(dir.path))) + val iac = CliScanType.Iac + assertEquals(expected, plan(iac, LOCAL_DIRECTORY_REF, "main")) + assertEquals(expected, plan(iac, "other", "main", GitRepository(plain.path))) + } finally { + plain.deleteRecursively() + } + } + + @Test + fun sameRevisionIsRefused() { + assertEquals(DiffScanPlan.Refused("diffSameRevisionNotification"), plan(secret, "main", "main")) + assertEquals( + DiffScanPlan.Refused("diffSameRevisionNotification"), + plan(secret, LOCAL_DIRECTORY_REF, LOCAL_DIRECTORY_REF) + ) + } + + @Test + fun gitProblemsAreReportedAndStartNoScan() { + assertEquals(DiffScanPlan.Refused("diffUnknownRevisionNotification"), plan(secret, "main", "nope")) + + val plain = createPlainDirectory() + try { + assertEquals( + DiffScanPlan.Refused("diffNotGitRepositoryNotification"), + plan(secret, LOCAL_DIRECTORY_REF, "main", GitRepository(plain.path)) + ) + } finally { + plain.deleteRecursively() + } + } + + @Test + fun unsafeRefsAreRefusedInBothFlavours() { + assertEquals( + DiffScanPlan.Refused("diffUnknownRevisionNotification"), + plan(secret, LOCAL_DIRECTORY_REF, "--output=x") + ) + assertEquals(DiffScanPlan.Refused("diffUnknownRevisionNotification"), plan(secret, "--output=x", "main")) + } + + @Test + fun sameCommitUnderDifferentNamesIsRefused() { + assertEquals(DiffScanPlan.Refused("diffSameCommitNotification"), plan(secret, "main", "HEAD")) + } + + @Test + fun noCommonHistoryIsRefused() { + sh("checkout", "--orphan", "orphan") + File(dir, "o").writeText("o") + sh("add", "o") + sh("commit", "-m", "o") + assertEquals(DiffScanPlan.Refused("diffNoCommonHistoryNotification"), plan(secret, "main", "orphan")) + } + + @Test + fun everyDiffScanTypeGetsAPlan() { + CliScanType.entries.forEach { + assertTrue(plan(it, LOCAL_DIRECTORY_REF, "main") is DiffScanPlan.Run) + } + } +} diff --git a/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt b/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt new file mode 100644 index 0000000..f245d4a --- /dev/null +++ b/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt @@ -0,0 +1,86 @@ +package com.cycode.plugin + +import com.cycode.plugin.cli.* +import org.junit.Assert.* +import org.junit.Test + +class DiffScanTest { + @Test + fun commitRangeArgs() { + assertArrayEquals( + arrayOf("commit-history", "--commit-range", "a..b", "/repo"), + getDiffScanArgs(DiffScanMode.CommitRange, "a..b", "/repo") + ) + } + + @Test + fun localDiffArgs() { + assertArrayEquals( + arrayOf("pre-commit", "--include-unstaged", "--base-ref", "main", "--path", "/repo"), + getDiffScanArgs(DiffScanMode.LocalDiff, "main", "/repo") + ) + } + + @Test + fun optionLikeRefIsRejected() { + assertThrows(IllegalArgumentException::class.java) { + getDiffScanArgs(DiffScanMode.LocalDiff, "--output=x", "/repo") + } + assertFalse(isSafeRefArg("a\nb")) + assertTrue(isSafeRefArg("feature/x")) + } + + @Test + fun iacDoesNotSupportDiff() { + assertFalse(supportsDiffScan(CliScanType.Iac)) + assertTrue(supportsDiffScan(CliScanType.Secret)) + } + + @Test + fun versionGate() { + assertTrue(isVersionAtLeast("3.25.0", "3.25.0")) + assertTrue(isVersionAtLeast("3.26.0", "3.25.0")) + assertTrue(isVersionAtLeast("4.0.0", "3.25.0")) + assertFalse(isVersionAtLeast("3.24.9", "3.25.0")) + assertFalse(isVersionAtLeast("0.0.1.dev498", "3.25.0")) + assertFalse(isDiffScanSupportedByCli(null)) + } + + @Test + fun scanTargetArgs() { + assertArrayEquals(arrayOf("path", "/a", "/b"), ScanTarget.Paths(listOf("/a", "/b")).toCliArgs()) + assertArrayEquals( + arrayOf("commit-history", "--commit-range", "x..y", "/repo"), + ScanTarget.Diff(DiffScanMode.CommitRange, "x..y", "/repo").toCliArgs() + ) + } + + @Test + fun unsafeRefsAreRejected() { + assertThrows(IllegalArgumentException::class.java) { assertSafeRefArg("") } + assertThrows(IllegalArgumentException::class.java) { assertSafeRefArg("a\u0000b") } + assertThrows(IllegalArgumentException::class.java) { getDiffScanArgs(DiffScanMode.CommitRange, "-x", "/repo") } + assertFalse(isSafeRefArg("")) + assertFalse(isSafeRefArg("-")) + assertTrue(isSafeRefArg("origin/feature-1")) + assertTrue(isSafeRefArg("HEAD~1")) + } + + @Test + fun versionEdgeCases() { + assertTrue(isVersionAtLeast("v3.25.0", "3.25.0")) + assertTrue(isVersionAtLeast("3.25", "3.25.0")) + assertTrue(isVersionAtLeast("3.25.0.dev1", "3.25.0")) + assertFalse(isVersionAtLeast("3.25.0-alpha", "3.26.0")) + assertTrue(isVersionAtLeast("10.0.0", "3.25.0")) + assertFalse(isVersionAtLeast("", "3.25.0")) + assertFalse(isVersionAtLeast("garbage", "3.25.0")) + assertTrue(isDiffScanSupportedByCli("3.26.0")) + assertFalse(isDiffScanSupportedByCli("3.21.0")) + } + + @Test + fun everyScanTypeExceptIacSupportsDiff() { + CliScanType.entries.forEach { assertEquals(it != CliScanType.Iac, supportsDiffScan(it)) } + } +} diff --git a/src/test/kotlin/com/cycode/plugin/GitRepositoryTest.kt b/src/test/kotlin/com/cycode/plugin/GitRepositoryTest.kt new file mode 100644 index 0000000..4595b3e --- /dev/null +++ b/src/test/kotlin/com/cycode/plugin/GitRepositoryTest.kt @@ -0,0 +1,197 @@ +package com.cycode.plugin + +import com.cycode.plugin.git.* +import org.junit.Assert.* +import org.junit.Test + +/** Uses real temporary git repositories: the exit-code semantics are the point. */ +class GitRepositoryTest : GitTestBase() { + private fun diverge() { + sh("checkout", "-b", "feature") + commit("feature-1") + sh("checkout", "main") + commit("main-1") + } + + @Test + fun divergedBranchesGiveMergeBaseRangeBothWays() { + diverge() + val base = sh("merge-base", "main", "feature") + val feature = sh("rev-parse", "feature") + val main = sh("rev-parse", "main") + + assertEquals(CommitRangeResult.Range("$base..$feature"), git.getCommitRange("main", "feature")) + assertEquals(CommitRangeResult.Range("$base..$main"), git.getCommitRange("feature", "main")) + } + + @Test + fun newestFirstIsSwapped() { + val old = sh("rev-parse", "HEAD") + commit("second") + val new = sh("rev-parse", "HEAD") + + assertEquals(CommitRangeResult.Range("$old..$new"), git.getCommitRange(old, new)) + assertEquals(CommitRangeResult.Range("$old..$new"), git.getCommitRange(new, old)) + } + + @Test + fun gitIsAvailable() { + assertTrue(git.isGitAvailable()) + } + + @Test + fun sameCommit() { + assertEquals(CommitRangeResult.SameCommit, git.getCommitRange("HEAD", "main")) + } + + @Test + fun noCommonHistory() { + sh("checkout", "--orphan", "orphan") + commit("orphan-1") + assertEquals(CommitRangeResult.NoCommonHistory, git.getCommitRange("main", "orphan")) + } + + @Test + fun unknownAndOptionLikeRevisions() { + assertEquals(CommitRangeResult.UnknownRevision, git.getCommitRange("main", "nope")) + assertEquals(CommitRangeResult.UnknownRevision, git.getCommitRange("main", "--output=x")) + } + + @Test + fun nonGitFolder() { + val plain = createPlainDirectory() + try { + assertFalse(GitRepository(plain.path).isGitRepository()) + assertTrue(git.isGitRepository()) + } finally { + plain.deleteRecursively() + } + } + + @Test + fun refLabelsAndPinning() { + diverge() + val refs = git.getAvailableRefs() + assertEquals(HEAD_REF, refs.first().value) + assertTrue(refs.any { it.value == "feature" && it.label.startsWith("feature$LABEL_SEPARATOR") }) + // a commit that is a branch tip is listed once, under the ref name + assertEquals(1, refs.count { it.label.endsWith("main-1") }) + + val first = sh("rev-list", "--max-parents=0", "HEAD") + assertTrue(git.getAvailableRefs(listOf(first)).any { it.value == first }) + assertFalse(git.getAvailableRefs(listOf("nope")).any { it.value == "nope" }) + } + + @Test + fun labelFormat() { + assertEquals("main │ abc123 │ subject", GitRepository.buildLabel("main", "abc123", "subject")) + } + + @Test + fun refListsAreCapped() { + repeat(GitRepository.MAX_REFS + 5) { sh("branch", "b$it") } + repeat(GitRepository.MAX_COMMITS + 5) { commit("c$it") } + + val refs = git.getAvailableRefs() + val sha = Regex("[0-9a-f]{40}") + val branchesAndTags = refs.count { it.value != HEAD_REF && !sha.matches(it.value) } + assertTrue(branchesAndTags <= GitRepository.MAX_REFS) + // HEAD + capped refs + capped commits + assertTrue(refs.size <= 1 + GitRepository.MAX_REFS + GitRepository.MAX_COMMITS) + } + + @Test + fun tagsAreListed() { + sh("tag", "v1") + assertTrue(git.getAvailableRefs().any { it.value == "v1" }) + } + + @Test + fun commitsAreLabelledWithTheCurrentBranch() { + commit("second") + val commitOption = git.getAvailableRefs().first { it.label.endsWith("base") } + assertTrue(commitOption.label.startsWith("main$LABEL_SEPARATOR")) + } + + @Test + fun detachedHeadCommitsHaveNoBranchPrefix() { + commit("second") + sh("checkout", "--detach", "HEAD~1") + val refs = git.getAvailableRefs() + val baseCommit = refs.first { it.label.endsWith("base") && it.value.length == 40 } + assertFalse(baseCommit.label.contains("main")) + assertEquals(HEAD_REF, refs.first().value) + } + + @Test + fun remoteHeadSymbolicRefIsSkipped() { + sh("update-ref", "refs/remotes/origin/main", "HEAD") + sh("symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/main") + val refs = git.getAvailableRefs() + assertTrue(refs.any { it.value == "origin/main" }) + assertFalse(refs.any { it.value.endsWith("/HEAD") }) + } + + @Test + fun commitRangeWithTagsAndRelativeRevisions() { + sh("tag", "v1") + commit("second") + val result = git.getCommitRange("v1", "HEAD") as CommitRangeResult.Range + assertTrue(result.range.matches(Regex("[0-9a-f]{40}\\.\\.[0-9a-f]{40}"))) + assertEquals(result, git.getCommitRange("v1", "main")) + } + + @Test + fun unknownOrUnsafeFromRevision() { + assertEquals(CommitRangeResult.UnknownRevision, git.getCommitRange("nope", "main")) + assertEquals(CommitRangeResult.UnknownRevision, git.getCommitRange("--output=x", "main")) + assertEquals(CommitRangeResult.UnknownRevision, git.getCommitRange("", "main")) + } + + @Test + fun pinnedRefThatScrolledOutOfTheListIsKept() { + val oldest = sh("rev-parse", "HEAD") + repeat(GitRepository.MAX_COMMITS + 5) { commit("c$it") } + val refs = git.getAvailableRefs(listOf(oldest, LOCAL_DIRECTORY_REF, "HEAD")) + assertEquals(1, refs.count { it.value == oldest }) + assertEquals(1, refs.count { it.value == HEAD_REF }) + assertFalse(refs.any { it.value == LOCAL_DIRECTORY_REF }) + } + + @Test + fun unsafePinnedRefIsDropped() { + assertFalse(git.getAvailableRefs(listOf("--output=x")).any { it.value == "--output=x" }) + } + + @Test + fun labelWithoutRefNameOrSubject() { + assertEquals("abc123", GitRepository.buildLabel(null, "abc123", "")) + assertEquals("abc123 │ subject", GitRepository.buildLabel("", "abc123", "subject")) + } + + @Test + fun headFingerprintChangesOnCommitAndBranchSwitchOnly() { + val first = git.getHeadFingerprint()!! + assertEquals(first, git.getHeadFingerprint()) + + sh("branch", "other") // a new ref that is not checked out does not change it + assertEquals(first, git.getHeadFingerprint()) + + commit("second") + val afterCommit = git.getHeadFingerprint()!! + assertNotEquals(first, afterCommit) + + sh("checkout", "other") + assertNotEquals(afterCommit, git.getHeadFingerprint()) + } + + @Test + fun headFingerprintIsNullOutsideARepository() { + val plain = createPlainDirectory() + try { + assertNull(GitRepository(plain.path).getHeadFingerprint()) + } finally { + plain.deleteRecursively() + } + } +} diff --git a/src/test/kotlin/com/cycode/plugin/GitTestBase.kt b/src/test/kotlin/com/cycode/plugin/GitTestBase.kt new file mode 100644 index 0000000..f53d163 --- /dev/null +++ b/src/test/kotlin/com/cycode/plugin/GitTestBase.kt @@ -0,0 +1,50 @@ +package com.cycode.plugin + +import com.cycode.plugin.git.GitRepository +import org.junit.After +import org.junit.Before +import java.io.File +import java.nio.file.Files + +/** + * Real temporary git repository with one commit ("base") on `main`: the git semantics are the point of the tests, + * so nothing is mocked. + */ +abstract class GitTestBase { + protected lateinit var dir: File + protected lateinit var git: GitRepository + + protected fun sh(vararg args: String): String { + // signing and the user's global config must not influence the tests + val command = listOf( + "git", "-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false", + "-c", "tag.gpgsign=false", *args + ) + val process = ProcessBuilder(command).directory(dir).redirectErrorStream(true).start() + val out = process.inputStream.bufferedReader().readText().trim() + check(process.waitFor() == 0) { "git ${args.toList()} failed: $out" } + return out + } + + protected fun commit(name: String) { + File(dir, name).writeText(name) + sh("add", name) + sh("commit", "-m", name) + } + + protected fun createPlainDirectory(): File = Files.createTempDirectory("cycode-plain").toFile() + + @Before + fun createRepository() { + dir = Files.createTempDirectory("cycode-git").toFile() + sh("init") + sh("symbolic-ref", "HEAD", "refs/heads/main") // `init -b` needs git 2.28 + commit("base") + git = GitRepository(dir.path) + } + + @After + fun deleteRepository() { + dir.deleteRecursively() + } +} diff --git a/src/test/kotlin/com/cycode/plugin/ScanScopeLogicTest.kt b/src/test/kotlin/com/cycode/plugin/ScanScopeLogicTest.kt new file mode 100644 index 0000000..1891319 --- /dev/null +++ b/src/test/kotlin/com/cycode/plugin/ScanScopeLogicTest.kt @@ -0,0 +1,74 @@ +package com.cycode.plugin + +import com.cycode.plugin.cli.CliScanType +import com.cycode.plugin.cli.isFileSupportedByScanType +import com.cycode.plugin.cli.partitionByFileSupport +import com.cycode.plugin.git.DiffRefsCache +import com.cycode.plugin.git.RefOption +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test + +class ScanScopeLogicTest { + private val allTypes = listOf(CliScanType.Secret, CliScanType.Sca, CliScanType.Sast, CliScanType.Iac) + + @Test + fun secretAndSastScanAnyFile() { + assertTrue(isFileSupportedByScanType("/p/Main.kt", CliScanType.Secret)) + assertTrue(isFileSupportedByScanType("/p/Main.kt", CliScanType.Sast)) + } + + @Test + fun scaOnlyScansPackageFiles() { + assertTrue(isFileSupportedByScanType("/p/package.json", CliScanType.Sca)) + assertTrue(isFileSupportedByScanType("/p/requirements.txt", CliScanType.Sca)) + assertFalse(isFileSupportedByScanType("/p/Main.kt", CliScanType.Sca)) + } + + @Test + fun iacOnlyScansInfrastructureFiles() { + assertTrue(isFileSupportedByScanType("/p/main.tf", CliScanType.Iac)) + assertTrue(isFileSupportedByScanType("/p/Dockerfile", CliScanType.Iac)) + assertTrue(isFileSupportedByScanType("/p/deploy.yaml", CliScanType.Iac)) + assertFalse(isFileSupportedByScanType("/p/Main.kt", CliScanType.Iac)) + } + + @Test + fun partitionKeepsTheOrderOfTheScanTypes() { + val (supported, unsupported) = partitionByFileSupport("/p/Main.kt", allTypes) + assertEquals(listOf(CliScanType.Secret, CliScanType.Sast), supported) + assertEquals(listOf(CliScanType.Sca, CliScanType.Iac), unsupported) + + val (all, none) = partitionByFileSupport("/p/package.json", listOf(CliScanType.Secret, CliScanType.Sca)) + assertEquals(listOf(CliScanType.Secret, CliScanType.Sca), all) + assertTrue(none.isEmpty()) + } + + private val refs = listOf(RefOption("HEAD", "HEAD")) + + @Test + fun cacheIsReusedOnlyForTheSameKnownGitState() { + val cache = DiffRefsCache("main@abc", refs) + assertTrue(cache.canReuse("main@abc")) + assertFalse(cache.canReuse("main@def")) // a commit was created + assertFalse(cache.canReuse("other@abc")) // the branch changed + assertFalse(cache.canReuse(null)) // git state unknown + } + + @Test + fun cacheWithoutFingerprintOrListIsNeverReused() { + assertFalse(DiffRefsCache(null, refs).canReuse(null)) + assertFalse(DiffRefsCache("main@abc", emptyList()).canReuse("main@abc")) + } + + @Test + fun listsAreNeverPairedWithAnotherStatesFingerprint() { + // the fingerprint and the list live in one immutable object, so a stale request cannot split them + val first = DiffRefsCache("main@abc", refs) + val second = DiffRefsCache("main@def", listOf(RefOption("x", "x"))) + assertFalse(first.canReuse("main@def")) + assertEquals("x", second.refs.single().value) + assertTrue(second.canReuse("main@def")) + } +} From c1308aef55833174961e446f40fac7775626981d Mon Sep 17 00:00:00 2001 From: Aaron Butler Date: Mon, 9 Nov 2026 09:39:36 -0500 Subject: [PATCH 2/4] CM-77192: split diff git state out of ScanScopeService, model diff sides - DiffSide (Local or Rev) replaces the NUL-prefixed sentinel string, so the compiler enforces the local-directory special case - DiffRefsService owns the repository state, the selected sides and the cached revision lists; ScanScopeService keeps the scope and the dispatch - Rename GitRepository to GitCli so it does not clash with git4idea.repo.GitRepository Co-Authored-By: Claude Sonnet 5.5 --- .../scanContentTab/ScanContentTab.kt | 52 +++++---- .../com/cycode/plugin/git/DiffScanPlanner.kt | 15 ++- .../kotlin/com/cycode/plugin/git/DiffSide.kt | 8 ++ .../git/{GitRepository.kt => GitCli.kt} | 5 +- .../services/CycodeTemporaryStateService.kt | 26 ----- .../cycode/plugin/services/DiffRefsService.kt | 105 ++++++++++++++++++ .../plugin/services/ScanScopeService.kt | 83 ++------------ .../com/cycode/plugin/services/Services.kt | 2 + .../com/cycode/plugin/DiffScanPlannerTest.kt | 27 +++-- .../{GitRepositoryTest.kt => GitCliTest.kt} | 25 ++--- .../kotlin/com/cycode/plugin/GitTestBase.kt | 6 +- 11 files changed, 190 insertions(+), 164 deletions(-) create mode 100644 src/main/kotlin/com/cycode/plugin/git/DiffSide.kt rename src/main/kotlin/com/cycode/plugin/git/{GitRepository.kt => GitCli.kt} (97%) create mode 100644 src/main/kotlin/com/cycode/plugin/services/DiffRefsService.kt rename src/test/kotlin/com/cycode/plugin/{GitRepositoryTest.kt => GitCliTest.kt} (86%) diff --git a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt index 290b547..176706f 100644 --- a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt +++ b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt @@ -7,9 +7,10 @@ import com.cycode.plugin.components.Component import com.cycode.plugin.components.common.createClickableLabel import com.cycode.plugin.components.toolWindow.updateToolWindowState import com.cycode.plugin.git.HEAD_REF -import com.cycode.plugin.git.LOCAL_DIRECTORY_REF +import com.cycode.plugin.git.DiffSide import com.cycode.plugin.git.RefOption import com.cycode.plugin.services.CycodeService +import com.cycode.plugin.services.diffRefs import com.cycode.plugin.services.pluginLocalState import com.cycode.plugin.services.scanScope import com.intellij.icons.AllIcons @@ -94,13 +95,13 @@ class ScanContentTab : Component() { private fun addScopeControls(service: CycodeService) { val scopeService = scanScope(service.project) - val pluginLocalState = pluginLocalState(service.project) val effectiveScope = scopeService.getEffectiveScanScope() - val isGitRepository = scopeService.isGitRepository() + val diffRefs = diffRefs(service.project) + val isGitRepository = diffRefs.isGitRepository val scopes = ScanScope.entries.filter { it != ScanScope.Diff || scopeService.isDiffScanSupported() } // Diff is disabled when this turns out not to be a git repository; the tab is rebuilt if that changes - scopeService.refreshGitRepositoryState() + diffRefs.refreshGitRepositoryState() addComponentToPanel(createClickableLabel(CycodeBundle.message("scanScopeLabel"))) @@ -143,49 +144,46 @@ class ScanContentTab : Component() { addComponentToPanel(createNote(CycodeBundle.message("scanScopeDiffIacNote"), AllIcons.General.Warning)) // lists are reloaded in the background and the combos updated in place (never while a popup is open) - scopeService.refreshDiffRefs { - populateRefCombo(fromCombo, true, pluginLocalState.diffFromRef, pluginLocalState.diffRefs) - populateRefCombo(toCombo, false, pluginLocalState.diffToRef, pluginLocalState.diffRefs) + diffRefs.refresh { + populateCombo(fromCombo, true, diffRefs.from, diffRefs.refs) + populateCombo(toCombo, false, diffRefs.to, diffRefs.refs) } } - private fun createRefCombo(service: CycodeService, isFrom: Boolean): ComboBox { - val pluginLocalState = pluginLocalState(service.project) - return ComboBox().apply { + /** A combo entry: the local directory or a revision. */ + private class SideOption(val side: DiffSide, val label: String) { + override fun toString() = label + } + + private fun createRefCombo(service: CycodeService, isFrom: Boolean): ComboBox { + val diffRefs = diffRefs(service.project) + return ComboBox().apply { // long labels are truncated instead of widening the tool window setMinimumAndPreferredWidth(JBUI.scale(REF_COMBO_WIDTH)) maximumRowCount = REF_COMBO_VISIBLE_ROWS renderer = SimpleListCellRenderer.create("") { it.label } - populateRefCombo( - this, - isFrom, - if (isFrom) pluginLocalState.diffFromRef else pluginLocalState.diffToRef, - pluginLocalState.diffRefs - ) + populateCombo(this, isFrom, if (isFrom) diffRefs.from else diffRefs.to, diffRefs.refs) addActionListener { if (updatingCombos) return@addActionListener - val selected = selectedItem as? RefOption ?: return@addActionListener - if (isFrom) { - scanScope(service.project).setDiffRefs(selected.value, pluginLocalState.diffToRef) - } else { - scanScope(service.project).setDiffRefs(pluginLocalState.diffFromRef, selected.value) - } + val selected = (selectedItem as? SideOption)?.side ?: return@addActionListener + if (isFrom) diffRefs.setSides(selected, diffRefs.to) else diffRefs.setSides(diffRefs.from, selected) } } } - private fun populateRefCombo(combo: ComboBox, isFrom: Boolean, selectedValue: String, refs: List) { + private fun populateCombo(combo: ComboBox, isFrom: Boolean, selected: DiffSide, known: List) { // replacing the model closes an open popup if (combo.isPopupVisible) return - val items = mutableListOf(RefOption(LOCAL_DIRECTORY_REF, CycodeBundle.message("scanScopeDiffLocalDirectory"))) - items.addAll(refs.ifEmpty { listOf(RefOption(HEAD_REF, HEAD_REF)) }) + val refs = known.ifEmpty { listOf(RefOption(HEAD_REF, HEAD_REF)) } + val items = listOf(SideOption(DiffSide.Local, CycodeBundle.message("scanScopeDiffLocalDirectory"))) + + refs.map { SideOption(DiffSide.Rev(it.value), it.label) } updatingCombos = true try { combo.model = DefaultComboBoxModel(items.toTypedArray()) - combo.selectedItem = items.firstOrNull { it.value == selectedValue } - ?: items.first { it.value == if (isFrom) LOCAL_DIRECTORY_REF else HEAD_REF } + combo.selectedItem = items.firstOrNull { it.side == selected } + ?: items.first { it.side == if (isFrom) DiffSide.Local else DiffSide.Rev(HEAD_REF) } } finally { updatingCombos = false } diff --git a/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt b/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt index df2cbc7..e4976df 100644 --- a/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt +++ b/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt @@ -17,7 +17,7 @@ sealed class DiffScanPlan { * Decides what a diff scan of [scanType] should run, without touching the IDE. Runs git, so call it on a * background thread. */ -fun planDiffScan(scanType: CliScanType, from: String, to: String, projectRoot: String, git: GitRepository): DiffScanPlan { +fun planDiffScan(scanType: CliScanType, from: DiffSide, to: DiffSide, projectRoot: String, git: GitCli): DiffScanPlan { if (from == to) { return DiffScanPlan.Refused("diffSameRevisionNotification") } @@ -31,15 +31,18 @@ fun planDiffScan(scanType: CliScanType, from: String, to: String, projectRoot: S return DiffScanPlan.Refused("diffNotGitRepositoryNotification") } - if (from == LOCAL_DIRECTORY_REF || to == LOCAL_DIRECTORY_REF) { - val ref = if (from == LOCAL_DIRECTORY_REF) to else from - if (!isSafeRefArg(ref)) { + if (from is DiffSide.Local || to is DiffSide.Local) { + val rev = (if (from is DiffSide.Local) to else from) as DiffSide.Rev + if (!isSafeRefArg(rev.ref)) { return DiffScanPlan.Refused("diffUnknownRevisionNotification") } - return DiffScanPlan.Run(ScanTarget.Diff(DiffScanMode.LocalDiff, ref, projectRoot)) + return DiffScanPlan.Run(ScanTarget.Diff(DiffScanMode.LocalDiff, rev.ref, projectRoot)) } - return when (val result = git.getCommitRange(from, to)) { + // both sides are revisions here (two local sides were caught by the equality check above) + from as DiffSide.Rev + to as DiffSide.Rev + return when (val result = git.getCommitRange(from.ref, to.ref)) { is CommitRangeResult.Range -> DiffScanPlan.Run(ScanTarget.Diff(DiffScanMode.CommitRange, result.range, projectRoot)) CommitRangeResult.SameCommit -> DiffScanPlan.Refused("diffSameCommitNotification") CommitRangeResult.NoCommonHistory -> DiffScanPlan.Refused("diffNoCommonHistoryNotification") diff --git a/src/main/kotlin/com/cycode/plugin/git/DiffSide.kt b/src/main/kotlin/com/cycode/plugin/git/DiffSide.kt new file mode 100644 index 0000000..f0a32f1 --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/git/DiffSide.kt @@ -0,0 +1,8 @@ +package com.cycode.plugin.git + +/** One side of a diff scan: the local directory (uncommitted changes) or a revision (branch, tag or commit). */ +sealed interface DiffSide { + object Local : DiffSide + + data class Rev(val ref: String) : DiffSide +} diff --git a/src/main/kotlin/com/cycode/plugin/git/GitRepository.kt b/src/main/kotlin/com/cycode/plugin/git/GitCli.kt similarity index 97% rename from src/main/kotlin/com/cycode/plugin/git/GitRepository.kt rename to src/main/kotlin/com/cycode/plugin/git/GitCli.kt index 253809b..902acdb 100644 --- a/src/main/kotlin/com/cycode/plugin/git/GitRepository.kt +++ b/src/main/kotlin/com/cycode/plugin/git/GitCli.kt @@ -7,7 +7,6 @@ import com.intellij.openapi.diagnostic.thisLogger import java.io.File import java.nio.charset.StandardCharsets -const val LOCAL_DIRECTORY_REF = "\u0000local" const val HEAD_REF = "HEAD" const val LABEL_SEPARATOR = " │ " @@ -32,7 +31,7 @@ data class GitOutput(val exitCode: Int, val stdout: String, val stderr: String) * Git is invoked with an argv list (never a shell string); exit codes keep their git semantics * because the user-facing messages depend on them. */ -class GitRepository(private val workDirectory: String) { +class GitCli(private val workDirectory: String) { fun run(vararg args: String): GitOutput? { return try { val commandLine = GeneralCommandLine("git") @@ -173,7 +172,7 @@ class GitRepository(private val workDirectory: String) { } for (pinned in pinnedRefs) { - if (pinned == LOCAL_DIRECTORY_REF || pinned in listedValues || !isSafeRefArg(pinned)) continue + if (pinned in listedValues || !isSafeRefArg(pinned)) continue val (sha, _) = resolveCommit(pinned) if (sha == null) continue val subject = run("log", "-n", "1", "--format=%h%x09%s", sha)?.stdout?.split("\t", limit = 2) diff --git a/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt b/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt index b2a785a..ad641c7 100755 --- a/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt @@ -1,10 +1,6 @@ package com.cycode.plugin.services import com.cycode.plugin.cli.models.StatusResult -import com.cycode.plugin.git.DiffRefsCache -import com.cycode.plugin.git.HEAD_REF -import com.cycode.plugin.git.LOCAL_DIRECTORY_REF -import com.cycode.plugin.git.RefOption import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.thisLogger @@ -19,28 +15,6 @@ class CycodeTemporaryStateService { thisLogger().info("cliStatus set") } - // the "git is not available" message is shown once per session - @Volatile - var gitUnavailableNotified: Boolean = false - - // per-repository and therefore session-only; persisting them globally leaks picks between projects - @Volatile - var diffFromRef: String = LOCAL_DIRECTORY_REF - - @Volatile - var diffToRef: String = HEAD_REF - - // the revision lists and the git state they were built for (see GitRepository.getHeadFingerprint) - @Volatile - var diffRefsCache: DiffRefsCache? = null - - val diffRefs: List - get() = diffRefsCache?.refs ?: emptyList() - - // null until known; only an explicit "not a git repository" answer makes it false - @Volatile - var isGitRepository: Boolean? = null - val isSecretScanningEnabled: Boolean get() = cliStatus?.supportedModules?.secretScanning == true diff --git a/src/main/kotlin/com/cycode/plugin/services/DiffRefsService.kt b/src/main/kotlin/com/cycode/plugin/services/DiffRefsService.kt new file mode 100644 index 0000000..893a05d --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/services/DiffRefsService.kt @@ -0,0 +1,105 @@ +package com.cycode.plugin.services + +import com.cycode.plugin.CycodeBundle +import com.cycode.plugin.components.toolWindow.updateToolWindowState +import com.cycode.plugin.git.DiffRefsCache +import com.cycode.plugin.git.DiffSide +import com.cycode.plugin.git.GitCli +import com.cycode.plugin.git.HEAD_REF +import com.cycode.plugin.git.RefOption +import com.cycode.plugin.utils.CycodeNotifier +import com.intellij.openapi.application.ApplicationManager +import com.intellij.openapi.components.Service +import com.intellij.openapi.project.Project +import java.util.concurrent.atomic.AtomicLong + +/** + * Everything about git for the Diff scan scope: whether the project is a git repository, the two selected sides and + * the cached revision lists. All of it is per project and session-only. + */ +@Service(Service.Level.PROJECT) +class DiffRefsService(private val project: Project) { + private val cliService = cli(project) + private val refreshRequestId = AtomicLong() + + // per-repository and therefore session-only; persisting them globally leaks picks between projects + @Volatile + var from: DiffSide = DiffSide.Local + private set + + @Volatile + var to: DiffSide = DiffSide.Rev(HEAD_REF) + private set + + // the revision lists and the git state they were built for (see GitCli.getHeadFingerprint) + @Volatile + private var cache: DiffRefsCache? = null + + val refs: List + get() = cache?.refs ?: emptyList() + + // null until known; only an explicit "not a git repository" answer makes it false + @Volatile + var isGitRepository: Boolean? = null + private set + + // the "git is not available" message is shown once per session + @Volatile + private var gitUnavailableNotified = false + + fun setSides(from: DiffSide, to: DiffSide) { + this.from = from + this.to = to + } + + /** Checks in the background whether the project is a git repository; rebuilds the scan tab if that changed. */ + fun refreshGitRepositoryState() { + val projectRoot = cliService.getProjectRootDirectory() ?: return + + ApplicationManager.getApplication().executeOnPooledThread { + val isRepository = GitCli(projectRoot).isGitRepository() + if (!project.isDisposed && isRepository != isGitRepository) { + isGitRepository = isRepository + updateToolWindowState(project) + } + } + } + + /** + * Reloads the revision lists in the background and resets stale picks to the defaults. + * A request id drops results of superseded requests. + */ + fun refresh(onDone: (() -> Unit)? = null) { + val projectRoot = cliService.getProjectRootDirectory() ?: return + val requestId = refreshRequestId.incrementAndGet() + val pinned = listOf(from, to).filterIsInstance().map { it.ref } + + ApplicationManager.getApplication().executeOnPooledThread { + val git = GitCli(projectRoot) + + // the lists are rebuilt only when the branch changes or a commit is created + val fingerprint = git.getHeadFingerprint() + if (fingerprint == null && !gitUnavailableNotified && !git.isGitAvailable()) { + gitUnavailableNotified = true + CycodeNotifier.notifyInfo(project, CycodeBundle.message("diffGitUnavailableNotification")) + } + + val current = cache + val reuse = current != null && current.canReuse(fingerprint) + val refs = if (reuse) current!!.refs else git.getAvailableRefs(pinned) + if (requestId != refreshRequestId.get() || project.isDisposed) { + return@executeOnPooledThread + } + + val known = refs.map { it.value }.toSet() + if (from is DiffSide.Rev && (from as DiffSide.Rev).ref !in known) from = DiffSide.Local + if (to is DiffSide.Rev && (to as DiffSide.Rev).ref !in known) to = DiffSide.Rev(HEAD_REF) + // only a request that is still current may publish lists, together with the state they were built for + if (!reuse) cache = DiffRefsCache(fingerprint, refs) + + if (onDone != null) { + ApplicationManager.getApplication().invokeLater({ onDone() }, project.disposed) + } + } + } +} diff --git a/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt b/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt index 109a651..10e074e 100644 --- a/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt @@ -8,24 +8,18 @@ import com.cycode.plugin.cli.getScanTypeDisplayName import com.cycode.plugin.cli.isDiffScanSupportedByCli import com.cycode.plugin.cli.isFileSupportedByScanType import com.cycode.plugin.cli.partitionByFileSupport -import com.cycode.plugin.components.toolWindow.updateToolWindowState -import com.cycode.plugin.git.DiffRefsCache import com.cycode.plugin.git.DiffScanPlan -import com.cycode.plugin.git.GitRepository -import com.cycode.plugin.git.HEAD_REF -import com.cycode.plugin.git.LOCAL_DIRECTORY_REF +import com.cycode.plugin.git.GitCli import com.cycode.plugin.git.planDiffScan import com.cycode.plugin.utils.CycodeNotifier -import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project -import java.util.concurrent.atomic.AtomicLong /** - * The scan scope (Project / Diff / File): which scope is selected, the revisions of a diff scan and starting - * scans for the selected scope. + * The scan scope (Project / Diff / File): which scope is selected and starting scans for it. The git side of Diff + * (revisions, repository state) lives in [DiffRefsService]. */ @Service(Service.Level.PROJECT) class ScanScopeService(private val project: Project) { @@ -33,7 +27,7 @@ class ScanScopeService(private val project: Project) { private val cycodeService = cycode(project) private val pluginLocalState = pluginLocalState(project) private val projectState = projectState(project) - private val refreshRequestId = AtomicLong() + private val diffRefs = diffRefs(project) fun getScanScope(): ScanScope { return ScanScope.entries.firstOrNull { it.name == projectState.scanScope } ?: ScanScope.Project @@ -42,17 +36,14 @@ class ScanScopeService(private val project: Project) { fun setScanScope(scope: ScanScope) { projectState.scanScope = scope.name if (scope == ScanScope.Diff) { - refreshDiffRefs() + diffRefs.refresh() } } fun isDiffScanSupported(): Boolean = isDiffScanSupportedByCli(pluginLocalState.cliStatus?.version) - /** False only when the project folder is known not to be inside a git repository. */ - fun isGitRepository(): Boolean? = pluginLocalState.isGitRepository - /** Diff needs a new enough CLI and a git repository. */ - fun isDiffScanAvailable(): Boolean = isDiffScanSupported() && isGitRepository() != false + fun isDiffScanAvailable(): Boolean = isDiffScanSupported() && diffRefs.isGitRepository != false /** Until the CLI status is known (or if the CLI is too old or there is no repository), Diff behaves as Project. */ fun getEffectiveScanScope(): ScanScope { @@ -60,62 +51,6 @@ class ScanScopeService(private val project: Project) { return if (scope == ScanScope.Diff && !isDiffScanAvailable()) ScanScope.Project else scope } - /** Checks in the background whether the project is a git repository; rebuilds the scan tab if that changed. */ - fun refreshGitRepositoryState() { - val projectRoot = cliService.getProjectRootDirectory() ?: return - - ApplicationManager.getApplication().executeOnPooledThread { - val isRepository = GitRepository(projectRoot).isGitRepository() - if (!project.isDisposed && isRepository != pluginLocalState.isGitRepository) { - pluginLocalState.isGitRepository = isRepository - updateToolWindowState(project) - } - } - } - - fun setDiffRefs(from: String, to: String) { - pluginLocalState.diffFromRef = from - pluginLocalState.diffToRef = to - } - - /** - * Reloads the revision lists in the background and resets stale picks to the defaults. - * A request id drops results of superseded requests. - */ - fun refreshDiffRefs(onDone: (() -> Unit)? = null) { - val projectRoot = cliService.getProjectRootDirectory() ?: return - val requestId = refreshRequestId.incrementAndGet() - val pinned = listOf(pluginLocalState.diffFromRef, pluginLocalState.diffToRef) - - ApplicationManager.getApplication().executeOnPooledThread { - val git = GitRepository(projectRoot) - - // the lists are rebuilt only when the branch changes or a commit is created - val fingerprint = git.getHeadFingerprint() - if (fingerprint == null && !pluginLocalState.gitUnavailableNotified && !git.isGitAvailable()) { - pluginLocalState.gitUnavailableNotified = true - CycodeNotifier.notifyInfo(project, CycodeBundle.message("diffGitUnavailableNotification")) - } - - val cache = pluginLocalState.diffRefsCache - val reuse = cache != null && cache.canReuse(fingerprint) - val refs = if (reuse) cache!!.refs else git.getAvailableRefs(pinned) - if (requestId != refreshRequestId.get() || project.isDisposed) { - return@executeOnPooledThread - } - - val values = refs.map { it.value }.toSet() + LOCAL_DIRECTORY_REF - if (pluginLocalState.diffFromRef !in values) pluginLocalState.diffFromRef = LOCAL_DIRECTORY_REF - if (pluginLocalState.diffToRef !in values) pluginLocalState.diffToRef = HEAD_REF - // only a request that is still current may publish lists, together with the state they were built for - if (!reuse) pluginLocalState.diffRefsCache = DiffRefsCache(fingerprint, refs) - - if (onDone != null) { - ApplicationManager.getApplication().invokeLater({ onDone() }, project.disposed) - } - } - } - /** * Scans according to the selected scope. */ @@ -182,8 +117,8 @@ class ScanScopeService(private val project: Project) { } private fun startDiffScan(scanType: CliScanType) { - val from = pluginLocalState.diffFromRef - val to = pluginLocalState.diffToRef + val from = diffRefs.from + val to = diffRefs.to val projectRoot = cliService.getProjectRootDirectory() if (projectRoot == null) { @@ -197,7 +132,7 @@ class ScanScopeService(private val project: Project) { return@runBackgroundTask } - val target = when (val plan = planDiffScan(scanType, from, to, projectRoot, GitRepository(projectRoot))) { + val target = when (val plan = planDiffScan(scanType, from, to, projectRoot, GitCli(projectRoot))) { is DiffScanPlan.Run -> plan.target is DiffScanPlan.Refused -> { CycodeNotifier.notifyInfo(project, CycodeBundle.message(plan.messageKey)) diff --git a/src/main/kotlin/com/cycode/plugin/services/Services.kt b/src/main/kotlin/com/cycode/plugin/services/Services.kt index 99ccc3f..88b4b7c 100644 --- a/src/main/kotlin/com/cycode/plugin/services/Services.kt +++ b/src/main/kotlin/com/cycode/plugin/services/Services.kt @@ -34,3 +34,5 @@ fun cycode(project: Project? = null): CycodeService = getCycodeService(project) fun projectState(project: Project): CycodeProjectStateService = getCycodeService(project) fun scanScope(project: Project? = null): ScanScopeService = getCycodeService(project) + +fun diffRefs(project: Project): DiffRefsService = getCycodeService(project) diff --git a/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt b/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt index b549903..3cca8e7 100644 --- a/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt +++ b/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt @@ -4,8 +4,8 @@ import com.cycode.plugin.cli.CliScanType import com.cycode.plugin.cli.DiffScanMode import com.cycode.plugin.cli.ScanTarget import com.cycode.plugin.git.DiffScanPlan -import com.cycode.plugin.git.GitRepository -import com.cycode.plugin.git.LOCAL_DIRECTORY_REF +import com.cycode.plugin.git.GitCli +import com.cycode.plugin.git.DiffSide import com.cycode.plugin.git.planDiffScan import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue @@ -20,8 +20,11 @@ class DiffScanPlannerTest : GitTestBase() { commit("b") } - private fun plan(type: CliScanType, from: String, to: String, repo: GitRepository = git) = - planDiffScan(type, from, to, dir.path, repo) + // a side is either DiffSide.Local or the name of a revision + private fun side(value: Any): DiffSide = value as? DiffSide ?: DiffSide.Rev(value as String) + + private fun plan(type: CliScanType, from: Any, to: Any, repo: GitCli = git) = + planDiffScan(type, side(from), side(to), dir.path, repo) private val secret = CliScanType.Secret @@ -30,8 +33,8 @@ class DiffScanPlannerTest : GitTestBase() { val expected = DiffScanPlan.Run( ScanTarget.Diff(DiffScanMode.LocalDiff, "main", dir.path) ) - assertEquals(expected, plan(secret, LOCAL_DIRECTORY_REF, "main")) - assertEquals(expected, plan(secret, "main", LOCAL_DIRECTORY_REF)) + assertEquals(expected, plan(secret, DiffSide.Local, "main")) + assertEquals(expected, plan(secret, "main", DiffSide.Local)) } @Test @@ -48,8 +51,8 @@ class DiffScanPlannerTest : GitTestBase() { try { val expected = DiffScanPlan.Run(ScanTarget.Paths(listOf(dir.path))) val iac = CliScanType.Iac - assertEquals(expected, plan(iac, LOCAL_DIRECTORY_REF, "main")) - assertEquals(expected, plan(iac, "other", "main", GitRepository(plain.path))) + assertEquals(expected, plan(iac, DiffSide.Local, "main")) + assertEquals(expected, plan(iac, "other", "main", GitCli(plain.path))) } finally { plain.deleteRecursively() } @@ -60,7 +63,7 @@ class DiffScanPlannerTest : GitTestBase() { assertEquals(DiffScanPlan.Refused("diffSameRevisionNotification"), plan(secret, "main", "main")) assertEquals( DiffScanPlan.Refused("diffSameRevisionNotification"), - plan(secret, LOCAL_DIRECTORY_REF, LOCAL_DIRECTORY_REF) + plan(secret, DiffSide.Local, DiffSide.Local) ) } @@ -72,7 +75,7 @@ class DiffScanPlannerTest : GitTestBase() { try { assertEquals( DiffScanPlan.Refused("diffNotGitRepositoryNotification"), - plan(secret, LOCAL_DIRECTORY_REF, "main", GitRepository(plain.path)) + plan(secret, DiffSide.Local, "main", GitCli(plain.path)) ) } finally { plain.deleteRecursively() @@ -83,7 +86,7 @@ class DiffScanPlannerTest : GitTestBase() { fun unsafeRefsAreRefusedInBothFlavours() { assertEquals( DiffScanPlan.Refused("diffUnknownRevisionNotification"), - plan(secret, LOCAL_DIRECTORY_REF, "--output=x") + plan(secret, DiffSide.Local, "--output=x") ) assertEquals(DiffScanPlan.Refused("diffUnknownRevisionNotification"), plan(secret, "--output=x", "main")) } @@ -105,7 +108,7 @@ class DiffScanPlannerTest : GitTestBase() { @Test fun everyDiffScanTypeGetsAPlan() { CliScanType.entries.forEach { - assertTrue(plan(it, LOCAL_DIRECTORY_REF, "main") is DiffScanPlan.Run) + assertTrue(plan(it, DiffSide.Local, "main") is DiffScanPlan.Run) } } } diff --git a/src/test/kotlin/com/cycode/plugin/GitRepositoryTest.kt b/src/test/kotlin/com/cycode/plugin/GitCliTest.kt similarity index 86% rename from src/test/kotlin/com/cycode/plugin/GitRepositoryTest.kt rename to src/test/kotlin/com/cycode/plugin/GitCliTest.kt index 4595b3e..aeaf9f8 100644 --- a/src/test/kotlin/com/cycode/plugin/GitRepositoryTest.kt +++ b/src/test/kotlin/com/cycode/plugin/GitCliTest.kt @@ -5,7 +5,7 @@ import org.junit.Assert.* import org.junit.Test /** Uses real temporary git repositories: the exit-code semantics are the point. */ -class GitRepositoryTest : GitTestBase() { +class GitCliTest : GitTestBase() { private fun diverge() { sh("checkout", "-b", "feature") commit("feature-1") @@ -61,7 +61,7 @@ class GitRepositoryTest : GitTestBase() { fun nonGitFolder() { val plain = createPlainDirectory() try { - assertFalse(GitRepository(plain.path).isGitRepository()) + assertFalse(GitCli(plain.path).isGitRepository()) assertTrue(git.isGitRepository()) } finally { plain.deleteRecursively() @@ -84,20 +84,20 @@ class GitRepositoryTest : GitTestBase() { @Test fun labelFormat() { - assertEquals("main │ abc123 │ subject", GitRepository.buildLabel("main", "abc123", "subject")) + assertEquals("main │ abc123 │ subject", GitCli.buildLabel("main", "abc123", "subject")) } @Test fun refListsAreCapped() { - repeat(GitRepository.MAX_REFS + 5) { sh("branch", "b$it") } - repeat(GitRepository.MAX_COMMITS + 5) { commit("c$it") } + repeat(GitCli.MAX_REFS + 5) { sh("branch", "b$it") } + repeat(GitCli.MAX_COMMITS + 5) { commit("c$it") } val refs = git.getAvailableRefs() val sha = Regex("[0-9a-f]{40}") val branchesAndTags = refs.count { it.value != HEAD_REF && !sha.matches(it.value) } - assertTrue(branchesAndTags <= GitRepository.MAX_REFS) + assertTrue(branchesAndTags <= GitCli.MAX_REFS) // HEAD + capped refs + capped commits - assertTrue(refs.size <= 1 + GitRepository.MAX_REFS + GitRepository.MAX_COMMITS) + assertTrue(refs.size <= 1 + GitCli.MAX_REFS + GitCli.MAX_COMMITS) } @Test @@ -151,11 +151,10 @@ class GitRepositoryTest : GitTestBase() { @Test fun pinnedRefThatScrolledOutOfTheListIsKept() { val oldest = sh("rev-parse", "HEAD") - repeat(GitRepository.MAX_COMMITS + 5) { commit("c$it") } - val refs = git.getAvailableRefs(listOf(oldest, LOCAL_DIRECTORY_REF, "HEAD")) + repeat(GitCli.MAX_COMMITS + 5) { commit("c$it") } + val refs = git.getAvailableRefs(listOf(oldest, "HEAD")) assertEquals(1, refs.count { it.value == oldest }) assertEquals(1, refs.count { it.value == HEAD_REF }) - assertFalse(refs.any { it.value == LOCAL_DIRECTORY_REF }) } @Test @@ -165,8 +164,8 @@ class GitRepositoryTest : GitTestBase() { @Test fun labelWithoutRefNameOrSubject() { - assertEquals("abc123", GitRepository.buildLabel(null, "abc123", "")) - assertEquals("abc123 │ subject", GitRepository.buildLabel("", "abc123", "subject")) + assertEquals("abc123", GitCli.buildLabel(null, "abc123", "")) + assertEquals("abc123 │ subject", GitCli.buildLabel("", "abc123", "subject")) } @Test @@ -189,7 +188,7 @@ class GitRepositoryTest : GitTestBase() { fun headFingerprintIsNullOutsideARepository() { val plain = createPlainDirectory() try { - assertNull(GitRepository(plain.path).getHeadFingerprint()) + assertNull(GitCli(plain.path).getHeadFingerprint()) } finally { plain.deleteRecursively() } diff --git a/src/test/kotlin/com/cycode/plugin/GitTestBase.kt b/src/test/kotlin/com/cycode/plugin/GitTestBase.kt index f53d163..2283bd3 100644 --- a/src/test/kotlin/com/cycode/plugin/GitTestBase.kt +++ b/src/test/kotlin/com/cycode/plugin/GitTestBase.kt @@ -1,6 +1,6 @@ package com.cycode.plugin -import com.cycode.plugin.git.GitRepository +import com.cycode.plugin.git.GitCli import org.junit.After import org.junit.Before import java.io.File @@ -12,7 +12,7 @@ import java.nio.file.Files */ abstract class GitTestBase { protected lateinit var dir: File - protected lateinit var git: GitRepository + protected lateinit var git: GitCli protected fun sh(vararg args: String): String { // signing and the user's global config must not influence the tests @@ -40,7 +40,7 @@ abstract class GitTestBase { sh("init") sh("symbolic-ref", "HEAD", "refs/heads/main") // `init -b` needs git 2.28 commit("base") - git = GitRepository(dir.path) + git = GitCli(dir.path) } @After From 3ce33c8c0381cb360869236d0e6e51bb0777b60a Mon Sep 17 00:00:00 2001 From: Aaron Butler Date: Thu, 19 Nov 2026 16:47:54 -0500 Subject: [PATCH 3/4] CM-77192: share the enabled scan type list, merge file scan paths, check custom CLI version once Co-Authored-By: Claude Sonnet 5.5 --- src/main/kotlin/com/cycode/plugin/Consts.kt | 1 - .../com/cycode/plugin/cli/CliVersion.kt | 18 ++++++ .../kotlin/com/cycode/plugin/cli/DiffScan.kt | 23 -------- .../scanContentTab/ScanContentTab.kt | 36 +++++------- .../plugin/listeners/FileSaveListener.kt | 6 +- .../com/cycode/plugin/services/CliService.kt | 19 ++++++ .../services/CycodeTemporaryStateService.kt | 16 +++++ .../plugin/services/ScanScopeService.kt | 58 +++++-------------- .../messages/CycodeBundle.properties | 1 + .../kotlin/com/cycode/plugin/DiffScanTest.kt | 3 - 10 files changed, 86 insertions(+), 95 deletions(-) create mode 100644 src/main/kotlin/com/cycode/plugin/cli/CliVersion.kt diff --git a/src/main/kotlin/com/cycode/plugin/Consts.kt b/src/main/kotlin/com/cycode/plugin/Consts.kt index 96903e1..57783d1 100644 --- a/src/main/kotlin/com/cycode/plugin/Consts.kt +++ b/src/main/kotlin/com/cycode/plugin/Consts.kt @@ -21,7 +21,6 @@ class Consts { val PLUGIN_PATH = PathManager.getPluginsPath() + "/cycode-intellij-platform-plugin" val DEFAULT_CLI_PATH = getDefaultCliPath() const val REQUIRED_CLI_VERSION = "3.25.0" - const val MIN_CLI_VERSION_FOR_DIFF_SCAN = "3.25.0" const val CYCODE_DOMAIN = "cycode.com" diff --git a/src/main/kotlin/com/cycode/plugin/cli/CliVersion.kt b/src/main/kotlin/com/cycode/plugin/cli/CliVersion.kt new file mode 100644 index 0000000..dc9cc40 --- /dev/null +++ b/src/main/kotlin/com/cycode/plugin/cli/CliVersion.kt @@ -0,0 +1,18 @@ +package com.cycode.plugin.cli + +/** Compares only the first three numeric segments; dev builds look like `0.0.1.dev498`. */ +fun isVersionAtLeast(version: String, minVersion: String): Boolean { + fun parse(value: String) = value.trim().removePrefix("v").split(".").take(3) + .map { segment -> segment.takeWhile { it.isDigit() }.toIntOrNull() ?: 0 } + .let { it + List(3 - it.size) { 0 } } + + val actual = parse(version) + val required = parse(minVersion) + for (i in 0 until 3) { + if (actual[i] != required[i]) { + return actual[i] > required[i] + } + } + + return true +} diff --git a/src/main/kotlin/com/cycode/plugin/cli/DiffScan.kt b/src/main/kotlin/com/cycode/plugin/cli/DiffScan.kt index 7a1d8c4..a974182 100644 --- a/src/main/kotlin/com/cycode/plugin/cli/DiffScan.kt +++ b/src/main/kotlin/com/cycode/plugin/cli/DiffScan.kt @@ -1,7 +1,5 @@ package com.cycode.plugin.cli -import com.cycode.plugin.Consts - enum class ScanScope { Project, Diff, File } @@ -42,24 +40,3 @@ fun assertSafeRefArg(ref: String) { } fun isSafeRefArg(ref: String): Boolean = ref.isNotEmpty() && !ref.startsWith("-") && ref.none { it.isISOControl() } - -/** Compares only the first three numeric segments; dev builds look like `0.0.1.dev498`. */ -fun isVersionAtLeast(version: String, minVersion: String): Boolean { - fun parse(value: String) = value.trim().removePrefix("v").split(".").take(3) - .map { segment -> segment.takeWhile { it.isDigit() }.toIntOrNull() ?: 0 } - .let { it + List(3 - it.size) { 0 } } - - val actual = parse(version) - val required = parse(minVersion) - for (i in 0 until 3) { - if (actual[i] != required[i]) { - return actual[i] > required[i] - } - } - - return true -} - -fun isDiffScanSupportedByCli(cliVersion: String?): Boolean { - return cliVersion != null && isVersionAtLeast(cliVersion, Consts.MIN_CLI_VERSION_FOR_DIFF_SCAN) -} diff --git a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt index 176706f..ea610f2 100644 --- a/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt +++ b/src/main/kotlin/com/cycode/plugin/components/toolWindow/components/scanContentTab/ScanContentTab.kt @@ -10,6 +10,7 @@ import com.cycode.plugin.git.HEAD_REF import com.cycode.plugin.git.DiffSide import com.cycode.plugin.git.RefOption import com.cycode.plugin.services.CycodeService +import com.cycode.plugin.services.CycodeTemporaryStateService import com.cycode.plugin.services.diffRefs import com.cycode.plugin.services.pluginLocalState import com.cycode.plugin.services.scanScope @@ -51,18 +52,9 @@ class ScanContentTab : Component() { addComponentToPanel(createClickableLabel(CycodeBundle.message("scanTabTitleLabel"))) addScopeControls(service) - addComponentToPanel(createScanButton(service, CliScanType.Secret, "scanTabSecretsBtn") { - pluginLocalState.isSecretScanningEnabled - }) - addComponentToPanel(createScanButton(service, CliScanType.Sca, "scanTabScaBtn") { - pluginLocalState.isScaScanningEnabled - }) - addComponentToPanel(createScanButton(service, CliScanType.Iac, "scanTabIacBtn") { - pluginLocalState.isIacScanningEnabled - }) - addComponentToPanel(createScanButton(service, CliScanType.Sast, "scanTabSastBtn") { - pluginLocalState.isSastScanningEnabled - }) + CycodeTemporaryStateService.SCAN_TYPES_IN_ORDER.forEach { scanType -> + addComponentToPanel(createScanButton(service, scanType, pluginLocalState.isScanTypeEnabled(scanType))) + } addComponentToPanel(createClickableLabel(CycodeBundle.message("scanTabOnSaveTip"))) addComponentToPanel(createClickableLabel(CycodeBundle.message("howToUseLabel"))) @@ -70,14 +62,15 @@ class ScanContentTab : Component() { return panel } - private fun createScanButton( - service: CycodeService, - scanType: CliScanType, - key: String, - isModuleEnabled: () -> Boolean - ): JButton { + private fun createScanButton(service: CycodeService, scanType: CliScanType, enabled: Boolean): JButton { + val key = when (scanType) { + CliScanType.Secret -> "scanTabSecretsBtn" + CliScanType.Sca -> "scanTabScaBtn" + CliScanType.Iac -> "scanTabIacBtn" + CliScanType.Sast -> "scanTabSastBtn" + } return JButton(CycodeBundle.message(key)).apply { - isEnabled = isModuleEnabled() + isEnabled = enabled addActionListener { scanScope(service.project).startScanForCurrentScope(scanType) } } } @@ -98,7 +91,6 @@ class ScanContentTab : Component() { val effectiveScope = scopeService.getEffectiveScanScope() val diffRefs = diffRefs(service.project) val isGitRepository = diffRefs.isGitRepository - val scopes = ScanScope.entries.filter { it != ScanScope.Diff || scopeService.isDiffScanSupported() } // Diff is disabled when this turns out not to be a git repository; the tab is rebuilt if that changes diffRefs.refreshGitRepositoryState() @@ -107,7 +99,7 @@ class ScanContentTab : Component() { val group = ButtonGroup() val radioPanel = JPanel(FlowLayout(FlowLayout.LEFT, 0, 0)) - scopes.forEach { scope -> + ScanScope.entries.forEach { scope -> val radio = JBRadioButton(CycodeBundle.message("scanScope${scope.name}"), scope == effectiveScope).apply { // Diff cannot work without a git repository isEnabled = scope != ScanScope.Diff || isGitRepository != false @@ -124,7 +116,7 @@ class ScanContentTab : Component() { } addComponentToPanel(radioPanel) addComponentToPanel(createNote(CycodeBundle.message("scanScope${effectiveScope.name}Hint"))) - if (scopes.contains(ScanScope.Diff) && isGitRepository == false) { + if (isGitRepository == false) { addComponentToPanel(createNote(CycodeBundle.message("scanScopeDiffNoGitNote"), AllIcons.General.Warning)) } diff --git a/src/main/kotlin/com/cycode/plugin/listeners/FileSaveListener.kt b/src/main/kotlin/com/cycode/plugin/listeners/FileSaveListener.kt index b156e32..abc2fa8 100644 --- a/src/main/kotlin/com/cycode/plugin/listeners/FileSaveListener.kt +++ b/src/main/kotlin/com/cycode/plugin/listeners/FileSaveListener.kt @@ -37,17 +37,17 @@ class FileSaveListener(private val project: Project) : FileDocumentManagerListen return } - if (pluginLocalState.isSecretScanningEnabled && pathsToScan.isNotEmpty()) { + if (pluginLocalState.isScanTypeEnabled(CliScanType.Secret) && pathsToScan.isNotEmpty()) { service.startScan(CliScanType.Secret, pathsToScan, onDemand = false) } val scaPathsToScan = excludeNonScaRelatedPaths(pathsToScan) - if (pluginLocalState.isScaScanningEnabled && scaPathsToScan.isNotEmpty()) { + if (pluginLocalState.isScanTypeEnabled(CliScanType.Sca) && scaPathsToScan.isNotEmpty()) { service.startScan(CliScanType.Sca, scaPathsToScan, onDemand = false) } val iacPathsToScan = excludeNonIacRelatedPaths(pathsToScan) - if (pluginLocalState.isIacScanningEnabled && iacPathsToScan.isNotEmpty()) { + if (pluginLocalState.isScanTypeEnabled(CliScanType.Iac) && iacPathsToScan.isNotEmpty()) { service.startScan(CliScanType.Iac, iacPathsToScan, onDemand = false) } } diff --git a/src/main/kotlin/com/cycode/plugin/services/CliService.kt b/src/main/kotlin/com/cycode/plugin/services/CliService.kt index 54008cb..9c87057 100644 --- a/src/main/kotlin/com/cycode/plugin/services/CliService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/CliService.kt @@ -1,5 +1,6 @@ package com.cycode.plugin.services +import com.cycode.plugin.Consts import com.cycode.plugin.CycodeBundle import com.cycode.plugin.cli.* import com.cycode.plugin.cli.models.AiRemediationResult @@ -30,6 +31,7 @@ class CliService(private val project: Project) { private val pluginLocalState = pluginLocalState(project) private val scanResults = scanResults(project) private val cli = CliWrapper(getProjectRootDirectory()) + private var outdatedCliNotified = false fun getProjectRootDirectory(): String? { val modules = ModuleManager.getInstance(project).modules @@ -112,9 +114,26 @@ class CliService(private val project: Project) { showErrorNotification(CycodeBundle.message("checkAuthErrorNotification")) } + notifyIfCustomCliIsOutdated(processedResult.result.version) + return } + /** A plugin-managed CLI is always at the required version; a user-provided one may be older. */ + private fun notifyIfCustomCliIsOutdated(version: String) { + if (pluginSettings().cliAutoManaged || outdatedCliNotified) { + return + } + + if (!isVersionAtLeast(version, Consts.REQUIRED_CLI_VERSION)) { + outdatedCliNotified = true + CycodeNotifier.notifyInfo( + project, + CycodeBundle.message("customCliOutdatedNotification", Consts.REQUIRED_CLI_VERSION) + ) + } + } + fun startAuth(cancelledCallback: TaskCancelledCallback = null): Boolean { val result: CliResult = cli.executeCommand( diff --git a/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt b/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt index ad641c7..c603ea5 100755 --- a/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/CycodeTemporaryStateService.kt @@ -1,5 +1,6 @@ package com.cycode.plugin.services +import com.cycode.plugin.cli.CliScanType import com.cycode.plugin.cli.models.StatusResult import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.thisLogger @@ -27,10 +28,25 @@ class CycodeTemporaryStateService { val isSastScanningEnabled: Boolean get() = cliStatus?.supportedModules?.sastScanning == true + fun isScanTypeEnabled(type: CliScanType): Boolean = when (type) { + CliScanType.Secret -> isSecretScanningEnabled + CliScanType.Sca -> isScaScanningEnabled + CliScanType.Iac -> isIacScanningEnabled + CliScanType.Sast -> isSastScanningEnabled + } + + /** Scan types enabled for the tenant, in the order the scan buttons are shown. */ + val enabledScanTypes: List + get() = SCAN_TYPES_IN_ORDER.filter { isScanTypeEnabled(it) } + val isAiLargeLanguageModelEnabled: Boolean get() = cliStatus?.supportedModules?.aiLargeLanguageModel == true init { thisLogger().info("CycodeTemporaryStateService init") } + + companion object { + val SCAN_TYPES_IN_ORDER = listOf(CliScanType.Secret, CliScanType.Sca, CliScanType.Iac, CliScanType.Sast) + } } diff --git a/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt b/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt index 10e074e..56e5c72 100644 --- a/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt @@ -5,8 +5,6 @@ import com.cycode.plugin.cli.ScanScope import com.cycode.plugin.cli.ScanTarget import com.cycode.plugin.cli.CliScanType import com.cycode.plugin.cli.getScanTypeDisplayName -import com.cycode.plugin.cli.isDiffScanSupportedByCli -import com.cycode.plugin.cli.isFileSupportedByScanType import com.cycode.plugin.cli.partitionByFileSupport import com.cycode.plugin.git.DiffScanPlan import com.cycode.plugin.git.GitCli @@ -40,12 +38,10 @@ class ScanScopeService(private val project: Project) { } } - fun isDiffScanSupported(): Boolean = isDiffScanSupportedByCli(pluginLocalState.cliStatus?.version) + /** Diff needs a git repository. */ + fun isDiffScanAvailable(): Boolean = diffRefs.isGitRepository != false - /** Diff needs a new enough CLI and a git repository. */ - fun isDiffScanAvailable(): Boolean = isDiffScanSupported() && diffRefs.isGitRepository != false - - /** Until the CLI status is known (or if the CLI is too old or there is no repository), Diff behaves as Project. */ + /** Without a git repository Diff behaves as Project. */ fun getEffectiveScanScope(): ScanScope { val scope = getScanScope() return if (scope == ScanScope.Diff && !isDiffScanAvailable()) ScanScope.Project else scope @@ -57,39 +53,17 @@ class ScanScopeService(private val project: Project) { fun startScanForCurrentScope(scanType: CliScanType) { when (getEffectiveScanScope()) { ScanScope.Project -> cycodeService.startScanForCurrentProject(scanType) - ScanScope.File -> startScanForCurrentFile(scanType) + ScanScope.File -> startFileScan(listOf(scanType)) ScanScope.Diff -> startDiffScan(scanType) } } /** Runs every scan type enabled for the tenant, according to the selected scope. */ fun startAllScansForCurrentScope() { - // without an open file every scan type would show the same message: say it once - if (getEffectiveScanScope() == ScanScope.File && currentLocalFilePath() == null) { - CycodeNotifier.notifyInfo(project, CycodeBundle.message("noOpenFileErrorNotification")) - return - } - - val local = pluginLocalState - val scanTypes = listOf( - CliScanType.Secret to local.isSecretScanningEnabled, - CliScanType.Sca to local.isScaScanningEnabled, - CliScanType.Sast to local.isSastScanningEnabled, - CliScanType.Iac to local.isIacScanningEnabled, - ).filter { it.second }.map { it.first } - - if (getEffectiveScanScope() != ScanScope.File) { - scanTypes.forEach { startScanForCurrentScope(it) } - return - } - - // one combined message for the types that cannot scan the open file, instead of one per type - val filePath = currentLocalFilePath() ?: return - val (supported, unsupported) = partitionByFileSupport(filePath, scanTypes) - supported.forEach { cycodeService.startScan(it, listOf(filePath)) } - if (unsupported.isNotEmpty()) { - val names = unsupported.joinToString(", ") { getScanTypeDisplayName(it) } - CycodeNotifier.notifyInfo(project, CycodeBundle.message("scanFileUnsupportedNotification", names)) + val scanTypes = pluginLocalState.enabledScanTypes + when (getEffectiveScanScope()) { + ScanScope.File -> startFileScan(scanTypes) + else -> scanTypes.forEach { startScanForCurrentScope(it) } } } @@ -98,22 +72,20 @@ class ScanScopeService(private val project: Project) { return file?.takeIf { it.isInLocalFileSystem }?.canonicalPath } - private fun startScanForCurrentFile(scanType: CliScanType) { + /** Scans the open file with the types that support it, with one combined message for the rest. */ + private fun startFileScan(scanTypes: List) { val filePath = currentLocalFilePath() if (filePath == null) { CycodeNotifier.notifyInfo(project, CycodeBundle.message("noOpenFileErrorNotification")) return } - if (!isFileSupportedByScanType(filePath, scanType)) { - CycodeNotifier.notifyInfo( - project, - CycodeBundle.message("scanFileUnsupportedNotification", getScanTypeDisplayName(scanType)) - ) - return + val (supported, unsupported) = partitionByFileSupport(filePath, scanTypes) + supported.forEach { cycodeService.startScan(it, listOf(filePath)) } + if (unsupported.isNotEmpty()) { + val names = unsupported.joinToString(", ") { getScanTypeDisplayName(it) } + CycodeNotifier.notifyInfo(project, CycodeBundle.message("scanFileUnsupportedNotification", names)) } - - cycodeService.startScan(scanType, listOf(filePath)) } private fun startDiffScan(scanType: CliScanType) { diff --git a/src/main/resources/messages/CycodeBundle.properties b/src/main/resources/messages/CycodeBundle.properties index ce31124..c46cea5 100755 --- a/src/main/resources/messages/CycodeBundle.properties +++ b/src/main/resources/messages/CycodeBundle.properties @@ -26,6 +26,7 @@ violationCardIntentionText=Cycode: {0} ({1}) notificationGroupId=Cycode notificationTitle=Cycode checkAuthErrorNotification=You are not authenticated in Cycode. Please authenticate +customCliOutdatedNotification=The Cycode CLI you configured is older than the required version {0}. Some features may not work. Please upgrade it or enable automatic CLI management in the settings. authErrorNotification=Authentication failed. Please try again missingCStandardLibraryErrorNotification=Plugin requires C standard library (libc/glibc) to be installed. Please install it and restart the IDE. unknownErrorNotification=Unknown error occurred. Please try again diff --git a/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt b/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt index f245d4a..a2dc224 100644 --- a/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt +++ b/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt @@ -43,7 +43,6 @@ class DiffScanTest { assertTrue(isVersionAtLeast("4.0.0", "3.25.0")) assertFalse(isVersionAtLeast("3.24.9", "3.25.0")) assertFalse(isVersionAtLeast("0.0.1.dev498", "3.25.0")) - assertFalse(isDiffScanSupportedByCli(null)) } @Test @@ -75,8 +74,6 @@ class DiffScanTest { assertTrue(isVersionAtLeast("10.0.0", "3.25.0")) assertFalse(isVersionAtLeast("", "3.25.0")) assertFalse(isVersionAtLeast("garbage", "3.25.0")) - assertTrue(isDiffScanSupportedByCli("3.26.0")) - assertFalse(isDiffScanSupportedByCli("3.21.0")) } @Test From 70adef48f6e09ed1705cdbec88a1070ea6b48217 Mon Sep 17 00:00:00 2001 From: Aaron Butler Date: Wed, 25 Nov 2026 09:11:10 -0500 Subject: [PATCH 4/4] CM-77192: run diff scans through startScan, validate revisions once, drop the refs cache Co-Authored-By: Claude Sonnet 5.5 --- README.md | 5 +- .../com/cycode/plugin/cli/CliVersion.kt | 18 ------ .../com/cycode/plugin/git/DiffRefsCache.kt | 12 ---- .../com/cycode/plugin/git/DiffScanPlanner.kt | 6 +- .../kotlin/com/cycode/plugin/git/DiffSide.kt | 9 ++- .../kotlin/com/cycode/plugin/git/GitCli.kt | 26 ++------ .../com/cycode/plugin/services/CliService.kt | 3 +- .../cycode/plugin/services/CycodeService.kt | 18 ++++-- .../cycode/plugin/services/DiffRefsService.kt | 23 +++---- .../plugin/services/ScanScopeService.kt | 17 +---- .../com/cycode/plugin/DiffScanPlannerTest.kt | 9 --- .../kotlin/com/cycode/plugin/DiffScanTest.kt | 23 +------ .../kotlin/com/cycode/plugin/GitCliTest.kt | 64 +++++-------------- .../com/cycode/plugin/ScanScopeLogicTest.kt | 29 --------- 14 files changed, 64 insertions(+), 198 deletions(-) delete mode 100644 src/main/kotlin/com/cycode/plugin/cli/CliVersion.kt delete mode 100644 src/main/kotlin/com/cycode/plugin/git/DiffRefsCache.kt diff --git a/README.md b/README.md index 3ec1889..c194a97 100644 --- a/README.md +++ b/README.md @@ -93,8 +93,9 @@ In the Cycode tool window, choose what the scan buttons and **Scan all** run on: Local directory compared with HEAD. Two different revisions are required. * Scanning only the changes is faster, but vulnerabilities that need the surrounding code may be less accurate. * Infrastructure As Code scans do not support diffs and always scan the full project. - * The project must be inside a Git repository (otherwise Diff is disabled), and Cycode CLI 3.25.0 or later is - required (otherwise the Diff option is hidden). + * The project must be inside a Git repository (otherwise Diff is disabled). Diff needs Cycode CLI 3.25.0 or later: + with a custom CLI that is older, the plugin shows one notification asking you to upgrade it or to turn + automatic CLI management back on. * **File** - scans only the file open in the editor. Package vulnerability and Infrastructure As Code scans only run for the file types they support. diff --git a/src/main/kotlin/com/cycode/plugin/cli/CliVersion.kt b/src/main/kotlin/com/cycode/plugin/cli/CliVersion.kt deleted file mode 100644 index dc9cc40..0000000 --- a/src/main/kotlin/com/cycode/plugin/cli/CliVersion.kt +++ /dev/null @@ -1,18 +0,0 @@ -package com.cycode.plugin.cli - -/** Compares only the first three numeric segments; dev builds look like `0.0.1.dev498`. */ -fun isVersionAtLeast(version: String, minVersion: String): Boolean { - fun parse(value: String) = value.trim().removePrefix("v").split(".").take(3) - .map { segment -> segment.takeWhile { it.isDigit() }.toIntOrNull() ?: 0 } - .let { it + List(3 - it.size) { 0 } } - - val actual = parse(version) - val required = parse(minVersion) - for (i in 0 until 3) { - if (actual[i] != required[i]) { - return actual[i] > required[i] - } - } - - return true -} diff --git a/src/main/kotlin/com/cycode/plugin/git/DiffRefsCache.kt b/src/main/kotlin/com/cycode/plugin/git/DiffRefsCache.kt deleted file mode 100644 index e0d6030..0000000 --- a/src/main/kotlin/com/cycode/plugin/git/DiffRefsCache.kt +++ /dev/null @@ -1,12 +0,0 @@ -package com.cycode.plugin.git - -/** - * The revision lists together with the git state they were built for. Kept as one immutable object so a list can - * never be paired with the fingerprint of a different state. - */ -data class DiffRefsCache(val fingerprint: String?, val refs: List) { - /** Reusable only when git state is known, unchanged since the lists were built, and there is something to show. */ - fun canReuse(currentFingerprint: String?): Boolean { - return currentFingerprint != null && currentFingerprint == fingerprint && refs.isNotEmpty() - } -} diff --git a/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt b/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt index e4976df..88fc53c 100644 --- a/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt +++ b/src/main/kotlin/com/cycode/plugin/git/DiffScanPlanner.kt @@ -3,7 +3,6 @@ package com.cycode.plugin.git import com.cycode.plugin.cli.CliScanType import com.cycode.plugin.cli.DiffScanMode import com.cycode.plugin.cli.ScanTarget -import com.cycode.plugin.cli.isSafeRefArg import com.cycode.plugin.cli.supportsDiffScan sealed class DiffScanPlan { @@ -33,16 +32,13 @@ fun planDiffScan(scanType: CliScanType, from: DiffSide, to: DiffSide, projectRoo if (from is DiffSide.Local || to is DiffSide.Local) { val rev = (if (from is DiffSide.Local) to else from) as DiffSide.Rev - if (!isSafeRefArg(rev.ref)) { - return DiffScanPlan.Refused("diffUnknownRevisionNotification") - } return DiffScanPlan.Run(ScanTarget.Diff(DiffScanMode.LocalDiff, rev.ref, projectRoot)) } // both sides are revisions here (two local sides were caught by the equality check above) from as DiffSide.Rev to as DiffSide.Rev - return when (val result = git.getCommitRange(from.ref, to.ref)) { + return when (val result = git.getCommitRange(from, to)) { is CommitRangeResult.Range -> DiffScanPlan.Run(ScanTarget.Diff(DiffScanMode.CommitRange, result.range, projectRoot)) CommitRangeResult.SameCommit -> DiffScanPlan.Refused("diffSameCommitNotification") CommitRangeResult.NoCommonHistory -> DiffScanPlan.Refused("diffNoCommonHistoryNotification") diff --git a/src/main/kotlin/com/cycode/plugin/git/DiffSide.kt b/src/main/kotlin/com/cycode/plugin/git/DiffSide.kt index f0a32f1..e33afb1 100644 --- a/src/main/kotlin/com/cycode/plugin/git/DiffSide.kt +++ b/src/main/kotlin/com/cycode/plugin/git/DiffSide.kt @@ -1,8 +1,15 @@ package com.cycode.plugin.git +import com.cycode.plugin.cli.assertSafeRefArg + /** One side of a diff scan: the local directory (uncommitted changes) or a revision (branch, tag or commit). */ sealed interface DiffSide { object Local : DiffSide - data class Rev(val ref: String) : DiffSide + /** The only place a revision enters the model: an unsafe value (e.g. `--output=x`) can never get further. */ + data class Rev(val ref: String) : DiffSide { + init { + assertSafeRefArg(ref) + } + } } diff --git a/src/main/kotlin/com/cycode/plugin/git/GitCli.kt b/src/main/kotlin/com/cycode/plugin/git/GitCli.kt index 902acdb..bca9bfc 100644 --- a/src/main/kotlin/com/cycode/plugin/git/GitCli.kt +++ b/src/main/kotlin/com/cycode/plugin/git/GitCli.kt @@ -56,16 +56,6 @@ class GitCli(private val workDirectory: String) { return output != null && output.exitCode == 0 } - /** - * Changes when the checked out branch changes or a commit is created on it. Null if git could not tell. - * Used to cache the revision lists, which are expensive to build. - */ - fun getHeadFingerprint(): String? { - val sha = run("rev-parse", "HEAD")?.takeIf { it.exitCode == 0 }?.stdout ?: return null - val branch = run("symbolic-ref", "-q", "HEAD")?.takeIf { it.exitCode == 0 }?.stdout ?: HEAD_REF - return "$branch@$sha" - } - /** Only an explicit "not a git repository" answer returns false; other failures are left to later steps. */ fun isGitRepository(): Boolean { val output = run("rev-parse", "--is-inside-work-tree") ?: return true @@ -94,14 +84,10 @@ class GitCli(private val workDirectory: String) { * Plain `from..to` is empty when picked newest-first, and `from...to` would also scan commits * that landed on the other branch since divergence. */ - fun getCommitRange(from: String, to: String): CommitRangeResult { - if (!isSafeRefArg(from) || !isSafeRefArg(to)) { - return CommitRangeResult.UnknownRevision - } - - val (fromSha, fromError) = resolveCommit(from) + fun getCommitRange(from: DiffSide.Rev, to: DiffSide.Rev): CommitRangeResult { + val (fromSha, fromError) = resolveCommit(from.ref) if (fromSha == null) return fromError!! - val (toSha, toError) = resolveCommit(to) + val (toSha, toError) = resolveCommit(to.ref) if (toSha == null) return toError!! if (fromSha == toSha) { @@ -130,7 +116,7 @@ class GitCli(private val workDirectory: String) { * HEAD first, then branches/tags, then recent commits, plus any [pinnedRefs] (the user's selection) * that scrolled out of the lists but still resolve. The caps are deliberate for now. */ - fun getAvailableRefs(pinnedRefs: List = emptyList()): List { + fun getAvailableRefs(pinnedRefs: List = emptyList()): List { val options = mutableListOf() val listedValues = mutableSetOf() val listedShas = mutableSetOf() @@ -171,8 +157,8 @@ class GitCli(private val workDirectory: String) { } } - for (pinned in pinnedRefs) { - if (pinned in listedValues || !isSafeRefArg(pinned)) continue + for ((pinned) in pinnedRefs) { + if (pinned in listedValues) continue val (sha, _) = resolveCommit(pinned) if (sha == null) continue val subject = run("log", "-n", "1", "--format=%h%x09%s", sha)?.stdout?.split("\t", limit = 2) diff --git a/src/main/kotlin/com/cycode/plugin/services/CliService.kt b/src/main/kotlin/com/cycode/plugin/services/CliService.kt index 9c87057..3f6bd3d 100644 --- a/src/main/kotlin/com/cycode/plugin/services/CliService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/CliService.kt @@ -21,6 +21,7 @@ import com.intellij.openapi.components.Service import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project +import com.intellij.util.text.VersionComparatorUtil typealias TaskCancelledCallback = (() -> Boolean)? @@ -125,7 +126,7 @@ class CliService(private val project: Project) { return } - if (!isVersionAtLeast(version, Consts.REQUIRED_CLI_VERSION)) { + if (VersionComparatorUtil.compare(version, Consts.REQUIRED_CLI_VERSION) < 0) { outdatedCliNotified = true CycodeNotifier.notifyInfo( project, diff --git a/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt b/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt index a453db0..64b3ed9 100755 --- a/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/CycodeService.kt @@ -62,7 +62,7 @@ class CycodeService(val project: Project) : Disposable { } } - fun getBackgroundScanningLabel(scanType: CliScanType) = when (scanType) { + private fun getBackgroundScanningLabel(scanType: CliScanType) = when (scanType) { CliScanType.Secret -> CycodeBundle.message("secretScanning") CliScanType.Sca -> CycodeBundle.message("scaScanning") CliScanType.Iac -> CycodeBundle.message("iacScanning") @@ -82,15 +82,25 @@ class CycodeService(val project: Project) : Disposable { } fun startScan(scanType: CliScanType, pathsToScan: List, onDemand: Boolean = true) { + startScan(scanType, onDemand) { ScanTarget.Paths(pathsToScan) } + } + + /** + * [resolveTarget] runs on the background thread once the scan is allowed to start; null means there is nothing + * to scan (the resolver has already told the user why). + */ + fun startScan(scanType: CliScanType, onDemand: Boolean = true, resolveTarget: () -> ScanTarget?) { runBackgroundTask(getBackgroundScanningLabel(scanType)) { indicator -> if (!pluginLocalState.cliAuthed) { CycodeNotifier.notifyInfo(project, CycodeBundle.message("authorizationRequiredNotification")) return@runBackgroundTask } - thisLogger().debug("[$scanType] Start scanning paths: $pathsToScan") - cliService.scan(scanType, ScanTarget.Paths(pathsToScan), onDemand) { indicator.isCanceled } - thisLogger().debug("[$scanType] Finish scanning paths: $pathsToScan") + val target = resolveTarget() ?: return@runBackgroundTask + + thisLogger().debug("[$scanType] Start scanning: $target") + cliService.scan(scanType, target, onDemand) { indicator.isCanceled } + thisLogger().debug("[$scanType] Finish scanning: $target") } } diff --git a/src/main/kotlin/com/cycode/plugin/services/DiffRefsService.kt b/src/main/kotlin/com/cycode/plugin/services/DiffRefsService.kt index 893a05d..c5e25fd 100644 --- a/src/main/kotlin/com/cycode/plugin/services/DiffRefsService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/DiffRefsService.kt @@ -2,7 +2,6 @@ package com.cycode.plugin.services import com.cycode.plugin.CycodeBundle import com.cycode.plugin.components.toolWindow.updateToolWindowState -import com.cycode.plugin.git.DiffRefsCache import com.cycode.plugin.git.DiffSide import com.cycode.plugin.git.GitCli import com.cycode.plugin.git.HEAD_REF @@ -31,12 +30,10 @@ class DiffRefsService(private val project: Project) { var to: DiffSide = DiffSide.Rev(HEAD_REF) private set - // the revision lists and the git state they were built for (see GitCli.getHeadFingerprint) + // rebuilt on every refresh: git is fast enough with the capped lists, and it picks up refs created elsewhere @Volatile - private var cache: DiffRefsCache? = null - - val refs: List - get() = cache?.refs ?: emptyList() + var refs: List = emptyList() + private set // null until known; only an explicit "not a git repository" answer makes it false @Volatile @@ -72,21 +69,18 @@ class DiffRefsService(private val project: Project) { fun refresh(onDone: (() -> Unit)? = null) { val projectRoot = cliService.getProjectRootDirectory() ?: return val requestId = refreshRequestId.incrementAndGet() - val pinned = listOf(from, to).filterIsInstance().map { it.ref } + val pinned = listOf(from, to).filterIsInstance() ApplicationManager.getApplication().executeOnPooledThread { val git = GitCli(projectRoot) + val refs = git.getAvailableRefs(pinned) - // the lists are rebuilt only when the branch changes or a commit is created - val fingerprint = git.getHeadFingerprint() - if (fingerprint == null && !gitUnavailableNotified && !git.isGitAvailable()) { + // nothing but HEAD: git may be missing (a repository without commits would still answer --version) + if (refs.size <= 1 && !gitUnavailableNotified && !git.isGitAvailable()) { gitUnavailableNotified = true CycodeNotifier.notifyInfo(project, CycodeBundle.message("diffGitUnavailableNotification")) } - val current = cache - val reuse = current != null && current.canReuse(fingerprint) - val refs = if (reuse) current!!.refs else git.getAvailableRefs(pinned) if (requestId != refreshRequestId.get() || project.isDisposed) { return@executeOnPooledThread } @@ -94,8 +88,7 @@ class DiffRefsService(private val project: Project) { val known = refs.map { it.value }.toSet() if (from is DiffSide.Rev && (from as DiffSide.Rev).ref !in known) from = DiffSide.Local if (to is DiffSide.Rev && (to as DiffSide.Rev).ref !in known) to = DiffSide.Rev(HEAD_REF) - // only a request that is still current may publish lists, together with the state they were built for - if (!reuse) cache = DiffRefsCache(fingerprint, refs) + this.refs = refs if (onDone != null) { ApplicationManager.getApplication().invokeLater({ onDone() }, project.disposed) diff --git a/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt b/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt index 56e5c72..cab3b0f 100644 --- a/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt +++ b/src/main/kotlin/com/cycode/plugin/services/ScanScopeService.kt @@ -2,7 +2,6 @@ package com.cycode.plugin.services import com.cycode.plugin.CycodeBundle import com.cycode.plugin.cli.ScanScope -import com.cycode.plugin.cli.ScanTarget import com.cycode.plugin.cli.CliScanType import com.cycode.plugin.cli.getScanTypeDisplayName import com.cycode.plugin.cli.partitionByFileSupport @@ -11,7 +10,6 @@ import com.cycode.plugin.git.GitCli import com.cycode.plugin.git.planDiffScan import com.cycode.plugin.utils.CycodeNotifier import com.intellij.openapi.components.Service -import com.intellij.openapi.diagnostic.thisLogger import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project @@ -98,23 +96,14 @@ class ScanScopeService(private val project: Project) { return } - cycodeService.runBackgroundTask(cycodeService.getBackgroundScanningLabel(scanType)) { indicator -> - if (!pluginLocalState.cliAuthed) { - CycodeNotifier.notifyInfo(project, CycodeBundle.message("authorizationRequiredNotification")) - return@runBackgroundTask - } - - val target = when (val plan = planDiffScan(scanType, from, to, projectRoot, GitCli(projectRoot))) { + cycodeService.startScan(scanType) { + when (val plan = planDiffScan(scanType, from, to, projectRoot, GitCli(projectRoot))) { is DiffScanPlan.Run -> plan.target is DiffScanPlan.Refused -> { CycodeNotifier.notifyInfo(project, CycodeBundle.message(plan.messageKey)) - return@runBackgroundTask + null } } - - thisLogger().debug("[$scanType] Start diff scan: $target") - cliService.scan(scanType, target, true) { indicator.isCanceled } - thisLogger().debug("[$scanType] Finish diff scan: $target") } } } diff --git a/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt b/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt index 3cca8e7..ba01949 100644 --- a/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt +++ b/src/test/kotlin/com/cycode/plugin/DiffScanPlannerTest.kt @@ -82,15 +82,6 @@ class DiffScanPlannerTest : GitTestBase() { } } - @Test - fun unsafeRefsAreRefusedInBothFlavours() { - assertEquals( - DiffScanPlan.Refused("diffUnknownRevisionNotification"), - plan(secret, DiffSide.Local, "--output=x") - ) - assertEquals(DiffScanPlan.Refused("diffUnknownRevisionNotification"), plan(secret, "--output=x", "main")) - } - @Test fun sameCommitUnderDifferentNamesIsRefused() { assertEquals(DiffScanPlan.Refused("diffSameCommitNotification"), plan(secret, "main", "HEAD")) diff --git a/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt b/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt index a2dc224..97d4851 100644 --- a/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt +++ b/src/test/kotlin/com/cycode/plugin/DiffScanTest.kt @@ -1,6 +1,7 @@ package com.cycode.plugin import com.cycode.plugin.cli.* +import com.cycode.plugin.git.DiffSide import org.junit.Assert.* import org.junit.Test @@ -36,15 +37,6 @@ class DiffScanTest { assertTrue(supportsDiffScan(CliScanType.Secret)) } - @Test - fun versionGate() { - assertTrue(isVersionAtLeast("3.25.0", "3.25.0")) - assertTrue(isVersionAtLeast("3.26.0", "3.25.0")) - assertTrue(isVersionAtLeast("4.0.0", "3.25.0")) - assertFalse(isVersionAtLeast("3.24.9", "3.25.0")) - assertFalse(isVersionAtLeast("0.0.1.dev498", "3.25.0")) - } - @Test fun scanTargetArgs() { assertArrayEquals(arrayOf("path", "/a", "/b"), ScanTarget.Paths(listOf("/a", "/b")).toCliArgs()) @@ -59,23 +51,14 @@ class DiffScanTest { assertThrows(IllegalArgumentException::class.java) { assertSafeRefArg("") } assertThrows(IllegalArgumentException::class.java) { assertSafeRefArg("a\u0000b") } assertThrows(IllegalArgumentException::class.java) { getDiffScanArgs(DiffScanMode.CommitRange, "-x", "/repo") } + assertThrows(IllegalArgumentException::class.java) { DiffSide.Rev("--output=x") } + assertThrows(IllegalArgumentException::class.java) { DiffSide.Rev("") } assertFalse(isSafeRefArg("")) assertFalse(isSafeRefArg("-")) assertTrue(isSafeRefArg("origin/feature-1")) assertTrue(isSafeRefArg("HEAD~1")) } - @Test - fun versionEdgeCases() { - assertTrue(isVersionAtLeast("v3.25.0", "3.25.0")) - assertTrue(isVersionAtLeast("3.25", "3.25.0")) - assertTrue(isVersionAtLeast("3.25.0.dev1", "3.25.0")) - assertFalse(isVersionAtLeast("3.25.0-alpha", "3.26.0")) - assertTrue(isVersionAtLeast("10.0.0", "3.25.0")) - assertFalse(isVersionAtLeast("", "3.25.0")) - assertFalse(isVersionAtLeast("garbage", "3.25.0")) - } - @Test fun everyScanTypeExceptIacSupportsDiff() { CliScanType.entries.forEach { assertEquals(it != CliScanType.Iac, supportsDiffScan(it)) } diff --git a/src/test/kotlin/com/cycode/plugin/GitCliTest.kt b/src/test/kotlin/com/cycode/plugin/GitCliTest.kt index aeaf9f8..baabae4 100644 --- a/src/test/kotlin/com/cycode/plugin/GitCliTest.kt +++ b/src/test/kotlin/com/cycode/plugin/GitCliTest.kt @@ -20,8 +20,8 @@ class GitCliTest : GitTestBase() { val feature = sh("rev-parse", "feature") val main = sh("rev-parse", "main") - assertEquals(CommitRangeResult.Range("$base..$feature"), git.getCommitRange("main", "feature")) - assertEquals(CommitRangeResult.Range("$base..$main"), git.getCommitRange("feature", "main")) + assertEquals(CommitRangeResult.Range("$base..$feature"), git.range("main", "feature")) + assertEquals(CommitRangeResult.Range("$base..$main"), git.range("feature", "main")) } @Test @@ -30,8 +30,8 @@ class GitCliTest : GitTestBase() { commit("second") val new = sh("rev-parse", "HEAD") - assertEquals(CommitRangeResult.Range("$old..$new"), git.getCommitRange(old, new)) - assertEquals(CommitRangeResult.Range("$old..$new"), git.getCommitRange(new, old)) + assertEquals(CommitRangeResult.Range("$old..$new"), git.range(old, new)) + assertEquals(CommitRangeResult.Range("$old..$new"), git.range(new, old)) } @Test @@ -41,20 +41,19 @@ class GitCliTest : GitTestBase() { @Test fun sameCommit() { - assertEquals(CommitRangeResult.SameCommit, git.getCommitRange("HEAD", "main")) + assertEquals(CommitRangeResult.SameCommit, git.range("HEAD", "main")) } @Test fun noCommonHistory() { sh("checkout", "--orphan", "orphan") commit("orphan-1") - assertEquals(CommitRangeResult.NoCommonHistory, git.getCommitRange("main", "orphan")) + assertEquals(CommitRangeResult.NoCommonHistory, git.range("main", "orphan")) } @Test - fun unknownAndOptionLikeRevisions() { - assertEquals(CommitRangeResult.UnknownRevision, git.getCommitRange("main", "nope")) - assertEquals(CommitRangeResult.UnknownRevision, git.getCommitRange("main", "--output=x")) + fun unknownRevision() { + assertEquals(CommitRangeResult.UnknownRevision, git.range("main", "nope")) } @Test @@ -78,8 +77,8 @@ class GitCliTest : GitTestBase() { assertEquals(1, refs.count { it.label.endsWith("main-1") }) val first = sh("rev-list", "--max-parents=0", "HEAD") - assertTrue(git.getAvailableRefs(listOf(first)).any { it.value == first }) - assertFalse(git.getAvailableRefs(listOf("nope")).any { it.value == "nope" }) + assertTrue(git.getAvailableRefs(listOf(DiffSide.Rev(first))).any { it.value == first }) + assertFalse(git.getAvailableRefs(listOf(DiffSide.Rev("nope"))).any { it.value == "nope" }) } @Test @@ -136,61 +135,30 @@ class GitCliTest : GitTestBase() { fun commitRangeWithTagsAndRelativeRevisions() { sh("tag", "v1") commit("second") - val result = git.getCommitRange("v1", "HEAD") as CommitRangeResult.Range + val result = git.range("v1", "HEAD") as CommitRangeResult.Range assertTrue(result.range.matches(Regex("[0-9a-f]{40}\\.\\.[0-9a-f]{40}"))) - assertEquals(result, git.getCommitRange("v1", "main")) + assertEquals(result, git.range("v1", "main")) } @Test - fun unknownOrUnsafeFromRevision() { - assertEquals(CommitRangeResult.UnknownRevision, git.getCommitRange("nope", "main")) - assertEquals(CommitRangeResult.UnknownRevision, git.getCommitRange("--output=x", "main")) - assertEquals(CommitRangeResult.UnknownRevision, git.getCommitRange("", "main")) + fun unknownFromRevision() { + assertEquals(CommitRangeResult.UnknownRevision, git.range("nope", "main")) } @Test fun pinnedRefThatScrolledOutOfTheListIsKept() { val oldest = sh("rev-parse", "HEAD") repeat(GitCli.MAX_COMMITS + 5) { commit("c$it") } - val refs = git.getAvailableRefs(listOf(oldest, "HEAD")) + val refs = git.getAvailableRefs(listOf(DiffSide.Rev(oldest), DiffSide.Rev("HEAD"))) assertEquals(1, refs.count { it.value == oldest }) assertEquals(1, refs.count { it.value == HEAD_REF }) } - @Test - fun unsafePinnedRefIsDropped() { - assertFalse(git.getAvailableRefs(listOf("--output=x")).any { it.value == "--output=x" }) - } - @Test fun labelWithoutRefNameOrSubject() { assertEquals("abc123", GitCli.buildLabel(null, "abc123", "")) assertEquals("abc123 │ subject", GitCli.buildLabel("", "abc123", "subject")) } - @Test - fun headFingerprintChangesOnCommitAndBranchSwitchOnly() { - val first = git.getHeadFingerprint()!! - assertEquals(first, git.getHeadFingerprint()) - - sh("branch", "other") // a new ref that is not checked out does not change it - assertEquals(first, git.getHeadFingerprint()) - - commit("second") - val afterCommit = git.getHeadFingerprint()!! - assertNotEquals(first, afterCommit) - - sh("checkout", "other") - assertNotEquals(afterCommit, git.getHeadFingerprint()) - } - - @Test - fun headFingerprintIsNullOutsideARepository() { - val plain = createPlainDirectory() - try { - assertNull(GitCli(plain.path).getHeadFingerprint()) - } finally { - plain.deleteRecursively() - } - } + private fun GitCli.range(from: String, to: String) = getCommitRange(DiffSide.Rev(from), DiffSide.Rev(to)) } diff --git a/src/test/kotlin/com/cycode/plugin/ScanScopeLogicTest.kt b/src/test/kotlin/com/cycode/plugin/ScanScopeLogicTest.kt index 1891319..de86516 100644 --- a/src/test/kotlin/com/cycode/plugin/ScanScopeLogicTest.kt +++ b/src/test/kotlin/com/cycode/plugin/ScanScopeLogicTest.kt @@ -3,8 +3,6 @@ package com.cycode.plugin import com.cycode.plugin.cli.CliScanType import com.cycode.plugin.cli.isFileSupportedByScanType import com.cycode.plugin.cli.partitionByFileSupport -import com.cycode.plugin.git.DiffRefsCache -import com.cycode.plugin.git.RefOption import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue @@ -44,31 +42,4 @@ class ScanScopeLogicTest { assertEquals(listOf(CliScanType.Secret, CliScanType.Sca), all) assertTrue(none.isEmpty()) } - - private val refs = listOf(RefOption("HEAD", "HEAD")) - - @Test - fun cacheIsReusedOnlyForTheSameKnownGitState() { - val cache = DiffRefsCache("main@abc", refs) - assertTrue(cache.canReuse("main@abc")) - assertFalse(cache.canReuse("main@def")) // a commit was created - assertFalse(cache.canReuse("other@abc")) // the branch changed - assertFalse(cache.canReuse(null)) // git state unknown - } - - @Test - fun cacheWithoutFingerprintOrListIsNeverReused() { - assertFalse(DiffRefsCache(null, refs).canReuse(null)) - assertFalse(DiffRefsCache("main@abc", emptyList()).canReuse("main@abc")) - } - - @Test - fun listsAreNeverPairedWithAnotherStatesFingerprint() { - // the fingerprint and the list live in one immutable object, so a stale request cannot split them - val first = DiffRefsCache("main@abc", refs) - val second = DiffRefsCache("main@def", listOf(RefOption("x", "x"))) - assertFalse(first.canReuse("main@def")) - assertEquals("x", second.refs.single().value) - assertTrue(second.canReuse("main@def")) - } }