Created
March 25, 2018 07:26
-
-
Save ssbb/2f10a9a349d27e1985d05cb1528257d6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import json | |
import os | |
import re | |
BASE_DIR = os.path.join(os.path.dirname(os.path.realpath(__file__))) | |
STATIC_DIR = os.path.join(BASE_DIR, '..', 'static') | |
def build_name(path): | |
(name, _ext) = os.path.splitext(os.path.basename(path)) | |
name = name.strip().replace('-', '_').replace(' ', '_') | |
name = re.sub(r'\((\d+)\)', '_\g<1>', name) | |
components = name.split('_') | |
return components[0] + ''.join(i.title() for i in components[1:]) | |
def build_assets(path): | |
result = {} | |
name = os.path.basename(path) | |
for sub_path in os.listdir(path): | |
if sub_path.startswith('.'): | |
continue | |
sub_name = build_name(sub_path) | |
if sub_name == 'icons': | |
continue | |
sub_path = os.path.join(path, sub_path) | |
if os.path.isdir(sub_path): | |
result[sub_name] = build_assets(sub_path) | |
else: | |
result[sub_name] = os.path.relpath(sub_path, BASE_DIR) | |
return result | |
def generate_javascript(assets, nest=1, level=0): | |
result = '\n' | |
spacer = ' ' * (nest * 2) | |
for (k, v) in assets.items(): | |
if type(v) is dict: | |
result += f'{spacer}{k}: {{{generate_javascript(v, nest + 1, level + 1)}{spacer}}},\n' | |
else: | |
result += f"{spacer}{k}: require('{v}'),\n" | |
if level == 0: | |
result = f'module.exports = {{{result}}};' | |
return result | |
def generate_elm(assets, level=0): | |
result = [] | |
for (k, v) in assets.items(): | |
if type(v) is dict: | |
result.append(f'{k} : {{ {generate_elm(v, level + 1)} }} ') | |
else: | |
result.append(f'{k} : String') | |
result = ', '.join(result) | |
if level == 0: | |
result = f'module Data.Assets exposing (Assets)\n\ntype alias Assets =\n {{{result}}}' | |
return result | |
if __name__ == '__main__': | |
assets = build_assets(STATIC_DIR) | |
js_code = generate_javascript(assets) | |
elm_code = generate_elm(assets) | |
with open('js/assets.js', 'w') as f: | |
f.write(js_code) | |
with open('elm/Data/Assets.elm', 'w') as f: | |
f.write(elm_code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment