private static string FetchNuGetApiKeyFromEnvVariable(ITaskContextInternal context, string environmentVariableName = DefaultNuGetApiKeyEnvVariable) { string apiKey = Environment.GetEnvironmentVariable(environmentVariableName); if (string.IsNullOrEmpty(apiKey)) { context.Fail($"NuGet API key environment variable ('{environmentVariableName}') does not exist, cannot publish the package.", 1); return(null); } return(apiKey); }
protected override int DoExecute(ITaskContextInternal context) { var findPackageTask = new FindNuGetPackageInUserRepositoryTask(_packageId); findPackageTask.Execute(context); if (findPackageTask.PackageVersion != null && _packageVersion != null && findPackageTask.PackageVersion > _packageVersion) { PackageDirectory = findPackageTask.PackageDirectory; return(0); } if (findPackageTask.PackageDirectory != null) { PackageDirectory = findPackageTask.PackageDirectory; return(0); } var task = new NuGetCmdLineTask("install") .WithArguments(_packageId) .WithArguments($"-Source {PackageSource}") .WithArguments("-NonInteractive") .WithArguments($"-OutputDirectory {NuGetPackagesCacheDir}"); if (_packageVersion != null) { task.WithArguments($"-Version {_packageVersion}"); } if (ConfigFile != null) { task.WithArguments($"-ConfigFile {ConfigFile}"); } if (Verbosity.HasValue) { task.Verbosity = Verbosity.Value; } task.Execute(context); findPackageTask.Execute(context); PackageDirectory = findPackageTask.PackageDirectory; context.LogError( PackageDirectory == null ? $"Something is wrong, after downloading it the NuGet package '{_packageId}' still could not be found." : "Package downloaded to '{packageDirectory}'"); return(0); }
protected override void BeforeExecute(ITaskContextInternal context, IRunProgramTask runProgramTask) { if (!GetArguments().Exists(x => x == "-c" || x == "--configuration")) { var configuration = context.Properties.Get <string>(BuildProps.BuildConfiguration, null); if (configuration != null) { Configuration(configuration); } } base.BeforeExecute(context, runProgramTask); }
protected override GitVersion DoExecute(ITaskContextInternal context) { base.DoExecute(context); if (!string.IsNullOrEmpty(ProgramOutput)) { var gitVersion = JsonConvert.DeserializeObject <GitVersion>(ProgramOutput); context.Properties.Set(BuildProps.BuildVersion, new Version(gitVersion.AssemblySemVer)); return(gitVersion); } return(null); }
private void TasksHelp(ITaskContextInternal context) { context.LogInfo("Tasks:"); // first sort the targets IEnumerable <ITask> tasks = _provider.GetServices <ITask>(); // now display them in sorted order foreach (ITask task in tasks) { context.LogInfo($" {task.GetType().FullName}"); } }
protected override int DoExecute(ITaskContextInternal context) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < _sourceFiles.Count; i++) { string file = _sourceFiles[i]; string current = File.ReadAllText(file); } File.WriteAllText(_destinationConfiguration, builder.ToString(), Encoding.UTF8); return(0); }
protected override int DoExecute(ITaskContextInternal context) { _packagePath.MustNotBeNullOrEmpty("packagePath (path to .nupkg) must not be null or empty."); // do not push new packages from a local build if (context.BuildServers().IsLocalBuild&& _skipPushOnLocalBuild) { context.LogInfo("pushing package on local build is disabled in build script...Skiping."); return(1); } return(base.DoExecute(context)); }
public DirectorySource( ITaskContextInternal taskContext, IDirectoryFilesLister directoryFilesLister, string id, FullPath directoryName, bool recursive) { _taskContext = taskContext; _directoryFilesLister = directoryFilesLister; _id = id; _recursive = recursive; _directoryPath = directoryName; }
protected override void BeforeExecute(ITaskContextInternal context) { var args = GetArguments(); if (args.Count == 0 || args[0].StartsWith("-")) { var solustionFileName = context.Properties.Get <string>(BuildProps.SolutionFileName, null); if (solustionFileName != null) { Project(solustionFileName); } } }
public void CheckLbStatus(ITaskContextInternal context, string enviroment) { if (enviroment != "Production" && enviroment != "Test") { context.LogInfo($"Switch healthcheck http status for enviroment {enviroment} is not turned on."); return; } WebClient client = new WebClient(); client.BaseAddress = WebApiBaseUrl(enviroment); var resposne = client.DownloadString("HealthCheck/Lb"); }
public static DirectorySource WebFilterSource( ITaskContextInternal taskContext, IDirectoryFilesLister directoryFilesLister, string id, FullPath directoryName, bool recursive) { DirectorySource source = new DirectorySource(taskContext, directoryFilesLister, id, directoryName, recursive, null); source.SetFileFilter(new NegativeFilter( new RegexFilter(@"^.*\.(svc|asax|config|aspx|ascx|css|js|gif|PNG)$"))); return(source); }
public static bool LogIfFilteredOut(string fileName, IFilter filter, ITaskContextInternal taskContext, bool logFiles) { if (filter != null && !filter.IsPassedThrough(fileName)) { if (logFiles) { taskContext.LogInfo($"File '{fileName}' has been filtered out."); } return(false); } return(true); }
public ITargetFluentInterface GetTargetFluentInterface(ITarget target, ITaskContextInternal taskContext) { ITargetFluentInterface t = _sp.GetRequiredService <ITargetFluentInterface>(); TargetFluentInterface targetFluent = (TargetFluentInterface)t; targetFluent.Target = target; targetFluent.Context = taskContext; targetFluent.CoreTaskFluent = GetCoreTaskFluentInterface(taskContext); targetFluent.TaskExtensionsFluent = GetTaskExtensionsFluentInterface(t, taskContext); targetFluent.CoreTaskExtensionsFluent = GetCoreTaskExtensionsFluentInterface(t, taskContext); targetFluent.TaskFluent = GetTaskFluentInterface(taskContext); return(targetFluent); }
public virtual void LogTargetsHelp(ITaskContextInternal context) { context.DecreaseDepth(); context.LogInfo("Targets:"); // first sort the targets var sortedTargets = new SortedList <string, ITargetInternal>(); foreach (var target in _targets.Values) { sortedTargets.Add(target.TargetName, target); } // now display them in sorted order foreach (ITargetInternal target in sortedTargets.Values) { if (target.IsHidden == false) { string help = $" {target.TargetName.Capitalize()}"; if (target.Dependencies != null && target.Dependencies.Count != 0) { help = $"{help} ({string.Join(", ", target.Dependencies.GetKeys())})"; } help = $"{help} : {target.Description}"; if (DefaultTargets.Contains(target)) { context.LogInfo(help, Color.DarkOrange); } else { context.LogInfo(help); } } } if (ScriptArgsHelp?.Count > 0) { context.LogInfo(" "); context.LogInfo("Global build script arguments:"); foreach (var argHelp in ScriptArgsHelp) { context.LogInfo($" {argHelp}"); } } context.IncreaseDepth(); }
protected override int DoExecute(ITaskContextInternal context) { IRunProgramTask task = context .Tasks() .RunProgramTask("systemctl") .WithArguments(_command, _service); if (DoNotFail) { task.DoNotFailOnError(); } return(task.Execute(context)); }
/// <inheritdoc /> protected override TResult DoExecute(ITaskContextInternal context) { if (string.IsNullOrEmpty(ExecutablePath)) { throw new TaskExecutionException($"{nameof(ExecutablePath)} must be set.", 5); } _task = context.Tasks() .RunProgramTask(ExecutablePath) .DoNotLogTaskExecutionInfo() .WorkingFolder(ExecuteWorkingFolder); _task.WithOutputLogLevel(OutputLogLevel); _task.WithLogLevel(TaskLogLevel); if (KeepProgramOutput) { _task.CaptureOutput(); } if (KeepProgramErrorOutput) { _task.CaptureErrorOutput(); } BeforeExecute(context, _task); AddOrOverrideArgumentsFromConsole(context); var argumentsFlat = ValidateAndGetArgumentsFlat(); foreach (var arg in argumentsFlat) { _task.WithArguments(arg.arg, arg.maskArg); } var result = _task .ChangeDefaultAdditionalOptionPrefix(AdditionalOptionPrefix) .AddPrefixToAdditionalOptionKey(_prefixToAdditionalOptionKeyFunc) .ChangeAdditionalOptionKeyValueSeperator(_additionalOptionKeyValueSeperator) .AddNewAdditionalOptionPrefix(_additionalOptionPrefixes) .Execute(context); if (typeof(TResult) == typeof(int)) { return((TResult)(object)result); } return(default(TResult)); }
protected override async Task <int> DoExecuteAsync(ITaskContextInternal context) { var client = WebApiClientFactory.Create(context.Properties.Get <string>(BuildProps.LastWebApiBaseUrl)); var response = await client.ExecuteAsync(c => c.UploadScriptAsync(new UploadScriptRequest { FilePath = _scriptFilePath })); if (response != null) { throw new TaskExecutionException($"Upload script failed: ErrorCode: {response.ErrorCode} ErrorMessage: {response.ErrorMessage}", 99); } return(0); }
public ZipProcessor( ITaskContextInternal taskContext, IZipper zipper, FileFullPath zipFileName, FullPath baseDir, bool optimizeFiles, params string[] sources) { _taskContext = taskContext; _zipper = zipper; _zipFileName = zipFileName; _baseDir = baseDir; _optimizeFiles = optimizeFiles; _sourcesToZip.AddRange(sources); }
public void TargetHelp(ITaskContextInternal context) { _targetTree.MarkTargetAsExecuted(this); context.LogInfo(" "); context.LogInfo($"Target {TargetName} will execute next tasks:"); for (int i = 0; i < _taskGroups.Count; i++) { for (int j = 0; j < _taskGroups[i].Tasks.Count; j++) { var task = (TaskHelp)_taskGroups[i].Tasks[j].task; task.LogTaskHelp(context); } } }
protected override int DoExecute(ITaskContextInternal context) { if (string.IsNullOrEmpty(ExecutablePath)) { ExecutablePath = context.Properties.GetDotnetExecutable(); if (string.IsNullOrEmpty(ExecutablePath)) { context.Fail("Dotnet executable not set!", -1); return(-1); } } KeepProgramErrorOutput = true; KeepProgramOutput = true; return(base.DoExecute(context)); }
protected override async Task <int> DoExecuteAsync(ITaskContextInternal context) { var json = JsonSerializer.Serialize(_message, serializeOptions); using (var client = new HttpClient()) { var result = await client.PostAsync(_webhookUrl, new StringContent(json, Encoding.UTF8, "application/json")); if (result.IsSuccessStatusCode) { return(0); } throw new TaskExecutionException(await result.Content.ReadAsStringAsync(), 20); } }
private static (List <string> targetsToRun, bool unknownTarget, List <string> notFoundTargets) ParseCmdLineArgs( ITaskContextInternal context, TargetTree targetTree) { if (context.Args.MainCommands == null || context.Args.MainCommands.Count == 0) { return(null, false, null); } if (targetTree.HasAllTargets(context.Args.MainCommands, out var notFoundTargets)) { return(context.Args.MainCommands, false, null); } return(new List <string> { "help" }, true, notFoundTargets); }
public DirectorySource( ITaskContextInternal taskContext, IDirectoryFilesLister directoryFilesLister, string id, FullPath directoryName, bool recursive, IFilter filter, bool logFiles = true) { _taskContext = taskContext; _directoryFilesLister = directoryFilesLister; _id = id; _recursive = recursive; DirectoryFilter = filter; _directoryPath = directoryName; _logFiles = logFiles; }
protected override int DoExecute(ITaskContextInternal context) { string program = ExecutablePath; if (string.IsNullOrEmpty(program)) { program = context.Properties.GetDotnetExecutable(); } if (string.IsNullOrEmpty(program)) { context.Fail("Dotnet executable not set!", -1); return(-1); } IRunProgramTask task = context.Tasks().RunProgramTask(program); if (NoOutputLog) { task.DoNotLogOutput(); } if (DoNotLog) { task.NoLog(); } BeforeExecute(context); var argumentsFlat = ValidateAndGetArgumentsFlat(); task .WithArguments(Command); foreach (var arg in argumentsFlat) { task.WithArguments(arg.arg, arg.maskArg); } task .WorkingFolder(ExecuteWorkingFolder) .CaptureErrorOutput() .CaptureOutput() .ExecuteVoid(context); return(0); }
protected override GitVersion DoExecute(ITaskContextInternal context) { AddPrefixToAdditionalOptionKey(PrefixProcessors.AddSlashPrefixToAdditionalOptionKey); ChangeAdditionalOptionKeyValueSeperator(' '); base.DoExecute(context); var output = GetOutput(); if (!string.IsNullOrEmpty(output)) { var gitVersion = JsonConvert.DeserializeObject <GitVersion>(output); context.Properties.Set(BuildProps.BuildVersion, new Version(gitVersion.AssemblySemVer)); return(gitVersion); } return(null); }
public ZipProcessor( ITaskContextInternal taskContext, IZipper zipper, FileFullPath zipFileName, FullPath baseDir, bool optimizeFiles, List <string> sources, bool logFiles = true) { _taskContext = taskContext; _zipper = zipper; _zipFileName = zipFileName; _baseDir = baseDir; _optimizeFiles = optimizeFiles; _sourcesToZip.AddRange(sources); _logFiles = logFiles; }
protected override async Task <int> DoExecuteAsync(ITaskContextInternal context) { if (string.IsNullOrEmpty(_saveAs)) { throw new ArgumentNullException(nameof(_saveAs)); } var extension = Path.GetExtension(_saveAs); if (string.IsNullOrEmpty(extension) || !extension.Equals(".zip", StringComparison.OrdinalIgnoreCase)) { throw new TaskExecutionException("SaveAs file extension must be .zip", 99); } var client = WebApiClientFactory.Create(context.Properties.Get <string>(BuildProps.LastWebApiBaseUrl)); try { var reports = await client.DownloadReportsAsync(new DownloadReportsRequest() { DownloadFromSubDirectory = _subDirectory }) as MemoryStream; using (FileStream file = new FileStream(_saveAs, FileMode.Create, FileAccess.Write)) { reports.WriteTo(file); #if !NETSTANDARD1_6 reports.Close(); file.Close(); #endif } } catch (WebApiException e) { if (e.ErrorCode == "NoReportsFound" && !_failWhenNoReportsFound) { context.LogInfo("No reports found on server."); return(0); } throw; } return(0); }
protected override Version DoExecute(ITaskContextInternal context) { _productRootDir = context.Properties.Get <string>(BuildProps.ProductRootDir, "."); if (string.IsNullOrEmpty(_productRootDir)) { _productRootDir = "."; } string projectVersionFileName; if (!string.IsNullOrEmpty(_projectVersionFileName)) { projectVersionFileName = Path.Combine(_productRootDir, _projectVersionFileName); } else { _productId = context.Properties.Get <string>(BuildProps.ProductId); projectVersionFileName = Path.Combine(_productRootDir, $"{_productId}.ProjectVersion.txt"); } if (!File.Exists(projectVersionFileName)) { throw new InvalidOperationException($"Project version file '{projectVersionFileName}' is missing."); } Version buildVersion; using (Stream stream = File.Open(projectVersionFileName, FileMode.Open)) { using (StreamReader reader = new StreamReader(stream)) { string versionAsString = reader.ReadLine(); buildVersion = new Version(versionAsString); } } if (!_doNotSaveVersionToSession) { context.SetBuildVersion(buildVersion); } DoLogInfo($"Project build version (from file): {buildVersion}"); return(buildVersion); }
protected override int DoExecute(ITaskContextInternal context) { var urlWithAccessToken = $"https://{_account}.slack.com/services/hooks/incoming-webhook?token={_token}"; var uri = new Uri(urlWithAccessToken); string payloadJson = JsonConvert.SerializeObject(_slackMessage); using (WebClient client = new WebClient()) { NameValueCollection data = new NameValueCollection(); data["payload"] = payloadJson; var response = client.UploadValues(uri, "POST", data); string responseText = _encoding.GetString(response); } return(0); }
protected override int DoExecute(ITaskContextInternal context) { JObject dest = new JObject(); foreach (string file in _sourceFiles) { JObject src = JObject.Parse(File.ReadAllText(file)); foreach (JToken child in src.Children()) { dest.Add(child); } } File.WriteAllText(_fileName, dest.ToString(Formatting.Indented), Encoding.UTF8); return(0); }