Skip to content

Commit

Permalink
Basic stats reporting started
Browse files Browse the repository at this point in the history
  • Loading branch information
scottbilas committed Apr 12, 2024
1 parent 51320a1 commit df7e6cd
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 15 deletions.
41 changes: 35 additions & 6 deletions src/Stale.Cli/Context.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,37 @@

#pragma warning disable CA1822

enum StatType
{
Init,
Command,
}

class Stat
{
DateTime? _start, _stop;

public void Start()
{
if (_start != null)
throw new InvalidOperationException("already started");
_start = DateTime.Now;
}

public void Stop()
{
if (_start == null)
throw new InvalidOperationException("not started");
if (_stop != null)
throw new InvalidOperationException("already stopped");
_stop = DateTime.Now;
}

public DateTime StartTime => _start ?? throw new InvalidOperationException("did not start");
public DateTime StopTime => _stop ?? throw new InvalidOperationException("did not stop");
public TimeSpan Elapsed => StopTime - StartTime;
}

class Context : IDisposable
{
readonly CancellationTokenSource _cancelSource = new();
Expand Down Expand Up @@ -42,11 +73,6 @@ public void Verbose(string text)
public void OutLine() =>
Terminal.OutLine();

public void OutLine<T>(T value) =>
Terminal.OutLine(value);
public void Out<T>(T value) =>
Terminal.Out(value);

public void OutLine(ReadOnlySpan<char> span)
{
Terminal.Out(span); // no OutLine provided for ReadOnlySpan<char>
Expand All @@ -61,7 +87,7 @@ public void Out(IRenderable renderable) =>
Terminal.Out(renderable.ToAnsi());

public void OutMarkupLine(string text) =>
_ansiConsole.MarkupLine(text!);
_ansiConsole.MarkupLine(text);
public void OutMarkup(string text) =>
_ansiConsole.Markup(text);
public void OutMarkupLineInterp(FormattableString value) =>
Expand Down Expand Up @@ -98,6 +124,8 @@ void OutDump<T>(T value, string? label, ColorConfig colors) => value.Dump(
output: s_dumpOutput,
tableConfig: new() { ShowTableHeaders = false });

public Stat this[StatType type] => _stats[(int)type];

class TerminalAnsiConsole(Context ctx) : IAnsiConsole
{
// we only need Write()
Expand Down Expand Up @@ -125,6 +153,7 @@ class TerminalDumpOutput : IDumpOutput
}

readonly IAnsiConsole _ansiConsole;
readonly Stat[] _stats = EnumUtility.GetNames<StatType>().Select(_ => new Stat()).ToArray();

static readonly IDumpOutput s_dumpOutput = new TerminalDumpOutput();
static readonly ColorConfig k_verboseDumpColors = new(new DumpColor("#808080"));
Expand Down
54 changes: 45 additions & 9 deletions src/Stale.Cli/StaleCli.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@

var programStart = DateTime.Now;
using var ctx = new Context();
ctx[StatType.Init].Start();
var logStats = false;

// ReSharper disable AccessToDisposedClosure
// ^ talking about ctx here, it's ok, it outlives everything
Expand Down Expand Up @@ -40,6 +42,8 @@
{
if (args[i] == "--verbose")
isVerbose = true;
else if (args[i] == "--stats")
logStats = true;
else if (args[i] == "--cwd")
{
if (++i == args.Length)
Expand All @@ -59,6 +63,9 @@
ctx.VerboseLine("Enabling verbose mode");
}

if (logStats && ctx.IsVerbose)
ctx.VerboseLine("Enabling stats printout at end");

if (useCwd != null)
{
if (ctx.IsVerbose)
Expand Down Expand Up @@ -154,17 +161,46 @@

int Run(Func<Task<CliExitCode>> task)
{
var operationStart = DateTime.Now;
ctx[StatType.Init].Stop();

ctx[StatType.Command].Start();
var result = task().Result;
ctx[StatType.Command].Stop();

if (ctx.IsVerbose)
if (logStats)
{
var operationElapsed = DateTime.Now - operationStart;
ctx.OutMarkupLine("[aqua]-- Stats from run --[/]");
var table = new Table() { Border = TableBorder.Minimal };
table.AddColumn("Stat");
table.AddColumn("Start");
table.AddColumn("Stop");
table.AddColumn("Elapsed");

foreach (var statType in EnumUtility.GetValues<StatType>())
{
var stat = ctx[statType];
table.AddRow(
statType.ToString(),
stat.StartTime.ToString("hh:mm:ss.fff"),
stat.StopTime.ToString("hh:mm:ss.fff"),
stat.Elapsed.TotalSeconds.ToString("F3"));
}

var totalStart = ctx[EnumUtility.GetValues<StatType>().First()].StartTime;
var totalStop = ctx[EnumUtility.GetValues<StatType>().Last()].StopTime;
table.AddRow(
"Total",
totalStart.ToString("hh:mm:ss.fff"),
totalStop.ToString("hh:mm:ss.fff"),
(totalStop - totalStart).TotalSeconds.ToString("F3"));

ctx.Out(table);

/* var operationElapsed = DateTime.Now - operationStart;
var programElapsed = DateTime.Now - programStart;
ctx.VerboseLine(
ctx.OutLine(
$"Finished in {operationElapsed.TotalSeconds:F3}s (total {programElapsed.TotalSeconds:F3}s) "+
$"with exit code {result} ({(int)result})");
$"with exit code {result} ({(int)result})");*/
}

return (int)result;
Expand All @@ -181,10 +217,10 @@ async Task<CliExitCode> Main(string command, IReadOnlyList<string> args)
const string stderrColor = "white on darkred";

var status = $">{process.Id} $ {command} {CliUtility.CommandLineArgsToString(args)}";
if (status.Length <= dims.Width)
ctx.OutMarkupLine($"[{statusColor}]{status.PadRight(dims.Width).EscapeMarkup()}[/]");
else
ctx.OutMarkupLine($"[{statusColor}]{status[..(dims.Width-1)].EscapeMarkup()}[/][blue]»[/]");
ctx.OutMarkupLine(
status.Length <= dims.Width
? $"[{statusColor}]{status.PadRight(dims.Width).EscapeMarkup()}[/]"
: $"[{statusColor}]{status[..(dims.Width-1)].EscapeMarkup()}[/][blue]»[/]");

await foreach (var capture in captures.ReadAllAsync(ctx.CancelToken))
{
Expand Down
1 change: 1 addition & 0 deletions src/Stale.Cli/StaleCli.docopt.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,5 @@ Options:
Special:
--verbose Log a lot of detail about what is happening. This can be applied to any command line as long as it appears
before anything else.
--stats Log cheap but useful stats about the run after command completion.
--cwd Use this as the working dir for {0}. Defaults to shell's working dir.

0 comments on commit df7e6cd

Please sign in to comment.