public void BuildPackage(string basePath, IList <string> includes, ManifestMetadata metadata, string outFolder, bool overwrite, bool verboseInfo)
        {
            var nugetPkgBuilder = new NuGet.Packaging.PackageBuilder();

            var manifestFiles = includes.Select(i => new ManifestFile {
                Source = i
            }).ToList();

            nugetPkgBuilder.PopulateFiles(basePath, manifestFiles);
            nugetPkgBuilder.Populate(metadata);

            if (verboseInfo)
            {
                foreach (var file in nugetPkgBuilder.Files)
                {
                    commandOutputProvider.Information($"Added file: {file.Path}");
                }
            }
            files.AddRange(nugetPkgBuilder.Files.Select(x => x.Path).ToArray());

            var filename = $"{metadata.Id}.{metadata.Version}.nupkg";
            var output   = Path.Combine(outFolder, filename);

            if (fileSystem.FileExists(output) && !overwrite)
            {
                throw new CommandException("The package file already exists and --overwrite was not specified");
            }

            commandOutputProvider.Information("Saving {Filename} to {OutFolder}...", filename, outFolder);

            fileSystem.EnsureDirectoryExists(outFolder);

            using (var outStream = fileSystem.OpenFile(output, FileMode.Create))
                nugetPkgBuilder.Save(outStream);
        }
Ejemplo n.º 2
0
        private static void LogDeploymentInfo(ICommandOutputProvider outputProvider, DeploymentResource deploymentItem, ReleaseResource release, ChannelResource channel,
                                              IDictionary <string, string> environmentsById, IDictionary <string, string> projectsById, IDictionary <string, string> tenantsById)
        {
            var nameOfDeploymentEnvironment = environmentsById[deploymentItem.EnvironmentId];
            var nameOfDeploymentProject     = projectsById[deploymentItem.ProjectId];

            outputProvider.Information(" - Project: {Project:l}", nameOfDeploymentProject);
            outputProvider.Information(" - Environment: {Environment:l}", nameOfDeploymentEnvironment);

            if (!string.IsNullOrEmpty(deploymentItem.TenantId))
            {
                var nameOfDeploymentTenant = tenantsById[deploymentItem.TenantId];
                outputProvider.Information(" - Tenant: {Tenant:l}", nameOfDeploymentTenant);
            }

            if (channel != null)
            {
                outputProvider.Information(" - Channel: {Channel:l}", channel.Name);
            }

            outputProvider.Information("\tCreated: {$Date:l}", deploymentItem.Created);

            // Date will have to be fetched from Tasks (they need to be loaded) it doesn't come down with the DeploymentResource
            //log.Information("   Date: {$Date:l}", deploymentItem.QueueTime);

            outputProvider.Information("\tVersion: {Version:l}", release.Version);
            outputProvider.Information("\tAssembled: {$Assembled:l}", release.Assembled);
            outputProvider.Information("\tPackage Versions: {PackageVersion:l}", GetPackageVersionsAsString(release.SelectedPackages));
            outputProvider.Information("\tRelease Notes: {ReleaseNotes:l}", GetReleaseNotes(release));
            outputProvider.Information(string.Empty);
        }
Ejemplo n.º 3
0
        public void BuildPackage(string basePath,
                                 IList <string> includes,
                                 ManifestMetadata metadata,
                                 string outFolder,
                                 bool overwrite,
                                 bool verboseInfo)
        {
            var filename = metadata.Id + "." + metadata.Version + ".zip";
            var output   = fileSystem.GetFullPath(Path.Combine(outFolder, filename));

            if (fileSystem.FileExists(output) && !overwrite)
            {
                throw new CommandException("The package file already exists and --overwrite was not specified");
            }

            commandOutputProvider.Information("Saving {Filename} to {OutFolder}...", filename, outFolder);

            fileSystem.EnsureDirectoryExists(outFolder);

            var basePathLength = fileSystem.GetFullPath(basePath).Length;

            using (var stream = fileSystem.OpenFile(output, FileAccess.Write))
                using (var archive = new ZipArchive(stream, ZipArchiveMode.Create))
                {
                    foreach (var pattern in includes)
                    {
                        commandOutputProvider.Debug("Adding files from {Path} matching pattern {Pattern}", basePath, pattern);
                        foreach (var file in PathResolver.PerformWildcardSearch(basePath, pattern))
                        {
                            var fullFilePath = fileSystem.GetFullPath(file);
                            if (string.Equals(fullFilePath, output, StringComparison.CurrentCultureIgnoreCase))
                            {
                                continue;
                            }

                            var relativePath = UseCrossPlatformDirectorySeparator(
                                fullFilePath.Substring(basePathLength).TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));

                            if (verboseInfo)
                            {
                                commandOutputProvider.Information($"Added file: {relativePath}");
                            }

                            files.Add(relativePath);

                            var entry = archive.CreateEntry(relativePath, compressionLevel);
                            UpdateLastWriteTime(file, entry);

                            using (var entryStream = entry.Open())
                                using (var sourceStream = File.OpenRead(file))
                                {
                                    sourceStream.CopyTo(entryStream);
                                }
                        }
                    }
                }
        }
Ejemplo n.º 4
0
        public static void ServiceMessage(this ICommandOutputProvider commandOutputProvider, string messageName, string value)
        {
            if (!serviceMessagesEnabled)
            {
                return;
            }

            if (buildEnvironment == AutomationEnvironment.TeamCity)
            {
                commandOutputProvider.Information("##teamcity[{MessageName:l} {Value:l}]", messageName, EscapeValue(value));
            }
            else
            {
                commandOutputProvider.Information("{MessageName:l} {Value:l}", messageName, EscapeValue(value));
            }
        }
Ejemplo n.º 5
0
        public static void TfsServiceMessage(this ICommandOutputProvider commandOutputProvider, string serverBaseUrl, ProjectResource project, ReleaseResource release)
        {
            if (!serviceMessagesEnabled)
            {
                return;
            }
            if (buildEnvironment == AutomationEnvironment.AzureDevOps || buildEnvironment == AutomationEnvironment.NoneOrUnknown)
            {
                var workingDirectory = Environment.GetEnvironmentVariable("SYSTEM_DEFAULTWORKINGDIRECTORY") ?? new FileInfo(typeof(CommandOutputProviderExtensionMethods).GetTypeInfo().Assembly.Location).DirectoryName;
                var selflink         = new Uri(new Uri(serverBaseUrl), release.Links["Web"].AsString());
                var markdown         = $"[Release {release.Version} created for '{project.Name}']({selflink})";
                var markdownFile     = Path.Combine(workingDirectory, Guid.NewGuid() + ".md");

                try
                {
                    File.WriteAllText(markdownFile, markdown);
                }
                catch (UnauthorizedAccessException uae)
                {
                    throw new UnauthorizedAccessException($"Could not write the TFS service message file '{markdownFile}'. Please make sure the SYSTEM_DEFAULTWORKINGDIRECTORY environment variable is set to a writeable directory. If this command is not being run on a build agent, omit the --enableServiceMessages parameter.", uae);
                }

                commandOutputProvider.Information("##vso[task.addattachment type=Distributedtask.Core.Summary;name=Octopus Deploy;]{MarkdownFile:l}", markdownFile);
            }
        }
Ejemplo n.º 6
0
        public static void ServiceMessage(this ICommandOutputProvider commandOutputProvider, string messageName, IDictionary <string, string> values)
        {
            if (!serviceMessagesEnabled)
            {
                return;
            }

            var valueSummary = string.Join(" ", values.Select(v => $"{v.Key}='{EscapeValue(v.Value)}'"));

            if (buildEnvironment == AutomationEnvironment.TeamCity)
            {
                commandOutputProvider.Information("##teamcity[{MessageName:l} {ValueSummary:l}]", messageName, valueSummary);
            }
            else
            {
                commandOutputProvider.Information("{MessageName:l} {ValueSummary:l}", messageName, valueSummary);
            }
        }
Ejemplo n.º 7
0
        void RenderToVSTS(ActivityElement element, ICommandOutputProvider commandOutputProvider, string indent)
        {
            if (!IsPrintable(element))
            {
                return;
            }

            commandOutputProvider.Information("{Indent:l}         {Status:l}: {Name:l}", indent, element.Status, element.Name);

            foreach (var logEntry in element.LogElements)
            {
                commandOutputProvider.Information("{Category,-8:l}{Indent:l}   {Message:l}", logEntry.Category, logEntry.MessageText);
            }

            foreach (var child in element.Children)
            {
                RenderToVSTS(child, commandOutputProvider, indent + "  ");
            }
        }
Ejemplo n.º 8
0
    public virtual void Install(bool dryRun)
    {
        commandOutputProvider.Information($"Installing scripts in {ProfileLocation}");
        var tempOutput = new StringBuilder();

        if (fileSystem.FileExists(ProfileLocation))
        {
            var profileText = fileSystem.ReadAllText(ProfileLocation);
            if (!dryRun)
            {
                if (profileText.Contains(AllShellsPrefix) || profileText.Contains(AllShellsSuffix) || profileText.Contains(ProfileScript))
                {
                    if (!profileText.Contains(ProfileScript))
                    {
                        var message =
                            $"Looks like command line completion is already installed, but points to a different executable.{Environment.NewLine}" +
                            $"Please manually edit the file {ProfileLocation} to remove the existing auto complete script and then re-install.";
                        throw new CommandException(message);
                    }

                    commandOutputProvider.Information("Looks like command line completion is already installed. Nothing to do.");
                    return;
                }

                var backupPath = ProfileLocation + ".orig";
                commandOutputProvider.Information($"Backing up the existing profile to {backupPath}");
                fileSystem.CopyFile(ProfileLocation, backupPath);
            }

            commandOutputProvider.Information($"Updating profile at {ProfileLocation}");
            tempOutput.AppendLine(profileText);
        }
        else
        {
            commandOutputProvider.Information($"Creating profile at {ProfileLocation}");
            fileSystem.EnsureDirectoryExists(Path.GetDirectoryName(ProfileLocation));
        }

        tempOutput.AppendLine(AllShellsPrefix);
        tempOutput.AppendLine(ProfileScript);
        tempOutput.AppendLine(AllShellsSuffix);

        if (dryRun)
        {
            commandOutputProvider.Warning("Preview of script changes: ");
            commandOutputProvider.Information(tempOutput.ToString());
            commandOutputProvider.Warning("Preview of script changes finished. ");
        }
        else
        {
            fileSystem.OverwriteFile(ProfileLocation, tempOutput.ToString());
            commandOutputProvider.Warning("All Done! Please reload your shell or dot source your profile to get started! Use the <tab> key to autocomplete.");
        }
    }
Ejemplo n.º 9
0
        void RenderToTeamCity(ActivityElement element, ICommandOutputProvider commandOutputProvider)
        {
            if (!IsPrintable(element))
            {
                return;
            }

            var blockName = element.Status + ": " + element.Name;

            commandOutputProvider.ServiceMessage("blockOpened", new { name = blockName });

            foreach (var logEntry in element.LogElements)
            {
                var lines = logEntry.MessageText.Split('\n').Where(l => !string.IsNullOrWhiteSpace(l)).ToArray();
                foreach (var line in lines)
                {
                    // If a customer writes custom TeamCity service messages in their scripts we should output it as-is,
                    // otherwise they won't be treated as a service message in TeamCity.
                    // https://github.com/OctopusDeploy/OctopusCLI/issues/7
                    var isAlreadyTeamCityServiceMessage = line.StartsWith("##teamcity", StringComparison.OrdinalIgnoreCase);
                    if (isAlreadyTeamCityServiceMessage)
                    {
                        commandOutputProvider.Information(line);
                    }
                    else
                    {
                        commandOutputProvider.ServiceMessage("message", new { text = line, status = ConvertToTeamCityMessageStatus(logEntry.Category) });
                    }
                }
            }

            foreach (var child in element.Children)
            {
                RenderToTeamCity(child, commandOutputProvider);
            }

            commandOutputProvider.ServiceMessage("blockClosed", new { name = blockName });
        }
        static void LogDeploymentInfo(ICommandOutputProvider commandOutputProvider,
                                      DashboardItemResource dashboardItem,
                                      ReleaseResource release,
                                      ChannelResource channel,
                                      IDictionary <string, string> environmentsById,
                                      IDictionary <string, string> projectedById,
                                      IDictionary <string, string> tenantsById)
        {
            var nameOfDeploymentEnvironment = environmentsById[dashboardItem.EnvironmentId];
            var nameOfDeploymentProject     = projectedById[dashboardItem.ProjectId];

            commandOutputProvider.Information(" - Project: {Project:l}", nameOfDeploymentProject);
            commandOutputProvider.Information(" - Environment: {Environment:l}", nameOfDeploymentEnvironment);
            if (!string.IsNullOrEmpty(dashboardItem.TenantId))
            {
                var nameOfDeploymentTenant = GetNameOfDeploymentTenant(tenantsById, dashboardItem.TenantId);
                commandOutputProvider.Information(" - Tenant: {Tenant:l}", nameOfDeploymentTenant);
            }

            if (channel != null)
            {
                commandOutputProvider.Information(" - Channel: {Channel:l}", channel.Name);
            }

            commandOutputProvider.Information("   Date: {$Date:l}", dashboardItem.QueueTime);
            commandOutputProvider.Information("   Duration: {Duration:l}", dashboardItem.Duration);

            if (dashboardItem.State == TaskState.Failed)
            {
                commandOutputProvider.Error("   State: {$State:l}", dashboardItem.State);
            }
            else
            {
                commandOutputProvider.Information("   State: {$State:l}", dashboardItem.State);
            }

            commandOutputProvider.Information("   Version: {Version:l}", release.Version);
            commandOutputProvider.Information("   Assembled: {$Assembled:l}", release.Assembled);
            commandOutputProvider.Information("   Package Versions: {PackageVersion:l}", GetPackageVersionsAsString(release.SelectedPackages));
            commandOutputProvider.Information("   Release Notes: {ReleaseNotes:l}", GetReleaseNotes(release));
            commandOutputProvider.Information(string.Empty);
        }
Ejemplo n.º 11
0
        async Task WaitForExecutionToComplete(
            IReadOnlyCollection <IExecutionResource> resources,
            bool showProgress,
            bool noRawLog,
            string rawLogFile,
            bool cancelOnTimeout,
            TimeSpan deploymentStatusCheckSleepCycle,
            TimeSpan deploymentTimeout,
            Func <IExecutionResource, Task> guidedFailureWarningGenerator,
            string alias
            )
        {
            var getTasks        = resources.Select(dep => repository.Tasks.Get(dep.TaskId));
            var deploymentTasks = await Task.WhenAll(getTasks).ConfigureAwait(false);

            if (showProgress && resources.Count > 1)
            {
                commandOutputProvider.Information("Only progress of the first task ({Task:l}) will be shown", deploymentTasks.First().Name);
            }

            try
            {
                commandOutputProvider.Information($"Waiting for {{NumberOfTasks}} {alias}(s) to complete....", deploymentTasks.Length);
                await repository.Tasks.WaitForCompletion(deploymentTasks.ToArray(), deploymentStatusCheckSleepCycle.Seconds, deploymentTimeout, PrintTaskOutput).ConfigureAwait(false);

                var failed = false;
                foreach (var deploymentTask in deploymentTasks)
                {
                    var updated = await repository.Tasks.Get(deploymentTask.Id).ConfigureAwait(false);

                    if (updated.FinishedSuccessfully)
                    {
                        commandOutputProvider.Information("{Task:l}: {State}", updated.Description, updated.State);
                    }
                    else
                    {
                        commandOutputProvider.Error("{Task:l}: {State}, {Error:l}", updated.Description, updated.State, updated.ErrorMessage);
                        failed = true;

                        if (noRawLog)
                        {
                            continue;
                        }

                        try
                        {
                            var raw = await repository.Tasks.GetRawOutputLog(updated).ConfigureAwait(false);

                            if (!string.IsNullOrEmpty(rawLogFile))
                            {
                                File.WriteAllText(rawLogFile, raw);
                            }
                            else
                            {
                                commandOutputProvider.Error(raw);
                            }
                        }
                        catch (Exception ex)
                        {
                            commandOutputProvider.Error(ex, "Could not retrieve the raw task log for the failed task.");
                        }
                    }
                }

                if (failed)
                {
                    throw new CommandException($"One or more {alias} tasks failed.");
                }

                commandOutputProvider.Information("Done!");
            }
            catch (TimeoutException e)
            {
                commandOutputProvider.Error(e.Message);

                await CancelExecutionOnTimeoutIfRequested(deploymentTasks, cancelOnTimeout, alias).ConfigureAwait(false);

                var guidedFailureDeployments =
                    from d in resources
                    where d.UseGuidedFailure
                    select d;
                if (guidedFailureDeployments.Any())
                {
                    commandOutputProvider.Warning($"One or more {alias} are using guided failure. Use the links below to check if intervention is required:");
                    foreach (var guidedFailureDeployment in guidedFailureDeployments)
                    {
                        await guidedFailureWarningGenerator(guidedFailureDeployment);
                    }
                }

                throw new CommandException(e.Message);
            }
        }