Example #1
0
        public IReadOnlyCollection <IFile> GetFiles(DirectoryPath directoryPath, PackageReference packageReference, PackageType type)
        {
            var files = new List <IFile>();

            foreach (var installedPackage in _installedPackages)
            {
                if (_blackListedPackages.Contains(installedPackage.Id))
                {
                    _log.Warning("Package {0} depends on package {1}. Will not load this dependency...",
                                 packageReference.Package, installedPackage.ToString());
                    continue;
                }

                var installPath = new DirectoryPath(_pathResolver.GetInstallPath(installedPackage));

                if (!_fileSystem.Exist(installPath))
                {
                    _log.Warning("Package {0} is not installed.", installedPackage.Id);
                    continue;
                }

                // If the installed package is not the target package,
                // create a new PackageReference which is passed to the content resolver.
                // This makes logging make more sense.
                var installedPackageReference = installedPackage.Id.Equals(packageReference.Package, StringComparison.OrdinalIgnoreCase) ?
                                                packageReference :
                                                new PackageReference($"nuget:?package={installedPackage.Id}");

                files.AddRange(_contentResolver.GetFiles(installPath, installedPackageReference, type));
            }

            return(files);
        }
Example #2
0
        private Type LoadModule(FilePath path)
        {
            try
            {
                var assembly = LoadAssembly(path);

                var attribute = assembly.GetCustomAttributes <CakeModuleAttribute>().FirstOrDefault();
                if (attribute == null)
                {
                    _log.Warning("The assembly '{0}' does not have module metadata.", path.FullPath);
                    return(null);
                }

                if (!typeof(ICakeModule).IsAssignableFrom(attribute.ModuleType))
                {
                    _log.Warning("The module type '{0}' is not an actual module.", attribute.ModuleType.FullName);
                    return(null);
                }

                return(attribute.ModuleType);
            }
            catch (CakeException)
            {
                throw;
            }
            catch
            {
                _log.Warning("Could not load module '{0}'.", path.FullPath);
                return(null);
            }
        }
Example #3
0
        // ReSharper disable once UnusedParameter.Local
        private void AnalyseResultsFile(FilePath resultsFilePath, bool throwOnViolations)
        {
            var anyFailures = false;
            var resultsFile = _fileSystem.GetFile(resultsFilePath);

            using (var stream = resultsFile.OpenRead())
            {
                var xmlDoc     = XDocument.Load(stream);
                var violations = xmlDoc.Descendants("IssueType").Where(i => i.Attribute("Severity") != null && i.Attribute("Severity").Value == "ERROR");

                foreach (var violation in violations)
                {
                    _log.Warning("Code Inspection Error(s) Located. Description: {0}", violation.Attribute("Description").Value);

                    var tempViolation = violation; // Copy to temporary variable to avoid side effects.
                    var issueLookups  = xmlDoc.Descendants("Issue").Where(i => i.Attribute("TypeId") != null && i.Attribute("TypeId").Value == tempViolation.Attribute("Id").Value);

                    foreach (var issueLookup in issueLookups)
                    {
                        var file    = issueLookup.Attribute("File") == null ? string.Empty : issueLookup.Attribute("File").Value;
                        var line    = issueLookup.Attribute("Line") == null ? string.Empty : issueLookup.Attribute("Line").Value;
                        var message = issueLookup.Attribute("Message") == null ? string.Empty : issueLookup.Attribute("Message").Value;

                        _log.Warning("File Name: {0} Line Number: {1} Message: {2}", file, line, message);
                    }

                    anyFailures = true;
                }
            }

            if (anyFailures && throwOnViolations)
            {
                throw new CakeException("Code Inspection Violations found in code base.");
            }
        }
Example #4
0
        private Type LoadModule(FilePath path, ICakeConfiguration configuration)
        {
            try
            {
                var loader   = new AssemblyLoader(_environment, _fileSystem, new AssemblyVerifier(configuration, _log));
                var assembly = loader.Load(path, true);

                var attribute = assembly.GetCustomAttributes <CakeModuleAttribute>().FirstOrDefault();
                if (attribute == null)
                {
                    _log.Warning("The assembly '{0}' does not have module metadata.", path.FullPath);
                    return(null);
                }

                if (!typeof(ICakeModule).IsAssignableFrom(attribute.ModuleType))
                {
                    _log.Warning("The module type '{0}' is not an actual module.", attribute.ModuleType.FullName);
                    return(null);
                }

                return(attribute.ModuleType);
            }
            catch (CakeException)
            {
                throw;
            }
            catch (Exception ex)
            {
                _log.Warning("Could not load module '{0}'. {1}", path.FullPath, ex);
                return(null);
            }
        }
Example #5
0
        public void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Warn about any code generation excluded namespaces
            foreach (var @namespace in script.ExcludedNamespaces)
            {
                _log.Warning("Namespace {0} excluded by code generation, affected methods:\r\n\t{1}",
                             @namespace.Key, string.Join("\r\n\t", @namespace.Value));
            }

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddImports(Namespaces.Except(script.ExcludedNamespaces.Keys))
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath))
                          .WithEmitDebugInformation(_settings.Debug)
                          .WithMetadataResolver(Microsoft.CodeAnalysis.Scripting.ScriptMetadataResolver.Default);

            var roslynScript = CSharpScript.Create(code, options, _host.GetType());

            _log.Verbose("Compiling build script...");
            var compilation = roslynScript.GetCompilation();
            var diagnostics = compilation.GetDiagnostics();

            var errors = new List <Diagnostic>();

            foreach (var diagnostic in diagnostics)
            {
                switch (diagnostic.Severity)
                {
                case DiagnosticSeverity.Info:
                    _log.Information(diagnostic.ToString());
                    break;

                case DiagnosticSeverity.Warning:
                    _log.Warning(diagnostic.ToString());
                    break;

                case DiagnosticSeverity.Error:
                    _log.Error(diagnostic.ToString());
                    errors.Add(diagnostic);
                    break;

                default:
                    break;
                }
            }

            if (errors.Any())
            {
                var errorMessages = string.Join(Environment.NewLine, errors.Select(x => x.ToString()));
                var message       = string.Format(CultureInfo.InvariantCulture, "Error(s) occurred when compiling build script:{0}{1}", Environment.NewLine, errorMessages);
                throw new CakeException(message);
            }

            roslynScript.RunAsync(_host).Wait();
        }
        /// <summary>
        /// Installs the specified resource at the given location.
        /// </summary>
        /// <param name="package">The package reference.</param>
        /// <param name="type">The package type.</param>
        /// <param name="path">The location where to install the package.</param>
        /// <returns>The installed files.</returns>
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            // Create the addin directory if it doesn't exist.
            path = GetPackagePath(path.MakeAbsolute(_environment), package);
            var root = _fileSystem.GetDirectory(path);

            if (!root.Exists)
            {
                _log.Debug("Creating directory {0}", path);
                root.Create();
            }

            // Package already exist?
            var packagePath = GetPackagePath(root, package.Package);

            if (packagePath != null)
            {
                // Fetch available content from disc.
                var content = _contentResolver.GetFiles(packagePath, package, type);
                if (content.Any())
                {
                    _log.Debug("Package {0} has already been installed.", package.Package);
                    return(content);
                }
            }

            // Install the package.
            InstallPackage(package, path);

            // Try locating the install folder again.
            packagePath = GetPackagePath(root, package.Package);

            // Get the files.
            var result = _contentResolver.GetFiles(packagePath, package, type);

            if (result.Count == 0)
            {
                if (type == PackageType.Addin)
                {
                    var framework = _environment.Runtime.TargetFramework;
                    _log.Warning("Could not find any assemblies compatible with {0}.", framework.FullName);
                }
                else if (type == PackageType.Tool)
                {
                    const string format = "Could not find any relevant files for tool '{0}'. Perhaps you need an include parameter?";
                    _log.Warning(format, package.Package);
                }
            }

            return(result);
        }
Example #7
0
        private void AnalyzeResultsFile(FilePath resultsFilePath, bool throwOnDuplicates)
        {
            var anyFailures = false;
            var resultsFile = _fileSystem.GetFile(resultsFilePath);
            var xmlDoc      = XDocument.Load(resultsFile.Open(FileMode.Open));
            var duplicates  = xmlDoc.Descendants("Duplicate");

            foreach (var duplicate in duplicates)
            {
                var cost = duplicate.Attribute("Cost") == null ? string.Empty : duplicate.Attribute("Cost").Value;

                _log.Warning("Duplicate Located with a cost of {0}, across {1} Fragments", cost, duplicate.Descendants("Fragment").Count());

                foreach (var fragment in duplicate.Descendants("Fragment"))
                {
                    var fileNameNode  = fragment.Descendants("FileName").FirstOrDefault();
                    var lineRangeNode = fragment.Descendants("LineRange").FirstOrDefault();

                    if (fileNameNode != null && lineRangeNode != null)
                    {
                        var start = lineRangeNode.Attribute("Start") == null ? string.Empty : lineRangeNode.Attribute("Start").Value;
                        var end   = lineRangeNode.Attribute("End") == null ? string.Empty : lineRangeNode.Attribute("End").Value;

                        _log.Warning("File Name: {0} Line Numbers: {1} - {2}", fileNameNode.Value, start, end);
                    }
                }

                anyFailures = true;
            }

            if (anyFailures && throwOnDuplicates)
            {
                throw new CakeException("Duplicates found in code base.");
            }
        }
Example #8
0
        /// <inheritdoc/>
        public IReadOnlyList <ScriptAlias> FindAliases(IEnumerable <Assembly> assemblies)
        {
            var result = new List <ScriptAlias>();

            if (assemblies != null)
            {
                foreach (var reference in assemblies)
                {
                    try
                    {
                        foreach (var typeInfo in reference.DefinedTypes)
                        {
                            var type = typeInfo.AsType();
                            if (type.IsStatic())
                            {
                                foreach (var method in GetAliasMethods(type))
                                {
                                    var alias = CreateAlias(method);
                                    if (alias != null)
                                    {
                                        result.Add(alias);
                                    }
                                }
                            }
                        }
                    }
                    catch (ReflectionTypeLoadException ex)
                    {
                        HashSet <string> notFound = new HashSet <string>(StringComparer.OrdinalIgnoreCase);
                        foreach (Exception loaderException in ex.LoaderExceptions)
                        {
                            _log.Debug(loaderException.Message);
                            FileNotFoundException fileNotFoundException = loaderException as FileNotFoundException;
                            if (fileNotFoundException != null)
                            {
                                if (!notFound.Contains(fileNotFoundException.FileName))
                                {
                                    notFound.Add(fileNotFoundException.FileName);
                                }
                            }
                            _log.Debug(string.Empty);
                        }

                        foreach (var file in notFound)
                        {
                            _log.Warning("Could not load {0} (missing {1})", reference.Location, file);
                        }
                    }
                    catch (FileNotFoundException ex)
                    {
                        _log.Warning("Could not load {0} (missing {1}))", reference.Location, ex.FileName);
                    }
                }
            }
            return(result);
        }
        /// <summary>
        /// Installs the specified resource.
        /// </summary>
        /// <param name="package">The package resource.</param>
        /// <param name="type">The package type.</param>
        /// <param name="path">The location where to install the resource.</param>
        /// <returns>The installed files.</returns>
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            // find npm
            _log.Debug("looking for npm.cmd");
            var npmTool = _toolLocator.Resolve("npm.cmd");

            if (npmTool == null)
            {
                _log.Debug("looking for npm");
                npmTool = _toolLocator.Resolve("npm");
            }

            if (npmTool == null)
            {
                throw new FileNotFoundException("npm could not be found.");
            }

            _log.Debug("Found npm at {0}", npmTool);

            // Install the package.
            _log.Debug("Installing package {0} with npm...", package.Package);
            var process = _processRunner.Start(
                npmTool.FullPath,
                new ProcessSettings {
                Arguments = GetArguments(package, _config), RedirectStandardOutput = true, Silent = _log.Verbosity < Verbosity.Diagnostic
            });

            process.WaitForExit();

            var exitCode = process.GetExitCode();

            if (exitCode != 0)
            {
                _log.Warning("npm exited with {0}", exitCode);
                var output = string.Join(Environment.NewLine, process.GetStandardOutput());
                _log.Verbose(Verbosity.Diagnostic, "Output:\r\n{0}", output);
            }

            var result = _contentResolver.GetFiles(package, type, package.GetSwitch("global"));

            if (result.Count != 0)
            {
                return(result);
            }

            _log.Warning("Could not determine installed package files! Installation may not be complete.");

            // TODO: maybe some warnings here
            return(result);
        }
        public IReadOnlyCollection <IFile> GetFiles(DirectoryPath directoryPath, PackageReference packageReference, PackageType type)
        {
            bool loadDependencies;

            if (packageReference.Parameters.ContainsKey("LoadDependencies"))
            {
                bool.TryParse(packageReference.Parameters["LoadDependencies"].FirstOrDefault() ?? bool.TrueString, out loadDependencies);
            }
            else
            {
                bool.TryParse(_config.GetValue(Constants.NuGet.LoadDependencies) ?? bool.FalseString, out loadDependencies);
            }

            var files       = new List <IFile>();
            var package     = _installedPackages.First(p => p.Id.Equals(packageReference.Package, StringComparison.OrdinalIgnoreCase));
            var installPath = new DirectoryPath(_pathResolver.GetInstallPath(package));

            if (!_fileSystem.Exist(installPath))
            {
                _log.Warning("Package {0} is not installed.", packageReference.Package);
                return(Array.Empty <IFile>());
            }

            files.AddRange(_contentResolver.GetFiles(installPath, packageReference, type));

            if (loadDependencies)
            {
                foreach (var dependency in _installedPackages
                         .Where(p => !p.Id.Equals(packageReference.Package, StringComparison.OrdinalIgnoreCase)))
                {
                    if (_blackListedPackages.Contains(dependency.Id))
                    {
                        _log.Warning("Package {0} depends on package {1}. Will not load this dependency...",
                                     packageReference.Package, dependency.ToString());
                        continue;
                    }

                    var dependencyInstallPath = new DirectoryPath(_pathResolver.GetInstallPath(dependency));

                    if (!_fileSystem.Exist(dependencyInstallPath))
                    {
                        _log.Warning("Package {0} is not installed.", dependency.Id);
                        continue;
                    }

                    files.AddRange(_contentResolver.GetFiles(dependencyInstallPath, packageReference, type));
                }
            }

            return(files);
        }
        /// <summary>
        /// Installs the specified resource at the given location.
        /// </summary>
        /// <param name="package">The package reference.</param>
        /// <param name="type">The package type.</param>
        /// <param name="path">The location where to install the package.</param>
        /// <returns>The installed files.</returns>
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

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

            // We are going to assume that the default install location is the
            // currently configured location for the Cake Tools Folder
            var toolsFolderDirectoryPath = _config.GetToolPath(_environment.WorkingDirectory, _environment);

            _log.Debug("Configured Tools Folder: {0}", toolsFolderDirectoryPath);

            var toolLocation = toolsFolderDirectoryPath.FullPath;

            if (package.Parameters.ContainsKey("global"))
            {
                toolLocation = "global";
            }

            // First we need to check if the Tool is already installed
            var installedToolNames = GetInstalledTools(toolLocation);

            _log.Debug("Checking for tool: {0}", package.Package.ToLowerInvariant());
            if (installedToolNames.Contains(package.Package.ToLowerInvariant()))
            {
                _log.Information("Tool {0} is already installed, so nothing to do here.", package.Package);
            }
            else
            {
                InstallTool(package, toolsFolderDirectoryPath);
            }

            var result = _contentResolver.GetFiles(package, type);

            if (result.Count == 0)
            {
                const string format = "Could not find any relevant files for tool '{0}'. Perhaps you need an include parameter?";
                _log.Warning(format, package.Package);
            }

            return(result);
        }
Example #12
0
        private void ExecuteProcess(FilePath filePath, ProcessArgumentBuilder arguments, int timeout = DefaultTimeoutMs)
        {
            try
            {
                // Start Runner
                filePath = filePath.MakeAbsolute(_Environment.WorkingDirectory);

                IProcess process = _Runner.Start(filePath, new ProcessSettings()
                {
                    Arguments             = arguments,
                    RedirectStandardError = true
                });

                process.WaitForExit(timeout);



                // Check for Errors
                IEnumerable <string> errors = process.GetStandardError();

                if (errors.Count() > 0)
                {
                    throw new Exception(string.Join(",", errors));
                }
            }
            catch (Exception ex)
            {
                if (!(ex is TimeoutException))
                {
                    throw;
                }

                _Log.Warning("Process timed out!");
            }
        }
Example #13
0
        /// <summary>
        /// Finds assemblies (DLLs) included in a nuget package.
        /// </summary>
        /// <param name="packageDirectory">The package directory.</param>
        /// <returns>
        /// the DLLs.
        /// </returns>
        public IReadOnlyList <IFile> FindAssemblies(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>().AsReadOnly());
            }

            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);
        }
Example #14
0
        public void Load(IScriptAnalyzerContext context, LoadReference reference)
        {
#if NETCORE
            throw new NotSupportedException("The NuGet provider for #load is not supported on .NET Core.");
#else
            // Create a package reference from our load reference.
            // The package should contain the necessary include parameters to make sure
            // that .cake files are included as part of the result.
            var separator = reference.OriginalString.Contains("?") ? "&" : "?";
            var uri       = string.Concat(reference.OriginalString, $"{separator}include=./**/*.cake");
            var package   = new PackageReference(uri);

            // Find the tool folder.
            var toolPath = GetToolPath(context.Root.GetDirectory());

            // Install the NuGet package.
            var files = _installer.Install(package, PackageType.Tool, toolPath);
            if (files.Count == 0)
            {
                // No files found.
                _log.Warning("No scripts found in NuGet package {0}.", package.Package);
                return;
            }

            foreach (var file in files)
            {
                var extension = file.Path.GetExtension();
                if (extension != null && extension.Equals(".cake", StringComparison.OrdinalIgnoreCase))
                {
                    context.Analyze(file.Path);
                }
            }
#endif
        }
Example #15
0
        /// <inheritdoc/>
        public void Verify(Assembly assembly)
        {
            _log.Debug(_skipVerification ? "Skipping verification of assembly '{0}'." : "Verifying assembly '{0}'.", assembly.FullName);

            // Verify that the assembly is valid.
            // We're still pre 1.0, so there are breaking changes from time to time.
            // We can refuse to load assemblies that reference too old version of Cake.
            var references = assembly.GetReferencedAssemblies();

            foreach (var reference in references)
            {
                if (reference.Name.Equals("Cake.Core"))
                {
                    if (reference.Version < Constants.LatestBreakingChange)
                    {
                        // The assembly is referencing a version of Cake that contains breaking changes.
                        const string message = "The assembly '{0}' \r\n" +
                                               "is referencing an older version of Cake.Core ({1}). \r\n" +
                                               "This assembly must reference at least Cake.Core version {2}. \r\n" +
                                               "Another option is to downgrade Cake to an earlier version. \r\n" +
                                               "It's not recommended, but you can explicitly opt out of assembly verification \r\n" +
                                               "by configuring the Skip Verification setting to true\r\n" +
                                               "(i.e. command line parameter \"--settings_skipverification=true\", \r\n" +
                                               "environment variable \"CAKE_SETTINGS_SKIPVERIFICATION=true\", \r\n" +
                                               "read more about configuration at https://cakebuild.net/docs/running-builds/configuration/)";

                        var args = new object[]
                        {
                            assembly.FullName,
                            reference.Version.ToString(3),
                            Constants.LatestBreakingChange.ToString(3)
                        };

                        if (_skipVerification)
                        {
                            _log.Debug(
                                message,
                                args);
                            return;
                        }

                        throw new CakeException(string.Format(message, args));
                    }

                    if (reference.Version < Constants.LatestPotentialBreakingChange)
                    {
                        // The assembly is referencing a version of Cake that might contain breaking changes.
                        const string message = "The assembly '{0}' \r\n" +
                                               "is referencing an older version of Cake.Core ({1}). \r\n" +
                                               "For best compatibility it should target Cake.Core version {2}.";
                        _log.Warning(
                            _skipVerification ? Verbosity.Verbose : Verbosity.Minimal,
                            message,
                            assembly.FullName,
                            reference.Version.ToString(3),
                            Constants.LatestPotentialBreakingChange.ToString(3));
                    }
                }
            }
        }
        public ParallelCakeEngine(ICakeLog logger)
        {
            logger.Warning("PARALLELIZER IS A WORK IN PROGRESS! YOU HAVE BEEN WARNED");

            _logger = logger;
            _tasks  = new List <CakeTask>();
        }
Example #17
0
        /// <summary>
        /// Gets all environment variables.
        /// </summary>
        /// <returns>The environment variables as IDictionary&lt;string, string&gt; </returns>
        public IDictionary <string, string> GetEnvironmentVariables()
        {
            return(Environment.GetEnvironmentVariables()
                   .Cast <System.Collections.DictionaryEntry>()
                   .Aggregate(
                       new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase),
                       (dictionary, entry) =>
            {
                var key = (string)entry.Key;
                var value = entry.Value as string;
                if (dictionary.TryGetValue(key, out var existingValue))
                {
                    if (!StringComparer.OrdinalIgnoreCase.Equals(value, existingValue))
                    {
                        _log.Warning("GetEnvironmentVariables() encountered duplicate for key: {0}, value: {1} (existing value: {2})",
                                     key,
                                     value,
                                     existingValue);
                    }
                }
                else
                {
                    dictionary.Add(key, value);
                }

                return dictionary;
            },
                       dictionary => dictionary));
        }
Example #18
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 #19
0
        /// <summary>
        /// Installs the specified resource at the given location.
        /// </summary>
        /// <param name="package">The package reference.</param>
        /// <param name="type">The package type.</param>
        /// <param name="path">The location where to install the package.</param>
        /// <returns>The installed files.</returns>
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            path = path.MakeAbsolute(_environment);

            var root        = _fileSystem.GetDirectory(path);
            var packagePath = path.Combine(package.Package);

            // Create the addin directory if it doesn't exist.
            if (!root.Exists)
            {
                _log.Debug("Creating directory {0}", path);
                root.Create();
            }

            // Fetch available content from disc.
            var content = _contentResolver.GetFiles(packagePath, type);

            if (content.Any())
            {
                _log.Debug("Package {0} has already been installed.", package.Package);
                return(content);
            }

            // Install the package.
            _log.Debug("Installing NuGet package {0}...", package.Package);
            var nugetPath = GetNuGetPath();
            var process   = _processRunner.Start(nugetPath, new ProcessSettings
            {
                Arguments = GetArguments(package, path, _config),
                RedirectStandardOutput = true,
                Silent = _log.Verbosity < Verbosity.Diagnostic
            });

            process.WaitForExit();

            var exitCode = process.GetExitCode();

            if (exitCode != 0)
            {
                _log.Warning("NuGet exited with {0}", exitCode);
                var output = string.Join(Environment.NewLine, process.GetStandardOutput());
                _log.Verbose(Verbosity.Diagnostic, "Output:\r\n{0}", output);
            }

            // Return the files.
            return(_contentResolver.GetFiles(packagePath, type));
        }
        public IEnumerable <string> GetStandardError()
        {
            string line;

            while ((line = _process.StandardError.ReadLine()) != null)
            {
                _log.Warning("{0}", _filterOutput(line));
                yield return(line);
            }
        }
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            if (_environment.Platform.Family != PlatformFamily.Linux)
            {
                _log.Warning("Non-Linux platform detected! Not attempting installation...");
                return(_contentResolver.GetFiles(package, type));
            }

            // Install the package.
            _log.Debug("Installing package {0} with APT...", package.Package);
            var process = _processRunner.Start(
                "apt-get",
                new ProcessSettings {
                Arguments = GetArguments(package, _config), RedirectStandardOutput = true, Silent = _log.Verbosity < Verbosity.Diagnostic
            });

            process.WaitForExit();

            var exitCode = process.GetExitCode();

            if (exitCode != 0)
            {
                _log.Warning("APT exited with {0}", exitCode);
                var output = string.Join(Environment.NewLine, process.GetStandardOutput());
                _log.Verbose(Verbosity.Diagnostic, "Output:\r\n{0}", output);
            }

            var result = _contentResolver.GetFiles(package, type);

            if (result.Count != 0)
            {
                return(result);
            }

            // TODO: maybe some warnings here
            return(result);
        }
Example #22
0
        public IReadOnlyCollection <IFile> GetFiles(DirectoryPath directoryPath, PackageReference packageReference, PackageType type)
        {
            var loadDependencies = packageReference.ShouldLoadDependencies(_config);

            var files       = new List <IFile>();
            var package     = _installedPackages.First(p => p.Id.Equals(packageReference.Package, StringComparison.OrdinalIgnoreCase));
            var installPath = new DirectoryPath(_pathResolver.GetInstallPath(package));

            if (!_fileSystem.Exist(installPath))
            {
                _log.Warning("Package {0} is not installed.", packageReference.Package);
                return(Array.Empty <IFile>());
            }

            files.AddRange(_contentResolver.GetFiles(installPath, packageReference, type));

            if (loadDependencies)
            {
                foreach (var dependency in _installedPackages
                         .Where(p => !p.Id.Equals(packageReference.Package, StringComparison.OrdinalIgnoreCase)))
                {
                    if (_blackListedPackages.Contains(dependency.Id))
                    {
                        _log.Warning("Package {0} depends on package {1}. Will not load this dependency...",
                                     packageReference.Package, dependency.ToString());
                        continue;
                    }

                    var dependencyInstallPath = new DirectoryPath(_pathResolver.GetInstallPath(dependency));

                    if (!_fileSystem.Exist(dependencyInstallPath))
                    {
                        _log.Warning("Package {0} is not installed.", dependency.Id);
                        continue;
                    }

                    files.AddRange(_contentResolver.GetFiles(dependencyInstallPath, packageReference, type));
                }
            }

            return(files);
        }
Example #23
0
        public ParallelCakeEngine(ICakeLog log)
        {
            if (log == null)
            {
                throw new ArgumentNullException(nameof(log));
            }

            log.Warning("PARALLELIZER IS A WORK IN PROGRESS! YOU HAVE BEEN WARNED");

            _log   = log;
            _tasks = new List <CakeTask>();
        }
Example #24
0
        internal bool EnsureSourceExists()
        {
            var data = new EventSourceCreationData(Settings.SourceName, Settings.LogName)
            {
                MachineName = Settings.MachineName
            };
            var exists = false;

            try
            {
                exists = System.Diagnostics.EventLog.Exists(Settings.SourceName);
                if (!exists)
                {
                    _log?.Information("Source does not exist. Creating...");
                    System.Diagnostics.EventLog.CreateEventSource(data);
                    exists = System.Diagnostics.EventLog.SourceExists(Settings.SourceName);
                }
            }
            catch (SecurityException)
            {
                // we couldn't determine if the source exists
                LogPrivilegeWarning();
                _log?.Warning("Could not determine if the source exists. Attempting creation.");
                try
                {
                    System.Diagnostics.EventLog.CreateEventSource(data);
                }
                catch (ArgumentException)
                {
                    // couldn't test if exists but creation failed
                    _log?.Information("Creating event source failed! The source apepars to already exist.");
                    exists = true;
                }
            }
            catch (Exception)
            {
                exists = false;
            }
            return(exists);
        }
Example #25
0
        public void Initialize(ICakeEngine engine, IFrostingContext context, IEnumerable <IFrostingTask> tasks,
                               IFrostingLifetime lifetime, IFrostingTaskLifetime taskLifetime)
        {
            if (tasks != null)
            {
                foreach (var task in tasks)
                {
                    var taskName = TaskNameHelper.GetTaskName(task);
                    _log.Debug("Registering task {0} with engine...", taskName);

                    // Get the task's context type.
                    if (!task.HasCompatibleContext(context))
                    {
                        const string format = "Task cannot be used since the context isn't convertable to {0}.";
                        _log.Warning(format, task.GetContextType().FullName);
                    }
                    else
                    {
                        // Register task with the Cake engine.
                        var cakeTask = engine.RegisterTask(taskName);
                        cakeTask.Does(task.Run);
                        cakeTask.WithCriteria(task.ShouldRun);

                        // Add dependencies
                        var attributes = task.GetType().GetTypeInfo().GetCustomAttributes <DependencyAttribute>();
                        foreach (var dependency in attributes)
                        {
                            var dependencyName = TaskNameHelper.GetTaskName(dependency);
                            if (!typeof(IFrostingTask).IsAssignableFrom(dependency.Task))
                            {
                                throw new FrostingException($"The dependency {dependencyName} does not implement IFrostingTask.");
                            }
                            cakeTask.IsDependentOn(dependencyName);
                        }
                    }
                }
            }

            if (lifetime != null)
            {
                _log.Debug("Registering lifetime {0} with engine...", lifetime.GetType().FullName);
                engine.RegisterSetupAction(info => lifetime.Setup(context));
                engine.RegisterTeardownAction(info => lifetime.Teardown(context, info));
            }

            if (taskLifetime != null)
            {
                _log.Debug("Registering task lifetime {0} with engine...", taskLifetime.GetType().Name);
                engine.RegisterTaskSetupAction(info => taskLifetime.Setup(context, info));
                engine.RegisterTaskTeardownAction(info => taskLifetime.Teardown(context, info));
            }
        }
Example #26
0
        public void Load(IScriptAnalyzerContext context, LoadReference reference)
        {
            FilePath path = null;

            if (reference.Parameters.ContainsKey("path"))
            {
                if (reference.Parameters["path"].Count == 1)
                {
                    path = reference.Parameters["path"].FirstOrDefault();
                }
                else if (reference.Parameters["path"].Count > 1)
                {
                    throw new CakeException("Query string for #load contains more than one parameter 'path'.");
                }
            }

            if (path == null)
            {
                throw new CakeException("Query string for #load is missing parameter 'path'.");
            }

            // URL decode the path.
            path = new FilePath(WebUtility.UrlDecode(path.FullPath));

            // Get the current script path.
            var current = context.Current.Path.GetDirectory();

            path = path.MakeAbsolute(current);

            var expectedExtension = path.HasExtension ? path.GetExtension() : ".cake";
            var files             = _globber
                                    .GetFiles(path.FullPath)
                                    .Where(file =>
            {
                var extension = file.GetExtension();
                return(extension != null && (extension.Equals(".cake", StringComparison.OrdinalIgnoreCase) || extension.Equals(expectedExtension, StringComparison.OrdinalIgnoreCase)));
            })
                                    .ToArray();

            if (files.Length == 0)
            {
                // No scripts found.
                _log.Warning("No scripts found at {0}.", path);
                return;
            }

            foreach (var file in files)
            {
                context.Analyze(file);
            }
        }
Example #27
0
        public SolutionInfoResult GetSolutionToBuild(string fileName = null)
        {
            var files = _globber.GetFiles("./**/*.sln").ToList();

            if (files.Count == 0)
            {
                throw new Exception("Solution file not found");
            }
            if (files.Count > 1)
            {
                if (string.IsNullOrWhiteSpace(fileName))
                {
                    _log.Warning("Multiple solution files found");
                    foreach (var file in files)
                    {
                        _log.Warning(file.FullPath);
                    }
                }
                else
                {
                    var matchFile = files.FirstOrDefault(f => string.Compare(f.GetFilename().ToString(), fileName, StringComparison.OrdinalIgnoreCase) == 0);
                    if (matchFile == null)
                    {
                        throw new Exception($"Solution file specified as {fileName} was not found");
                    }
                    return(new SolutionInfoResult
                    {
                        SolutionFileAndPath = matchFile.FullPath,
                        SolutionFilename = matchFile.GetFilename().ToString()
                    });
                }
            }
            return(new SolutionInfoResult
            {
                SolutionFileAndPath = files[0].FullPath,
                SolutionFilename = files[0].GetFilename().ToString()
            });
        }
Example #28
0
        public void Register(ICakeContainerRegistrar registrar)
        {
            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            if (_options.Mono)
            {
                _log.Warning("The Mono script engine has been removed so the expected behavior might differ. " +
                             "See Release Notes for Cake 0.22.0 for more information.");
            }

            registrar.RegisterType <RoslynScriptEngine>().As <IScriptEngine>().Singleton();
        }
Example #29
0
        private UnityVersion DetermineVersion(FilePath editorPath)
        {
            log.Debug("Determining version of Unity Editor at path {0}...", editorPath);

            var fileVersion = FileVersionInfo.GetVersionInfo(editorPath.FullPath);

            var(year, stream, update) = (fileVersion.FileMajorPart, fileVersion.FileMinorPart, fileVersion.FileBuildPart);

            if (year <= 0 || stream <= 0 || update < 0)
            {
                log.Warning("Unity Editor file version {0} is incorrect.", $"{year}.{stream}.{update}.{fileVersion.FilePrivatePart}");
                log.Warning("Expected first two numbers to be positive and third one to be non negative.");
                log.Warning("Path: {0}", editorPath.FullPath);
                log.Warning(string.Empty);
                return(null);
            }

            log.Debug("Unity version from file version: {0}.{1}.{2}", year, stream, update);

            var suffix = DetermineVersionSuffix(editorPath, year, stream, update);

            if (suffix.HasValue)
            {
                var version = new UnityVersion(year, stream, update, suffix.Value.character, suffix.Value.number);
                log.Debug("Result Unity Editor version (full): {0}", version);
                log.Debug(string.Empty);
                return(version);
            }
            else
            {
                var version = new UnityVersion(year, stream, update);
                log.Debug("Result Unity Editor version (short): {0}", version);
                log.Debug(string.Empty);
                return(version);
            }
        }
Example #30
0
        public void Log(MessageLevel level, string message, params object[] args)
        {
            switch (level)
            {
            case MessageLevel.Warning:
                _log.Warning(message, args);
                break;

            case MessageLevel.Error:
                _log.Error(message, args);
                break;

            default:
                _log.Debug(message, args);
                break;
            }
        }