Skip to content

Commit

Permalink
Merge pull request #57 from davewalker5/cli-help
Browse files Browse the repository at this point in the history
Added command line help to the lookup tool
  • Loading branch information
davewalker5 authored Aug 21, 2024
2 parents 3a4a1cf + 6f0aeca commit cbfdc49
Show file tree
Hide file tree
Showing 7 changed files with 145 additions and 47 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
public enum CommandLineOptionType
{
Unknown,
Help,
Lookup,
Import,
Export,
Expand Down
13 changes: 13 additions & 0 deletions src/MusicCatalogue.Entities/Interfaces/ICommandLineParser.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using MusicCatalogue.Entities.CommandLine;

namespace MusicCatalogue.Entities.Interfaces
{
public interface ICommandLineParser
{
void Add(CommandLineOptionType optionType, bool isOperation, string name, string shortName, string description, int minimumNumberOfValues, int maximumNumberOfValues);
List<string>? GetValues(CommandLineOptionType optionType);
bool IsPresent(CommandLineOptionType optionType);
void Help();
void Parse(IEnumerable<string> args);
}
}
9 changes: 9 additions & 0 deletions src/MusicCatalogue.Entities/Interfaces/IHelpGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
using MusicCatalogue.Entities.CommandLine;

namespace MusicCatalogue.Entities.Interfaces
{
public interface IHelpGenerator
{
void Generate(IEnumerable<CommandLineOption> options);
}
}
25 changes: 23 additions & 2 deletions src/MusicCatalogue.Logic/CommandLine/CommandLineParser.cs
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
using MusicCatalogue.Entities.CommandLine;
using MusicCatalogue.Entities.Exceptions;
using MusicCatalogue.Entities.Interfaces;

namespace MusicCatalogue.Logic.CommandLine
{
public class CommandLineParser
public class CommandLineParser : ICommandLineParser
{
private readonly List<CommandLineOption> _options = new List<CommandLineOption>();
private readonly Dictionary<CommandLineOptionType, CommandLineOptionValue> _values = new Dictionary<CommandLineOptionType, CommandLineOptionValue>();
private readonly IHelpGenerator? _helpGenerator = null;

public CommandLineParser() { }

public CommandLineParser(IHelpGenerator generator)
=> _helpGenerator = generator;

/// <summary>
/// Add an option to the available command line options
Expand Down Expand Up @@ -70,6 +77,14 @@ public void Parse(IEnumerable<string> args)
CheckForSingleOperation();
}

/// <summary>
/// Return true if a command line option has been specified
/// </summary>
/// <param name="optionType"></param>
/// <returns></returns>
public bool IsPresent(CommandLineOptionType optionType)
=> _values.ContainsKey(optionType);

/// <summary>
/// Return the valus for the specified option type
/// </summary>
Expand All @@ -79,14 +94,20 @@ public void Parse(IEnumerable<string> args)
{
List<string>? values = null;

if (_values.ContainsKey(optionType))
if (IsPresent(optionType))
{
values = _values[optionType].Values;
}

return values;
}

/// <summary>
/// Generate help
/// </summary>
public void Help()
=> _helpGenerator?.Generate(_options);

/// <summary>
/// Check that each supplied option has sufficient values with it
/// </summary>
Expand Down
43 changes: 43 additions & 0 deletions src/MusicCatalogue.LookupTool/Logic/HelpTabulator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
using MusicCatalogue.Entities.CommandLine;
using MusicCatalogue.Entities.Interfaces;
using Spectre.Console;

namespace MusicCatalogue.LookupTool.Logic
{

public class HelpTabulator : IHelpGenerator
{
/// <summary>
/// Tabulate a collection of available command line options
/// </summary>
/// <param name="options"></param>
public void Generate(IEnumerable<CommandLineOption> options)
{
var table = new Table();

table.AddColumn("Option");
table.AddColumn("Short Form");
table.AddColumn("Min Values");
table.AddColumn("Max Values");
table.AddColumn("Description");

foreach (var option in options)
{
var rowData = new string[] {
GetCellData(option.Name),
GetCellData(option.ShortName),
GetCellData(option.MinimumNumberOfValues.ToString()),
GetCellData(option.MaximumNumberOfValues.ToString()),
GetCellData(option.Description)
};

table.AddRow(rowData);
}

AnsiConsole.Write(table);
}

private string GetCellData(string value)
=> $"[white]{value}[/]";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ReleaseVersion>1.24.0.0</ReleaseVersion>
<FileVersion>1.24.0.0</FileVersion>
<ProductVersion>1.24.0</ProductVersion>
<ReleaseVersion>1.25.0.0</ReleaseVersion>
<FileVersion>1.25.0.0</FileVersion>
<ProductVersion>1.25.0</ProductVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
Expand All @@ -26,6 +26,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Spectre.Console" Version="0.49.1" />
</ItemGroup>

<ItemGroup>
Expand Down
94 changes: 52 additions & 42 deletions src/MusicCatalogue.LookupTool/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
using System.Diagnostics;
using System.Reflection;

namespace MusicCatalogue.LookupPoC
namespace MusicCatalogue.LookupTool
{
public static class Program
{
Expand All @@ -24,60 +24,70 @@ public static class Program
/// <returns></returns>
public static async Task Main(string[] args)
{
// Read the application settings
MusicApplicationSettings? settings = new MusicCatalogueConfigReader().Read("appsettings.json");

// Configure the log file
FileLogger logger = new FileLogger();
logger.Initialise(settings!.LogFile, settings.MinimumLogLevel);

// Get the version number and application title
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo info = FileVersionInfo.GetVersionInfo(assembly.Location);
var title = $"Music Catalogue Lookup Tool v{info.FileVersion}";

// Log the startup messages
Console.WriteLine($"{title}\n");
logger.LogMessage(Severity.Info, new string('=', 80));
logger.LogMessage(Severity.Info, title);

try
{
// Parse the command line
CommandLineParser parser = new();
CommandLineParser parser = new(new HelpTabulator());
parser.Add(CommandLineOptionType.Help, true, "--help", "-h", "Show command line help", 0, 0);
parser.Add(CommandLineOptionType.Lookup, true, "--lookup", "-l", "Lookup an album and display its details", 3, 3);
parser.Add(CommandLineOptionType.Import, true, "--import", "-i", "Import data from a CSV format file", 1, 1);
parser.Add(CommandLineOptionType.Export, true, "--export", "-e", "Export the collection or equipment register to a CSV file or Excel Workbook", 2, 2);
parser.Parse(args);

// Configure the business logic factory
var context = new MusicCatalogueDbContextFactory().CreateDbContext(Array.Empty<string>());
var factory = new MusicCatalogueFactory(context);

// If this is a lookup, look up the album details
var values = parser.GetValues(CommandLineOptionType.Lookup);
if (values != null)
// If help's been requested, show help and exit
if (parser.IsPresent(CommandLineOptionType.Help))
{
// Determine the target for new albums (catalogue or wish list) and lookup the album
var targetType = (TargetType)Enum.Parse(typeof(TargetType), values[2]);
var storeInWishList = targetType == TargetType.wishlist;
await new AlbumLookup(logger, factory, settings!).LookupAlbum(values[0], values[1], storeInWishList);
parser.Help();
}

// If this is an import, import data from the specified CSV file
values = parser.GetValues(CommandLineOptionType.Import);
if (values != null)
else
{
new DataImport(logger, factory).Import(values[0]);
}
// Read the application settings
MusicApplicationSettings? settings = new MusicCatalogueConfigReader().Read("appsettings.json");

// If this is an export, export the collection to the specified file
values = parser.GetValues(CommandLineOptionType.Export);
if (values != null)
{
var exportType = (ExportType)Enum.Parse(typeof(ExportType), values[0]);
IDataExporter exporter = exportType == ExportType.music ? new CatalogueExporter(logger, factory) : new EquipmentExporter(logger, factory);
exporter.Export(values[1]);
// Configure the log file
FileLogger logger = new FileLogger();
logger.Initialise(settings!.LogFile, settings.MinimumLogLevel);

// Get the version number and application title
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo info = FileVersionInfo.GetVersionInfo(assembly.Location);
var title = $"Music Catalogue Lookup Tool v{info.FileVersion}";

// Log the startup messages
Console.WriteLine($"{title}\n");
logger.LogMessage(Severity.Info, new string('=', 80));
logger.LogMessage(Severity.Info, title);

// Configure the business logic factory
var context = new MusicCatalogueDbContextFactory().CreateDbContext(Array.Empty<string>());
var factory = new MusicCatalogueFactory(context);

// If this is a lookup, look up the album details
var values = parser.GetValues(CommandLineOptionType.Lookup);
if (values != null)
{
// Determine the target for new albums (catalogue or wish list) and lookup the album
var targetType = (TargetType)Enum.Parse(typeof(TargetType), values[2]);
var storeInWishList = targetType == TargetType.wishlist;
await new AlbumLookup(logger, factory, settings!).LookupAlbum(values[0], values[1], storeInWishList);
}

// If this is an import, import data from the specified CSV file
values = parser.GetValues(CommandLineOptionType.Import);
if (values != null)
{
new DataImport(logger, factory).Import(values[0]);
}

// If this is an export, export the collection to the specified file
values = parser.GetValues(CommandLineOptionType.Export);
if (values != null)
{
var exportType = (ExportType)Enum.Parse(typeof(ExportType), values[0]);
IDataExporter exporter = exportType == ExportType.music ? new CatalogueExporter(logger, factory) : new EquipmentExporter(logger, factory);
exporter.Export(values[1]);
}
}
}
catch (Exception ex)
Expand Down

0 comments on commit cbfdc49

Please sign in to comment.