Skip to content
This repository was archived by the owner on Aug 5, 2022. It is now read-only.

Commit ed85a4d

Browse files
JohnVillalovosgrgustaf
authored andcommitted
[build] Rewrite 'convert.sh' into python as 'convert.py' (#1831)
The 'convert.sh' script was a bit difficult to understand. Rewrite it using Python 3 and call it 'convert.py' Signed-off-by: John L. Villalovos <[email protected]>
1 parent cb6f7ba commit ed85a4d

File tree

5 files changed

+117
-99
lines changed

5 files changed

+117
-99
lines changed

Makefile

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -391,9 +391,9 @@ ifeq ($(SNAPSHOT), on)
391391
else
392392
@echo Creating C string from JS application...
393393
ifeq ($(BOARD), linux)
394-
@./scripts/convert.sh $(JS) $(OUT)/include/zjs_script_gen.h
394+
@./scripts/convert.py $(JS) $(OUT)/include/zjs_script_gen.h
395395
else
396-
@./scripts/convert.sh $(OUT)/$(JS_TMP) $(OUT)/include/zjs_script_gen.h
396+
@./scripts/convert.py $(OUT)/$(JS_TMP) $(OUT)/include/zjs_script_gen.h
397397
endif
398398
endif
399399

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ output when you do build for Arduino 101.
337337

338338
## JS Minifier
339339

340-
To save space it is recommended to use a minifier. In `convert.sh`, the script
340+
To save space it is recommended to use a minifier. In `convert.py`, the script
341341
used to encode your JS into a source file, we use `uglifyjs`. If you didn't
342342
install this earlier, you can do so with the command:
343343
```bash

scripts/README

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ checkheaders
2323
Tries to detect whether our header files include all the header files they
2424
depend on.
2525

26-
convert.sh
26+
convert.py
2727
----------
2828
Runs minifier on a JavaScript file and writes it out in a C string format.
2929

scripts/convert.py

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
#!/usr/bin/env python3
2+
3+
#
4+
# This script converts a file's ASCII data into a C char array:
5+
#
6+
# const char script_gen[] = { ........ }
7+
#
8+
9+
# This script was written to be compatible with Python 3.4
10+
11+
import argparse
12+
import collections
13+
import os
14+
import pathlib
15+
import subprocess
16+
import sys
17+
18+
Uglify = collections.namedtuple("Uglify", ['content', 'used_uglifyjs'])
19+
20+
21+
def main():
22+
args = parse_args()
23+
minified_result = uglifyjs(args.input)
24+
write_minified(args.output, minified_result)
25+
26+
27+
def write_minified(output_path, minified_result):
28+
"""Write the minified output, escaping things as necessary
29+
30+
:param output_path: A pathlib.Path() object of the output file.
31+
:param minified_result: An Uglify() object containing the content to write.
32+
"""
33+
with output_path.open('w') as out_file:
34+
last_char = ""
35+
print('"', end='', file=out_file)
36+
for char in minified_result.content:
37+
# Escape quote symbols
38+
if char in ('"', ):
39+
print(r'\"', end='', file=out_file)
40+
elif last_char == "\\":
41+
# Special case for new line and carriage return that can appear
42+
# in a string e.g. print("some string\n");
43+
# This is needed because BASH reads the "\n" as two characters,
44+
# but in a C string it is just one character.
45+
if char in ('n', 'r'):
46+
# NOTE(jlvillal): If not 'n' or 'r' we print nothing. This
47+
# is how 'convert.sh' did it.
48+
print('\\{}'.format(char), end='', file=out_file)
49+
elif char == "\n":
50+
if not minified_result.used_uglifyjs:
51+
print(r'\n"', end='\n"', file=out_file)
52+
else:
53+
print(char, end='', file=out_file)
54+
last_char = char
55+
print('"', end='', file=out_file)
56+
57+
58+
def uglifyjs(input_path):
59+
"""Run 'uglifyjs' on the input file
60+
61+
:param input_path: A pathlib.Path() object of the input file.
62+
:returns: An Uglify() object
63+
"""
64+
filename = str(input_path)
65+
# NOTE(jlvillal): The docs say that '-nc' is the same as '--no-copyright'
66+
# but in testing it is not.
67+
# https://github.com/mishoo/UglifyJS/blob/2bc1d02363db3798d5df41fb5059a19edca9b7eb/README.html#L481-L483
68+
ugl_args = ["-nc", "-mt"]
69+
70+
# uglifyjs seems to have vastly different options between versions, this
71+
# should work with both
72+
cmd_line = ['uglifyjs', '--version']
73+
try:
74+
result = subprocess.call(cmd_line, stdout=subprocess.DEVNULL)
75+
except FileNotFoundError:
76+
# We don't have uglifyjs, so return the contents of the file
77+
return Uglify(input_path.read_text(), False)
78+
79+
if result == 0:
80+
# We have newer uglifyjs
81+
cmd_line = ['uglifyjs', filename] + ugl_args
82+
else:
83+
# Older uglifyjs
84+
cmd_line = ['uglifyjs'] + ugl_args + [filename]
85+
try:
86+
output = subprocess.check_output(cmd_line)
87+
except subprocess.CalledProcessError as exc:
88+
print("ERROR: Minification failed!")
89+
sys.exit(exc.returncode)
90+
return Uglify(output.decode('utf-8'), True)
91+
92+
93+
def parse_args():
94+
parser = argparse.ArgumentParser(
95+
description=("Runs minifier on a JavaScript file and writes it out in "
96+
"a C string format."))
97+
parser.add_argument("input", metavar='INPUT_FILE')
98+
parser.add_argument("output", metavar='OUTPUT_FILE')
99+
args = parser.parse_args()
100+
# Make all paths absolute and expand any "~/" usage.
101+
for arg_name in ('input', 'output'):
102+
setattr(args, arg_name, pathlib.Path(
103+
os.path.abspath(os.path.expanduser(getattr(args, arg_name)))))
104+
if not args.input.is_file():
105+
print("ERROR: The INPUT_FILE {!r} does not exist.".format(
106+
str(args.input)))
107+
parser.print_help()
108+
sys.exit(1)
109+
return args
110+
111+
112+
if '__main__' == __name__:
113+
sys.exit(main())

scripts/convert.sh

Lines changed: 0 additions & 95 deletions
This file was deleted.

0 commit comments

Comments
 (0)