How to embed code from repo in github markdown?
UPDATE:
It turns out this is now possible if you paste a permalink of the code in your README.md
file.
To figure out how to get the permalink, check GitHub's docs on the topic. The permalink and the README.md
needs to be in the same repository.
OLD ANSWER:
You can't do that currently. You will have to copy your code sample and paste it between triple ticks in your README file. Here is an example:
``` Ruby class MyClass end ```
This will be static of course and you must update it manually when that code changes.
@Petros's answer is (still) correct, however I got annoyed enough with this that I've created a tool to automate the copying and keep your readme synchronised with the source - https://github.com/zakhenry/embedme
Example usage from the accepted answer
Insert a comment into the code fence
```rb
# path/to/your/file.rb
```
Run npx embedme README.md
(this assumes you have Nodejs installed)
The README will be written in-place, with the content of the file following your comment
```rb
# path/to/your/file.rb
class MyClass
end
```
Note that as the comment is still there, you can happily re-run npx embedme README.md
again and it won't make any change.
If you have CI, you can also run npx embedme --verify README.md
which will return 1
if it detects a diff (this would mean that the source was updated without the readme being updated).
If you are willing to use github actions, I found Markdown autodocs on Github Marketplace to work for my project.
All you have to do is to add a line in your .github/workflows/your-workflow.yml
file:
uses: dineshsonachalam/[email protected]
Then insert these snippets in your Markdown files:
<!-- MARKDOWN-AUTO-DOCS:START (CODE:src=./relative/path/to/code.js) -->
<!-- MARKDOWN-AUTO-DOCS:END -->
I also like the fact that it allows for remote files to be used:
<!-- MARKDOWN-AUTO-DOCS:START (CODE:src=https://raw.githubusercontent.com/username/project/master/path/to/file) -->
<!-- MARKDOWN-AUTO-DOCS:END -->
And also the fact that you can restrict the number of lines printed:
<!-- MARKDOWN-AUTO-DOCS:START (CODE:src=https://raw.githubusercontent.com/username/project/master/path/to/file&lines=1-42) -->
<!-- MARKDOWN-AUTO-DOCS:END -->