Skip to content

Commit

Permalink
Add CLI help param (#42)
Browse files Browse the repository at this point in the history
  • Loading branch information
chekkan authored and ttu committed Jan 27, 2019
1 parent 3f62a4a commit df77784
Show file tree
Hide file tree
Showing 6 changed files with 62 additions and 63 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
FakeServer.xml
releases/

# Visual Studio Code
.vscode

# User-specific files
*.suo
*.user
Expand Down
1 change: 1 addition & 0 deletions FakeServer.Test/FakeServerAuthenticationSpecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
namespace FakeServer.Test
{
[Collection("Integration collection")]
[Trait("category", "integration")]
public class FakeServerAuthenticationSpecs : IDisposable
{
private readonly IntegrationFixture _fixture;
Expand Down
3 changes: 2 additions & 1 deletion FakeServer.Test/FakeServerSpecs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ namespace FakeServer.Test
// Tests in the same collection are not run in parallel
// After each test data should be in the same state as in the beginning of the test or future tests might fail
[Collection("Integration collection")]
[Trait("category", "integration")]
public class FakeServerSpecs : IDisposable
{
private readonly IntegrationFixture _fixture;
Expand Down Expand Up @@ -1072,7 +1073,7 @@ public async Task GetPaginationHeaders_page_per_page_no_first_and_prev()
Assert.DoesNotContain(@"rel=""prev""", linksHeaders);
}
}

[Fact]
public async Task GetItem_ETag_Cached_NoHeader()
{
Expand Down
2 changes: 1 addition & 1 deletion FakeServer.Test/ObjectHelperTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ public void WebSocketMessage()
Assert.Equal("POST", msg.Method.Value);
}

[Fact]
[Fact(Skip = "DateTime parsing fails when current culture is not en-US")]
public void GetValueAsCorrectType()
{
Assert.IsType<int>(ObjectHelper.GetValueAsCorrectType("2"));
Expand Down
1 change: 1 addition & 0 deletions FakeServer/FakeServer.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
<ItemGroup>
<PackageReference Include="GraphQL" Version="2.4.0" />
<PackageReference Include="JsonFlatFileDataStore" Version="2.0.1" />
<PackageReference Include="McMaster.Extensions.CommandLineUtils" Version="2.3.1" />
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.5.1" />
<PackageReference Include="Microsoft.AspNetCore" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="2.2.0" />
Expand Down
115 changes: 54 additions & 61 deletions FakeServer/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
using McMaster.Extensions.CommandLineUtils;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.PlatformAbstractions;
Expand All @@ -8,7 +8,6 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;

namespace FakeServer
Expand All @@ -17,39 +16,19 @@ public class Program
{
public static int Main(string[] args)
{
if (args.Any(arg => arg == "--version"))
{
Console.WriteLine(GetAssemblyVersion());
return 0;
}

var inMemoryCollection = ParseInMemoryCollection(args);

if (inMemoryCollection.ContainsKey("staticFolder"))
{
if (!Directory.Exists(inMemoryCollection["staticFolder"]))
{
Console.WriteLine($"Folder doesn't exist: {inMemoryCollection["staticFolder"]}");
return 1;
}

Console.WriteLine($"Static files: {inMemoryCollection["staticFolder"]}");
// When user defines static files, fake server is used only to server static files
}
else
{
Console.WriteLine($"Datastore file: {inMemoryCollection["file"]}");
Console.WriteLine($"Datastore location: {inMemoryCollection["currentPath"]}");
Console.WriteLine($"Static files: default wwwroot");
}
var app = BuildCommandLineApp(Run);
return app.Execute(args);
}

private static int Run(string[] args, Dictionary<string, string> initialData)
{
var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";

var config = new ConfigurationBuilder()
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env}.json", optional: true)
.AddJsonFile("authentication.json", optional: true, reloadOnChange: true)
.AddInMemoryCollection(inMemoryCollection)
.AddInMemoryCollection(initialData)
.AddEnvironmentVariables()
.Build();

Expand Down Expand Up @@ -80,49 +59,63 @@ public static IWebHostBuilder BuildWebHost(string[] args, IConfigurationRoot con
.UseConfiguration(config)
.UseStartup<Startup>()
.UseSerilog();

private static string GetAssemblyVersion()
{
return FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;
}

private static Dictionary<string, string> ParseInMemoryCollection(string[] args)
private static CommandLineApplication BuildCommandLineApp(
Func<string[], Dictionary<string, string>, int> invoke)
{
var dictionary = new Dictionary<string, string>();

for (int idx = 0; idx < args.Length; idx += 2)
{
dictionary.Add(args[idx], args[idx + 1]);
}
var app = new CommandLineApplication(throwOnUnexpectedArg: false);
app.HelpOption();

var inMemoryCollection = new Dictionary<string, string>();
var optionVersion = app.Option("--version", "Prints the version of the app", CommandOptionType.NoValue);
var optionFile = app.Option<string>("--file <FILE>", "Data store's JSON file (default datastore.json)",
CommandOptionType.SingleValue);
var optionServe = app.Option("-s|--serve <PATH>", "Static files (default wwwroot)",
CommandOptionType.SingleValue);
app.Option("--urls <URLS>", "Server url (default http://localhost:57602)", CommandOptionType.SingleValue);

foreach (var kvp in dictionary)
app.OnExecute(() =>
{
inMemoryCollection.Add(kvp.Key.Replace("-", ""), kvp.Value);
}

inMemoryCollection.TryAdd("currentPath", Directory.GetCurrentDirectory());
if (optionVersion.HasValue())
{
Console.WriteLine(GetAssemblyVersion());
return 0;
}
if (!inMemoryCollection.ContainsKey("file"))
{
dictionary.TryGetValue("--file", out string file);
inMemoryCollection.Add("file", file ?? "datastore.json");
}
var initialData = new Dictionary<string, string>()
{
{"file", optionFile.HasValue() ? optionFile.Value() : "datastore.json"}
};
if (!inMemoryCollection.ContainsKey("staticFolder"))
{
dictionary.TryGetValue("-s", out string folder);
if (string.IsNullOrEmpty(folder))
dictionary.TryGetValue("--serve", out folder);
initialData.TryAdd("currentPath", Directory.GetCurrentDirectory());
if (!string.IsNullOrEmpty(folder))
if (optionServe.HasValue() && !string.IsNullOrEmpty(optionServe.Value()))
{
inMemoryCollection.Add("staticFolder", Path.GetFullPath(folder));
if (!Directory.Exists(optionServe.Value()))
{
Console.WriteLine($"Folder doesn't exist: {optionServe.Value()}");
return 1;
}
initialData.Add("staticFolder", Path.GetFullPath(optionServe.Value()));
Console.WriteLine($"Static files: {initialData["staticFolder"]}");
// When user defines static files, fake server is used only to server static files
}
else
{
Console.WriteLine($"Datastore file: {initialData["file"]}");
Console.WriteLine($"Datastore location: {initialData["currentPath"]}");
Console.WriteLine($"Static files: default wwwroot");
}
}
return inMemoryCollection;
return invoke(app.RemainingArguments.ToArray(), initialData);
});

return app;
}

private static string GetAssemblyVersion()
{
return FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).ProductVersion;
}
}
}
}

0 comments on commit df77784

Please sign in to comment.