-
Notifications
You must be signed in to change notification settings - Fork 30
Add shared Elastic.Documentation.Tooling libraries for all CLI binaries #548
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
// Licensed to Elasticsearch B.V under one or more agreements. | ||
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. | ||
// See the LICENSE file in the project root for more information | ||
|
||
using Actions.Core.Extensions; | ||
using Elastic.Documentation.Tooling.Logging; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.DependencyInjection.Extensions; | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Logging.Console; | ||
|
||
namespace Elastic.Documentation.Tooling; | ||
|
||
public static class DocumentationTooling | ||
{ | ||
public static ServiceProvider CreateServiceProvider(ref string[] args, Action<IServiceCollection>? configure = null) | ||
{ | ||
var defaultLogLevel = LogLevel.Information; | ||
ProcessCommandLineArguments(ref args, ref defaultLogLevel); | ||
|
||
var services = new ServiceCollection() | ||
.AddGitHubActionsCore(); | ||
services.TryAddEnumerable(ServiceDescriptor.Singleton<ConsoleFormatter, CondensedConsoleFormatter>()); | ||
_ = services.AddLogging(x => x | ||
.ClearProviders() | ||
.SetMinimumLevel(defaultLogLevel) | ||
.AddConsole(c => c.FormatterName = "condensed") | ||
); | ||
|
||
|
||
configure?.Invoke(services); | ||
|
||
return services.BuildServiceProvider(); | ||
} | ||
|
||
private static void ProcessCommandLineArguments(ref string[] args, ref LogLevel defaultLogLevel) | ||
{ | ||
var newArgs = new List<string>(); | ||
for (var i = 0; i < args.Length; i++) | ||
{ | ||
if (args[i] == "--log-level") | ||
{ | ||
if (args.Length > i + 1) | ||
defaultLogLevel = GetLogLevel(args[i + 1]); | ||
|
||
i++; | ||
} | ||
else | ||
newArgs.Add(args[i]); | ||
} | ||
|
||
args = [.. newArgs]; | ||
} | ||
|
||
private static LogLevel GetLogLevel(string? logLevel) => logLevel switch | ||
{ | ||
"trace" => LogLevel.Trace, | ||
"debug" => LogLevel.Debug, | ||
"information" => LogLevel.Information, | ||
"info" => LogLevel.Information, | ||
"warning" => LogLevel.Warning, | ||
"error" => LogLevel.Error, | ||
"critical" => LogLevel.Critical, | ||
_ => LogLevel.Information | ||
}; | ||
} |
17 changes: 17 additions & 0 deletions
17
Elastic.Documentation.Tooling/Elastic.Documentation.Tooling.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
<Project Sdk="Microsoft.NET.Sdk"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>net9.0</TargetFramework> | ||
<ImplicitUsings>enable</ImplicitUsings> | ||
<Nullable>enable</Nullable> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="ConsoleAppFramework.Abstractions" Version="5.4.1" /> | ||
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.2"/> | ||
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="9.0.2"/> | ||
<PackageReference Include="Github.Actions.Core" Version="9.0.0"/> | ||
<PackageReference Include="Crayon" Version="2.0.69"/> | ||
</ItemGroup> | ||
|
||
</Project> |
31 changes: 31 additions & 0 deletions
31
Elastic.Documentation.Tooling/Filters/CatchExceptionFilter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
// Licensed to Elasticsearch B.V under one or more agreements. | ||
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. | ||
// See the LICENSE file in the project root for more information | ||
|
||
using ConsoleAppFramework; | ||
using Microsoft.Extensions.Logging; | ||
|
||
namespace Elastic.Documentation.Tooling.Filters; | ||
|
||
public sealed class CatchExceptionFilter(ConsoleAppFilter next, ILogger<CatchExceptionFilter> logger) | ||
: ConsoleAppFilter(next) | ||
{ | ||
public override async Task InvokeAsync(ConsoleAppContext context, Cancel cancellationToken) | ||
{ | ||
try | ||
{ | ||
await Next.InvokeAsync(context, cancellationToken); | ||
} | ||
catch (Exception ex) | ||
{ | ||
if (ex is OperationCanceledException) | ||
{ | ||
logger.LogInformation("Cancellation requested, exiting."); | ||
return; | ||
} | ||
|
||
throw; | ||
|
||
} | ||
} | ||
} |
36 changes: 8 additions & 28 deletions
36
src/docs-builder/Cli/Filters.cs → ...tation.Tooling/Filters/StopwatchFilter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,51 +1,31 @@ | ||
// Licensed to Elasticsearch B.V under one or more agreements. | ||
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. | ||
// See the LICENSE file in the project root for more information | ||
|
||
using System.Diagnostics; | ||
using ConsoleAppFramework; | ||
using Microsoft.Extensions.Logging; | ||
|
||
namespace Documentation.Builder.Cli; | ||
namespace Elastic.Documentation.Tooling.Filters; | ||
|
||
internal sealed class StopwatchFilter(ConsoleAppFilter next) : ConsoleAppFilter(next) | ||
public class StopwatchFilter(ConsoleAppFilter next, ILogger<StopwatchFilter> logger) : ConsoleAppFilter(next) | ||
{ | ||
public override async Task InvokeAsync(ConsoleAppContext context, Cancel ctx) | ||
public override async Task InvokeAsync(ConsoleAppContext context, Cancel cancellationToken) | ||
{ | ||
var isHelpOrVersion = context.Arguments.Any(a => a is "--help" or "-h" or "--version"); | ||
var name = string.IsNullOrWhiteSpace(context.CommandName) ? "generate" : context.CommandName; | ||
var startTime = Stopwatch.GetTimestamp(); | ||
if (!isHelpOrVersion) | ||
ConsoleApp.Log($"{name} :: Starting..."); | ||
logger.LogInformation("{Name} :: Starting...", name); | ||
try | ||
{ | ||
await Next.InvokeAsync(context, ctx); | ||
await Next.InvokeAsync(context, cancellationToken); | ||
} | ||
finally | ||
{ | ||
var endTime = Stopwatch.GetElapsedTime(startTime); | ||
if (!isHelpOrVersion) | ||
ConsoleApp.Log($"{name} :: Finished in '{endTime}"); | ||
} | ||
} | ||
} | ||
|
||
internal sealed class CatchExceptionFilter(ConsoleAppFilter next) : ConsoleAppFilter(next) | ||
{ | ||
public override async Task InvokeAsync(ConsoleAppContext context, Cancel cancellationToken) | ||
{ | ||
try | ||
{ | ||
await Next.InvokeAsync(context, cancellationToken); | ||
} | ||
catch (Exception ex) | ||
{ | ||
if (ex is OperationCanceledException) | ||
{ | ||
ConsoleApp.Log("Cancellation requested, exiting."); | ||
return; | ||
} | ||
|
||
throw; | ||
|
||
logger.LogInformation("{Name} :: Finished in '{EndTime}'", name, endTime); | ||
} | ||
} | ||
} |
57 changes: 57 additions & 0 deletions
57
Elastic.Documentation.Tooling/Logging/CondensedConsoleLogger.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
// Licensed to Elasticsearch B.V under one or more agreements. | ||
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License. | ||
// See the LICENSE file in the project root for more information | ||
|
||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Logging.Abstractions; | ||
using Microsoft.Extensions.Logging.Console; | ||
using static Crayon.Output; | ||
|
||
namespace Elastic.Documentation.Tooling.Logging; | ||
|
||
public class CondensedConsoleFormatter() : ConsoleFormatter("condensed") | ||
{ | ||
public override void Write<TState>( | ||
in LogEntry<TState> logEntry, IExternalScopeProvider? scopeProvider, TextWriter textWriter | ||
) | ||
{ | ||
var now = DateTime.UtcNow; | ||
var message = logEntry.Formatter.Invoke(logEntry.State, logEntry.Exception); | ||
|
||
var logLevel = GetLogLevel(logEntry.LogLevel); | ||
var categoryName = logEntry.Category; | ||
|
||
var nowString = | ||
Environment.UserInteractive | ||
? "" | ||
: now.ToString("[yyyy-MM-ddTHH:mm:ss.fffZ] ", System.Globalization.CultureInfo.InvariantCulture); | ||
|
||
textWriter.WriteLine($"{nowString}{logLevel}::{ShortCategoryName(categoryName)}:: {message}"); | ||
} | ||
|
||
private static string GetLogLevel(LogLevel logLevel) => logLevel switch | ||
{ | ||
LogLevel.Trace => "trace", | ||
LogLevel.Debug => "debug", | ||
LogLevel.Information => Blue().Bold().Text("info "), | ||
LogLevel.Warning => Yellow().Bold().Text("warn "), | ||
LogLevel.Error => Red().Bold().Text("error"), | ||
LogLevel.Critical => Red().Bold().Text("fail "), | ||
LogLevel.None => " ", | ||
_ => "???" | ||
}; | ||
|
||
private static string ShortCategoryName(string category) | ||
{ | ||
var tokens = category.Split('.', StringSplitOptions.RemoveEmptyEntries); | ||
var s = string.Join(".", tokens.Take(tokens.Length - 1).Select(t => t.ToLowerInvariant().First()).ToArray()); | ||
if (s.Length > 0) | ||
s += "."; | ||
|
||
var maxLength = 22 - s.Length; | ||
var last = tokens.Last(); | ||
var start = Math.Max(0, last.Length - maxLength); | ||
s += last[start..]; | ||
return Dim().Text(s.PadRight(22)); | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
# Elastic.Documentation.Tooling | ||
|
||
This is a shared library for our command line tooling. | ||
|
||
Ensures we share the same logging infrastructure and command line helpers |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@reakaleek this is actually an important fix for docs-content and asciidocalypse since they generate from the root 😸