Debian Codegraph @

docs/_extensions/affiliatelinks.py

raw symbols SCIP
1 """
2 ::
3
4 File: affiliatelinks.py
5 Authors: Michael Altfield <[email protected]>
6 Created: 2020-07-28
7 Updated: 2020-07-28
8 Version: 0.1
9
10 This sphinx extension takes a list of links and builds targets from those links
11 depending on the buildername. If the buildername is 'html', it will use our
12 affiliate links. Otherwise, the target will use the fallback link.
13
14 This is important because amazon affiliates don't permit offline material to
15 include affiliate links, so we need to make sure that our pdf, epub, etc just
16 link to our online documentation and not directly to our affiliate's products.
17
18 For more info, see: https://buskill.in/
19 """
20 from docutils import nodes
21 from docutils.parsers.rst import Directive
22
23 from sphinx.locale import _
24 from sphinx.util.docutils import SphinxDirective
25
26 class AffiliateLinks(SphinxDirective):
27
28 has_content = True
29
30 def run(self):
31
32 # generate a list of targets for each line in the body passed to us
33 target_nodes = list()
34 for target in self.content:
35
36 # skip empty lines
37 if target == '':
38 continue
39
40 target_node = nodes.target( '', '' )
41 target_nodes.append( target_node )
42
43 # split this line up into space-separated fields
44 affiliateUri,fallbackUri,name = target.split()
45
46 # the name of the target is what it will be referenced by in .rst
47 # files (eg: `some hyperlink custom text`targetname_ )
48 target_node['names'] = [name]
49
50 # only use the affiliate link if we're building html
51 # use the fall-back URI if we're building to anything else, such as pdf
52 if self.env.config.buildername == 'html':
53 target_node['refuri'] = affiliateUri
54 else:
55 target_node['refuri'] = fallbackUri
56
57 return target_nodes
58
59 def setup(app):
60 app.add_directive("affiliatelinks", AffiliateLinks)
61
62 return {
63 'version': '0.1',
64 'parallel_read_safe': True,
65 'parallel_write_safe': True,
66 }