Last active
May 1, 2017 11:08
-
-
Save tpb1908/2e5b2eb2be50cdc95ed258d1dcad2b00 to your computer and use it in GitHub Desktop.
Insert code from file into markdown
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import re | |
import os | |
def get_imports(source): | |
imports = [] | |
i = 0 | |
while i < len(source)-1: | |
print i | |
# Find the next import | |
i = source.find("#import", i, len(source)) | |
if i == -1: | |
break | |
clip_start = i | |
i += + len("#import") | |
# Start clip | |
import_value = "" | |
# Skip any whitespave | |
while source[i] == ' ': | |
i += 1 | |
# Match " | |
print i | |
assert source[i] == '"' | |
# Extract value | |
i += 1 | |
import_value = "" | |
import_func = "" | |
while source[i] != '"': | |
if(source[i] == '$'): | |
j = i+1 | |
while(source[j] != '$'): | |
import_func += source[j] | |
j += 1 | |
i = j | |
elif(source[i] != ' '): | |
import_value += source[i] | |
i += 1 | |
i += 1 | |
import_type = import_value[import_value.rfind('.')+1:] | |
# End clip | |
clip_end = i | |
print source[clip_start:clip_end] | |
imports.append((clip_start, clip_end, import_value, import_type, import_func)) | |
return imports | |
source = "" | |
with open('doc.md') as source_doc: | |
source = source_doc.read().replace("#page", "<div style=\"page-break-after: always;\"></div>") | |
base = "/home/theo/Documents/workspace/AndroidProjectsClient/" | |
imports = get_imports(source) | |
offset = 0 | |
for (start, end, value, file_type, file_function) in imports: | |
value = str(base + value) | |
print "Importing: {}".format(value) | |
with open(value, 'r') as import_file: | |
code = "" | |
insert = "**" + os.path.basename(import_file.name) | |
if(len(file_function) != 0): | |
print("Importing: function: " + str(file_function)) | |
s = import_file.read() | |
try: | |
funstart = s.index(file_function) | |
i = s.index('{', funstart) | |
opened = 1 | |
closed = 0 | |
while(opened != closed): | |
i += 1 | |
if(s[i] == '{'): | |
opened += 1 | |
elif(s[i] == '}'): | |
closed += 1 | |
code = s[funstart:i + 1] | |
except ValueError: | |
raise ImportError("Couldn't find function: " + str(file_function)) | |
else : | |
code = import_file.read() | |
insert += "**\n" + "``` " + file_type + "\n" + code + "\n```" | |
source = source[:start-offset] + insert + source[end-offset:] | |
offset += end - start - len(insert) | |
with open('doc_gen.md', 'w') as doc: | |
doc.write(source) | |
os.system("git add doc_gen.md") | |
# os.system("markdown-pdf --css-path ./github.css --paper-format A4 ./doc_gen.md") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
#import "path_to_your_code$a_fully_qualified_function_name$ "