[backend/startup] Move CLI argument parsing to the very beginning of the startup process

This allows --printconfig and --help to work correctly despite improper configuration / missing files.
This commit is contained in:
Laura Hausmann 2024-04-15 23:28:16 +02:00
parent c25b613376
commit 450d859e19
No known key found for this signature in database
GPG key ID: D044E84C5BE01605
3 changed files with 32 additions and 21 deletions

View file

@ -1,4 +1,3 @@
using System.Reflection;
using System.Runtime.InteropServices;
using Iceshrimp.Backend.Core.Configuration;
using Iceshrimp.Backend.Core.Database;
@ -46,26 +45,6 @@ public static class WebApplicationExtensions
public static async Task<Config.InstanceSection> Initialize(this WebApplication app, string[] args)
{
if (args.Contains("-h") || args.Contains("--help") || args.Contains("-?"))
{
Console.WriteLine($"""
Usage: ./{typeof(Program).Assembly.GetName().Name} [options...]
--migrate Apply pending migrations, then exit
--migrate-and-start Apply pending migrations, then start the application
--printconfig Print the example config, then exit
--help Print information on available command line arguments
""");
Environment.Exit(0);
}
if (args.Contains("--printconfig"))
{
var assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var config = await File.ReadAllTextAsync(Path.Join(assemblyDir, "configuration.ini"));
Console.WriteLine(config);
Environment.Exit(0);
}
var instanceConfig = app.Configuration.GetSection("Instance").Get<Config.InstanceSection>() ??
throw new Exception("Failed to read Instance config section");
var workerId = app.Configuration.GetSection("Worker").Get<Config.WorkerSection>()?.WorkerId;

View file

@ -0,0 +1,29 @@
using System.Reflection;
namespace Iceshrimp.Backend.Core.Helpers;
public static class StartupHelpers
{
public static void ParseCliArguments(string[] args)
{
if (args.Contains("-h") || args.Contains("--help") || args.Contains("-?"))
{
Console.WriteLine($"""
Usage: ./{typeof(Program).Assembly.GetName().Name} [options...]
--migrate Apply pending migrations, then exit
--migrate-and-start Apply pending migrations, then start the application
--printconfig Print the example config, then exit
--help Print information on available command line arguments
""");
Environment.Exit(0);
}
if (args.Contains("--printconfig"))
{
var assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var config = File.ReadAllText(Path.Join(assemblyDir, "configuration.ini"));
Console.WriteLine(config);
Environment.Exit(0);
}
}
}

View file

@ -1,7 +1,10 @@
using Iceshrimp.Backend.Core.Extensions;
using Iceshrimp.Backend.Core.Helpers;
using Iceshrimp.Backend.Hubs;
using Iceshrimp.Backend.Hubs.Authentication;
StartupHelpers.ParseCliArguments(args);
var builder = WebApplication.CreateBuilder(args);
builder.Configuration.Sources.Clear();