forked from 0voice/interview_internal_reference
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sync_link
45 lines (40 loc) · 1.2 KB
/
sync_link
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: [email protected]
import re
from shutil import move
from urllib import parse
from pathlib import Path
class REMatcher(object):
def __init__(self, matchstring):
self.matchstring = matchstring
def match(self,regexp):
self.rematch = re.match(regexp, self.matchstring)
return bool(self.rematch)
def group(self,i):
return self.rematch.group(i)
def get_path(name):
try:
files = Path('./').glob('**/%s.md' % name)
for file in files:
return str(file)
except:
pass
return None
prefix = '##### '
filepath = './README.md'
temppath = filepath + '.tmp'
with open(filepath, 'r') as lines:
with open(temppath, 'w') as file:
for line in lines:
m1 = REMatcher(line)
if not m1.match(r'%s(.*)' % prefix):
file.write(line)
continue
name = m1.group(1)
m2 = REMatcher(name)
if m2.match(r'\[(.*)\]\((.*)\)'):
name = m2.group(1)
path = get_path(name)
file.write(('%s[%s](%s)\n' % (prefix, name, parse.quote(path))) if path else line)
move(temppath, filepath)