public ScriptRunnerFixture(string fileName = "/Working/build.cake") { Script = fileName; Source = "Hello World"; AssemblyLoader = Substitute.For <IAssemblyLoader>(); Environment = FakeEnvironment.CreateUnixEnvironment(); FileSystem = new FakeFileSystem(Environment); FileSystem.CreateFile(Script.MakeAbsolute(Environment)).SetContent(Source); Globber = new Globber(FileSystem, Environment); Configuration = Substitute.For <ICakeConfiguration>(); AliasFinder = Substitute.For <IScriptAliasFinder>(); Log = new FakeLog(); Session = Substitute.For <IScriptSession>(); ArgumentDictionary = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); Engine = Substitute.For <IScriptEngine>(); Engine.CreateSession(Arg.Any <IScriptHost>()).Returns(Session); var runtime = new CakeRuntime(); ScriptAnalyzer = new ScriptAnalyzer(FileSystem, Environment, Log, new[] { new FileLoadDirectiveProvider(Globber, Log) }); ScriptProcessor = Substitute.For <IScriptProcessor>(); ScriptConventions = new ScriptConventions(FileSystem, AssemblyLoader, runtime); var context = Substitute.For <ICakeContext>(); context.Environment.Returns(c => Environment); context.FileSystem.Returns(c => FileSystem); Host = Substitute.For <IScriptHost>(); Host.Context.Returns(context); }
public FakeCakeContext() { testsDir = new DirectoryPath( System.IO.Path.GetFullPath(AppContext.BaseDirectory)); var fileSystem = new FileSystem(); log = new FakeLog(); var runtime = new CakeRuntime(); var platform = new FakePlatform(PlatformFamily.Windows); var environment = new CakeEnvironment(platform, runtime); var globber = new Globber(fileSystem, environment); var args = new FakeCakeArguments(); var registry = new WindowsRegistry(); var dataService = new FakeDataService(); var toolRepository = new ToolRepository(environment); var config = new FakeConfiguration(); var toolResolutionStrategy = new ToolResolutionStrategy(fileSystem, environment, globber, config, log); IToolLocator tools = new ToolLocator(environment, toolRepository, toolResolutionStrategy); var processRunner = new ProcessRunner(fileSystem, environment, log, tools, config); context = new CakeContext(fileSystem, environment, globber, log, args, processRunner, registry, tools, dataService, config); context.Environment.WorkingDirectory = testsDir; }
public FakeCakeContext() { var fileSystem = new FileSystem(); Log = new FakeLog(); var runtime = new CakeRuntime(); var platform = new FakePlatform(PlatformFamily.Windows); var environment = new CakeEnvironment(platform, runtime, Log); var globber = new Globber(fileSystem, environment); var args = Substitute.For <ICakeArguments>(); var registry = new WindowsRegistry(); var dataService = Substitute.For <ICakeDataService>(); var toolRepository = new ToolRepository(environment); var toolResolutionStrategy = new ToolResolutionStrategy(fileSystem, environment, globber, new FakeConfiguration()); var tools = new ToolLocator(environment, toolRepository, toolResolutionStrategy); var processRunner = new ProcessRunner(fileSystem, environment, Log, tools, new FakeConfiguration()); Context = new CakeContext(fileSystem, environment, globber, Log, args, processRunner, registry, tools, dataService); WorkingDirectory = new DirectoryPath( System.IO.Path.GetFullPath(AppContext.BaseDirectory)); Context.Environment.WorkingDirectory = WorkingDirectory; }
public void Should_Return_Correct_Result_For_CoreClr() { // Given var runtime = new CakeRuntime(); // When var framework = runtime.BuiltFramework; // Then #if NETFRAMEWORK Assert.Equal(".NETFramework,Version=v4.6.1", framework.FullName); #elif !NETCOREAPP Assert.Equal(".NETStandard,Version=v2.0", framework.FullName); #else var expect = string.Concat(".NETCoreApp,Version=v", #if NETCOREAPP2_0 "2.0"); #elif NETCOREAPP2_1 "2.1"); #elif NETCOREAPP2_2 "2.2"); #elif NETCOREAPP3_0 "3.0"); #endif // ToDo: Enable mocking runtime resolution, temp work around for missing runtimes. switch (expect) { case ".NETCoreApp,Version=v2.0": { switch (framework.FullName) { case ".NETCoreApp,Version=v2.1": case ".NETCoreApp,Version=v3.0": { TestOutputHelper.WriteLine("Expect changed from {0} to {1}.", expect, framework.FullName); expect = framework.FullName; break; } } break; } case ".NETCoreApp,Version=v2.1": { switch (framework.FullName) { case ".NETCoreApp,Version=v3.0": { TestOutputHelper.WriteLine("Expect changed from {0} to {1}.", expect, framework.FullName); expect = framework.FullName; break; } } break; } } Assert.Equal(expect, framework.FullName); #endif }
static ProjectReference() { var platform = new CakePlatform(); var runtime = new CakeRuntime(); var cakeConsole = new CakeConsole(); var cakeLog = new CakeBuildLog(cakeConsole, Verbosity.Diagnostic); _environment = new CakeEnvironment(platform, runtime, cakeLog); _fileSystem = new Cake.Core.IO.FileSystem(); }
static ProjectHelper() { var platform = new CakePlatform(); var runtime = new CakeRuntime(); var cakeConsole = new CakeConsole(); var cakeLog = new CakeBuildLog(cakeConsole, Verbosity.Quiet); _environment = new CakeEnvironment(platform, runtime, cakeLog); _fileSystem = new FileSystem(); }
public void Should_Return_Correct_Result_For_CoreClr() { // Given var runtime = new CakeRuntime(); // When var framework = runtime.TargetFramework; // Then Assert.Equal(".NETStandard,Version=v1.6", framework.FullName); }
public void Should_Return_Correct_Result_For_Clr() { // Given var runtime = new CakeRuntime(); // When var framework = runtime.BuiltFramework; // Then Assert.Equal(".NETFramework,Version=v4.6.1", framework.FullName); }
internal static IEnumerable <string> GetCSharpFilesFromProject(string csProjFolderPath) { var csProjFilePath = Directory.EnumerateFiles(csProjFolderPath, "*.csproj", SearchOption.TopDirectoryOnly).SingleOrDefault(); if (csProjFilePath is null) { throw new FileNotFoundException(); } var fileSystem = new Cake.Core.IO.FileSystem(); var platform = new CakePlatform(); var runtime = new CakeRuntime(); var cakeConsole = new CakeConsole(); var cakeLog = new CakeBuildLog(cakeConsole, Verbosity.Diagnostic); var environment = new CakeEnvironment(platform, runtime, cakeLog); var projectPath = new Cake.Core.IO.FilePath(csProjFilePath); if (projectPath.IsRelative) { projectPath = projectPath.MakeAbsolute(environment); } var projectFile = fileSystem.GetFile(projectPath); var parseResult = projectFile.ParseProjectFile("Debug"); // TODO: do not assume all .cs files are included by default? // TODO: do not return .cs files that are removed from Compile in the .csproj foreach (var sourceFile in GetCSharpFilesFromFolder(csProjFolderPath)) { yield return(sourceFile); } // TODO: if a project or package is encountered multiple times through recursion, ensure it only gets evaluated once (use HashSet?) // TODO: handle the case where a library is referenced as both a projectReference and a packageReference (NuGet gives error when this happens) foreach (var projectReference in parseResult.ProjectReferences) { // TODO: test that this works correctly foreach (var sourceFile in GetCSharpFilesFromProject(projectReference.FilePath.FullPath)) { yield return(sourceFile); } } // Assume package reference is either a .Sources package, or it's not and has no .cs files packed. foreach (var packageReference in parseResult.PackageReferences) { // TODO: try to get source files from package's dependencies (recursively) foreach (var sourceFile in DiscoverPackageReferenceSourceFiles(packageReference.Name, packageReference.Version)) { yield return(sourceFile); } } }
/// <summary> /// Runs the application. /// </summary> /// <param name="args">Arguments.</param> /// <param name="appRoot">Application root folder</param> /// <returns>The result of the run.</returns> public async Task <RunResult> RunAsync(IEnumerable <string> args, string appRoot = null) { var console = new CakeConsole(); var logger = new SafeCakeLog(console); ICakeDataService dataService = new CodeCakeDataService(); var engine = new CakeEngine(dataService, logger); ICakePlatform platform = new CakePlatform(); ICakeRuntime runtime = new CakeRuntime(); IFileSystem fileSystem = new FileSystem(); MutableCakeEnvironment environment = new MutableCakeEnvironment(platform, runtime, appRoot); console.SupportAnsiEscapeCodes = AnsiDetector.SupportsAnsi(environment); IGlobber globber = new Globber(fileSystem, environment); IRegistry windowsRegistry = new WindowsRegistry(); // Parse options. var argumentParser = new ArgumentParser(logger, fileSystem); CakeOptions options = argumentParser.Parse(args); Debug.Assert(options != null); CakeConfigurationProvider configProvider = new CakeConfigurationProvider(fileSystem, environment); ICakeConfiguration configuration = configProvider.CreateConfiguration(environment.ApplicationRoot, options.Arguments); IToolRepository toolRepo = new ToolRepository(environment); IToolResolutionStrategy toolStrategy = new ToolResolutionStrategy(fileSystem, environment, globber, configuration, logger); IToolLocator locator = new ToolLocator(environment, toolRepo, toolStrategy); IToolLocator toolLocator = new ToolLocator(environment, toolRepo, toolStrategy); IProcessRunner processRunner = new ProcessRunner(fileSystem, environment, logger, toolLocator, configuration); logger.SetVerbosity(options.Verbosity); ICakeArguments arguments = new CakeArguments(options.Arguments); var context = new CakeContext( fileSystem, environment, globber, logger, arguments, processRunner, windowsRegistry, locator, dataService, configuration); CodeCakeBuildTypeDescriptor choosenBuild; if (!AvailableBuilds.TryGetValue(options.Script, out choosenBuild)) { logger.Error("Build script '{0}' not found.", options.Script); return(new RunResult(-1, context.InteractiveMode())); } // Set the working directory: the solution directory. logger.Information($"Working in Solution directory: '{_solutionDirectory}'."); environment.WorkingDirectory = new DirectoryPath(_solutionDirectory); try { SetEnvironmentVariablesFromCodeCakeBuilderKeyVault(logger, context); // Instantiates the script object. CodeCakeHost._injectedActualHost = new BuildScriptHost(engine, context); CodeCakeHost c = (CodeCakeHost)Activator.CreateInstance(choosenBuild.Type); var target = context.Arguments.GetArgument("target") ?? "Default"; var execSettings = new ExecutionSettings().SetTarget(target); var exclusiveTargetOptional = context.Arguments.HasArgument("exclusiveOptional"); var exclusiveTarget = exclusiveTargetOptional | context.Arguments.HasArgument("exclusive"); var strategy = new CodeCakeExecutionStrategy(logger, exclusiveTarget ? target : null); if (exclusiveTargetOptional && !engine.Tasks.Any(t => t.Name == target)) { logger.Warning($"No task '{target}' defined. Since -exclusiveOptional is specified, nothing is done."); return(new RunResult(0, context.InteractiveMode())); } var report = await engine.RunTargetAsync(context, strategy, execSettings); if (report != null && !report.IsEmpty) { var printerReport = new CakeReportPrinter(console); printerReport.Write(report); } } catch (CakeTerminateException ex) { switch (ex.Option) { case CakeTerminationOption.Error: logger.Error("Termination with Error: '{0}'.", ex.Message); return(new RunResult(-2, context.InteractiveMode())); case CakeTerminationOption.Warning: logger.Warning("Termination with Warning: '{0}'.", ex.Message); break; default: Debug.Assert(ex.Option == CakeTerminationOption.Success); logger.Information("Termination with Success: '{0}'.", ex.Message); break; } } catch (TargetInvocationException ex) { logger.Error("Error occurred: '{0}'.", ex.InnerException?.Message ?? ex.Message); return(new RunResult(-3, context.InteractiveMode())); } catch (AggregateException ex) { logger.Error("Error occurred: '{0}'.", ex.Message); foreach (var e in ex.InnerExceptions) { logger.Error(" -> '{0}'.", e.Message); } return(new RunResult(-4, context.InteractiveMode())); } catch (Exception ex) { logger.Error("Error occurred: '{0}'.", ex.Message); return(new RunResult(-5, context.InteractiveMode())); } return(new RunResult(0, context.InteractiveMode())); }
/// <summary> /// Runs the application. /// </summary> /// <param name="args">Arguments.</param> /// <returns>0 on success.</returns> public int Run( string[] args ) { var console = new CakeConsole(); var logger = new SafeCakeLog( console ); var engine = new CakeEngine( logger ); ICakePlatform platform = new CakePlatform(); ICakeRuntime runtime = new CakeRuntime(); IFileSystem fileSystem = new FileSystem(); MutableCakeEnvironment environment = new MutableCakeEnvironment( platform, runtime ); IGlobber globber = new Globber( fileSystem, environment ); environment.Initialize( globber ); IProcessRunner processRunner = new ProcessRunner( environment, logger ); IRegistry windowsRegistry = new WindowsRegistry(); // Parse options. var argumentParser = new ArgumentParser( logger, fileSystem ); CakeOptions options = argumentParser.Parse( args ); Debug.Assert( options != null ); CakeConfigurationProvider configProvider = new CakeConfigurationProvider( fileSystem, environment ); ICakeConfiguration configuration = configProvider.CreateConfiguration( environment.ApplicationRoot, options.Arguments ); IToolRepository toolRepo = new ToolRepository( environment ); IToolResolutionStrategy toolStrategy = new ToolResolutionStrategy( fileSystem, environment, globber, configuration ); IToolLocator locator = new ToolLocator( environment, toolRepo, toolStrategy ); IToolLocator toolLocator = new ToolLocator( environment, toolRepo, toolStrategy ); logger.SetVerbosity( options.Verbosity ); CodeCakeBuildTypeDescriptor choosenBuild; if( !AvailableBuilds.TryGetValue( options.Script, out choosenBuild ) ) { logger.Error( "Build script '{0}' not found.", options.Script ); return -1; } ICakeArguments arguments = new CakeArguments(options.Arguments); var context = new CakeContext( fileSystem, environment, globber, logger, arguments, processRunner, windowsRegistry, locator ); // Copy the arguments from the options. // Set the working directory: the solution directory. environment.WorkingDirectory = new DirectoryPath( _solutionDirectory ); // Adds additional paths from chosen build. foreach( var p in choosenBuild.AdditionnalPatternPaths ) { environment.AddPath( p ); } logger.Information( "Path(s) added: " + string.Join( ", ", environment.EnvironmentAddedPaths ) ); logger.Information( "Dynamic pattern path(s) added: " + string.Join( ", ", environment.EnvironmentDynamicPaths ) ); try { // Instanciates the script object. CodeCakeHost._injectedActualHost = new BuildScriptHost( engine, context ); CodeCakeHost c = (CodeCakeHost)Activator.CreateInstance( choosenBuild.Type ); var strategy = new DefaultExecutionStrategy( logger ); var report = engine.RunTarget( context, strategy, context.Arguments.GetArgument( "target" ) ?? "Default" ); if( report != null && !report.IsEmpty ) { var printerReport = new CakeReportPrinter( console ); printerReport.Write( report ); } } catch( CakeTerminateException ex ) { switch( ex.Option ) { case CakeTerminationOption.Error: logger.Error( "Termination with Error: '{0}'.", ex.Message ); return -1; case CakeTerminationOption.Warning: logger.Warning( "Termination with Warning: '{0}'.", ex.Message ); break; default: Debug.Assert( ex.Option == CakeTerminationOption.Success ); logger.Information( "Termination with Success: '{0}'.", ex.Message ); break; } } catch( TargetInvocationException ex ) { logger.Error( "Error occurred: '{0}'.", ex.InnerException?.Message ?? ex.Message ); return -1; } catch( Exception ex ) { logger.Error( "Error occurred: '{0}'.", ex.Message ); return -1; } return 0; }
/// <summary> /// Runs the application. /// </summary> /// <param name="args">Arguments.</param> /// <param name="appRoot">Application root folder</param> /// <returns>0 on success.</returns> public int Run(string[] args, string appRoot = null) { var console = new CakeConsole(); var logger = new SafeCakeLog(console); var engine = new CakeEngine(logger); ICakePlatform platform = new CakePlatform(); ICakeRuntime runtime = new CakeRuntime(); IFileSystem fileSystem = new FileSystem(); MutableCakeEnvironment environment = new MutableCakeEnvironment(platform, runtime, appRoot); IGlobber globber = new Globber(fileSystem, environment); environment.Initialize(globber); IProcessRunner processRunner = new ProcessRunner(environment, logger); IRegistry windowsRegistry = new WindowsRegistry(); // Parse options. var argumentParser = new ArgumentParser(logger, fileSystem); CakeOptions options = argumentParser.Parse(args); Debug.Assert(options != null); CakeConfigurationProvider configProvider = new CakeConfigurationProvider(fileSystem, environment); ICakeConfiguration configuration = configProvider.CreateConfiguration(environment.ApplicationRoot, options.Arguments); IToolRepository toolRepo = new ToolRepository(environment); IToolResolutionStrategy toolStrategy = new ToolResolutionStrategy(fileSystem, environment, globber, configuration); IToolLocator locator = new ToolLocator(environment, toolRepo, toolStrategy); IToolLocator toolLocator = new ToolLocator(environment, toolRepo, toolStrategy); logger.SetVerbosity(options.Verbosity); CodeCakeBuildTypeDescriptor choosenBuild; if (!AvailableBuilds.TryGetValue(options.Script, out choosenBuild)) { logger.Error("Build script '{0}' not found.", options.Script); return(-1); } ICakeArguments arguments = new CakeArguments(options.Arguments); var context = new CakeContext(fileSystem, environment, globber, logger, arguments, processRunner, windowsRegistry, locator); // Copy the arguments from the options. // Set the working directory: the solution directory. environment.WorkingDirectory = new DirectoryPath(_solutionDirectory); // Adds additional paths from chosen build. foreach (var p in choosenBuild.AdditionnalPatternPaths) { environment.AddPath(p); } logger.Information("Path(s) added: " + string.Join(", ", environment.EnvironmentAddedPaths)); logger.Information("Dynamic pattern path(s) added: " + string.Join(", ", environment.EnvironmentDynamicPaths)); try { // Instanciates the script object. CodeCakeHost._injectedActualHost = new BuildScriptHost(engine, context); CodeCakeHost c = (CodeCakeHost)Activator.CreateInstance(choosenBuild.Type); var strategy = new DefaultExecutionStrategy(logger); var report = engine.RunTargetAsync(context, strategy, context.Arguments.GetArgument("target") ?? "Default").GetAwaiter().GetResult(); if (report != null && !report.IsEmpty) { var printerReport = new CakeReportPrinter(console); printerReport.Write(report); } } catch (CakeTerminateException ex) { switch (ex.Option) { case CakeTerminationOption.Error: logger.Error("Termination with Error: '{0}'.", ex.Message); return(-1); case CakeTerminationOption.Warning: logger.Warning("Termination with Warning: '{0}'.", ex.Message); break; default: Debug.Assert(ex.Option == CakeTerminationOption.Success); logger.Information("Termination with Success: '{0}'.", ex.Message); break; } } catch (TargetInvocationException ex) { logger.Error("Error occurred: '{0}'.", ex.InnerException?.Message ?? ex.Message); return(-1); } catch (Exception ex) { logger.Error("Error occurred: '{0}'.", ex.Message); return(-1); } return(0); }