compudanzas/links.py

71 lines
2.1 KiB
Python

import re
import os
import shutil
def filename2Wikilink( s ):
return '{' + s.replace('_',' ').replace('.gmo','') + '}'
def wikilink2Filename( s, ext='.gmi' ):
return s.strip("{}").replace(' ','_') + ext
os.chdir('src/')
incoming = {}
for filename in os.listdir():
if filename.endswith('.gmo'):
# copy to tmp
shutil.copy(filename, '../tmp/'+filename)
# if filename != 'pages.gmo' and filename != 'index.gmo':
if filename != 'pages.gmo':
# convert filename to wikilink
wikilink=filename2Wikilink(filename)
if wikilink not in incoming:
incoming[wikilink] = set()
# open file and search for all outgoing links
file = open(filename)
pre_mode = False
for line in file:
if re.match("```",line) != None: # toggle preformatted mode
pre_mode = not pre_mode
if pre_mode: # skip preformatted mode
continue
m=re.search("\{.+\}",line)
if m:
match = m.group(0) # get matched string
if match not in incoming: # create a new set for that page
incoming[match] = set()
# add this file
incoming[match].add(wikilink)
file.close()
os.chdir('../tmp/')
# remove incoming links for:
# incoming.pop('{pages}')
incoming.pop('{home}')
#incoming.pop('{license}')
for key,links in incoming.items():
# get filename for key
filename = wikilink2Filename(key,'.gmo')
# print(key)
# open file in append mode
file = open(filename, 'a')
if len(links):
# write incoming links
# print( '{} incoming links\n'.format( len(links) ) )
file.write("\n\n# incoming links\n")
for link in links:
gemlink = '=> ./{} {}'.format(wikilink2Filename(link), link)
# print(gemlink)
file.write(gemlink+"\n")
else:
print( '{}: orphan\n'.format(key) )
file.write("\n\nno incoming links\n")
file.close()