// Stage all files and return true if anything to commit public bool StageAll() { GenLog.Info("Staging all files"); return(!RunFluent("add", "-A", "*") .RunFluent("status") .IsClean()); }
protected void UpdateVersionInFile(string path, PackageDefinition package, NuGetVersion toVersion) { var fileContent = File.ReadAllLines(path); var changesMade = false; var marker = new Regex($@"\b{package.Id}\b", RegexOptions.IgnoreCase); for (var i = 0; i < fileContent.Length; i++) { var line = fileContent[i]; if (!marker.IsMatch(line)) { continue; } changesMade = true; fileContent[i] = line.Replace(package.FullNuGetVersion.ToString(), toVersion.ToString()); } if (!changesMade) { return; } GenLog.Info($"Updating {package.Id} {package.FullNuGetVersion} => {toVersion} in {path}"); FileSystem.WriteToFileSafely(path, fileContent); }
public bool GetYesNoResponse(string prompt) { if (Options.Passive) { GenLog.Info($"Non-interactive mode, using defaults '{prompt}' => 'yes'"); return(true); } while (true) { Console.Out.Write($"{prompt} (y/n) "); var result = Console.ReadKey(); Console.Out.WriteLine(""); // ReSharper disable once SwitchStatementMissingSomeCases switch (result.Key) { case ConsoleKey.Y: return(true); case ConsoleKey.N: return(false); default: continue; } } }
// Stage modified files and return true if anything to commit public bool StageModified() { GenLog.Info("Staging modified files"); return(!RunFluent("add", "-u") .RunFluent("status") .IsClean()); }
private Client Run(string cmd, params string[] packagesAndArguments) { var args = new List <object> { cmd, "-y" }; args.AddRange(packagesAndArguments); var result = Shell.RunAndGetExitCodeMS(GetChocoExecutable(), args.ToArray()); GenLog.Info("Chocolatey command done"); switch (result) { case 0: break; case 1641: _interactionHandler.ExitWithSuccess("Exiting for reboot"); break; case 3010: AskForRestart(); break; default: _interactionHandler.ExitWithError("Chocolatey failed"); break; } return(this); }
public static void DeleteDirectory(string path) { if (String.IsNullOrWhiteSpace(path)) { return; } var retries = 5; while (Directory.Exists(path)) { try { GenLog.Info($"Deleting directory: {path}..."); Directory.Delete(path, true); } catch (Exception e) when(e is IOException && retries-- >= 0) { GenLog.Warning("Unable to delete directory. Will retry..."); Thread.Sleep(3000); } catch (UnauthorizedAccessException) when(retries-- >= 0) { GenLog.Warning("Unable to delete directory. Will attempt to remove read-only files..."); DeleteReadOnlyDirectory(path); } } }
// True if environment variable is set to a generic "not false" value public static bool IsEnvironmentVariableTrue(string name) { var value = Environment.GetEnvironmentVariable(name); GenLog.Info($"Env: {name} => {value}"); if (string.IsNullOrWhiteSpace(value)) { return(false); } if (value.ToLowerInvariant() == "false") { return(false); } if (int.TryParse(value, out var result)) { if (result == 0) { return(false); } } return(true); }
public static void UseStandardLogFile() { var name = System.Diagnostics.Process.GetCurrentProcess().ProcessName; GenLog.LogFile = Path.Combine(GetZInternalsDir(), $"{name}.log"); GenLog.Info($"Writing logfile to {GenLog.LogFile}"); }
public static async Task <(int exitCode, string stdout, string stderr)> RunAsync( string program, params object[] args) { var(exitCode, stdout, stderr) = await RunSilent(program, args); if (!string.IsNullOrWhiteSpace(stdout)) { GenLog.Info("=====================================stdout====================================="); GenLog.Info(stdout); } else { GenLog.Info("<no stdout>"); } if (!string.IsNullOrWhiteSpace(stderr)) { GenLog.Info("=====================================stderr====================================="); GenLog.Info(stderr); } GenLog.Info("================================================================================"); return(exitCode, stdout, stderr); }
public static bool TrySearchUpForFileFrom( out string foundPath, string filename, string startingLocation, string underSubDir = null) { var directoryToCheck = startingLocation; GenLog.Info($"Searching for {filename} starting from {startingLocation}"); while (directoryToCheck != null) { var possibleFileLocation = !string.IsNullOrWhiteSpace(underSubDir) ? Path.Combine(directoryToCheck, underSubDir, filename) : Path.Combine(directoryToCheck, filename); if (File.Exists(possibleFileLocation) || Directory.Exists(possibleFileLocation)) { GenLog.Info($"Found at {possibleFileLocation}"); foundPath = possibleFileLocation; return(true); } directoryToCheck = Directory.GetParent(directoryToCheck)?.FullName; } foundPath = null; return(false); }
private static void DeleteDirectory(string path) { if (string.IsNullOrWhiteSpace(path)) { return; } var retries = 10; while (Directory.Exists(path)) { try { GenLog.Info($"Deleting directory: {path}..."); Directory.Delete(path, true); } catch (IOException e) when(retries-- >= 0) { GenLog.Warning("Unable to delete directory. Will retry..."); GenLog.Warning(e.Message); Thread.Sleep(5000); } catch (UnauthorizedAccessException) when(retries-- >= 0) { GenLog.Warning("Unable to delete directory. Will attempt to remove read-only files..."); RemoveReadOnlyAttributes(path); } } }
// Returns all remote branch refs without remote prefix public IEnumerable <string> GetLogicalBranchList() { GenLog.Info($"Gathering logical branch list in {Name}"); var cutLength = $"{DefaultRemote}/".Length; return(GetRemoteBranchList() .Select(b => b.Substring(cutLength))); }
public static int RunAndGetExitCode(string program, params object[] args) { GenLog.Info($"{program} {string.Join(" ", args)}"); var command = Command.Run(program, args) .RedirectTo(Console.Out) .RedirectStandardErrorTo(Console.Error); command.Wait(); return(command.Result.ExitCode); }
public static void CreateDirectory(string path) { if (Directory.Exists(path)) { return; } GenLog.Info($"Creating directory {path}"); Directory.CreateDirectory(path); }
public void Commit(string message) { GenLog.Info("Committing staged files"); if (message.Contains('\n')) { throw new Exception("Multi-line messages are not supported by this method"); } RunAndFailIfNotExitZero("commit", message); }
public static string GetWorkDir() { var filename = AppDomain.CurrentDomain.FriendlyName; var basename = Path.GetFileNameWithoutExtension(filename); var workDir = Path.Combine(GetZInternalsDir(), basename); GenLog.Info($"Using work dir {workDir}"); CreateDirectory(workDir); return(workDir); }
public void Commit(string message) { GenLog.Info("Committing staged files"); if (message.Contains('\n')) { throw new Exception("Multi-line messages are not supported by this method"); } var result = Run($"commit {message}"); GenLog.Info(result); }
private string GetInput(string prompt, string defaultValue) { if (Options.Passive) { GenLog.Info($"Non-interactive mode, using defaults '{prompt}' => '{defaultValue ?? "[null]"}'"); return(defaultValue); } Console.Out.Write($"{prompt} [{defaultValue ?? ""}]: "); var result = Console.ReadLine(); return(string.IsNullOrWhiteSpace(result) ? defaultValue : result); }
public static Credential GetCredential(string name) { var result = Values.Credentials.FirstOrDefault(c => c.Name == name); if (result == null) { throw new ConfigurationException( $"Resource Resolver: Credential set {name} not found!"); } GenLog.Info($"Returning credentials for user {result.Username}"); return(result); }
private static string RunWithoutChangingRoot(string arguments) { var output = new StringBuilder(); // FIXME check that git is in the PATH var p = new Process { StartInfo = { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, FileName = "git", Arguments = arguments } }; var outputLock = new object(); p.OutputDataReceived += (sender, args) => { lock (outputLock) { output.Append(args.Data + "\n"); } }; p.ErrorDataReceived += (sender, args) => { lock (outputLock) { output.Append(args.Data + "\n"); } }; GenLog.Info($"Running: git.exe {arguments}"); GenLog.Info($"\tFrom {Directory.GetCurrentDirectory()}"); try { p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit(); } catch (Exception e) { GenLog.Info(output.ToString()); GenLog.Info($"Failed Command: git.exe {arguments}"); throw new Exception("Failure: " + e.Message); } var result = output.ToString(); if (p.ExitCode == 0) { return(result); } GenLog.Info(result); GenLog.Info($"Failed Command: git.exe {arguments}"); throw new Exception($"Command returned exit code: {p.ExitCode}"); }
public string GetChocoExecutable() { if (string.IsNullOrWhiteSpace(_choco)) { _choco = FindChocoExecutable(); if (!_upgraded) { GenLog.Info("Upgrading Chocolatey"); InstallOrUpgradePackages("chocolatey"); _upgraded = true; } } return(_choco); }
public static async Task OnExceptionAsync( [InstantHandle] Func <Task> action, string introMessage, CancellationToken cancellationToken, int numRetries = 3, int delay = 3000) { if (numRetries < 0) { numRetries = 0; } while (numRetries-- > 0 && !cancellationToken.IsCancellationRequested) { try { if (!introMessage.IsEmpty()) { GenLog.Info(introMessage); } await action(); return; } catch (FatalException e) { GenLog.Error($"Aborting due to fatal exception: {e?.InnerException?.Message}"); throw; } catch (Exception e) { if (cancellationToken.IsCancellationRequested) { GenLog.Warning("Cancelling retry-able operation"); throw; } GenLog.Warning("Caught exception during retry-able operation:"); GenLog.Warning(e.Message); if (numRetries == 0) { GenLog.Error("No more retries left"); throw; } GenLog.Info($"Retries remaining: {numRetries}"); await Task.Delay(delay, cancellationToken); delay *= 2; } } }
public static void Delete(string path) { if (Directory.Exists(path)) { DeleteDirectory(path); return; } if (!File.Exists(path)) { return; } GenLog.Info($"Deleting {path}"); File.Delete(path); }
public void Checkout(string localBranchName) { if (IsLocalBranch(localBranchName)) { GenLog.Info($"Checking out local branch {localBranchName}"); RunAndShowOutput($"checkout {localBranchName}"); } else { Fetch(); var remoteBranchDesignation = $"{DefaultRemote}/{localBranchName}"; GenLog.Info($"Checking out remote branch {remoteBranchDesignation} into local"); RunAndShowOutput($"checkout -t {remoteBranchDesignation}"); } RunAndShowOutput("submodule update --recursive"); }
public void AddOrUpdateProps(IEnumerable <JavaProp> props) { GenLog.Info($"Adding/Updating properties in {_path}"); var originalContent = _content; foreach (var pair in props) { AddOrUpdatePropImpl(pair.Key, pair.Value); } if (_content == originalContent) { GenLog.Info("No changes needed"); return; } GenLog.Info($"Updating {_path} on disk"); File.WriteAllText(_path, _content); }
RunNuGet(params string[] arguments) { var nuget = GetNuGet(); var argsJoined = string.Join(" ", arguments); GenLog.Info($"Running: {nuget} {argsJoined}"); // ReSharper disable once CoVariantArrayConversion var command = Medallion.Shell.Command.Run(nuget, arguments); var stdout = command.StandardOutput.ReadToEnd(); var stderr = command.StandardError.ReadToEnd(); GenLog.Info(stdout); GenLog.Info(stderr); GenLog.Info(command.Result.Success ? "Command success" : "Command failed!"); return(command.Result.Success, stdout, stderr); }
public static string GetShare(string name) { GenLog.Info($"Resolving share path for '{name}'"); var result = Values.Shares.FirstOrDefault(s => s.Name == name); if (result == null) { throw new ConfigurationException( $"Resource Resolver: Share {name} not found!"); } if (result.NeedsCredentials()) { void Login() { if (result.ForceLogin) { Shell.RunAndGetExitCode( "net", $"use /d {result.Path}"); } else if (Directory.Exists(result.Path)) { return; } var creds = GetCredential(result.CredentialsName); Shell.RunAndFailIfNotExitZero( "net", $"use {result.Path} /user:{creds.Username} {creds.Password}"); } Login(); } if (!Directory.Exists(result.Path)) { throw new UnauthorizedAccessException($"Unable to access {result.Path}."); } GenLog.Info($"Returning share path {result.Path}"); return(result.Path); }
public async Task <Repo> CloneIfNotExistUnderAsync(string directory, params string[] extraArgs) { var root = GetGeneratedRoot(directory); GenLog.Info($"Checking for existing clone at: {root}"); var configPath = Path.Combine(root, ".git", "config"); var bareConfigPath = Path.Combine(root, "config"); if (!File.Exists(configPath) && !File.Exists(bareConfigPath)) { return(await CloneUnder(directory, extraArgs)); } GenLog.Info("Clone found, not doing a new clone"); var repo = new Repo(root, this); repo.Fetch(); return(repo); }
private string FindChocoExecutable() { GenLog.Info("Looking for chocolatey"); var choco = Shell.GetExecutableInPath("choco"); if (!string.IsNullOrWhiteSpace(choco)) { return(choco); } var allUsersProfile = Environment.GetEnvironmentVariable("ALLUSERSPROFILE"); if (allUsersProfile == null) { throw new ConfigurationException("Cannot determine All Users profile directory"); } choco = Path.Combine(allUsersProfile, "chocolatey", "bin", "choco.exe"); if (File.Exists(choco)) { return(choco); } GenLog.Info("Installing Chocolatey"); var chocoInstallScript = Path.Combine(Path.GetTempPath(), "choco-install.ps1"); ADLib.Net.Client.DownloadFile( "https://chocolatey.org/install.ps1", chocoInstallScript); Shell.RunPowerShellScriptAndFailIfNotExitZero(chocoInstallScript); if (!File.Exists(choco)) { throw new ConfigurationException($"Chocolatey not found in {choco}, please install manually"); } _upgraded = true; return(choco); }
public static IEnumerable <PackageCollection> GetPackageCollectionsUnder(string root) { GenLog.Info($"Looking for NuGet packages used under {root}"); var pkgConfigFiles = Directory.GetFiles(root, "packages.config", SearchOption.AllDirectories) .Where(ShouldProcessDirectoryContaining); foreach (var file in pkgConfigFiles) { yield return(PackagesInConfigFile.Create(file)); } var projects = Directory.GetFiles(root, "*.csproj", SearchOption.AllDirectories) .Where(ShouldProcessProject); foreach (var file in projects) { yield return(PackagesInStandardProject.Create(file)); } }