Skip to content

Instantly share code, notes, and snippets.

@Bondrake
Created April 20, 2024 01:16
Show Gist options
  • Save Bondrake/b7ceb021f70172b65a551ecc42a78c98 to your computer and use it in GitHub Desktop.
Save Bondrake/b7ceb021f70172b65a551ecc42a78c98 to your computer and use it in GitHub Desktop.
This script will update all the Unicode codepoints in json/yaml/toml files to point to new Nerd Font icon locations
import os
import sys
def unicode_to_surrogate_pair(codepoint):
# Convert a Unicode codepoint to a surrogate pair if necessary
code = int(codepoint, 16)
if code <= 0xFFFF:
return f"\\u{codepoint.lower()}"
# Calculation for surrogate pairs
code -= 0x10000
high_surrogate = 0xD800 + (code // 0x400)
low_surrogate = 0xDC00 + (code % 0x400)
return f"\\u{high_surrogate:04x}\\u{low_surrogate:04x}"
def load_translation_table(filename):
translation_dict = {}
try:
with open(filename, 'r', encoding='utf-8') as file:
for line in file:
parts = line.strip().split()
if len(parts) >= 2:
old_code, new_code = parts[:2]
old_char = chr(int(old_code, 16))
new_char = chr(int(new_code, 16))
old_escape = f"\\u{old_code.lower()}"
new_escape = unicode_to_surrogate_pair(new_code)
translation_dict[old_char] = new_char
translation_dict[old_escape] = new_escape
except FileNotFoundError:
print(f"Error: The file '{filename}' was not found.")
sys.exit(1)
except Exception as e:
print(f"An error occurred: {e}")
sys.exit(1)
return translation_dict
def replace_codepoints(text_content, translation_dict):
for old_pattern, new_pattern in translation_dict.items():
text_content = text_content.replace(old_pattern, new_pattern)
return text_content
def process_directory(source_dir, dest_dir, translation_dict):
supported_extensions = {'.json', '.yaml', '.yml', '.toml'}
for root, dirs, files in os.walk(source_dir):
for file in files:
file_path = os.path.join(root, file)
file_ext = os.path.splitext(file)[1]
if file_ext in supported_extensions:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
updated_content = replace_codepoints(content, translation_dict)
dest_file_path = os.path.join(dest_dir, file)
os.makedirs(os.path.dirname(dest_file_path), exist_ok=True)
with open(dest_file_path, 'w', encoding='utf-8') as f:
f.write(updated_content)
def main():
if len(sys.argv) != 3:
print("Usage: python script.py <source_directory> <destination_directory>")
sys.exit(1)
source_dir = sys.argv[1]
dest_dir = sys.argv[2]
table_filename = os.path.join(sys.path[0], "nerdfont-new-unicode-icon-lookup-table")
translation_dict = load_translation_table(table_filename)
process_directory(source_dir, dest_dir, translation_dict)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment