-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.py
executable file
·59 lines (48 loc) · 2.01 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/python3
import argparse
import os
import logging
from utils import generate_html_page, tokenize_source_code
from tokenizers.PyTokenizer import PyTokenizer
from tokenizers.BashTokenizer import BashTokenizer
from tokenizers.CTokenizer import CTokenizer
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Add syntax highlighting to Python source code',
formatter_class=argparse.RawDescriptionHelpFormatter
)
parser.add_argument('sourcefile', help='Sourcecode file.')
parser.add_argument('outputfile', help='Result file name.')
parser.add_argument('-b', '--browser', action='store_true',
help='Run browser with rendered page.')
parser.add_argument('-l', '--language', type=str,
help='Programming language to parse.',
choices=['python', 'bash', 'c'])
parser.add_argument('-d', '--debug', action='store_true',
help='Run program in debug mode.')
args = parser.parse_args()
if args.debug:
logging.basicConfig(level=logging.DEBUG)
sourcename = args.sourcefile
tokenizer = None
tokenizers = (PyTokenizer, BashTokenizer, CTokenizer)
if args.language:
for ct in tokenizers:
if ct.LANGUAGE_NAME == args.language:
tokenizer = ct
else:
for ct in tokenizers:
if any(sourcename.endswith(ext) for ext in ct.EXTENSIONS):
tokenizer = ct
if tokenizer is None:
raise ValueError('No tokenizer found for you language. Specify it '
'manually with -l/--language')
with open(sourcename, 'r') as f:
source = f.read()
encoded_text = generate_html_page(tokenize_source_code(source,
tokenizer))
with open(args.outputfile, 'w') as f:
f.write(encoded_text)
if args.browser:
import webbrowser
webbrowser.open('file://' + os.path.abspath(args.outputfile))