Skip to content

Commit

Permalink
Added Cake Build script with Tool Resolution for exe (#3) (#4)
Browse files Browse the repository at this point in the history
dotnet tool config added
CodeQL Added
  • Loading branch information
louisfischer authored May 10, 2023
1 parent 7178728 commit eaba934
Show file tree
Hide file tree
Showing 16 changed files with 377 additions and 21 deletions.
12 changes: 12 additions & 0 deletions .config/dotnet-tools.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"version": 1,
"isRoot": true,
"tools": {
"cake.tool": {
"version": "3.0.0",
"commands": [
"dotnet-cake"
]
}
}
}
1 change: 1 addition & 0 deletions .github/CODEOWNERS
Validating CODEOWNERS rules …
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* @louisfischer
11 changes: 11 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
- package-ecosystem: "" # See documentation for possible values
directory: "/" # Location of package manifests
schedule:
interval: "weekly"
78 changes: 78 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
name: Build

on:
pull_request:
workflow_dispatch:
inputs:
target:
description: 'Task'
required: true
default: Default
type: choice
options:
- Default
- Clean
- Restore
- Build
- Pack
- Push

pushToNuget:
description: 'Push to Nuget'
required: false
default: false
type: boolean

logLevel:
description: 'Verbosity'
required: false
default: Normal
type: choice
options:
- Quiet
- Minimal
- Normal
- Verbose
- Diagnostic
push:
branches:
- "**"
tags:
- "*.*.*"
paths-ignore:
- "README.md"

env:
DOTNET_SKIP_FIRST_TIME_EXPERIENCE: true
DOTNET_CLI_TELEMETRY_OPTOUT: true
DOTNET_NOLOGO: true

jobs:
build:
runs-on: ${{ matrix.os }}
strategy:
matrix:
os: [ubuntu-latest]

name: ${{ matrix.os }}
steps:
- name: Setup net6.0
uses: actions/setup-dotnet@v3.0.3
with:
dotnet-version: 6.x

- name: Checkout
uses: actions/checkout@v3.5.2
with:
fetch-depth: 0

- name: Run the Cake script
uses: cake-build/cake-action@master
with:
target: ${{ inputs.target || 'Default' }}
verbosity: ${{ inputs.logLevel || 'Diagnostic' }}
cake-version: tool-manifest
arguments: |
NUGET_PUSH: ${{ inputs.pushToNuget || true }}
NUGET_URL: ${{ secrets.NUGET_SOURCE }}
NUGET_API_KEY: ${{ secrets.NUGET_API_KEY }}
40 changes: 40 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
name: CodeQL

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
schedule:
- cron: '44 6 * * 6'

jobs:
analyze:
name: Analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write

strategy:
fail-fast: false
matrix:
language: [ 'csharp' ]
steps:
- name: Checkout repository
uses: actions/checkout@v3

- name: Initialize CodeQL
uses: github/codeql-action/init@v2
with:
languages: ${{ matrix.language }}
queries: security-extended,security-and-quality

- name: Autobuild
uses: github/codeql-action/autobuild@v2

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
with:
category: "/language:${{matrix.language}}"
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -276,4 +276,5 @@ __pycache__/
# Cake - Uncomment if you are using it
tools/**
!tools/packages.config
BuildArtifacts/
BuildArtifacts/
.cake/
9 changes: 9 additions & 0 deletions Cake.CodeQL.Cli.sln
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,15 @@ 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
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{46391845-2542-4C09-B354-DFB023C6FB4E}"
ProjectSection(SolutionItems) = preProject
build.cake = build.cake
.github\workflows\build.yml = .github\workflows\build.yml
cake.config = cake.config
.github\workflows\codeql.yml = .github\workflows\codeql.yml
.config\dotnet-tools.json = .config\dotnet-tools.json
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ This plugin is a set of Cake aliases for [GitHub CodeQL CLI](https://docs.github
```
### Cake Frosting Project
```xml
<PackageReference Include="Cake.CodeQL.Cli" Version="1.0.0" />
<PackageReference Include="Cake.CodeQL.Cli" Version="3.2.0" />
```

## Discussion
Expand Down
105 changes: 105 additions & 0 deletions build.cake
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
#tool "dotnet:?package=minver-cli&version=4.2.0"
#addin "nuget:?package=Cake.MinVer&version=3.0.0"
#addin "nuget:?package=Cake.Args&version=3.0.0"

var target = ArgumentOrDefault<string>("Target") ?? "Default";
var buildVersion = MinVer(s => s.WithTagPrefix("v").WithDefaultPreReleasePhase("preview"));

Task("Clean")
.Does(() =>
{
EnsureDirectoryDoesNotExist("./artifact/");
CleanDirectories("./**/^{bin,obj}");
});

Task("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
DotNetRestore("./Cake.CodeQL.Cli.sln", new DotNetRestoreSettings
{
LockedMode = true,
});
});

Task("Build")
.IsDependentOn("Restore")
.DoesForEach(new[] { "Debug", "Release" }, (configuration) =>
{
DotNetBuild("./Cake.CodeQL.Cli.sln", new DotNetBuildSettings
{
Configuration = configuration,
NoRestore = true,
NoIncremental = false,
MSBuildSettings = new DotNetMSBuildSettings
{
Version = buildVersion.Version,
AssemblyVersion = buildVersion.AssemblyVersion,
FileVersion = buildVersion.FileVersion,
ContinuousIntegrationBuild = BuildSystem.IsLocalBuild,
},
});
});

Task("Pack")
.IsDependentOn("Build")
.Does(() =>
{
DotNetPack("./src/Cake.CodeQL.Cli/Cake.CodeQL.Cli.csproj", new DotNetPackSettings
{
Configuration = "Release",
NoRestore = true,
NoBuild = true,
OutputDirectory = "./artifact/nuget",
MSBuildSettings = new DotNetMSBuildSettings
{
Version = buildVersion.Version,
PackageReleaseNotes = $"https://github.com/cake-contrib/Cake.CodeQL.Cli/releases/tag/v{buildVersion.Version}"
}
});
});

Task("Push")
.IsDependentOn("Pack")
.WithCriteria(() => GitHubActions.IsRunningOnGitHubActions)
.WithCriteria(() => string.Equals("refs/heads/main", GitHubActions.Environment.Workflow.Ref, StringComparison.OrdinalIgnoreCase) || GitHubActions.Environment.Workflow.Ref.StartsWith("refs/tags/", StringComparison.OrdinalIgnoreCase))
.WithCriteria(() => ArgumentOrDefault<bool>("NUGET_PUSH"))
.Does(context =>
{
var url = context.ArgumentOrDefault<string>("NUGET_URL");
if (string.IsNullOrWhiteSpace(url))
{
context.Information("No NuGet URL specified. Skipping publishing of NuGet packages");
return;
}

var apiKey = context.ArgumentOrDefault<string>("NUGET_API_KEY");
if (string.IsNullOrWhiteSpace(apiKey))
{
context.Information("No NuGet API key specified. Skipping publishing of NuGet packages");
return;
}

var nugetPushSettings = new DotNetNuGetPushSettings
{
Source = url,
ApiKey = apiKey,
SkipDuplicate = true
};

foreach (var nugetPackageFile in GetFiles("./artifact/nuget/*.nupkg"))
DotNetNuGetPush(nugetPackageFile.FullPath, nugetPushSettings);
});

Task("Publish")
.IsDependentOn("Push")
.WithCriteria(() => GetFiles("./artifact/nuget/**/*")?.Count > 0)
.WithCriteria(() => GitHubActions.IsRunningOnGitHubActions)
.WithCriteria(() => string.Equals("refs/heads/main", GitHubActions.Environment.Workflow.Ref, StringComparison.OrdinalIgnoreCase) || GitHubActions.Environment.Workflow.Ref.StartsWith("refs/tags/", StringComparison.OrdinalIgnoreCase))
.Does(async () =>
await GitHubActions.Commands.UploadArtifact(Directory("./artifact/nuget"), $"Cake.CodeQL.Cli.{buildVersion.Version}"));

Task("Default")
.IsDependentOn("Publish");

RunTarget(target);
12 changes: 12 additions & 0 deletions cake.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[Nuget]
Source=https://api.nuget.org/v3/index.json
UseInProcessClient=true
LoadDependencies=false

[Paths]
Tools=./.cake
Addins=./.cake/addins
Modules=./.cake/modules

[Settings]
SkipVerification=false
2 changes: 1 addition & 1 deletion src/Cake.CodeQL.Cli/Cake.CodeQL.Cli.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<ImplicitUsings>true</ImplicitUsings>
</PropertyGroup>
<PropertyGroup>
<Version>3.0.0</Version>
<Version>0.0.0</Version>
<Title>Cake.CodeQL.Cli</Title>
<Description>Cake.CodeQL.Cli 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.</Description>
<Authors>louisfischer, cake-contrib</Authors>
Expand Down
30 changes: 30 additions & 0 deletions src/Cake.CodeQL.Cli/CodeQLResolveToolPath.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
namespace Cake.CodeQL.Cli;

internal class CodeQLResolveToolPath
{
private readonly IFileSystem fileSystem;
private readonly ICakeEnvironment environment;

public CodeQLResolveToolPath(IFileSystem fileSystem, ICakeEnvironment environment)
{
this.fileSystem = fileSystem;
this.environment = environment;
}

public IEnumerable<FilePath> Find(IEnumerable<string> toolNames, DirectoryPath dir)
{
if (dir == null || toolNames == null || toolNames?.Count() < 1) return null;

var globSettings = new GlobberSettings()
{
IsCaseSensitive = false,
FilePredicate = file => toolNames.Any(toolName => toolName.Equals(file.Path.GetFilename().ToString(), StringComparison.OrdinalIgnoreCase))
};

var globPattern = $"{dir.MakeAbsolute(environment).ToString().TrimEnd('/', '\\')}/**/*";

var globber = new Globber(fileSystem, environment);

return globber.Match(globPattern, globSettings).OfType<FilePath>();
}
}
24 changes: 23 additions & 1 deletion src/Cake.CodeQL.Cli/CodeQLTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ namespace Cake.CodeQL.Cli;
public abstract class CodeQLTool<TSettings> : Tool<TSettings>
where TSettings : CodeQLToolSettings
{
private readonly IFileSystem fileSystem;
private readonly ICakeEnvironment environment;

/// <summary>
/// Initializes a new instance of the <see cref="CodeQLTool{TSettings}"/> class.
/// </summary>
Expand All @@ -18,6 +21,8 @@ public abstract class CodeQLTool<TSettings> : Tool<TSettings>
protected CodeQLTool(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools, ICakeLog log)
: base(fileSystem, environment, processRunner, tools)
{
this.fileSystem = fileSystem;
this.environment = environment;
CakeLog = log;
}

Expand All @@ -36,7 +41,24 @@ protected CodeQLTool(IFileSystem fileSystem, ICakeEnvironment environment, IProc
/// Gets the possible names of the tool executable.
/// </summary>
/// <returns>The tool executable name.</returns>
protected sealed override IEnumerable<string> GetToolExecutableNames() => new[] { "codeql", "codeql.exe" };
protected sealed override IEnumerable<string> GetToolExecutableNames() => new[] { "codeql.exe", "codeql" };

/// <summary>
/// CodeQL Installs into a subdirectory. This checks the subdirectories as well
/// </summary>
/// <param name="settings"></param>
/// <returns></returns>
protected override IEnumerable<FilePath> GetAlternativeToolPaths(TSettings settings)
{
var toolResolver = new CodeQLResolveToolPath(fileSystem, environment);

var toolPaths = toolResolver.Find(GetToolExecutableNames(), settings.WorkingDirectory.Combine("tools"));

if(toolPaths == null || toolPaths.Count() < 1)
return base.GetAlternativeToolPaths(settings);

return toolPaths;
}

/// <summary>
/// Runss CodeQL
Expand Down
Loading

0 comments on commit eaba934

Please sign in to comment.