Skip to content

Commit

Permalink
Implement standard build script to allow very simple command line dep…
Browse files Browse the repository at this point in the history
…loyment
  • Loading branch information
Sebazzz committed Oct 10, 2018
1 parent 59c61ad commit f3da156
Show file tree
Hide file tree
Showing 10 changed files with 1,261 additions and 170 deletions.
2 changes: 1 addition & 1 deletion src/FinancialApp.sln → FinancialApp.sln
Expand Up @@ -5,7 +5,7 @@ VisualStudioVersion = 15.0.26430.6
MinimumVisualStudioVersion = 10.0.40219.1
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{461F62A8-DC5B-4F28-B5CC-707E466ED1A8}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "App", "App\App.csproj", "{D653B77B-6B7D-4465-9897-C08BE13EC2AD}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "App", "src\App\App.csproj", "{D653B77B-6B7D-4465-9897-C08BE13EC2AD}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down
File renamed without changes.
153 changes: 153 additions & 0 deletions build.cake
@@ -0,0 +1,153 @@
//////////////////////////////////////////////////////////////////////
// ARGUMENTS
//////////////////////////////////////////////////////////////////////

var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var verbosity = Argument<Verbosity>("verbosity", Verbosity.Minimal);

//////////////////////////////////////////////////////////////////////
// PREPARATION
//////////////////////////////////////////////////////////////////////

var baseName = "FinancialApp";
var buildDir = Directory("./build") + Directory(configuration);
var publishDir = Directory("./build/publish");
var assemblyInfoFile = Directory($"./src/{baseName}/Properties") + File("AssemblyInfo.cs");
var nodeEnv = configuration == "Release" ? "production" : "development";

//////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////

Task("Clean")
.Does(() => {
CleanDirectory(buildDir);
CleanDirectory(publishDir);
CleanDirectories("./src/App/bin");
CleanDirectories("./src/App/obj");
});

Task("Rebuild")
.IsDependentOn("Clean")
.IsDependentOn("Build");

Task("Check-Node-Version")
.Does(() => {
try {
Information("Checking node.js version...");
var processSettings = new ProcessSettings()
.WithArguments(args => args.Append("--version"))
.SetRedirectStandardOutput(true)
;
var process = StartAndReturnProcess("node", processSettings);
process.WaitForExit();
string line = null;
foreach (var output in process.GetStandardOutput()) {
line = output;
Debug(output);
}
if (String.IsNullOrEmpty(line)) {
throw new CakeException("Didn't get any output from Node.js");
}
Version actualVersion = Version.Parse(line.Substring(1));
Version wantedVersion = new Version(6,1,0);
Information("Got version {0} - we want at least version {1}", actualVersion, wantedVersion);
if (wantedVersion > actualVersion) {
throw new CakeException($"Node version {actualVersion} does not satisfy the requirement of Node>={wantedVersion}");
}
} catch (Exception e) when (!(e is CakeException)) {
throw new CakeException("Unable to check Node.js version");
}
});

Task("Restore-NuGet-Packages")
.Does(() => {
DotNetCoreRestore(new DotNetCoreRestoreSettings {
IgnoreFailedSources = true
});
});

Task("Set-NodeEnvironment")
.Does(() => {
Information("Setting NODE_ENV to {0}", nodeEnv);
System.Environment.SetEnvironmentVariable("NODE_ENV", nodeEnv);
});

Task("Restore-Node-Packages")
.IsDependentOn("Check-Node-Version")
.Does(() => {
var exitCode =
StartProcess("cmd", new ProcessSettings()
.UseWorkingDirectory("./src/App")
.WithArguments(args => args.Append("/C").AppendQuoted("npm install")));
if (exitCode != 0) {
throw new CakeException($"'npm install' returned exit code {exitCode} (0x{exitCode:x2})");
}
});

Task("Build")
.IsDependentOn("Set-NodeEnvironment")
.IsDependentOn("Restore-NuGet-Packages")
.IsDependentOn("Restore-Node-Packages")
.Does(() => {
DotNetCoreBuild($"./{baseName}.sln");
});

Task("Run")
.IsDependentOn("Build")
.Does(() => {
DotNetCoreRun($"App.csproj", null, new DotNetCoreRunSettings { WorkingDirectory = "./src/App" });
});

Action<String> PublishSelfContained = (string platform) => {
Information("Publishing self-contained for platform {0}", platform);
var settings = new DotNetCorePublishSettings
{
Configuration = configuration,
OutputDirectory = publishDir + Directory(platform),
Runtime = platform
};
DotNetCorePublish($"./src/App/App.csproj", settings);
};

Task("Publish-Win10")
.IsDependentOn("Rebuild")
.Does(() => PublishSelfContained("win10-x64"));

Task("Publish-Ubuntu")
.IsDependentOn("Rebuild")
.Does(() => PublishSelfContained("ubuntu.14.04-x64"));

Task("Publish")
.IsDependentOn("Publish-Win10")
.IsDependentOn("Publish-Ubuntu");



//////////////////////////////////////////////////////////////////////
// TASK TARGETS
//////////////////////////////////////////////////////////////////////

Task("None");

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

//////////////////////////////////////////////////////////////////////
// EXECUTION
//////////////////////////////////////////////////////////////////////

RunTarget(target);
2 changes: 2 additions & 0 deletions build.cmd
@@ -0,0 +1,2 @@
@echo off
powershell -File build.ps1 -Arguments %*
181 changes: 181 additions & 0 deletions build.ps1
@@ -0,0 +1,181 @@
<#
.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 Experimental
Tells Cake to use the latest Roslyn release.
.PARAMETER WhatIf
Performs a dry run of the build script.
No tasks will be executed.
.PARAMETER Mono
Tells Cake to use the Mono scripting engine.
.PARAMETER SkipToolPackageRestore
Skips restoring of packages.
.PARAMETER ScriptArgs
Remaining arguments are added here.
.LINK
http://cakebuild.net
#>

[CmdletBinding()]
Param(
[string]$Script = "build.cake",
[string]$Target = "Default",
[ValidateSet("Release", "Debug")]
[string]$Configuration = "Release",
[ValidateSet("Quiet", "Minimal", "Normal", "Verbose", "Diagnostic")]
[string]$Verbosity = "Verbose",
[switch]$Experimental,
[Alias("DryRun","Noop")]
[switch]$WhatIf,
[switch]$Mono,
[switch]$SkipToolPackageRestore,
[Parameter(Position=0,Mandatory=$false,ValueFromRemainingArguments=$true)]
[string[]]$ScriptArgs
)

[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()
}
}
}

if ($ScriptArgs -and $ScriptArgs[1] -imatch "^(-?-?|\/)(help|\?)$") {
Write-Host "Going to show the task descriptions... one moment please..." -ForegroundColor Green
$ScriptArgs[1] = "--showdescription"
$Verbosity = "Quiet"
}

Write-Host "Preparing to run build script..."

if(!$PSScriptRoot){
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
}

$TOOLS_DIR = Join-Path $PSScriptRoot "tools"
$TOOLS_PACKAGES_DIR = Join-Path $TOOLS_DIR "packages"
$NUGET_EXE = Join-Path $TOOLS_DIR "nuget.exe"
$CAKE_EXE = Join-Path $TOOLS_PACKAGES_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"

# Is this a dry run?
$UseDryRun = "";
if($WhatIf.IsPresent) {
$UseDryRun = "-dryrun"
}

# 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 { (New-Object System.Net.WebClient).DownloadFile("http://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 $_) }
$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 {
(New-Object System.Net.WebClient).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

# Restore tools from NuGet?
if(-Not $SkipToolPackageRestore.IsPresent) {
Write-Host "Restoring packages"

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..."
Remove-Item * -Recurse -Exclude packages.config,nuget.exe,.gitignore
}

Write-Verbose -Message "Restoring tools from NuGet..."
$Expr = "&`"$NUGET_EXE`" install -ExcludeVersion -OutputDirectory `"$TOOLS_PACKAGES_DIR`""
Write-Verbose $Expr

$NuGetOutput = Invoke-Expression $Expr

if ($LASTEXITCODE -ne 0) {
Throw "An error occured while restoring NuGet tools."
}
else
{
$md5Hash | Out-File $PACKAGES_CONFIG_MD5 -Encoding "ASCII"
}
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"
}

# Start Cake
Write-Host "Running build script..."
Invoke-Expression "& `"$CAKE_EXE`" `"$Script`" -target=`"$Target`" -configuration=`"$Configuration`" -verbosity=`"$Verbosity`" $UseDryRun $ScriptArgs"
exit $LASTEXITCODE
2 changes: 1 addition & 1 deletion src/App/App.csproj
Expand Up @@ -105,7 +105,7 @@

<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
<Exec Command="npm install" />
<Exec Command="npm build" />
<Exec Command="npm run-script build" />
</Target>

<ItemGroup>
Expand Down

0 comments on commit f3da156

Please sign in to comment.