Skip to content

Instantly share code, notes, and snippets.

@ayust
Created January 21, 2017 18:16
Show Gist options
  • Save ayust/e1bb9348ee34629714c743ed420aa096 to your computer and use it in GitHub Desktop.
Save ayust/e1bb9348ee34629714c743ed420aa096 to your computer and use it in GitHub Desktop.
Quick script to convert TOML front matter to JSON front matter
#!/usr/bin/env python
import json
import os
JSON_CONFIG = {
"indent": 2,
"sort_keys": True,
"ensure_ascii": False,
"allow_nan": False,
"separators": (",", ": "),
}
def strip_enclosing_quotes(val):
if val[:1] == val[-1:] and val[:1] in ("'", '"'):
val = val[1:-1]
return val
def convert_toml_to_json(toml_input):
# Note - this assumes that the input is valid TOML.
# We don't try to handle invalid markup cases.
fields = {}
lines = toml_input.split("\n")
for line in lines:
key, equals_sign, value = line.partition("=")
if not equals_sign:
continue
key = key.strip()
value = value.strip()
if not (key and value):
continue
key = strip_enclosing_quotes(key)
value = strip_enclosing_quotes(value)
fields[key] = value
return json.dumps(fields, **JSON_CONFIG)
def fix_file(path):
with open(path) as f:
before = f.read()
if not before.startswith("+++\n"):
return False
front_matter, ok, content = before[4:].partition("\n+++\n")
if not ok:
return False
json_front_matter = convert_toml_to_json(front_matter)
if json_front_matter is None:
return False
with open(path, "w") as f:
f.write(json_front_matter)
f.write("\n")
f.write(content)
return True
def main():
fixed_count = 0
for dirpath, _, filenames in os.walk(os.getcwd()):
markdown_files = (f for f in filenames if f.endswith(".md"))
markdown_paths = (os.path.join(dirpath, f) for f in markdown_files)
fixed_count += sum(1 for p in markdown_paths if fix_file(p))
print("{} files fixed.".format(fixed_count))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment