Created
November 6, 2020 11:13
-
-
Save yeyeto2788/0be7dad67baa0114ae3a85edce3a3c80 to your computer and use it in GitHub Desktop.
Minify python code 🐍
This file contains 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/python3 | |
import argparse | |
try: | |
from pyminifier import minification | |
from pyminifier import token_utils | |
except ImportError: | |
message = """ | |
Please install pyminifier by issuing: | |
pip install pyminifier | |
""" | |
print(message) | |
exit(1) | |
class PyminiferOptions: | |
""" | |
Abstract class to define the options used for the pyminifier module. | |
""" | |
def __init__(self): | |
"""Simple constructor method to define the properties for . | |
""" | |
# Use tabs instead of spaces | |
self.tabs = False | |
# Obfuscate all code | |
self.obfuscate = False | |
self.obf_classes = False | |
self.obf_functions = False | |
self.nominify = False | |
self.obf_variables = False | |
self.obf_builtins = False | |
self.obf_import_methods = False | |
self.replacement_length = 1 | |
self.use_nonlatin = False | |
def main(args): | |
# Open the file and read it's content. | |
source = open(args.file).read() | |
# Get tokens from file. | |
tokens = token_utils.listified_tokenizer(source) | |
# Minify the file content based on the tokens | |
minified = minification.minify(tokens, PyminiferOptions()) | |
# Recompute tokens from minified version. | |
tokens = token_utils.listified_tokenizer(minified) | |
# Final result on file minified. | |
result = token_utils.untokenize(tokens) | |
if args.output is not None: | |
with open(args.output, "w") as output_file: | |
output_file.write(result) | |
else: | |
print(result) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser() | |
parser.add_argument( | |
"-f", "--file", | |
type=str, | |
action='store', | |
help="File to be minified.", | |
required=True | |
) | |
parser.add_argument( | |
"-o", "--output", | |
type=str, | |
action='store', | |
help="Filename for output", | |
default=None | |
) | |
args = parser.parse_args() | |
main(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment