DimerceDemoApplication/services/ApplicationConfigurationService.cs

93 lines
3.2 KiB
C#
Raw Permalink Normal View History

namespace Configuration
{
2023-01-06 15:08:26 +00:00
public sealed class ApplicationConfigurationService
{
private FileInfo[] jsonFiles;
public FileInfo[] JsonFilesInfo
{
get { return jsonFiles; }
private set
{
jsonFiles = value.Reverse().ToArray();
}
}
private FileInfo outputFile;
public FileInfo OutputFile{
get {return outputFile;}
private set
{
if (!canCreateFile(value.FullName))
throw new DemoApplicationConfigurationException($"Given output name '{value.FullName}' cannot be used");
outputFile = value;
}
}
2023-01-06 15:08:26 +00:00
public static ApplicationConfigurationService InitializeFrom(string[] args)
{
if (args.Length < 3)
throw new DemoApplicationConfigurationException("Must have atleast: 1 flag, 1 path, 1 output filename");
var outputFileName = new FileInfo(args.Last());
// Remove last file-name arg, to get a more consistent array
var strippedArgs = args.SkipLast(1).ToArray();
string[] givenFlags = strippedArgs.Where((value, index) => index % 2 == 0).ToArray();
string[] givenFilePaths = strippedArgs.Where((value, index) => index % 2 != 0).ToArray();
try
{
// Assert only a single 'd' was passed
if ( givenFlags.Length == 1 && givenFlags[0].Equals("-d") ) {
string[] filesInDirectory = Directory.GetFiles(givenFilePaths[0]);
2023-01-06 15:08:26 +00:00
return new ApplicationConfigurationService {
OutputFile = outputFileName,
JsonFilesInfo = filesInDirectory.Select(name => new FileInfo(name)).ToArray(),
};
}
// Assert only '-f' were passed
else if (givenFlags.All((string flag) => flag.Equals("-f"))) {
2023-01-06 15:08:26 +00:00
return new ApplicationConfigurationService {
OutputFile = outputFileName,
JsonFilesInfo = givenFilePaths.Select(name => new FileInfo(name)).ToArray(),
};
}
else {
throw new DemoApplicationConfigurationException("Must have either 1 flag that is '-d', or all flags must be '-f");
}
} catch (Exception)
{
Console.WriteLine("Something went wrong");
throw;
}
}
private static bool canCreateFile(string filename) {
try
{
using (File.Create(filename)) {
File.Delete(filename);
return true;
}
}
catch
{
return false;
}
}
[Serializable]
internal sealed class DemoApplicationConfigurationException : Exception
{
public DemoApplicationConfigurationException()
{
}
public DemoApplicationConfigurationException(string? message) : base(message)
{
}
}
}
}