compudanzas/links.py

71 lines
2.1 KiB
Python
Raw Permalink Normal View History

2021-06-16 04:37:46 +00:00
import re
import os
2021-06-16 18:18:59 +00:00
import shutil
2021-06-16 04:37:46 +00:00
def filename2Wikilink( s ):
2021-06-16 18:18:59 +00:00
return '{' + s.replace('_',' ').replace('.gmo','') + '}'
2021-06-16 18:40:20 +00:00
def wikilink2Filename( s, ext='.gmi' ):
return s.strip("{}").replace(' ','_') + ext
2021-06-16 04:37:46 +00:00
os.chdir('src/')
2021-06-16 18:18:59 +00:00
incoming = {}
2021-06-16 04:37:46 +00:00
for filename in os.listdir():
2021-06-16 18:18:59 +00:00
if filename.endswith('.gmo'):
# copy to tmp
shutil.copy(filename, '../tmp/'+filename)
2021-06-16 18:40:20 +00:00
# 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)
2021-08-16 01:17:39 +00:00
pre_mode = False
2021-06-16 18:40:20 +00:00
for line in file:
2021-08-16 01:17:39 +00:00
if re.match("```",line) != None: # toggle preformatted mode
pre_mode = not pre_mode
if pre_mode: # skip preformatted mode
2021-07-23 01:10:30 +00:00
continue
m=re.search("\{.+\}",line)
2021-06-16 18:40:20 +00:00
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()
2021-06-16 18:18:59 +00:00
os.chdir('../tmp/')
2021-06-16 18:40:20 +00:00
# remove incoming links for:
# incoming.pop('{pages}')
2021-06-17 00:37:29 +00:00
incoming.pop('{home}')
2021-06-17 00:41:43 +00:00
#incoming.pop('{license}')
2021-06-16 18:40:20 +00:00
2021-06-16 18:18:59 +00:00
for key,links in incoming.items():
2021-06-16 18:40:20 +00:00
# get filename for key
filename = wikilink2Filename(key,'.gmo')
2022-01-06 20:36:49 +00:00
# print(key)
2021-06-16 18:40:20 +00:00
# open file in append mode
file = open(filename, 'a')
if len(links):
# write incoming links
2022-01-06 20:36:49 +00:00
# print( '{} incoming links\n'.format( len(links) ) )
2021-07-06 22:52:29 +00:00
file.write("\n\n# incoming links\n")
2021-06-16 18:18:59 +00:00
for link in links:
2021-06-16 18:44:52 +00:00
gemlink = '=> ./{} {}'.format(wikilink2Filename(link), link)
2021-06-16 18:40:20 +00:00
# print(gemlink)
file.write(gemlink+"\n")
else:
2022-01-06 20:36:49 +00:00
print( '{}: orphan\n'.format(key) )
2021-06-16 18:40:20 +00:00
file.write("\n\nno incoming links\n")
file.close()