-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathimport-inline-code
executable file
·51 lines (44 loc) · 1.41 KB
/
import-inline-code
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
#!/usr/bin/env python2.7
from __future__ import print_function
import errno
import os
from glob import glob
FILE_EXTENSION_BY_LANGUAGE = {
'bash': 'sh',
'C': 'c',
'C#': 'cs',
'C++': 'cpp',
'go': 'go',
'java': 'java',
'powershell': 'ps1',
'python': 'py',
'R': 'R',
}
def import_lesson(lesson_file_path):
with open(lesson_file_path) as lesson_file:
for line in lesson_file:
if line.startswith('```'):
write_output(lesson_file, line[3:].split()[0])
return
def write_output(lesson_file, language):
extension = FILE_EXTENSION_BY_LANGUAGE.get(language)
if not extension:
return
path_parts = lesson_file_path.split('/')
chapter = os.path.join('projects', extension, path_parts[1])
try:
os.makedirs(chapter)
except OSError as error:
if error.errno != errno.EEXIST:
raise
file_name = os.path.splitext(path_parts[2])[0] + '.' + extension
file_name = file_name[file_name.find('-') + 1:] # remove prefix
with open(os.path.join(chapter, file_name), 'w') as output_file:
for code_line in lesson_file:
if code_line == '```\n':
return
output_file.write(code_line)
if __name__ == '__main__':
for lesson_file_path in glob('markdowns/*/*.md'):
import_lesson(lesson_file_path)
print('imported code from', lesson_file_path)