• Stars
    star
    159
  • Rank 235,916 (Top 5 %)
  • Language
    C#
  • License
    MIT License
  • Created almost 6 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Extracts snippets from code files and merges them into markdown documents.

MarkdownSnippets

Build status NuGet Status NuGet Status NuGet Status

A dotnet tool that extract snippets from code files and merges them into markdown documents.

.net 6 or higher is required to run this tool.

Value Proposition

Automatically extract snippets from code and injecting them into markdown documents has several benefits:

  • Snippets can be verified by a compiler or parser.
  • Tests can be run on snippets, or snippets can be pulled from existing tests.
  • Changes in code are automatically reflected in documentation.
  • Snippets are less likely to get out of sync with the main code-base.
  • Snippets in markdown is easier to create and maintain since any preferred editor can be used to edit them.

Behavior

  • Recursively scan the target directory for code files containing snippets. (See exclusion).
  • Recursively scan the target directory for markdown (.md or mdx) files. (See Document Scanning).
  • Merge the snippets into those markdown files.

Installation

Ensure dotnet CLI is installed.

Install MarkdownSnippets.Tool

dotnet tool install -g MarkdownSnippets.Tool

Usage

mdsnippets C:\Code\TargetDirectory

If no directory is passed the current directory will be used, but only if it exists with a git repository directory tree. If not an error is returned.

Document Convention

There are two approaches scanning and modifying markdown files.

SourceTransform

This is the default.

source.md file

The file convention recursively scans the target directory for all *.source.md files. Once snippets are merged the .source.md to produce .md files. So for example readme.source.md would be merged with snippets to produce readme.md. Note that this process will overwrite any existing .md files that have matching .source.md files.

mdsource directory

There is a secondary convention that leverages the use of a directory named mdsource. Where .source.md files are placed in a mdsource sub-directory, the mdsource part of the file path will be removed when calculating the target path. This allows the .source.md to be grouped in a sub directory and avoid cluttering up the main documentation directory.

When using the mdsource convention, all references to other files, such as links and images, should specify the full path from the root of the repository. This will allow those links to work correctly in both the source and generated markdown files. Relative paths cannot work for both the source and the target file.

InPlaceOverwrite

Recursively scans the target directory for all *.md files and merges snippets into those files.

Command line
mdsnippets -c InPlaceOverwrite
mdsnippets --convention InPlaceOverwrite
Config file

Can be enabled in mdsnippets.json config file.

{
  "Convention": "InPlaceOverwrite"
}

Moving from SourceTransform to InPlaceOverwrite

  • Ensure "WriteHeader": false is used in mdsnippets.json.
  • Ensure "ReadOnly": false is used in mdsnippets.json.
  • Ensure using the current stable version and a docs generation has run.
  • Delete all .source.md files.
  • Modify mdsnippets.json to add "Convention": "InPlaceOverwrite".
  • Run the docs generation.

Mark resulting files as read only

To mark the resulting documents files as read only use -r or --read-only.

This can be helpful in preventing incorrectly editing the documents file instead of the .source. file conventions.

mdsnippets -r true
mdsnippets --read-only true

Defining Snippets

Any code wrapped in a convention based comment will be picked up. The comment needs to start with begin-snippet: which is followed by the key. The snippet is then terminated by end-snippet.

// begin-snippet: MySnippetName
My Snippet Code
// end-snippet

Named C# regions will also be picked up, with the name of the region used as the key.

To stop regions collapsing in Visual Studio disable 'enter outlining mode when files open'. See Visual Studio outlining.

UrlsAsSnippets

Urls to files to be included as snippets. Space separated for multiple values.

Each url will be accessible using the file name as a key. Any snippets within the files will be extracted and accessible as individual keyed snippets.

mdsnippets --urls-as-snippets "https://github.com/SimonCropp/MarkdownSnippets/snippet.cs"
mdsnippets -u "https://github.com/SimonCropp/MarkdownSnippets/snippet.cs"

Using Snippets

The keyed snippets can be used in any documentation .md file by adding the text snippet: KEY.

Then snippets with that key.

For example

Some blurb about the below snippet
snippet: MySnippetName

The resulting markdown will be:

<!-- snippet: MySnippetName -->
Some blurb about the below snippet
<a id='snippet-MySnippetName'></a>
```
My Snippet Code
```
<sup><a href='/relativeUrlToFile#L1-L11' title='Snippet source file'>snippet source</a> | <a href='#snippet-MySnippetName' title='Start of snippet'>anchor</a></sup>
<!-- endSnippet -->

Notes:

Including a snippet from the web

Snippets that start with http will be downloaded and the contents rendered. For example:

snippet: https://raw.githubusercontent.com/SimonCropp/MarkdownSnippets/master/license.txt

Will render:

<!-- snippet: https://raw.githubusercontent.com/SimonCropp/MarkdownSnippets/master/license.txt -->
<a id='snippet-https://raw.githubusercontent.com/SimonCropp/MarkdownSnippets/master/license.txt'></a>
```txt
The MIT License (MIT)
...
```
<sup><a href='#snippet-https://raw.githubusercontent.com/SimonCropp/MarkdownSnippets/master/license.txt' title='Snippet source file'>anchor</a></sup>
<!-- endSnippet -->

Files are downloaded to %temp%MarkdownSnippets with a maximum of 100 files kept.

Including a full file

If no snippet is found matching the defined name. The target directory will be searched for a file matching that name. For example:

snippet: license.txt

Will render:

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

Files are downloaded to %temp%MarkdownSnippets with a maximum of 100 files kept.

LinkFormat

Defines the format of snippet source links that appear under each snippet.

Command line

mdsnippets --link-format Bitbucket
mdsnippets -l Bitbucket

Values

namespace MarkdownSnippets;

public enum LinkFormat
{
    GitHub,
    Tfs,
    Bitbucket,
    GitLab,
    None
}

snippet source | anchor

Link format None will omit the source link but still keep the snippet anchor.

OmitSnippetLinks

The links below a snippet can be omitted.

Command line

mdsnippets --omit-snippet-links true

Config file

{
  "OmitSnippetLinks": true
}

How links are constructed

if (linkFormat == LinkFormat.GitHub)
{
    return $"{path}#L{snippet.StartLine}-L{snippet.EndLine}";
}

if (linkFormat == LinkFormat.Tfs)
{
    return $"{path}&line={snippet.StartLine}&lineEnd={snippet.EndLine}";
}

if (linkFormat == LinkFormat.Bitbucket)
{
    return $"{path}#lines={snippet.StartLine}:{snippet.EndLine}";
}

if (linkFormat == LinkFormat.GitLab)
{
    return $"{path}#L{snippet.StartLine}-{snippet.EndLine}";
}

snippet source | anchor

UrlPrefix

UrlPrefix allows a string to be defined that will prefix all snippet links. This is helpful when the markdown file are being hosted on a site that is no co-located with the source code files. It can be defined in the config file, the MsBuild task, and the dotnet tool.

Command line

mdsnippets --url-prefix "TheUrlPrefix"

Config file

{
  "UrlPrefix": "TheUrlPrefix"
}

Add to Windows Explorer

Use src/context-menu.reg to add MarkdownSnippets to the Windows Explorer context menu.

Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\Directory\Shell]
@="none"
[HKEY_CLASSES_ROOT\Directory\shell\mdsnippets]
"MUIVerb"="run mdsnippets"
"Position"="bottom"
[HKEY_CLASSES_ROOT\Directory\Background\shell\mdsnippets]
"MUIVerb"="run mdsnippets"
"Position"="bottom"
[HKEY_CLASSES_ROOT\Directory\shell\mdsnippets\command]
@="cmd.exe /c mdsnippets \"%V\""
[HKEY_CLASSES_ROOT\Directory\Background\shell\mdsnippets\command]
@="cmd.exe /c mdsnippets \"%V\""

snippet source | anchor

More Documentation

Credits

Loosely based on some code from https://github.com/shiftkey/scribble.

Icon

Down by Alfredo Creates from The Noun Project.

More Repositories

1

GraphQL.EntityFramework

Adds EntityFramework Core IQueryable support to GraphQL
C#
357
star
2

WinDebloat

A dotnet tool that removes the bloat in Windows
C#
303
star
3

NaughtyStrings

Provides a strong typed .NET API for the Big List of Naughty Strings https://github.com/minimaxir/big-list-of-naughty-strings
C#
197
star
4

LocalDb

Provides a wrapper around SqlLocalDB to simplify running tests or samples that require a SQL Server Database
C#
148
star
5

XunitContext

Extends xUnit to expose extra context and simplify logging
C#
129
star
6

Polyfill

Source only package that exposes newer .net and C# features to older runtimes.
C#
93
star
7

WaffleGenerator

Produces text which, on first glance, looks like real, ponderous, prose; replete with clichรฉs.
C#
84
star
8

CountryData

Provides a .net wrapper around the GeoNames Data
C#
64
star
9

Cymbal

An MSBuild Task to enable exception line numbers for references in a deployed app
C#
44
star
10

SetStartupProjects

Setting Visual Studio startup projects by hacking the suo
C#
42
star
11

GraphQL.Validation

Add FluentValidation support to GraphQL.net
C#
40
star
12

Replicant

A wrapper for HttpClient that caches to disk. Cached files, over the max specified, are deleted based on the last access times.
C#
31
star
13

PandocNet

Conversion of documents in .net via Pandoc.
C#
23
star
14

GitHubSync

A tool to help synchronizing specific files and folders across GitHub hosted repositories
C#
23
star
15

PackageUpdate

A dotnet tool that updates packages for all solutions in a directory.
C#
20
star
16

Delta

An opinionated approach to implementing a 304 Not Modified
C#
19
star
17

GraphQL.Attachments

Provides access to a HTTP stream in GraphQL
C#
17
star
18

Timestamp

Adds a build timestamp to an assembly.
C#
16
star
19

NodaTime.Bogus

Add support for NodaTime to Bogus.
C#
13
star
20

SimpleInfoName

Generates simple names for *Infos (types, parameters, properties, fields, and methods)
C#
13
star
21

SeqProxy

Enables writing seq logs by proxying requests through an ASP.NET Controller or Middleware.
C#
13
star
22

NullabilityInfo

Exposes top-level nullability information from reflection
C#
11
star
23

ExtendedFluentValidation

Extends FluentValidation with some more opinionated rules.
C#
8
star
24

Argon

Argon is a JSON framework for .NET. It is a hard fork of Newtonsoft.Json.
C#
8
star
25

ProjectDefaults

Pascal
3
star
26

scratch

C#
3
star
27

RoboBogus

C#
3
star
28

GitModTimes

C#
2
star
29

OssIndexClient

A .net client for OSSIndex (https://ossindex.sonatype.org/)
C#
2
star
30

.github

1
star
31

AsposeHelpers

C#
1
star
32

GitHubSync.TestRepository

1
star