/// <summary> /// Attempts to authorize a GitHub domain via OAuth. /// </summary> /// <param name="host">Auth host.</param> /// <returns>True on success.</returns> public virtual bool AuthorizeOAuth(string host) { string[] domains = config.Get(Settings.GithubDomains); if (!Array.Exists(domains, (domain) => domain == host)) { return(false); } // if available use token from git config. if (process.Execute("git config github.accesstoken", out string stdout) != 0) { return(false); } io.SetAuthentication(host, (stdout ?? string.Empty).Trim(), "x-oauth-basic"); return(true); }
public async Task <GitData> CreateGitData() { return(new GitData { Head = new GitHead { Id = await Git(GitArgs.ID), AuthorName = await Git(GitArgs.AUTHOR_NAME), AuthorEmail = await Git(GitArgs.AUTHOR_EMAIL), CommitterName = await Git(GitArgs.COMMITTER_NAME), CommitterEmail = await Git(GitArgs.COMMITTER_EMAIL), Message = await Git(GitArgs.MESSAGE), }, Branch = await Git(GitArgs.BRANCH), Remotes = await ParseRemotes() }); async Task <GitRemote[]> ParseRemotes() { var remotes = (await Git(GitArgs.REMOTES))?.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); if (remotes?.Length > 0) { var splits = new[] { '\t', ' ' }; return(remotes .Select(r => { var parts = r.Split(splits, StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 2) { return null; } return new GitRemote { Name = parts[0], Url = parts[1] }; }) .Where(r => r != null) .Distinct() .ToArray()); } return(null); } async Task <string> Git(string arguments) { var psi = new ProcessStartInfo("git", arguments); var(stdOut, stdErr, exit) = await processExecutor.Execute(psi); if (exit > 0) { return(null); } return(stdOut.TrimEnd()); } }
public string Execute(string command, bool waitForExit, string workingDirectory = null) { command.CheckArgumentNullOrWhiteSpace(nameof(command)); string nugetPath = _environmentSettings.IsNetCore ? "nuget" : Path.Combine(_workingDirectoriesProvider.WindowsNugetToolDirectory, "nuget.exe"); return(_processExecutor.Execute(nugetPath, command, waitForExit, workingDirectory)); }
/// <summary> /// Executes the given command with command line. /// </summary> /// <param name="process">The <see cref="IProcessExecutor"/> instance.</param> /// <param name="command">The command that will be executed.</param> /// <param name="stdout">The output string from the command.</param> /// <param name="stderr">The error string from the command.</param> /// <param name="cwd">Specify the execution path of the command.</param> /// <returns>The return status of the executed command.</returns> public static int Execute(this IProcessExecutor process, string command, out string stdout, out string stderr, string cwd = null) { var ret = process.Execute(command, out string[] output, out string[] error, cwd); stdout = string.Join(Environment.NewLine, output ?? Array.Empty <string>()); stderr = string.Join(Environment.NewLine, error ?? Array.Empty <string>()); return(ret); }
/// <summary> /// extract <paramref name="file"/> to <paramref name="extractPath"/> with unzip command. /// </summary> protected internal virtual void ExtractWithUnzipCommand(string file, string extractPath, bool isFallback = false) { // When called after a ZipArchive failed, perhaps // there is some files to overwrite var overwrite = isFallback ? "-o " : string.Empty; var command = $"unzip -qq {overwrite}{ProcessExecutor.Escape(file)} -d {ProcessExecutor.Escape(extractPath)}"; FileSystemLocal.EnsureDirectory(extractPath); SException processException; try { if (process.Execute(command, out _, out string stderr) == 0) { return; } throw new RuntimeException( $"Failed to execute {command} {Environment.NewLine}{Environment.NewLine} {stderr}"); } #pragma warning disable CA1031 catch (SException ex) #pragma warning restore CA1031 { processException = ex; } if (isFallback) { ExceptionDispatchInfo.Capture(processException).Throw(); } io.WriteError($" {processException.Message}"); io.WriteError($" The archive may contain identical file names with different capitalization (which fails on case insensitive filesystems)"); io.WriteError($" Unzip with unzip command failed, falling back to {nameof(ZipArchive)}."); ExtractWithZipArchive(file, extractPath, true); }
public bool Process(PushEventPayload payload) { try { var rule = _ruleMatcher.Match(payload.Ref, payload.Repository?.Url); if (rule != null) { _processExecutor.Execute(rule.Execute); return(true); } } catch (Exception ex) { _log.LogError(ex, "Unexpected error while trying to execute script"); return(false); } return(false); }
public string Execute(string filePath) { Guard.IsNotNull(filePath, nameof(filePath)); ProcessWorkingDirectoryContext processDirectoryContext = null; try { _logger.LogInfo("******** Process Started ********"); _logger.LogInfo($"File Path: {filePath}"); _logger.LogInfo($"Process ID: {Id}"); processDirectoryContext = _processSetup.SetupProcessDirectory(Id, filePath); _logger.LogInfo("**** Beginning Executables processing. ****"); _processExecutor.Execute(Id, processDirectoryContext.ProcessDirectory); _logger.LogInfo("**** Executables processing completed successfully. ****"); } catch (Exception ex) { _logger.LogInfo("** FAILURE **"); _logger.LogInfo($"Process Error: {ex.Message}"); _logger.LogError(ex); } finally { try { // TODO //_finalizer.OnComplete(success, processDirectoryContext?.WorkingDirectory); _logger.LogInfo("******** Process Complete ********"); } catch (Exception ex) { _logger.LogError(ex); } } return(_logger.ToString()); }
/// <summary> /// Execution script command. /// </summary> protected internal virtual void ExecuteScript(string callable, object sender, BucketEventArgs eventArgs) { var args = string.Join(Str.Space, Arr.Map(eventArgs.GetArguments(), ProcessExecutor.Escape)); var exec = callable + (string.IsNullOrEmpty(args) ? string.Empty : (Str.Space + args)); if (io.IsVerbose) { io.WriteError($"> {eventArgs.Name}: {exec}"); } else { io.WriteError($"> {exec}"); } var possibleLocalBinaries = bucket.GetPackage().GetBinaries() ?? Array.Empty <string>(); foreach (var localBinary in possibleLocalBinaries) { if (!Regex.IsMatch(localBinary, $"\\b{Regex.Escape(callable)}$")) { continue; } var caller = InstallerBinary.DetermineBinaryCaller(localBinary, fileSystem); exec = Regex.Replace(exec, $"^{Regex.Escape(callable)}", $"{caller} {localBinary}"); } var exitCode = process.Execute(exec, out string stdout, out string stderr); if (exitCode != ExitCodes.Normal) { io.WriteError($"<error>Script \"{callable}\" handling the \"{eventArgs.Name}\" event returned with error code: {exitCode}</error>", verbosity: Verbosities.Quiet); throw new ScriptExecutionException($"Error Output: {stderr}", exitCode); } if (io.IsDebug) { io.WriteError(stdout); } }
private DateTime?GetPackageTimeFromSource(IPackage package) { var installedPath = Path.Combine(Environment.CurrentDirectory, installationManager.GetInstalledPath(package)); var sourceType = package.GetSourceType(); DateTime?ret = null; if (string.IsNullOrEmpty(installedPath) || !Array.Exists(new[] { "git" }, (item) => item == sourceType)) { return(null); } var sourceReference = package.GetSourceReference() ?? package.GetDistReference(); DateTime?GetGitDateTime() { Git.CleanEnvironment(); if (process.Execute( $"git log -n1 --pretty=%aD {ProcessExecutor.Escape(sourceReference)}", out string output, installedPath) == 0 && DateTime.TryParse(output.Trim(), out DateTime dateTime)) { return(dateTime); } return(null); } switch (sourceReference) { case "git": ret = GetGitDateTime(); break; default: break; } return(ret); }
public void TestChangedRootIdentifier() { InitializeGitRepository(); Assert.AreEqual(0, process.Execute("git checkout 1.0")); var driver = CreateAndInitializeDriver(); Assert.AreEqual("1.0", driver.GetRootIdentifier()); }
/// <inheritdoc /> public override void Delete(string path = null) { AssertReadonly(); var location = ApplyRootPath(path); void DeleteFile(string fileLocation) { if (!File.Exists(fileLocation)) { return; } File.SetAttributes(fileLocation, FileAttributes.Normal); File.Delete(fileLocation); } void DeleteDirectory(string directoryLocation) { if (!Directory.Exists(directoryLocation)) { return; } var files = Directory.GetFiles(directoryLocation); var directories = Directory.GetDirectories(directoryLocation); Array.ForEach(files, DeleteFile); Array.ForEach(directories, DeleteDirectory); Directory.Delete(directoryLocation, false); } try { DeleteFile(location); DeleteDirectory(location); } #pragma warning disable CA1031 catch (SException) #pragma warning restore CA1031 { // Retry after a bit on windows since it tends // to be touchy with mass removals. if (Platform.IsWindows) { Thread.Sleep(350); } try { DeleteFile(location); DeleteDirectory(location); } catch (SException) { string command; if (Platform.IsWindows) { command = $"rmdir /S /Q {ProcessExecutor.Escape(location)}"; } else { command = $"rm -rf {ProcessExecutor.Escape(location)}"; } if (process.Execute(command) != 0) { throw; } } } }
public string Execute(string command, bool waitForExit, string workingDirectory = null) { command.CheckArgumentNullOrWhiteSpace(nameof(command)); return(_processExecutor.Execute("dotnet", command, waitForExit, workingDirectory)); }
private void InitializeGitRepository() { Assert.AreEqual(0, process.Execute("git init")); Assert.AreEqual(0, process.Execute("git config user.email [email protected]")); Assert.AreEqual(0, process.Execute("git config user.name BucketTest")); fileSystem.Write("foo", ToStream("foo")); Assert.AreEqual(0, process.Execute("git add foo")); Assert.AreEqual(0, process.Execute("git commit -m init")); Assert.AreEqual(0, process.Execute("git tag 0.1.0")); Assert.AreEqual(0, process.Execute("git branch oldbranch")); var jsonObject = new JObject() { { "name", "a/b" } }; fileSystem.Write("bucket.json", ToStream(jsonObject.ToString())); Assert.AreEqual(0, process.Execute("git add bucket.json")); Assert.AreEqual(0, process.Execute("git commit -m addbucket")); Assert.AreEqual(0, process.Execute("git tag 0.6.0")); // add feature-a branch Assert.AreEqual(0, process.Execute("git checkout -b feature/a")); fileSystem.Write("foo", ToStream("bar feature")); Assert.AreEqual(0, process.Execute("git add foo")); Assert.AreEqual(0, process.Execute("git commit -m change-foo")); // add version to bucket.json Assert.AreEqual(0, process.Execute("git checkout master")); jsonObject["version"] = "1.0.0"; fileSystem.Write("bucket.json", ToStream(jsonObject.ToString())); Assert.AreEqual(0, process.Execute("git add bucket.json")); Assert.AreEqual(0, process.Execute("git commit -m addversion")); Assert.AreEqual(0, process.Execute("git tag 1.0.0")); Assert.AreEqual(0, process.Execute("git branch 1.0")); }
/// <summary> /// Executes the given command with command line. /// </summary> /// <param name="process">The <see cref="IProcessExecutor"/> instance.</param> /// <param name="command">The command that will be executed.</param> /// <param name="stdout">The output string from the command.</param> /// <param name="cwd">Specify the execution path of the command.</param> /// <returns>The return status of the executed command.</returns> public static int Execute(this IProcessExecutor process, string command, out string[] stdout, string cwd = null) { return(process.Execute(command, out stdout, out _, cwd)); }
/// <summary> /// Synchronize the specified git repository to the specified directory. /// </summary> /// <param name="uri">The specified git repository. can use ssh.</param> /// <param name="path">The specified saved path. this path will be based on the file system.</param> /// <returns>True if successful to sync mirror.</returns> public bool SyncMirror(string uri, string path = null) { path = string.IsNullOrEmpty(path) ? GetRepositoryNameFromUri(uri) : path; if (fileSystem is IReportPath report) { path = report.ApplyRootPath(path); } if (string.IsNullOrEmpty(path)) { throw new FileSystemException("Clone path is invalid, cannot be empty."); } if (fileSystem.Exists(path, FileSystemOptions.Directory) && process.Execute("git rev-parse --git-dir", out string output, path) == 0 && output.Trim() == ".") { string Upgrate(string protoUri) { return($"git remote set-url origin {protoUri} && git remote update --prune origin"); } try { ExecuteCommand(Upgrate, uri, path); return(true); } #pragma warning disable CA1031 catch (System.Exception) #pragma warning restore CA1031 { return(false); } } fileSystem.Delete(path); string Cloneable(string protoUri) { return($"git clone --mirror {ProcessExecutor.Escape(protoUri)} {ProcessExecutor.Escape(path)}"); } ExecuteCommand(Cloneable, uri, path, true); return(true); }