diff --git a/.appveyor.yml b/.appveyor.yml deleted file mode 100644 index 23b94ca..0000000 --- a/.appveyor.yml +++ /dev/null @@ -1,50 +0,0 @@ -#---------------------------------# -# Build Image # -#---------------------------------# -image: Visual Studio 2022 - -#---------------------------------# -# Build Script # -#---------------------------------# -build_script: - - ps: .\build.ps1 -Target AppVeyor - -#---------------------------------# -# Tests -#---------------------------------# -test: off - -#---------------------------------# -# Pull Requests # -#---------------------------------# -pull_requests: - do_not_increment_build_number: true - -#---------------------------------# -# General # -#---------------------------------# -skip_branch_with_pr: true - -#---------------------------------# -# Branches to build # -#---------------------------------# -branches: - # Whitelist - only: - - develop - - master - - /release/.*/ - - /hotfix/.*/ - -#---------------------------------# -# Build Cache # -#---------------------------------# -cache: -- tools -> recipe.cake, tools/packages.config - -#---------------------------------# -# Skip builds for doc changes # -#---------------------------------# -skip_commits: - # Regex for matching commit message - message: /(doc).*/ diff --git a/Cake.CodeQL.Cli.sln b/Cake.CodeQL.Cli.sln new file mode 100644 index 0000000..c43c4dd --- /dev/null +++ b/Cake.CodeQL.Cli.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.3.32819.101 +MinimumVisualStudioVersion = 15.0.26124.0 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Cake.CodeQL.Cli", "src\Cake.CodeQL.Cli\Cake.CodeQL.Cli.csproj", "{32D1A768-6DDF-4127-967D-DA9BD00C8F26}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {32D1A768-6DDF-4127-967D-DA9BD00C8F26}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {32D1A768-6DDF-4127-967D-DA9BD00C8F26}.Debug|Any CPU.Build.0 = Debug|Any CPU + {32D1A768-6DDF-4127-967D-DA9BD00C8F26}.Release|Any CPU.ActiveCfg = Release|Any CPU + {32D1A768-6DDF-4127-967D-DA9BD00C8F26}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {7D15F748-7D66-45A7-A2C5-3119C8652D48} + EndGlobalSection +EndGlobal diff --git a/GitReleaseManager.yaml b/GitReleaseManager.yaml deleted file mode 100644 index 721c1ba..0000000 --- a/GitReleaseManager.yaml +++ /dev/null @@ -1,12 +0,0 @@ -issue-labels-include: -- Breaking change -- Feature -- Bug -- Improvement -- Documentation -issue-labels-exclude: -- Build -issue-labels-alias: - - name: Documentation - header: Documentation - plural: Documentation \ No newline at end of file diff --git a/README.md b/README.md index d983043..1a4f0bd 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ -# Cake.CodeQL +# Cake.CodeQL.Cli CodeQL Scanning from GitHub is the analysis engine used by developers to automate security checks, and by security researchers to perform variant analysis. -This plugin is a set of Cake aliases for [GitHub CodeQL CLI](https://docs.github.com/en/code-security/code-scanning/using-codeql-code-scanning-with-your-existing-ci-system/about-codeql-code-scanning-in-your-ci-system) (.NET Core or .NET6) used for scanning code hosted GitHub or GitHub Enterprise when GitHub Actions is not an option. +This plugin is a set of Cake aliases for [GitHub CodeQL CLI](https://docs.github.com/en/code-security/code-scanning/using-codeql-code-scanning-with-your-existing-ci-system/about-codeql-code-scanning-in-your-ci-system) (.NET Core or .NET6) used for scanning code hosted on GitHub or GitHub Enterprise when GitHub Actions is not an option. > :exclamation: Please read the [GitHub CodeQL Terms and Conditions](https://github.com/github/codeql-cli-binaries/blob/main/LICENSE.md) before considering using this plugin. @@ -13,11 +13,11 @@ This plugin is a set of Cake aliases for [GitHub CodeQL CLI](https://docs.github ### Cake Script ```csharp -#addin "nuget:?package=Cake.CodeQL" +#addin "nuget:?package=Cake.CodeQL.Cli" ``` -### Project +### Cake Frosting Project ```xml - + ``` ## Discussion diff --git a/build.ps1 b/build.ps1 deleted file mode 100644 index 4514a51..0000000 --- a/build.ps1 +++ /dev/null @@ -1,256 +0,0 @@ -########################################################################## -# This is the Cake bootstrapper script for PowerShell. -# This file was downloaded from https://github.com/cake-build/resources -# Feel free to change this file to fit your needs. -########################################################################## - -<# - -.SYNOPSIS -This is a Powershell script to bootstrap a Cake build. - -.DESCRIPTION -This Powershell script will download NuGet if missing, restore NuGet tools (including Cake) -and execute your Cake build script with the parameters you provide. - -.PARAMETER Script -The build script to execute. -.PARAMETER Target -The build script target to run. -.PARAMETER Configuration -The build configuration to use. -.PARAMETER Verbosity -Specifies the amount of information to be displayed. -.PARAMETER ShowDescription -Shows description about tasks. -.PARAMETER DryRun -Performs a dry run. -.PARAMETER SkipToolPackageRestore -Skips restoring of packages. -.PARAMETER ScriptArgs -Remaining arguments are added here. - -.LINK -https://cakebuild.net - -#> - -[CmdletBinding()] -Param( - [string]$Script = "recipe.cake", - [string]$Target, - [string]$Configuration, - [ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")] - [string]$Verbosity, - [switch]$ShowDescription, - [Alias("WhatIf", "Noop")] - [switch]$DryRun, - [switch]$SkipToolPackageRestore, - [Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)] - [string[]]$ScriptArgs -) - -# Attempt to set highest encryption available for SecurityProtocol. -# PowerShell will not set this by default (until maybe .NET 4.6.x). This -# will typically produce a message for PowerShell v2 (just an info -# message though) -try { - # Set TLS 1.2 (3072), then TLS 1.1 (768), then TLS 1.0 (192), finally SSL 3.0 (48) - # Use integers because the enumeration values for TLS 1.2 and TLS 1.1 won't - # exist in .NET 4.0, even though they are addressable if .NET 4.5+ is - # installed (.NET 4.5 is an in-place upgrade). - # PowerShell Core already has support for TLS 1.2 so we can skip this if running in that. - if (-not $IsCoreCLR) { - [System.Net.ServicePointManager]::SecurityProtocol = 3072 -bor 768 -bor 192 -bor 48 - } - } catch { - Write-Output 'Unable to set PowerShell to use TLS 1.2 and TLS 1.1 due to old .NET Framework installed. If you see underlying connection closed or trust errors, you may need to upgrade to .NET Framework 4.5+ and PowerShell v3' - } - -[Reflection.Assembly]::LoadWithPartialName("System.Security") | Out-Null -function MD5HashFile([string] $filePath) -{ - if ([string]::IsNullOrEmpty($filePath) -or !(Test-Path $filePath -PathType Leaf)) - { - return $null - } - - [System.IO.Stream] $file = $null; - [System.Security.Cryptography.MD5] $md5 = $null; - try - { - $md5 = [System.Security.Cryptography.MD5]::Create() - $file = [System.IO.File]::OpenRead($filePath) - return [System.BitConverter]::ToString($md5.ComputeHash($file)) - } - finally - { - if ($file -ne $null) - { - $file.Dispose() - } - } -} - -function GetProxyEnabledWebClient -{ - $wc = New-Object System.Net.WebClient - $proxy = [System.Net.WebRequest]::GetSystemWebProxy() - $proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials - $wc.Proxy = $proxy - return $wc -} - -Write-Host "Preparing to run build script..." - -if(!$PSScriptRoot){ - $PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent -} - -$TOOLS_DIR = Join-Path $PSScriptRoot "tools" -$ADDINS_DIR = Join-Path $TOOLS_DIR "Addins" -$MODULES_DIR = Join-Path $TOOLS_DIR "Modules" -$NUGET_EXE = Join-Path $TOOLS_DIR "nuget.exe" -$CAKE_EXE = Join-Path $TOOLS_DIR "Cake/Cake.exe" -$NUGET_URL = "https://dist.nuget.org/win-x86-commandline/latest/nuget.exe" -$PACKAGES_CONFIG = Join-Path $TOOLS_DIR "packages.config" -$PACKAGES_CONFIG_MD5 = Join-Path $TOOLS_DIR "packages.config.md5sum" -$ADDINS_PACKAGES_CONFIG = Join-Path $ADDINS_DIR "packages.config" -$MODULES_PACKAGES_CONFIG = Join-Path $MODULES_DIR "packages.config" - -# Make sure tools folder exists -if ((Test-Path $PSScriptRoot) -and !(Test-Path $TOOLS_DIR)) { - Write-Verbose -Message "Creating tools directory..." - New-Item -Path $TOOLS_DIR -Type Directory | Out-Null -} - -# Make sure that packages.config exist. -if (!(Test-Path $PACKAGES_CONFIG)) { - Write-Verbose -Message "Downloading packages.config..." - try { - $wc = GetProxyEnabledWebClient - $wc.DownloadFile("https://cakebuild.net/download/bootstrapper/packages", $PACKAGES_CONFIG) - } catch { - Throw "Could not download packages.config." - } -} - -# Try find NuGet.exe in path if not exists -if (!(Test-Path $NUGET_EXE)) { - Write-Verbose -Message "Trying to find nuget.exe in PATH..." - $existingPaths = $Env:Path -Split ';' | Where-Object { (![string]::IsNullOrEmpty($_)) -and (Test-Path $_ -PathType Container) } - $NUGET_EXE_IN_PATH = Get-ChildItem -Path $existingPaths -Filter "nuget.exe" | Select -First 1 - if ($NUGET_EXE_IN_PATH -ne $null -and (Test-Path $NUGET_EXE_IN_PATH.FullName)) { - Write-Verbose -Message "Found in PATH at $($NUGET_EXE_IN_PATH.FullName)." - $NUGET_EXE = $NUGET_EXE_IN_PATH.FullName - } -} - -# Try download NuGet.exe if not exists -if (!(Test-Path $NUGET_EXE)) { - Write-Verbose -Message "Downloading NuGet.exe..." - try { - $wc = GetProxyEnabledWebClient - $wc.DownloadFile($NUGET_URL, $NUGET_EXE) - } catch { - Throw "Could not download NuGet.exe." - } -} - -# Save nuget.exe path to environment to be available to child processed -$env:NUGET_EXE = $NUGET_EXE -$env:NUGET_EXE_INVOCATION = if ($IsLinux -or $IsMacOS) { - "mono `"$NUGET_EXE`"" -} else { - "`"$NUGET_EXE`"" -} - -# Restore tools from NuGet? -if(-Not $SkipToolPackageRestore.IsPresent) { - Push-Location - Set-Location $TOOLS_DIR - - # Check for changes in packages.config and remove installed tools if true. - [string] $md5Hash = MD5HashFile $PACKAGES_CONFIG - if((!(Test-Path $PACKAGES_CONFIG_MD5)) -Or - ($md5Hash -ne (Get-Content $PACKAGES_CONFIG_MD5 ))) { - Write-Verbose -Message "Missing or changed package.config hash..." - Get-ChildItem -Exclude packages.config,nuget.exe,Cake.Bakery | - Remove-Item -Recurse - } - - Write-Verbose -Message "Restoring tools from NuGet..." - - $NuGetOutput = Invoke-Expression "& $env:NUGET_EXE_INVOCATION install -ExcludeVersion -OutputDirectory `"$TOOLS_DIR`"" - - if ($LASTEXITCODE -ne 0) { - Throw "An error occurred while restoring NuGet tools." - } - else - { - $md5Hash | Out-File $PACKAGES_CONFIG_MD5 -Encoding "ASCII" - } - Write-Verbose -Message ($NuGetOutput | Out-String) - - Pop-Location -} - -# Restore addins from NuGet -if (Test-Path $ADDINS_PACKAGES_CONFIG) { - Push-Location - Set-Location $ADDINS_DIR - - Write-Verbose -Message "Restoring addins from NuGet..." - $NuGetOutput = Invoke-Expression "& $env:NUGET_EXE_INVOCATION install -ExcludeVersion -OutputDirectory `"$ADDINS_DIR`"" - - if ($LASTEXITCODE -ne 0) { - Throw "An error occurred while restoring NuGet addins." - } - - Write-Verbose -Message ($NuGetOutput | Out-String) - - Pop-Location -} - -# Restore modules from NuGet -if (Test-Path $MODULES_PACKAGES_CONFIG) { - Push-Location - Set-Location $MODULES_DIR - - Write-Verbose -Message "Restoring modules from NuGet..." - $NuGetOutput = Invoke-Expression "& $env:NUGET_EXE_INVOCATION install -ExcludeVersion -OutputDirectory `"$MODULES_DIR`"" - - if ($LASTEXITCODE -ne 0) { - Throw "An error occurred while restoring NuGet modules." - } - - Write-Verbose -Message ($NuGetOutput | Out-String) - - Pop-Location -} - -# Make sure that Cake has been installed. -if (!(Test-Path $CAKE_EXE)) { - Throw "Could not find Cake.exe at $CAKE_EXE" -} - -$CAKE_EXE_INVOCATION = if ($IsLinux -or $IsMacOS) { - "mono `"$CAKE_EXE`"" -} else { - "`"$CAKE_EXE`"" -} - - -# Build Cake arguments -$cakeArguments = @("$Script"); -if ($Target) { $cakeArguments += "-target=$Target" } -if ($Configuration) { $cakeArguments += "-configuration=$Configuration" } -if ($Verbosity) { $cakeArguments += "-verbosity=$Verbosity" } -if ($ShowDescription) { $cakeArguments += "-showdescription" } -if ($DryRun) { $cakeArguments += "-dryrun" } -$cakeArguments += $ScriptArgs - -# Start Cake -Write-Host "Running build script..." -Invoke-Expression "& $CAKE_EXE_INVOCATION $($cakeArguments -join " ")" -exit $LASTEXITCODE diff --git a/build.sh b/build.sh deleted file mode 100644 index 7fc4599..0000000 --- a/build.sh +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env bash - -########################################################################## -# This is the Cake bootstrapper script for Linux and OS X. -# This file was downloaded from https://github.com/cake-build/resources -# Feel free to change this file to fit your needs. -########################################################################## - -# Define directories. -SCRIPT_DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) -TOOLS_DIR=$SCRIPT_DIR/tools -ADDINS_DIR=$TOOLS_DIR/Addins -MODULES_DIR=$TOOLS_DIR/Modules -NUGET_EXE=$TOOLS_DIR/nuget.exe -CAKE_EXE=$TOOLS_DIR/Cake/Cake.exe -PACKAGES_CONFIG=$TOOLS_DIR/packages.config -PACKAGES_CONFIG_MD5=$TOOLS_DIR/packages.config.md5sum -ADDINS_PACKAGES_CONFIG=$ADDINS_DIR/packages.config -MODULES_PACKAGES_CONFIG=$MODULES_DIR/packages.config - -# Define md5sum or md5 depending on Linux/OSX -MD5_EXE= -if [[ "$(uname -s)" == "Darwin" ]]; then - MD5_EXE="md5 -r" -else - MD5_EXE="md5sum" -fi - -# Define default arguments. -SCRIPT="recipe.cake" -CAKE_ARGUMENTS=() - -# Parse arguments. -for i in "$@"; do - case $1 in - -s|--script) SCRIPT="$2"; shift ;; - --) shift; CAKE_ARGUMENTS+=("$@"); break ;; - *) CAKE_ARGUMENTS+=("$1") ;; - esac - shift -done - -# Make sure the tools folder exist. -if [ ! -d "$TOOLS_DIR" ]; then - mkdir "$TOOLS_DIR" -fi - -# Make sure that packages.config exist. -if [ ! -f "$TOOLS_DIR/packages.config" ]; then - echo "Downloading packages.config..." - curl -Lsfo "$TOOLS_DIR/packages.config" https://cakebuild.net/download/bootstrapper/packages - if [ $? -ne 0 ]; then - echo "An error occurred while downloading packages.config." - exit 1 - fi -fi - -# Download NuGet if it does not exist. -if [ ! -f "$NUGET_EXE" ]; then - echo "Downloading NuGet..." - curl -Lsfo "$NUGET_EXE" https://dist.nuget.org/win-x86-commandline/latest/nuget.exe - if [ $? -ne 0 ]; then - echo "An error occurred while downloading nuget.exe." - exit 1 - fi -fi - -# Restore tools from NuGet. -pushd "$TOOLS_DIR" >/dev/null -if [ ! -f "$PACKAGES_CONFIG_MD5" ] || [ "$( cat "$PACKAGES_CONFIG_MD5" | sed 's/\r$//' )" != "$( $MD5_EXE "$PACKAGES_CONFIG" | awk '{ print $1 }' )" ]; then - find . -type d ! -name . ! -name 'Cake.Bakery' | xargs rm -rf -fi - -mono "$NUGET_EXE" install -ExcludeVersion -if [ $? -ne 0 ]; then - echo "Could not restore NuGet tools." - exit 1 -fi - -$MD5_EXE "$PACKAGES_CONFIG" | awk '{ print $1 }' >| "$PACKAGES_CONFIG_MD5" - -popd >/dev/null - -# Restore addins from NuGet. -if [ -f "$ADDINS_PACKAGES_CONFIG" ]; then - pushd "$ADDINS_DIR" >/dev/null - - mono "$NUGET_EXE" install -ExcludeVersion - if [ $? -ne 0 ]; then - echo "Could not restore NuGet addins." - exit 1 - fi - - popd >/dev/null -fi - -# Restore modules from NuGet. -if [ -f "$MODULES_PACKAGES_CONFIG" ]; then - pushd "$MODULES_DIR" >/dev/null - - mono "$NUGET_EXE" install -ExcludeVersion - if [ $? -ne 0 ]; then - echo "Could not restore NuGet modules." - exit 1 - fi - - popd >/dev/null -fi - -# Make sure that Cake has been installed. -if [ ! -f "$CAKE_EXE" ]; then - echo "Could not find Cake.exe at '$CAKE_EXE'." - exit 1 -fi - -# Start Cake -exec mono "$CAKE_EXE" $SCRIPT "${CAKE_ARGUMENTS[@]}" diff --git a/recipe.cake b/recipe.cake deleted file mode 100644 index bf115f2..0000000 --- a/recipe.cake +++ /dev/null @@ -1,29 +0,0 @@ -#load nuget:?package=Cake.Recipe&version=1.0.0 - -Environment.SetVariableNames(); - -BuildParameters.SetParameters( - context: Context, - buildSystem: BuildSystem, - sourceDirectoryPath: "./src", - title: "Cake.CodeQL", - repositoryOwner: "louisfischer", - repositoryName: "Cake.CodeQL", - appVeyorAccountName: "louisfischer", - shouldRunDupFinder: false, - shouldRunInspectCode: false, - shouldRunCodecov: false, - shouldDeployGraphDocumentation: false, - shouldRunGitVersion: true, - shouldRunDotNetCorePack: true); - -BuildParameters.PrintParameters(Context); - -ToolSettings.SetToolSettings( - context: Context, - dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/Cake.CodeQL.Tests/**/*.cs" }, - testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* -[Shouldly]*", - testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", - testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); - -Build.RunDotNetCore(); diff --git a/src/Cake.CodeQL/Cake.CodeQL.csproj b/src/Cake.CodeQL.Cli/Cake.CodeQL.Cli.csproj similarity index 56% rename from src/Cake.CodeQL/Cake.CodeQL.csproj rename to src/Cake.CodeQL.Cli/Cake.CodeQL.Cli.csproj index 87881bb..081def0 100644 --- a/src/Cake.CodeQL/Cake.CodeQL.csproj +++ b/src/Cake.CodeQL.Cli/Cake.CodeQL.Cli.csproj @@ -1,40 +1,47 @@  - Cake.CodeQL - netcoreapp3.1;net6.0 + Cake.CodeQL.Cli + net6.0 true true true 0 bin\$(Configuration)\net6.0\$(AssemblyName).xml - true + True full true false + true - 2.0.0 - Cake.CodeQL - Cake.CodeQL is a set of Cake aliases that use CodeQL Scanning code hosted GitHub or GitHub Enterprise when GitHub Actions is not an option. - louisfischer, Cake-Contrib + 1.0.0 + Cake.CodeQL.Cli + Cake.CodeQL.Clie is a set of Cake aliases that integrate with GitHub Advanced Security (GAS). GAS uses CodeQL to find vulnerabilities in your code. The code must be hosted GitHub or GitHub Enterprise. + louisfischer, cake-contrib Cake-Contrib icon.png MIT - https://github.com/louisfischer/Cake.EntityFrameworkCore.git - Cake;codeql;scan;scanning; + https://github.com/cake-contrib/Cake.CodeQL.Cli.git + cake;codeql;scan;scanning;github;github enterprise;github advanced security;gas; $(PackageProjectUrl) git Copyright © 2022 - $([System.DateTime]::Now.Year) Cake Contributions Organization $(TargetsForTfmSpecificContentInPackage);PackBuildOutputs - 2.0.0.0 - 2.0.0.0 + 1.0.0.0 + 1.0.0.0 + warnings + README.md + + True + \ + - - + + diff --git a/src/Cake.CodeQL.Cli/CodeQLAddinInformation.cs b/src/Cake.CodeQL.Cli/CodeQLAddinInformation.cs new file mode 100644 index 0000000..39d0aaf --- /dev/null +++ b/src/Cake.CodeQL.Cli/CodeQLAddinInformation.cs @@ -0,0 +1,16 @@ +namespace Cake.CodeQL.Cli; + +internal static class CodeQLAddinInformation +{ + private static readonly string InformationalVersion = typeof(CodeQLAddinInformation).GetTypeInfo().Assembly.GetCustomAttribute()?.InformationalVersion; +#pragma warning disable CS8602 // Dereference of a possibly null reference. + private static readonly string AssemblyVersion = typeof(CodeQLAddinInformation).GetTypeInfo().Assembly.GetName().Version.ToString(); +#pragma warning restore CS8602 // Dereference of a possibly null reference. + private static readonly string AssemblyName = typeof(CodeQLAddinInformation).GetTypeInfo().Assembly.GetName().Name; + + /// + /// verbosely log addin version information + /// + /// + public static void LogVersionInformation(ICakeLog log) => log.Verbose(entry => entry("Using addin: {0} v{1} ({2})", AssemblyName, AssemblyVersion, InformationalVersion)); +} diff --git a/src/Cake.CodeQL.Cli/CodeQLAliases.cs b/src/Cake.CodeQL.Cli/CodeQLAliases.cs new file mode 100644 index 0000000..4ddc983 --- /dev/null +++ b/src/Cake.CodeQL.Cli/CodeQLAliases.cs @@ -0,0 +1,149 @@ +using Cake.CodeQL.Cli.Install; + +namespace Cake.CodeQL.Cli; + +/// +/// CodeQL Cli aliases +/// +[CakeAliasCategory("CodeQL")] +[CakeNamespaceImport("Cake.CodeQL.Cli")] +public static class CodeQLAliases +{ + /// + /// Creates a CodeQL Databases that can be use for vunerability scanning. Assumes the codeQL cli is installed on the host and available in the terminal path. + /// + /// The context. + /// The settings. + /// + /// Creates a CodeQL database in a specific working directory. + /// + /// + /// + /// + [CakeMethodAlias] + [CakeAliasCategory("Database")] + public static void CodeQLCreateDatabase(this ICakeContext context, CodeQLCreateDatabaseToolSettings settings) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + if (settings == null) throw new ArgumentNullException(nameof(settings)); + + CodeQLAddinInformation.LogVersionInformation(context.Log); + var tool = new CodeQLCreateDatabaseTool(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools, context.Log); + tool.CreateDatabase(settings); + } + + /// + /// Analyzes a CodeQL database for vunerabilities and summarizes the results in a SARIF file. Assumes the codeQL cli is installed on the host and available in the terminal path. + /// + /// The context. + /// The settings. + /// + /// Analyzes a CodeQL database and produces an output SARIF file + /// + /// + /// + /// + [CakeMethodAlias] + [CakeAliasCategory("Database")] + public static void CodeQLAnalyzeDatabase(this ICakeContext context, CodeQLAnalyzeDatabaseToolSettings settings) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + if (settings == null) throw new ArgumentNullException(nameof(settings)); + + CodeQLAddinInformation.LogVersionInformation(context.Log); + var tool = new CodeQLAnalyzeDatabaseTool(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools, context.Log); + tool.AnalyzeDatabase(settings); + } + + /// + /// Uploads the results of a CodeQL analysis in SARIF file format to GitHub or GitHub Enterprise Server. Assumes the codeQL cli is installed on the host and available in the terminal path. + /// + /// The context. + /// The settings. + /// + /// + /// + /// + /// + /// + [CakeMethodAlias] + [CakeAliasCategory("Upload")] + public static void CodeQLUploadResults(this ICakeContext context, CodeQLUploadResultsToolSettings settings) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + if (settings == null) throw new ArgumentNullException(nameof(settings)); + + CodeQLAddinInformation.LogVersionInformation(context.Log); + var tool = new CodeQLUploadResultsTool(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools, context.Log); + tool.UploadSarifFileResults(settings); + } + + /// + /// Installs CodeQL on the host agent. + /// + /// The context. + /// The settings. + /// + /// + /// + /// + /// + /// + [CakeMethodAlias] + [CakeAliasCategory("Install")] + public static void CodeQLInstall(this ICakeContext context, CodeQLInstallToolSettings settings) + { + if (context == null) throw new ArgumentNullException(nameof(context)); + if (settings == null) throw new ArgumentNullException(nameof(settings)); + + CodeQLAddinInformation.LogVersionInformation(context.Log); + var tool = new CodeQLInstallTool(context); + tool.Install(settings); + } +} diff --git a/src/Cake.CodeQL.Cli/CodeQLTool.cs b/src/Cake.CodeQL.Cli/CodeQLTool.cs new file mode 100644 index 0000000..699cdd5 --- /dev/null +++ b/src/Cake.CodeQL.Cli/CodeQLTool.cs @@ -0,0 +1,81 @@ +namespace Cake.CodeQL.Cli; + +/// +/// Base class for all CodeQL Scanning tools. +/// +/// The settings type. +public abstract class CodeQLTool : Tool + where TSettings : CodeQLToolSettings +{ + /// + /// Initializes a new instance of the class. + /// + /// The file system. + /// The environment. + /// The process runner. + /// The tool locator. + /// Cake log instance. + protected CodeQLTool(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools, ICakeLog log) + : base(fileSystem, environment, processRunner, tools) + { + CakeLog = log; + } + + /// + /// Cake log instance. + /// + public ICakeLog CakeLog { get; } + + /// + /// Gets the name of the tool. + /// + /// The name of the tool. + protected sealed override string GetToolName() => "CodeQL"; + + /// + /// Gets the possible names of the tool executable. + /// + /// The tool executable name. + protected sealed override IEnumerable GetToolExecutableNames() => new[] { "codeql", "codeql.exe" }; + + /// + /// Runs libman. + /// + /// The settings. + protected void RunCore(TSettings settings) => RunCore(settings, new ProcessSettings(), null); + + /// + /// Runs CodeQL. + /// + /// The settings. + /// The process settings. null for default settings. + /// Action which should be executed after running libman. null for no action. + protected void RunCore(TSettings settings, ProcessSettings processSettings, Action postAction) + { + if (settings == null) throw new ArgumentNullException(nameof(settings)); + + if (!settings.CakeVerbosityLevel.HasValue) + settings.CakeVerbosityLevel = CakeLog.Verbosity; + + processSettings.RedirectStandardError = settings.RedirectStandardError; + processSettings.RedirectStandardOutput = settings.RedirectStandardOutput; + + var args = GetArguments(settings); + Run(settings, args, processSettings, postAction); + } + + /// + /// Builds the arguments for codeQL. + /// + /// Settings used for building the arguments. + /// Argument builder containing the arguments based on . + protected ProcessArgumentBuilder GetArguments(TSettings settings) + { + var args = new ProcessArgumentBuilder(); + settings.Evaluate(args); + + CakeLog.Verbose("CodeQL arguments: {0}", args.RenderSafe()); + + return args; + } +} diff --git a/src/Cake.CodeQL.Cli/CodeQLToolSettings.cs b/src/Cake.CodeQL.Cli/CodeQLToolSettings.cs new file mode 100644 index 0000000..e9e7f47 --- /dev/null +++ b/src/Cake.CodeQL.Cli/CodeQLToolSettings.cs @@ -0,0 +1,58 @@ +namespace Cake.CodeQL.Cli; + +#pragma warning disable CS1711 // XML comment has a typeparam tag, but there is no type parameter by that name +/// +/// Base class for all CodeQL cli tools. +/// +/// The settings type. +public abstract class CodeQLToolSettings : ToolSettings +#pragma warning restore CS1711 // XML comment has a typeparam tag, but there is no type parameter by that name +{ + /// + /// Initializes a new instance of the class. + /// + /// Command to run. + protected CodeQLToolSettings(string command) + { + Command = command; + RedirectStandardError = false; + RedirectStandardOutput = false; + } + + /// + /// Gets or sets the process option to redirect standard error + /// + public bool RedirectStandardError { get; set; } + + /// + /// Gets or sets the process option to redirect standard output + /// + public bool RedirectStandardOutput { get; set; } + + /// + /// Gets or sets the Log level set by Cake. + /// + internal Verbosity? CakeVerbosityLevel { get; set; } + + /// + /// Gets the command which should be run. + /// + protected string Command { get; private set; } + + /// + /// Evaluates the settings and writes them to . + /// + /// The argument builder into which the settings should be written. + internal void Evaluate(ProcessArgumentBuilder args) + { + args.Append(Command); + EvaluateCore(args); + } + + /// + /// Evaluates the settings and writes them to . + /// + /// The argument builder into which the settings should be written. + protected virtual void EvaluateCore(ProcessArgumentBuilder args) + { } +} diff --git a/src/Cake.CodeQL.Cli/Database/CodeLanguage.cs b/src/Cake.CodeQL.Cli/Database/CodeLanguage.cs new file mode 100644 index 0000000..bd14869 --- /dev/null +++ b/src/Cake.CodeQL.Cli/Database/CodeLanguage.cs @@ -0,0 +1,36 @@ +namespace Cake.CodeQL.Cli.Database; + +/// +/// Coding Language(s) to scan +/// +public enum CodeLanguage +{ + /// + /// C++ programming langugage + /// + cpp, + /// + /// C# programming language + /// + csharp, + /// + /// Go programming language + /// + go, + /// + /// Java programming language + /// + java, + /// + /// Javascript (including TypeScript) programming lanaguage + /// + javascript, + /// + /// Python programming language + /// + python, + /// + /// Ruby programming language + /// + ruby +} diff --git a/src/Cake.CodeQL.Cli/Database/CodeQLAnalyzeDatabaseTool.cs b/src/Cake.CodeQL.Cli/Database/CodeQLAnalyzeDatabaseTool.cs new file mode 100644 index 0000000..9ab0cad --- /dev/null +++ b/src/Cake.CodeQL.Cli/Database/CodeQLAnalyzeDatabaseTool.cs @@ -0,0 +1,31 @@ +namespace Cake.CodeQL.Cli.Database; + +/// +/// Tool for analyzing CodeQL Databases that can be use for vunerability scanning +/// +public class CodeQLAnalyzeDatabaseTool : CodeQLTool +{ + /// + /// Initializes a new instance of the class. + /// + /// The file system. + /// The environment. + /// The process runner. + /// The tool locator. + /// Cake log instance. + public CodeQLAnalyzeDatabaseTool(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools, ICakeLog log) + : base(fileSystem, environment, processRunner, tools, log) + { } + + /// + /// Run queries to analyze each CodeQL database and summarize the results in a SARIF file. + /// + /// The settings. + public void AnalyzeDatabase(CodeQLAnalyzeDatabaseToolSettings settings) + { + if (settings == null) + throw new ArgumentNullException(nameof(settings)); + + RunCore(settings); + } +} diff --git a/src/Cake.CodeQL.Cli/Database/CodeQLAnalyzeDatabaseToolSettings.cs b/src/Cake.CodeQL.Cli/Database/CodeQLAnalyzeDatabaseToolSettings.cs new file mode 100644 index 0000000..8e28837 --- /dev/null +++ b/src/Cake.CodeQL.Cli/Database/CodeQLAnalyzeDatabaseToolSettings.cs @@ -0,0 +1,108 @@ +namespace Cake.CodeQL.Cli.Database; + +/// +/// Tool for creating CodeQL databases +/// +public class CodeQLAnalyzeDatabaseToolSettings : CodeQLToolSettings +{ + private readonly List _queryPacks = new List(); + + /// + /// Initializes a new instance of the + /// + public CodeQLAnalyzeDatabaseToolSettings() + : base("database analyze") + { } + + /// + /// Specifies the path for the directory that contains the CodeQL database to analyze. + /// + /// This is required + public DirectoryPath DatabaseDir { get; set; } + + /// + /// Specify CodeQL packs or queries to run. To run the standard queries used for code scanning, omit this parameter. + /// To see the other query suites included in the CodeQL CLI bundle, look in /<extraction-root>/qlpacks/codeql/<language>-queries/codeql-suites. + /// For information about creating your own query suite, see Creating CodeQL query suites in the documentation for the CodeQL CLI. + /// + public IList QueryPacks=> _queryPacks; + + /// + /// Specify the format for the results file generated by the command. For upload to GitHub this should be: sarifv2.1.0 + /// + /// + /// This is required. Defaults to sarifv2.1.0 + /// + public string Format { get; set; } = "sarifv2.1.0"; + + /// + /// Specify where to save the SARIF results file. + /// + /// + /// This is required + /// + public FilePath OutputFile { get; set; } + + /// + /// Optional for single database analysis. Required to define the language when you analyze multiple databases for a single commit in a repository. + /// Specify a category to include in the SARIF results file for this analysis. + /// A category is used to distinguish multiple analyses for the same tool and commit, but performed on different languages or different parts of the code. + /// + public string SarifCategory { get; set; } + + /// + /// Optional. Use if you want to include any available markdown-rendered query help for custom queries used in your analysis. + /// Any query help for custom queries included in the SARIF output will be displayed in the code scanning UI if the relevant query generates an alert. + /// + public string SarifAddQueryHelp { get; set; } + + /// + /// Use if you want to use more than one thread to run queries. + /// The default value is 1. You can specify more threads to speed up query execution. + /// To set the number of threads to the number of logical processors, specify 0. + /// + public int? Threads { get; set; } + + /// + /// Optional. Use to get more detailed information about the analysis process and diagnostic data from the database creation process + /// + public bool Verbose { get; set; } + + /// + /// Evaluates the settings and writes them to . + /// + /// The argument builder into which the settings should be written. + protected override void EvaluateCore(ProcessArgumentBuilder args) + { + const string equals = "="; + + base.EvaluateCore(args); + + if (DatabaseDir == null) throw new ArgumentNullException(nameof(DatabaseDir), $"Missing required {nameof(DatabaseDir)} property."); + if (OutputFile == null) throw new ArgumentNullException(nameof(OutputFile), $"Missing required {nameof(OutputFile)} property."); + if (string.IsNullOrWhiteSpace(Format)) throw new ArgumentException(nameof(Format), $"Missing required {nameof(Format)} property."); + if(Threads.HasValue && Threads.Value < 0) throw new ArgumentException(nameof(Threads), $"{nameof(Threads)} property cannot have a value less than 0."); + + args.AppendQuoted(DatabaseDir.FullPath); + + if (QueryPacks.Any()) + foreach (var queryPack in QueryPacks) + args.Append(queryPack); + + args.AppendSwitch("--format", equals, Format); + + args.AppendSwitchQuoted("--output", equals, OutputFile.FullPath); + + if (!string.IsNullOrWhiteSpace(SarifCategory)) + args.AppendSwitch("--sarif-category", equals, SarifCategory); + + if (!string.IsNullOrWhiteSpace(SarifAddQueryHelp)) + args.AppendSwitchQuoted("--sarif-add-query-help", equals, SarifAddQueryHelp); + + if (Threads.HasValue) + args.AppendSwitch("--threads", equals, Threads.Value.ToString()); + + if (Verbose) + args.Append("--verbose"); + } +} diff --git a/src/Cake.CodeQL.Cli/Database/CodeQLCreateDatabaseTool.cs b/src/Cake.CodeQL.Cli/Database/CodeQLCreateDatabaseTool.cs new file mode 100644 index 0000000..5126682 --- /dev/null +++ b/src/Cake.CodeQL.Cli/Database/CodeQLCreateDatabaseTool.cs @@ -0,0 +1,31 @@ +namespace Cake.CodeQL.Cli.Database; + +/// +/// Tool for create CodeQL Databases that can be use for vunerability scanning +/// +public class CodeQLCreateDatabaseTool : CodeQLTool +{ + /// + /// Initializes a new instance of the class. + /// + /// The file system. + /// The environment. + /// The process runner. + /// The tool locator. + /// Cake log instance. + public CodeQLCreateDatabaseTool(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools, ICakeLog log) + : base(fileSystem, environment, processRunner, tools, log) + { } + + /// + /// Create a CodeQL database to represent the hierarchical structure of each supported programming language in the repository. + /// + /// The settings. + public void CreateDatabase(CodeQLCreateDatabaseToolSettings settings) + { + if (settings == null) + throw new ArgumentNullException(nameof(settings)); + + RunCore(settings); + } +} diff --git a/src/Cake.CodeQL.Cli/Database/CodeQLCreateDatabaseToolSettings.cs b/src/Cake.CodeQL.Cli/Database/CodeQLCreateDatabaseToolSettings.cs new file mode 100644 index 0000000..51b4de5 --- /dev/null +++ b/src/Cake.CodeQL.Cli/Database/CodeQLCreateDatabaseToolSettings.cs @@ -0,0 +1,95 @@ +namespace Cake.CodeQL.Cli.Database; + +/// +/// Tool for creating CodeQL databases +/// +public class CodeQLCreateDatabaseToolSettings : CodeQLToolSettings +{ + private readonly List _languages = new List(); + + /// + /// Initializes a new instance of the + /// + /// + /// codeql database create /codeql-dbs/example-repo --language=javascript --source-root /checkouts/example-repo + /// + public CodeQLCreateDatabaseToolSettings () + : base("database create") + { } + + /// + /// Specify the location of a directory to create for the CodeQL database. The command will fail if you try to overwrite an existing directory. If you also specify --db-cluster, this is the parent directory and a subdirectory is created for each language analyzed. + /// + /// This is required + public DirectoryPath DatabaseDir { get; set; } + + /// + /// One or more CodeLanguage to create CodeQL Database for. + /// Specify the identifier for the language to create a database for, one of: cpp`, `csharp`, `go`, `java`, `javascript`, `python`, and `ruby (use javascript to analyze TypeScript code). When used with --db-cluster, the option accepts a comma-separated list, or can be specified more than once. + /// + /// This is required + public IList Languages => _languages; + + /// + ///Recommended. Use to specify the build command or script that invokes the build process for the codebase. Commands are run from the current folder or, where it is defined, from --source-root. Not needed for Python and JavaScript/TypeScript analysis. + /// + public string BuildCommand { get; set; } + + /// + /// Optional. Use in multi-language codebases to generate one database for each language specified. + /// + public bool DbCluster { get; set; } + + /// + /// Recommended. Use to suppress the build command for languages where the CodeQL CLI does not need to monitor the build (for example, Python and JavaScript/TypeScript). + /// + public bool NoRunUnnecessaryBuilds { get; set; } + + /// + /// Optional. Use if you run the CLI outside the checkout root of the repository. By default, the database create command assumes that the current directory is the root directory for the source files, use this option to specify a different location. + /// + public DirectoryPath SourceRootDir { get; set; } + + /// + /// Advanced. Optional (Advanced). Use if you have a configuration file that specifies how to create the CodeQL databases and what queries to run in later steps. + /// + public FilePath CodeScanningConfigFile { get; set; } + + /// + /// Evaluates the settings and writes them to . + /// + /// The argument builder into which the settings should be written. + protected override void EvaluateCore(ProcessArgumentBuilder args) + { + const string separator = "="; + + base.EvaluateCore(args); + + if (DatabaseDir == null) throw new ArgumentNullException(nameof(DatabaseDir), $"Missing required {nameof(DatabaseDir)} property."); + if (!_languages.Any()) throw new ArgumentException(nameof(Languages), $"At least one coding language is required to be specified."); + + args.AppendQuoted(DatabaseDir.FullPath); + + args.AppendSwitch("--language", separator, string.Join(',', _languages)); + + if (!string.IsNullOrWhiteSpace(BuildCommand)) + { + if (BuildCommand.Contains(separator)) + args.AppendSwitchQuoted("--command", separator, BuildCommand); + else + args.AppendSwitch("--command", separator, BuildCommand); + } + + if (DbCluster) + args.Append("--db-cluster"); + + if (NoRunUnnecessaryBuilds) + args.Append("--no-run-unnecessary-builds"); + + if (SourceRootDir != null) + args.AppendSwitchQuoted("--source-root", separator, SourceRootDir.FullPath); + + if (CodeScanningConfigFile != null) + args.AppendSwitchQuoted("--codescanning-config", separator, CodeScanningConfigFile.FullPath); + } +} diff --git a/src/Cake.CodeQL.Cli/Install/CodeQLInstallTool.cs b/src/Cake.CodeQL.Cli/Install/CodeQLInstallTool.cs new file mode 100644 index 0000000..3115ee2 --- /dev/null +++ b/src/Cake.CodeQL.Cli/Install/CodeQLInstallTool.cs @@ -0,0 +1,109 @@ +namespace Cake.CodeQL.Cli.Install; + +/// +/// Tool for downloading and installing CodeQL +/// +public class CodeQLInstallTool +{ + private readonly ICakeContext _context; + + /// + /// Initializes a new instance of the class. + /// + /// The cake Context + public CodeQLInstallTool(ICakeContext cakeContext) => _context = cakeContext; + + /// + /// Downloads CodeQL and extracts bundle on the agent machine + /// + /// The settings. + public void Install(CodeQLInstallToolSettings settings) + { + if (settings == null) + throw new ArgumentNullException(nameof(settings)); + + // 1. Enusre CodeQL install status + var installDir = GetInstallDirectory(settings); + var dirExists = EnsureInstallDirectoryExists(settings, installDir); + + if (!dirExists) + { + var downloadFileUri = GetCodeQLDownloadUrl(); + var outFilePath = GetCodeQLFilePath(settings); + + // 2. Download CodeQL + _context.DownloadFile(downloadFileUri, outFilePath); + + // 3. Installs the CodeQL CLI on the Host Operating System. + ExtractCodeQL(outFilePath, installDir); + } + + // 4. Verifies that the CodeQL CLI is correctly set up to create and analyze databases. + VerifyCodeQL(); + } + + /// + /// Ensures the codeql directory exists....if Force set to true. This will always return false. + /// + /// + /// + /// + private bool EnsureInstallDirectoryExists(CodeQLInstallToolSettings settings, DirectoryPath installDir) + { + var dirExists = _context.DirectoryExists(installDir); + + if (dirExists) + { + _context.Log.Verbose("CodeQL install {0} directory already exists.", installDir.FullPath); + if (settings.Force) + { + _context.Log.Information("Force install requested. Deleting existing install directory {0}", installDir.FullPath); + _context.EnsureDirectoryDoesNotExist(installDir); + dirExists = false; + } + else + return true; + } + + _context.EnsureDirectoryExists(installDir); + + return dirExists; + } + + private void ExtractCodeQL(FilePath outFilePath, DirectoryPath installDir) + { + var argBuilder = new ProcessArgumentBuilder(); + + argBuilder.Append("-xvzf"); + argBuilder.AppendQuoted(outFilePath.FullPath); + argBuilder.Append("-C"); + argBuilder.AppendQuoted(installDir.FullPath); + + _context.StartProcess("tar", new ProcessSettings { Arguments = argBuilder }); + } + + private void VerifyCodeQL() => _context.Command(toolExecutableNames: new[] { "codeql", "codeql.exe" }, arguments: "resolve qlpacks"); + + private DirectoryPath GetInstallDirectory(CodeQLInstallToolSettings settings) => + settings.InstallDirectory != null ? _context.MakeAbsolute(settings.InstallDirectory) : _context.MakeAbsolute(GetWorkingDirectory(settings).Combine("tools/codeql")); + + private DirectoryPath GetWorkingDirectory(CodeQLInstallToolSettings settings) => + settings.WorkingDirectory != null ? settings.WorkingDirectory : _context.Environment.WorkingDirectory; + + private FilePath GetCodeQLFilePath(CodeQLInstallToolSettings settings) + { + var workingDir = GetWorkingDirectory(settings); + var downloadFile = GetCodeQLDownloadUrl(); + var filePath = _context.File(System.IO.Path.GetFileName(downloadFile)); + + return workingDir.CombineWithFilePath(filePath); + } + + private string GetCodeQLDownloadUrl() => _context.Environment.Platform.Family switch + { + PlatformFamily.Linux => "https://github.com/github/codeql-action/releases/latest/download/codeql-bundle-linux64.tar.gz", + PlatformFamily.Windows => "https://github.com/github/codeql-action/releases/latest/download/codeql-bundle-win64.tar.gz", + PlatformFamily.OSX => "https://github.com/github/codeql-action/releases/latest/download/codeql-bundle-osx64.tar.gz", + _ => throw new NotSupportedException("Operating System is not supported.") + }; +} diff --git a/src/Cake.CodeQL.Cli/Install/CodeQLInstallToolSettings.cs b/src/Cake.CodeQL.Cli/Install/CodeQLInstallToolSettings.cs new file mode 100644 index 0000000..df0c902 --- /dev/null +++ b/src/Cake.CodeQL.Cli/Install/CodeQLInstallToolSettings.cs @@ -0,0 +1,24 @@ +namespace Cake.CodeQL.Cli.Install; + +/// +/// Tool for installing CodeQL on the host machine +/// +public class CodeQLInstallToolSettings +{ + /// + /// Gets or sets the working directory + /// + /// The working directory. + public DirectoryPath WorkingDirectory { get; set; } + + /// + /// Gets or sets the install directory that CodeQL will be extracted to. Defaults to "./tools/codeql" + /// + /// the install directory that CodeQL will be extracted tool. + public DirectoryPath InstallDirectory { get; set; } + + /// + /// Gets or Sets whether to force an install of CodeQL even if the tool is already installs + /// + public bool Force { get; set; } = false; +} diff --git a/src/Cake.CodeQL.Cli/Namespaces.cs b/src/Cake.CodeQL.Cli/Namespaces.cs new file mode 100644 index 0000000..59a5ce4 --- /dev/null +++ b/src/Cake.CodeQL.Cli/Namespaces.cs @@ -0,0 +1,46 @@ +using System.Runtime.CompilerServices; + +namespace Cake.CodeQL.Cli +{ + /// + /// This namespace contain types used for operations using the CodeQL tool wrapper. + /// + [CompilerGenerated] + internal class NamespaceDoc + { + } +} + + +namespace Cake.CodeQL.Cli.Database +{ + /// + /// This namespace contain types used for database operations for CodeQL. + /// + [CompilerGenerated] + internal class NamespaceDoc + { + } +} + +namespace Cake.CodeQL.Cli.Upload +{ + /// + /// This namespace contain types used to upload results to github for for CodeQL. + /// + [CompilerGenerated] + internal class NamespaceDoc + { + } +} + +namespace Cake.CodeQL.CliInstall +{ + /// + /// This namespace contain types used to install CodeQL + /// + [CompilerGenerated] + internal class NamespaceDoc + { + } +} \ No newline at end of file diff --git a/src/Cake.CodeQL.Cli/Properties/InternalsVisibleInfo.cs b/src/Cake.CodeQL.Cli/Properties/InternalsVisibleInfo.cs new file mode 100644 index 0000000..2112629 --- /dev/null +++ b/src/Cake.CodeQL.Cli/Properties/InternalsVisibleInfo.cs @@ -0,0 +1,3 @@ +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Cake.CodeQL.Tests")] \ No newline at end of file diff --git a/src/Cake.CodeQL/Properties/NamespaceDoc.cs b/src/Cake.CodeQL.Cli/Properties/NamespaceDoc.cs similarity index 71% rename from src/Cake.CodeQL/Properties/NamespaceDoc.cs rename to src/Cake.CodeQL.Cli/Properties/NamespaceDoc.cs index b378a82..780f3c6 100644 --- a/src/Cake.CodeQL/Properties/NamespaceDoc.cs +++ b/src/Cake.CodeQL.Cli/Properties/NamespaceDoc.cs @@ -1,9 +1,9 @@ using System.Runtime.CompilerServices; -namespace Cake.EntityFrameworkCore +namespace Cake.CodeQL { /// - /// This namespace contain types used for operations using the EntityFrameworkCore tool wrapper. + /// This namespace contain types used for operations using the CodeQL Cli tool wrapper. /// [CompilerGenerated] internal class NamespaceDoc @@ -11,10 +11,10 @@ internal class NamespaceDoc } -namespace Cake.EntityFrameworkCore.Database +namespace Cake.CodeQL.Database { /// - /// This namespace contain types used for operations using the EntityFrameworkCore tool wrapper. + /// This namespace contain types used for operations using the CodeQL Cli tool wrapper. /// [CompilerGenerated] internal class NamespaceDoc diff --git a/src/Cake.CodeQL.Cli/Upload/CodeQLUploadResultsTool.cs b/src/Cake.CodeQL.Cli/Upload/CodeQLUploadResultsTool.cs new file mode 100644 index 0000000..c83b4d8 --- /dev/null +++ b/src/Cake.CodeQL.Cli/Upload/CodeQLUploadResultsTool.cs @@ -0,0 +1,31 @@ +namespace Cake.CodeQL.Cli.Upload; + +/// +/// Tool for uploading CodeQL Sarif result(s) to github +/// +public class CodeQLUploadResultsTool : CodeQLTool +{ + /// + /// Initializes a new instance of the class. + /// + /// The file system. + /// The environment. + /// The process runner. + /// The tool locator. + /// Cake log instance. + public CodeQLUploadResultsTool(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools, ICakeLog log) + : base(fileSystem, environment, processRunner, tools, log) + { } + + /// + /// Uploads the sarif results of a CodeQL result to GitHub Server or GitHub + /// + /// The settings. + public void UploadSarifFileResults(CodeQLUploadResultsToolSettings settings) + { + if (settings == null) + throw new ArgumentNullException(nameof(settings)); + + RunCore(settings); + } +} diff --git a/src/Cake.CodeQL.Cli/Upload/CodeQLUploadResultsToolSettings.cs b/src/Cake.CodeQL.Cli/Upload/CodeQLUploadResultsToolSettings.cs new file mode 100644 index 0000000..dc79446 --- /dev/null +++ b/src/Cake.CodeQL.Cli/Upload/CodeQLUploadResultsToolSettings.cs @@ -0,0 +1,74 @@ +namespace Cake.CodeQL.Cli.Upload; + +/// +/// Tool for uploading results to GitHub +/// +public class CodeQLUploadResultsToolSettings : CodeQLToolSettings +{ + /// + /// Initializes a new instance of the + /// + /// + /// codeql github upload-results --repository=<repository-name> --ref=<ref> --commit=<commit> --sarif=<file> --github-url=<URL> --github-auth-stdin + /// + public CodeQLUploadResultsToolSettings() + : base("github upload-results") + { } + + /// + /// Specify the OWNER/NAME of the repository to upload data to. The owner must be an organization within an enterprise that has a license for GitHub Advanced Security and GitHub Advanced Security must be enabled for the repository. + /// + public string RepositoryName { get; set; } + + /// + /// Specify the name of the ref you checked out and analyzed so that the results can be matched to the correct code. For a branch use: refs/heads/BRANCH-NAME, for the head commit of a pull request use refs/pull/NUMBER/head, or for the GitHub-generated merge commit of a pull request use refs/pull/NUMBER/merge. + /// + public string Ref { get; set; } + + /// + /// Specify the full SHA of the commit you analyzed. + /// + public string Commit { get; set; } + + /// + /// Specify the SARIF file to load. + /// + public FilePath SarifFilePath { get; set; } + + /// + /// Specify the URL for GitHub Enterprise Server. If blanks,defaults to to github.com. + /// + public string GitHubUrl { get; set; } + + /// + /// Optional. Use to pass the CLI the GitHub App or personal access token created for authentication with GitHub's REST API via standard input. This is not needed if the command has access to a GITHUB_TOKEN environment variable set with this token. + /// + public bool GitHubAuthStdin { get; set; } = false; + + /// + /// Evaluates the settings and writes them to . + /// + /// The argument builder into which the settings should be written. + protected override void EvaluateCore(ProcessArgumentBuilder args) + { + const string separator = "="; + + base.EvaluateCore(args); + + if (string.IsNullOrWhiteSpace(RepositoryName)) throw new ArgumentNullException(nameof(RepositoryName), $"Missing required {nameof(RepositoryName)} property."); + if (string.IsNullOrWhiteSpace(Ref)) throw new ArgumentNullException(nameof(RepositoryName), $"Missing required {nameof(Ref)} property."); + if (string.IsNullOrWhiteSpace(Commit)) throw new ArgumentNullException(nameof(Commit), $"Missing required {nameof(Commit)} property."); + if (SarifFilePath == null) throw new ArgumentException(nameof(SarifFilePath), $"Missing required {nameof(SarifFilePath)} property."); + + args.AppendSwitch("--repository", separator, RepositoryName); + args.AppendSwitch("--ref", separator, Ref); + args.AppendSwitch("--commit", separator, Commit); + args.AppendSwitchQuoted("--sarif", separator, SarifFilePath.FullPath); + + if (!string.IsNullOrWhiteSpace(GitHubUrl)) + args.AppendSwitchQuoted("--github-url", separator, GitHubUrl); + + if (GitHubAuthStdin) + args.Append("--github-auth-stdin"); + } +} diff --git a/src/Cake.CodeQL.Cli/_Usings.cs b/src/Cake.CodeQL.Cli/_Usings.cs new file mode 100644 index 0000000..3e4c00c --- /dev/null +++ b/src/Cake.CodeQL.Cli/_Usings.cs @@ -0,0 +1,12 @@ +global using Cake.CodeQL.Cli.Database; +global using Cake.CodeQL.Cli.Upload; +global using Cake.Common; +global using Cake.Common.IO; +global using Cake.Common.Net; +global using Cake.Common.Tools.Command; +global using Cake.Core; +global using Cake.Core.Annotations; +global using Cake.Core.Diagnostics; +global using Cake.Core.IO; +global using Cake.Core.Tooling; +global using System.Reflection; diff --git a/src/Cake.CodeQL.Cli/icon.png b/src/Cake.CodeQL.Cli/icon.png new file mode 100644 index 0000000..fce71e5 Binary files /dev/null and b/src/Cake.CodeQL.Cli/icon.png differ diff --git a/src/Cake.CodeQL.Tests/Cake.EntityFrameworkCore.Tests.csproj b/src/Cake.CodeQL.Tests/Cake.EntityFrameworkCore.Tests.csproj deleted file mode 100644 index 823eb3a..0000000 --- a/src/Cake.CodeQL.Tests/Cake.EntityFrameworkCore.Tests.csproj +++ /dev/null @@ -1,30 +0,0 @@ - - - - net5.0 - - false - - - - - - - - - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - - - - - - - - diff --git a/src/Cake.CodeQL.Tests/Extensions/ExceptionAssertExtensions.cs b/src/Cake.CodeQL.Tests/Extensions/ExceptionAssertExtensions.cs deleted file mode 100644 index f6969c2..0000000 --- a/src/Cake.CodeQL.Tests/Extensions/ExceptionAssertExtensions.cs +++ /dev/null @@ -1,24 +0,0 @@ -namespace Cake.EntityFrameworkCore.Tests -{ - using System; - using Xunit; - - public static class ExceptionAssertExtensions - { - public static void IsArgumentException(this Exception exception, string parameterName) - { - Assert.IsType(exception); - Assert.Equal(parameterName, ((ArgumentException)exception).ParamName); - } - - public static void IsArgumentNullException(this Exception exception, string parameterName) - { - Assert.IsType(exception); - Assert.Equal(parameterName, ((ArgumentNullException)exception).ParamName); - } - - public static void IsNotSupportException(this Exception exception) => Assert.IsType(exception); - - public static void IsUriFormatException(this Exception exception) => Assert.IsType(exception); - } -} diff --git a/src/Cake.CodeQL.Tests/Fixtures/EfCoreDatabaseUpdaterFixture.cs b/src/Cake.CodeQL.Tests/Fixtures/EfCoreDatabaseUpdaterFixture.cs deleted file mode 100644 index cbf7ca2..0000000 --- a/src/Cake.CodeQL.Tests/Fixtures/EfCoreDatabaseUpdaterFixture.cs +++ /dev/null @@ -1,13 +0,0 @@ -using Cake.EntityFrameworkCore.Database; - -namespace Cake.EntityFrameworkCore.Tests.Database -{ - internal sealed class EfCoreDatabaseUpdaterFixture : EfCoreToolFixture - { - protected override void RunTool() - { - var tool = new EfCoreDatabaseUpdater(FileSystem, Environment, ProcessRunner, Tools, Log); - tool.Update(Settings); - } - } -} diff --git a/src/Cake.CodeQL.Tests/Fixtures/EfCoreToolFixture.cs b/src/Cake.CodeQL.Tests/Fixtures/EfCoreToolFixture.cs deleted file mode 100644 index 725baef..0000000 --- a/src/Cake.CodeQL.Tests/Fixtures/EfCoreToolFixture.cs +++ /dev/null @@ -1,22 +0,0 @@ -using Cake.Core.Diagnostics; -using Cake.Core.IO; -using Cake.Testing; -using Cake.Testing.Fixtures; - -namespace Cake.EntityFrameworkCore.Tests -{ - internal abstract class EfCoreToolFixture : ToolFixture - where TSettings : EfCoreToolSettings, new() - { - protected EfCoreToolFixture() - : base("dotnet.exe") - { - ProcessRunner.Process.SetStandardOutput(new string[] { }); - Log.Verbosity = Verbosity.Normal; - } - - protected override ToolFixtureResult CreateResult(FilePath path, ProcessSettings process) => new ToolFixtureResult(path, process); - - protected ICakeLog Log { get; } = new FakeLog(); - } -} diff --git a/src/Cake.CodeQL.Tests/Unit/EfCoreDatabaseUpdateSettingsExtensionsTests.cs b/src/Cake.CodeQL.Tests/Unit/EfCoreDatabaseUpdateSettingsExtensionsTests.cs deleted file mode 100644 index fd8a2fc..0000000 --- a/src/Cake.CodeQL.Tests/Unit/EfCoreDatabaseUpdateSettingsExtensionsTests.cs +++ /dev/null @@ -1,25 +0,0 @@ -using Cake.EntityFrameworkCore.Database; -using Shouldly; -using Xunit; - -namespace Cake.EntityFrameworkCore.Tests -{ - public sealed class EfCoreDatabaseUpdateSettingsExtensionsTests - { - public sealed class TheSetTargetMigration - { - [Fact] - public void Should_Set_Migrations() - { - // Given - var settings = new EfCoreDatabaseUpdateSettings(); - - // When - settings.SetTargetMigration(@"20201221_MyTable_Change"); - - // Then - settings.Migration.ShouldBe(@"20201221_MyTable_Change"); - } - } - } -} diff --git a/src/Cake.CodeQL.Tests/Unit/EfCoreDatabaseUpdaterTests.cs b/src/Cake.CodeQL.Tests/Unit/EfCoreDatabaseUpdaterTests.cs deleted file mode 100644 index 84623f4..0000000 --- a/src/Cake.CodeQL.Tests/Unit/EfCoreDatabaseUpdaterTests.cs +++ /dev/null @@ -1,51 +0,0 @@ -using Cake.Core.IO; -using System; -using Xunit; - -namespace Cake.EntityFrameworkCore.Tests.Database -{ - public sealed class EfCoreDatabaseUpdaterTests - { - public sealed class TheUpdateMethod - { - [Fact] - public void Should_Throw_If_Settings_Are_Null() - { - // Given - var fixture = new EfCoreDatabaseUpdaterFixture(); - fixture.Settings = null; - - // When - var result = Record.Exception(() => fixture.Run()); - - // Then - result.IsArgumentNullException("settings"); - } - - [Fact] - public void Should_Update() - { - // Given - var fixture = new EfCoreDatabaseUpdaterFixture(); - - fixture.Tools.RegisterFile("c:/myproject/tools/Microsoft.EntityFrameworkCore.Tools.5.0.4/netcoreapp2.0/any/ef.dll"); - - fixture.Settings.WorkingDirectory = "c:/myproject"; - fixture.Settings.DbContextClassName = "MyDbContext"; - fixture.Settings.MigrationsNamespace = "My.Demo.Migrations"; - fixture.Settings.MigrationDll = "MyNamespace.Migrations.dll"; - fixture.Settings.StartupDll = "MyNamespace.WebUI.dll"; - fixture.Settings.Verbose = true; - fixture.Settings.Version = true; - - // When - var result = fixture.Run(); - - // Then - var expected = $"exec --depsfile \"c:/myproject/MyNamespace.WebUI.deps.json\" --additionalprobingpath \"{DirectoryPath.FromString(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))}/.nuget/packages\" --runtimeconfig \"c:/myproject/MyNamespace.Migrations.runtimeconfig.json\" \"c:/myproject/tools/Microsoft.EntityFrameworkCore.Tools.5.0.4/netcoreapp2.0/any/ef.dll\" database update --assembly \"c:/myproject/MyNamespace.Migrations.dll\" --startup-assembly \"c:/myproject/MyNamespace.WebUI.dll\" --project-dir \"c:/myproject\" --data-dir \"c:/myproject\" --context \"MyDbContext\" --root-namespace \"My.Demo.Migrations\" --verbose"; - - Assert.Equal(expected, result.Args); - } - } - } -} diff --git a/src/Cake.CodeQL.Tests/Unit/EfCoreSettingsExtensionsTests.cs b/src/Cake.CodeQL.Tests/Unit/EfCoreSettingsExtensionsTests.cs deleted file mode 100644 index eb8e3b7..0000000 --- a/src/Cake.CodeQL.Tests/Unit/EfCoreSettingsExtensionsTests.cs +++ /dev/null @@ -1,231 +0,0 @@ -using Shouldly; -using Xunit; - -namespace Cake.EntityFrameworkCore.Tests -{ - public sealed class EfCoreToolSettingsExtensionsTests - { - public sealed class TheSetVerboseMethod - { - [Fact] - public void Should_Throw_If_Settings_Are_Null() - { - // Given - EfCoreToolSettings settings = null; - - // When - var result = Record.Exception(() => settings.SetVerbose()); - - // Then - result.IsArgumentNullException(nameof(settings)); - } - - [Fact] - public void Should_Set_Verbose_To_True() - { - // Given - var settings = new EfCoreToolSettings(); - - // When - settings.SetVerbose(); - - // Then - settings.Verbose.ShouldBeTrue(); - } - } - - public sealed class TheSetNoColorMethod - { - [Fact] - public void Should_Throw_If_Settings_Are_Null() - { - // Given - EfCoreToolSettings settings = null; - - // When - var result = Record.Exception(() => settings.SetNoColor()); - - // Then - result.IsArgumentNullException(nameof(settings)); - } - - [Fact] - public void Should_Set_NoColor_To_True() - { - // Given - var settings = new EfCoreToolSettings(); - - // When - settings.SetNoColor(); - - // Then - settings.NoColor.ShouldBeTrue(); - } - } - - public sealed class TheSetPrefixOutputMethod - { - [Fact] - public void Should_Throw_If_Settings_Are_Null() - { - // Given - EfCoreToolSettings settings = null; - - // When - var result = Record.Exception(() => settings.SetPrefixOutput()); - - // Then - result.IsArgumentNullException(nameof(settings)); - } - - [Fact] - public void Should_Set_PrefixOutput_To_True() - { - // Given - var settings = new EfCoreToolSettings(); - - // When - settings.SetPrefixOutput(); - - // Then - settings.PrefixOutput.ShouldBeTrue(); - } - } - - public sealed class TheSetVersionMethod - { - [Fact] - public void Should_Throw_If_Settings_Are_Null() - { - // Given - EfCoreToolSettings settings = null; - - // When - var result = Record.Exception(() => settings.SetVersion()); - - // Then - result.IsArgumentNullException(nameof(settings)); - } - - [Fact] - public void Should_Set_Version_To_True() - { - // Given - var settings = new EfCoreToolSettings(); - - // When - settings.SetVersion(); - - // Then - settings.Version.ShouldBeTrue(); - } - - } - - public sealed class TheFromPathMethod - { - [Fact] - public void Should_Throw_If_Settings_Are_Null() - { - // Given - EfCoreToolSettings settings = null; - - // When - var result = Record.Exception(() => settings.FromPath(@"c:\temp")); - - // Then - result.IsArgumentNullException(nameof(settings)); - } - - [Fact] - public void Should_Throw_If_Path_Is_Null() - { - // Given - var settings = new EfCoreToolSettings(); - - // When - var result = Record.Exception(() => settings.FromPath(null)); - - // Then - result.IsArgumentNullException("path"); - } - - [Fact] - public void Should_Set_WorkingDirectory() - { - // Given - var settings = new EfCoreToolSettings(); - - // When - settings.FromPath(@"c:\temp"); - - // Then - settings.WorkingDirectory.ToString().ShouldBe(@"c:/temp"); - } - } - - public sealed class TheSetMigrationsDll - { - [Fact] - public void Should_Set_MigrationsDll() - { - // Given - var settings = new EfCoreToolSettings(); - - // When - settings.SetMigrationsDll(@"MyMigrations.dll"); - - // Then - settings.MigrationDll.ShouldBe(@"MyMigrations.dll"); - } - } - - public sealed class TheSetMigrationsNamespace - { - [Fact] - public void Should_Set_MigrationsNamespace() - { - // Given - var settings = new EfCoreToolSettings(); - - // When - settings.SetMigrationsNamespace("My.Demo.Migrations"); - - // Then - settings.MigrationsNamespace.ShouldBe("My.Demo.Migrations"); - } - } - - public sealed class TheSetStartupDll - { - [Fact] - public void Should_Set_StartupDll() - { - // Given - var settings = new EfCoreToolSettings(); - - // When - settings.SetStartupDll("MyWebUI.dll"); - - // Then - settings.StartupDll.ShouldBe("MyWebUI.dll"); - } - } - - public sealed class TheSetDbContextClass - { - [Fact] - public void Should_Set_DbContextClass() - { - // Given - var settings = new EfCoreToolSettings(); - - // When - settings.SetDbContextClass("MyDbContext"); - - // Then - settings.DbContextClassName.ShouldBe("MyDbContext"); - } - } - } -} diff --git a/src/Cake.CodeQL.sln b/src/Cake.CodeQL.sln deleted file mode 100644 index 41641af..0000000 --- a/src/Cake.CodeQL.sln +++ /dev/null @@ -1,43 +0,0 @@ - -Microsoft Visual Studio Solution File, Format Version 12.00 -# Visual Studio Version 17 -VisualStudioVersion = 17.3.32819.101 -MinimumVisualStudioVersion = 15.0.26124.0 -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Cake.CodeQL", "Cake.CodeQL\Cake.CodeQL.csproj", "{F04A19AD-4F4C-488C-9D3C-022032FC2357}" -EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{849370F8-B133-41C1-A0BF-B4027D16AFC0}" - ProjectSection(SolutionItems) = preProject - build.cake = build.cake - ..\README.md = ..\README.md - EndProjectSection -EndProject -Global - GlobalSection(SolutionConfigurationPlatforms) = preSolution - Debug|Any CPU = Debug|Any CPU - Debug|x64 = Debug|x64 - Debug|x86 = Debug|x86 - Release|Any CPU = Release|Any CPU - Release|x64 = Release|x64 - Release|x86 = Release|x86 - EndGlobalSection - GlobalSection(ProjectConfigurationPlatforms) = postSolution - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Debug|Any CPU.Build.0 = Debug|Any CPU - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Debug|x64.ActiveCfg = Debug|Any CPU - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Debug|x64.Build.0 = Debug|Any CPU - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Debug|x86.ActiveCfg = Debug|Any CPU - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Debug|x86.Build.0 = Debug|Any CPU - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Release|Any CPU.ActiveCfg = Release|Any CPU - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Release|Any CPU.Build.0 = Release|Any CPU - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Release|x64.ActiveCfg = Release|Any CPU - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Release|x64.Build.0 = Release|Any CPU - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Release|x86.ActiveCfg = Release|Any CPU - {F04A19AD-4F4C-488C-9D3C-022032FC2357}.Release|x86.Build.0 = Release|Any CPU - EndGlobalSection - GlobalSection(SolutionProperties) = preSolution - HideSolutionNode = FALSE - EndGlobalSection - GlobalSection(ExtensibilityGlobals) = postSolution - SolutionGuid = {7D15F748-7D66-45A7-A2C5-3119C8652D48} - EndGlobalSection -EndGlobal diff --git a/src/Cake.CodeQL/Database/EFCoreDatabaseUpdateAliases.cs b/src/Cake.CodeQL/Database/EFCoreDatabaseUpdateAliases.cs deleted file mode 100644 index 9f12f7c..0000000 --- a/src/Cake.CodeQL/Database/EFCoreDatabaseUpdateAliases.cs +++ /dev/null @@ -1,95 +0,0 @@ -using Cake.Core; -using Cake.Core.Annotations; -using Cake.EntityFrameworkCore; -using Cake.EntityFrameworkCore.Database; -using System; -using System.Runtime; - -namespace Cake.EntityFrameworkCore.Database -{ - /// - /// Entity Framework Core (ef.dll) Database Update aliases - /// - [CakeAliasCategory("EntityFrameworkCore")] - [CakeNamespaceImport("Cake.EntityFrameworkCore.Database")] - public static class EFCoreDatabaseUpdateAliases - { - /// - /// Applies any pending migrations to the database using the ef.dll migration tool. - /// - /// The context. - /// The settings configurator. - /// - /// Applies any pending migrations to the database using the ef.dll dotnet tool. ('dotnet ef database update') - /// - /// - /// { - /// settings - /// .FromPath(@"c:/myproject") - /// .SetDbContextClass("MyDbContext") - /// .SetMigrationsDll("MyMigrations.dll") - /// .SetMigrationsNamespace("My.Demo.Migrations") - /// .SetStartupDll("MyWebUI.dll") - /// .SetTargetMigration("20201221_MyTable_Change") - /// .SetVersion() - /// .SetNoColor() - /// .SetVerbose(); - /// }); - /// ]]> - /// - /// - [CakeMethodAlias] - [CakeAliasCategory("Database")] - public static void EfCoreDatabaseUpdate(this ICakeContext context, Action configurator) - { - if (context == null) - throw new ArgumentNullException(nameof(context)); - - if (configurator == null) - throw new ArgumentNullException(nameof(configurator)); - - var settings = new EfCoreDatabaseUpdateSettings(); - configurator(settings); - context.EfCoreDatabaseUpdate(settings); - } - - /// - /// Applies any pending migrations to the database using the ef.dll migration tool. - /// - /// The context. - /// The settings. - /// - /// Applies any pending migrations to the database using the ef.dll migration tool. ('dotnet ef database update') - /// - /// - /// - /// - [CakeMethodAlias] - [CakeAliasCategory("Database")] - public static void EfCoreDatabaseUpdate(this ICakeContext context, EfCoreDatabaseUpdateSettings settings) - { - if (context == null) - throw new ArgumentNullException(nameof(context)); - - if (settings == null) - throw new ArgumentNullException(nameof(settings)); - - EfCoreAddinInformation.LogVersionInformation(context.Log); - var tool = new EfCoreDatabaseUpdater(context.FileSystem, context.Environment, context.ProcessRunner, context.Tools, context.Log); - tool.Update(settings); - } - } -} \ No newline at end of file diff --git a/src/Cake.CodeQL/Database/EfCoreDatabaseUpdateSettings.cs b/src/Cake.CodeQL/Database/EfCoreDatabaseUpdateSettings.cs deleted file mode 100644 index ca98380..0000000 --- a/src/Cake.CodeQL/Database/EfCoreDatabaseUpdateSettings.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Cake.Common.Tools.DotNetCore; -using Cake.Core; -using Cake.Core.IO; - -namespace Cake.EntityFrameworkCore.Database -{ - /// - /// Contains settings used by . - /// - public class EfCoreDatabaseUpdateSettings : EfCoreToolSettings - { - /// - /// The target migration. If '0', all migrations will be reverted. Defaults to the last migration. - /// - public string Migration { get; set; } - } -} diff --git a/src/Cake.CodeQL/Database/EfCoreDatabaseUpdateSettingsExtensions.cs b/src/Cake.CodeQL/Database/EfCoreDatabaseUpdateSettingsExtensions.cs deleted file mode 100644 index af36324..0000000 --- a/src/Cake.CodeQL/Database/EfCoreDatabaseUpdateSettingsExtensions.cs +++ /dev/null @@ -1,34 +0,0 @@ -using Cake.Core; -using Cake.Core.Diagnostics; -using Cake.Core.IO; -using Cake.Core.Tooling; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Cake.EntityFrameworkCore.Database -{ - /// - /// Extensions for . - /// - public static class EfCoreDatabaseUpdateSettingsExtensions - { - /// - /// Sets a named target migration to migrate the database too. - /// - /// The settings. - /// The name of the migration to target - /// The instance with set to . - public static EfCoreDatabaseUpdateSettings SetTargetMigration(this EfCoreDatabaseUpdateSettings settings, string migration) - { - if (settings == null) - throw new ArgumentNullException(nameof(settings)); - - settings.Migration = migration; - - return settings; - } - } -} diff --git a/src/Cake.CodeQL/Database/EfCoreDatabaseUpdater.cs b/src/Cake.CodeQL/Database/EfCoreDatabaseUpdater.cs deleted file mode 100644 index 14283bf..0000000 --- a/src/Cake.CodeQL/Database/EfCoreDatabaseUpdater.cs +++ /dev/null @@ -1,57 +0,0 @@ -using Cake.Common.Tools.DotNetCore; -using Cake.Core; -using Cake.Core.Diagnostics; -using Cake.Core.IO; -using Cake.Core.Tooling; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime; -using System.Text; -using System.Threading.Tasks; - -namespace Cake.EntityFrameworkCore.Database -{ - /// - /// .Net Ef Core Database Updater using Migrations - /// - public class EfCoreDatabaseUpdater : EfCoreTool - { - private readonly ICakeEnvironment _environment; - - /// - /// Initializes a new instance of the class. - /// - /// The file system. - /// The environment. - /// The process runner. - /// The tool locator. - public EfCoreDatabaseUpdater(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools, ICakeLog log) - : base(fileSystem, environment, processRunner, tools, log) - { } - - - /// - /// Updates the database to a specified migration. - /// - /// The target migration. If '0', all migrations will be reverted. Defaults to the last migration.. - /// The settings. - public void Update(EfCoreDatabaseUpdateSettings settings) - { - if (settings == null) - throw new ArgumentNullException(nameof(settings)); - - RunCommand(settings, GetArguments(settings)); - } - - protected override ProcessArgumentBuilder AppendToolArguments(ProcessArgumentBuilder builder, EfCoreDatabaseUpdateSettings settings) - { - builder.Append("database update"); - - if (!string.IsNullOrEmpty(settings.Migration)) - builder.Append(settings.Migration); - - return builder; - } - } -} \ No newline at end of file diff --git a/src/Cake.CodeQL/EfCoreAddinInformation.cs b/src/Cake.CodeQL/EfCoreAddinInformation.cs deleted file mode 100644 index 20632a2..0000000 --- a/src/Cake.CodeQL/EfCoreAddinInformation.cs +++ /dev/null @@ -1,26 +0,0 @@ -using Cake.Core.Diagnostics; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Reflection; -using System.Text; -using System.Threading.Tasks; - -namespace Cake.EntityFrameworkCore -{ - internal static class EfCoreAddinInformation - { - private static readonly string InformationalVersion = typeof(EfCoreAddinInformation).GetTypeInfo().Assembly.GetCustomAttribute()?.InformationalVersion; - private static readonly string AssemblyVersion = typeof(EfCoreAddinInformation).GetTypeInfo().Assembly.GetName().Version.ToString(); - private static readonly string AssemblyName = typeof(EfCoreAddinInformation).GetTypeInfo().Assembly.GetName().Name; - - /// - /// verbosely log addin version information - /// - /// - public static void LogVersionInformation(ICakeLog log) - { - log.Verbose(entry => entry("Using addin: {0} v{1} ({2})", AssemblyName, AssemblyVersion, InformationalVersion)); - } - } -} diff --git a/src/Cake.CodeQL/EfCoreTool.cs b/src/Cake.CodeQL/EfCoreTool.cs deleted file mode 100644 index 690067c..0000000 --- a/src/Cake.CodeQL/EfCoreTool.cs +++ /dev/null @@ -1,90 +0,0 @@ -using Cake.Common.Tools.DotNetCore; -using Cake.Common.Tools.DotNetCore.Pack; -using Cake.Core; -using Cake.Core.Diagnostics; -using Cake.Core.IO; -using Cake.Core.Tooling; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Cake.EntityFrameworkCore -{ - /// - /// Base class for all efcore tools. - /// - /// The settings type. - public abstract class EfCoreTool : DotNetCoreTool - where TSettings : EfCoreToolSettings - { - protected readonly ICakeEnvironment _environment; - protected readonly ICakeLog _log; - private readonly IToolLocator _tools; - - /// - /// Initializes a new instance of the class. - /// - /// The file system. - /// The environment. - /// The process runner. - /// The tool locator. - protected EfCoreTool(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools, ICakeLog log) - : base(fileSystem, environment, processRunner, tools) - { - _environment = environment; - _log = log; - _tools = tools; - } - - /// - /// Adds specific tool commandline arguments. - /// - /// Process argument builder to update. - /// The settings. - /// Returns updated with common commandline arguments. - protected abstract ProcessArgumentBuilder AppendToolArguments(ProcessArgumentBuilder builder, TSettings settings); - - /// - /// Gets all the Arguments needed to run a ef command from a mgiration dll. - /// - /// The settings. - /// Returns updated with common commandline arguments. - protected ProcessArgumentBuilder GetArguments(TSettings settings) - { - var builder = base.CreateArgumentBuilder(settings); - - var migrationsDirectory = settings.WorkingDirectory.MakeAbsolute(_environment); - var migrationDllPath = settings.WorkingDirectory.CombineWithFilePath(settings.MigrationDll).MakeAbsolute(_environment); - var startupDllPath = settings.WorkingDirectory.CombineWithFilePath(settings.StartupDll).MakeAbsolute(_environment); - var runtimeConfigPath = settings.WorkingDirectory.CombineWithFilePath(System.IO.Path.GetFileNameWithoutExtension(settings.StartupDll)).AppendExtension(".runtimeconfig.json").MakeAbsolute(_environment).MakeAbsolute(_environment); - var depsJsonPath = settings.WorkingDirectory.CombineWithFilePath(System.IO.Path.GetFileNameWithoutExtension(settings.StartupDll)).AppendExtension(".deps.json").MakeAbsolute(_environment); - var pathToNuGetPackages = DirectoryPath.FromString(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)).Combine(".nuget/packages").MakeAbsolute(_environment); - var efDllPath = _tools.Resolve("ef.dll").MakeAbsolute(_environment); - - builder.Append("exec"); - builder.AppendSwitchQuoted("--depsfile", depsJsonPath.ToString()); - builder.AppendSwitchQuoted("--additionalprobingpath", pathToNuGetPackages.ToString()); - builder.AppendSwitchQuoted("--runtimeconfig", runtimeConfigPath.ToString()); - builder.AppendQuoted(efDllPath.ToString()); - - AppendToolArguments(builder, settings); - - builder.AppendSwitchQuoted("--assembly", migrationDllPath.ToString()); - builder.AppendSwitchQuoted("--startup-assembly", startupDllPath.ToString()); - builder.AppendSwitchQuoted("--project-dir", migrationsDirectory.ToString()); - builder.AppendSwitchQuoted("--data-dir", migrationsDirectory.ToString()); - builder.AppendSwitchQuoted("--context", settings.DbContextClassName); - - if (!string.IsNullOrWhiteSpace(settings.MigrationsNamespace)) - builder.AppendSwitchQuoted("--root-namespace", settings.MigrationsNamespace); - - if (settings.Verbose) - builder.Append("--verbose"); - - return builder; - - } - } -} \ No newline at end of file diff --git a/src/Cake.CodeQL/EfCoreToolSettings.cs b/src/Cake.CodeQL/EfCoreToolSettings.cs deleted file mode 100644 index a06f633..0000000 --- a/src/Cake.CodeQL/EfCoreToolSettings.cs +++ /dev/null @@ -1,63 +0,0 @@ -using Cake.Common.Tools.DotNetCore; -using Cake.Common.Tools.DotNetCore.Tool; -using Cake.Core; -using Cake.Core.IO; -using Cake.Core.Tooling; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Cake.EntityFrameworkCore -{ - /// - /// Ef Core Tool Basic Settings - /// - public class EfCoreToolSettings : DotNetCoreSettings - { - /// - /// Filename of the DLL that contains your migrations. - /// - /// My.Demo123.Api.dll - public string MigrationDll { get; set; } - - /// - /// .NET namespace for the DbContext class. 'Benday.Demo123.Api.dll - /// - /// My.Demo123.Api - public string MigrationsNamespace { get; set; } - - /// - /// Filename of the DLL that is the startup DLL for this published application - /// - /// My.Demo123.WebUi.dll - public string StartupDll { get; set; } - - /// - /// Class name for the DbContext that controls the migrations to deploy - /// - /// MyDbContext - public string DbContextClassName { get; set; } - - /// - /// Gets or Sets whether to show Verbose output - /// - public bool Verbose { get; set; } - - /// - /// Gets or Sets whether to show the version of Entity Framework. - /// - public bool Version { get; set; } - - /// - /// Gets or Sets whether to colorize the output. - /// - public bool NoColor { get; set; } - - /// - /// Prefix output with level. - /// - public bool PrefixOutput { get; set; } - } -} diff --git a/src/Cake.CodeQL/EfCoreToolSettingsExtensions.cs b/src/Cake.CodeQL/EfCoreToolSettingsExtensions.cs deleted file mode 100644 index b2f5451..0000000 --- a/src/Cake.CodeQL/EfCoreToolSettingsExtensions.cs +++ /dev/null @@ -1,155 +0,0 @@ -using Cake.Core; -using Cake.Core.Diagnostics; -using Cake.Core.IO; -using Cake.Core.Tooling; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace Cake.EntityFrameworkCore -{ - /// - /// Extensions for . - /// - public static class EfCoreToolSettingsExtensions - { - /// - /// Sets the verbose output for Entity Framework output. (e.g. - Show verbose output). - /// - /// The settings. - /// The instance with set to true. - public static T SetVerbose(this T settings) - where T : EfCoreToolSettings - { - if (settings == null) - throw new ArgumentNullException(nameof(settings)); - - settings.Verbose = true; - - return settings; - } - - /// - /// Sets the no color output for Entity Framework output (e.g. - Don't colorize output). - /// - /// The settings. - /// The instance with set to true. - public static T SetNoColor(this T settings) - where T : EfCoreToolSettings - { - if (settings == null) - throw new ArgumentNullException(nameof(settings)); - - settings.NoColor = true; - - return settings; - } - - /// - /// Sets the Prefix Out with level for the ef.dll. (e.g. - Prefix output with level.). - /// - /// The settings. - /// The instance with set to true. - public static T SetPrefixOutput(this T settings) - where T : EfCoreToolSettings - { - if (settings == null) - throw new ArgumentNullException(nameof(settings)); - - settings.PrefixOutput = true; - - return settings; - } - - /// - /// Sets the to display version information in console output - /// - /// The settings. - /// The instance with set to true. - public static T SetVersion(this T settings) - where T : EfCoreToolSettings - { - if (settings == null) - throw new ArgumentNullException(nameof(settings)); - - settings.Version = true; - - return settings; - } - - /// - /// Sets the working directory which should be used to run the ef.dll command. - /// - /// The settings. - /// Working directory which should be used to run the ef.dll command. - /// The instance with set to . - public static T FromPath(this T settings, DirectoryPath path) - where T : EfCoreToolSettings - { - if (settings == null) - throw new ArgumentNullException(nameof(settings)); - - settings.WorkingDirectory = path ?? throw new ArgumentNullException(nameof(path)); - - return settings; - } - - /// - /// Sets the name of File of the DLL that contains your migrations - /// - /// The settings. - /// file name - /// The instance with - public static T SetMigrationsDll(this T settings, string fileName) - where T : EfCoreToolSettings - { - if (settings == null) throw new ArgumentNullException(nameof(settings)); - settings.MigrationDll = fileName ?? throw new ArgumentNullException(nameof(fileName)); - return settings; - } - - /// - /// Sets the migrations namespace that contains the DbContext - /// - /// The settings. - /// file name - /// The instance with set to . - public static T SetMigrationsNamespace(this T settings, string @namespace) - where T : EfCoreToolSettings - { - if (settings == null) throw new ArgumentNullException(nameof(settings)); - settings.MigrationsNamespace = @namespace ?? throw new ArgumentNullException(nameof(@namespace)); - return settings; - } - - /// - /// Sets the statup dll for the published application the publised application - /// - /// The settings. - /// file name. - /// The instance with set to . - public static T SetStartupDll(this T settings, string fileName) - where T : EfCoreToolSettings - { - if (settings == null) throw new ArgumentNullException(nameof(settings)); - settings.StartupDll = fileName ?? throw new ArgumentNullException(nameof(fileName)); - return settings; - } - - /// - /// Class name for the DbContext that controls the migrations to deploy - /// - /// The settings. - /// DbContext class name - /// The instance with set to . - public static T SetDbContextClass(this T settings, string name) - where T : EfCoreToolSettings - { - if (settings == null) throw new ArgumentNullException(nameof(settings)); - settings.DbContextClassName = name ?? throw new ArgumentNullException(nameof(name)); - return settings; - } - } -} diff --git a/src/Cake.CodeQL/Properties/InternalsVisibleInfo.cs b/src/Cake.CodeQL/Properties/InternalsVisibleInfo.cs deleted file mode 100644 index 3642492..0000000 --- a/src/Cake.CodeQL/Properties/InternalsVisibleInfo.cs +++ /dev/null @@ -1,3 +0,0 @@ -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("Cake.EntityFrameworkCore.Tests")] \ No newline at end of file diff --git a/src/Cake.CodeQL/icon.png b/src/Cake.CodeQL/icon.png deleted file mode 100644 index 7524b13..0000000 Binary files a/src/Cake.CodeQL/icon.png and /dev/null differ diff --git a/src/build.cake b/src/build.cake deleted file mode 100644 index 32c50f8..0000000 --- a/src/build.cake +++ /dev/null @@ -1,33 +0,0 @@ -/////////////////////////////////////////////////////////////////////////////// -// ARGUMENTS -/////////////////////////////////////////////////////////////////////////////// - -var target = Argument("target", "Default"); -var configuration = Argument("configuration", "Release"); - -/////////////////////////////////////////////////////////////////////////////// -// SETUP / TEARDOWN -/////////////////////////////////////////////////////////////////////////////// - -Setup(ctx => -{ - // Executed BEFORE the first task. - Information("Running tasks..."); -}); - -Teardown(ctx => -{ - // Executed AFTER the last task. - Information("Finished running tasks."); -}); - -/////////////////////////////////////////////////////////////////////////////// -// TASKS -/////////////////////////////////////////////////////////////////////////////// - -Task("Default") -.Does(() => { - Information("Hello Cake!"); -}); - -RunTarget(target); \ No newline at end of file