public virtual void Report(ProgressChanged value)
 {
     if (value.IsUnknowSize)
     {
         io?.OverwriteError($"{prompt}Downloading ({AbstractHelper.FormatMemory(value.ReceivedSize)})", false);
     }
     else
     {
         io?.OverwriteError($"{prompt}Downloading (<comment>{value}%</comment>)", false);
     }
 }
示例#2
0
        /// <summary>
        /// Writes a message to the output.
        /// </summary>
        /// <param name="messages">An array of string.</param>
        /// <param name="newLine">Whether to add a newline or not.</param>
        /// <param name="stderr">Whether is stderr output.</param>
        /// <param name="verbosity">Verbosity level from the verbosity * constants.</param>
        private void DoWrite(string[] messages, bool newLine = false, bool stderr = false,
                             Verbosities verbosity           = Verbosities.Normal)
        {
            if (!VerbosityMapping.TryGetValue(verbosity, out OutputOptions options))
            {
                return;
            }

            if (stopwatch != null && stopwatch.IsRunning)
            {
                var memoryUsage = AbstractHelper.FormatMemory(Environment.WorkingSet);
                var timeSpent   = stopwatch.Elapsed;
                messages = Arr.Map(messages, (message) =>
                {
                    if (!string.IsNullOrEmpty(message))
                    {
                        return($"[{memoryUsage}/{timeSpent.TotalSeconds.ToString("0.00")}s] {message}");
                    }

                    return(message);
                });
            }

            if (stderr && Output is IOutputConsole consoleOutput)
            {
                var errorOutput = consoleOutput.GetErrorOutput();
                Array.ForEach(messages, (message) =>
                {
                    errorOutput.Write(message, newLine, options);
                });

                if (SatisfyVerbosity(errorOutput, options))
                {
                    lastMessageError = string.Join(newLine ? Environment.NewLine : string.Empty, messages);
                }

                return;
            }

            Array.ForEach(messages, (message) =>
            {
                Output.Write(message, newLine, options);
            });

            if (SatisfyVerbosity(Output, options))
            {
                lastMessage = string.Join(newLine ? Environment.NewLine : string.Empty, messages);
            }
        }
示例#3
0
        /// <inheritdoc />
        protected override int DoRun(IInput input, IOutput output)
        {
            disablePluginsByDefault = input.HasRawOption("--no-plugins");
            var ioConsole = new IOConsole(input, output);

            io = ioConsole;

            var commandName = GetCommandName(input);

            TryGetCommand(commandName, out BaseCommand command);

            LoadPluginCommands(command);

            var isProxyCommand = false;

            if (!string.IsNullOrEmpty(commandName) || command != null)
            {
                // Maybe the command is provided by the plugin. If we can't find
                // us again, we will stop intercepting the exception.
                if (command == null)
                {
                    command = Find(commandName);
                }

                isProxyCommand = command is Command.BaseCommand baseCommand && baseCommand.IsProxyCommand;
            }

            if (!isProxyCommand)
            {
                io.WriteError(
                    $"Running {Bucket.GetVersionPretty()} ({Bucket.GetVersion()},{Bucket.GetReleaseDataPretty()}) on {Platform.GetOSInfo()}",
                    verbosity: Verbosities.Debug);

                if (!(command is CommandSelfUpdate) && Bucket.IsDev && (DateTime.Now - Bucket.GetReleaseData()) > new TimeSpan(60, 0, 0, 0, 0))
                {
                    io.WriteError(
                        "<warning>Warning: This development build of bucket is over 60 days old. It is recommended to update it by running \"self-update\" to get the latest version.</warning>");
                }
            }

            Stopwatch stopWatch = null;

            try
            {
                if (input.HasRawOption("--profile"))
                {
                    stopWatch = new Stopwatch();
                    ioConsole.SetDebugging(stopWatch);
                }

                stopWatch?.Start();
                var exitCode = base.DoRun(input, output);
                stopWatch?.Stop();

                if (stopWatch != null)
                {
                    var memoryUsage = AbstractHelper.FormatMemory(Environment.WorkingSet);
                    var timeSpent   = stopWatch.Elapsed;
                    io.WriteError(string.Empty);
                    io.WriteError($"<info>Memory usage: {memoryUsage}, total time: {timeSpent.TotalSeconds.ToString("0.00")}s</info>");
                    io.WriteError(string.Empty);
                }

                return(exitCode);
            }
            catch (ScriptExecutionException ex)
            {
                return(ex.ExitCode);
            }
        }
示例#4
0
        /// <inheritdoc />
        public bool GC(int ttl, int maxSize)
        {
            if (!Enable)
            {
                return(false);
            }

            cacheCollected = true;

            var candidates  = new SortSet <IMetaData, DateTime>();
            var directories = new Queue <string>();

            void AddCandidate(string file)
            {
                var meta = fileSystem.GetMetaData(file);

                candidates.Add(meta, meta.LastAccessTime);
            }

            if (!fileSystem.Exists(CacheDirectory, FileSystemOptions.Directory))
            {
                return(true);
            }

            var contents = fileSystem.GetContents(CacheDirectory);

            Array.ForEach(contents.GetDirectories(), directories.Enqueue);
            Array.ForEach(contents.GetFiles(), AddCandidate);

            while (directories.Count > 0)
            {
#pragma warning disable S4158 // bug: Empty collections should not be accessed or iterated
                contents = fileSystem.GetContents(directories.Dequeue());
#pragma warning restore S4158

                Array.ForEach(contents.GetDirectories(), directories.Enqueue);
                Array.ForEach(contents.GetFiles(), AddCandidate);
            }

            var freeSpace    = 0L;
            var deletedFiles = 0;

            // gc with ttl.
            var expire = DateTime.Now.AddSeconds(-ttl);
            foreach (var candidate in candidates)
            {
                if (candidate.LastAccessTime >= expire)
                {
                    // The sorset will have sorted the modification time.
                    break;
                }

                fileSystem.Delete(candidate.Path);
                candidates.Remove(candidate);
                freeSpace += candidate.Size;
                deletedFiles++;
            }

            void PromptFree()
            {
                io.WriteError($"Cache garbage collection completed, delete {deletedFiles} files, free {AbstractHelper.FormatMemory(freeSpace)} space.");
            }

            // gc with maxSize
            var totalSize = fileSystem.GetMetaData(CacheDirectory).Size;
            if (totalSize < maxSize)
            {
                PromptFree();
                return(true);
            }

            foreach (var candidate in candidates)
            {
                if (totalSize < maxSize)
                {
                    break;
                }

                fileSystem.Delete(candidate.Path);
                totalSize -= candidate.Size;
                freeSpace += candidate.Size;
                deletedFiles++;
            }

            PromptFree();
            return(true);
        }