Skip to content
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

Dotnet try publish #741

Merged
merged 17 commits into from
May 7, 2020
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 158 additions & 0 deletions MLS.Agent.Tests/CommandLine/PublishCommandTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,158 @@
using System.Collections.Generic;
using System.CommandLine.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using FluentAssertions;
using MLS.Agent.CommandLine;
using MLS.Agent.Tools;
using MLS.Agent.Tools.Tests;
using WorkspaceServer.Tests;
using Xunit;
using Xunit.Abstractions;

namespace MLS.Agent.Tests.CommandLine
{
public class PublishCommandTests
{
private const string CsprojContents = @"<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
</Project>
";

private const string CompilingProgramWithRegionCs = @"
using System;

public class Program
{
public static void Main(string[] args)
{
#region null_coalesce
var length = (args[0] as string)?.Length ?? 0;
#endregion

#region userCodeRegion
#endregion
}
}";

public class WithMarkdownOutputFormat : WithPublish
{
public WithMarkdownOutputFormat(ITestOutputHelper output) : base(output) {}

[Theory]
[InlineData("##Title")]
[InlineData("markdown with line\r\nbreak")]
[InlineData("markdown with linux line\nbreak")]
[InlineData("[link](https://try.dot.net/)")]
public async Task When_there_are_no_code_fence_annotations_markdown_is_unchanged(string markdown)
{
var files = PrepareFiles(
("doc.md", markdown)
);

var (publishOutput, resultCode) = await DoPublish(files).ConfigureAwait(false);

resultCode.Should().Be(0);
publishOutput.OutputFiles.Single().Content.Should().Be(markdown);
}

[Theory]
[InlineData(@"
## C# null coalesce example
``` cs --source-file ./project/Program.cs --region null_coalesce --project ./project/some.csproj
```
")] [InlineData(@"
## C# null coalesce example
``` cs --source-file ./project/Program.cs --region null_coalesce --project ./project/some.csproj
var length = some buggy c# example code

```
")]
public async Task When_there_are_code_fence_annotations_in_markdown_content_of_the_fenced_section_is_replaced_with_the_project_code(string markdown)
{
var files = PrepareFiles(
("./folder/project/some.csproj", CsprojContents),
("./folder/project/Program.cs", CompilingProgramWithRegionCs),
("./folder/doc.md", markdown)
);

var (publishOutput, resultCode) = await DoPublish(files).ConfigureAwait(false);
ax0l0tl marked this conversation as resolved.
Show resolved Hide resolved

resultCode.Should().Be(0);
MarkdownShouldBeEquivalent(publishOutput.OutputFiles.Single().Content, @"
## C# null coalesce example
``` cs --source-file ./project/Program.cs --region null_coalesce --project ./project/some.csproj
var length = (args[0] as string)?.Length ?? 0;
```
");
}
}

public abstract class WithPublish
{
private static PublishOptions Options(IDirectoryAccessor source, IDirectoryAccessor target = null) => new PublishOptions(source, target ?? source, PublishFormat.Markdown);

private readonly ITestOutputHelper _output;

protected WithPublish(ITestOutputHelper output) => _output = output;

protected static IDirectoryAccessor PrepareFiles(params (string path, string content)[] files)
{
var rootDirectory = Create.EmptyWorkspace(isRebuildablePackage: true).Directory;

var directoryAccessor = new InMemoryDirectoryAccessor(rootDirectory);
foreach (var file in files)
directoryAccessor.Add(file);
directoryAccessor.CreateFiles();

return directoryAccessor;
}

protected async Task<(PublishOutput publishOutput, int resultCode)> DoPublish(IDirectoryAccessor source)
{
var console = new TestConsole();

var output = new PublishOutput();
void WriteOutput(string path, string content) => output.Add(path, content);

var resultCode = await PublishCommand.Do(Options(source), console, writeOutput: WriteOutput).ConfigureAwait(false);

_output.WriteLine(console.Out.ToString());
return (output, resultCode);
}
}

static void MarkdownShouldBeEquivalent(string expected, string actual)
{
static string Normalize(string input) => Regex.Replace(input.Trim(), @"[\s]+", " ");

var expectedNormalized = Normalize(expected);
var actualNormalized = Normalize(actual);

actualNormalized.Should().Be(expectedNormalized);
}

public class PublishOutput
{
private readonly List<OutputFile> _outputFiles = new List<OutputFile>();
public IEnumerable<OutputFile> OutputFiles => _outputFiles;

public void Add(string path, string content) => _outputFiles.Add(new OutputFile(path, content));
}

public class OutputFile
{
public string Path { get; }
public string Content { get; }

public OutputFile(string path, string content)
{
Path = path;
Content = content;
}
}
}
}
15 changes: 4 additions & 11 deletions MLS.Agent.Tools/FileSystemDirectoryAccessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,10 @@ public FileSystemInfo GetFullyQualifiedPath(RelativePath path)
throw new ArgumentNullException(nameof(path));
}

switch (path)
{
case RelativeFilePath file:
return new FileInfo(
_rootDirectory.Combine(file).FullName);
case RelativeDirectoryPath dir:
return new DirectoryInfo(
_rootDirectory.Combine(dir).FullName);
default:
throw new NotSupportedException($"{path.GetType()} is not supported.");
}
return path.Match<FileSystemInfo>(
directory => new DirectoryInfo(_rootDirectory.Combine(directory).FullName),
file => new FileInfo(_rootDirectory.Combine(file).FullName)
);
}

public IDirectoryAccessor GetDirectoryAccessorForRelativePath(RelativeDirectoryPath relativePath)
Expand Down
2 changes: 1 addition & 1 deletion MLS.Agent.Tools/RelativePath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ public abstract class RelativePath
{
private string _value;

protected RelativePath(string value)
protected internal RelativePath(string value)
ax0l0tl marked this conversation as resolved.
Show resolved Hide resolved
{
if (value == null)
{
Expand Down
14 changes: 14 additions & 0 deletions MLS.Agent.Tools/RelativePathExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;

namespace MLS.Agent.Tools
Expand Down Expand Up @@ -33,5 +34,18 @@ public static DirectoryInfo Combine(
RelativePath.NormalizeDirectory(directory.FullName),
directoryPath.Value.Replace('/', Path.DirectorySeparatorChar)));
}

public static T Match<T>(this RelativePath path, Func<RelativeDirectoryPath, T> directory, Func<RelativeFilePath, T> file)
{
switch (path)
{
case RelativeDirectoryPath relativeDirectoryPath:
return directory(relativeDirectoryPath);
case RelativeFilePath relativeFilePath:
return file(relativeFilePath);
default:
throw new ArgumentOutOfRangeException($"Unexpected type derived from {nameof(RelativePath)}: {path.GetType().Name}");
}
}
}
}
34 changes: 34 additions & 0 deletions MLS.Agent/CommandLine/CommandLineParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ public delegate Task<int> Verify(
IConsole console,
StartupOptions startupOptions);

public delegate Task<int> Publish(
PublishOptions options,
IConsole console,
StartupOptions startupOptions);

public static Parser Create(
IServiceCollection services,
StartServer startServer = null,
Expand All @@ -61,6 +66,7 @@ public static Parser Create(
TryGitHub tryGithub = null,
Pack pack = null,
Verify verify = null,
Publish publish = null,
ITelemetry telemetry = null,
IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = null)
{
Expand Down Expand Up @@ -88,6 +94,12 @@ public static Parser Create(
console,
startupOptions));

publish = publish ??
((options, console, startupOptions) =>
PublishCommand.Do(options,
console,
startupOptions));

pack = pack ??
PackCommand.Do;

Expand Down Expand Up @@ -132,6 +144,7 @@ public static Parser Create(
rootCommand.AddCommand(Install());
rootCommand.AddCommand(Pack());
rootCommand.AddCommand(Verify());
rootCommand.AddCommand(Publish());

return new CommandLineBuilder(rootCommand)
.UseDefaults()
Expand Down Expand Up @@ -435,6 +448,27 @@ Command Verify()

return verifyCommand;
}

Command Publish()
{
var publishCommand = new Command("publish", "Publish code from sample projects to Markdown files in the target directory and its children.")
{
new Option("--format", "Format of the files to publish")
{
Argument = new Argument<PublishFormat>()
},
new Option("--target-directory", "Specify the path where the rendered files should go. Can be equal to root directory. In case of Markdown output format and equal root and target directories, original source files will be replaced.")
{
Argument = new Argument<FileSystemDirectoryAccessor>(() => new FileSystemDirectoryAccessor(Directory.GetCurrentDirectory()))
Copy link
Contributor

@jonsequitur jonsequitur Apr 24, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should probably be Argument<DirectoryInfo>.

},
dirArgument
};

publishCommand.Handler = CommandHandler.Create<PublishOptions, IConsole, StartupOptions>(
(options, console, startupOptions) => publish(options, console, startupOptions));

return publishCommand;
}
}
}
}
46 changes: 46 additions & 0 deletions MLS.Agent/CommandLine/DirectoryExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.IO;
using MLS.Agent.Tools;

namespace MLS.Agent.CommandLine
{
internal static class DirectoryExtensions
{
private static readonly RelativeDirectoryPath _here = new RelativeDirectoryPath("./");

public static bool IsChildOf(this FileSystemInfo file, IDirectoryAccessor directory)
{
var parent = directory.GetFullyQualifiedPath(_here).FullName;
var child = Path.GetDirectoryName(file.FullName);

child = child.EndsWith('/') || child.EndsWith('\\') ? child : child + "/";
return IsBaseOf(parent, child, selfIsChild: true);
}

public static bool IsSubDirectoryOf(this IDirectoryAccessor potentialChild, IDirectoryAccessor directory)
{
var child = potentialChild.GetFullyQualifiedPath(_here).FullName;
var parent = directory.GetFullyQualifiedPath(_here).FullName;
return IsBaseOf(parent, child, selfIsChild: false);
}

private static bool IsBaseOf(string parent, string child, bool selfIsChild)
{
var parentUri = new Uri(parent);
var childUri = new Uri(child);
return (selfIsChild || parentUri != childUri) && parentUri.IsBaseOf(childUri);
}

public static void EnsureDirectoryExists(this IDirectoryAccessor directoryAccessor, RelativePath path)
{
var relativeDirectoryPath = path.Match(
directory => directory,
file => file.Directory
);
directoryAccessor.EnsureDirectoryExists(relativeDirectoryPath);
}
}
}
Loading