Advertisement
VikkaLorel

md2dk.py

Mar 16th, 2020
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.95 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # md2dk.py
  3. # Created by dturba at 13/03/2020
  4. import re
  5. from argparse import ArgumentParser, Namespace
  6. from typing import List, Optional
  7.  
  8. _link_pattern = re.compile(r'\[(?P<name>[^\]]+)(\])(\()(?P<link>[^)]+)\)',
  9.                            flags=0)
  10.  
  11.  
  12. def title_formatting(*, line: str, **_) -> str:
  13.     if line.startswith('#' * 6):
  14.         line = f"{line.replace('#' * 6, '=')} ="
  15.     elif line.startswith('#' * 5):
  16.         line = f"{line.replace('#' * 5, '=' * 2)} {'=' * 2}"
  17.     elif line.startswith('#' * 4):
  18.         line = f"{line.replace('#' * 4, '=' * 3)} {'=' * 3}"
  19.     elif line.startswith('#' * 3):
  20.         line = f"{line.replace('#' * 3, '=' * 4)} {'=' * 4}"
  21.     elif line.startswith('#' * 2):
  22.         line = f"{line.replace('#' * 2, '=' * 5)} {'=' * 5}"
  23.     elif line.startswith('#'):
  24.         line = f"{line.replace('#', '=' * 6)} {'=' * 6}"
  25.     return line
  26.  
  27.  
  28. def code_block_formatting(
  29.         *, line: str, lines: List[str], current_i: int, **_) -> str:
  30.     if '```' in line:
  31.         line = line.replace('```', '')
  32.         for i, tmp_line in enumerate(lines[current_i + 1:], 1):
  33.             if '```' in tmp_line:
  34.                 lines[current_i + i] = lines[current_i + i].replace('```', '')
  35.                 break
  36.             else:
  37.                 lines[current_i + i] = ''.join(('  ', lines[current_i + i]))
  38.     return line
  39.  
  40.  
  41. def list_formatting(*, line: str, **_) -> str:
  42.     if line.startswith('- '):
  43.         line = line.replace('- ', '  * ')
  44.     return line
  45.  
  46.  
  47. def monospace_formatting(*, line: str, **_) -> str:
  48.     new_line = line
  49.     while new_line.find('`') != -1:
  50.         new_line = new_line.replace('`', "''%%", 1)
  51.         new_line = new_line.replace('`', "%%''", 1)
  52.     return new_line
  53.  
  54.  
  55. def link_formatting(*, line: str, **_) -> str:
  56.     new_line = line
  57.     link_match = _link_pattern.search(new_line)
  58.     while link_match:
  59.         new_line = f"{new_line[:link_match.start()]}[[" \
  60.                    f"{link_match.group('link')}|" \
  61.                    f"{link_match.group('name')}]]" \
  62.                    f"{new_line[link_match.end():]}"
  63.         link_match = _link_pattern.search(new_line)
  64.     return new_line
  65.  
  66.  
  67. def formatting(text: str) -> str:
  68.     lines = text.splitlines()
  69.     format_function_li = [
  70.         title_formatting,
  71.         code_block_formatting,
  72.         list_formatting,
  73.         monospace_formatting,
  74.         link_formatting,
  75.     ]
  76.     final_lines = list()
  77.  
  78.     for i, line in enumerate(lines):
  79.         for format_function in format_function_li:
  80.             line = format_function(line=line, lines=lines, current_i=i)
  81.         final_lines.append(line)
  82.     final_text = '\n'.join(final_lines)
  83.     return final_text
  84.  
  85.  
  86. def convert_md_to_mw(input_filename: str, output_filename: Optional[str],
  87.                      open_mode: str) -> None:
  88.     with open(input_filename, 'r') as input_file:
  89.         final_text = formatting(input_file.read())
  90.     if not output_filename:
  91.         return print(final_text)
  92.     with open(output_filename, open_mode) as output_file:
  93.         output_file.write(final_text)
  94.     return print(f'{output_filename} written')
  95.  
  96.  
  97. if __name__ == '__main__':
  98.     parser = ArgumentParser(prog='md2dk',
  99.                             usage='%(prog)s [-h] [-o O] input_file [--w]',
  100.                             description='Convert a file from markdown to '
  101.                                         'dokuwiki. If no output file is given,'
  102.                                         ' the standard output will be used.')
  103.     parser.add_argument('input_file', type=str,
  104.                         help='the file you need to convert')
  105.     parser.add_argument('-o',
  106.                         help='name of output file in dokuwiki format')
  107.     parser.add_argument('--w', default='x', const='w', action='store_const',
  108.                         help='if you want to overwrite the output file')
  109.     args: Namespace = parser.parse_args()
  110.     convert_md_to_mw(args.input_file, args.o, args.w)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement