Skip to content

Commit 1dca758

Browse files
first commit
0 parents  commit 1dca758

File tree

6 files changed

+314
-0
lines changed

6 files changed

+314
-0
lines changed

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
__pycache__
2+
build
3+
dist
4+
*.egg
5+
*.egg-info

LICENSE

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Copyright (c) 2018 The Python Packaging Authority
2+
3+
Permission is hereby granted, free of charge, to any person obtaining a copy
4+
of this software and associated documentation files (the "Software"), to deal
5+
in the Software without restriction, including without limitation the rights
6+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7+
copies of the Software, and to permit persons to whom the Software is
8+
furnished to do so, subject to the following conditions:
9+
10+
The above copyright notice and this permission notice shall be included in all
11+
copies or substantial portions of the Software.
12+
13+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19+
SOFTWARE.

README.md

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# Sphinx Markdown Extension
2+
3+
This extension fixes or improves how Sphinx handles links related to Markdown
4+
when it generates the HTML site. It assumes you are using the `recommonmark`
5+
extension.
6+
7+
**Contents**
8+
9+
- [What it does](#what-it-does)
10+
- [How to use it](#how-to-use-it)
11+
12+
## What it does
13+
14+
1. Markdown files: Converts references to Markdown files that include anchors.
15+
``` md
16+
[configuration options](autotest.md#configuration-options)
17+
```
18+
2. reST files: Fixes explicit links to Markdown files.
19+
``` rst
20+
`Google Cloud Engine <gce.md>`__
21+
```
22+
3. Markdown files: Fixes references to reST files.
23+
``` md
24+
[Application examples](examples/readme.rst)
25+
```
26+
4. Markdown files: Fixes links to files and directories within the GitHub repo.
27+
``` md
28+
[Makefile](/Makefile)
29+
[deploy/kustomize](/deploy/kustomize)
30+
```
31+
Links to files can be fixed one of two ways, which can be set in the
32+
[conf.py](/conf.py).
33+
34+
``` python
35+
baseBranch = "devel"
36+
useGitHubURL = True
37+
commitSHA = getenv('GITHUB_SHA')
38+
githubBaseURL = "https://github.com/intelkevinputnam/pmem-csi/"
39+
```
40+
41+
If ``useGitHubURL`` is set to True, it will try to create links based on
42+
your ``githubBaseURL`` and the SHA for the commit to the GitHub repo
43+
determined by the GitHub workflow on merge). If there is no SHA available,
44+
it will use the value of ``baseBranch``.
45+
46+
If ``useGitHubURL`` is set to False, it will copy the files to the HTML
47+
output directory and provide links to that location.
48+
49+
NOTE: Links to files and directories should use absolute paths relative to
50+
the repo (see Makefile and deploy/kustomize above). This will work both for
51+
the Sphinx build and when viewing in the GitHub repo.
52+
53+
Links to directories are always converted to links to the GitHub repository.
54+
55+
## How to use it
56+
57+
1. Install the sphinx_md extension:
58+
59+
``` bash
60+
pip3 install sphinx_md
61+
```
62+
63+
2. Add `sphinx_md` to the extensions in your `conf.py`:
64+
65+
``` python
66+
extensions = ['sphinx_md', ...]
67+
```
68+
69+
3. If you want to use GitHub commit links, add the entire code snippet to
70+
your `conf.py`:
71+
72+
``` python
73+
from os import getenv
74+
75+
sphinx_md_useGitHubURL = True
76+
baseBranch = "devel"
77+
commitSHA = getenv('GITHUB_SHA')
78+
githubBaseURL = 'https://github.com/' + (getenv('GITHUB_REPOSITORY') or 'intel/pmem-csi') + '/'
79+
githubFileURL = githubBaseURL + "blob/"
80+
githubDirURL = githubBaseURL + "tree/"
81+
if commitSHA:
82+
githubFileURL = githubFileURL + commitSHA + "/"
83+
githubDirURL = githubDirURL + commitSHA + "/"
84+
else:
85+
githubFileURL = githubFileURL + baseBranch + "/"
86+
githubDirURL = githubDirURL + baseBranch + "/"
87+
sphinx_md_githubFileURL = githubFileURL
88+
sphinx_md_githubDirURL = githubDirURL
89+
```

example_conf.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
from os import getenv
2+
3+
extensions = ['sphinx_md']
4+
5+
# Configure path for repo files
6+
# Environment variables are based on GitHub workflow defaults
7+
8+
sphinx_md_useGitHubURL = True
9+
baseBranch = "devel"
10+
commitSHA = getenv('GITHUB_SHA')
11+
githubBaseURL = 'https://github.com/' + (getenv('GITHUB_REPOSITORY') or 'intel/pmem-csi') + '/'
12+
githubFileURL = githubBaseURL + "blob/"
13+
githubDirURL = githubBaseURL + "tree/"
14+
if commitSHA:
15+
githubFileURL = githubFileURL + commitSHA + "/"
16+
githubDirURL = githubDirURL + commitSHA + "/"
17+
else:
18+
githubFileURL = githubFileURL + baseBranch + "/"
19+
githubDirURL = githubDirURL + baseBranch + "/"
20+
sphinx_md_githubFileURL = githubFileURL
21+
sphinx_md_githubDirURL = githubDirURL

setup.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import setuptools
2+
3+
with open("README.md", "r") as fh:
4+
long_description = fh.read()
5+
6+
setuptools.setup(
7+
name="sphinx-md-kevinputnam",
8+
version="0.0.1",
9+
author="Kevin Putnam",
10+
author_email="[email protected]",
11+
description="Sphinx extension to use with Recommonmark to fix links to rst from md, links to md from rst, and links to embedded files and dirs.",
12+
long_description=long_description,
13+
long_description_content_type="text/markdown",
14+
url="https://github.com/intelkevinputnam/sphinx-md",
15+
packages=setuptools.find_packages(),
16+
classifiers=[
17+
"Programming Language :: Python :: 3",
18+
"License :: OSI Approved :: MIT License",
19+
"Operating System :: OS Independent",
20+
],
21+
python_requires='>=3.6',
22+
)

sphinx_md/__init__.py

Lines changed: 158 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,158 @@
1+
"""
2+
Sphinx Markdown link fixer
3+
"""
4+
5+
import sphinx
6+
7+
from docutils import nodes
8+
from os.path import isdir, isfile, join, basename, dirname
9+
from os import makedirs
10+
from shutil import copyfile
11+
12+
##############################################################################
13+
#
14+
# This section determines the behavior of links to local items in .md files.
15+
#
16+
# if useGitHubURL == True:
17+
#
18+
# links to local files and directories will be turned into github URLs
19+
# using either the baseBranch defined here or using the commit SHA.
20+
#
21+
# if useGitHubURL == False:
22+
#
23+
# local files will be moved to the website directory structure when built
24+
# local directories will still be links to github URLs
25+
#
26+
# if built with GitHub workflows:
27+
#
28+
# the GitHub URLs will use the commit SHA (GITHUB_SHA environment variable
29+
# is defined by GitHub workflows) to link to the specific commit.
30+
#
31+
##############################################################################
32+
33+
# End GitHub URL section
34+
35+
##############################################################################
36+
#
37+
# This section defines callbacks that make markdown specific tweaks to
38+
# either:
39+
#
40+
# 1. Fix something that recommonmark does wrong.
41+
# 2. Provide support for .md files that are written as READMEs in a GitHub
42+
# repo.
43+
#
44+
# Only use these changes if using the extension ``recommonmark``.
45+
#
46+
##############################################################################
47+
48+
# Callback registerd with 'missing-reference'.
49+
def fixRSTLinkInMD(app, env, node, contnode):
50+
refTarget = node.get('reftarget')
51+
filePath = refTarget.lstrip("/")
52+
if '.rst' in refTarget and "://" not in refTarget:
53+
# This occurs when a .rst file is referenced from a .md file
54+
# Currently unable to check if file exists as no file
55+
# context is provided and links are relative.
56+
#
57+
# Example: [Application examples](examples/readme.rst)
58+
#
59+
contnode['refuri'] = contnode['refuri'].replace('.rst','.html')
60+
contnode['internal'] = "True"
61+
return contnode
62+
else:
63+
# This occurs when a file is referenced for download from an .md file.
64+
# Construct a list of them and short-circuit the warning. The files
65+
# are moved later (need file location context). To avoid warnings,
66+
# write .md files, make the links absolute. This only marks them fixed
67+
# if it can verify that they exist.
68+
#
69+
# Example: [Makefile](/Makefile)
70+
#
71+
if isfile(filePath) or isdir(filePath):
72+
return contnode
73+
74+
75+
def normalizePath(docPath,uriPath):
76+
if uriPath == "":
77+
return uriPath
78+
if "#" in uriPath:
79+
# Strip out anchors
80+
uriPath = uriPath.split("#")[0]
81+
if uriPath.startswith("/"):
82+
# It's an absolute path
83+
return uriPath.lstrip("/") #path to file from project directory
84+
else:
85+
# It's a relative path
86+
docDir = dirname(docPath)
87+
return join(docDir,uriPath) #path to file from referencing file
88+
89+
90+
# Callback registerd with 'doctree-resolved'.
91+
def fixLocalMDAnchors(app, doctree, docname):
92+
useGitHubURL = app.config.sphinx_md_useGitHubURL
93+
githubFileURL = app.config.sphinx_md_githubFileURL
94+
githubDirURL = app.config.sphinx_md_githubDirURL
95+
for node in doctree.traverse(nodes.reference):
96+
uri = node.get('refuri')
97+
filePath = normalizePath(docname,uri)
98+
if isfile(filePath):
99+
# Only do this if the file exists.
100+
#
101+
# TODO: Pop a warning if the file doesn't exist.
102+
#
103+
if '.md' in uri and '://' not in uri:
104+
# Make sure .md file links that weren't caught are converted.
105+
# These occur when creating an explicit link to an .md file
106+
# from an .rst file. By default these are not validated by Sphinx
107+
# or recommonmark. Only toctree references are validated. recommonmark
108+
# also fails to convert links to local Markdown files that include
109+
# anchors. This fixes that as well.
110+
#
111+
# Only include this code if .md files are being converted to html
112+
#
113+
# Example: `Google Cloud Engine <gce.md>`__
114+
# [configuration options](autotest.md#configuration-options)
115+
#
116+
node['refuri'] = node['refuri'].replace('.md','.html')
117+
else:
118+
# Handle the case where markdown is referencing local files in the repo
119+
#
120+
# Example: [Makefile](/Makefile)
121+
#
122+
if useGitHubURL:
123+
# Replace references to local files with links to the GitHub repo
124+
#
125+
newURI = githubFileURL + filePath
126+
print("new url: ", newURI)
127+
node['refuri']=newURI
128+
else:
129+
# If there are links to local files other than .md (.rst files are caught
130+
# when warnings are fired), move the files into the Sphinx project, so
131+
# they can be accessed.
132+
newFileDir = join(app.outdir,dirname(filePath)) # where to move the file in Sphinx output.
133+
newFilePath = join(app.outdir,filePath)
134+
newURI = uri # if the path is relative no need to change it.
135+
if uri.startswith("/"):
136+
# It's an absolute path. Need to make it relative.
137+
uri = uri.lstrip("/")
138+
docDirDepth = len(docname.split("/")) - 1
139+
newURI = "../"*docDirDepth + uri
140+
if not isdir(newFileDir):
141+
makedirs(newFileDir)
142+
copyfile(filePath,newFilePath)
143+
node['refuri'] = newURI
144+
elif "#" not in uri: # ignore anchors
145+
# turn links to directories into links to the repo
146+
if isdir(filePath):
147+
newURI = githubDirURL + filePath
148+
node['refuri']=newURI
149+
150+
def setup(app):
151+
app.add_config_value('sphinx_md_useGitHubURL',False,'')
152+
app.add_config_value('sphinx_md_githubFileURL','','')
153+
app.add_config_value('sphinx_md_githubDirURL','','')
154+
app.connect('doctree-resolved',fixLocalMDAnchors)
155+
app.connect('missing-reference',fixRSTLinkInMD)
156+
157+
158+

0 commit comments

Comments
 (0)