Skip to content

Commit 5c7b16f

Browse files
author
Juan Carlos
committed
Remove dependencies
1 parent 9357ce7 commit 5c7b16f

File tree

1 file changed

+39
-51
lines changed

1 file changed

+39
-51
lines changed

css_html_js_minify/minify.py

Lines changed: 39 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -26,16 +26,10 @@
2626
from .html_minifier import html_minify
2727
from .js_minifier import js_minify
2828

29-
from anglerfish import (check_encoding, check_folder, make_logger,
30-
make_post_exec_msg, set_process_name,
31-
set_single_instance, walk2list, beep,
32-
set_terminal_title)
3329

34-
35-
__all__ = ('process_multiple_files', 'prefixer_extensioner', 'prepare',
30+
__all__ = ('process_multiple_files', 'prefixer_extensioner',
3631
'process_single_css_file', 'process_single_html_file',
3732
'process_single_js_file', 'make_arguments_parser', 'main')
38-
start_time = datetime.now()
3933

4034

4135
##############################################################################
@@ -45,18 +39,17 @@ def process_multiple_files(file_path, watch=False, wrap=False, timestamp=False,
4539
comments=False, sort=False, overwrite=False,
4640
zipy=False, prefix='', add_hash=False):
4741
"""Process multiple CSS, JS, HTML files with multiprocessing."""
48-
log.debug("Process {} is Compressing {}.".format(os.getpid(), file_path))
42+
print(f"Process {os.getpid()} is Compressing {file_path}.")
4943
if watch:
5044
previous = int(os.stat(file_path).st_mtime)
51-
log.info("Process {} is Watching {}.".format(os.getpid(), file_path))
45+
print(f"Process {os.getpid()} is Watching {file_path}.")
5246
while True:
5347
actual = int(os.stat(file_path).st_mtime)
5448
if previous == actual:
5549
sleep(60)
5650
else:
5751
previous = actual
58-
log.debug("Modification detected on {0}.".format(file_path))
59-
check_folder(os.path.dirname(file_path))
52+
print(f"Modification detected on {file_path}.")
6053
if file_path.endswith(".css"):
6154
process_single_css_file(
6255
file_path, wrap=wrap, timestamp=timestamp,
@@ -95,13 +88,13 @@ def prefixer_extensioner(file_path, old, new,
9588
>>> prefixer_extensioner('/tmp/test.js', '.js', '.min.js')
9689
'/tmp/test.min.js'
9790
"""
98-
log.debug("Prepending '{}' Prefix to {}.".format(new.upper(), file_path))
91+
print(f"Prepending '{new.upper()}' Prefix to {file_path}.")
9992
extension = os.path.splitext(file_path)[1].lower().replace(old, new)
10093
filenames = os.path.splitext(os.path.basename(file_path))[0]
10194
filenames = prefix + filenames if prefix else filenames
10295
if add_hash and file_content: # http://stackoverflow.com/a/25568916
10396
filenames += "-" + sha1(file_content.encode("utf-8")).hexdigest()[:11]
104-
log.debug("Appending SHA1 HEX-Digest Hash to '{}'.".format(file_path))
97+
print(f"Appending SHA1 HEX-Digest Hash to '{file_path}'.")
10598
dir_names = os.path.dirname(file_path)
10699
file_path = os.path.join(dir_names, filenames + extension)
107100
return file_path
@@ -112,10 +105,10 @@ def process_single_css_file(css_file_path, wrap=False, timestamp=False,
112105
zipy=False, prefix='', add_hash=False,
113106
output_path=None):
114107
"""Process a single CSS file."""
115-
log.info("Processing CSS file: {0}.".format(css_file_path))
108+
print(f"Processing CSS file: {css_file_path}.")
116109
with open(css_file_path, encoding="utf-8") as css_file:
117110
original_css = css_file.read()
118-
log.debug("INPUT: Reading CSS file {}.".format(css_file_path))
111+
print(f"INPUT: Reading CSS file {css_file_path}.")
119112
minified_css = css_minify(original_css, wrap=wrap,
120113
comments=comments, sort=sort)
121114
if timestamp:
@@ -130,7 +123,7 @@ def process_single_css_file(css_file_path, wrap=False, timestamp=False,
130123
css_file_path, ".css",
131124
".css.gz" if overwrite else ".min.css.gz", original_css,
132125
prefix=prefix, add_hash=add_hash)
133-
log.debug("OUTPUT: Writing ZIP CSS {}.".format(gz_file_path))
126+
print(f"OUTPUT: Writing ZIP CSS {gz_file_path}.")
134127
else:
135128
min_css_file_path = gz_file_path = output_path
136129
if not zipy or output_path is None:
@@ -140,17 +133,17 @@ def process_single_css_file(css_file_path, wrap=False, timestamp=False,
140133
if zipy:
141134
with gzip.open(gz_file_path, "wt", encoding="utf-8") as output_gz:
142135
output_gz.write(minified_css)
143-
log.debug("OUTPUT: Writing CSS Minified {0}.".format(min_css_file_path))
136+
print(f"OUTPUT: Writing CSS Minified {min_css_file_path}.")
144137
return min_css_file_path
145138

146139

147140
def process_single_html_file(html_file_path, comments=False, overwrite=False,
148141
prefix='', add_hash=False, output_path=None):
149142
"""Process a single HTML file."""
150-
log.info("Processing HTML file: {0}.".format(html_file_path))
143+
print(f"Processing HTML file: {html_file_path}.")
151144
with open(html_file_path, encoding="utf-8") as html_file:
152145
minified_html = html_minify(html_file.read(), comments=comments)
153-
log.debug("INPUT: Reading HTML file {0}.".format(html_file_path))
146+
print(f"INPUT: Reading HTML file {html_file_path}.")
154147
if output_path is None:
155148
html_file_path = prefixer_extensioner(
156149
html_file_path, ".html" if overwrite else ".htm", ".html",
@@ -159,17 +152,17 @@ def process_single_html_file(html_file_path, comments=False, overwrite=False,
159152
html_file_path = output_path
160153
with open(html_file_path, "w", encoding="utf-8") as output_file:
161154
output_file.write(minified_html)
162-
log.debug("OUTPUT: Writing HTML Minified {0}.".format(html_file_path))
155+
print(f"OUTPUT: Writing HTML Minified {html_file_path}.")
163156
return html_file_path
164157

165158

166159
def process_single_js_file(js_file_path, timestamp=False, overwrite=False,
167160
zipy=False, output_path=None):
168161
"""Process a single JS file."""
169-
log.info("Processing JS file: {0}.".format(js_file_path))
162+
print(f"Processing JS file: {js_file_path}.")
170163
with open(js_file_path, encoding="utf-8") as js_file:
171164
original_js = js_file.read()
172-
log.debug("INPUT: Reading JS file {0}.".format(js_file_path))
165+
print(f"INPUT: Reading JS file {js_file_path}.")
173166
minified_js = js_minify(original_js)
174167
if timestamp:
175168
taim = "/* {} */ ".format(datetime.now().isoformat()[:-7].lower())
@@ -182,7 +175,7 @@ def process_single_js_file(js_file_path, timestamp=False, overwrite=False,
182175
gz_file_path = prefixer_extensioner(
183176
js_file_path, ".js", ".js.gz" if overwrite else ".min.js.gz",
184177
original_js)
185-
log.debug("OUTPUT: Writing ZIP JS {}.".format(gz_file_path))
178+
print(f"OUTPUT: Writing ZIP JS {gz_file_path}.")
186179
else:
187180
min_js_file_path = gz_file_path = output_path
188181
if not zipy or output_path is None:
@@ -192,7 +185,7 @@ def process_single_js_file(js_file_path, timestamp=False, overwrite=False,
192185
if zipy:
193186
with gzip.open(gz_file_path, "wt", encoding="utf-8") as output_gz:
194187
output_gz.write(minified_js)
195-
log.debug("OUTPUT: Writing JS Minified {0}.".format(min_js_file_path))
188+
print(f"OUTPUT: Writing JS Minified {min_js_file_path}.")
196189
return min_js_file_path
197190

198191

@@ -232,56 +225,53 @@ def make_arguments_parser():
232225
parser.add_argument('--watch', action='store_true', help="Watch changes.")
233226
parser.add_argument('--multiple', action='store_true',
234227
help="Allow Multiple instances (Not Recommended).")
235-
parser.add_argument('--beep', action='store_true',
236-
help="Beep sound will be played when it ends at exit.")
237228
return parser.parse_args()
238229

239230

240-
def prepare():
241-
"""Prepare basic setup for main loop running."""
242-
global log
243-
log = make_logger("css-html-js-minify", emoji=True) # Make a Logger Log.
244-
set_terminal_title("css-html-js-minify")
245-
check_encoding() # AutoMagically Check Encodings/root
246-
set_process_name("css-html-js-minify") # set Name
247-
set_single_instance("css-html-js-minify") # set Single Instance
248-
return log
231+
def walk2list(folder: str, target: tuple, omit: tuple=(),
232+
showhidden: bool=False, topdown: bool=True,
233+
onerror: object=None, followlinks: bool=False) -> tuple:
234+
"""Perform full walk, gather full path of all files."""
235+
oswalk = os.walk(folder, topdown=topdown,
236+
onerror=onerror, followlinks=followlinks)
237+
238+
return [os.path.abspath(os.path.join(r, f))
239+
for r, d, fs in oswalk
240+
for f in fs if not f.startswith(() if showhidden else ".") and
241+
not f.endswith(omit) and f.endswith(target)]
249242

250243

251244
def main():
252245
"""Main Loop."""
253246
args = make_arguments_parser()
254-
log.disable(log.CRITICAL) if args.quiet else log.debug("Max Logging ON")
255-
check_folder(os.path.dirname(args.fullpath))
256-
atexit.register(beep) if args.beep else log.debug("Beep sound at exit OFF")
257247
if os.path.isfile(args.fullpath) and args.fullpath.endswith(".css"):
258-
log.info("Target is a CSS File.") # Work based on if argument is
248+
print("Target is a CSS File.") # Work based on if argument is
259249
list_of_files = str(args.fullpath) # file or folder, folder is slower.
260250
process_single_css_file(
261251
args.fullpath, wrap=args.wrap, timestamp=args.timestamp,
262252
comments=args.comments, sort=args.sort, overwrite=args.overwrite,
263253
zipy=args.zipy, prefix=args.prefix, add_hash=args.hash)
264254
elif os.path.isfile(args.fullpath) and args.fullpath.endswith(
265255
".html" if args.overwrite else ".htm"):
266-
log.info("Target is HTML File.")
256+
print("Target is HTML File.")
267257
list_of_files = str(args.fullpath)
268258
process_single_html_file(
269259
args.fullpath, comments=args.comments,
270260
overwrite=args.overwrite, prefix=args.prefix, add_hash=args.hash)
271261
elif os.path.isfile(args.fullpath) and args.fullpath.endswith(".js"):
272-
log.info("Target is a JS File.")
262+
print("Target is a JS File.")
273263
list_of_files = str(args.fullpath)
274264
process_single_js_file(
275265
args.fullpath, timestamp=args.timestamp,
276266
overwrite=args.overwrite, zipy=args.zipy)
277267
elif os.path.isdir(args.fullpath):
278-
log.info("Target is a Folder with CSS, HTML, JS files !.")
279-
log.warning("Processing a whole Folder may take some time...")
268+
print("Target is a Folder with CSS, HTML, JS files !.")
269+
print("Processing a whole Folder may take some time...")
280270
list_of_files = walk2list(
281271
args.fullpath,
282272
(".css", ".js", ".html" if args.overwrite else ".htm"),
283273
(".min.css", ".min.js", ".htm" if args.overwrite else ".html"))
284-
log.info('Total Maximum CPUs used: ~{0} Cores.'.format(cpu_count()))
274+
print(f'Total Maximum CPUs used: ~{cpu_count()} Cores.')
285275
pool = Pool(cpu_count()) # Multiprocessing Async
286276
pool.map_async(partial(
287277
process_multiple_files, watch=args.watch,
@@ -293,12 +283,10 @@ def main():
293283
pool.close()
294284
pool.join()
295285
else:
296-
log.critical("File or folder not found,or cant be read,or I/O Error.")
286+
print("File or folder not found,or cant be read,or I/O Error.")
297287
sys.exit(1)
298288
if args.after and getoutput:
299-
log.info(getoutput(str(args.after)))
300-
log.info('\n {0} \n Files Processed: {1}.'.format('-' * 80, list_of_files))
301-
log.info('Number of Files Processed: {0}.'.format(
302-
len(list_of_files) if isinstance(list_of_files, tuple) else 1))
303-
set_terminal_title()
304-
make_post_exec_msg(start_time)
289+
print(getoutput(str(args.after)))
290+
print(f'\n {"-" * 80} \n Files Processed: {list_of_files}.')
291+
print(f'''Number of Files Processed:
292+
{len(list_of_files) if isinstance(list_of_files, tuple) else 1}.''')

0 commit comments

Comments
 (0)