Example #1
0
        public void Analyze(FilePath path)
        {
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            // Get the absolute path to the script and make
            // sure that it exists.
            path = path.IsRelative ? path.MakeAbsolute(_environment) : path;
            if (!_fileSystem.Exist(path))
            {
                const string format  = "Could not find script '{0}'.";
                var          message = string.Format(CultureInfo.InvariantCulture, format, path.FullPath);
                throw new CakeException(message);
            }

            if (_processedScripts.Contains(path))
            {
                _log.Debug("Script '{0}' has already been processed.", path.FullPath);
                return;
            }
            _processedScripts.Add(path);

            // Set as the current script.
            Push(path);

            // Analyze the script.
            _callback(this);

            // Pop the current script.
            Pop();
        }
Example #2
0
        private FilePath LookInPath(string tool)
        {
            lock (_lock)
            {
                if (_path == null)
                {
                    _path = GetPathDirectories();
                }

                foreach (var pathDir in _path)
                {
                    var file = pathDir.CombineWithFilePath(tool);
                    try
                    {
                        if (_fileSystem.Exist(file))
                        {
                            return(file.MakeAbsolute(_environment));
                        }
                    }
                    catch
                    {
                    }
                }

                return(null);
            }
        }
 /// <summary>
 /// Validates settings
 /// </summary>
 /// <param name="settings">the settings class</param>
 /// <exception cref="FileNotFoundException">when gulp file does not exist</exception>
 protected virtual void ValidateSettings(TSettings settings = null)
 {
     if (settings?.GulpFile != null && !_fileSystem.Exist(settings.GulpFile))
     {
         throw new FileNotFoundException("gulpfile not found", settings.GulpFile.FullPath);
     }
 }
        private DirectoryPath GetGlobalPrefix()
        {
            try
            {
                var env = Environment.GetEnvironmentVariable("npm_config_prefix");
                if (!string.IsNullOrWhiteSpace(env))
                {
                    return(new DirectoryPath(env));
                }

                if (_fileSystem.Exist(GetNpmConfigPath()))
                {
                    var config = _fileSystem.GetFile(GetNpmConfigPath()).ReadLines(System.Text.Encoding.UTF8);
                    var lines  = config as IList <string> ?? config.ToList();
                    if (lines.Any(l => l.StartsWith("prefix=")))
                    {
                        return(lines.First(l => l.StartsWith("prefix=")).Split('=').Last());
                    }
                }

                return(GetDefaultPath());
            }
            catch
            {
                // time for some reasonable defaults
                return(GetDefaultPath());
            }
        }
Example #5
0
        private static DirectoryPath GetVisualStudio2017Path(IFileSystem fileSystem, ICakeEnvironment environment,
                                                             MSBuildPlatform buildPlatform)
        {
            var vsEditions = new[]
            {
                "Enterprise",
                "Professional",
                "Community",
                "BuildTools"
            };

            var visualStudio2017Path = environment.GetSpecialPath(SpecialPath.ProgramFilesX86);

            foreach (var edition in vsEditions)
            {
                // Get the bin path.
                var binPath = visualStudio2017Path.Combine(string.Concat("Microsoft Visual Studio/2017/", edition, "/MSBuild/15.0/Bin"));
                if (fileSystem.Exist(binPath))
                {
                    if (buildPlatform == MSBuildPlatform.Automatic)
                    {
                        if (environment.Platform.Is64Bit)
                        {
                            binPath = binPath.Combine("amd64");
                        }
                    }
                    if (buildPlatform == MSBuildPlatform.x64)
                    {
                        binPath = binPath.Combine("amd64");
                    }
                    return(binPath);
                }
            }
            return(visualStudio2017Path.Combine("Microsoft Visual Studio/2017/Professional/MSBuild/15.0/Bin"));
        }
Example #6
0
        protected override Assembly Load(AssemblyName assemblyName)
        {
            // Exists in default dependency context?
            var context = DependencyContext.Default;
            var library = context.CompileLibraries.FirstOrDefault(d => d.Name.Contains(assemblyName.Name));

            if (library != null)
            {
                // Load the assembly in the default assembly load context.
                return(Assembly.Load(new AssemblyName(library.Name)));
            }

            // Does the file exist on disk?
            var file = new FilePath(assemblyName.Name).ChangeExtension(".dll");
            var path = _root.CombineWithFilePath(file);

            if (_fileSystem.Exist(path))
            {
                // Try loading it in this context.
                return(LoadFromAssemblyPath(path.FullPath));
            }

            // Load the assembly in the default assembly load context.
            return(Assembly.Load(assemblyName));
        }
Example #7
0
        /// <summary>
        /// Creates a NuGet package from the specified settings.
        /// </summary>
        /// <param name="settings">The settings.</param>
        public void Pack(NuGetPackSettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }
            if (settings.OutputDirectory == null || !_fileSystem.Exist(settings.OutputDirectory))
            {
                throw new CakeException("Required setting OutputDirectory not specified or doesn't exists.");
            }
            if (string.IsNullOrWhiteSpace(settings.Id))
            {
                throw new CakeException("Required setting Id not specified.");
            }
            if (string.IsNullOrWhiteSpace(settings.Version))
            {
                throw new CakeException("Required setting Version not specified.");
            }
            if (settings.Authors == null || settings.Authors.Count == 0)
            {
                throw new CakeException("Required setting Authors not specified.");
            }
            if (string.IsNullOrWhiteSpace(settings.Description))
            {
                throw new CakeException("Required setting Description not specified.");
            }
            if ((settings.Files == null || settings.Files.Count == 0) && (settings.Dependencies == null || settings.Dependencies.Count == 0))
            {
                throw new CakeException("Required setting Files not specified.");
            }

            Pack(settings, () => _processor.Process(settings));
        }
Example #8
0
        public static FilePath GetMSBuildPath(IFileSystem fileSystem, ICakeEnvironment environment, MSBuildToolVersion version, MSBuildPlatform buildPlatform)
        {
            if (environment.Platform.Family == PlatformFamily.OSX)
            {
                var macMSBuildPath = new FilePath("/Library/Frameworks/Mono.framework/Versions/Current/Commands/msbuild");

                if (fileSystem.Exist(macMSBuildPath))
                {
                    return(macMSBuildPath);
                }

                throw new CakeException("Could not resolve MSBuild.");
            }

            var binPath = version == MSBuildToolVersion.Default
                ? GetHighestAvailableMSBuildVersion(fileSystem, environment, buildPlatform)
                : GetMSBuildPath(fileSystem, environment, (MSBuildVersion)version, buildPlatform);

            if (binPath == null)
            {
                throw new CakeException("Could not resolve MSBuild.");
            }

            // Get the MSBuild path.
            return(binPath.CombineWithFilePath("MSBuild.exe"));
        }
Example #9
0
        private static Tuple <DirectoryPath, FilePath> GetNuGetConfigPath(ICakeEnvironment environment, ICakeConfiguration config, IFileSystem fileSystem)
        {
            DirectoryPath rootPath;
            FilePath      filePath;

            var nugetConfigFile = config.GetValue(Constants.NuGet.ConfigFile);

            if (!string.IsNullOrEmpty(nugetConfigFile))
            {
                var configFilePath = new FilePath(nugetConfigFile).MakeAbsolute(environment);

                if (!fileSystem.Exist(configFilePath))
                {
                    throw new System.IO.FileNotFoundException("NuGet Config file not found.", configFilePath.FullPath);
                }

                rootPath = configFilePath.GetDirectory();
                filePath = configFilePath.GetFilename();
            }
            else
            {
                rootPath = GetToolPath(environment, config);
                filePath = null;
            }

            return(Tuple.Create(rootPath, filePath));
        }
Example #10
0
        private FilePath LookInPath(string tool)
        {
            lock (_lock)
            {
                if (_path == null)
                {
                    _path = GetPathDirectories();
                }

                foreach (var pathDir in _path)
                {
                    var file = pathDir.CombineWithFilePath(tool);
                    try
                    {
                        if (_fileSystem.Exist(file))
                        {
                            _log.Debug($"Resolved tool to path {file}");
                            return(file.MakeAbsolute(_environment));
                        }
                    }
                    catch
                    {
                    }
                }

                var allPaths = string.Join(",", _path);
                _log.Debug($"Could not resolve path for tool \"{tool}\" using these directories: {allPaths}");
                return(null);
            }
        }
Example #11
0
        protected override IReadOnlyCollection <IFile> GetAddinAssemblies(DirectoryPath packageDirectory)
        {
            if (packageDirectory == null)
            {
                throw new ArgumentNullException("packageDirectory");
            }
            if (packageDirectory.IsRelative)
            {
                throw new CakeException("Package directory (" + packageDirectory.FullPath + ") must be an absolute path.");
            }
            if (!_fileSystem.Exist(packageDirectory))
            {
                return(new List <IFile>());
            }

            var packageAssemblies = GetAllPackageAssemblies(packageDirectory);

            if (!packageAssemblies.Any())
            {
                _log.Warning("Unable to locate any assemblies under {0}", packageDirectory.FullPath);
            }

            var compatibleAssemblyPaths = FilterCompatibleAssemblies(packageAssemblies, packageDirectory);
            var resolvedAssemblyFiles   = ResolveAssemblyFiles(compatibleAssemblyPaths);

            return(resolvedAssemblyFiles);
        }
        public override bool Process(IScriptAnalyzerContext context, string line, out string replacement)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            replacement = null;

            var tokens = Split(line);

            if (tokens.Length <= 0)
            {
                return(false);
            }

            if (!tokens[0].Equals("#r", StringComparison.Ordinal) &&
                !tokens[0].Equals("#reference", StringComparison.Ordinal))
            {
                return(false);
            }

            var referencePath = new FilePath(tokens[1].UnQuote());

            var directoryPath         = GetAbsoluteDirectory(context.Script.Path);
            var absoluteReferencePath = referencePath.MakeAbsolute(directoryPath);

            context.Script.References.Add(_fileSystem.Exist(absoluteReferencePath)
                ? absoluteReferencePath.FullPath : referencePath.FullPath);

            return(true);
        }
Example #13
0
 public TemplateFileReader(IFileSystem fs, FilePath templateFilePath)
 {
     if (!fs.Exist(templateFilePath))
     {
         throw new FileNotFoundException("Could not find requested template file", templateFilePath.FullPath);
     }
     _file = fs.GetFile(templateFilePath);
 }
Example #14
0
        private IReadOnlyCollection <IFile> GetAddinAssemblies(DirectoryPath path, PackageReference package)
        {
            if (!_fileSystem.Exist(path))
            {
                return(new List <IFile>());
            }

            // Get current framework.
            var provider = DefaultFrameworkNameProvider.Instance;
            var current  = NuGetFramework.Parse(_environment.Runtime.BuiltFramework.FullName, provider);

            // Get all ref assemblies.
            var refAssemblies = _globber.GetFiles(path.FullPath + "/ref/**/*.dll");

            // Get all candidate files.
            var pathComparer = PathComparer.Default;
            var assemblies   = GetFiles(path, package, new[] { path.FullPath + "/**/*.dll" })
                               .Where(file => !"Cake.Core.dll".Equals(file.Path.GetFilename().FullPath, StringComparison.OrdinalIgnoreCase) &&
                                      IsCLRAssembly(file) &&
                                      !refAssemblies.Contains(file.Path, pathComparer))
                               .ToList();

            // Iterate all found files.
            var comparer = new NuGetFrameworkFullComparer();
            var mapping  = new Dictionary <NuGetFramework, List <FilePath> >(comparer);

            foreach (var assembly in assemblies)
            {
                // Get relative path.
                var relative  = path.GetRelativePath(assembly.Path);
                var framework = ParseFromDirectoryPath(current, relative.GetDirectory());
                if (!mapping.ContainsKey(framework))
                {
                    mapping.Add(framework, new List <FilePath>());
                }
                mapping[framework].Add(assembly.Path);
            }

            // Reduce found frameworks to the closest one.
            var reducer = new FrameworkReducer();
            var nearest = reducer.GetNearest(current, mapping.Keys);

            if (nearest == null || !mapping.ContainsKey(nearest))
            {
                return(new List <IFile>());
            }

            if (nearest == NuGetFramework.AnyFramework)
            {
                var framework = _environment.Runtime.BuiltFramework;
                _log.Warning("Could not find any assemblies compatible with {0} in NuGet package {1}. " +
                             "Falling back to using root folder of NuGet package.", framework.FullName, package.Package);
            }

            // Return the result.
            return(mapping[nearest].Select(p => _fileSystem.GetFile(p)).ToList());
        }
Example #15
0
        public static FilePath GetMSBuildPath(IFileSystem fileSystem, ICakeEnvironment environment, MSBuildPlatform buildPlatform, MSBuildSettings settings)
        {
            if (environment.Platform.Family == PlatformFamily.OSX)
            {
                var macMSBuildPath = new FilePath("/Library/Frameworks/Mono.framework/Versions/Current/Commands/msbuild");

                if (fileSystem.Exist(macMSBuildPath))
                {
                    return(macMSBuildPath);
                }

                var brewMSBuildPath = new FilePath("/usr/local/bin/msbuild");

                if (fileSystem.Exist(brewMSBuildPath))
                {
                    return(brewMSBuildPath);
                }

                throw new CakeException("Could not resolve MSBuild.");
            }
            else if (environment.Platform.Family == PlatformFamily.Linux)
            {
                var linuxMSBuildPath = new FilePath("/usr/bin/msbuild");

                if (fileSystem.Exist(linuxMSBuildPath))
                {
                    return(linuxMSBuildPath);
                }

                throw new CakeException("Could not resolve MSBuild.");
            }

            var binPath = settings.ToolVersion == MSBuildToolVersion.Default
                ? GetHighestAvailableMSBuildVersion(fileSystem, environment, buildPlatform, settings.AllowPreviewVersion)
                : GetMSBuildPath(fileSystem, environment, (MSBuildVersion)settings.ToolVersion, buildPlatform, settings.CustomVersion, settings.AllowPreviewVersion);

            if (binPath == null)
            {
                throw new CakeException("Could not resolve MSBuild.");
            }

            // Get the MSBuild path.
            return(binPath.CombineWithFilePath("MSBuild.exe"));
        }
        /// <summary>
        /// Creates a configuration from the provided arguments.
        /// </summary>
        /// <param name="path">The directory to look for the configuration file.</param>
        /// <param name="baseConfiguration">The initial base configuration.</param>
        /// <param name="arguments">The arguments.</param>
        /// <returns>The created configuration.</returns>
        public ICakeConfiguration CreateConfiguration(DirectoryPath path, IEnumerable <KeyValuePair <string, string> > baseConfiguration, IDictionary <string, string> arguments)
        {
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            if (baseConfiguration == null)
            {
                throw new ArgumentNullException(nameof(baseConfiguration));
            }

            if (arguments == null)
            {
                throw new ArgumentNullException(nameof(arguments));
            }

            var result = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

            // Add base configuration.
            foreach (var kv in baseConfiguration)
            {
                result[KeyNormalizer.Normalize(kv.Key)] = kv.Value;
            }

            // Get all environment variables.
            foreach (var variable in _environment.GetEnvironmentVariables())
            {
                if (variable.Key.StartsWith("CAKE_", StringComparison.OrdinalIgnoreCase))
                {
                    var key = variable.Key.Substring(5);
                    result[KeyNormalizer.Normalize(key)] = variable.Value;
                }
            }

            // Parse the configuration file.
            var configurationPath = path.CombineWithFilePath("cake.config").MakeAbsolute(_environment);

            if (_fileSystem.Exist(configurationPath))
            {
                var parser        = new ConfigurationParser(_fileSystem, _environment);
                var configuration = parser.Read(configurationPath);
                foreach (var key in configuration.Keys)
                {
                    result[KeyNormalizer.Normalize(key)] = configuration[key];
                }
            }

            // Add all arguments.
            foreach (var key in arguments.Keys)
            {
                result[KeyNormalizer.Normalize(key)] = arguments[key];
            }

            return(new CakeConfiguration(result));
        }
Example #17
0
        private AppxManifestAsset ParseImage(DirectoryPath root, Func <string> func)
        {
            var resource = func();

            if (string.IsNullOrWhiteSpace(resource))
            {
                return(null);
            }

            var file = root.CombineWithFilePath(new FilePath(resource));

            if (_fileSystem.Exist(file))
            {
                return(new AppxManifestAsset
                {
                    Name = resource,
                    Path = file
                });
            }

            var stack = new Stack <string>(new[] { "400", "300", "200", "150", "125", "100" });

            while (stack.Count > 0)
            {
                var current = stack.Pop();

                var scale = file.RemoveExtension()
                            .AppendExtension(new FileExtension($"scale-{current}"))
                            .AppendExtension(file.GetExtension());

                if (_fileSystem.Exist(scale))
                {
                    return(new AppxManifestAsset
                    {
                        Name = resource,
                        Path = scale
                    });
                }
            }

            return(null);
        }
Example #18
0
            public void ShouldThrowIfProcessHasANonZeroExitCode(
                [Frozen] IProcess process,
                [Frozen] IFileSystem fileSystem, ChutzpahRunner sut)
            {
                fileSystem.Exist(Arg.Any <FilePath>()).Returns(true);
                process.GetExitCode().Returns(3);

                sut.Invoking(s => s.Run())
                .ShouldThrow <CakeException>()
                .WithMessage("Chutzpah: Process returned an error (exit code 3).");
            }
Example #19
0
        /// <summary>
        /// Gets alternative file paths which the tool may exist in
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <returns>The default tool path.</returns>
        protected override IEnumerable <FilePath> GetAlternativeToolPaths(MSTestSettings settings)
        {
            foreach (var version in new[] { "14.0", "12.0", "11.0", "10.0" })
            {
                var path = GetToolPath(version);
                if (_fileSystem.Exist(path))
                {
                    yield return(path);
                }
            }

            foreach (var environmentVariable in new[] { "VS140COMNTOOLS", "VS130COMNTOOLS", "VS120COMNTOOLS", "VS110COMNTOOLS", "VS100COMNTOOLS" })
            {
                var path = GetCommonToolPath(environmentVariable);
                if (path != null && _fileSystem.Exist(path))
                {
                    yield return(path);
                }
            }
        }
Example #20
0
        /// <summary>
        /// Gets alternative file paths which the tool may exist in.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <returns>The default tool path.</returns>
        protected override IEnumerable <FilePath> GetAlternativeToolPaths(VSTestSettings settings)
        {
            foreach (var yearAndEdition in new[] { "2019/Enterprise", "2019/Professional", "2019/Community", "2017/Enterprise", "2017/Professional", "2017/Community" })
            {
                var path = GetYearAndEditionToolPath(yearAndEdition);
                if (_fileSystem.Exist(path))
                {
                    yield return(path);
                }
            }

            foreach (var version in new[] { "15.0", "14.0", "12.0", "11.0" })
            {
                var path = GetVersionNumberToolPath(version);
                if (_fileSystem.Exist(path))
                {
                    yield return(path);
                }
            }
        }
Example #21
0
 /// <summary>
 /// Gets alternative file paths which the tool may exist in
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <returns>The default tool path.</returns>
 protected override IEnumerable <FilePath> GetAlternativeToolPaths(VSTestSettings settings)
 {
     foreach (var version in new[] { "15.0", "14.0", "12.0", "11.0" })
     {
         var path = GetToolPath(version);
         if (_fileSystem.Exist(path))
         {
             yield return(path);
         }
     }
 }
Example #22
0
        private FilePath GetFromDisc()
        {
            var programFilesPath = _environment.GetSpecialPath(SpecialPath.ProgramFilesX86);

            var files = new List <FilePath>();

            if (_environment.Platform.Is64Bit)
            {
                files.Add(programFilesPath.Combine(@"Windows Kits\10\bin\x64").CombineWithFilePath("makeappx.exe"));
                files.Add(programFilesPath.Combine(@"Windows Kits\8.1\bin\x64").CombineWithFilePath("makeappx.exe"));
                files.Add(programFilesPath.Combine(@"Windows Kits\8.0\bin\x64").CombineWithFilePath("makeappx.exe"));
            }
            else
            {
                files.Add(programFilesPath.Combine(@"Windows Kits\10\bin\x86").CombineWithFilePath("makeappx.exe"));
                files.Add(programFilesPath.Combine(@"Windows Kits\8.1\bin\x86").CombineWithFilePath("makeappx.exe"));
                files.Add(programFilesPath.Combine(@"Windows Kits\8.0\bin\x86").CombineWithFilePath("makeappx.exe"));
            }
            return(files.FirstOrDefault(file => _fileSystem.Exist(file)));
        }
        public void ShouldSetSystraySwitch([Frozen] IAdvProcessRunner runner,
             IFileSystem fileSystem, AppPathBasedIISExpressRunner sut)
        {
            var settings = new AppPathBasedIISExpressSettings(@"c:\MyApp") { EnableSystemTray = false };
            fileSystem.Exist(settings.AppPath).Returns(true);
            sut.StartServer(settings);

            runner.Received()
                .Start(Arg.Any<FilePath>(),
                    Arg.Is<AdvProcessSettings>(p => p.Arguments.Render() == "/path:\"c:/MyApp\" /systray:false"));
        }
Example #24
0
        /// <summary>
        /// Runs the tool using a custom tool path and the specified settings.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="arguments">The arguments.</param>
        /// <param name="toolPath">The tool path to use.</param>
        protected void Run(T settings, ToolArgumentBuilder arguments, FilePath toolPath)
        {
            if (arguments == null)
            {
                throw new ArgumentNullException("arguments");
            }

            // Get the tool name.
            var toolName = GetToolName();

            // Get the tool path.
            toolPath = GetToolPath(settings, toolPath);
            if (toolPath == null || !_fileSystem.Exist(toolPath))
            {
                const string message = "{0}: Could not locate executable.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Get the working directory.
            var workingDirectory = GetWorkingDirectory(settings);

            if (workingDirectory == null)
            {
                const string message = "{0}: Could not resolve working directory.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Create the process start info.
            var info = new ProcessStartInfo(toolPath.FullPath)
            {
                WorkingDirectory = workingDirectory.MakeAbsolute(_environment).FullPath,
                Arguments        = arguments.Render(),
                UseShellExecute  = false
            };

            // Run the process.
            var process = _processRunner.Start(info);

            if (process == null)
            {
                const string message = "{0}: Process was not started.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Wait for the process to exit.
            process.WaitForExit();

            // Did an error occur?
            if (process.GetExitCode() != 0)
            {
                const string message = "{0}: Process returned an error.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }
        }
Example #25
0
        public int BuildPage(CompilerConfiguration configuration, Content root, Content parent, Content current)
        {
            var count = 1;

            // Create the view model.
            var model = new LayoutViewModel(parent, current.Title);

            model.CurrentId = current.Id;
            model.Current   = current;
            model.Root      = root;

            // Render the master page with the model.
            var html = _engine.Render(configuration, "templates/layout.cshtml", model);

            // Save the result to disc.
            var outputFilePath = current.Id == "index" && current.Parent == root
                ? new FilePath("index.html")
                : new FilePath(string.Concat(current.GetLink(), "/index.html").TrimStart('/'));

            outputFilePath = outputFilePath.MakeAbsolute(configuration.OutputPath);
            var outputPath = outputFilePath.GetDirectory();

            if (!_fileSystem.Exist(outputPath))
            {
                _fileSystem.GetDirectory(outputPath).Create();
            }

            using (var stream = _fileSystem.GetFile(outputFilePath).OpenWrite())
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(html);
                }

            // Process child pages recursivly.
            foreach (var child in current.Children)
            {
                count += BuildPage(configuration, root, current, child);
            }

            return(count);
        }
Example #26
0
 /// <summary>
 /// Gets the default tool path.
 /// </summary>
 /// <returns>The default tool path.</returns>
 protected override FilePath GetDefaultToolPath(MSTestSettings settings)
 {
     foreach (var version in new[] { "12.0", "11.0", "10.0" })
     {
         var path = GetToolPath(version);
         if (_fileSystem.Exist(path))
         {
             return(path);
         }
     }
     return(null);
 }
Example #27
0
        private IEnumerable <Path> GetPath(string rootPath)
        {
            // Is this an existing file?
            var rootFilePath = new FilePath(rootPath);

            if (_fileSystem.Exist(rootFilePath))
            {
                return(new Path[] { rootFilePath });
            }

            // Is this an existing directory?
            var rootDirectoryPath = new DirectoryPath(rootPath);

            if (_fileSystem.Exist(rootDirectoryPath))
            {
                return(new Path[] { rootDirectoryPath });
            }

            // Neither an existing file or directory.
            return(new Path[] { });
        }
Example #28
0
 /// <summary>
 /// Gets the working directory from the NpmRunnerSettings
 ///             Defaults to the currently set working directory.
 /// </summary>
 /// <param name="settings">The settings.</param>
 /// <returns>
 /// The working directory for the tool.
 /// </returns>
 protected override DirectoryPath GetWorkingDirectory(NpmRunnerSettings settings)
 {
     if (_workingDirectoryPath == null)
     {
         return(base.GetWorkingDirectory(settings));
     }
     if (!_fileSystem.Exist(_workingDirectoryPath))
     {
         throw new DirectoryNotFoundException($"Working directory path not found [{_workingDirectoryPath.FullPath}]");
     }
     return(_workingDirectoryPath);
 }
Example #29
0
        /// <summary>
        /// Resolves the path to the dotfuscaotr  tool (dotfuscaotr.exe)
        /// </summary>
        /// <returns>The path to dotfuscaotr.exe</returns>
        public FilePath GetToolPath()
        {
            if (_exePath != null)
            {
                return(_exePath);
            }

            // Get the path to program files.
            var programFilesPath = _environment.GetSpecialPath(SpecialPath.ProgramFilesX86);

            _exePath = programFilesPath.Combine(@"PreEmptive Solutions\Dotfuscator Professional Edition 4.9").CombineWithFilePath("dotfuscator.exe");

            if (_fileSystem.Exist(_exePath))
            {
                return(_exePath);
            }
            else
            {
                throw new CakeException("Failed to find dotfuscator.exe.");
            }
        }
Example #30
0
        private DirectoryPath GetWorkingDirectory()
        {
            var workingDirectory = _options.WorkingDirectory ?? _workingDirectory?.Path ?? ".";

            workingDirectory = workingDirectory.MakeAbsolute(_environment);

            if (!_fileSystem.Exist(workingDirectory))
            {
                throw new FrostingException($"The working directory '{workingDirectory.FullPath}' does not exist.");
            }

            return(workingDirectory);
        }
Example #31
0
            public void ShouldBuildEmptyCommand([Frozen] IProcess process,
                                                [Frozen] IProcessRunner processRunner,
                                                [Frozen] IFileSystem fileSystem, ChutzpahRunner sut)
            {
                process.GetExitCode().Returns(0);
                fileSystem.Exist(Arg.Any <FilePath>()).Returns(true);

                sut.Run();

                processRunner.Received(1)
                .Start(Arg.Any <FilePath>(),
                       Arg.Is <ProcessSettings>(p => p.Arguments.Render() == string.Empty));
            }
        public void ShouldThrowIfAppPathDoesNotExist([Frozen] IAdvProcessRunner runner,
            IFileSystem fileSystem,
            AppPathBasedIISExpressRunner sut)
        {
            var settings = new AppPathBasedIISExpressSettings(@"c:\MyApp");

            fileSystem.Exist(settings.AppPath).Returns(false);

            sut.Invoking(s => s.StartServer(settings)).ShouldThrow<CakeException>();

            runner.DidNotReceiveWithAnyArgs()
                .Start(null, null);
        }
        public void ShouldSetAppPathSwitchFromAbsolutePath(
            [Frozen] ICakeEnvironment environment,
            IFileSystem fileSystem, [Frozen] IAdvProcessRunner runner,
            AppPathBasedIISExpressRunner sut)
        {
            var settings = new AppPathBasedIISExpressSettings(@"c:\MyApp");
            
            fileSystem.Exist(Arg.Is(settings.AppPath)).Returns(true);

            sut.StartServer(settings);

            runner.Received()
                .Start(Arg.Any<FilePath>(),
                    Arg.Is<AdvProcessSettings>(
                        p =>
                            p.Arguments.Render() ==
                            "/path:\"c:/MyApp\""));
        }
        public void ShouldSetAppPathSwitchFromRelativeFilePath(
            [Frozen] ICakeEnvironment environment,
            IFileSystem fileSystem, [Frozen] IAdvProcessRunner runner,
            AppPathBasedIISExpressRunner sut)
        {
            environment.WorkingDirectory.Returns("c:/build/MyWorkingDirectory");

            var settings = new AppPathBasedIISExpressSettings(@"..\MyApp");

            fileSystem.Exist(Arg.Is<DirectoryPath>(x => x.FullPath == "c:/build/MyApp")).Returns(true);

            sut.StartServer(settings);

            runner.Received()
                .Start(Arg.Any<FilePath>(),
                    Arg.Is<AdvProcessSettings>(
                        p =>
                            p.Arguments.Render() ==
                            "/path:\"c:/build/MyApp\""));
        }
        public void ShouldThrowWhenIISExpressProcessWritesToErrorStream([Frozen] IAdvProcess process,
            IFileSystem fileSystem,
            [Frozen] IAdvProcessRunner processRunner, [Frozen] IRegistry registry,
            AppPathBasedIISExpressRunner sut)
        {
            processRunner.Start(Arg.Any<FilePath>(), Arg.Any<AdvProcessSettings>()).Returns(process);

            var settings = new AppPathBasedIISExpressSettings(@"c:\MyApp");
            fileSystem.Exist(settings.AppPath).Returns(true);

            sut.StartServer(settings);

            process.Invoking(
                           p =>
                               p.ErrorDataReceived +=
                                   Raise.EventWith(
                                       new ProcessOutputReceivedEventArgs("some dummy error data received")))
                           .ShouldThrow<CakeException>()
                           .WithMessage(
                               "IIS Express returned the following error message: 'some dummy error data received'");
        }
        public void ShouldSetClrVersionSwitch([Frozen] IAdvProcessRunner runner,
             IFileSystem fileSystem, AppPathBasedIISExpressRunner sut)
        {
            var settings = new AppPathBasedIISExpressSettings(@"c:\MyApp") { ClrVersion = ClrVersion.Version20 };
            fileSystem.Exist(settings.AppPath).Returns(true);

            sut.StartServer(settings);

            runner.Received()
                .Start(Arg.Any<FilePath>(),
                    Arg.Is<AdvProcessSettings>(
                        p => p.Arguments.Render() == "/path:\"c:/MyApp\" /clr:v2.0"));
        }
        public void ShouldWaitUntilIISExpressServerIsStarted([Frozen] ICakeLog log,
            [Frozen] IAdvProcess process, IFileSystem fileSystem,
            [Frozen] IAdvProcessRunner processRunner, [Frozen] IRegistry registry,
            AppPathBasedIISExpressRunner sut)
        {
            var simulatedStandardOutput = new[]
            {"1", "2", "3", "4", "IIS Express is running.", "5"};

            // hooking into the logging call that occurs previous to waiting is the only place I could 
            // think of to send in simulated output to signal IIS Express has started.
            log.When(
                l =>
                    l.Write(Arg.Any<Verbosity>(), Arg.Any<LogLevel>(),
                        "Waiting for IIS Express to start (timeout: {0}ms)", Arg.Any<object[]>()))
                .Do(ci =>
                {
                    foreach (var s in simulatedStandardOutput)
                    {
                        process.OutputDataReceived += Raise.EventWith(process,
                            new ProcessOutputReceivedEventArgs(s));
                    }
                });

            processRunner.Start(Arg.Any<FilePath>(), Arg.Any<AdvProcessSettings>())
                .Returns(ci => process);

            var settings = new AppPathBasedIISExpressSettings(@"c:\MyApp") {WaitForStartup = 1000};
            fileSystem.Exist(settings.AppPath).Returns(true);

            sut.StartServer(settings);

            log.Received()
                .Write(Verbosity.Normal, LogLevel.Information,
                    Arg.Is<string>(s => s.StartsWith("IIS Express is running")), Arg.Any<object[]>());
        }
        public void ShouldThrowWhenConfigFileDoesNotExist([Frozen] ICakeEnvironment environment,
            IFileSystem fileSystem, [Frozen] IAdvProcessRunner runner,
            ConfigBasedIISExpressRunner sut)
        {
            environment.WorkingDirectory.Returns("c:/MyWorkingDirectory");

            var settings = new ConfigBasedIISExpressSettings
            {
                ConfigFilePath =
                    FilePath.FromString(@"c:\someOtherDirectory\applicationhost.config")
            };

            fileSystem.Exist(
                Arg.Is<FilePath>(
                    f =>
                        f.FullPath.Equals(settings.ConfigFilePath.FullPath,
                            StringComparison.OrdinalIgnoreCase))).Returns(false);

            sut.Invoking(s => s.StartServer(settings)).ShouldThrow<CakeException>();

            runner.DidNotReceiveWithAnyArgs().Start(null, null);
        }
        public void ShouldSetConfigFileSwitchFromRelativeFilePath(
            [Frozen] ICakeEnvironment environment,
            IFileSystem fileSystem, [Frozen] IAdvProcessRunner runner,
            ConfigBasedIISExpressRunner sut)
        {
            environment.WorkingDirectory.Returns("c:/MyWorkingDirectory");
            var settings = new ConfigBasedIISExpressSettings
            {
                ConfigFilePath = FilePath.FromString("applicationhost.config")
            };

            fileSystem.Exist(
                Arg.Is<FilePath>(
                    f =>
                        f.FullPath.Equals("c:/MyWorkingDirectory/applicationhost.config",
                            StringComparison.OrdinalIgnoreCase))).Returns(true);

            sut.StartServer(settings);

            runner.Received()
                .Start(Arg.Any<FilePath>(),
                    Arg.Is<AdvProcessSettings>(
                        p =>
                            p.Arguments.Render() ==
                            "/config:\"c:/MyWorkingDirectory/applicationhost.config\""));
        }