Beispiel #1
0
        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));
            }

            var packageRoot              = path.MakeAbsolute(_environment).FullPath;
            var targetFramework          = type == PackageType.Addin ? _currentFramework : NuGetFramework.AnyFramework;
            var sourceRepositoryProvider = new NuGetSourceRepositoryProvider(_nugetSettings, _config, package, packageRoot);

            var localAndPrimaryRepositories = new HashSet <SourceRepository>(new NuGetSourceRepositoryComparer());

            localAndPrimaryRepositories.AddRange(sourceRepositoryProvider.LocalRepositories);
            localAndPrimaryRepositories.AddRange(sourceRepositoryProvider.PrimaryRepositories);

            var allRepositories = new HashSet <SourceRepository>(new NuGetSourceRepositoryComparer());

            allRepositories.AddRange(localAndPrimaryRepositories);
            allRepositories.AddRange(sourceRepositoryProvider.Repositories);

            var packageIdentity = GetPackageId(package, localAndPrimaryRepositories, targetFramework, _sourceCacheContext, _nugetLogger);

            if (packageIdentity == null)
            {
                return(Array.Empty <IFile>());
            }

            if (packageIdentity.Version.IsPrerelease && !package.IsPrerelease())
            {
                // TODO: Is this allowed? If not, log and return
                return(Array.Empty <IFile>());
            }

            var pathResolver       = new PackagePathResolver(packageRoot);
            var dependencyBehavior = GetDependencyBehavior(type, package);
            var downloadContext    = new PackageDownloadContext(_sourceCacheContext);

            var availablePackages = new HashSet <SourcePackageDependencyInfo>(PackageIdentityComparer.Default);

            GetPackageDependencies(packageIdentity,
                                   targetFramework,
                                   _sourceCacheContext,
                                   _nugetLogger,
                                   allRepositories,
                                   availablePackages,
                                   dependencyBehavior,
                                   localAndPrimaryRepositories);

            var resolverContext = new PackageResolverContext(
                dependencyBehavior,
                new[] { packageIdentity.Id },
                Enumerable.Empty <string>(),
                Enumerable.Empty <global::NuGet.Packaging.PackageReference>(),
                Enumerable.Empty <PackageIdentity>(),
                availablePackages,
                allRepositories.Select(s => s.PackageSource),
                NullLogger.Instance);

            var resolver          = new PackageResolver();
            var packagesToInstall = resolver.Resolve(resolverContext, CancellationToken.None)
                                    .Select(p => availablePackages.Single(x => PackageIdentityComparer.Default.Equals(x, p)));

            var packageExtractionContext = new PackageExtractionContext(
                PackageSaveMode.Nuspec | PackageSaveMode.Files | PackageSaveMode.Nupkg,
                XmlDocFileSaveMode.None,
                ClientPolicyContext.GetClientPolicy(_nugetSettings, _nugetLogger),
                _nugetLogger);

            var installedFiles = new List <IFile>();

            foreach (var packageToInstall in packagesToInstall)
            {
                var isTargetPackage = packageToInstall.Id.Equals(package.Package, StringComparison.OrdinalIgnoreCase);
                var installPath     = new DirectoryPath(pathResolver.GetInstallPath(packageToInstall));
                if (!_fileSystem.Exist(installPath))
                {
                    var downloadResource = packageToInstall.Source.GetResourceAsync <DownloadResource>(CancellationToken.None).GetAwaiter().GetResult();
                    var downloadResult   = downloadResource.GetDownloadResourceResultAsync(
                        packageToInstall,
                        downloadContext,
                        SettingsUtility.GetGlobalPackagesFolder(_nugetSettings),
                        _nugetLogger, CancellationToken.None).GetAwaiter().GetResult();

                    PackageExtractor.ExtractPackageAsync(
                        downloadResult.PackageSource,
                        downloadResult.PackageStream,
                        pathResolver,
                        packageExtractionContext,
                        CancellationToken.None).GetAwaiter().GetResult();

                    // If this is the target package, to avoid problems with casing, get the actual install path from the nuspec
                    if (isTargetPackage)
                    {
                        installPath = new DirectoryPath(pathResolver.GetInstallPath(downloadResult.PackageReader.GetIdentity()));
                    }
                }

                if (_blackListedPackages.Contains(packageToInstall.Id))
                {
                    const string format = "Package {0} depends on package {1}. This dependency won't be loaded.";
                    _log.Debug(format, package.Package, packageToInstall.ToString());
                    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 = isTargetPackage ? package : new PackageReference($"nuget:?package={packageToInstall.Id}");

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

            return(installedFiles);
        }
Beispiel #2
0
        public IReadOnlyCollection <UnityEditorDescriptor> Seek()
        {
            var searchPattern = $"{ProgramFiles}/*Unity*/**/Editor/Unity.exe";

            log.Debug("Searching for available Unity Editors...");
            log.Debug("Search pattern: {0}", searchPattern);
            var candidates = globber.GetFiles(searchPattern).ToList();

            log.Debug("Found {0} candidates.", candidates.Count);
            log.Debug(string.Empty);

            var editors =
                from candidatePath in candidates
                let version = DetermineVersion(candidatePath)
                              where version != null
                              select new UnityEditorDescriptor(version, candidatePath);

            return(editors.ToList());
        }
Beispiel #3
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(nameof(package));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(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, package, 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);
            }

            // 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);
        }
Beispiel #4
0
 private void LogExecutingCommand(PowershellSettings settings, string script, bool safe = true)
 {
     _Log.Debug(Verbosity.Normal, String.Format("Executing: {0}", this.AppendArguments(script, settings.Arguments, safe).EscapeCurleyBrackets()));
 }
        private int Convert(string wkhtmltopdfPath, string switches, string baseDirectory, ICakeLog log)
        {
            if (string.IsNullOrEmpty(wkhtmltopdfPath))
            {
                wkhtmltopdfPath = Path.Combine(baseDirectory, "wkhtmltopdf.exe");
            }

            log.Debug("Run html to pdf converter: " + wkhtmltopdfPath);
            log.Debug("Using switches: " + switches);

            Process process = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName               = wkhtmltopdfPath,
                    Arguments              = switches,
                    UseShellExecute        = false,
                    RedirectStandardOutput = true,
                    RedirectStandardError  = true,
                    RedirectStandardInput  = true,
                    CreateNoWindow         = true,
                    WindowStyle            = ProcessWindowStyle.Hidden
                }
            };

            var output = new StringBuilder();

            ExecutionOutputText = "";

            void OnOutputDataReceived(object o, DataReceivedEventArgs e) => output.AppendLine(e.Data);

            process.OutputDataReceived += OnOutputDataReceived;
            process.ErrorDataReceived  += OnOutputDataReceived;

            try
            {
                process.Start();

                process.BeginOutputReadLine();
                process.BeginErrorReadLine();

                bool result = process.WaitForExit(3 * 60 * 1000);

                if (!result)
                {
                    return(-10);
                }
            }
            catch (Exception e)
            {
                output.AppendLine(e.ToString());
                log.Error(e);
                return(-1);
            }
            finally
            {
                process.OutputDataReceived -= OnOutputDataReceived;
                process.ErrorDataReceived  -= OnOutputDataReceived;
            }

            ExecutionOutputText = output.ToString();

            return(process.ExitCode);
        }
        /// <summary>
        /// Finds script aliases in the provided assemblies.
        /// </summary>
        /// <param name="assemblies">The assemblies to find script aliases in.</param>
        /// <returns>The script aliases that were found.</returns>
        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);
                                }
#if !NETCORE
                                if (!string.IsNullOrEmpty(fileNotFoundException.FusionLog))
                                {
                                    _log.Debug("Fusion Log:");
                                    _log.Debug(fileNotFoundException.FusionLog);
                                }
#endif
                            }
                            _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);
        }
Beispiel #7
0
        /// <inheritdoc/>
        public IReadOnlyList <FilePath> InstallAddins(
            IReadOnlyCollection <PackageReference> addins,
            DirectoryPath installPath)
        {
            if (addins == null)
            {
                throw new ArgumentNullException(nameof(addins));
            }
            if (installPath == null)
            {
                throw new ArgumentNullException(nameof(installPath));
            }

            // Make the installation root absolute.
            installPath = installPath.MakeAbsolute(_environment);

            var result = new HashSet <FilePath>(PathComparer.Default);

            if (addins.Count > 0)
            {
                _log.Verbose("Installing addins...");
                foreach (var addin in addins)
                {
                    CheckPackageVersion(addin, "addin");

                    // Get the installer.
                    var installer = GetInstaller(addin, PackageType.Addin);
                    if (installer == null)
                    {
                        const string format  = "Could not find an installer for the '{0}' scheme.";
                        var          message = string.Format(CultureInfo.InvariantCulture, format, addin.Scheme);
                        throw new CakeException(message);
                    }

                    var assemblies = installer.Install(addin, PackageType.Addin, installPath);
                    if (assemblies.Count == 0)
                    {
                        const string format  = "Failed to install addin '{0}'.";
                        var          message = string.Format(CultureInfo.InvariantCulture, format, addin.Package);
                        throw new CakeException(message);
                    }

                    // Reference found assemblies.
                    foreach (var assembly in assemblies)
                    {
                        var assemblyPath = assembly.Path.MakeAbsolute(_environment);

                        try
                        {
                            assemblyPath = _environment.WorkingDirectory.GetRelativePath(assemblyPath);
                        }
                        catch (InvalidOperationException)
                        {
                            // Paths must share a common prefix.
                        }

                        _log.Debug("The addin {0} will reference {1}.", addin.Package, assemblyPath);

                        result.Add(assembly.Path);
                    }
                }
            }
            return(result.ToArray());
        }
Beispiel #8
0
 public void Debug(string message)
 {
     _cakeLogger.Debug(message);
 }
Beispiel #9
0
        public VersionHelper(ICakeEnvironment environment, ICakeLog log, ICakeArguments arguments,
                             IAppVeyorProvider appVeyorProvider, ITFBuildProvider azureProvider, IGlobber globber, IFileSystem fileSystem, IProcessRunner processRunner, IToolLocator tools)
        {
            _environment      = environment;
            _log              = log;
            _arguments        = arguments;
            _appVeyorProvider = appVeyorProvider;
            _azureProvider    = azureProvider;
            _globber          = globber;
            _fileSystem       = fileSystem;
            _processRunner    = processRunner;
            _tools            = tools;
            if (environment == null)
            {
                throw new ArgumentNullException(nameof(environment));
            }
            if (log == null)
            {
                throw new ArgumentNullException(nameof(log));
            }

            Configuration = environment.GetEnvironmentVariable("CONFIGURATION");
            if (string.IsNullOrWhiteSpace(Configuration))
            {
                Configuration = _arguments.HasArgument("configuration") ? _arguments.GetArgument("configuration") : "Release";
            }

            string envLogging = environment.GetEnvironmentVariable("LOGGINGLEVEL");

            if (!string.IsNullOrWhiteSpace(envLogging))
            {
                Verbosity loggingEnum;
                if (Enum.TryParse(envLogging, true, out loggingEnum))
                {
                    log.Verbosity = loggingEnum;
                    log.Information($"Logging Level: {loggingEnum}", Verbosity.Quiet);
                    if (IsAppVeyor)
                    {
                        _appVeyorProvider.AddInformationalMessage($"Logging set by LoggingLevel enviornment variable to {loggingEnum}");
                    }
                    _isDefaultLoggingLevel = false;
                }
                else
                {
                    string msg = $"Invalid logging level [{envLogging}].  Use {Verbosity.Quiet}, {Verbosity.Minimal}, {Verbosity.Normal}, {Verbosity.Verbose} or {Verbosity.Diagnostic}";
                    if (IsAppVeyor)
                    {
                        log.Warning(msg);
                    }
                    _appVeyorProvider.AddWarningMessage(msg);
                }
            }
            else
            {
                _isDefaultLoggingLevel = !arguments.HasArgument("verbosity");
            }

            if (_log.Verbosity > Verbosity.Normal)
            {
                var environmentVariables = environment.GetEnvironmentVariables();
                foreach (string key in environmentVariables.Keys)
                {
                    log.Verbose($"{key}:{environmentVariables[key]}");
                }
            }

            CommitMessageMatches = new MatchResult {
                Success = false
            };
            if (IsAppVeyor)
            {
                Branch             = _appVeyorProvider.Environment.Repository.Branch;
                CommitMessageShort = _appVeyorProvider.Environment.Repository.Commit.Message;
                var match = CommitMessageRegex.Match(_appVeyorProvider.Environment.Repository.Commit.ExtendedMessage);
                CommitMessageMatches = new MatchResult {
                    Success = match.Success, Groups = match.Groups
                };
                _log.Debug($"Branch:{Branch}");
                _log.Debug($"Commit Msg Short:{CommitMessageShort}");
                _log.Debug($"Commit Msg Extended:{_appVeyorProvider.Environment.Repository.Commit.ExtendedMessage}");
                _log.Debug($"Commit Message Cmd Match:{CommitMessageMatches.Success}");
                if (_log.Verbosity >= Verbosity.Verbose && CommitMessageMatches.Success)
                {
                    _log.Debug("RegEx Group Matches");
                    foreach (string groupName in CommitMessageRegex.GetGroupNames())
                    {
                        _log.Debug($"{groupName} : {CommitMessageMatches.Groups[groupName].Value}");
                    }
                }
            }
            if (IsAzureDevops)
            {
                Branch = _azureProvider.Environment.Repository.Branch;
                //CommitMessageShort = _azureProvider.Environment.Repository.Commit.Message;
                //var match = CommitMessageRegex.Match(_azureProvider.Environment.Repository.Commit.ExtendedMessage);
                //CommitMessageMatches = new MatchResult { Success = match.Success, Groups = match.Groups };
                //_log.Debug($"Branch:{Branch}");
                //_log.Debug($"Commit Msg Short:{CommitMessageShort}");
                //_log.Debug($"Commit Msg Extended:{_appVeyorProvider.Environment.Repository.Commit.ExtendedMessage}");
                //_log.Debug($"Commit Message Cmd Match:{CommitMessageMatches.Success}");
                //if (_log.Verbosity >= Verbosity.Verbose && CommitMessageMatches.Success)
                //{
                //    _log.Debug("RegEx Group Matches");
                //    foreach (string groupName in CommitMessageRegex.GetGroupNames())
                //    {
                //        _log.Debug($"{groupName} : {CommitMessageMatches.Groups[groupName].Value}");
                //    }
                //}
            }
        }
Beispiel #10
0
        /// <summary>
        /// Deploys the content of a website
        /// </summary>
        /// <param name="settings">The deployment settings.</param>
        /// <returns>The <see cref="DeploymentChangeSummary"/> that was applied during the deployment.</returns>
        public DeploymentChangeSummary Deploy(DeploySettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (settings.SourcePath == null)
            {
                throw new ArgumentNullException("settings.SourcePath");
            }



            DeploymentBaseOptions sourceOptions = new DeploymentBaseOptions();
            DeploymentBaseOptions destOptions   = this.GetBaseOptions(settings);

            FilePath sourcePath = settings.SourcePath.MakeAbsolute(_Environment);
            string   destPath   = settings.SiteName;

            destOptions.TraceLevel = settings.TraceLevel;
            destOptions.Trace     += OnTraceEvent;

            DeploymentWellKnownProvider sourceProvider = DeploymentWellKnownProvider.ContentPath;
            DeploymentWellKnownProvider destProvider   = DeploymentWellKnownProvider.Auto;



            //If a target path was specified, it could be virtual or physical
            if (settings.DestinationPath != null)
            {
                if (System.IO.Path.IsPathRooted(settings.DestinationPath.FullPath))
                {
                    // If it's rooted (e.g. d:\home\site\foo), use DirPath
                    sourceProvider = DeploymentWellKnownProvider.DirPath;
                    destProvider   = DeploymentWellKnownProvider.DirPath;

                    destPath = settings.DestinationPath.FullPath;
                }
                else
                {
                    // It's virtual, so append it to what we got from the publish profile
                    destPath += "/" + settings.DestinationPath.FullPath;
                }
            }
            //When a SiteName is given but no DestinationPath
            else if (!String.IsNullOrWhiteSpace(settings.SiteName))
            {
                //use ContentPath so it gets deployed to the Path of the named website in IIS
                //which is the same behaviour as in Visual Studio
                destProvider = DeploymentWellKnownProvider.ContentPath;
            }



            //If the content path is a zip file, use the Package provider
            string extension = sourcePath.GetExtension();

            if (extension != null && extension.Equals(".zip", StringComparison.OrdinalIgnoreCase))
            {
                // For some reason, we can't combine a zip with a physical target path
                if (destProvider == DeploymentWellKnownProvider.DirPath)
                {
                    throw new Exception("A source zip file can't be used with a physical target path");
                }

                sourceProvider = DeploymentWellKnownProvider.Package;
            }

            // If a parameters file was specified then read the file in and add the parameters
            if (settings.ParametersFilePath != null)
            {
                FilePath parametersFile = settings.ParametersFilePath.MakeAbsolute(_Environment);
                if (System.IO.File.Exists(parametersFile.FullPath))
                {
                    System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
                    doc.Load(parametersFile.FullPath);

                    System.Xml.XmlNodeList nodes = doc.SelectNodes("/parameters/setParameter");
                    foreach (System.Xml.XmlElement node in nodes)
                    {
                        settings.AddParameter(node.GetAttribute("name"), node.GetAttribute("value"));
                    }
                }
            }


            //Sync Options
            DeploymentSyncOptions syncOptions = new DeploymentSyncOptions
            {
                DoNotDelete = !settings.Delete,
                WhatIf      = settings.WhatIf,
                UseChecksum = settings.UseChecksum
            };

            if (settings.UseAppOffline)
            {
                AddRule(syncOptions, "appOffline");
            }

            // Add SkipRules
            foreach (var rule in settings.SkipRules)
            {
                syncOptions.Rules.Add(new DeploymentSkipRule(rule.Name, rule.SkipAction, rule.ObjectName, rule.AbsolutePath, rule.XPath));
            }

            //Deploy
            _Log.Debug(Verbosity.Normal, "Deploying Website...");
            _Log.Debug(Verbosity.Normal, String.Format("-siteName '{0}'", settings.SiteName));
            _Log.Debug(Verbosity.Normal, String.Format("-destination '{0}'", settings.PublishUrl));
            _Log.Debug(Verbosity.Normal, String.Format("-source '{0}'", sourcePath.FullPath));
            _Log.Debug("");

            using (var deploymentObject = DeploymentManager.CreateObject(sourceProvider, sourcePath.FullPath, sourceOptions))
            {
                foreach (var kv in settings.Parameters)
                {
                    if (deploymentObject.SyncParameters.Contains(kv.Key))
                    {
                        deploymentObject.SyncParameters[kv.Key].Value = kv.Value;
                    }
                    else
                    {
                        deploymentObject.SyncParameters.Add(new DeploymentSyncParameter(kv.Key, kv.Key, "", "")
                        {
                            Value = kv.Value
                        });
                    }
                }

                return(deploymentObject.SyncTo(destProvider, destPath, destOptions, syncOptions));
            }
        }
Beispiel #11
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(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 installedTools = GetInstalledTools(toolLocation);

            _log.Debug("Checking for tool: {0}", package.Package.ToLowerInvariant());

            var installedTool = installedTools.FirstOrDefault(t => string.Equals(t.Id, package.Package, StringComparison.InvariantCultureIgnoreCase));

            if (installedTool != null)
            {
                // The tool is already installed, so need to check if requested version is the same as
                // what is already installed
                string requestedVersion = null;

                if (package.Parameters.ContainsKey("version"))
                {
                    requestedVersion = package.Parameters["version"].First();
                }

                if (requestedVersion == null)
                {
                    _log.Warning("Tool {0} is already installed, and no specific version has been requested via pre-processor directive, so leaving current version installed.", package.Package);
                }
                else if (requestedVersion.ToLowerInvariant() != installedTool.Version.ToLowerInvariant())
                {
                    _log.Warning("Tool {0} is already installed, but a different version has been requested.  Uninstall/install will now be performed...", package.Package);
                    RunDotNetTool(package, toolsFolderDirectoryPath, DotNetToolOperation.Uninstall);
                    RunDotNetTool(package, toolsFolderDirectoryPath, DotNetToolOperation.Install);
                }
                else
                {
                    _log.Information("Tool {0} is already installed, with required version.", package.Package);
                }
            }
            else
            {
                // The tool isn't already installed, go ahead and install it
                RunDotNetTool(package, toolsFolderDirectoryPath, DotNetToolOperation.Install);
            }

            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);
        }
Beispiel #12
0
 /// <summary>
 /// Writes a debug message to the log using the specified string value.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="value">The value.</param>
 public static void Debug(this ICakeLog log, string value)
 {
     log.Debug("{0}", value);
 }
Beispiel #13
0
 /// <summary>
 /// Writes a debug message to the log using the specified value.
 /// </summary>
 /// <param name="log">The log.</param>
 /// <param name="value">The value.</param>
 public static void Debug(this ICakeLog log, object value)
 {
     log.Debug("{0}", value);
 }
 public void Debug(string message)
 {
     _cakeLogger?.Debug(message);
     _serilogLogger?.Debug(message);
 }
Beispiel #15
0
 public void LogDebug(string data) => _log.Debug(data);
Beispiel #16
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}", taskName);

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

                        // Is the run method overridden?
                        if (task.IsRunOverridden(context))
                        {
                            cakeTask.Does(task.RunAsync);
                        }

                        // Is the criteria method overridden?
                        if (task.IsShouldRunOverridden(context))
                        {
                            cakeTask.WithCriteria(task.ShouldRun);
                        }

                        // Continue on error?
                        if (task.IsContinueOnError())
                        {
                            cakeTask.ContinueOnError();
                        }

                        // Is the on error method overridden?
                        if (task.IsOnErrorOverridden(context))
                        {
                            cakeTask.OnError(exception => task.OnError(exception, context));
                        }

                        // Is the finally method overridden?
                        if (task.IsFinallyOverridden(context))
                        {
                            cakeTask.Finally(() => task.Finally(context));
                        }

                        // 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}' is not a valid task.");
                            }
                            cakeTask.IsDependentOn(dependencyName);
                        }
                    }
                }
            }

            if (lifetime != null)
            {
                _log.Debug("Registering lifetime: {0}", lifetime.GetType().Name);

                if (lifetime.IsSetupOverridden(context))
                {
                    engine.RegisterSetupAction(info => lifetime.Setup(context));
                }
                if (lifetime.IsTeardownOverridden(context))
                {
                    engine.RegisterTeardownAction(info => lifetime.Teardown(context, info));
                }
            }

            if (taskLifetime != null)
            {
                _log.Debug("Registering task lifetime: {0}", taskLifetime.GetType().Name);

                if (taskLifetime.IsSetupOverridden(context))
                {
                    engine.RegisterTaskSetupAction(info => taskLifetime.Setup(context, info));
                }

                if (taskLifetime.IsTeardownOverridden(context))
                {
                    engine.RegisterTaskTeardownAction(info => taskLifetime.Teardown(context, info));
                }
            }
        }
Beispiel #17
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(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);
            var createdDirectory = false;

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

            // 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.
            if (!InstallPackage(package, path))
            {
                _log.Warning("An error occured while installing package {0}.", package.Package);
                if (createdDirectory)
                {
                    _log.Debug("Deleting package directory {0}...", path);
                    root.Delete(true);
                    return(Array.Empty <IFile>());
                }
            }

            // 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);
        }
        /// <summary>
        /// Deploys the content of a website
        /// </summary>
        /// <param name="settings">The deployment settings.</param>
        /// <returns>The <see cref="DeploymentChangeSummary"/> that was applied during the deployment.</returns>
        public DeploymentChangeSummary Deploy(DeploySettings settings)
        {
            if (settings == null)
            {
                throw new ArgumentNullException("settings");
            }
            if (settings.SourcePath == null)
            {
                throw new ArgumentNullException("settings.SourcePath");
            }



            DeploymentBaseOptions sourceOptions = new DeploymentBaseOptions();
            DeploymentBaseOptions destOptions   = this.GetBaseOptions(settings);

            FilePath sourcePath = settings.SourcePath.MakeAbsolute(_Environment);
            string   destPath   = settings.SiteName;

            destOptions.TraceLevel = settings.TraceLevel;
            destOptions.Trace     += OnTraceEvent;

            DeploymentWellKnownProvider sourceProvider = DeploymentWellKnownProvider.ContentPath;
            DeploymentWellKnownProvider destProvider   = DeploymentWellKnownProvider.Auto;



            //If a target path was specified, it could be virtual or physical
            if (settings.DestinationPath != null)
            {
                if (System.IO.Path.IsPathRooted(settings.DestinationPath.FullPath))
                {
                    // If it's rooted (e.g. d:\home\site\foo), use DirPath
                    sourceProvider = DeploymentWellKnownProvider.DirPath;
                    destProvider   = DeploymentWellKnownProvider.DirPath;

                    destPath = settings.DestinationPath.FullPath;
                }
                else
                {
                    // It's virtual, so append it to what we got from the publish profile
                    destPath += "/" + settings.DestinationPath.FullPath;
                }
            }
            //When a SiteName is given but no DestinationPath
            else if (!String.IsNullOrWhiteSpace(settings.SiteName))
            {
                //use ContentPath so it gets deployed to the Path of the named website in IIS
                //which is the same behaviour as in Visual Studio
                destProvider = DeploymentWellKnownProvider.ContentPath;
            }



            //If the content path is a zip file, use the Package provider
            string extension = sourcePath.GetExtension();

            if (extension != null && extension.Equals(".zip", StringComparison.OrdinalIgnoreCase))
            {
                // For some reason, we can't combine a zip with a physical target path
                if (destProvider == DeploymentWellKnownProvider.DirPath)
                {
                    throw new Exception("A source zip file can't be used with a physical target path");
                }

                sourceProvider = DeploymentWellKnownProvider.Package;
            }



            //Sync Options
            DeploymentSyncOptions syncOptions = new DeploymentSyncOptions
            {
                DoNotDelete = !settings.Delete,
                WhatIf      = settings.WhatIf
            };



            //Deploy
            _Log.Debug(Verbosity.Normal, "Deploying Website...");
            _Log.Debug(Verbosity.Normal, String.Format("-siteName '{0}'", settings.SiteName));
            _Log.Debug(Verbosity.Normal, String.Format("-destination '{0}'", settings.PublishUrl));
            _Log.Debug(Verbosity.Normal, String.Format("-source '{0}'", sourcePath.FullPath));
            _Log.Debug("");

            using (var deploymentObject = DeploymentManager.CreateObject(sourceProvider, sourcePath.FullPath, sourceOptions))
            {
                foreach (var kv in settings.Parameters)
                {
                    deploymentObject.SyncParameters[kv.Key].Value = kv.Value;
                }

                return(deploymentObject.SyncTo(destProvider, destPath, destOptions, syncOptions));
            }
        }
        public Assembly[] GetReferenceAssemblies()
        {
            IEnumerable <Assembly> TryGetReferenceAssemblies()
            {
                foreach (var reference in
#if NETCOREAPP3_1
                         Basic.Reference.Assemblies.NetCoreApp31.All)
#elif NET5_0
                         Basic.Reference.Assemblies.Net50.All)
#else
                         Basic.Reference.Assemblies.Net60.All)
#endif
                {
                    Assembly assembly;
                    try
                    {
                        assembly = Assembly.Load(System.IO.Path.GetFileNameWithoutExtension(reference.FilePath));
                    }
                    catch (Exception ex)
                    {
                        _log.Debug(log => log("Failed to load {0}\r\nException: {1}", reference.FilePath, ex));
                        continue;
                    }

                    if (assembly == null)
                    {
                        continue;
                    }

                    yield return(assembly);

                    foreach (var assemblyRefName in assembly.GetReferencedAssemblies())
                    {
                        if (assemblyRefName == null ||
                            assemblyRefName.Version == VersionZero)
                        {
                            continue;
                        }

                        Assembly assemblyRef;
                        try
                        {
                            assemblyRef = Assembly.Load(assemblyRefName);
                        }
                        catch (Exception ex)
                        {
                            _log.Debug(log => log("Failed to load {0}\r\nReference: {1}\r\n Exception: {2}", assemblyRefName, assembly, ex));
                            continue;
                        }

                        if (assemblyRef == null)
                        {
                            continue;
                        }

                        yield return(assemblyRef);
                    }
                }
            }

            return(TryGetReferenceAssemblies().ToArray());
        }