From 32434a0719e88fcde9b914ae0daf06899884413f Mon Sep 17 00:00:00 2001
From: RWTHApp Service <rwthapp@itc.rwth-aachen.de>
Date: Wed, 18 Sep 2019 15:51:23 +0200
Subject: [PATCH] C#-Template

---
 .gitlab-ci.yml |  59 ++++---
 .releaserc     |   2 +-
 build.cake     | 446 ++++++++++++++++++++++++++++---------------------
 build.ps1      |  91 +++++-----
 4 files changed, 340 insertions(+), 258 deletions(-)

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index a60ae9c..50709f6 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -1,5 +1,3 @@
-
-
 stages:
   - build
   - test
@@ -8,30 +6,31 @@ stages:
   - build-release
   - semantic-release
   - release
-    
+  - pre_release
+
 build:
-  before_script:
-    - PowerShell .\build.ps1 -Target Clean
-    - PowerShell .\build.ps1 -Target Restore-NuGet-Packages
   stage: build
   script:
-    - PowerShell .\build.ps1 -Target Build
+    - PowerShell .\build.ps1 -Target Build -Configuration Debug
+  variables:
+    GIT_STRATEGY: clone
   except:
     variables:
       - $GITLAB_USER_ID == $GIT_BOT_USER_ID
-  
+
 test:
   stage: test
   script:
-    - PowerShell .\build.ps1 -Target Resharper
-    - PowerShell .\build.ps1 -Target Run-Unit-Tests
+    - PowerShell .\build.ps1 -Target LinterAndTest -Configuration Debug
   variables:
     GIT_STRATEGY: none
   dependencies:
     - build
   artifacts:
     reports:
-      junit: TestResult.xml
+      junit: "./Artifacts/TestResults.xml"
+    paths:
+      - "./Artifacts/*"
   except:
     variables:
       - $GITLAB_USER_ID == $GIT_BOT_USER_ID
@@ -39,7 +38,7 @@ test:
 update-assembly-info:
   stage: update-assembly-info
   script:
-    - PowerShell .\build.ps1 -Target Update-Assembly-Info
+    - PowerShell .\build.ps1 -Target UpdateAssemblyInfo
   variables:
     GIT_STRATEGY: none
   dependencies:
@@ -51,12 +50,10 @@ update-assembly-info:
       - $GITLAB_USER_ID == $GIT_BOT_USER_ID
 
 build-release:
-  before_script:
-    - PowerShell .\build.ps1 -Target Clean
-    - PowerShell .\build.ps1 -Target Restore-NuGet-Packages
   stage: build-release
   script:
-    - PowerShell .\build.ps1 -Target Build-Release
+    - PowerShell .\build.ps1 -Target Build -Configuration Release
+    - PowerShell .\build.ps1 -Configuration Release -Target NugetPack
   variables:
     GIT_STRATEGY: none
   dependencies:
@@ -80,11 +77,11 @@ docs:
   except:
     variables:
       - $GITLAB_USER_ID == $GIT_BOT_USER_ID
-  
+
 semantic-release:
   stage: semantic-release
   script:
-    - PowerShell .\build.ps1 -Target Semantic-Release
+    - PowerShell .\build.ps1 -Target SemanticRelease
   variables:
     GIT_STRATEGY: none
   dependencies:
@@ -94,15 +91,33 @@ semantic-release:
   except:
     variables:
       - $GITLAB_USER_ID == $GIT_BOT_USER_ID
-  
+
 release:
+  before_script:
   stage: release
   script:
-    - PowerShell .\build.ps1 -Target Build-Release
+    - PowerShell .\build.ps1 -Target Build -Configuration Release
+    - PowerShell .\build.ps1 -Configuration Release -Target NugetPack
+    - PowerShell .\build.ps1 -Configuration Release -Target NugetPush --nugetApiKey="$NUGET_API_KEY"
   variables:
-    GIT_STRATEGY: none
+    GIT_STRATEGY: clone
   artifacts:
     paths:
-      - dist
+      - "./Artifacts/*"
   only:
     - tags
+
+pre_release:
+  stage: pre_release
+  script:
+    - PowerShell .\build.ps1 -Target Build -Configuration Release
+  variables:
+    GIT_STRATEGY: clone
+  artifacts:
+    paths:
+      - "./Artifacts/*"
+  when: manual
+  except:
+    - tags
+    - master
+    
\ No newline at end of file
diff --git a/.releaserc b/.releaserc
index 576a3f7..72ff270 100644
--- a/.releaserc
+++ b/.releaserc
@@ -20,4 +20,4 @@
       "message": "Chore: ${nextRelease.version}\n\n${nextRelease.notes}"
     }]
   ]
-}
\ No newline at end of file
+}
diff --git a/build.cake b/build.cake
index 9167f13..4827ab9 100644
--- a/build.cake
+++ b/build.cake
@@ -1,241 +1,307 @@
 #tool nuget:?package=NUnit.ConsoleRunner&version=3.9.0
 #tool nuget:?package=JetBrains.ReSharper.CommandLineTools&version=2018.3.4
-
-#addin nuget:https://api.nuget.org/v3/index.json?package=Cake.Npx&version=1.3.0
-#addin nuget:https://api.nuget.org/v3/index.json?package=Cake.Issues&version=0.6.2
-#addin nuget:https://api.nuget.org/v3/index.json?package=Cake.Issues.InspectCode&version=0.6.1
-#addin nuget:https://api.nuget.org/v3/index.json?package=Cake.FileHelpers&version=3.1.0
-
+#tool nuget:?package=vswhere&version=2.6.7
+	
+#addin nuget:https://api.nuget.org/v3/index.json?package=Cake.Npx&version=1.6.0
+#addin nuget:https://api.nuget.org/v3/index.json?package=Cake.Issues&version=0.7.1
+#addin nuget:https://api.nuget.org/v3/index.json?package=Cake.Issues.InspectCode&version=0.7.1
+#addin nuget:https://api.nuget.org/v3/index.json?package=Cake.FileHelpers&version=3.2.1
 //////////////////////////////////////////////////////////////////////
 // ARGUMENTS
 //////////////////////////////////////////////////////////////////////
-
 var target = Argument("target", "Default");
 var configuration = Argument("configuration", "Release");
+var nugetApiKey = Argument<string>("nugetApiKey", null);
 
 //////////////////////////////////////////////////////////////////////
 // PREPARATION
 //////////////////////////////////////////////////////////////////////
-
 // Define directories.
-string projectName;
-string projectPath;
-DirectoryPath buildDir;
-FilePath solutionFile;
+var projects = GetFiles("./**/*.csproj");
+var artifactsDir = Directory("./Artifacts");
+string nupkgDir;
+var solutionFile = GetFiles("./**/*.sln").First();
+var projectName = solutionFile.GetFilenameWithoutExtension().ToString();
+var assemblyInfoSubPath = "Properties/AssemblyInfo.cs";
+var nugetSource = "https://api.nuget.org/v3/index.json";
+
+// get latest MSBuild version
+var vsLatest  = VSWhereLatest();	
+var msBuildPathX64 = (vsLatest == null) ? null : vsLatest.CombineWithFilePath("./MSBuild/Current/Bin/MSBuild.exe");
 
 // Error rules for resharper
 // Example: {"InconsistentNaming", "RedundantUsingDirective"};
-string [] resharperErrorRules = {};
+string[] resharperErrorRules = {};
+// Paths to exclude from dupFinder
+List<string> dupFinderExcludePatterns = projects.Select( x => $"{x.GetDirectory().ToString()}/{assemblyInfoSubPath}").ToList();
+string[] dupFinderExcludeCodeRegionsByNameSubstring = { "DupFinder Exclusion" };
+
+Action <NpxSettings> requiredSemanticVersionPackages = settings =>
+	settings.AddPackage("semantic-release")
+	.AddPackage("@semantic-release/commit-analyzer")
+	.AddPackage("@semantic-release/release-notes-generator")
+	.AddPackage("@semantic-release/gitlab")
+	.AddPackage("@semantic-release/git")
+	.AddPackage("@semantic-release/exec")
+	.AddPackage("conventional-changelog-eslint");
+
+///////////////////////////////////////////////////////////////////////////////
+// SETUP / TEARDOWN
+///////////////////////////////////////////////////////////////////////////////
+Setup(context =>{
+	nupkgDir = $"{artifactsDir.ToString()}/nupkg";
+	Information("Running tasks...");
+});
 
-Action<NpxSettings> requiredSemanticVersionPackages = settings => settings
-    .AddPackage("semantic-release")
-    .AddPackage("@semantic-release/commit-analyzer")
-    .AddPackage("@semantic-release/release-notes-generator")
-    .AddPackage("@semantic-release/gitlab")
-    .AddPackage("@semantic-release/git")
-    .AddPackage("@semantic-release/exec")
-    .AddPackage("conventional-changelog-eslint");
+Teardown(context =>{
+	Information("Finished running tasks.");
+});
 
 //////////////////////////////////////////////////////////////////////
 // TASKS
 //////////////////////////////////////////////////////////////////////
-
-Task("Get-Project-Name")
-    .Does(() =>
-{
-    var solutions = GetFiles("./**/*.sln");
-    projectName = solutions.First().GetFilenameWithoutExtension().ToString();
-    Information("Project Name: {0}", projectName);
+Task("Clean")
+.Description("Cleans all build and artifacts directories")
+.Does(() =>{
+	var settings = new DeleteDirectorySettings {
+		Recursive = true,
+		Force = true
+	};
 	
-    solutionFile = solutions.First().ToString();
-    Information("Solution File: {0}", solutionFile.ToString());
+	var directoriesToDelete = new List<DirectoryPath>();
 	
-    projectPath = Context.Environment.WorkingDirectory.ToString().ToString() + "/src";
-    Information("Project Directory: {0}", projectPath);
+	foreach(var project in projects) {
+		directoriesToDelete.Add(Directory($"{project.GetDirectory()}/obj"));
+		directoriesToDelete.Add(Directory($"{project.GetDirectory()}/bin"));
+	}
 	
-    buildDir = Directory(projectPath + "/" + projectName + "/bin") + Directory(configuration);
-    Information("Build Directory: {0}", buildDir.ToString());
+	directoriesToDelete.Add(artifactsDir);
+
+	foreach(var dir in directoriesToDelete) {
+		if (DirectoryExists(dir)) {
+			Information($"Cleaning path {dir} ...");
+			DeleteDirectory(dir, settings);
+		}
+	}
 });
 
-Task("Clean")
-    .IsDependentOn("Get-Project-Name")
-    .Does(() =>
-{
-    CleanDirectory(buildDir);
-    CleanDirectory("./dist");
+Task("Restore")
+.Does(() =>{
+	// Restore all NuGet packages.
+	Information($"Restoring {solutionFile}...");
+	NuGetRestore(solutionFile, new NuGetRestoreSettings {
+		NoCache = true
+	});
+});
+
+Task("DupFinder")
+.Description("Find duplicates in the code")
+.Does(() =>{
+	var settings = new DupFinderSettings() {
+		ShowStats = true,
+		ShowText = true,
+		OutputFile = $"{artifactsDir}/dupfinder.xml",
+		ExcludeCodeRegionsByNameSubstring = dupFinderExcludeCodeRegionsByNameSubstring,
+		ExcludePattern = dupFinderExcludePatterns.ToArray(),
+		ThrowExceptionOnFindingDuplicates = true
+	};
+	DupFinder(solutionFile, settings);
+});
+
+Task("InspectCode")
+.Description("Inspect the code using Resharper's rule set")
+.Does(() =>{
+	var settings = new InspectCodeSettings() {
+		SolutionWideAnalysis = true,
+		OutputFile = $"{artifactsDir}/inspectcode.xml",
+		ThrowExceptionOnFindingViolations = false
+	};
+	InspectCode(solutionFile, settings);
+
+	var issues = ReadIssues(
+	InspectCodeIssuesFromFilePath($"{artifactsDir}/inspectcode.xml"), Context.Environment.WorkingDirectory);
+
+	Information("{0} issues are found.", issues.Count());
+
+	var errorIssues = issues.Where(issue =>resharperErrorRules.Any(issue.Rule.Contains)).ToList();
+
+	if (errorIssues.Any()) {
+		var errorMessage = errorIssues.Aggregate(new StringBuilder(), (stringBuilder, issue) =>stringBuilder.AppendFormat("FileName: {0} Line: {1} Message: {2}{3}", issue.AffectedFileRelativePath, issue.Line, issue.Message, Environment.NewLine));
+		throw new CakeException($"{errorIssues.Count} errors detected: {Environment.NewLine}{errorMessage}.");
+	}
 });
 
-Task("Restore-NuGet-Packages")
-    .IsDependentOn("Get-Project-Name")
-    .Does(() =>
-{
-    NuGetRestore(solutionFile);
+Task("Test")
+.Does(() =>{
+	NUnit3($"./src/**/bin/{configuration}/*.Tests.dll", new NUnit3Settings {
+		// generate the xml file
+		NoResults = false,
+		Results = new NUnit3Result[] {
+			new NUnit3Result() {
+				FileName = $"{artifactsDir}/TestResults.xml",
+				Transform = Context.Environment.WorkingDirectory + "/nunit3-junit.xslt"
+			}
+		}
+	});
 });
 
-Task("Resharper")
-    .IsDependentOn("Get-Project-Name")
-    .Does(() =>
-{
-    FilePath dupLog = Context.Environment.WorkingDirectory + "/Resharper/dupfinder.xml";
-    FilePath inspectLog = Context.Environment.WorkingDirectory + "/Resharper/inspectcode.xml";
-    
-    DupFinder(solutionFile, new DupFinderSettings() {
-        OutputFile = dupLog.ToString()
-    });
-    
-    Information("DupFinder Log:{0}{1}", Environment.NewLine, FileReadText(dupLog));
-    
-    InspectCode(solutionFile, new InspectCodeSettings() {
-        OutputFile = inspectLog.ToString()
-    });
-    
-    var issues = ReadIssues(
-        InspectCodeIssuesFromFilePath(inspectLog.ToString()),
-        Context.Environment.WorkingDirectory);
-
-    Information("{0} issues are found.", issues.Count());
-    
-    Information("InspectCode Log:{0}{1}", Environment.NewLine, FileReadText(inspectLog));
-    
-    var errorIssues = issues.Where(issue => resharperErrorRules.Any(issue.Rule.Contains)).ToList();
- 
-    if(errorIssues.Any())
-    {
-        var errorMessage = errorIssues.Aggregate(new StringBuilder(), (stringBuilder, issue) => stringBuilder.AppendFormat("FileName: {0} Line: {1} Message: {2}{3}", issue.AffectedFileRelativePath, issue.Line, issue.Message, Environment.NewLine));
-        throw new CakeException($"{errorIssues.Count} errors detected: {Environment.NewLine}{errorMessage}.");
-    }
+Task("NugetPush")
+.Does(() =>{
+	var nupkgs = GetFiles($"{nupkgDir}/*.nupkg");
+
+	Information("Need to push {0} packages", nupkgs.Count);
+	foreach(var nupkg in nupkgs) {
+		Information("Pushing {0}", nupkg);
+		NuGetPush(nupkg, new NuGetPushSettings {
+			Source = nugetSource,
+			ApiKey = nugetApiKey
+ 		});
+	}
 });
-                
-Task("Update-Assembly-Info")
-    .IsDependentOn("Get-Project-Name")
-    .Does(() =>
-{
-    
-    Information("Running semantic-release in dry run mode to extract next semantic version number");
-
-    string[] semanticReleaseOutput;
-    Npx("semantic-release", "--dry-run", requiredSemanticVersionPackages, out semanticReleaseOutput);
-
-    Information(string.Join(Environment.NewLine, semanticReleaseOutput));
-
-    var nextSemanticVersionNumber = ExtractNextSemanticVersionNumber(semanticReleaseOutput);
-
-    if (nextSemanticVersionNumber == null) {
-        Warning("There are no relevant changes. AssemblyInfo won't be updated!");
-    } else {
-        Information("Next semantic version number is {0}", nextSemanticVersionNumber);
-        
-        var assemblyVersion = $"{nextSemanticVersionNumber}.0";
-            
-        CreateAssemblyInfo(projectPath + "/" + projectName + "/Properties/AssemblyInfo.cs", new AssemblyInfoSettings{
-            Product = projectName,
-            Title = projectName,
-            Company = "RWTH Aachen University IT Center",
-            Version = assemblyVersion,
-            FileVersion = assemblyVersion,
-            InformationalVersion  = assemblyVersion,
-            Copyright = "RWTH Aachen University IT Center " + DateTime.Now.Year
-        });
-    }
+
+Task("NugetPack")
+.Does(() =>{
+	foreach(var project in projects) {
+			var nuspec = $"{project.GetDirectory()}/{project.GetFilenameWithoutExtension()}.nuspec";
+			if(!project.ToString().EndsWith(".Tests") 
+			&& FileExists(nuspec))
+			{
+				Information("Packing {0}...", nuspec);
+				
+				
+
+				if(!DirectoryExists(nupkgDir)) {
+					CreateDirectory(nupkgDir);
+				}
+				 
+				 NuGetPack(project.ToString() ,new NuGetPackSettings 
+				 {
+					OutputDirectory = nupkgDir,
+					Properties = new Dictionary<string, string> { {"Configuration", "Release"}}
+				 });
+			}
+		}
 });
-                
-Task("Build-Release")
-    .IsDependentOn("Get-Project-Name")
-    .Does(() =>
-{        
-    if(IsRunningOnWindows())
-    {
-        // Use MSBuild
-        MSBuild(solutionFile, settings => 
-        {
-            settings.SetConfiguration(configuration);
-            settings.WithProperty("DebugSymbols", "false");
-            settings.WithProperty("DebugType", "None");
-        });
-    }
-    else
-    {
-        // Use XBuild
-        XBuild(solutionFile, settings =>
-        {            
-            settings.SetConfiguration(configuration);
-            settings.WithProperty("DebugSymbols", "false");
-            settings.WithProperty("DebugType", "None");
-        });
-    }
-    CopyDirectory(buildDir, "./dist");
+
+
+Task("UpdateAssemblyInfo")
+.Does(() =>{
+	Information("Running semantic-release in dry run mode to extract next semantic version number");
+
+	string[] semanticReleaseOutput;
+	Npx("semantic-release", "--dry-run", requiredSemanticVersionPackages, out semanticReleaseOutput);
+
+	Information(string.Join(Environment.NewLine, semanticReleaseOutput));
+
+	var nextSemanticVersionNumber = ExtractNextSemanticVersionNumber(semanticReleaseOutput);
+
+	if (nextSemanticVersionNumber == null) {
+		Warning("There are no relevant changes. AssemblyInfo won't be updated!");
+	} else {
+		Information("Next semantic version number is {0}", nextSemanticVersionNumber);
+
+		var assemblyVersion = $"{nextSemanticVersionNumber}.0";
+
+		foreach(var project in projects) {
+			CreateAssemblyInfo($"{project.GetDirectory()}/{assemblyInfoSubPath}", new AssemblyInfoSettings {
+				Product = project.GetFilenameWithoutExtension().ToString(),
+				Title = project.GetFilenameWithoutExtension().ToString(),
+				Company = "IT Center, RWTH Aachen University",
+				Version = assemblyVersion,
+				FileVersion = assemblyVersion,
+				InformationalVersion = assemblyVersion,
+				Copyright = $"{DateTime.Now.Year} IT Center, RWTH Aachen University",
+				Description = $"{project.GetFilenameWithoutExtension().ToString()} is a part of the CoScInE group."
+			});
+		}
+	}
 });
 
 Task("Build")
-    .IsDependentOn("Get-Project-Name")
-    .Does(() =>
-{        
-    if(IsRunningOnWindows())
-    {
-        // Use MSBuild
-        MSBuild(solutionFile, settings => 
-        {
-            settings.SetConfiguration(configuration);
-            settings.WithProperty("RunCodeAnalysis", "true");
-        });
-    }
-    else
-    {
-        // Use XBuild
-        XBuild(solutionFile, settings =>
-        {            
-            settings.SetConfiguration(configuration);
-            settings.WithProperty("RunCodeAnalysis", "true");
-        });
-    }
-});
+.IsDependentOn("Clean")
+.IsDependentOn("Restore")
+.Does(() =>{
+	if (IsRunningOnWindows()) {
+		var frameworkSettingsWindows = new MSBuildSettings {
+			Configuration = configuration,
+			Restore = true
+		};
+		
+		frameworkSettingsWindows.ToolPath = msBuildPathX64;
+		frameworkSettingsWindows.WorkingDirectory = Context.Environment.WorkingDirectory;
+
+		if (configuration.Equals("Release")) {
+			frameworkSettingsWindows.WithProperty("DebugSymbols", "false");
+			frameworkSettingsWindows.WithProperty("DebugType", "None");
+		}
+		// Use MSBuild
+		Information($"Building {solutionFile}");
+		MSBuild(solutionFile, frameworkSettingsWindows);
+	}
+	else {
+		var frameworkSettingsUnix = new XBuildSettings {
+			Configuration = configuration
+		};
+
+		if (configuration.Equals("Release")) {
+			frameworkSettingsUnix.WithProperty("DebugSymbols", "false");
+			frameworkSettingsUnix.WithProperty("DebugType", "None");
+		}
+		// Use XBuild
+		Information($"Building {solutionFile}");
+		XBuild(solutionFile, frameworkSettingsUnix);
+	}
+	
+	if (configuration.Equals("Release")) {
+		if(!DirectoryExists(artifactsDir)) {
+			CreateDirectory(artifactsDir);
+		}
+		
+		foreach(var project in projects) {
+			if(!project.GetDirectory().ToString().EndsWith(".Tests")
+			&& !FileExists($"{project.GetDirectory()}/{project.GetFilenameWithoutExtension()}.nuspec"))
+			{
+				Information($"Copying {project.GetDirectory()}/bin/{configuration}/* to {artifactsDir}");
+				CopyDirectory($"{project.GetDirectory()}/bin/{configuration}/", artifactsDir);
+			}
+		}
+	}
 
-Task("Run-Unit-Tests")
-    .Does(() =>
-{
-    NUnit3("./src/**/bin/" + configuration + "/*.Tests.dll", new NUnit3Settings {
-        // generate the xml file
-        NoResults = false,
-        Results = new NUnit3Result[]{new NUnit3Result(){
-            FileName = Context.Environment.WorkingDirectory + "/TestResult.xml",
-            Transform = Context.Environment.WorkingDirectory + "/nunit3-junit.xslt"
-        }}
-    });
 });
 
-Task("Semantic-Release")
-    .Does(() =>
-{
-    Npx("semantic-release", requiredSemanticVersionPackages);
+Task("SemanticRelease")
+.Does(() =>{
+	Npx("semantic-release", requiredSemanticVersionPackages);
 });
 
-//////////////////////////////////////////////////////////////////////
-// TASK TARGETS
-//////////////////////////////////////////////////////////////////////
+Task("Linter")
+.Description("Run DupFinder and InspectCode")
+.IsDependentOn("DupFinder")
+.IsDependentOn("InspectCode");
+
+Task("LinterAndTest")
+.Description("Run Linter and Tests")
+.IsDependentOn("Linter")
+.IsDependentOn("Test");
 
 Task("Default")
-    .IsDependentOn("Clean")
-    .IsDependentOn("Restore-NuGet-Packages")
-    .IsDependentOn("Resharper")
-    .IsDependentOn("Build")
-    .IsDependentOn("Run-Unit-Tests");
+.IsDependentOn("Clean")
+.IsDependentOn("Restore")
+.IsDependentOn("DupFinder")
+.IsDependentOn("InspectCode")
+.IsDependentOn("Build")
+.IsDependentOn("Test");
 
 //////////////////////////////////////////////////////////////////////
 // EXECUTION
 //////////////////////////////////////////////////////////////////////
-
 RunTarget(target);
 
 ///////////////////////////////////////////////////////////////////////////////
 // Helpers
 ///////////////////////////////////////////////////////////////////////////////
+string ExtractNextSemanticVersionNumber(string[] semanticReleaseOutput) {
+	var extractRegEx = new System.Text.RegularExpressions.Regex("^.+next release version is (?<SemanticVersionNumber>.*)$");
 
-string ExtractNextSemanticVersionNumber(string[] semanticReleaseOutput)
-{
-    var extractRegEx = new System.Text.RegularExpressions.Regex("^.+next release version is (?<SemanticVersionNumber>.*)$");
-
-    return semanticReleaseOutput
-        .Select(line => extractRegEx.Match(line).Groups["SemanticVersionNumber"].Value)
-        .Where(line => !string.IsNullOrWhiteSpace(line))
-        .SingleOrDefault();
-}
\ No newline at end of file
+	return semanticReleaseOutput.Select(line =>extractRegEx.Match(line).Groups["SemanticVersionNumber"].Value).Where(line =>!string.IsNullOrWhiteSpace(line)).SingleOrDefault();
+}
diff --git a/build.ps1 b/build.ps1
index f83382e..7f1f813 100644
--- a/build.ps1
+++ b/build.ps1
@@ -1,24 +1,3 @@
-#The MIT License (MIT)
-#
-#Copyright (c) 2014 - 2016 Patrik Svensson, Mattias Karlsson, Gary Ewan Park and contributors
-#
-#Permission is hereby granted, free of charge, to any person obtaining a copy of
-#this software and associated documentation files (the "Software"), to deal in
-#the Software without restriction, including without limitation the rights to
-#use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
-#the Software, and to permit persons to whom the Software is furnished to do so,
-#subject to the following conditions:
-#
-#The above copyright notice and this permission notice shall be included in all
-#copies or substantial portions of the Software.
-#
-#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
-#FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-#COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
-#IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
 ##########################################################################
 # This is the Cake bootstrapper script for PowerShell.
 # This file was downloaded from https://github.com/cake-build/resources
@@ -46,10 +25,6 @@ Specifies the amount of information to be displayed.
 Shows description about tasks.
 .PARAMETER DryRun
 Performs a dry run.
-.PARAMETER Experimental
-Uses the nightly builds of the Roslyn script engine.
-.PARAMETER Mono
-Uses the Mono Compiler rather than the Roslyn script engine.
 .PARAMETER SkipToolPackageRestore
 Skips restoring of packages.
 .PARAMETER ScriptArgs
@@ -70,13 +45,28 @@ Param(
     [switch]$ShowDescription,
     [Alias("WhatIf", "Noop")]
     [switch]$DryRun,
-    [switch]$Experimental,
-    [switch]$Mono,
     [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)
 {
@@ -106,7 +96,7 @@ function GetProxyEnabledWebClient
 {
     $wc = New-Object System.Net.WebClient
     $proxy = [System.Net.WebRequest]::GetSystemWebProxy()
-    $proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials        
+    $proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials
     $wc.Proxy = $proxy
     return $wc
 }
@@ -131,15 +121,16 @@ $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
+    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 {        
+    Write-Verbose -Message "Downloading packages.config..."
+    try {
         $wc = GetProxyEnabledWebClient
-        $wc.DownloadFile("https://cakebuild.net/download/bootstrapper/packages", $PACKAGES_CONFIG) } catch {
+        $wc.DownloadFile("https://cakebuild.net/download/bootstrapper/packages", $PACKAGES_CONFIG)
+    } catch {
         Throw "Could not download packages.config."
     }
 }
@@ -167,7 +158,12 @@ if (!(Test-Path $NUGET_EXE)) {
 }
 
 # Save nuget.exe path to environment to be available to child processed
-$ENV:NUGET_EXE = $NUGET_EXE
+$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) {
@@ -175,15 +171,17 @@ if(-Not $SkipToolPackageRestore.IsPresent) {
     Set-Location $TOOLS_DIR
 
     # Check for changes in packages.config and remove installed tools if true.
-    [string] $md5Hash = MD5HashFile($PACKAGES_CONFIG)
+    [string] $md5Hash = MD5HashFile $PACKAGES_CONFIG
     if((!(Test-Path $PACKAGES_CONFIG_MD5)) -Or
-      ($md5Hash -ne (Get-Content $PACKAGES_CONFIG_MD5 ))) {
+    ($md5Hash -ne (Get-Content $PACKAGES_CONFIG_MD5 ))) {
         Write-Verbose -Message "Missing or changed package.config hash..."
-        Remove-Item * -Recurse -Exclude packages.config,nuget.exe
+        Get-ChildItem -Exclude packages.config,nuget.exe,Cake.Bakery |
+        Remove-Item -Recurse
     }
 
     Write-Verbose -Message "Restoring tools from NuGet..."
-    $NuGetOutput = Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion -OutputDirectory `"$TOOLS_DIR`""
+    
+    $NuGetOutput = Invoke-Expression "& $env:NUGET_EXE_INVOCATION install -ExcludeVersion -OutputDirectory `"$TOOLS_DIR`""
 
     if ($LASTEXITCODE -ne 0) {
         Throw "An error occurred while restoring NuGet tools."
@@ -192,7 +190,7 @@ if(-Not $SkipToolPackageRestore.IsPresent) {
     {
         $md5Hash | Out-File $PACKAGES_CONFIG_MD5 -Encoding "ASCII"
     }
-    Write-Verbose -Message ($NuGetOutput | out-string)
+    Write-Verbose -Message ($NuGetOutput | Out-String)
 
     Pop-Location
 }
@@ -203,13 +201,13 @@ if (Test-Path $ADDINS_PACKAGES_CONFIG) {
     Set-Location $ADDINS_DIR
 
     Write-Verbose -Message "Restoring addins from NuGet..."
-    $NuGetOutput = Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion -OutputDirectory `"$ADDINS_DIR`""
+    $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)
+    Write-Verbose -Message ($NuGetOutput | Out-String)
 
     Pop-Location
 }
@@ -220,13 +218,13 @@ if (Test-Path $MODULES_PACKAGES_CONFIG) {
     Set-Location $MODULES_DIR
 
     Write-Verbose -Message "Restoring modules from NuGet..."
-    $NuGetOutput = Invoke-Expression "&`"$NUGET_EXE`" install -ExcludeVersion -OutputDirectory `"$MODULES_DIR`""
+    $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)
+    Write-Verbose -Message ($NuGetOutput | Out-String)
 
     Pop-Location
 }
@@ -236,6 +234,11 @@ 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
@@ -245,11 +248,9 @@ if ($Configuration) { $cakeArguments += "-configuration=$Configuration" }
 if ($Verbosity) { $cakeArguments += "-verbosity=$Verbosity" }
 if ($ShowDescription) { $cakeArguments += "-showdescription" }
 if ($DryRun) { $cakeArguments += "-dryrun" }
-if ($Experimental) { $cakeArguments += "-experimental" }
-if ($Mono) { $cakeArguments += "-mono" }
 $cakeArguments += $ScriptArgs
 
 # Start Cake
 Write-Host "Running build script..."
-&$CAKE_EXE $cakeArguments
+Invoke-Expression "& $CAKE_EXE_INVOCATION $($cakeArguments -join " ")"
 exit $LASTEXITCODE
-- 
GitLab