core

package
v2023.3.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 22, 2024 License: Apache-2.0 Imports: 46 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// QodanaSuccessExitCode is Qodana exit code when the analysis is successfully completed.
	QodanaSuccessExitCode = 0
	// QodanaFailThresholdExitCode same as QodanaSuccessExitCode, but the threshold is set and exceeded.
	QodanaFailThresholdExitCode = 255
	// QodanaOutOfMemoryExitCode reports an interrupted process, sometimes because of an OOM.
	QodanaOutOfMemoryExitCode = 137
	// QodanaEapLicenseExpiredExitCode reports an expired license.
	QodanaEapLicenseExpiredExitCode = 7
	// QodanaTimeoutExitCodePlaceholder is not a real exit code (it is not obtained from IDE process! and not returned from CLI)
	// Placeholder used to identify the case when the analysis reached timeout
	QodanaTimeoutExitCodePlaceholder = 1000
)
View Source
const (
	QodanaToken            = "QODANA_TOKEN"
	QodanaLicenseOnlyToken = "QODANA_LICENSE_ONLY_TOKEN"

	QodanaConfEnv = "QODANA_CONF"
	QodanaToolEnv = "QODANA_TOOL"
	QodanaDistEnv = "QODANA_DIST"

	QodanaLicenseEndpoint = "LICENSE_ENDPOINT"
	QodanaLicense         = "QODANA_LICENSE"
	QodanaProjectIdHash   = "QODANA_PROJECT_ID_HASH"
	QodanaTreatAsRelease  = "QODANA_TREAT_AS_RELEASE"
)
View Source
const (
	QodanaSarifName = "qodana.sarif.json"
)

Variables

View Source
var (
	QDJVMC         = "QDJVMC"
	QDJVM          = "QDJVM"
	QDAND          = "QDAND"
	QDPHP          = "QDPHP"
	QDPY           = "QDPY"
	QDPYC          = "QDPYC"
	QDJS           = "QDJS"
	QDGO           = "QDGO"
	QDNET          = "QDNET"
	QDNETC         = "QDNETC"
	QDANDC         = "QDANDC"
	QDRST          = "QDRST"
	QDRUBY         = "QDRUBY"
	QDCL           = "QDCL"
	DockerImageMap = map[string]string{
		QDANDC: "jetbrains/qodana-jvm-android:",
		QDPHP:  "jetbrains/qodana-php:",
		QDJS:   "jetbrains/qodana-js:",
		QDNET:  "jetbrains/qodana-dotnet:",
		QDNETC: "jetbrains/qodana-cdnet:",
		QDPY:   "jetbrains/qodana-python:",
		QDPYC:  "jetbrains/qodana-python-community:",
		QDGO:   "jetbrains/qodana-go:",
		QDJVM:  "jetbrains/qodana-jvm:",
		QDJVMC: "jetbrains/qodana-jvm-community:",
		QDCL:   "jetbrains/qodana-clang:",
	}
)
View Source
var (
	EapSuffix = "-EAP"

	Products = map[string]string{
		QDJVM:  "IIU",
		QDJVMC: "IIC",

		QDPHP: "PS",
		QDJS:  "WS",
		QDNET: "RD",
		QDPY:  "PCP",
		QDPYC: "PCC",
		QDGO:  "GO",
		QDRST: "RR",
	}
)
View Source
var (
	QodanaSpinner = pterm.DefaultSpinner

	DefaultPromptText = "Do you want to continue?"
)

styles and different declarations intended to be used only inside this file

View Source
var AllCodes = append(allSupportedPaidCodes, allSupportedFreeCodes...)

AllCodes is a list of codes for all supported linters.

View Source
var AllImages = append(allImages(allSupportedPaidCodes), allSupportedFreeImages...)

AllImages is a list of all supported linters.

View Source
var AllNativeCodes = []string{QDNET}

AllNativeCodes is a list of all supported Qodana linters product codes

View Source
var (
	// DisableCheckUpdates flag to disable checking for updates
	DisableCheckUpdates = false
)
View Source
var Info = fmt.Sprintf(`
  %s (%s)
  https://jb.gg/qodana-cli
  Documentation – https://jb.gg/qodana-docs
  Contact us at qodana-support@jetbrains.com
  Bug Tracker: https://jb.gg/qodana-issue
  Community forum: https://jb.gg/qodana-forum
`, "Qodana CLI", Version)

Info Two newlines at the start are important to lay the output nicely in CLI.

View Source
var InterruptChannel chan os.Signal
View Source
var PricingUrl = "https://www.jetbrains.com/qodana/buy/"
View Source
var Prod product
View Source
var Version = "dev"

Version returns the version of the Qodana CLI, set during the GoReleaser build

Functions

func Append

func Append(slice []string, elems ...string) []string

Append appends a string to a slice if it's not already there.

func AskUserConfirm

func AskUserConfirm(what string) bool

AskUserConfirm asks the user for confirmation with yes/no.

func CheckContainerEngineMemory

func CheckContainerEngineMemory()

CheckContainerEngineMemory applicable only for Docker Desktop, (has the default limit of 2GB which can be not enough when Gradle runs inside a container).

func CheckDirFiles

func CheckDirFiles(dir string) bool

CheckDirFiles checks if a directory contains files.

func CheckForUpdates

func CheckForUpdates(currentVersion string)

CheckForUpdates check GitHub https://github.com/JetBrains/qodana-cli/ for the latest version of CLI release.

func ContainerCleanup

func ContainerCleanup()

ContainerCleanup cleans up Qodana containers.

func Contains

func Contains(s []string, str string) bool

Contains checks if a string is in a given slice.

func DisableColor

func DisableColor()

DisableColor disables colors in the output.

func DownloadFile

func DownloadFile(filepath string, url string, spinner *pterm.SpinnerPrinter) error

func EmptyMessage

func EmptyMessage()

EmptyMessage is a message that is used when there is no message to show.

func ErrorMessage

func ErrorMessage(message string, a ...interface{})

ErrorMessage prints an error message with the icon.

func ExtractQodanaEnvironment

func ExtractQodanaEnvironment(setEnvironmentFunc func(string, string))

ExtractQodanaEnvironment extracts Qodana environment variables from the current environment.

func FindQodanaYaml

func FindQodanaYaml(project string) string

FindQodanaYaml checks whether qodana.yaml exists or not

func GetAnalyzer added in v2023.3.1

func GetAnalyzer(path string, yamlName string) string

GetAnalyzer gets linter for the given path and saves configName

func GetContributors

func GetContributors(repoDirs []string, days int, excludeBots bool) []contributor

GetContributors returns the list of contributors of the git repository.

func GetDefaultUser

func GetDefaultUser() string

func GetDotNetConfig

func GetDotNetConfig(projectDir string, yamlName string) bool

GetDotNetConfig gets .NET config for the given path and saves configName

func GetProperties

func GetProperties(opts *QodanaOptions, yamlProps map[string]string, dotNetOptions DotNet, plugins []string) []string

GetProperties writes key=value `props` to file `f` having later key occurrence win

func Image

func Image(code string) string

func IsContainer

func IsContainer() bool

IsContainer checks if Qodana is running in a container.

func IsHomeDirectory

func IsHomeDirectory(path string) bool

IsHomeDirectory returns true if the given path is the user's home directory.

func IsInteractive

func IsInteractive() bool

IsInteractive returns true if the current execution environment is interactive (useful for colors/animations toggle).

func IsNativeAnalyzer added in v2023.3.1

func IsNativeAnalyzer(analyzer string) bool

func IsNativeRequired added in v2023.3.1

func IsNativeRequired(projectDir string, ide string) bool

func OpenDir

func OpenDir(path string) error

OpenDir opens directory in the default file manager

func PrepareContainerEnvSettings added in v2023.3.0

func PrepareContainerEnvSettings()

PrepareContainerEnvSettings checks if the host is ready to run Qodana container images.

func PrimaryBold

func PrimaryBold(text string, a ...interface{}) string

PrimaryBold prints a message in the primary bold style.

func PrintContributorsTable

func PrintContributorsTable(contributors []contributor, days int, dirs int)

PrintContributorsTable prints the contributors table and helpful messages.

func PrintFile

func PrintFile(file string)

PrintFile prints the given file content with lines like printProblem.

func PullImage

func PullImage(client *client.Client, image string)

PullImage pulls docker image and prints the process.

func QuoteForWindows

func QuoteForWindows(s string) string

QuoteForWindows wraps in '"' if '`s`' contains space on windows.

func ReadSarif

func ReadSarif(sarifPath string, printProblems bool)

ReadSarif prints Qodana Scan result into stdout

func RunAnalysis

func RunAnalysis(ctx context.Context, options *QodanaOptions) int

RunAnalysis runs the linter with the given options.

func RunCmd

func RunCmd(cwd string, args ...string) int

func RunCmdWithTimeout added in v2023.3.2

func RunCmdWithTimeout(cwd string, timeout time.Duration, timeoutExitCode int, args ...string) int

RunCmdWithTimeout executes subprocess with forwarding of signals, and returns its exit code. If timeout occurs, subprocess is terminated, timeoutExitCode is returned

func SelectAnalyzer added in v2023.3.1

func SelectAnalyzer(path string, analyzers []string, interactive bool, selectFunc func([]string) string) string

func SendReport

func SendReport(opts *QodanaOptions, token string)

SendReport sends report to Qodana Cloud.

func SetQodanaLinter

func SetQodanaLinter(path string, linter string, filename string)

SetQodanaLinter adds the linter to the qodana.yaml file.

func SetupLicenseAndProjectHash added in v2023.3.2

func SetupLicenseAndProjectHash(token string)

func SetupLicenseToken

func SetupLicenseToken(opts *QodanaOptions)

func ShowReport

func ShowReport(resultsDir string, reportPath string, port int)

ShowReport serves the Qodana report

func SuccessMessage

func SuccessMessage(message string, a ...interface{})

SuccessMessage prints a success message with the icon.

func ToJSON

func ToJSON(contributors []contributor) (string, error)

ToJSON returns the JSON representation of the list of contributors.

func WarningMessage

func WarningMessage(message string, a ...interface{})

WarningMessage prints a warning message with the icon.

Types

type Clude

type Clude struct {
	// The name of check to include/exclude.
	Name string `yaml:"name"`

	// Relative to the project root path to enable/disable analysis.
	Paths []string `yaml:"paths,omitempty"`
}

Clude A check id to enable/disable for include/exclude YAML field.

type CoverageThresholds added in v2023.3.0

type CoverageThresholds struct {
	// The run fails if the percentage of fresh lines covered is lower than this
	// number
	Fresh *int `json:"fresh,omitempty" yaml:"fresh,omitempty" mapstructure:"fresh,omitempty"`

	// The run fails if the percentage of total lines covered is lower than this
	// number.
	Total *int `json:"total,omitempty" yaml:"total,omitempty" mapstructure:"total,omitempty"`
}

CoverageThresholds Configures minimum thresholds for test coverage metrics. Absent properties are not checked

type CustomDependency

type CustomDependency struct {
	// Name is the name of the dependency.
	Name string `yaml:"name"`

	// Version is the dependency version.
	Version string `yaml:"version"`

	// Url is the dependency URL.
	Url string `yaml:"url,omitempty"`

	// LicenseOverride is the license of the dependency.
	Licenses []LicenseOverride `yaml:"licenses"`
}

type DependencyIgnore

type DependencyIgnore struct {
	// Name is the name of the dependency to ignore.
	Name string `yaml:"name"`
}

DependencyIgnore is a dependency to ignore for license checks in Qodana

type DependencyOverride

type DependencyOverride struct {
	// Name is dependency name.
	Name string `yaml:"name"`

	// Version is the dependency version.
	Version string `yaml:"version"`

	// Url is the dependency URL.
	Url string `yaml:"url,omitempty"`

	// LicenseOverride is the license of the dependency.
	Licenses []LicenseOverride `yaml:"licenses"`
}

type DotNet

type DotNet struct {
	// Solution is the name of a .NET solution inside the Qodana project.
	Solution string `yaml:"solution,omitempty"`

	// Project is the name of a .NET project inside the Qodana project.
	Project string `yaml:"project,omitempty"`

	// Configuration is the configuration in which .NET project should be opened by Qodana.
	Configuration string `yaml:"configuration,omitempty"`

	// Platform is the target platform in which .NET project should be opened by Qodana.
	Platform string `yaml:"platform,omitempty"`

	// Frameworks is a semicolon-separated list of target framework monikers (TFM) to be analyzed.
	Frameworks string `yaml:"frameworks,omitempty"`
}

func (DotNet) IsEmpty

func (d DotNet) IsEmpty() bool

IsEmpty checks whether the .NET configuration is empty or not.

type FailureConditions added in v2023.3.0

type FailureConditions struct {
	// SeverityThresholds corresponds to the JSON schema field "severityThresholds".
	SeverityThresholds *SeverityThresholds `yaml:"severityThresholds,omitempty"`

	// TestCoverageThresholds corresponds to the JSON schema field
	// "testCoverageThresholds".
	TestCoverageThresholds *CoverageThresholds `yaml:"testCoverageThresholds,omitempty"`
}

type LicenseOverride added in v2023.3.0

type LicenseOverride struct {
	// Key is the SPDX ID of the license.
	Key string `yaml:"key"`

	// Url is the URL of the license.
	Url string `yaml:"url,omitempty"`
}

type LicenseRule

type LicenseRule struct {
	// Keys is the list of project license SPDX IDs.
	Keys []string `yaml:"keys"`

	// Allowed is the list of allowed dependency licenses for project licenses.
	Allowed []string `yaml:"allowed,omitempty"`

	// Prohibited is the list of prohibited dependency licenses for project licenses.
	Prohibited []string `yaml:"prohibited,omitempty"`
}

LicenseRule is a license rule to apply for license compatibility checks in Qodana

type ModuleToAnalyze added in v2023.3.0

type ModuleToAnalyze struct {
	// Name corresponds to the JSON schema field "name".
	Name *string `yaml:"name,omitempty"`
}

ModuleToAnalyze is a submodule to include in the analysis

type Php

type Php struct {
	// Version is the PHP version to use for the analysis.
	Version string `yaml:"version,omitempty"`
}

type Plugin

type Plugin struct {
	// Id plugin id to install.
	Id string `yaml:"id"`
}

Plugin to be installed during the Qodana run.

type Product

type Product struct {
	Code     string
	Releases []ReleaseInfo
}

func GetProductByCode

func GetProductByCode(code string) (*Product, error)

type Profile

type Profile struct {
	// Name profile name to use.
	Name string `yaml:"name,omitempty"`

	// Path profile path to use.
	Path string `yaml:"path,omitempty"`
}

Profile A profile is some template set of checks to run with Qodana analysis.

type QodanaOptions

type QodanaOptions struct {
	ResultsDir            string
	CacheDir              string
	ProjectDir            string
	ReportDir             string
	CoverageDir           string
	Linter                string
	Ide                   string
	SourceDirectory       string
	DisableSanity         bool
	ProfileName           string
	ProfilePath           string
	RunPromo              string
	StubProfile           string // note: deprecated option
	Baseline              string
	BaselineIncludeAbsent bool
	SaveReport            bool
	ShowReport            bool
	Port                  int
	Property              []string
	Script                string
	FailThreshold         string
	Commit                string
	AnalysisId            string
	Env                   []string
	Volumes               []string
	User                  string
	PrintProblems         bool
	SkipPull              bool
	ClearCache            bool
	YamlName              string
	GitReset              bool
	FullHistory           bool
	ApplyFixes            bool
	Cleanup               bool
	FixesStrategy         string // note: deprecated option

	NoStatistics            bool   // thirdparty common option
	Solution                string // cdnet specific options
	Project                 string
	Configuration           string
	Platform                string
	NoBuild                 bool
	CompileCommands         string // clang specific options
	ClangArgs               string
	AnalysisTimeoutMs       int
	AnalysisTimeoutExitCode int
	// contains filtered or unexported fields
}

QodanaOptions is a struct that contains all the options to run a Qodana linter.

func (*QodanaOptions) ConfDirPath

func (o *QodanaOptions) ConfDirPath() string

func (*QodanaOptions) CoverageDirPath added in v2023.3.0

func (o *QodanaOptions) CoverageDirPath() string

func (*QodanaOptions) FetchAnalyzerSettings added in v2023.3.0

func (o *QodanaOptions) FetchAnalyzerSettings()

func (*QodanaOptions) GetAnalysisTimeout added in v2023.3.2

func (o *QodanaOptions) GetAnalysisTimeout() time.Duration

func (*QodanaOptions) GetLinterDir

func (o *QodanaOptions) GetLinterDir() string

func (*QodanaOptions) ReportResultsPath

func (o *QodanaOptions) ReportResultsPath() string

func (*QodanaOptions) RequiresToken

func (o *QodanaOptions) RequiresToken() bool

func (*QodanaOptions) ValidateToken

func (o *QodanaOptions) ValidateToken(refresh bool) string

ValidateToken checks if QODANA_TOKEN is set in CLI args, or environment or the system keyring, returns it's value.

type QodanaYaml

type QodanaYaml struct {
	// The qodana.yaml version of this log file.
	Version string `yaml:"version,omitempty"`

	// Linter to run.
	Linter string `yaml:"linter,omitempty"`

	// IDE to run.
	Ide string `yaml:"ide,omitempty"`

	// Profile is the profile configuration for Qodana analysis (either a profile name or a profile path).
	Profile Profile `yaml:"profile,omitempty"`

	// FailThreshold is a number of problems to fail the analysis (to exit from Qodana with code 255).
	FailThreshold int `yaml:"failThreshold,omitempty"`

	// Clude property to disable the wanted checks on the wanted paths.
	Excludes []Clude `yaml:"exclude,omitempty"`

	// Include property to enable the wanted checks.
	Includes []Clude `yaml:"include,omitempty"`

	// Properties property to override IDE properties.
	Properties map[string]string `yaml:"properties,omitempty"`

	// Bootstrap contains a command to run in the container before the analysis starts.
	Bootstrap string `yaml:"bootstrap,omitempty"`

	// LicenseRules contains a list of license rules to apply for license checks.
	LicenseRules []LicenseRule `yaml:"licenseRules,omitempty"`

	// Whether to include dev dependencies in the analysis
	AnalyzeDevDependencies bool `yaml:"analyzeDevDependencies,omitempty"`

	// DependencyIgnores contains a list of dependencies to ignore for license checks in Qodana.
	DependencyIgnores []DependencyIgnore `yaml:"dependencyIgnores,omitempty"`

	// Which submodules to include. Omitting this key will include all submodules
	ModulesToAnalyze []ModuleToAnalyze `yaml:"modulesToAnalyze,omitempty"`

	// Which dependencies to exclude from the generated SBOM report
	DependencySbomExclude []DependencyIgnore `yaml:"dependencySbomExclude,omitempty"`

	// DependencyOverrides contains a list of dependencies metadata to override for license checks in Qodana.
	DependencyOverrides []DependencyOverride `yaml:"dependencyOverrides,omitempty"`

	// CustomDependencies contains a list of custom dependencies to add to license checks in Qodana.
	CustomDependencies []CustomDependency `yaml:"customDependencies,omitempty"`

	// Overrides the licenses attached to the project
	ProjectLicenses []LicenseOverride `yaml:"projectLicenses,omitempty"`

	// Maximum amount of internal errors to collect in the report
	MaxRuntimeNotifications int `yaml:"maxRuntimeNotifications,omitempty"`

	// Plugins property containing plugins to install.
	Plugins []Plugin `yaml:"plugins,omitempty"`

	// Whether to fail the run when any internal error was encountered. In that case, the program returns exit code 70
	FailOnErrorNotification bool `yaml:"failOnErrorNotification,omitempty"`

	// Configures individual failure conditions. Absent properties will not be checked
	FailureConditions FailureConditions `yaml:"failureConditions,omitempty"`

	// DotNet is the configuration for .NET solutions and projects (either a solution name or a project name).
	DotNet DotNet `yaml:"dotnet,omitempty"`

	// Php is the configuration for PHP projects.
	Php Php `yaml:"php,omitempty"`

	// ProjectJdk is the configuration for the project JDK.
	ProjectJdk string `yaml:"projectJDK,omitempty"`

	// DisableSanityInspections property to disable sanity inspections.
	DisableSanityInspections string `yaml:"disableSanityInspections,omitempty"`

	// FixesStrategy property to set fixes strategy. Can be none (default), apply, cleanup.
	FixesStrategy string `yaml:"fixesStrategy,omitempty"`

	// RunPromoInspections property to run promo inspections.
	RunPromoInspections string `yaml:"runPromoInspections,omitempty"`

	// IncludeAbsent property to include absent problems from baseline.
	IncludeAbsent string `yaml:"includeAbsent,omitempty"`
}

QodanaYaml A standard qodana.yaml (or qodana.yml) format for Qodana configuration. https://github.com/JetBrains/qodana-profiles/blob/master/schemas/qodana-yaml-1.0.json

var Config QodanaYaml

func GetQodanaYaml

func GetQodanaYaml(project string) QodanaYaml

GetQodanaYaml reads qodana.yaml or qodana.yml

func LoadQodanaYaml

func LoadQodanaYaml(project string, filename string) *QodanaYaml

LoadQodanaYaml gets Qodana YAML from the project.

func (*QodanaYaml) IsDotNet added in v2023.3.1

func (q *QodanaYaml) IsDotNet() bool

type ReleaseDownloadInfo

type ReleaseDownloadInfo struct {
	Link         string
	Size         uint64
	ChecksumLink string
}

type ReleaseInfo

type ReleaseInfo struct {
	Date                 string
	Type                 string
	Downloads            *map[string]ReleaseDownloadInfo
	Version              *string
	MajorVersion         *string
	Build                *string
	PrintableReleaseType *string
}

func SelectLatestCompatibleRelease

func SelectLatestCompatibleRelease(product *Product, reqType string) *ReleaseInfo

type SeverityThresholds added in v2023.3.0

type SeverityThresholds struct {
	// The run fails if the total amount of results exceeds this number.
	Any *int `yaml:"any,omitempty"`

	// The run fails if the amount results with severity CRITICAL exceeds this number.
	Critical *int `yaml:"critical,omitempty"`

	// The run fails if the amount results with severity HIGH exceeds this number.
	High *int `yaml:"high,omitempty"`

	// The run fails if the amount results with severity INFO exceeds this number.
	Info *int `yaml:"info,omitempty"`

	// The run fails if the amount results with severity LOW exceeds this number.
	Low *int `yaml:"low,omitempty"`

	// The run fails if the amount results with severity MODERATE exceeds this number.
	Moderate *int `yaml:"moderate,omitempty"`
}

SeverityThresholds Configures maximum thresholds for different problem severities. Absent properties are not checked. If a baseline is given, only new results are counted

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL