replace_url.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import re
  2. def replace_url(slug, content, branch='master'):
  3. def repl(match):
  4. if not match:
  5. return
  6. url = match.group(1)
  7. if url.startswith('http'):
  8. return match.group(0)
  9. url_new = (
  10. 'https://github.com/{slug}/blob/{branch}/{url}'
  11. .format(slug=slug, branch=branch, url=url)
  12. )
  13. if re.match(r'.*[\.jpg|\.png]$', url_new):
  14. url_new += '?raw=true'
  15. start0, end0 = match.regs[0]
  16. start, end = match.regs[1]
  17. start -= start0
  18. end -= start0
  19. res = match.group(0)
  20. res = res[:start] + url_new + res[end:]
  21. return res
  22. lines = []
  23. for line in content.splitlines():
  24. patterns = [
  25. r'!\[.*?\]\((.*?)\)',
  26. r'<img.*?src="(.*?)".*?>',
  27. r'\[.*?\]\((.*?)\)',
  28. r'<a.*?href="(.*?)".*?>',
  29. ]
  30. for pattern in patterns:
  31. line = re.sub(pattern, repl, line)
  32. lines.append(line)
  33. return '\n'.join(lines)