Example #1
0
        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;
                }
            }
        }
Example #2
0
        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);
        }
Example #3
0
        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}");
        }
Example #4
0
        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);
                }
            }
        }
Example #5
0
        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);
        }
Example #6
0
 // 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());
 }
Example #7
0
        // 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);
        }
Example #8
0
        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);
        }
Example #9
0
 // 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());
 }
Example #10
0
        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);
        }
Example #11
0
        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);
        }
Example #12
0
 static ILog GetLogger(object obj)
 {
     //return new LoggerForInfo();
     //return theRefLog;
     // OR
     return(GenLog.For(obj.GetType().GetTypeInfo()));
 }
Example #13
0
        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);
                }
            }
        }
Example #14
0
        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);
            }
        }
Example #15
0
        // 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)));
        }
Example #16
0
        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);
        }
Example #17
0
        public static void CreateDirectory(string path)
        {
            if (Directory.Exists(path))
            {
                return;
            }

            GenLog.Info($"Creating directory {path}");
            Directory.CreateDirectory(path);
        }
Example #18
0
        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);
        }
Example #19
0
        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));
        }
Example #20
0
        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);
        }
Example #21
0
        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);
        }
Example #22
0
 public void Run()
 {
     try
     {
         DoWork();
         InteractionHandler.ExitWithSuccess("All done");
     }
     catch (Exception e)
     {
         GenLog.Error(e.StackTrace);
         InteractionHandler.ExitWithError(e.Message);
     }
 }
Example #23
0
        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);
        }
Example #24
0
        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);
        }
Example #25
0
        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);
        }
Example #26
0
        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}");
        }
Example #27
0
        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);
        }
Example #28
0
        public string GetChocoExecutable()
        {
            if (string.IsNullOrWhiteSpace(_choco))
            {
                _choco = FindChocoExecutable();
                if (!_upgraded)
                {
                    GenLog.Info("Upgrading Chocolatey");
                    InstallOrUpgradePackages("chocolatey");
                    _upgraded = true;
                }
            }

            return(_choco);
        }
Example #29
0
        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;
                }
            }
        }
Example #30
0
        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);
        }