Ejemplo n.º 1
0
        private IReadOnlyCollection <IFile> GetToolFiles(PackageReference package, bool isGlobal = false)
        {
            DirectoryPath modulesPath;

            if (isGlobal)
            {
                modulesPath = GetGlobalPrefix()?.Combine("./bin/") ?? "./bin";
                _log.Verbose($"Found global npm path at: {modulesPath.FullPath}");
                _log.Verbose(
                    "Using global npm binaries folder: installation may succeed without binaries being installed");
            }
            else
            {
                modulesPath = GetLocalInstallPath(package);
                _log.Verbose("Using local install path: " + modulesPath?.FullPath);
            }

            if (modulesPath == null || !_fileSystem.GetDirectory(modulesPath).Exists)
            {
                throw new System.IO.DirectoryNotFoundException("Could not determine install path!");
            }

            var installRoot = _fileSystem.GetDirectory(modulesPath);

            if (installRoot.Exists)
            {
                return(new ReadOnlyCollection <IFile>(installRoot.GetFiles("*", SearchScope.Recursive).ToList()));
            }

            return(new ReadOnlyCollection <IFile>(new List <IFile>()));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Runs the specified target.
        /// </summary>
        /// <param name="target">The target to run.</param>
        /// <returns>The resulting report.</returns>
        public CakeReport RunTarget(string target)
        {
            var graph = CakeGraphBuilder.Build(_tasks);

            // Make sure target exist.
            if (!graph.Exist(target))
            {
                const string format = "The target '{0}' was not found.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, format, target));
            }

            var stopWatch = new Stopwatch();
            var report    = new CakeReport();

            foreach (var task in graph.Traverse(target))
            {
                var taskNode = _tasks.FirstOrDefault(x => x.Name.Equals(task, StringComparison.OrdinalIgnoreCase));
                Debug.Assert(taskNode != null, "Node should not be null.");

                if (ShouldTaskExecute(taskNode))
                {
                    _log.Verbose("Executing task: {0}", taskNode.Name);

                    ExecuteTask(stopWatch, taskNode, report);

                    _log.Verbose("Finished executing task: {0}", taskNode.Name);
                }
            }

            return(report);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Starts an Amazon EBS-backed AMI that you've previously stopped. Instances that use Amazon EBS volumes as their root devices can be quickly stopped
        /// and started. When an instance is stopped, the compute resources are released and you are not billed for hourly instance usage. However, your root partition
        /// Amazon EBS volume remains, continues to persist your data, and you are charged for Amazon EBS volume usage. You can restart your instance at any time. Each
        ///  time you transition an instance from stopped to started, Amazon EC2 charges a full instance hour, even if transitions happen multiple times within a single hour.
        /// </summary>
        /// <param name="instances">A list of instance IDs to be started.</param>
        /// <param name="settings">The <see cref="EC2Settings"/> used during the request to AWS.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async Task <bool> StartInstances(IList <string> instances, EC2Settings settings, CancellationToken cancellationToken = default(CancellationToken))
        {
            if ((instances == null) || (instances.Count == 0))
            {
                throw new ArgumentNullException("instances");
            }



            //Create Request
            AmazonEC2Client       client  = this.CreateClient(settings);
            StartInstancesRequest request = new StartInstancesRequest();

            foreach (string instance in instances)
            {
                request.InstanceIds.Add(instance);
            }



            //Check Response
            StartInstancesResponse response = await client.StartInstancesAsync(request, cancellationToken);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                _Log.Verbose("Successfully started instances '{0}'", string.Join(",", instances));
                return(true);
            }
            else
            {
                _Log.Error("Failed to start instances '{0}'", string.Join(",", instances));
                return(false);
            }
        }
Ejemplo n.º 4
0
        public void Add(DirectoryPath value, PathSettings pathSettings)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value), "Value to add to path is null.");
            }

            if (pathSettings == null)
            {
                throw new ArgumentNullException(nameof(pathSettings), "Path settings is null.");
            }

            var pathTarget = pathSettings
                             .Target
                             .GetValueOrDefault(PathTarget.User);

            var parts = _environmentWrapper
                        .GetEnvironmentVariable("PATH", pathTarget, string.Empty)
                        .Split(';')
                        .Where(x => !string.IsNullOrWhiteSpace(x))
                        .ToList();

            if (parts.Contains(value.FullPath))
            {
                _log.Verbose($"PATH already contains '{value}'.");
                return;
            }

            parts.Add(value.FullPath);
            _environmentWrapper.SetEnvironmentVariable("PATH", string.Join(";", parts), pathTarget);
            _log.Verbose($"Added '{value}' to PATH.");
        }
Ejemplo n.º 5
0
        private Assembly AssemblyResolve(object sender, ResolveEventArgs args)
        {
            var name = new AssemblyName(args.Name);

            // Prevent recursion from the Assembly.Load() call inside
            if (_resolvedNames.Add(name.Name))
            {
                _log.Verbose($"Resolving assembly {args.Name}");
                try
                {
                    var assembly = AppDomain.CurrentDomain.GetAssemblies()
                                   .FirstOrDefault(x => !x.IsDynamic && x.GetName().Name == name.Name)
                                   ?? Assembly.Load(name.Name);
                    if (assembly != null)
                    {
                        _log.Verbose($"Resolved {name.Name} by assembly {assembly.FullName}");
                    }
                    else
                    {
                        _log.Verbose($"Assembly {name.Name} not resolved");
                    }
                    return(assembly);
                }
                catch (Exception ex)
                {
                    _log.Verbose($"Exception while resolving assembly {name.Name}: {ex.Message}");
                }
            }
            return(null);
        }
        public void CreateIso(string inputPath, string outputPath, string volumeIdentifier)
        {
            _log.Verbose($"Creating ISO from directory {inputPath}");
            var builder = new CDBuilder
            {
                UseJoliet        = true,
                VolumeIdentifier = volumeIdentifier ?? "CAKE_ISO"
            };

            foreach (var entry in Directory.GetFileSystemEntries(inputPath, "*", SearchOption.AllDirectories))
            {
                var fileInfo = new FileInfo(entry);
                if ((fileInfo.Attributes & FileAttributes.Directory) != 0)
                {
                    _log.Verbose($"Creating directory: {Path.GetFullPath(entry).Replace(inputPath, "")}");
                    builder.AddDirectory(Path.GetFullPath(entry).Replace(inputPath, ""));
                }
                else
                {
                    _log.Verbose($"Creating file: {Path.GetFullPath(entry).Replace(inputPath, "")}");
                    builder.AddFile(Path.GetFullPath(entry).Replace(inputPath, ""), entry);
                }
            }
            builder.Build(outputPath);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Uploads a file.
        /// </summary>
        /// <param name="serverUri">The URI for the FTP server.</param>
        /// <param name="uploadFile">The file to upload.</param>
        /// <param name="username">The FTP username.</param>
        /// <param name="password">The FTP password.</param>
        public void UploadFile(Uri serverUri, IFile uploadFile, string username, string password)
        {
            // Adding verbose logging for the URI being used.
            _log.Verbose("Uploading file to {0}", serverUri);
            // Creating the request
            var request = (FtpWebRequest)WebRequest.Create(serverUri);

            request.Method      = WebRequestMethods.Ftp.UploadFile;
            request.Credentials = new NetworkCredential(username, password);

            request.ContentLength = uploadFile.Length;

            using (var stream = new FileStream(uploadFile.Path.FullPath, FileMode.Open, FileAccess.Read))
            {
                var requestStream = request.GetRequestStream();
                stream.CopyTo(requestStream);
                requestStream.Close();

                // Getting the response from the FTP server.
                var response = (FtpWebResponse)request.GetResponse();

                // Logging if it completed and the description of the status returned.
                _log.Information("File upload complete, status {0}", response.StatusDescription);
                response.Close();
            }
        }
Ejemplo n.º 8
0
        private void Install(DirectoryPath root)
        {
            if (root == null)
            {
                throw new ArgumentNullException("root");
            }

            var installRoot = root.Combine(Guid.NewGuid().ToString().Replace("-", string.Empty));

            // Install package.
            _log.Verbose("Installing package...");
            var repository     = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2");
            var packageManager = new PackageManager(repository, installRoot.FullPath);

            packageManager.InstallPackage("Roslyn.Compilers.CSharp", new SemanticVersion(new Version(1, 2, 20906, 2)), false, true);

            // Copy files
            _log.Verbose("Copying files...");
            foreach (var path in _paths)
            {
                var source      = _fileSystem.GetFile(installRoot.CombineWithFilePath(path));
                var destination = _fileSystem.GetFile(root.CombineWithFilePath(path.GetFilename()));

                _log.Information("Copying {0}...", source.Path.GetFilename());

                if (!destination.Exists)
                {
                    source.Copy(destination.Path, true);
                }
            }

            // Delete the install directory.
            _log.Verbose("Deleting installation directory...");
            _fileSystem.GetDirectory(installRoot).Delete(true);
        }
        /// <summary>
        /// Returns the build definition for the <paramref name="settings"/>.
        /// </summary>
        /// <param name="log">The Cake log context.</param>
        /// <param name="settings">Settings for accessing AzureDevOps.</param>
        /// <returns>The build definition for the BuildDefinitionName on <paramref name="settings"/>.
        /// <c>null</c> if the BuildDefinitionName was not set or no build definition was found.</returns>
        private static AzureDevOpsBuildDefinition GetBuildDefinition(
            ICakeLog log,
            AzureDevOpsBuildsSettings settings)
        {
            log.NotNull(nameof(log));
            settings.NotNull(nameof(settings));

            var buildDefinitions =
                AzureDevOpsBuildsDefinitionHelper
                .GetAzureDevOpsBuildDefinitions(
                    log,
                    settings);

            var buildDefinition =
                buildDefinitions
                .SingleOrDefault(x => x.Name.Equals(settings.BuildDefinitionName, StringComparison.InvariantCultureIgnoreCase));

            if (buildDefinition == null)
            {
                log.Verbose(
                    "Build definition '{0}' not found",
                    settings.BuildDefinitionName);
            }

            log.Verbose(
                "Build definition '{0}' found",
                settings.BuildDefinitionName);

            return(buildDefinition);
        }
Ejemplo n.º 10
0
        public void UploadFile(Uri serverUri, IFile uploadFile, string username, string password)
        {
            // Adding verbose logging for the URI being used.
            _log.Verbose("Uploading file to {0}", serverUri);
            // Creating the request
            var request = (FtpWebRequest)WebRequest.Create(serverUri);

            request.Method = WebRequestMethods.Ftp.UploadFile;

            // Adding verbose logging for credentials used.
            _log.Verbose("Using the following credentials {0}, {1}", username, password);
            request.Credentials = new NetworkCredential(username, password);

            using (var streamReader = new StreamReader(uploadFile.OpenRead())) {
                // Get the file contents.
                var fileContents = Encoding.UTF8.GetBytes(streamReader.ReadToEnd());
                request.ContentLength = fileContents.Length;

                // Writing the file to the request stream.
                var requestStream = request.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();

                // Getting the response from the FTP server.
                var response = (FtpWebResponse)request.GetResponse();

                // Logging if it completed and the description of the status returned.
                _log.Information("File upload complete, status {0}", response.StatusDescription);
                response.Close();
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Does the actual bootstrapping.
        /// </summary>
        /// <param name="version">The Version to download.</param>
        internal void Bootstrap(GradleVersionIdentifier version)
        {
            var versionInfo = GetGradleVersion(version)
                              .ConfigureAwait(false)
                              .GetAwaiter()
                              .GetResult();

            _log.Verbose($"Current gradle version is {versionInfo.Version}");
            var toolsFolder = _fileSystem.GetDirectory(
                _config.GetToolPath(_environment.WorkingDirectory, _environment));

            if (!toolsFolder.Exists)
            {
                toolsFolder.Create();
            }

            var gradleInstallFolder = toolsFolder.Path.Combine($"gradle-{versionInfo.Version}");

            if (_fileSystem.GetDirectory(gradleInstallFolder).Exists)
            {
                _log.Debug("Gradle tool directory exists. Not downloading.");
                return;
            }

            // download gradle
            var gradleZip = DownloadGradle(versionInfo.DownloadUrl, toolsFolder.Path)
                            .ConfigureAwait(false)
                            .GetAwaiter()
                            .GetResult();

            UnzipGradle(gradleZip, toolsFolder.Path);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Installs a Topshelf windows service
        /// </summary>
        /// <param name="filePath">The file path of the Topshelf executable to install.</param>
        /// <param name="settings">The <see cref="TopshelfSettings"/> used to install the service.</param>
        public void InstallService(FilePath filePath, TopshelfSettings settings = null)
        {
            if (filePath == null)
            {
                throw new ArgumentNullException("filePath");
            }

            this.ExecuteProcess(filePath, this.GetInstallArguments(settings), settings.Timeout);

            _Log.Verbose("Topshelf service installed.");
        }
Ejemplo n.º 13
0
        internal string CreateNewVersionAsync(HockeyAppUploadSettings settings)
        {
            _log.Verbose($"Creating Version {settings.ShortVersion} ({settings.Version}) for {settings.AppId}.");

            var response = _client.CreateNewVersionAsync(settings.ApiToken, settings.AppId,
                                                         settings.Version, settings.ShortVersion);

            _log.Information($"Created Version {response.ShortVersion} ({response.Version}) for {response.Title}.");

            return(response.Id);
        }
Ejemplo n.º 14
0
        public bool CreateApplicationVersion(string applicationName, string description, string versionLabel, string s3Bucket, string s3Key, bool autoCreateApplication, ElasticBeanstalkSettings settings)
        {
            if (string.IsNullOrEmpty(applicationName))
            {
                throw new ArgumentNullException("applicationName");
            }

            if (string.IsNullOrEmpty(description))
            {
                throw new ArgumentNullException("description");
            }

            if (string.IsNullOrEmpty(versionLabel))
            {
                throw new ArgumentNullException("versionLabel");
            }

            if (string.IsNullOrEmpty(s3Bucket))
            {
                throw new ArgumentNullException("s3Bucket");
            }

            if (string.IsNullOrEmpty(s3Key))
            {
                throw new ArgumentNullException("s3Key");
            }


            try
            {
                var client = GetClient(settings);
                client.CreateApplicationVersion(new CreateApplicationVersionRequest
                {
                    ApplicationName       = applicationName,
                    AutoCreateApplication = autoCreateApplication,
                    Description           = description,
                    //Process = true,
                    VersionLabel = versionLabel,
                    SourceBundle = new S3Location
                    {
                        S3Bucket = s3Bucket,
                        S3Key    = s3Key
                    }
                });
            }
            catch (Exception ex)
            {
                _Log.Error("Failed to create new application version '{0}'", ex.Message);
                return(false);
            }

            _Log.Verbose("Successfully created new application version '{0}' for application '{1}'", versionLabel, applicationName);
            return(true);
        }
        /// <summary>
        /// Returns the build definition for the <paramref name="settings"/>.
        /// </summary>
        /// <param name="log">The Cake log context.</param>
        /// <param name="buildHttpClient">The Http build client.</param>
        /// <param name="settings">Settings for accessing AzureDevOps.</param>
        /// <returns>The build definition for the BuildDefinitionName on <paramref name="settings"/>.
        /// <c>null</c> if the BuildDefinitionName was not set or no build definition was found.</returns>
        private static BuildDefinitionReference GetBuildDefinition(
            ICakeLog log,
            BuildHttpClient buildHttpClient,
            AzureDevOpsBuildsSettings settings)
        {
            log.NotNull(nameof(log));
            buildHttpClient.NotNull(nameof(buildHttpClient));
            settings.NotNull(nameof(settings));

            List <BuildDefinitionReference> buildDefinitions = null;

            if (settings.ProjectGuid != Guid.Empty)
            {
                buildDefinitions =
                    buildHttpClient
                    .GetDefinitionsAsync(settings.ProjectGuid)
                    .ConfigureAwait(false)
                    .GetAwaiter()
                    .GetResult();
            }
            else if (!string.IsNullOrWhiteSpace(settings.ProjectName))
            {
                buildDefinitions =
                    buildHttpClient
                    .GetDefinitionsAsync(settings.ProjectName)
                    .ConfigureAwait(false)
                    .GetAwaiter()
                    .GetResult();
            }
            else
            {
                throw new ArgumentOutOfRangeException(
                          nameof(settings),
                          "Either ProjectGuid or ProjectName needs to be set");
            }

            var buildDefinition =
                buildDefinitions
                .SingleOrDefault(x => x.Name.Equals(settings.BuildDefinitionName, StringComparison.InvariantCultureIgnoreCase));

            if (buildDefinition == null)
            {
                log.Verbose(
                    "Build definition '{0}' not found",
                    settings.BuildDefinitionName);
            }

            log.Verbose(
                "Build definition '{0}' found",
                settings.BuildDefinitionName);

            return(buildDefinition);
        }
Ejemplo n.º 16
0
        public override void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddNamespaces(Namespaces)
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath));

            _log.Verbose("Compiling build script for debugging...");

            var roslynScript = Microsoft.CodeAnalysis.Scripting.CSharp.CSharpScript.Create(code, options)
                               .WithGlobalsType(_host.GetType());

            var compilation = roslynScript.GetCompilation();

            compilation = compilation.WithOptions(compilation.Options
                                                  .WithOptimizationLevel(Microsoft.CodeAnalysis.OptimizationLevel.Debug)
                                                  .WithOutputKind(Microsoft.CodeAnalysis.OutputKind.DynamicallyLinkedLibrary));

            using (var exeStream = new MemoryStream())
                using (var pdbStream = new MemoryStream())
                {
                    var result = compilation.Emit(exeStream, pdbStream: pdbStream);

                    if (result.Success)
                    {
                        _log.Verbose("Compilation successful");

                        var assembly = AppDomain.CurrentDomain.Load(exeStream.ToArray(), pdbStream.ToArray());

                        var type   = assembly.GetType(CompiledType);
                        var method = type.GetMethod(CompiledMethod, BindingFlags.Static | BindingFlags.Public);

                        var submissionStates = new object[2];
                        submissionStates[0] = _host;

                        method.Invoke(null, new[] { submissionStates });
                    }
                    else
                    {
                        _log.Verbose("Compilation failed");

                        var errors  = string.Join(Environment.NewLine, result.Diagnostics.Select(x => x.ToString()));
                        var message = string.Format(System.Globalization.CultureInfo.InvariantCulture, "Error occurred when compiling: {0}", errors);

                        throw new CakeException(message);
                    }
                }
        }
Ejemplo n.º 17
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)
                    {
                        _log.Debug("The addin {0} will reference {1}.", addin.Package, assembly.Path.GetFilename());
                        result.Add(assembly.Path);
                    }
                }
            }
            return(result.ToArray());
        }
        private void Install(SemanticVersion version)
        {
            var root        = _environment.GetApplicationRoot().MakeAbsolute(_environment);
            var installRoot = root.Combine(Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));

            var packages = new Dictionary <string, SemanticVersion>
            {
                { "Microsoft.CodeAnalysis.Scripting", version },
                { "Microsoft.CodeAnalysis.CSharp", version }
            };

            // Install package.
            var nugetSource    = _configuration.GetValue("Roslyn_NuGetSource") ?? "https://packages.nuget.org/api/v2";
            var repo           = PackageRepositoryFactory.Default.CreateRepository(nugetSource);
            var packageManager = new PackageManager(repo, installRoot.FullPath);

            _log.Verbose("Installing packages (using {0})...", nugetSource);
            foreach (var package in packages)
            {
                _log.Information("Downloading package {0} ({1})...", package.Key, package.Value);
                packageManager.InstallPackage(package.Key, package.Value, false, true);
            }

            // Copy files.
            _log.Verbose("Copying files...");
            foreach (var path in _paths)
            {
                // Find the file within the temporary directory.
                var exp       = string.Concat(installRoot.FullPath, "/**/", path);
                var foundFile = _globber.Match(exp).FirstOrDefault();
                if (foundFile == null)
                {
                    var format  = "Could not find file {0}.";
                    var message = string.Format(CultureInfo.InvariantCulture, format, path);
                    throw new CakeException(message);
                }

                var source      = _fileSystem.GetFile((FilePath)foundFile);
                var destination = _fileSystem.GetFile(root.CombineWithFilePath(path.GetFilename()));

                _log.Information("Copying {0}...", source.Path.GetFilename());

                if (!destination.Exists)
                {
                    source.Copy(destination.Path, true);
                }
            }

            // Delete the install directory.
            _log.Verbose("Deleting installation directory...");
            _fileSystem.GetDirectory(installRoot).Delete(true);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Performs the setup.
        /// </summary>
        /// <param name="action">The action.</param>
        public void PerformSetup(Action action)
        {
            if (action != null)
            {
                _log.Information(string.Empty);
                _log.Information("----------------------------------------");
                _log.Information("Setup");
                _log.Information("----------------------------------------");
                _log.Verbose("Executing custom setup action...");

                action();
            }
        }
Ejemplo n.º 20
0
        private Assembly AssemblyResolve(object sender, ResolveEventArgs args)
        {
            var name = new AssemblyName(args.Name);

            // Prevent recursion from the Assembly.Load() call inside
            if (_resolvedNames.Add(name.Name))
            {
                _log.Verbose($"Resolving assembly {args.Name}");

                return(AssemblyResolve(name));
            }
            return(null);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Deploys an application revision through the specified deployment group.
        /// </summary>
        /// <param name="applicationName">The name of an AWS CodeDeploy application associated with the applicable IAM user or AWS account.</param>
        /// <param name="deploymentGroup">The name of the deployment group.</param>
        /// <param name="settings">The <see cref="DeploySettings"/> used during the request to AWS.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async Task <bool> CreateDeployment(string applicationName, string deploymentGroup, DeploySettings settings, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (String.IsNullOrEmpty(applicationName))
            {
                throw new ArgumentNullException("applicationName");
            }
            if (String.IsNullOrEmpty(deploymentGroup))
            {
                throw new ArgumentNullException("deploymentGroup");
            }



            // Create Request
            AmazonCodeDeployClient  client  = this.CreateClient(settings);
            CreateDeploymentRequest request = new CreateDeploymentRequest();

            request.ApplicationName     = applicationName;
            request.DeploymentGroupName = deploymentGroup;

            request.Revision = new RevisionLocation()
            {
                RevisionType = RevisionLocationType.S3,

                S3Location = new S3Location()
                {
                    BundleType = BundleType.Zip,

                    Bucket  = settings.S3Bucket,
                    Key     = settings.S3Key,
                    Version = settings.S3Version
                }
            };



            // Check Response
            CreateDeploymentResponse response = await client.CreateDeploymentAsync(request, cancellationToken);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                _Log.Verbose("Successfully deployed application '{0}'", applicationName);
                return(true);
            }
            else
            {
                _Log.Error("Failed to deploy application '{0}'", applicationName);
                return(false);
            }
        }
Ejemplo n.º 22
0
 public string GetBaseVersionString(string defaultVersion)
 {
     if (_arguments.HasArgument(BuildVersionArgumentName))
     {
         return(_arguments.GetArgument(BuildVersionArgumentName));
     }
     if (IsAppVeyor)
     {
         string version = _appVeyorProvider.Environment.Build.Version;
         _log.Verbose($"AppVeyor Build Version from Env Variable:{version}");
         return(string.IsNullOrWhiteSpace(version) ? defaultVersion : version);
     }
     return(defaultVersion);
 }
Ejemplo n.º 23
0
        public void Zip(DirectoryPath rootPath, FilePath outputPath, IEnumerable <FilePath> filePaths)
        {
            if (rootPath == null)
            {
                throw new ArgumentNullException("rootPath");
            }
            if (outputPath == null)
            {
                throw new ArgumentNullException("outputPath");
            }
            if (filePaths == null)
            {
                throw new ArgumentNullException("filePaths");
            }

            // Make root path and output file path absolute.
            rootPath   = rootPath.MakeAbsolute(_environment);
            outputPath = outputPath.MakeAbsolute(_environment);

            // Get the output file.
            var outputFile = _fileSystem.GetFile(outputPath);

            // Open up a stream to the output file.
            _log.Verbose("Creating zip file: {0}", outputPath.FullPath);
            using (var outputStream = outputFile.Open(FileMode.Create, FileAccess.Write, FileShare.None))
                using (var archive = new ZipArchive(outputStream, ZipArchiveMode.Create))
                {
                    foreach (var inputPath in filePaths)
                    {
                        var absoluteInputPath = inputPath.MakeAbsolute(_environment);
                        var file = _fileSystem.GetFile(absoluteInputPath);
                        using (var inputStream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read))
                        {
                            // Get the relative filename to the rootPath.
                            var relativeFilePath = GetRelativeFilePath(rootPath, absoluteInputPath);
                            _log.Verbose("Adding file: {0}", relativeFilePath);

                            // Create the zip archive entry.
                            var entry = archive.CreateEntry(relativeFilePath.FullPath);
                            using (var entryStream = entry.Open())
                            {
                                // Copy the content of the input stream to the entry stream.
                                inputStream.CopyTo(entryStream);
                            }
                        }
                    }
                }
            _log.Verbose("Zip successfully created: {0}", outputPath.FullPath);
        }
 internal void Send(string metricName, double value, DateTime timeStamp)
 {
     try
     {
         _log.Verbose($"Sending metric: '{PrefixMetricName(metricName)}' with value '{value}' and timestamp '{timeStamp.ToLongDateString()}'");
         _client.Send(PrefixMetricName(metricName), value, timeStamp);
     }
     catch (Exception ex)
     {
         if (_settings.ThrowExceptions)
         {
             throw;
         }
         _log.Verbose($"{nameof(Send)} would have thrown an {ex.GetType()}");
     }
 }
Ejemplo n.º 25
0
        private void RunDotNetTool(PackageReference package, DirectoryPath toolsFolderDirectoryPath, DotNetToolOperation operation)
        {
            // Install the tool....
            _log.Debug("Running dotnet tool with operation {0}: {1}...", operation, package.Package);
            var process = _processRunner.Start(
                "dotnet",
                new ProcessSettings
            {
                Arguments = GetArguments(package, operation, _log, toolsFolderDirectoryPath),
                RedirectStandardOutput = true,
                Silent             = _log.Verbosity < Verbosity.Diagnostic,
                NoWorkingDirectory = true
            });

            process.WaitForExit();

            var exitCode = process.GetExitCode();

            if (exitCode != 0)
            {
                _log.Warning("dotnet exited with {0}", exitCode);
                var output = string.Join(Environment.NewLine, process.GetStandardError());
                _log.Verbose(Verbosity.Diagnostic, "Output:\r\n{0}", output);
            }
        }
Ejemplo n.º 26
0
        private bool InstallPackage(PackageReference package, DirectoryPath path)
        {
            _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(false);
            }

            return(true);
        }
Ejemplo n.º 27
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();
        }
Ejemplo n.º 28
0
        public void Execute(Script script)
        {
            // Generate the script code.
            var generator = new RoslynCodeGenerator();
            var code      = generator.Generate(script);

            // Create the script options dynamically.
            var options = Microsoft.CodeAnalysis.Scripting.ScriptOptions.Default
                          .AddImports(Namespaces)
                          .AddReferences(References)
                          .AddReferences(ReferencePaths.Select(r => r.FullPath))
                          .WithEmitDebugInformation(_options.PerformDebug)
                          .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();

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

            roslynScript.RunAsync(_host).Wait();
        }
Ejemplo n.º 29
0
        public void Execute(Script script)
        {
            if (script == null)
            {
                throw new ArgumentNullException("script");
            }

            if (script.UsingAliasDirectives.Count > 0)
            {
                throw new CakeException("The Mono scripting engine do not support using alias directives.");
            }

            var code = MonoCodeGenerator.Generate(script);

            try
            {
                // Build the class we generated.
                _log.Verbose("Compiling build script...");
                _evaluator.Run(code);

                // Actually execute it.
                _evaluator.Run("new CakeBuildScriptImpl (ScriptHost).Execute ();");
            }
            catch (InternalErrorException)
            {
                // The error will be logged via the report printer.
                throw new CakeException("An error occured while executing build script.");
            }
        }
Ejemplo n.º 30
0
        internal async Task <string> CreateNewVersionAsync(HockeyAppUploadSettings settings)
        {
            _log.Verbose($"Creating Version {settings.ShortVersion} ({settings.Version}) for {settings.AppId}.");

            var response = await _client.CreateNewVersionAsync(settings.ApiToken, settings.AppId,
                                                               settings.Version, settings.ShortVersion);

            if (!response.Success)
            {
                throw new Exception(response.Message);
            }

            _log.Information($"Created Version {response.ShortVersion} ({response.Version}) for {response.Title}.");

            return(response.Id);
        }
Ejemplo n.º 31
0
 public HockeyAppClient(ICakeLog log)
 {
     _log = log;
     _client = new HockeyAppApiClient(HockeyAppBaseUrl);
     _log.Verbose("Initialized HockeyApp Api at {0}", HockeyAppBaseUrl);
 }