Example #1
0
        static CakeAPI()
        {
            var env        = new CakeEnvironment(new CakePlatform(), new CakeRuntime());
            var fileSystem = new FileSystem();

            var verbosity = Verbosity.Normal;

            if (Startup.HasArgument("cake-verbosity"))
            {
                verbosity = Enum.Parse <Verbosity>(Startup.Argument("cake-verbosity"));
            }
            var cakeLog = new CakeBuildLog(new CakeConsole(env), verbosity);

            var cakeConfiguration = new CakeConfiguration(new Dictionary <string, string>());
            var toolRepos         = new ToolRepository(env);

            Globber = new Globber(fileSystem, env);
            var cakeDataService = new CakeDataService();
            var registry        = new WindowsRegistry();
            var toolLocator     = new ToolLocator(env, toolRepos, new ToolResolutionStrategy(fileSystem, env, Globber, cakeConfiguration, cakeLog));
            var cakeArgs        = new CakeArguments(new List <string>().ToLookup(x => x));
            var procRunner      = new ProcessRunner(fileSystem, env, cakeLog, toolLocator, cakeConfiguration);

            Context = new CakeContext(fileSystem, env, Globber, cakeLog, cakeArgs, procRunner, registry, toolLocator, cakeDataService, cakeConfiguration);
        }
Example #2
0
        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;
        }
Example #3
0
        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;
        }
Example #4
0
        public UnityRunnerFixture()
        {
            ProjectPath = new DirectoryPath("C:/Project");
            Platform    = Substitute.For <UnityPlatform>();

            DefaultToolPathExist = true;
            ProjectPathExist     = true;

            Process = new FakeProcess();

            ProcessRunner = Substitute.For <IProcessRunner>();
            ProcessRunner.Start(Arg.Any <FilePath>(), Arg.Any <ProcessSettings>()).Returns(Process);

            Environment = new FakeEnvironment(PlatformFamily.Windows)
            {
                WorkingDirectory = "/Working"
            };
            Environment.SetSpecialPath(SpecialPath.ProgramFilesX86, "C:/Program Files (x86)");

            FileSystem = new FakeFileSystem(Environment);
            var globber = new Globber(FileSystem, Environment);

            Tools   = new ToolLocator(Environment, new ToolRepository(Environment), new ToolResolutionStrategy(FileSystem, Environment, globber, new FakeConfiguration()));
            Context = new CakeContext(FileSystem, Environment, globber, new FakeLog(), Substitute.For <ICakeArguments>(), ProcessRunner, Substitute.For <IRegistry>(), Tools, Substitute.For <ICakeDataService>());
        }
Example #5
0
        public FakeCakeContext()
        {
            var testsDir = new DirectoryPath(System.IO.Path.GetFullPath(AppContext.BaseDirectory));

            var fileSystem  = new FileSystem();
            var environment = new FakeEnvironment(PlatformFamily.Windows);
            var globber     = new Globber(fileSystem, environment);
            var log         = new FakeLog();
            var args        = new FakeCakeArguments();
            var toolRepo    = new ToolRepository(environment);
            var config      =
                new CakeConfigurationProvider(fileSystem, environment)
                .CreateConfiguration(testsDir,
                                     new Dictionary <string, string>());
            var toolResolutionStrategy = new ToolResolutionStrategy(fileSystem, environment, globber, config);
            var toolLocator            = new ToolLocator(environment, toolRepo, toolResolutionStrategy);
            var processRunner          = new ProcessRunner(fileSystem, environment, log, toolLocator, config);
            var registry    = new WindowsRegistry();
            var dataService = new FakeDataService();

            _context = new CakeContext(
                fileSystem,
                environment,
                globber,
                log,
                args,
                processRunner,
                registry,
                toolLocator,
                dataService,
                config);

            _context.Environment.WorkingDirectory = testsDir;
        }
Example #6
0
 public NuGetToolResolverFixture(FakeEnvironment environment = null)
 {
     Environment = environment ?? FakeEnvironment.CreateUnixEnvironment();
     FileSystem  = new FakeFileSystem(Environment);
     Tools       = new ToolLocator(
         Environment,
         new ToolRepository(Environment),
         new ToolResolutionStrategy(FileSystem, Environment, new Globber(FileSystem, Environment), new FakeConfiguration()));
 }
 public CloudShellToolResolverFixture(FakeEnvironment environment = null)
 {
     this.Environment = environment ?? FakeEnvironment.CreateUnixEnvironment();
     this.FileSystem  = new FakeFileSystem(this.Environment);
     this.Tools       = new ToolLocator(
         this.Environment,
         new ToolRepository(this.Environment),
         new ToolResolutionStrategy(this.FileSystem, this.Environment, new Globber(this.FileSystem, this.Environment), new FakeConfiguration()));
 }
        /// <inheritdoc/>
        public void Import(SpriteFontAsset options, List <char> characters)
        {
            fontSource = options.FontSource.GetFontPath();
            if (string.IsNullOrEmpty(fontSource))
            {
                return;
            }

            // Get the msdfgen.exe location
            var msdfgen = ToolLocator.LocateTool("msdfgen.exe") ?? throw new AssetException("Failed to compile a font asset, msdfgen was not found.");

            msdfgenExe = msdfgen.FullPath;
            tempDir    = $"{Environment.GetEnvironmentVariable("TEMP")}\\";

            var factory = new Factory();

            FontFace fontFace = options.FontSource.GetFontFace();

            var fontMetrics = fontFace.Metrics;

            // Create a bunch of GDI+ objects.
            var fontSize = options.FontType.Size;

            var glyphList = new List <Glyph>();

            // Remap the LineMap coming from the font with a user defined remapping
            // Note:
            // We are remapping the lineMap to allow to shrink the LineGap and to reposition it at the top and/or bottom of the
            // font instead of using only the top
            // According to http://stackoverflow.com/questions/13939264/how-to-determine-baseline-position-using-directwrite#comment27947684_14061348
            // (The response is from a MSFT employee), the BaseLine should be = LineGap + Ascent but this is not what
            // we are experiencing when comparing with MSWord (LineGap + Ascent seems to offset too much.)
            //
            // So we are first applying a factor to the line gap:
            //     NewLineGap = LineGap * LineGapFactor
            var lineGap = fontMetrics.LineGap * options.LineGapFactor;

            // Store the font height.
            LineSpacing = (float)(lineGap + fontMetrics.Ascent + fontMetrics.Descent) / fontMetrics.DesignUnitsPerEm * fontSize;

            // And then the baseline is also changed in order to allow the linegap to be distributed between the top and the
            // bottom of the font:
            //     BaseLine = NewLineGap * LineGapBaseLineFactor
            BaseLine = (float)(lineGap * options.LineGapBaseLineFactor + fontMetrics.Ascent) / fontMetrics.DesignUnitsPerEm * fontSize;

            // Generate SDF bitmaps for each character in turn.
            foreach (var character in characters)
            {
                glyphList.Add(ImportGlyph(fontFace, character, fontMetrics, fontSize));
            }

            Glyphs = glyphList;

            factory.Dispose();
        }
        public MkDocsContextFixture(IProcess process)
        {
            ProcessRunner = new FakeProcessRunner(process);
            Environment   = FakeEnvironment.CreateUnixEnvironment();
            FileSystem    = new FakeFileSystem(Environment);
            Globber       = new Globber(FileSystem, Environment);
            Configuration = new FakeConfiguration();
            Tools         = new ToolLocator(Environment, new ToolRepository(Environment), new ToolResolutionStrategy(FileSystem, Environment, Globber, Configuration));
            Data          = new FakeCakeDataService();

            DefaultToolPath = new FilePath("./tools/mkdocs.exe").MakeAbsolute(Environment);
            ((FakeFileSystem)FileSystem).CreateFile(DefaultToolPath);
        }
Example #10
0
        /// <summary>
        /// Ensures that the environment is a windows environment.
        /// <para>WARNING: As calling this method will remove the existing Environment
        /// and replace it with a new one, this method should be called first, before any
        /// other modifications are made.</para>
        /// </summary>
        public void GivenAWindowsEnvironment()
        {
            Environment = FakeEnvironment.CreateWindowsEnvironment();

            // re-create everything that had a reference to the old environment
            // see https://github.com/cake-build/cake/blob/main/src/Cake.Testing/Fixtures/ToolFixture%602.cs#L78
            FileSystem = new FakeFileSystem(Environment);
            Globber    = new Globber(FileSystem, Environment);
            Tools      = new ToolLocator(Environment, new ToolRepository(Environment), new ToolResolutionStrategy(FileSystem, Environment, Globber, Configuration, new NullLog()));

            // re-create the tool (as it, too, had a reference to the environment
            _tool = new GradleRunner(FileSystem, Environment, ProcessRunner, Tools);
        }
Example #11
0
            public void Should_Throw_If_Tool_Is_Null()
            {
                // Given
                var environment = FakeEnvironment.CreateUnixEnvironment();
                var repository  = Substitute.For <IToolRepository>();
                var strategy    = Substitute.For <IToolResolutionStrategy>();
                var locator     = new ToolLocator(environment, repository, strategy);

                // When
                var result = Record.Exception(() => locator.Resolve(null));

                // Then
                AssertEx.IsArgumentNullException(result, "tool");
            }
Example #12
0
            public void Should_Throw_If_Tool_Is_Empty(string tool)
            {
                // Given
                var environment = FakeEnvironment.CreateUnixEnvironment();
                var repository  = Substitute.For <IToolRepository>();
                var strategy    = Substitute.For <IToolResolutionStrategy>();
                var locator     = new ToolLocator(environment, repository, strategy);

                // When
                var result = Record.Exception(() => locator.Resolve(tool));

                // Then
                Assert.IsArgumentException(result, "tool", "Tool name cannot be empty.");
            }
Example #13
0
        protected ToolFixture(string toolFilename)
        {
            Settings      = new TToolSettings();
            ProcessRunner = new ToolFixtureProcessRunner <TFixtureResult>(CreateResult);
            Environment   = FakeEnvironment.CreateUnixEnvironment();
            FileSystem    = new FakeFileSystem(Environment);
            Globber       = new Globber(FileSystem, Environment);
            Configuration = new FakeConfiguration();
            Tools         = new ToolLocator(Environment, new ToolRepository(Environment), new ToolResolutionStrategy(FileSystem, Environment, Globber, Configuration));

            // ReSharper disable once VirtualMemberCallInContructor
            _defaultToolPath = GetDefaultToolPath(toolFilename);
            FileSystem.CreateFile(_defaultToolPath);
        }
Example #14
0
        public MockContext()
        {
            Arguments   = new CakeArguments();
            Environment = FakeEnvironment.CreateUnixEnvironment();
            FileSystem  = new FakeFileSystem(Environment);
            Globber     = Substitute.For <IGlobber>();
            Log         = new FakeLog();

            var configuration = new FakeConfiguration();

            Configuration = configuration;
            Registry      = new WindowsRegistry();
            Tools         = new ToolLocator(Environment, new ToolRepository(Environment), new ToolResolutionStrategy(FileSystem, Environment, Globber, configuration, Log));
            ProcessRunner = new ProcessRunner(FileSystem, Environment, Log, Tools, configuration);
        }
Example #15
0
            public void Should_Resolve_Tool_Using_The_Tool_Resolution_Strategy()
            {
                // Given
                var environment = FakeEnvironment.CreateUnixEnvironment();
                var repository  = Substitute.For <IToolRepository>();
                var strategy    = Substitute.For <IToolResolutionStrategy>();
                var locator     = new ToolLocator(environment, repository, strategy);

                // When
                locator.Resolve("test.exe");

                // Then
                strategy.Received(1)
                .Resolve(Arg.Is(repository), Arg.Is("test.exe"));
            }
Example #16
0
            public void Should_Resolve_ToolExeNames_Using_The_Tool_Resolution_Strategy()
            {
                // Given
                var environment = FakeEnvironment.CreateUnixEnvironment();
                var repository  = Substitute.For <IToolRepository>();
                var strategy    = Substitute.For <IToolResolutionStrategy>();
                var locator     = new ToolLocator(environment, repository, strategy);

                // When
                locator.Resolve(new[] { "test.exe", "dotnet-test", "dotnet-test.exe" });

                // Then
                strategy.Received(1)
                .Resolve(Arg.Is(repository), Arg.Is <IEnumerable <string> >(arg => arg.SequenceEqual(new[] { "test.exe", "dotnet-test", "dotnet-test.exe" })));
            }
Example #17
0
            public void Should_Register_File_Path_With_Tool_Repository()
            {
                // Given
                var environment = FakeEnvironment.CreateUnixEnvironment();
                var repository  = Substitute.For <IToolRepository>();
                var strategy    = Substitute.For <IToolResolutionStrategy>();
                var locator     = new ToolLocator(environment, repository, strategy);

                // When
                locator.RegisterFile("./mytools/test.exe");

                // Then
                repository.Received(1)
                .Register(Arg.Is <FilePath>(path => path.FullPath == "/Working/mytools/test.exe"));
            }
Example #18
0
        private static string GetCakePath(string cwd)
        {
            var locator = new ToolLocator(new List <string> {
                "dotnet-cake.exe", "dotnet-cake", "cake.exe"
            })
                          .AddConfigPath(() => new ConfigurationParser(ConfigurationParser.GetConfigFilePath(cwd)))
                          .AddEnvironmentVariables()
                          .AddKnownPaths("tools/Cake", "Cake", ".");
            var path = locator.Locate(cwd);

            return(string.IsNullOrWhiteSpace(path)
                ? PathHelpers.ExistsOnPath("cake.exe")
                    ? "cake"
                    : null
                : path);
        }
        protected BaseMkDocsServeAsyncFixture()
        {
            Settings      = new MkDocsServeAsyncSettings();
            ProcessRunner = new ToolFixtureProcessLongRunner(CreateResult);
            Environment   = FakeEnvironment.CreateUnixEnvironment();
            FileSystem    = new FakeFileSystem(Environment);
            Globber       = new Globber(FileSystem, Environment);
            Configuration = new FakeConfiguration();
            Tools         = new ToolLocator(Environment, new ToolRepository(Environment),
                                            new ToolResolutionStrategy(FileSystem, Environment, Globber, Configuration));

            // ReSharper disable once VirtualMemberCallInConstructor
            DefaultToolPath = GetDefaultToolPath(ToolFileName);
            FileSystem.CreateFile(DefaultToolPath);

            Settings.Token = new CancellationToken(true);
        }
        public CakeFixture()
        {
            var env = FakeEnvironment.CreateUnixEnvironment();

            FileSystem = new FakeFileSystem(env);
            var globber         = new Globber(FileSystem, env);
            var log             = new NullLog();
            var reg             = new WindowsRegistry();
            var config          = new CakeConfiguration(new Dictionary <string, string>());
            var strategy        = new ToolResolutionStrategy(FileSystem, env, globber, config, log);
            var toolLocator     = new ToolLocator(env, new ToolRepository(env), strategy);
            var cakeDataService = new FakeDataService();
            var runner          = new ProcessRunner(FileSystem, env, log, toolLocator, config);
            var args            = new FakeArguments();

            Context = new CakeContext(FileSystem, env, globber, log, args, runner, reg, toolLocator, cakeDataService, config);
        }
Example #21
0
        public FakeCakeContext ()
        {
            testsDir = new DirectoryPath(System.IO.Path.GetFullPath(AppContext.BaseDirectory));

            var environment = Cake.Testing.FakeEnvironment.CreateUnixEnvironment (false);

            var fileSystem = new Cake.Testing.FakeFileSystem (environment);
            var globber = new Globber (fileSystem, environment);
            log = new Cake.Testing.FakeLog ();
            var args = new FakeCakeArguments ();
            var processRunner = new ProcessRunner (environment, log);
            var registry = new WindowsRegistry ();

            var tools = new ToolLocator(environment, new ToolRepository(environment), new ToolResolutionStrategy(fileSystem, environment, globber, new FakeConfiguration()));
            context = new CakeContext (fileSystem, environment, globber, log, args, processRunner, registry, tools);
            context.Environment.WorkingDirectory = testsDir;
        }
Example #22
0
    public static IScriptHost GetScriptHost()
    {
        var              console     = new CakeConsole();
        ICakeLog         log         = new CakeBuildLog(console);
        IFileSystem      fileSystem  = new FileSystem();
        ICakeDataService data        = new BridgeDataService();
        ICakeEnvironment environment = new CakeEnvironment(
            new CakePlatform(),
            new CakeRuntime(),
            log
            );
        IGlobber           globber       = new Globber(fileSystem, environment);
        ICakeArguments     arguments     = new BridgeArguments();
        ICakeConfiguration configuration = new BridgeConfiguration();
        IToolLocator       tools         = new ToolLocator(
            environment,
            new ToolRepository(environment),
            new ToolResolutionStrategy(
                fileSystem,
                environment,
                globber,
                configuration
                )
            );
        ICakeContext context = new CakeContext(
            fileSystem,
            environment,
            globber,
            log,
            arguments,
            new ProcessRunner(fileSystem, environment, log, tools, configuration),
            new WindowsRegistry(),
            tools,
            data,
            configuration
            );

        return(new BridgeScriptHost(
                   new CakeEngine(data, log),
                   context,
                   new DefaultExecutionStrategy(log),
                   new CakeReportPrinter(console, context),
                   arguments
                   ));
    }
Example #23
0
        /// <inheritdoc />
        protected override void RunTool()
        {
            FileSystem.CreateFile("TestFiles/Version1/Cake.BitDiffer.TestAssembly.dll");
            FileSystem.CreateFile("TestFiles/Version2/Cake.BitDiffer.TestAssembly.dll");
            if (string.IsNullOrWhiteSpace(Settings?.ResultOutputFile?.FullPath))
            {
                FileSystem.CreateFile("comparison.xml");
            }
            else
            {
                FileSystem.CreateFile(Settings.ResultOutputFile);
            }

            var toolLocator = new ToolLocator(Environment, new ToolRepository(Environment),
                                              new ToolResolutionStrategy(FileSystem, Environment, Globber, new FakeConfiguration()));
            var tool = new BitDifferRunner(FileSystem, Environment, ProcessRunner, toolLocator);

            tool.Run(Settings);
        }
        public FakeCakeContext()
        {
            testsDir = new DirectoryPath(System.IO.Path.Combine(System.IO.Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory), "..", "..", ".."));

            log = new FakeCakeLog();
            var fileSystem             = new FileSystem();
            var environment            = new CakeEnvironment(new CakePlatform(), new CakeRuntime(), log);
            var globber                = new Globber(fileSystem, environment);
            var args                   = new FakeCakeArguments();
            var processRunner          = new ProcessRunner(environment, log);
            var registry               = new WindowsRegistry();
            var toolRepo               = new ToolRepository(environment);
            var config                 = new Core.Configuration.CakeConfigurationProvider(fileSystem, environment).CreateConfiguration(testsDir, new Dictionary <string, string>());
            var toolResolutionStrategy = new ToolResolutionStrategy(fileSystem, environment, globber, config);
            var toolLocator            = new ToolLocator(environment, toolRepo, toolResolutionStrategy);

            context = new CakeContext(fileSystem, environment, globber, log, args, processRunner, registry, toolLocator);
            context.Environment.WorkingDirectory = testsDir;
        }
Example #25
0
 public FakeCakeContext ()
 {
     testsDir = new DirectoryPath (
         System.IO.Path.GetFullPath (AppDomain.CurrentDomain.BaseDirectory));
     
     var fileSystem = new FileSystem ();
     var environment = new CakeEnvironment (new CakePlatform (), new CakeRuntime ());
     var globber = new Globber (fileSystem, environment);
     log = new FakeLog ();
     var args = new FakeCakeArguments ();
     var processRunner = new ProcessRunner (environment, log);
     var registry = new WindowsRegistry ();
     var toolRepo = new ToolRepository (environment);
     var config = new Core.Configuration.CakeConfigurationProvider (fileSystem, environment).CreateConfiguration (testsDir, new Dictionary<string, string> ());
     var toolResolutionStrategy = new ToolResolutionStrategy (fileSystem, environment, globber, config);
     var toolLocator = new ToolLocator (environment, toolRepo, toolResolutionStrategy);
     context = new CakeContext (fileSystem, environment, globber, log, args, processRunner, registry, toolLocator);
     context.Environment.WorkingDirectory = testsDir;
 }
        public void TestMethod1()
        {
            var environment = Substitute.For <ICakeEnvironment>();

            environment.Platform.Returns(info =>
            {
                var platform = Substitute.For <ICakePlatform>();
                platform.Is64Bit.Returns(true);
                platform.Family.Returns(PlatformFamily.Windows);
                return(platform);
            });

            var fileSystem    = Substitute.For <IFileSystem>();
            var processRunner = Substitute.For <IProcessRunner>();
            var globber       = new Globber(fileSystem, environment);
            var configuration = Substitute.For <ICakeConfiguration>();

            var toolLocator = new ToolLocator(environment, new ToolRepository(environment), new ToolResolutionStrategy(fileSystem, environment, globber, configuration));
        }
Example #27
0
        public FakeCakeContext ()
        {
            testsDir = new DirectoryPath (
                System.IO.Path.GetDirectoryName (System.Reflection.Assembly.GetExecutingAssembly ().Location));

            var fileSystem = new FileSystem ();
            var environment = new CakeEnvironment ();
            var globber = new Globber (fileSystem, environment);
            log = new FakeLog ();
            var args = new FakeCakeArguments ();
            var processRunner = new ProcessRunner (environment, log);
            var registry = new WindowsRegistry ();
            var toolRepo = new ToolRepository (environment);
            var config = new Core.Configuration.CakeConfigurationProvider (fileSystem, environment).CreateConfiguration (new Dictionary<string, string> ());
            var toolResStrat = new ToolResolutionStrategy (fileSystem, environment, globber, config);
            var toolLocator = new ToolLocator (environment, toolRepo, toolResStrat);

            context = new CakeContext (fileSystem, environment, globber, log, args, processRunner, registry, toolLocator);
            context.Environment.WorkingDirectory = testsDir;
        }
        public FakeCakeContext()
        {
            _testsDir = new DirectoryPath(
                System.IO.Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory));

            var fileSystem = new FileSystem();

            _log = new FakeLog();
            var environment = new CakeEnvironment(new CakePlatform(), new CakeRuntime(), _log);
            var globber     = new Globber(fileSystem, environment);

            var args          = new FakeCakeArguments();
            var processRunner = new ProcessRunner(environment, _log);
            var registry      = new WindowsRegistry();

            var toolLocator = new ToolLocator(environment, new ToolRepository(environment), new ToolResolutionStrategy(fileSystem, environment, globber, new FakeConfiguration()));

            _context = new CakeContext(fileSystem, environment, globber, _log, args, processRunner, registry, toolLocator);
            _context.Environment.WorkingDirectory = _testsDir;
        }
Example #29
0
        public FakeCakeContext()
        {
            testsDir = new DirectoryPath(Path.GetFullPath(AppContext.BaseDirectory));

            var environment = FakeEnvironment.CreateUnixEnvironment(false);

            var fileSystem = new FakeFileSystem(environment);
            var globber    = new Globber(fileSystem, environment);

            log = new FakeLog();
            var args     = new FakeCakeArguments();
            var registry = new WindowsRegistry();

            var config        = new FakeConfiguration();
            var tools         = new ToolLocator(environment, new ToolRepository(environment), new ToolResolutionStrategy(fileSystem, environment, globber, config, log));
            var processRunner = new ProcessRunner(fileSystem, environment, log, tools, config);
            var data          = Substitute.For <ICakeDataService>();

            context = new CakeContext(fileSystem, environment, globber, log, args, processRunner, registry, tools, data, config);
            context.Environment.WorkingDirectory = testsDir;
        }
Example #30
0
        public FakeCakeContext()
        {
            testsDir = new DirectoryPath(
                System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));

            var fileSystem  = new FileSystem();
            var environment = new FakeEnvironment(PlatformFamily.OSX);
            var globber     = new Globber(fileSystem, environment);

            log = new FakeLog();
            var args                   = new FakeCakeArguments();
            var processRunner          = new ProcessRunner(environment, log);
            var registry               = new WindowsRegistry();
            var toolRepo               = new ToolRepository(environment);
            var config                 = new Core.Configuration.CakeConfigurationProvider(fileSystem, environment).CreateConfiguration(testsDir, new Dictionary <string, string>());
            var toolResolutionStrategy = new ToolResolutionStrategy(fileSystem, environment, globber, config);
            var toolLocator            = new ToolLocator(environment, toolRepo, toolResolutionStrategy);

            context = new CakeContext(fileSystem, environment, globber, log, args, processRunner, registry, toolLocator);
            context.Environment.WorkingDirectory = testsDir;
        }
Example #31
0
        /// <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;
        }
Example #33
0
            /// <inheritdoc />
            protected override async Task <ResultStatus> DoCommandOverride(ICommandContext commandContext)
            {
                // Get path to ffmpeg
                var ffmpeg = ToolLocator.LocateTool("ffmpeg.exe")?.ToWindowsPath() ?? throw new AssetException("Failed to compile a sound asset, ffmpeg was not found.");

                // Get absolute path of asset source on disk
                var assetDirectory = Parameters.Source.GetParent();
                var assetSource    = UPath.Combine(assetDirectory, Parameters.Source);

                // Execute ffmpeg to convert source to PCM and then encode with Celt
                var tempFile = Path.GetTempFileName();

                try
                {
                    var channels    = Parameters.Spatialized ? 1 : 2;
                    var commandLine = "  -hide_banner -loglevel error" +                                          // hide most log output
                                      $" -i \"{assetSource.ToWindowsPath()}\"" +                                  // input file
                                      $" -f f32le -acodec pcm_f32le -ac {channels} -ar {Parameters.SampleRate}" + // codec
                                      $" -map 0:{Parameters.Index}" +                                             // stream index
                                      $" -y \"{tempFile}\"";                                                      // output file (always overwrite)
                    var ret = await ShellHelper.RunProcessAndGetOutputAsync(ffmpeg, commandLine, commandContext.Logger);

                    if (ret != 0 || commandContext.Logger.HasErrors)
                    {
                        throw new AssetException($"Failed to compile a sound asset, ffmpeg failed to convert {assetSource}");
                    }

                    var encoder = new Celt(Parameters.SampleRate, CompressedSoundSource.SamplesPerFrame, channels, false);

                    var uncompressed = CompressedSoundSource.SamplesPerFrame * channels * sizeof(short); //compare with int16 for CD quality comparison.. but remember we are dealing with 32 bit floats for encoding!!
                    var target       = (int)Math.Floor(uncompressed / (float)Parameters.CompressionRatio);

                    var dataUrl  = Url + "_Data";
                    var newSound = new Sound
                    {
                        CompressedDataUrl = dataUrl,
                        Channels          = channels,
                        SampleRate        = Parameters.SampleRate,
                        StreamFromDisk    = Parameters.StreamFromDisk,
                        Spatialized       = Parameters.Spatialized,
                    };

                    //make sure we don't compress celt data
                    commandContext.AddTag(new ObjectUrl(UrlType.Content, dataUrl), Builder.DoNotCompressTag);

                    var delay = encoder.GetDecoderSampleDelay();

                    var frameSize = CompressedSoundSource.SamplesPerFrame * channels;
                    using (var reader = new BinaryReader(new FileStream(tempFile, FileMode.Open, FileAccess.Read)))
                        using (var outputStream = MicrothreadLocalDatabases.DatabaseFileProvider.OpenStream(dataUrl, VirtualFileMode.Create, VirtualFileAccess.Write, VirtualFileShare.Read, StreamFlags.Seekable))
                        {
                            var writer = new BinarySerializationWriter(outputStream);

                            var outputBuffer = new byte[target];
                            var buffer       = new float[frameSize];
                            var count        = 0;
                            var padding      = sizeof(float) * channels * delay;
                            var length       = reader.BaseStream.Length; // Cache the length, because this getter is expensive to use
                            for (var position = 0; position < length + padding; position += sizeof(float))
                            {
                                if (count == frameSize) //flush
                                {
                                    var len = encoder.Encode(buffer, outputBuffer);
                                    writer.Write((short)len);
                                    outputStream.Write(outputBuffer, 0, len);

                                    newSound.Samples += count / channels;
                                    newSound.NumberOfPackets++;
                                    newSound.MaxPacketLength = Math.Max(newSound.MaxPacketLength, len);

                                    count = 0;
                                    Array.Clear(buffer, 0, frameSize);
                                }

                                // Pad with 0 once we reach end of stream (this is needed because of encoding delay)
                                buffer[count++] = (position < length)
                                    ? reader.ReadSingle()
                                    : 0.0f;
                            }

                            if (count > 0) //flush
                            {
                                var len = encoder.Encode(buffer, outputBuffer);
                                writer.Write((short)len);
                                outputStream.Write(outputBuffer, 0, len);

                                newSound.Samples += count / channels;
                                newSound.NumberOfPackets++;
                                newSound.MaxPacketLength = Math.Max(newSound.MaxPacketLength, len);
                            }
                        }

                    // Samples is the real sound sample count, remove the delay at the end
                    newSound.Samples -= delay;

                    var assetManager = new ContentManager(MicrothreadLocalDatabases.ProviderService);
                    assetManager.Save(Url, newSound);

                    return(ResultStatus.Successful);
                }
                finally
                {
                    File.Delete(tempFile);
                }
            }