Skip to content

Commit

Permalink
Merge pull request #10 from davidomarf/develop
Browse files Browse the repository at this point in the history
Add YAML support for the sketches metadata
  • Loading branch information
davidomarf committed Oct 17, 2019
2 parents 23f08b1 + ae217c7 commit 93a2615
Show file tree
Hide file tree
Showing 10 changed files with 171 additions and 126 deletions.
2 changes: 1 addition & 1 deletion MANIFEST.in
Original file line number Diff line number Diff line change
@@ -1 +1 @@
recursive-include ginpar *.html *.css *.py *.jinja2 *.js
recursive-include ginpar *.html *.css *.py *.jinja2 *.js *.yaml
1 change: 1 addition & 0 deletions Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ pylint = "*"

[packages]
Jinja2 = "*"
PyYAML = "*"

[requires]
python_version = "3.7"
29 changes: 26 additions & 3 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

107 changes: 69 additions & 38 deletions ginpar/__init__.py
Original file line number Diff line number Diff line change
@@ -1,103 +1,134 @@
import os
import shutil
import yaml

from jinja2 import Environment, FileSystemLoader

from ginpar.settings import read_config
import ginpar.generators as gg

_SITE_FILE = 'config.json'
_SITE_FILE = "config.json"


def parse(path):
return eval('f"""' + open(path).read() + '"""')
return eval('f"""' + open(path).read() + '"""')

def build_sketch (sketch):

def build_sketch(sketch):
content = sketch
return content


def build_link(sketch):
title = sketch.split("/")[-1].split(".")[0]
return f'<a href="./{title}"">{title}</a><br/>\n'


def build_index(sketches):
content = ""
for s in sketches:
content += build_link(s)
return content


def unkebab(s):
return " ".join(s.split("-"))


def get_sketches_list(path):
sketches = []
# Create a list with all the directories inside path
for r, d, _ in os.walk(path):
for sketch in d:
sketches.append(
{
"name": sketch,
"script": os.path.join(r, sketch, "sketch.js"),
"data": os.path.join(r, sketch, "data.yaml"),
}
)

# Remove all the directories that don't contain both a `sketch.js` and `data.yaml` file
sketches[:] = filter(
lambda a: os.path.isfile(a["script"]) and os.path.isfile(a["data"]), sketches
)
return sketches


def convert_information(sketch):
path = sketch["data"]
with open(path, "r") as stream:
try:
parsed_data = yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
sketch["data"] = parsed_data
return sketch


def main():
_SITE = read_config(_SITE_FILE)

_THEME = _SITE['theme']
_THEME = _SITE["theme"]

_TEMPLATES_PATH = os.path.join('themes', _THEME, 'templates')
_TEMPLATES_PATH = os.path.join("themes", _THEME, "templates")

_jinja_env = Environment(
loader=FileSystemLoader(_TEMPLATES_PATH),
trim_blocks=True,
)
_jinja_env = Environment(loader=FileSystemLoader(_TEMPLATES_PATH), trim_blocks=True)

_jinja_env.filters['unkebab'] = unkebab
_jinja_env.filters["unkebab"] = unkebab

## Remove existent /public folder and create an empty one
if os.path.exists("public"):
shutil.rmtree('public')
shutil.rmtree("public")

os.mkdir('public')
os.mkdir("public")

## Copy the static/ folder of the theme
shutil.copytree(
os.path.join('themes', _THEME, 'static'),
os.path.join('public', 'static'))
os.path.join("themes", _THEME, "static"), os.path.join("public", "static")
)

## Create a sketches array
sketches_path = "./sketches"
sketches = []

for r, _, f in os.walk(sketches_path):
for file in f:
if file.endswith(".js"):
sketches.append(os.path.join(r, file))
sketches = get_sketches_list(sketches_path)
sketches[:] = map(convert_information, sketches)

## Create an index to contain all the sketches
_index_template = _jinja_env.get_template('index.html')

_index_template = _jinja_env.get_template("index.html")
index = open("public/index.html", "w")
index.write(_index_template.render(sketches=sketches, site = _SITE))
index.write(
_index_template.render(
sketches=map(lambda a: a["name"], sketches), site=_SITE
)
)
index.close()

for s in sketches:
## Ignore the path and extension of the sketch
title = s.split("/")[-1].split(".")[0]

## Create a directory with the sketch title
os.mkdir(f'public/{title}')
os.mkdir(f"public/{s['name']}")

## Convert the form JSON into a dict
form_dict = gg.sketch_to_dict(open(s).read())
form_dict = s["data"]

## Add name key to the dict elements
form_dict = gg.add_name(form_dict)

## Create index.html
_sketch_template = _jinja_env.get_template('sketch.html')
sketch_index = open(f'public/{title}/index.html', "w+")
sketch_index.write(_sketch_template.render(
sketch = unkebab(title),
form = gg.sketch_index(form_dict),
site = _SITE))
_sketch_template = _jinja_env.get_template("sketch.html")
sketch_index = open(f"public/{s['name']}/index.html", "w+")
sketch_index.write(
_sketch_template.render(
sketch=unkebab(s["name"]), form=gg.sketch_index(form_dict), site=_SITE
)
)
sketch_index.close()

## Create sketch.js
sketch_path = f'public/{title}/sketch.js'
sketch_path = f"public/{s['name']}/sketch.js"
sketch = open(sketch_path, "w+")

## Copy all the content from original sketches/{title}.js to sketch.js
sf = open(s, 'r')
sf = open(s["script"], "r")

sketch.write(gg.makeValueGetter(form_dict))

Expand Down
62 changes: 34 additions & 28 deletions ginpar/generators.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,50 @@
import os
import string
import json
import yaml

from jinja2 import Environment, FileSystemLoader


def dict_to_attrs(d):
attrs = []
for k, v in d.items():
attrs.append(f'{k}="{v}"')
attrs = " ".join(attrs)
return attrs

delimiters = '/* ##ginpar */'

delimiters = "/* ##ginpar */"

_INPUT_TEMPLATES_DIR = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'templates')
os.path.dirname(os.path.abspath(__file__)), "templates"
)

# Get a list that contains the name of the templates
_INPUT_TEMPLATES_LIST = list(
map(
lambda e : e.split(".")[0],
filter(
lambda e : e.endswith(".html"),
os.listdir(_INPUT_TEMPLATES_DIR))))
lambda e: e.split(".")[0],
filter(lambda e: e.endswith(".html"), os.listdir(_INPUT_TEMPLATES_DIR)),
)
)

_jinja_env = Environment(
loader=FileSystemLoader(_INPUT_TEMPLATES_DIR),
trim_blocks=True,
loader=FileSystemLoader(_INPUT_TEMPLATES_DIR), trim_blocks=True
)

_jinja_env.filters['getattrs'] = dict_to_attrs
_jinja_env.filters["getattrs"] = dict_to_attrs


def makeValueGetter(attrs):
_TEMPLATE = _jinja_env.get_template("retrieve.js")

return _TEMPLATE.render(attrs = attrs)

return _TEMPLATE.render(attrs=attrs)


def sketch_to_dict(s):
"""Receives the content of a sketch file with a JSON object
inside a pair of ginpar delimiters"""

## Work only with the substring between two delimiters
params_string = s.split(delimiters)[1]

Expand All @@ -55,47 +59,49 @@ def sketch_to_dict(s):

return json.loads(params)


def to_kebab(s):
s = s.lower().split(" ")
return '-'.join(s)
return "-".join(s)


def input_tag(field):
## Obtain the html id
id = to_kebab(field['name'])
##
id = to_kebab(field["name"])

##
attrs = []
for k, v in field["attrs"].items():
attrs.append(f'{k}="{v}"')
attrs = " ".join(attrs)

if id in _INPUT_TEMPLATES_LIST:
_input_template = _jinja_env.get_template(id + '.html')
_input_template = _jinja_env.get_template(id + ".html")
else:
_input_template = _jinja_env.get_template('input.html')
_input_template = _jinja_env.get_template("input.html")

# print(attrs)

return (_input_template.render(
id=id, name = field['name'], attrs = field["attrs"]))
return _input_template.render(id=id, name=field["name"], attrs=field["attrs"])


def form_tag(fields):
form = ["<form>"]
for f in fields:
form.append(input_tag(f))
form.append('\n</form>')
form.append("\n</form>")
form = "\n".join(form)
return form


def add_name(fields):
"""Adds a `name` using the `var` when no `name` was specified"""
for field in fields:
if 'name' not in field:
field['name'] = " ".join(field['var'].split("_")).capitalize()
field['id'] = to_kebab(field['name'])
if "name" not in field:
field["name"] = " ".join(field["var"].split("_")).capitalize()
field["id"] = to_kebab(field["name"])
return fields


def sketch_index(sketch):
return form_tag(sketch)

0 comments on commit 93a2615

Please sign in to comment.