Bug fix / changed the way messages output

Changed a few typos and rearranged some code to make things more efficient. Added a counter to printed statements so you don't get 55 separate messages telling you that it couldn't link your files so it had to copy them instead
This commit is contained in:
pine 2021-04-30 11:12:39 -06:00
parent 989a408325
commit 36578a7414
Signed by: pine
GPG Key ID: 66AAFCFCCFBB559E
2 changed files with 40 additions and 26 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
__pycache__/

View File

@ -16,7 +16,7 @@ def default(var, default, dir = False):
except NameError: return default
def parse_directory(dir):
if not dir.endsiwth('/'): dir += '/'
if not dir.endswith('/'): dir += '/'
if not os.path.exists(dir): os.mkdir(dir)
return dir
@ -42,7 +42,15 @@ dynamic_dict = {
}
dynamic_dict.update(replace_table) #add whatever's specified in settings.py
messages = {}
#START HELPER FUNCTIONS
def add_message(m):
if not messages.get(m) is None:
messages[m] += 1
else:
messages[m] = 1
def files_to_gem(dir, files, date=None, name=lambda f, dir:f[len(dir):]):
s = []
for f in files: #I apoligize for this one-liner, but it works?
@ -73,7 +81,7 @@ def link(src, dest):
os.remove(dest)
link(src, dest)
except OSError:
print("Can't create hard-link, destination folder is on a different partition. Copying instead.")
add_message("Can't create hard-link, destination folder is on a different partition. Copying instead.")
copyfile(src, dest)
perms_s = oct(os.stat(src).st_mode)[-3:]
perms_d = oct(os.stat(dest).st_mode)[-3:]
@ -88,9 +96,11 @@ def parse_str_int(s):
i = int(s[1:]) if negative else int(s)
return i, negative
except:
print("Error: Could not parse argument as integer")
add_message("Error: Could not parse argument as integer")
return None, None
rel_path = lambda path: path[len(SOURCE_DIR):]
def replace_dynamic(body, fpath, d_list=None, dynamic_dict=dynamic_dict, VAR_REGEX=VAR_REGEX):
if d_list == None:
#^don't recompile regex if we don't have to
@ -122,13 +132,13 @@ def replace_dynamic(body, fpath, d_list=None, dynamic_dict=dynamic_dict, VAR_REG
if not args: replace_val = dynamic_dict[key]([])
else: replace_val = dynamic_dict[key](args)
except TypeError:
print("Too many args supplied to key %s: %s" % (key, args))
add_message("Too many args supplied to key %s: %s" % (key, args))
replace_val = dynamic_dict[key]([])
#^If the function takes arguments, pass arguments
else:
replace_val = dynamic_dict.get(key)
if replace_val is None:
print("Variable used but not defined in dynamic_dict or metadata: %s" % key)
add_message("Variable used but not defined in dynamic_dict or metadata: %s" % key)
replace_val = ""
body = body.replace(replace, str(replace_val))
if body[0:10] == "!TEMPLATE":
@ -141,7 +151,7 @@ def atom(count=0, dir=SOURCE_DIR, d=dynamic_dict):
if not d.get('site_url'): return "Must specify `site_url` in settings.py for atom feeds to work"
fname = lambda fpath: get_meta(f, "TITLE") if get_meta(fpath, "TITLE") else fpath[len(dir):]
url = lambda fpath: d['site_url'] + '/' + dir[len(SOURCE_DIR):] + os.path.basename(fpath)
url = lambda fpath: d['site_url'] + '/' + rel_path(dir) + os.path.basename(fpath)
date = lambda fpath: dt.fromtimestamp(os.path.getmtime(fpath)).strftime('%Y-%m-%dT%H:%M:%S+00:00')
files = [i for i in glob(dir + '/*') if os.path.isfile(i) and len(i.split('.')) > 1 and i.split('.')[-1] in TEMPLATE_EXTENSIONS and not os.path.basename(i).startswith(IGNORE_PREFIX)]
@ -197,10 +207,10 @@ def python(command, fpath):
exec(command, namespace)
return namespace["out"]
except KeyError:
print("python did not return anything because you did not define the variable `out` in your statement")
add_message("python did not return anything because you did not define the variable `out` in your statement")
return ""
except:
print("python encountered a problem")
add_message("python encountered a problem")
return ""
def shell(command, fpath, encoding="UTF-8"):
@ -209,7 +219,7 @@ def shell(command, fpath, encoding="UTF-8"):
parent_dir = "/".join(fpath.split('/')[:-1]) + '/'
return subprocess.check_output(command, shell=True, cwd=parent_dir).decode(encoding).strip()
except:
print("shell encountered a problem")
add_message("shell encountered a problem")
return ""
def tags(dir=SOURCE_DIR):
@ -223,12 +233,12 @@ def tags(dir=SOURCE_DIR):
tags[tag.lower()] = [f] if tags.get(tag.lower()) is None else tags[tag.lower()] + [f]
if not tags: return "No tags created yet"
tag_dir = DEST_DIR + dir[len(SOURCE_DIR):] + 'tag'
tag_dir = DEST_DIR + rel_path(dir) + 'tag'
tag_template_exists = os.path.isfile(TEMPLATE_DIR + "tag.template") #defined here so the function isn't called multiple times in the for loop
if not os.path.isdir(tag_dir): os.mkdir(tag_dir)
for tag, files in tags.items():
fname = lambda f, dir: get_meta(f, "TITLE") if os.path.isfile(f) and get_meta(f, "TITLE") else f[len(dir):]
file_s = '\n'.join(['=> /%s %s' % (f[len(SOURCE_DIR):], fname(f, dir)) for f in files])
file_s = '\n'.join(['=> /%s %s' % (rel_path(f), fname(f, dir)) for f in files])
with open("%s/%s.gmi" % (tag_dir, tag), 'w') as f:
if tag_template_exists:
lines = [file_s]
@ -256,29 +266,32 @@ def make(SOURCE_DIR=SOURCE_DIR,
dynamic_dict["CURRENT_DIR"] = root if root.endswith("/") else root + '/' #I use this in the source files
[dirs.remove(d) for d in list(dirs) if d.startswith('_')]
for d in dirs: #create the directories if they haven't been created
if not os.path.isdir(DEST_DIR + d): os.mkdir(DEST_DIR + d)
if not os.path.isdir(DEST_DIR + os.path.join(rel_path(root), d)):
os.mkdir(DEST_DIR + os.path.join(rel_path(root), d))
for fname in files:
parent = root[len(SOURCE_DIR):]
parent = rel_path(root)
fpath = os.path.join(root, fname)
dynamic_dict["CURRENT_FILE"] = fpath #Use this in the source files, too
dpath = "%s%s" % (DEST_DIR, os.path.join(parent, fname))
template = None
isChangable = len(fname.split(".")) > 1 and fname.split(".")[-1] in TEMPLATE_EXTENSIONS
with open(fpath, 'r') as f:
rl = f.read().splitlines()
isChangable = os.path.splitext(fname)[1][1:] in TEMPLATE_EXTENSIONS
if not isChangable:
link(fpath, dpath)
else:
#^Only look at files with a suffix in template_extensions, saves time + sometimes you can't read weird files like executables
with open(fpath, 'r') as f:
rl = f.read().splitlines()
#Get the template
if rl and rl[0].strip() == "!TEMPLATE:none": #don't do a template if it says !TEMPLATE:none
rl.pop(0)
elif isChangable:
#^Only look at files with a suffix in template_extensions, saves time
if rl[0].startswith("!TEMPLATE"):
#Get the template
if rl and rl[0].strip() == "!TEMPLATE:none": #don't do a template if it says !TEMPLATE:none
rl.pop(0)
elif rl[0].startswith("!TEMPLATE"):
#TEMPLATE CASE 1: It's explicitely written out
try:
with open(TEMPLATE_DIR + r[0][10:] + ".template", 'r') as tfile:
template = tfile.read().splitlines()
except:
print("Template '%s' specified but does not exist" % r[0][10:])
add_message("Template '%s' specified but does not exist" % r[0][10:])
elif os.path.isfile(TEMPLATE_DIR + parent + ".template"):
#TEMPALTE CASE 2: It's automatically applied to the dynamic_dict
with open(TEMPLATE_DIR + parent + ".template", 'r') as tfile:
@ -286,9 +299,6 @@ def make(SOURCE_DIR=SOURCE_DIR,
if not template is None:
rl = template[:template.index("!CONTENT")] + rl + template[template.index("!CONTENT")+1:]
if not isChangable:
link(fpath, dpath)
else:
body = "\n".join([i for i in rl if not i.startswith("&")])
d_list = VAR_REGEX.findall(body)
if body == "\n".join(rl) and not d_list: #the files aren't dynamic, link them
@ -301,6 +311,9 @@ def make(SOURCE_DIR=SOURCE_DIR,
def main():
make()
for message, count in messages.items():
if count > 1: print("%s (x%s)" % (message, count))
else: print(message)
if __name__ == "__main__":
main()