public static async Task MigrateIssuesVersion(MigrateIssuesVersionSettings settings, ICakeLog logger) { try { var jira = Atlassian.Jira.Jira.CreateRestClient(settings.Host, settings.User, settings.Password); logger.Information($"Finding issues on version {settings.FromVersion}..."); var issuesToMove = await jira.Issues.GetIssuesFromJqlAsync($"project = {settings.Project} and fixVersion is not EMPTY and fixVersion IN (\"{settings.FromVersion}\")"); foreach (var issue in issuesToMove) { logger.Information($"Moving issue {issue.Key} from {settings.FromVersion} to {settings.ToVersion}"); issue.FixVersions.Remove(settings.FromVersion); issue.FixVersions.Add(settings.ToVersion); await jira.Issues.UpdateIssueAsync(issue); } logger.Information("Issue migration complete!"); } catch (Exception ex) { logger.Error($"Error migrating issues: {ex.Message}"); if (ex.InnerException != null) { logger.Error(ex.InnerException); } } }
public static string DeployAzureResourceGroup(ICakeLog log, Credentials credentials, string subscriptionId, string resourceGroupName, string deploymentName, string template, string parameters) { var client = GetClient(credentials, subscriptionId); log.Information($"Starting template deployment '{deploymentName}' in resource group '{resourceGroupName}'"); dynamic parametersObject = JsonConvert.DeserializeObject(parameters); var deployment = new Deployment { Properties = new DeploymentProperties { Mode = DeploymentMode.Incremental, Template = JsonConvert.DeserializeObject(template), Parameters = parametersObject["parameters"].ToObject <JObject>() } }; var deploymentResult = client.Deployments.CreateOrUpdate(resourceGroupName, deploymentName, deployment); log.Information($"Deployment status: {deploymentResult.Properties.ProvisioningState}"); return(JsonConvert.SerializeObject(deploymentResult.Properties.Outputs)); }
/// <summary> /// Runs CMake using the specified path and settings. /// </summary> /// <param name="settings">The settings.</param> public override void Run(CMakeSettings settings) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } if (settings.OutputPath == null && settings.SourcePath == null) { throw new ArgumentException("The settings properties OutputPath or SourcePath should not be null."); } // Get the output path. var outputPath = settings.OutputPath; var workingDirectory = (outputPath ?? settings.SourcePath).MakeAbsolute(_environment); if (!Directory.Exists(workingDirectory.FullPath)) { _log.Information("The working directory {0} does not found and will create.", workingDirectory.FullPath); Directory.CreateDirectory(workingDirectory.FullPath); _log.Information("The working directory {0} was created.", workingDirectory.FullPath); } // Create the process settings. var processSettings = new ProcessSettings { WorkingDirectory = workingDirectory }; // Run the tool using the specified settings. this.Run(settings, this.GetArguments(settings), processSettings, null); }
public IScriptSession CreateSession(IScriptHost host) { // Is Roslyn installed? if (!IsInstalled()) { // Find out which is the latest Roslyn version. _log.Information("Checking what the latest version of Roslyn is..."); var version = GetLatestVersion(); if (version == null) { throw new CakeException("Could not resolve latest version of Roslyn."); } _log.Information("The latest Roslyn version is {0}.", version); _log.Information("Downloading and installing Roslyn..."); Install(version); } // Load Roslyn assemblies dynamically. foreach (var filePath in _paths) { Assembly.LoadFrom(_environment .GetApplicationRoot() .CombineWithFilePath(filePath.GetFilename()) .FullPath); } // Create the session. return(new RoslynNightlyScriptSession(host, _log)); }
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(); } }
/// <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(); } }
public ProjectStatus GetAnalysisResults(SonarResultsSettings settings, string analysisId) { if (settings == null) { throw new ArgumentNullException(nameof(settings)); } try { String sonarUrl = settings.Url; if (!Utility.ValidateUrl(sonarUrl)) { throw new ArgumentException("Invalid SonarQube URL"); } if (settings.IsAuthEnabled) { _Client.Authenticator = settings.GetAuthenticator; } _Logger.Information($"Initializing analysis request"); string url = String.Format(_AnalysisUrl, sonarUrl, analysisId); var request = new RestRequest(url, Method.POST); _Logger.Information($"Setting API endpoint to {url} [POST]"); request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; }; var queryResult = _Client.Execute <ProjectStatusWrapper>(request); ValidateResult(queryResult); ProjectStatusWrapper x = queryResult.Data; return(x.ProjectStatus); } catch (Exception ex) { _Logger.Error($"An error occured while retrieving Analysis Status from SonarQube - {ex.Message}"); throw; } }
internal void Run(LocalDbSettings settings) { if (string.IsNullOrEmpty(settings.InstanceName)) { throw new InstanceNameEmptyException("settings.InstanceName"); } var argumentBuilder = new ProcessArgumentBuilder(); argumentBuilder.Append(settings.Action.ToString().ToLower(CultureInfo.InvariantCulture)); argumentBuilder.AppendQuoted(settings.InstanceName); if (settings.Action == LocalDbAction.Create) { switch (settings.InstanceVersion) { case LocalDbVersion.V11: argumentBuilder.Append("11.0"); break; case LocalDbVersion.V12: argumentBuilder.Append("12.0"); break; case LocalDbVersion.V13: argumentBuilder.Append("13.0"); break; default: throw new InstanceVersionUnknownException(); } // start the instance argumentBuilder.Append("-s"); } var arguments = argumentBuilder.Render(); contextLog.Information(Verbosity.Diagnostic, "Executing SQLLocalDB.Exe with parameters: {0}", arguments); var exitCode = 0; var output = string.Empty; Run(new LocalDbSettings(), argumentBuilder, new ProcessSettings { RedirectStandardOutput = true, }, process => { exitCode = process.GetExitCode(); output = string.Join("\n", process.GetStandardOutput() ?? new List <string>()); contextLog.Information(Verbosity.Diagnostic, "Process output: {0}", output); contextLog.Information(Verbosity.Diagnostic, "Process Exit Code: {0}", exitCode); }); if (exitCode != 0 || string.IsNullOrWhiteSpace(output)) { throw new LocalDBExecutionFailedException("LocalDB execution failed. Please see message above."); } }
public void Execute(CakeTask task, ICakeContext context) { if (task != null) { _log.Information("{0}. {1}", _counter, task.Name); _counter++; } }
public static async Task CreateJiraIssue(CreateIssueSettings settings, ICakeLog logger) { try { logger.Information($"Creating jira issue '{settings.Summary}' on {settings.Project}"); var jira = CreateJira(settings); var issueSettings = new CreateIssueFields(settings.Project); var issue = new Issue(jira, issueSettings) { Reporter = settings.Reporter, Summary = settings.Summary, Description = settings.Description, Environment = settings.Environment, Assignee = settings.Assignee, DueDate = settings.DueDate }; if (settings.Priority != 0) { issue.Priority = new IssuePriority(settings.Priority.ToString(CultureInfo.InvariantCulture)); } if (settings.Type != 0) { issue.Type = new IssueType(settings.Type.ToString(CultureInfo.InvariantCulture)); } if (settings.Labels != null) { issue.Labels.AddRange(settings.Labels); } var createdIssueKey = await issue.Jira.Issues.CreateIssueAsync(issue); if (!string.IsNullOrEmpty(createdIssueKey)) { logger.Information($"Jira issue '{settings.Summary}' created with key: " + createdIssueKey); } else { logger.Information($"Unable to create jira issue '{settings.Summary}'"); } } catch (Exception ex) { logger.Error($"Error creating issue '{settings.Summary}': {ex.Message}"); } }
public void Install(DirectoryPath root) { if (root == null) { throw new ArgumentNullException("root"); } var installRoot = root.Combine(Guid.NewGuid().ToString().Replace("-", "")); // Install package. _log.Verbose("Installing package..."); var repo = PackageRepositoryFactory.Default.CreateRepository("https://packages.nuget.org/api/v2"); var packageManager = new PackageManager(repo, installRoot.FullPath); packageManager.InstallPackage("Roslyn.Compilers.CSharp", new SemanticVersion(new Version(1, 2, 20906, 2))); // Copy files _log.Verbose("Copying files..."); foreach (var nugetPath in _nugetPaths) { var source = _fileSystem.GetFile(installRoot.CombineWithFilePath(nugetPath)); var destination = _fileSystem.GetFile(root.CombineWithFilePath(nugetPath.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> /// Runs npx. /// </summary> /// <param name="settings">The settings</param> /// <param name="redirectedStandardOutput">The captured standard output</param> public void Execute( NpxSettings settings, out string[] redirectedStandardOutput) { string[] standardOutput = null; var arguments = GetArguments(settings); var processSettings = new ProcessSettings { RedirectStandardOutput = true }; Action <IProcess> postAction = process => { standardOutput = process.GetStandardOutput().ToArray(); // even though we are redirecting standard out, if the // process exited with an error, we log standard out // for easier debugging as to why to the process failed if (process.GetExitCode() != 0) { _cakeLog.Information(string.Join(Environment.NewLine, standardOutput)); } }; Run(settings, arguments, processSettings, postAction); redirectedStandardOutput = standardOutput; }
public void RemoveBucket() { var task = minio.RemoveBucketAsync(bucketName); task.Wait(); logger.Information(string.Format("Bucket {0} is removed successfully", bucketName)); }
public void MakeBucket() { var task = minio.MakeBucketAsync(bucketName, region); task.Wait(); logger.Information(string.Format("Bucket {0} successfully created", bucketName)); }
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(); }
public IScriptSession CreateSession(IScriptHost host, IDictionary <string, string> arguments) { if (arguments == null) { throw new ArgumentNullException("arguments"); } // Are we using the experimental bits? var experimental = arguments.ContainsKey("experimental"); if (!experimental) { // Are we running Windows 10, build 10041? var operativeSystemVersion = Environment.OSVersion.Version; if (operativeSystemVersion.Major == 10 && operativeSystemVersion.Build >= 10041) { // Since .NET 4.6.1 is default here and since Roslyn // isn't compatible with that framework version, // we default to the experimental bits. experimental = true; } } // Create the script session. _log.Debug("Creating script session..."); if (experimental) { // Use the nightly build. _log.Information("Using nightly build of Roslyn."); return(_nightlyFactory.CreateSession(host)); } // Use the stable build. return(_stableFactory.CreateSession(host)); }
public void Run(SonarSettings settings) { Prepare(settings); var arguments = settings.GetArguments(_environment); _log.Information(arguments.RenderSafe()); if (_environment.Runtime.IsCoreClr) { var tool = _toolsLocator.Resolve(CORECLR_TOOL_NAME); if (tool == null) { throw new Exception($"No CoreCLR executable found ({CORECLR_TOOL_NAME})"); } _log.Debug("We're launching for CoreCLR with executable " + tool.FullPath); _coreRunner.Execute(new FilePath("dummy.file").MakeAbsolute(_environment), tool.FullPath, arguments, new DotNetCoreToolSettings { }); } else { _log.Debug("We're launching for CLR."); Run(settings, arguments, new ProcessSettings { RedirectStandardOutput = settings.Silent }, null); } }
public void SetNextVersion(VersionResult version) { _log.Information($"Building {version.FullVersion}"); if (IsInteractiveBuild) { _log.Information($"Interacitve Build Mode"); } else if (IsAppVeyor) { _appVeyorProvider.UpdateBuildVersion(version.FullVersion); _appVeyorProvider.AddInformationalMessage($"Building {version.FullVersion}"); } }
/// <summary> /// Sets the authentication settings for the site. /// </summary> /// <param name="config">The config object to adjust.</param> /// <param name="serverType">The type of the server.</param> /// <param name="site">The name of the site.</param> /// <param name="appPath">The application path.</param> /// <param name="settings">The authentication settings.</param> /// <param name="log">ICakeLog.</param> /// <returns></returns> public static Configuration SetAuthentication(this Configuration config, string serverType, string site, string appPath, AuthenticationSettings settings, ICakeLog log) { if (settings != null) { var locationPath = site + appPath; var sectionName = $"system.{serverType}/security/authentication/"; // Anonymous Authentication if (settings.EnableAnonymousAuthentication.HasValue) { var anonymousAuthentication = config.GetSection(sectionName + "anonymousAuthentication", locationPath); anonymousAuthentication.SetAttributeValue("enabled", settings.EnableAnonymousAuthentication.Value); log.Information("Anonymous Authentication enabled: {0}", settings.EnableAnonymousAuthentication.Value); } // Basic Authentication if (settings.EnableBasicAuthentication.HasValue) { var basicAuthentication = config.GetSection(sectionName + "basicAuthentication", locationPath); basicAuthentication.SetAttributeValue("enabled", settings.EnableBasicAuthentication.Value); if (settings.EnableBasicAuthentication.Value && !String.IsNullOrEmpty(settings.Username) && !String.IsNullOrEmpty(settings.Password)) { basicAuthentication.SetAttributeValue("userName", settings.Username); basicAuthentication.SetAttributeValue("password", settings.Password); } log.Information("Basic Authentication enabled: {0}", settings.EnableWindowsAuthentication.Value); } // Windows Authentication if (settings.EnableWindowsAuthentication.HasValue) { var windowsAuthentication = config.GetSection(sectionName + "windowsAuthentication", locationPath); windowsAuthentication.SetAttributeValue("enabled", settings.EnableWindowsAuthentication.Value); log.Information("Windows Authentication enabled: {0}", settings.EnableWindowsAuthentication.Value); } } return(config); }
public int CreatePullRequest() { using (var client = CreateGitClient(out var authorizedIdenity)) { var criteria = new GitPullRequestSearchCriteria { Status = PullRequestStatus.Active, SourceRefName = _settings.SourceBranch, TargetRefName = _settings.TargetBranch }; var query = client.GetPullRequestsAsync(_settings.ProjectName, _settings.RepositoryName, criteria).Result; if (query.Count > 0) { var item = query.First(); _log.Information("Pull Request already exists: {0}", item.Url); return(item.PullRequestId); } var pr = client.CreatePullRequestAsync( new GitPullRequest { SourceRefName = _settings.SourceBranch, TargetRefName = _settings.TargetBranch, Title = _settings.Title, Description = _settings.Description, CompletionOptions = new GitPullRequestCompletionOptions { DeleteSourceBranch = _settings.DeleteSourceBranch, SquashMerge = _settings.SquashMerge, BypassPolicy = true, BypassReason = "Automatic Merge" }, AutoCompleteSetBy = new IdentityRef { Id = authorizedIdenity.Id.ToString() } }, _settings.ProjectName, _settings.RepositoryName).Result; _log.Information("New Pull Request was created: {0}", pr.Url); return(pr.PullRequestId); } }
public void UploadFile(FilePath file, HockeyAppUploadSettings settings, FilePath symbolFile = null) { if (string.IsNullOrEmpty(settings.ApiToken)) { throw new ArgumentNullException("settings.ApiToken", $"You have to ether specify an ApiToken or define the {HockeyAppAliases.TokenVariable} environment variable."); } if (string.IsNullOrEmpty(settings.AppId)) { throw new ArgumentNullException("settings.AppId", "You have to specify an AppId"); } _log.Information("Uploading file to HockeyApp. This can take several minutes...."); var versionId = CreateNewVersionAsync(settings); UploadToVersion(file, settings, versionId, symbolFile); }
public static void DeleteAzureResourceGroup(ICakeLog log, Credentials credentials, string subscriptionId, string resourceGroupName) { var client = GetClient(credentials, subscriptionId); if (client.ResourceGroups.CheckExistence(resourceGroupName)) { log.Information($"Deleting resource group '{resourceGroupName}'"); client.ResourceGroups.Delete(resourceGroupName); } else { log.Information($"Resource group '{resourceGroupName}' doesn't exist."); } }
/// <summary> /// Check if a directory exist, if it does not exist it will be created /// </summary> /// <param name="directoryPath">Directory path to check</param> /// <param name="log">Cake log</param> public static void CheckAndCreateDirectory(this DirectoryPath directoryPath, ICakeLog log) { if (Directory.Exists(directoryPath.FullPath)) { return; } Directory.CreateDirectory(directoryPath.FullPath); log.Information("{0} was created", directoryPath.FullPath); }
public Task ExecuteAsync(CakeTask task, ICakeContext context) { if (task != null) { _log.Information("{0}. {1}", _counter, task.Name); _counter++; } return(Task.CompletedTask); }
public void Initialize() { var root = _environment.GetApplicationRoot(); if (!_installer.IsInstalled(root)) { _log.Information("Downloading and installing Roslyn..."); _installer.Install(root); } }
public void Run(SonarSettings settings) { var arguments = settings.GetArguments(_environment); _log.Information(arguments.RenderSafe()); Run(settings, arguments, new ProcessSettings { RedirectStandardOutput = settings.Silent }, null); }
public void ListBuckets() { var task = minio.ListBucketsAsync(); task.Wait(); if (!string.IsNullOrEmpty(task.Result.Owner)) { logger.Information(string.Format("Bucket Owner: {0}", task.Result.Owner)); } if (task.Result.Buckets.Count == 0) { logger.Warning("No bucket found!"); } foreach (Bucket bucket in task.Result.Buckets) { logger.Information(string.Format("Bucket Name: {0}, Creation Date: {1}", bucket.Name, bucket.CreationDate)); } }
public async Task <HockeyAppUploadResult> UploadFile(FilePath file, FilePath symbolFile, HockeyAppUploadSettings settings) { if (string.IsNullOrEmpty(settings.ApiToken)) { throw new ArgumentNullException("settings.ApiToken", $"You have to either specify an ApiToken or define the {HockeyAppAliases.TokenVariable} environment variable."); } _log.Information("Uploading file to HockeyApp. This can take several minutes...."); if (settings.AppId == null) { return(await Upload(file, symbolFile, settings)); } var versionId = await CreateNewVersionAsync(settings); return(await UploadToVersion(file, symbolFile, settings, versionId)); }
public IScriptSession CreateSession(IScriptHost host) { // Is Roslyn installed? if (!IsInstalled()) { _log.Information("Downloading and installing Roslyn (experimental)..."); Install(new SemanticVersion(1, 0, 0, "rc2")); } // Load Roslyn assemblies dynamically. foreach (var filePath in _paths) { Assembly.LoadFrom(_environment.ApplicationRoot .CombineWithFilePath(filePath.GetFilename()) .FullPath); } // Create the session. return(CreateSession(host, _log)); }
public void DeleteAllRecursive(string ftpUri, FtpDeploySettings settings, List <string> directoriesToRemove) { var directoryDetailsList = ListDirectoryDetails(ftpUri, settings); foreach (var directoryDetails in directoryDetailsList) { if (directoryDetails.Type == DirectoryDetailsType.File) { var filePath = ftpUri + "/" + directoryDetails.Name; Interlocked.Increment(ref _requestNumber); _log.Information($"Deleting file: {filePath}\n"); Task.Factory.StartNew(() => DeleteFile(filePath, settings)); } else if (directoryDetails.Type == DirectoryDetailsType.Directory) { var directoryPath = ftpUri + "/" + directoryDetails.Name; DeleteAllRecursive(directoryPath, settings, directoriesToRemove); directoriesToRemove.Add(directoryPath); } } }