Skip to content

Implemented a #L10-20 syntax for files, and #M-MethodName syntax for CSharp methods #715

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
26 changes: 26 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,32 @@ Will render:
<sup><a href='#snippet-license.txt' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

### Including a partial file

If no snippet is found matching the defined name. The target directory will be searched for a file matching that name.
Using a syntax of #L10-20 you can only include lines 10 to 20 from that file. For example:

<!-- snippet: license.txt#L1-3 -->
<a id='snippet-license.txt#L1-3'></a>
```txt
The MIT License (MIT)
...
```
<sup><a href='#snippet-license.txt' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

### Including a C# Method

If no snippet is found matching the defined name. The target directory will be searched for a file matching that name.
Using a syntax of #M-MethodName you can reference a specific method. For example:

<!-- snippet: src\ConfigReader\LogBuilder.cs#M-GetHeader -->
<a id='src\ConfigReader\LogBuilder.cs#M-GetHeader'></a>
```cs
...
```
<sup><a href='#src\ConfigReader\LogBuilder.cs' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

### LinkFormat

Expand Down
26 changes: 26 additions & 0 deletions readme.source.md
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,32 @@ Will render:
<sup><a href='#snippet-license.txt' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

### Including a partial file

If no snippet is found matching the defined name. The target directory will be searched for a file matching that name.
Using a syntax of #L10-20 you can only include lines 10 to 20 from that file. For example:

<!-- snippet: license.txt#L1-3 -->
<a id='snippet-license.txt#L1-3'></a>
```txt
The MIT License (MIT)
...
```
<sup><a href='#snippet-license.txt' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

### Including a C# Method

If no snippet is found matching the defined name. The target directory will be searched for a file matching that name.
Using a syntax of #M-MethodName you can reference a specific method. For example:

<!-- snippet: src\ConfigReader\LogBuilder.cs#M-GetHeader -->
<a id='src\ConfigReader\LogBuilder.cs#M-GetHeader'></a>
```cs
...
```
<sup><a href='#src\ConfigReader\LogBuilder.cs' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

### LinkFormat

Expand Down
1 change: 1 addition & 0 deletions src/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
<PackageVersion Include="Argon" Version="0.26.0" />
<PackageVersion Include="CommandLineParser" Version="2.9.1" />
<PackageVersion Include="Microsoft.Build.Tasks.Core" Version="17.12.6" />
<PackageVersion Include="Microsoft.CodeAnalysis.CSharp" Version="4.12.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageVersion Include="Polyfill" Version="7.12.0" />
<PackageVersion Include="ProjectDefaults" Version="1.0.147" />
Expand Down
9 changes: 7 additions & 2 deletions src/MarkdownSnippets/GlobalUsings.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
global using System.Diagnostics.CodeAnalysis;
global using System.Diagnostics.CodeAnalysis;
global using System.Net;
global using System.Net.Http;
global using System.Text.RegularExpressions;
global using MarkdownSnippets;
global using MarkdownSnippets;

global using System.Text;
global using Microsoft.CodeAnalysis;
global using Microsoft.CodeAnalysis.CSharp;
global using Microsoft.CodeAnalysis.CSharp.Syntax;
2 changes: 1 addition & 1 deletion src/MarkdownSnippets/MarkdownSnippets.csproj
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@

<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net48;net8.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" />
<PackageReference Include="ProjectDefaults" PrivateAssets="all" />
<PackageReference Include="Polyfill" PrivateAssets="all" />
<PackageReference Include="System.Memory" Condition="'$(TargetFrameworkIdentifier)' == '.NETStandard' OR '$(TargetFrameworkIdentifier)' == '.NETFramework' OR '$(TargetFrameworkIdentifier)' == '.NETCOREAPP'" />
Expand Down
91 changes: 77 additions & 14 deletions src/MarkdownSnippets/Processing/MarkdownProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -311,9 +311,18 @@ bool FilesToSnippets(
return true;
}

string? lineExpression = null;

if (key.Contains('#'))
{
var splitByHash = key.Split('#', StringSplitOptions.None);
key = splitByHash[0];
lineExpression = splitByHash[1];
}

if (RelativeFile.Find(allFiles, targetDirectory, key, relativePath, linePath, out var path))
{
snippetsForKey = SnippetsForFile(key, path);
snippetsForKey = SnippetsForFile(key, path, lineExpression);
return true;
}

Expand All @@ -322,8 +331,7 @@ bool FilesToSnippets(
}


List<Snippet> SnippetsForFile(string key, string relativeToRoot) =>
[FileToSnippet(key, relativeToRoot, null)];
List<Snippet> SnippetsForFile(string key, string relativeToRoot, string? lines = null) => [FileToSnippet(key, relativeToRoot, null, lines)];

bool GetForHttp(string key, out IReadOnlyList<Snippet> snippetsForKey)
{
Expand All @@ -338,22 +346,77 @@ bool GetForHttp(string key, out IReadOnlyList<Snippet> snippetsForKey)
return true;
}

Snippet FileToSnippet(string key, string file, string? path)
Snippet FileToSnippet(string key, string file, string? path, string? linesExpression = null)
{
var language = Path.GetExtension(file)[1..];

if (linesExpression == null)
{
var (text, endLine) = ReadNonStartEndLines(file);
return Snippet.Build(startLine: 1, endLine: endLine, value: text, key: key, language: language, path: path);
}

if (linesExpression[0] == 'L')
{
return ParseSpecificLines(key, file, path, linesExpression, language);
}

if (linesExpression[0] == 'M' && language == "cs")
{
return ParseCSharpMethod(key, file, path, linesExpression, language);
}

throw new SnippetException($"Unable to parse expression '{linesExpression}'");
}

static Snippet ParseCSharpMethod(string key, string file, string? path, string linesExpression, string language)
{
var (text, lineCount) = ReadNonStartEndLines(file);
var methodName = linesExpression[2..];

var code = File.ReadAllText(file);
var tree = CSharpSyntaxTree.ParseText(code);
var root = tree.GetCompilationUnitRoot();

var method = root.DescendantNodes()
.OfType<MethodDeclarationSyntax>()
.FirstOrDefault(m => m.Identifier.Text == methodName);

if (method != null)
{
var text = method.ToFullString();
var startLine = method.Span.Start;
var endLine = method.Span.End;

return Snippet.Build(startLine: startLine, endLine: endLine, value: text, key: key, language: language, path: path);
}

throw new SnippetException(
$"""
Failed to find method {methodName} in file {file} configuration.
Content:
{code}
""");
}

static Snippet ParseSpecificLines(string key, string file, string? path, string linesExpression, string language)
{
var text = string.Empty;

var expressionSplit = linesExpression.Split('-');
var startLine = int.Parse(expressionSplit[0][1..]);
var endLine = int.Parse(expressionSplit[1]);

var fileLines = File.ReadAllLines(file);

var selectedText = new StringBuilder();

if (lineCount == 0)
for (var index = startLine; index < endLine; index++)
{
lineCount++;
selectedText.AppendLine(fileLines[index]);
text = selectedText.ToString();
}

return Snippet.Build(
startLine: 1,
endLine: lineCount,
value: text,
key: key,
language: Path.GetExtension(file)[1..],
path: path);
return Snippet.Build(startLine: startLine, endLine: endLine, value: text, key: key, language: language, path: path);
}

(string text, int lineCount) ReadNonStartEndLines(string file)
Expand Down