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; } } }
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); }
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}"); }
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); } } }
public static string GetClientIfFound() { if (!string.IsNullOrWhiteSpace(_gitPath)) { return(_gitPath); } _gitPath = Shell.GetExecutableInPath("git"); if (string.IsNullOrWhiteSpace(_gitPath)) { _gitPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles)}\git\bin\git.exe"; } if (!File.Exists(_gitPath)) { _gitPath = $@"{Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)}\git\bin\git.exe"; } if (!File.Exists(_gitPath)) { GenLog.Error("git.exe not found in any standard location"); _gitPath = null; } return(_gitPath); }
// 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()); }
// 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 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); }
// 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()); }
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); }
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); }
static ILog GetLogger(object obj) { //return new LoggerForInfo(); //return theRefLog; // OR return(GenLog.For(obj.GetType().GetTypeInfo())); }
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); } } }
protected override void Parse() { GenLog.Debug($"Parsing for NuGet packages in {PackagesConfigFile}"); var xelement = GetParsedXml(PackagesConfigFile); var packages = xelement.Descendants("package"); foreach (var packageElement in packages) { var id = packageElement.Attribute("id")?.Value; var versionRaw = packageElement.Attribute("version")?.Value; if (id == null || versionRaw == null) { throw new Exception($"Invalid syntax in {PackagesConfigFile}"); } var result = Statics.GetPackageDefinition(id, versionRaw); if (result == null) { continue; } GenLog.Debug($"Found {result}"); Packages.Add(result); } }
// 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 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 void CreateDirectory(string path) { if (Directory.Exists(path)) { return; } GenLog.Info($"Creating directory {path}"); Directory.CreateDirectory(path); }
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 IInteractionHandler GetHandler(IInteractivityOptions options) { if (options.Pause) { GenLog.Debug("Using TemporaryConsoleInteractionHandler"); return(new TemporaryConsoleInteractionHandler(options)); } GenLog.Debug("Using ConsoleInteractionHandler"); return(new ConsoleInteractionHandler(options)); }
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); }
public void Run() { try { DoWork(); InteractionHandler.ExitWithSuccess("All done"); } catch (Exception e) { GenLog.Error(e.StackTrace); InteractionHandler.ExitWithError(e.Message); } }
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 PackageDefinition GetPackageDefinition(string packageId, string versionRaw) { try { var version = NuGetVersion.Parse(versionRaw); return(new PackageDefinition(packageId, version)); } catch (Exception) { GenLog.Warning($"Ignoring unparsable version for {packageId}: {versionRaw}"); } return(null); }
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 static async Task <(int exitCode, string stdout, string stderr)> RunSilent(string program, params object[] args) { var argsPrinted = args.Length == 0 ? "" : string.Join(" ", args); GenLog.Debug($"{program} {argsPrinted}"); var command = Command.Run(program, args); await command.Task; var stdout = await command.StandardOutput.ReadToEndAsync(); var stderr = await command.StandardError.ReadToEndAsync(); return(command.Result.ExitCode, stdout, stderr); }
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; } } }
protected static XDocument GetParsedXml(string file) { XDocument xelement; try { xelement = XDocument.Parse(File.ReadAllText(file)); } catch (XmlException e) { GenLog.Error($"XML Exception while loading {file}: {e.Message}"); throw; } return(xelement); }