Skip to content

Commit 3d0aa6b

Browse files
committed
html_attribute: imageリポジトリ参照URLを解決
1 parent 09e3f63 commit 3d0aa6b

File tree

1 file changed

+21
-1
lines changed

1 file changed

+21
-1
lines changed

html_attribute.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,10 @@ def __init__(self, md, config):
167167
self.url_current = self.url_base + self._remove_md(self.config['full_path'])
168168
self.url_current_base = self.url_base + self.config['base_path'].strip('/')
169169

170+
image_repo = self.config['image_repo']
171+
self.re_url_github_image = re.compile(r'^https?://(?:raw.github.com/%s/master|github.com/%s/raw)/' % (image_repo, image_repo))
172+
self.image_base = 'https://raw.githubusercontent.com/%s/master/' % image_repo
173+
170174
def _iterate(self, elements, f):
171175
f(elements)
172176
for child in elements:
@@ -275,13 +279,27 @@ def _to_relative_url(self, element):
275279
elif href.startswith(self.url_base):
276280
element.attrib['href'] = posixpath.relpath(href, self.url_current_base)
277281

282+
def _resolve_image_src(self, element):
283+
if element.tag == 'img' and 'src' in element.attrib:
284+
src = element.attrib['src']
285+
src = self.re_url_github_image.sub(self.image_base, src, count=1)
286+
if self.config['use_static_image'] and src.startswith(self.image_base):
287+
src = 'static/image/' + src[len(self.image_base):]
288+
if self.config['use_relative_link']:
289+
src = posixpath.relpath(self.url_base + src, self.url_current_base)
290+
else:
291+
src = '/' + src
292+
element.attrib['src'] = src
293+
278294
def _adjust_url(self, element):
279295
self._to_absolute_url(element)
280296

281297
# 一旦絶対パスに統一してから相対パスに変換する
282298
if self.config['use_relative_link']:
283299
self._to_relative_url(element)
284300

301+
self._resolve_image_src(element)
302+
285303
def _add_meta(self, element):
286304
body = etree.Element('div', itemprop="articleBody")
287305
after_h1 = False
@@ -335,7 +353,9 @@ def __init__(self, **kwargs):
335353
'base_path': ['', "Base Path used to link URL as relative URL"],
336354
'full_path': ['', "Full Path used to link URL as anchor URL"],
337355
'extension': ['', "URL extension"],
338-
'use_relative_link': [False, "Whether to use relative paths for domestic links"]
356+
'use_relative_link': [False, "Whether to use relative paths for domestic links"],
357+
'image_repo': ['cpprefjp/image', "Name of GitHub repository that contains the images"],
358+
'use_static_image': [False, "Whether to use the images in static/image instead on GitHub"]
339359
}
340360

341361
super().__init__(**kwargs)

0 commit comments

Comments
 (0)