├── .gitignore
├── LICENSE
├── README.rst
├── docs
├── Makefile
├── html
└── source
│ ├── analyze.rst
│ ├── compression.rst
│ ├── conf.py
│ ├── index.rst
│ ├── minification.rst
│ ├── obfuscate.rst
│ ├── pyminifier.rst
│ └── token_utils.rst
├── pyminifier
├── __init__.py
├── __main__.py
├── analyze.py
├── compression.py
├── minification.py
├── obfuscate.py
└── token_utils.py
├── setup.cfg
├── setup.py
└── tests
├── __init__.py
└── test_minification.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 |
5 | # C extensions
6 | *.so
7 |
8 | # Distribution / packaging
9 | .Python
10 | env/
11 | bin/
12 | build/
13 | develop-eggs/
14 | dist/
15 | eggs/
16 | lib/
17 | lib64/
18 | parts/
19 | sdist/
20 | var/
21 | *.egg-info/
22 | .installed.cfg
23 | *.egg
24 |
25 | # Installer logs
26 | pip-log.txt
27 | pip-delete-this-directory.txt
28 |
29 | # Unit test / coverage reports
30 | htmlcov/
31 | .tox/
32 | .coverage
33 | .cache
34 | nosetests.xml
35 | coverage.xml
36 |
37 | # Translations
38 | *.mo
39 |
40 | # Mr Developer
41 | .mr.developer.cfg
42 | .project
43 | .pydevproject
44 |
45 | # Rope
46 | .ropeproject
47 |
48 | # Django stuff:
49 | *.log
50 | *.pot
51 |
52 | # Sphinx documentation
53 | docs/_build/
54 |
55 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | pyminifier
2 | ==========
3 |
4 | Pyminifier is a Python code minifier, obfuscator, and compressor.
5 |
6 | .. note::
7 |
8 | * For the latest, complete documentation: http://liftoff.github.io/pyminifier/
9 | * For the latest code: https://github.com/liftoff/pyminifier
10 |
11 | Overview
12 | --------
13 | When you install pyminifier it should automatically add a 'pyminifier'
14 | executable to your ``$PATH``. This executable has a number of command line
15 | arguments:
16 |
17 | .. code-block:: sh
18 |
19 | $ pyminifier --help
20 | Usage: pyminifier [options] ""
21 |
22 | Options:
23 | --version show program's version number and exit
24 | -h, --help show this help message and exit
25 | -o , --outfile=
26 | Save output to the given file.
27 | -d , --destdir=
28 | Save output to the given directory. This option is
29 | required when handling multiple files. Defaults to
30 | './minified' and will be created if not present.
31 | --nominify Don't bother minifying (only used with --pyz).
32 | --use-tabs Use tabs for indentation instead of spaces.
33 | --bzip2 bzip2-compress the result into a self-executing python
34 | script. Only works on stand-alone scripts without
35 | implicit imports.
36 | --gzip gzip-compress the result into a self-executing python
37 | script. Only works on stand-alone scripts without
38 | implicit imports.
39 | --lzma lzma-compress the result into a self-executing python
40 | script. Only works on stand-alone scripts without
41 | implicit imports.
42 | --pyz=.pyz
43 | zip-compress the result into a self-executing python
44 | script. This will create a new file that includes any
45 | necessary implicit (local to the script) modules.
46 | Will include/process all files given as arguments to
47 | pyminifier.py on the command line.
48 | -O, --obfuscate Obfuscate all function/method names, variables, and
49 | classes. Default is to NOT obfuscate.
50 | --obfuscate-classes Obfuscate class names.
51 | --obfuscate-functions
52 | Obfuscate function and method names.
53 | --obfuscate-variables
54 | Obfuscate variable names.
55 | --obfuscate-import-methods
56 | Obfuscate globally-imported mouled methods (e.g.
57 | 'Ag=re.compile').
58 | --obfuscate-builtins Obfuscate built-ins (i.e. True, False, object,
59 | Exception, etc).
60 | --replacement-length=1
61 | The length of the random names that will be used when
62 | obfuscating identifiers.
63 | --nonlatin Use non-latin (unicode) characters in obfuscation
64 | (Python 3 only). WARNING: This results in some
65 | SERIOUSLY hard-to-read code.
66 | --prepend=
67 | Prepend the text in this file to the top of our
68 | output. e.g. A copyright notice.
69 |
70 | For the examples below we'll be minifying, obfuscating, and compressing the
71 | following totally made-up Python script (saved to ``/tmp/tumult.py``)::
72 |
73 | #!/usr/bin/env python
74 | """
75 | tumult.py - Because everyone needs a little chaos every now and again.
76 | """
77 |
78 | try:
79 | import demiurgic
80 | except ImportError:
81 | print("Warning: You're not demiurgic. Actually, I think that's normal.")
82 | try:
83 | import mystificate
84 | except ImportError:
85 | print("Warning: Dark voodoo may be unreliable.")
86 |
87 | # Globals
88 | ATLAS = False # Nothing holds up the world by default
89 |
90 | class Foo(object):
91 | """
92 | The Foo class is an abstract flabbergaster that when instantiated
93 | represents a discrete dextrogyratory inversion of a cattywompus
94 | octothorp.
95 | """
96 | def __init__(self, *args, **kwargs):
97 | """
98 | The initialization vector whereby the ineffably obstreperous
99 | becomes paramount.
100 | """
101 | # TODO. BTW: What happens if we remove that docstring? :)
102 |
103 | def demiurgic_mystificator(self, dactyl):
104 | """
105 | A vainglorious implementation of bedizenment.
106 | """
107 | inception = demiurgic.palpitation(dactyl) # Note the imported call
108 | demarcation = mystificate.dark_voodoo(inception)
109 | return demarcation
110 |
111 | def test(self, whatever):
112 | """
113 | This test method tests the test by testing your patience.
114 | """
115 | print(whatever)
116 |
117 | if __name__ == "__main__":
118 | print("Forming...")
119 | f = Foo("epicaricacy", "perseverate")
120 | f.test("Codswallop")
121 |
122 | By default pyminifier will perform basic minification and print the resulting
123 | code to stdout:
124 |
125 | .. note:: The tumult.py script is 1358 bytes. Remember that.
126 |
127 | .. code-block:: sh
128 |
129 | $ pyminifier /tmp/tumult.py
130 | #!/usr/bin/env python
131 | try:
132 | import demiurgic
133 | except ImportError:
134 | print("Warning: You're not demiurgic. Actually, I think that's normal.")
135 | try:
136 | import mystificate
137 | except ImportError:
138 | print("Warning: Dark voodoo may be unreliable.")
139 | ATLAS=False
140 | class Foo(object):
141 | def __init__(self,*args,**kwargs):
142 | pass
143 | def demiurgic_mystificator(self,dactyl):
144 | inception=demiurgic.palpitation(dactyl)
145 | demarcation=mystificate.dark_voodoo(inception)
146 | return demarcation
147 | def test(self,whatever):
148 | print(whatever)
149 | if __name__=="__main__":
150 | print("Forming...")
151 | f=Foo("epicaricacy","perseverate")
152 | f.test("Codswallop")
153 | # Created by pyminifier.py
154 |
155 | This reduced the size of tumult.py from 1358 bytes to 640 bytes. Not bad!
156 |
157 | Minifying by itself can reduce code size considerably but pyminifier can go
158 | further by obfuscating the code. What that means is that it will replace the
159 | names of things like variables and functions to the smallest possible size.
160 |
161 | To see more examples of pyminifier in action (e.g. compression features) see the
162 | `full documentation `_
163 |
164 | Special Sauce
165 | -------------
166 | So let's pretend for a moment that your intentions are not pure; that you
167 | totally want to mess with the people that look at your minified code. What you
168 | need is Python 3 and the ``--nonlatin`` option...
169 |
170 | .. code-block:: sh
171 |
172 | #!/usr/bin/env python
173 | ﵛ=ImportError
174 | ࡅ=print
175 | 㮀=False
176 | 搓=object
177 | try:
178 | import demiurgic
179 | except ﵛ:
180 | ࡅ("Warning: You're not demiurgic. Actually, I think that's normal.")
181 | try:
182 | import mystificate
183 | except ﵛ:
184 | ࡅ("Warning: Dark voodoo may be unreliable.")
185 | ﵩ=㮀
186 | class רּ(搓):
187 | def __init__(self,*args,**kwargs):
188 | pass
189 | def 𐨱(self,dactyl):
190 | ﱲ=demiurgic.palpitation(dactyl)
191 | ꁁ=mystificate.dark_voodoo(ﱲ)
192 | return ꁁ
193 | def 𨠅(self,whatever):
194 | ࡅ(whatever)
195 | if __name__=="__main__":
196 | ࡅ("Forming...")
197 | 녂=רּ("epicaricacy","perseverate")
198 | 녂.𨠅("Codswallop")
199 | # Created by pyminifier.py (https://github.com/liftoff/pyminifier)
200 |
201 | Yes, that code actually works *but only using Python 3*. This is because Python
202 | 3 supports coding in languages that use non-latin character sets.
203 |
204 | .. note::
205 |
206 | Most text editors/IDEs will have a hard time with code generated using the
207 | ``--nonlatin`` option because it will be a random mix of left-to-right
208 | and right-to-left characters. Often the result is some code appearing on
209 | the left of the screen and some code appearing on the right. This makes it
210 | *really* hard to figure out things like indentation levels and whatnot!
211 |
212 | There's even more ways to mess with people in the
213 | `full documentation `_
214 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = build
9 |
10 | # User-friendly check for sphinx-build
11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/)
13 | endif
14 |
15 | # Internal variables.
16 | PAPEROPT_a4 = -D latex_paper_size=a4
17 | PAPEROPT_letter = -D latex_paper_size=letter
18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
19 | # the i18n builder cannot share the environment and doctrees with the others
20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
21 |
22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
23 |
24 | help:
25 | @echo "Please use \`make ' where is one of"
26 | @echo " html to make standalone HTML files"
27 | @echo " dirhtml to make HTML files named index.html in directories"
28 | @echo " singlehtml to make a single large HTML file"
29 | @echo " pickle to make pickle files"
30 | @echo " json to make JSON files"
31 | @echo " htmlhelp to make HTML files and a HTML help project"
32 | @echo " qthelp to make HTML files and a qthelp project"
33 | @echo " devhelp to make HTML files and a Devhelp project"
34 | @echo " epub to make an epub"
35 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
36 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
37 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
38 | @echo " text to make text files"
39 | @echo " man to make manual pages"
40 | @echo " texinfo to make Texinfo files"
41 | @echo " info to make Texinfo files and run them through makeinfo"
42 | @echo " gettext to make PO message catalogs"
43 | @echo " changes to make an overview of all changed/added/deprecated items"
44 | @echo " xml to make Docutils-native XML files"
45 | @echo " pseudoxml to make pseudoxml-XML files for display purposes"
46 | @echo " linkcheck to check all external links for integrity"
47 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
48 |
49 | clean:
50 | rm -rf $(BUILDDIR)/*
51 |
52 | html:
53 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
54 | @echo
55 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
56 |
57 | dirhtml:
58 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
59 | @echo
60 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
61 |
62 | singlehtml:
63 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
64 | @echo
65 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
66 |
67 | pickle:
68 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
69 | @echo
70 | @echo "Build finished; now you can process the pickle files."
71 |
72 | json:
73 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
74 | @echo
75 | @echo "Build finished; now you can process the JSON files."
76 |
77 | htmlhelp:
78 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
79 | @echo
80 | @echo "Build finished; now you can run HTML Help Workshop with the" \
81 | ".hhp project file in $(BUILDDIR)/htmlhelp."
82 |
83 | qthelp:
84 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
85 | @echo
86 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
87 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
88 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pyminifier.qhcp"
89 | @echo "To view the help file:"
90 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pyminifier.qhc"
91 |
92 | devhelp:
93 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
94 | @echo
95 | @echo "Build finished."
96 | @echo "To view the help file:"
97 | @echo "# mkdir -p $$HOME/.local/share/devhelp/pyminifier"
98 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pyminifier"
99 | @echo "# devhelp"
100 |
101 | epub:
102 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
103 | @echo
104 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
105 |
106 | latex:
107 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
108 | @echo
109 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
110 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
111 | "(use \`make latexpdf' here to do that automatically)."
112 |
113 | latexpdf:
114 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
115 | @echo "Running LaTeX files through pdflatex..."
116 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
117 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
118 |
119 | latexpdfja:
120 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
121 | @echo "Running LaTeX files through platex and dvipdfmx..."
122 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
123 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
124 |
125 | text:
126 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
127 | @echo
128 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
129 |
130 | man:
131 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
132 | @echo
133 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
134 |
135 | texinfo:
136 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
137 | @echo
138 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
139 | @echo "Run \`make' in that directory to run these through makeinfo" \
140 | "(use \`make info' here to do that automatically)."
141 |
142 | info:
143 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
144 | @echo "Running Texinfo files through makeinfo..."
145 | make -C $(BUILDDIR)/texinfo info
146 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
147 |
148 | gettext:
149 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
150 | @echo
151 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
152 |
153 | changes:
154 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
155 | @echo
156 | @echo "The overview file is in $(BUILDDIR)/changes."
157 |
158 | linkcheck:
159 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
160 | @echo
161 | @echo "Link check complete; look for any errors in the above output " \
162 | "or in $(BUILDDIR)/linkcheck/output.txt."
163 |
164 | doctest:
165 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
166 | @echo "Testing of doctests in the sources finished, look at the " \
167 | "results in $(BUILDDIR)/doctest/output.txt."
168 |
169 | xml:
170 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
171 | @echo
172 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml."
173 |
174 | pseudoxml:
175 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
176 | @echo
177 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
178 |
--------------------------------------------------------------------------------
/docs/html:
--------------------------------------------------------------------------------
1 | build/html
--------------------------------------------------------------------------------
/docs/source/analyze.rst:
--------------------------------------------------------------------------------
1 | :mod:`analyze.py` - For analyzing Python code
2 | =============================================
3 |
4 | .. moduleauthor:: Dan McDougall (daniel.mcdougall@liftoffsoftware.com)
5 |
6 | .. automodule:: pyminifier.analyze
7 | :members:
8 | :private-members:
9 |
--------------------------------------------------------------------------------
/docs/source/compression.rst:
--------------------------------------------------------------------------------
1 | :mod:`compression.py` - For compressing Python code
2 | ===================================================
3 |
4 | .. moduleauthor:: Dan McDougall (daniel.mcdougall@liftoffsoftware.com)
5 |
6 | .. automodule:: pyminifier.compression
7 | :members:
8 | :private-members:
9 |
--------------------------------------------------------------------------------
/docs/source/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # pyminifier documentation build configuration file, created by
4 | # sphinx-quickstart on Sat May 24 14:25:46 2014.
5 | #
6 | # This file is execfile()d with the current directory set to its
7 | # containing dir.
8 | #
9 | # Note that not all possible configuration values are present in this
10 | # autogenerated file.
11 | #
12 | # All configuration values have a default; values that are commented out
13 | # serve to show the default.
14 |
15 | import sys
16 | import os
17 |
18 | # If extensions (or modules to document with autodoc) are in another directory,
19 | # add these directories to sys.path here. If the directory is relative to the
20 | # documentation root, use os.path.abspath to make it absolute, like shown here.
21 | sys.path.insert(0, os.path.abspath('../../'))
22 | import pyminifier
23 |
24 | # -- General configuration ------------------------------------------------
25 |
26 | # If your documentation needs a minimal Sphinx version, state it here.
27 | #needs_sphinx = '1.0'
28 |
29 | # Add any Sphinx extension module names here, as strings. They can be
30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
31 | # ones.
32 | extensions = [
33 | 'sphinx.ext.autodoc',
34 | 'sphinx.ext.intersphinx',
35 | 'sphinx.ext.todo',
36 | 'sphinx.ext.viewcode',
37 | ]
38 |
39 | # Add any paths that contain templates here, relative to this directory.
40 | templates_path = ['_templates']
41 |
42 | # The suffix of source filenames.
43 | source_suffix = '.rst'
44 |
45 | # The encoding of source files.
46 | #source_encoding = 'utf-8-sig'
47 |
48 | # The master toctree document.
49 | master_doc = 'index'
50 |
51 | # General information about the project.
52 | project = u'pyminifier'
53 | copyright = u'2014, Dan McDougall'
54 |
55 | # The version info for the project you're documenting, acts as replacement for
56 | # |version| and |release|, also used in various other places throughout the
57 | # built documents.
58 | #
59 | # The short X.Y version.
60 | version = pyminifier.__version__
61 | # The full version, including alpha/beta/rc tags.
62 | release = version
63 |
64 | # The language for content autogenerated by Sphinx. Refer to documentation
65 | # for a list of supported languages.
66 | #language = None
67 |
68 | # There are two options for replacing |today|: either, you set today to some
69 | # non-false value, then it is used:
70 | #today = ''
71 | # Else, today_fmt is used as the format for a strftime call.
72 | #today_fmt = '%B %d, %Y'
73 |
74 | # List of patterns, relative to source directory, that match files and
75 | # directories to ignore when looking for source files.
76 | exclude_patterns = []
77 |
78 | # The reST default role (used for this markup: `text`) to use for all
79 | # documents.
80 | #default_role = None
81 |
82 | # If true, '()' will be appended to :func: etc. cross-reference text.
83 | #add_function_parentheses = True
84 |
85 | # If true, the current module name will be prepended to all description
86 | # unit titles (such as .. function::).
87 | #add_module_names = True
88 |
89 | # If true, sectionauthor and moduleauthor directives will be shown in the
90 | # output. They are ignored by default.
91 | #show_authors = False
92 |
93 | # The name of the Pygments (syntax highlighting) style to use.
94 | pygments_style = 'manni'
95 |
96 | # A list of ignored prefixes for module index sorting.
97 | #modindex_common_prefix = []
98 |
99 | # If true, keep warnings as "system message" paragraphs in the built documents.
100 | #keep_warnings = False
101 |
102 |
103 | # -- Options for HTML output ----------------------------------------------
104 |
105 | # The theme to use for HTML and HTML Help pages. See the documentation for
106 | # a list of builtin themes.
107 | import sphinx_rtd_theme
108 |
109 | html_theme = "sphinx_rtd_theme"
110 |
111 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
112 |
113 | # Theme options are theme-specific and customize the look and feel of a theme
114 | # further. For a list of options available for each theme, see the
115 | # documentation.
116 | #html_theme_options = {}
117 |
118 | # Add any paths that contain custom themes here, relative to this directory.
119 | #html_theme_path = []
120 |
121 | # The name for this set of Sphinx documents. If None, it defaults to
122 | # " v documentation".
123 | #html_title = None
124 |
125 | # A shorter title for the navigation bar. Default is the same as html_title.
126 | #html_short_title = None
127 |
128 | # The name of an image file (relative to this directory) to place at the top
129 | # of the sidebar.
130 | #html_logo = None
131 |
132 | # The name of an image file (within the static path) to use as favicon of the
133 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
134 | # pixels large.
135 | #html_favicon = None
136 |
137 | # Add any paths that contain custom static files (such as style sheets) here,
138 | # relative to this directory. They are copied after the builtin static files,
139 | # so a file named "default.css" will overwrite the builtin "default.css".
140 | html_static_path = ['_static']
141 |
142 | # Add any extra paths that contain custom files (such as robots.txt or
143 | # .htaccess) here, relative to this directory. These files are copied
144 | # directly to the root of the documentation.
145 | #html_extra_path = []
146 |
147 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
148 | # using the given strftime format.
149 | #html_last_updated_fmt = '%b %d, %Y'
150 |
151 | # If true, SmartyPants will be used to convert quotes and dashes to
152 | # typographically correct entities.
153 | #html_use_smartypants = True
154 |
155 | # Custom sidebar templates, maps document names to template names.
156 | #html_sidebars = {}
157 |
158 | # Additional templates that should be rendered to pages, maps page names to
159 | # template names.
160 | #html_additional_pages = {}
161 |
162 | # If false, no module index is generated.
163 | #html_domain_indices = True
164 |
165 | # If false, no index is generated.
166 | #html_use_index = True
167 |
168 | # If true, the index is split into individual pages for each letter.
169 | #html_split_index = False
170 |
171 | # If true, links to the reST sources are added to the pages.
172 | #html_show_sourcelink = True
173 |
174 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
175 | #html_show_sphinx = True
176 |
177 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
178 | #html_show_copyright = True
179 |
180 | # If true, an OpenSearch description file will be output, and all pages will
181 | # contain a tag referring to it. The value of this option must be the
182 | # base URL from which the finished HTML is served.
183 | #html_use_opensearch = ''
184 |
185 | # This is the file name suffix for HTML files (e.g. ".xhtml").
186 | #html_file_suffix = None
187 |
188 | # Output file base name for HTML help builder.
189 | htmlhelp_basename = 'pyminifierdoc'
190 |
191 |
192 | # -- Options for LaTeX output ---------------------------------------------
193 |
194 | latex_elements = {
195 | # The paper size ('letterpaper' or 'a4paper').
196 | #'papersize': 'letterpaper',
197 |
198 | # The font size ('10pt', '11pt' or '12pt').
199 | #'pointsize': '10pt',
200 |
201 | # Additional stuff for the LaTeX preamble.
202 | #'preamble': '',
203 | }
204 |
205 | # Grouping the document tree into LaTeX files. List of tuples
206 | # (source start file, target name, title,
207 | # author, documentclass [howto, manual, or own class]).
208 | latex_documents = [
209 | ('index', 'pyminifier.tex', u'pyminifier Documentation',
210 | u'Dan McDougall', 'manual'),
211 | ]
212 |
213 | # The name of an image file (relative to this directory) to place at the top of
214 | # the title page.
215 | #latex_logo = None
216 |
217 | # For "manual" documents, if this is true, then toplevel headings are parts,
218 | # not chapters.
219 | #latex_use_parts = False
220 |
221 | # If true, show page references after internal links.
222 | #latex_show_pagerefs = False
223 |
224 | # If true, show URL addresses after external links.
225 | #latex_show_urls = False
226 |
227 | # Documents to append as an appendix to all manuals.
228 | #latex_appendices = []
229 |
230 | # If false, no module index is generated.
231 | #latex_domain_indices = True
232 |
233 |
234 | # -- Options for manual page output ---------------------------------------
235 |
236 | # One entry per manual page. List of tuples
237 | # (source start file, name, description, authors, manual section).
238 | man_pages = [
239 | ('index', 'pyminifier', u'pyminifier Documentation',
240 | [u'Dan McDougall'], 1)
241 | ]
242 |
243 | # If true, show URL addresses after external links.
244 | #man_show_urls = False
245 |
246 |
247 | # -- Options for Texinfo output -------------------------------------------
248 |
249 | # Grouping the document tree into Texinfo files. List of tuples
250 | # (source start file, target name, title, author,
251 | # dir menu entry, description, category)
252 | texinfo_documents = [
253 | ('index', 'pyminifier', u'pyminifier Documentation',
254 | u'Dan McDougall', 'pyminifier', 'One line description of project.',
255 | 'Miscellaneous'),
256 | ]
257 |
258 | # Documents to append as an appendix to all manuals.
259 | #texinfo_appendices = []
260 |
261 | # If false, no module index is generated.
262 | #texinfo_domain_indices = True
263 |
264 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
265 | #texinfo_show_urls = 'footnote'
266 |
267 | # If true, do not generate a @detailmenu in the "Top" node's menu.
268 | #texinfo_no_detailmenu = False
269 |
270 |
271 | # Example configuration for intersphinx: refer to the Python standard library.
272 | intersphinx_mapping = {'http://docs.python.org/': None}
273 |
--------------------------------------------------------------------------------
/docs/source/index.rst:
--------------------------------------------------------------------------------
1 | .. pyminifier documentation master file, created by
2 | sphinx-quickstart on Sat May 24 14:25:46 2014.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | pyminifier - Minify, obfuscate, and compress Python code
7 | ========================================================
8 |
9 | .. moduleauthor:: Dan McDougall
10 |
11 | Modules
12 | -------
13 |
14 | .. toctree::
15 |
16 | pyminifier.rst
17 | analyze.rst
18 | compression.rst
19 | minification.rst
20 | obfuscate.rst
21 | token_utils.rst
22 |
23 | Overview
24 | --------
25 | When you install pyminifier it should automatically add a 'pyminifier'
26 | executable to your ``$PATH``. This executable has a number of command line
27 | arguments:
28 |
29 | .. code-block:: sh
30 |
31 | $ pyminifier --help
32 | Usage: pyminifier [options] ""
33 |
34 | Options:
35 | --version show program's version number and exit
36 | -h, --help show this help message and exit
37 | -o , --outfile=
38 | Save output to the given file.
39 | -d , --destdir=
40 | Save output to the given directory. This option is
41 | required when handling multiple files. Defaults to
42 | './minified' and will be created if not present.
43 | --nominify Don't bother minifying (only used with --pyz).
44 | --use-tabs Use tabs for indentation instead of spaces.
45 | --bzip2 bzip2-compress the result into a self-executing python
46 | script. Only works on stand-alone scripts without
47 | implicit imports.
48 | --gzip gzip-compress the result into a self-executing python
49 | script. Only works on stand-alone scripts without
50 | implicit imports.
51 | --lzma lzma-compress the result into a self-executing python
52 | script. Only works on stand-alone scripts without
53 | implicit imports.
54 | --pyz=.pyz
55 | zip-compress the result into a self-executing python
56 | script. This will create a new file that includes any
57 | necessary implicit (local to the script) modules.
58 | Will include/process all files given as arguments to
59 | pyminifier.py on the command line.
60 | -O, --obfuscate Obfuscate all function/method names, variables, and
61 | classes. Default is to NOT obfuscate.
62 | --obfuscate-classes Obfuscate class names.
63 | --obfuscate-functions
64 | Obfuscate function and method names.
65 | --obfuscate-variables
66 | Obfuscate variable names.
67 | --obfuscate-import-methods
68 | Obfuscate globally-imported mouled methods (e.g.
69 | 'Ag=re.compile').
70 | --obfuscate-builtins Obfuscate built-ins (i.e. True, False, object,
71 | Exception, etc).
72 | --replacement-length=1
73 | The length of the random names that will be used when
74 | obfuscating identifiers.
75 | --nonlatin Use non-latin (unicode) characters in obfuscation
76 | (Python 3 only). WARNING: This results in some
77 | SERIOUSLY hard-to-read code.
78 | --prepend=
79 | Prepend the text in this file to the top of our
80 | output. e.g. A copyright notice.
81 |
82 | For the examples below we'll be minifying, obfuscating, and compressing the
83 | following totally made-up Python script (saved to ``/tmp/tumult.py``)::
84 |
85 | #!/usr/bin/env python
86 | """
87 | tumult.py - Because everyone needs a little chaos every now and again.
88 | """
89 |
90 | try:
91 | import demiurgic
92 | except ImportError:
93 | print("Warning: You're not demiurgic. Actually, I think that's normal.")
94 | try:
95 | import mystificate
96 | except ImportError:
97 | print("Warning: Dark voodoo may be unreliable.")
98 |
99 | # Globals
100 | ATLAS = False # Nothing holds up the world by default
101 |
102 | class Foo(object):
103 | """
104 | The Foo class is an abstract flabbergaster that when instantiated
105 | represents a discrete dextrogyratory inversion of a cattywompus
106 | octothorp.
107 | """
108 | def __init__(self, *args, **kwargs):
109 | """
110 | The initialization vector whereby the ineffiably obstreperous
111 | becomes paramount.
112 | """
113 | # TODO. BTW: What happens if we remove that docstring? :)
114 |
115 | def demiurgic_mystificator(self, dactyl):
116 | """
117 | A vainglorious implementation of bedizenment.
118 | """
119 | inception = demiurgic.palpitation(dactyl) # Note the imported call
120 | demarcation = mystificate.dark_voodoo(inception)
121 | return demarcation
122 |
123 | def test(self, whatever):
124 | """
125 | This test method tests the test by testing your patience.
126 | """
127 | print(whatever)
128 |
129 | if __name__ == "__main__":
130 | print("Forming...")
131 | f = Foo("epicaricacy", "perseverate")
132 | f.test("Codswallop")
133 |
134 | By default pyminifier will perform basic minification and print the resulting
135 | code to stdout:
136 |
137 | .. note:: The tumult.py script is 1358 bytes. Remember that.
138 |
139 | .. code-block:: sh
140 |
141 | $ pyminifier /tmp/tumult.py
142 | #!/usr/bin/env python
143 | try:
144 | import demiurgic
145 | except ImportError:
146 | print("Warning: You're not demiurgic. Actually, I think that's normal.")
147 | try:
148 | import mystificate
149 | except ImportError:
150 | print("Warning: Dark voodoo may be unreliable.")
151 | ATLAS=False
152 | class Foo(object):
153 | def __init__(self,*args,**kwargs):
154 | pass
155 | def demiurgic_mystificator(self,dactyl):
156 | inception=demiurgic.palpitation(dactyl)
157 | demarcation=mystificate.dark_voodoo(inception)
158 | return demarcation
159 | def test(self,whatever):
160 | print(whatever)
161 | if __name__=="__main__":
162 | print("Forming...")
163 | f=Foo("epicaricacy","perseverate")
164 | f.test("Codswallop")
165 | # Created by pyminifier.py (https://github.com/liftoff/pyminifier)
166 |
167 | This reduced the size of tumult.py from 1358 bytes to 640 bytes. Not bad!
168 |
169 | Minifying by itself can reduce code size considerably but pyminifier can go
170 | further by obfuscating the code. What that means is that it will replace the
171 | names of things like variables and functions to the smallest possible size:
172 |
173 | .. code-block:: sh
174 |
175 | $ pyminifier --obfuscate /tmp/tumult.py
176 | #!/usr/bin/env python
177 | T=ImportError
178 | q=print
179 | m=False
180 | O=object
181 | try:
182 | import demiurgic
183 | except T:
184 | q("Warning: You're not demiurgic. Actually, I think that's normal.")
185 | try:
186 | import mystificate
187 | except T:
188 | q("Warning: Dark voodoo may be unreliable.")
189 | Q=m
190 | class U(O):
191 | def __init__(self,*args,**kwargs):
192 | pass
193 | def B(self,dactyl):
194 | G=demiurgic.palpitation(dactyl)
195 | w=mystificate.dark_voodoo(G)
196 | return w
197 | def k(self,whatever):
198 | q(whatever)
199 | if __name__=="__main__":
200 | q("Forming...")
201 | f=U("epicaricacy","perseverate")
202 | f.test("Codswallop")
203 | # Created by pyminifier.py (https://github.com/liftoff/pyminifier)
204 |
205 | That's all fine and good but pyminifier can go the extra mile and also
206 | *compress* your code using gzip, bz2, or even lzma using a special container:
207 |
208 | .. code-block:: sh
209 |
210 | $ pyminifier --obfuscate --gzip /tmp/tumult.py
211 | #!/usr/bin/env python3
212 | import zlib, base64
213 | exec(zlib.decompress(base64.b64decode('eJx1kcFOwzAMhu95ClMO66apu0/KAQEbE5eJC+IUpa27haVJ5Ljb+vakLYJx4JAoiT/7/+3c3626SKvSuBW6M4Sej96Jq9y1wRM/E3kSexnIOBZObrSNKI7Sl59YsWDq1wLMiEKNrenoYCqB1woDwzXF9nn2rskZd1jDh+9mhOD8DVvAQ8WdtrZfwg74aNwp7ZpnMXHUaltk878ybR/ZNKbSjP8JPWk6wdn72ntodQ8lQucIrdGlxaHgq3QgKqtjhCY/zlN6jQ0oZZxhpfKItlkuNB3icrE4XYbDwEBICRP6NjG1rri3YyzK356CtsGwZuNd/o0kYitvrBd18qgmj3kcwoTckYPtJPAyCVzSKPCMNErs85+rMINdp1tUSspMqVYbp1Q2DWKTJpcGURRDr9DIJs8wJFlKq+qzZRaQ4lAnVRuJgjFynj36Ol7SX/iQXr8ANfezCw==')))
214 | # Created by pyminifier.py (https://github.com/liftoff/pyminifier)
215 |
216 | That created a 572 byte file... Not much saved over basic minification
217 | which producted a 640 byte file. This is because the input file was so small
218 | to begin with. There's potential to save a lot more space with larger scripts.
219 | Why the heck would you ever want to use such a strange method of compressing
220 | Python code? Only one reason:
221 |
222 | * You can still import it from other Python code.
223 |
224 | That's an important thing to remember when I reveal **the penultimate form of
225 | compression**: The ``--pyz`` option.
226 |
227 | The ``--pyz`` method of compression uses the zip file container format specified
228 | in PEP 441 (http://legacy.python.org/dev/peps/pep-0441/). This format is
229 | basically a zip file that also happens to be an executable Python script.
230 | Here's an example of how to use it:
231 |
232 | .. code-block:: sh
233 |
234 | $ pyminifier --obfuscate --pyz=/tmp/tumult.pyz /tmp/tumult.py
235 | /tmp/tumult.py saved as compressed executable zip: tumult.pyz
236 | The following modules were automatically included (as automagic dependencies):
237 |
238 |
239 | Overall size reduction: 61.71% of original size
240 | $
241 |
242 | In this case the resulting file is 838 bytes... The opposite of space savings!
243 | This is of course due to the *original size* of our test script. The tumult.py
244 | code is simply too small for the .pyz container format to be effective.
245 |
246 | Another important aspect of the .pyz container format is the fact that it
247 | requires all local imports be included in the same container. For this reason
248 | pyminifier will automatically find locally-imported modules and include them in
249 | the container (more on this below).
250 |
251 | To properly demonstrate the effectiveness of each minification, obfuscation,
252 | and compression method we'll minify the pyminifier.py code itself. Here's the
253 | results:
254 |
255 | ================ ========= ===========
256 | Method File Size % Reduction
257 | ================ ========= ===========
258 | pyminifier.py 17987 0%
259 | minification 8403 53.28%
260 | plus obfuscation 6699 62.76%
261 | with gzip 3480 80.65%
262 | with bz2 3782 78.97%
263 | with lzma 3572 80.14%
264 | ================ ========= ===========
265 |
266 | .. note::
267 |
268 | The sizes of these files may change over time. The sizes used here were
269 | taken at the time this documentation was written.
270 |
271 | For the .pyz comparison we'll need to add up the total sum of pyminifier.py
272 | plus all it's sister modules (since it imports them all at some point):
273 |
274 | =============== =====
275 | File Bytes
276 | =============== =====
277 | analyze.py 12259
278 | compression.py 11293
279 | minification.py 18639
280 | obfuscate.py 26474
281 | pyminifier.py 17987
282 | token_utils.py 1175
283 | =============== =====
284 |
285 | The total sum of all files is 87827 bytes. In order to properly compare the
286 | various output options we'll need to perform the same test we performed above
287 | but for all those files. To do things like this pyminifier includes the
288 | ``--destdir`` option. It will save all minified/obfuscated/compressed files
289 | to the given directory if you provide more than one (e.g. ``*.py``). Let's do
290 | that:
291 |
292 | Pyminifier can also work on a whole directory of Python scripts:
293 |
294 | .. code-block:: sh
295 |
296 | $ pyminifier --destdir=/tmp/minified_pyminifier pyminifier/*.py
297 | pyminifier/analyze.py (12259) reduced to 7009 bytes (57.17% of original size)
298 | pyminifier/compression.py (11293) reduced to 4880 bytes (43.21% of original size)
299 | pyminifier/__init__.py (284) reduced to 193 bytes (67.96% of original size)
300 | pyminifier/minification.py (18639) reduced to 8586 bytes (46.06% of original size)
301 | pyminifier/obfuscate.py (26474) reduced to 13582 bytes (51.3% of original size)
302 | pyminifier/pyminifier.py (17987) reduced to 8439 bytes (46.92% of original size)
303 | pyminifier/token_utils.py (1175) reduced to 604 bytes (51.4% of original size)
304 | Overall size reduction: 49.13% of original size
305 | $ du -hs /tmp/minified_pyminifier/
306 | 64K /tmp/minified_pyminifier/
307 |
308 | Not bad! Not bad at all--for defaults!
309 |
310 | Let's see what we get using some other compression options:
311 |
312 | **GZIP**
313 |
314 | .. code-block:: sh
315 |
316 | $ rm -rf /tmp/minified_pyminifier # Clean up after ourselves first
317 | $ pyminifier --destdir=/tmp/minified_pyminifier --gzip pyminifier/*.py
318 | pyminifier/analyze.py (12259) reduced to 2773 bytes (22.62% of original size)
319 | pyminifier/compression.py (11293) reduced to 2165 bytes (19.17% of original size)
320 | pyminifier/__init__.py (284) reduced to 289 bytes (101.76% of original size)
321 | pyminifier/minification.py (18639) reduced to 2829 bytes (15.18% of original size)
322 | pyminifier/obfuscate.py (26474) reduced to 3924 bytes (14.82% of original size)
323 | pyminifier/pyminifier.py (17987) reduced to 3652 bytes (20.3% of original size)
324 | pyminifier/token_utils.py (1175) reduced to 497 bytes (42.3% of original size)
325 | Overall size reduction: 18.31% of original size
326 |
327 | **BZIP2**
328 |
329 | .. code-block:: sh
330 |
331 | $ rm -rf /tmp/minified_pyminifier # Clean up after ourselves first
332 | $ pyminifier --destdir=/tmp/minified_pyminifier --bzip2 pyminifier/*.py
333 | pyminifier/analyze.py (12259) reduced to 2951 bytes (24.07% of original size)
334 | pyminifier/compression.py (11293) reduced to 2435 bytes (21.56% of original size)
335 | pyminifier/__init__.py (284) reduced to 327 bytes (115.14% of original size)
336 | pyminifier/minification.py (18639) reduced to 2995 bytes (16.07% of original size)
337 | pyminifier/obfuscate.py (26474) reduced to 3986 bytes (15.06% of original size)
338 | pyminifier/pyminifier.py (17987) reduced to 3926 bytes (21.83% of original size)
339 | pyminifier/token_utils.py (1175) reduced to 555 bytes (47.23% of original size)
340 | Overall size reduction: 19.49% of original size
341 |
342 | .. note::
343 |
344 | To self: Wow, bzip2 kinda sucks in comparsion. Why do we need it again?
345 |
346 | **LZMA**
347 |
348 | .. code-block:: sh
349 |
350 | $ rm -rf /tmp/minified_pyminifier # Clean up after ourselves first
351 | $ pyminifier --destdir=/tmp/minified_pyminifier --lzma pyminifier/*.py
352 | pyminifier/analyze.py (12259) reduced to 2801 bytes (22.85% of original size)
353 | pyminifier/compression.py (11293) reduced to 2273 bytes (20.13% of original size)
354 | pyminifier/__init__.py (284) reduced to 361 bytes (127.11% of original size)
355 | pyminifier/minification.py (18639) reduced to 2881 bytes (15.46% of original size)
356 | pyminifier/obfuscate.py (26474) reduced to 3904 bytes (14.75% of original size)
357 | pyminifier/pyminifier.py (17987) reduced to 3720 bytes (20.68% of original size)
358 | pyminifier/token_utils.py (1175) reduced to 601 bytes (51.15% of original size)
359 | Overall size reduction: 18.77% of original size
360 |
361 | Now let's try that .pyz container format. It can't be that much better, right?
362 | WRONG:
363 |
364 | .. code-block:: sh
365 |
366 | $ pyminifier --pyz=/tmp/pyminifier.pyz pyminifier.py
367 | pyminifier.py saved as compressed executable zip: /tmp/pyminifier.pyz
368 | The following modules were automatically included (as automagic dependencies):
369 |
370 | obfuscate.py
371 | minification.py
372 | token_utils.py
373 | compression.py
374 | analyze.py
375 |
376 | Overall size reduction: 16.64% of original size
377 | $ # NOTE: Resulting file is 14617 bytes
378 |
379 | Now that's some space-savings! But does it actually work? Let's test out that
380 | pyminifier.pyz by re-minifying tumult.py...
381 |
382 | .. note:: Remember, the more code there is the more space will be saved.
383 |
384 | .. code-block:: sh
385 |
386 | $ /tmp/pyminifier.pyz /tmp/tumult.py
387 | #!/usr/bin/env python
388 | try:
389 | import demiurgic
390 | except ImportError:
391 | print("Warning: You're not demiurgic. Actually, I think that's normal.")
392 | try:
393 | import mystificate
394 | except ImportError:
395 | print("Warning: Dark voodoo may be unreliable.")
396 | ATLAS=False
397 | class Foo(object):
398 | def __init__(self,*args,**kwargs):
399 | pass
400 | def demiurgic_mystificator(self,dactyl):
401 | inception=demiurgic.palpitation(dactyl)
402 | demarcation=mystificate.dark_voodoo(inception)
403 | return demarcation
404 | def test(self,whatever):
405 | print(whatever)
406 | if __name__=="__main__":
407 | print("Forming...")
408 | f=Foo("epicaricacy","perseverate")
409 | f.test("Codswallop")
410 | # Created by pyminifier.py (https://github.com/liftoff/pyminifier)
411 |
412 | It works!
413 |
414 | Special Sauce
415 | -------------
416 | So let's pretend for a moment that your intentions are not pure; that you
417 | totally want to mess with the people that look at your minified code. What you
418 | need is Python 3 and the ``--nonlatin`` option...
419 |
420 | .. code-block:: sh
421 |
422 | #!/usr/bin/env python3
423 | ﵛ=ImportError
424 | ࡅ=print
425 | 㮀=False
426 | 搓=object
427 | try:
428 | import demiurgic
429 | except ﵛ:
430 | ࡅ("Warning: You're not demiurgic. Actually, I think that's normal.")
431 | try:
432 | import mystificate
433 | except ﵛ:
434 | ࡅ("Warning: Dark voodoo may be unreliable.")
435 | ﵩ=㮀
436 | class רּ(搓):
437 | def __init__(self,*args,**kwargs):
438 | pass
439 | def 𐨱(self,dactyl):
440 | ﱲ=demiurgic.palpitation(dactyl)
441 | ꁁ=mystificate.dark_voodoo(ﱲ)
442 | return ꁁ
443 | def 𨠅(self,whatever):
444 | ࡅ(whatever)
445 | if __name__=="__main__":
446 | ࡅ("Forming...")
447 | 녂=רּ("epicaricacy","perseverate")
448 | 녂.𨠅("Codswallop")
449 | # Created by pyminifier.py (https://github.com/liftoff/pyminifier)
450 |
451 | Yes, that code actually works *but only using Python 3*. This is because Python
452 | 3 supports coding in languages that use non-latin character sets.
453 |
454 | .. note::
455 |
456 | Most text editors/IDEs will have a hard time with code generated using the
457 | ``--nonlatin`` option because it will be a random mix of left-to-right
458 | and right-to-left characters. Often the result is some code appearing on
459 | the left of the screen and some code appearing on the right. This makes it
460 | *really* hard to figure out things like indentation levels and whatnot!
461 |
462 | Let's have some more fun by using the ``--replacement-length`` option. It tells
463 | pyminifier to use name replacements of the given size. So instead of trying to
464 | minimize the amount of characters used for replacements let's make them HUGE:
465 |
466 | .. code-block:: sh
467 |
468 | $ pyminifier --nonlatin --replacement-length=50 /tmp/tumult.py
469 | #!/usr/bin/env python3
470 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲמּ=ImportError
471 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ燱=print
472 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ巡=False
473 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ澨=object
474 | try:
475 | import demiurgic
476 | except ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲמּ:
477 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ燱("Warning: You're not demiurgic. Actually, I think that's normal.")
478 | try:
479 | import mystificate
480 | except ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲמּ:
481 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ燱("Warning: Dark voodoo may be unreliable.")
482 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲﺬ=ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ巡
483 | class ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𐦚(ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ澨):
484 | def __init__(self,*args,**kwargs):
485 | pass
486 | def ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ클(self,dactyl):
487 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ퐐=demiurgic.palpitation(dactyl)
488 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𠛲=mystificate.dark_voodoo(ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ퐐)
489 | return ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𠛲
490 | def ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𐠯(self,whatever):
491 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ燱(whatever)
492 | if __name__=="__main__":
493 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ燱("Forming...")
494 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲﺃ=ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𐦚("epicaricacy","perseverate")
495 | ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲﺃ.ﺭ异𞸐𐤔ﭞﰣﺁں𝕌𨿩𞸇뻛𐬑𥰫嬭ﱌ𢽁𐡆𧪮Ꝫﴹ뙫𢤴퉊ﳦﲣפּܟﺶ𐐤ﶨࠔ𐰷𢡶𧐎𐭈𞸏𢢘𦘼ﶻ𩏃𦽨𞺎𠛘𐠲䉊ﰸﭳᣲ𐠯("Codswallop")
496 | # Created by pyminifier (https://github.com/liftoff/pyminifier)
497 |
498 | Indices and tables
499 | ==================
500 |
501 | * :ref:`genindex`
502 | * :ref:`modindex`
503 | * :ref:`search`
504 |
505 |
--------------------------------------------------------------------------------
/docs/source/minification.rst:
--------------------------------------------------------------------------------
1 | :mod:`minification.py` - For minifying Python code
2 | ===================================================
3 |
4 | .. moduleauthor:: Dan McDougall (daniel.mcdougall@liftoffsoftware.com)
5 |
6 | .. automodule:: pyminifier.minification
7 | :members:
8 | :private-members:
9 |
--------------------------------------------------------------------------------
/docs/source/obfuscate.rst:
--------------------------------------------------------------------------------
1 | :mod:`obfuscate.py` - For obfuscating Python code
2 | =================================================
3 |
4 | .. moduleauthor:: Dan McDougall (daniel.mcdougall@liftoffsoftware.com)
5 |
6 | .. automodule:: pyminifier.obfuscate
7 | :members:
8 | :private-members:
9 |
--------------------------------------------------------------------------------
/docs/source/pyminifier.rst:
--------------------------------------------------------------------------------
1 | :mod:`pyminifier.py` - The main module for minifying, obfuscating, and compressing Python code
2 | ==============================================================================================
3 |
4 | .. moduleauthor:: Dan McDougall (daniel.mcdougall@liftoffsoftware.com)
5 |
6 | .. automodule:: pyminifier
7 | :members:
8 | :private-members:
9 |
--------------------------------------------------------------------------------
/docs/source/token_utils.rst:
--------------------------------------------------------------------------------
1 | :mod:`token_utils.py` - A collection of token-related functions
2 | ===============================================================
3 |
4 | .. moduleauthor:: Dan McDougall (daniel.mcdougall@liftoffsoftware.com)
5 |
6 | .. automodule:: pyminifier.token_utils
7 | :members:
8 | :private-members:
9 |
--------------------------------------------------------------------------------
/pyminifier/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Copyright 2013 Liftoff Software Corporation
4 | #
5 | # For license information see LICENSE.txt
6 |
7 | # Meta
8 | __version__ = '2.2'
9 | __version_info__ = (2, 2)
10 | __license__ = "GPLv3" # See LICENSE.txt
11 | __author__ = 'Dan McDougall '
12 |
13 | # TODO: Add the ability to mark variables, functions, classes, and methods for non-obfuscation.
14 | # TODO: Add the ability to selectively obfuscate identifiers inside strings (for metaprogramming stuff).
15 | # TODO: Add the ability to use a config file instead of just command line args.
16 | # TODO: Add the ability to save a file that allows for de-obfuscation later (or at least the ability to debug).
17 | # TODO: Separate out the individual functions of minification so that they can be chosen selectively like the obfuscation functions.
18 |
19 | __doc__ = """\
20 | **Python Minifier:** Reduces the size of (minifies) Python code for use on
21 | embedded platforms.
22 |
23 | Performs the following:
24 |
25 | * Removes docstrings.
26 | * Removes comments.
27 | * Minimizes code indentation.
28 | * Removes trailing commas.
29 | * Joins multiline pairs of parentheses, braces, and brackets (and removes extraneous whitespace within).
30 | * Joins disjointed strings like, ``("some" "disjointed" "string")`` into single strings: ``('''some disjointed string''')
31 | * Preserves shebangs and encoding info (e.g. "# -- coding: utf-8 --").
32 | * Optionally, produces a bzip2 or gzip-compressed self-extracting python script containing the minified source for ultimate minification. *Added in version 1.4*
33 | * Optionally, obfuscates the code using the shortest possible combination of letters and numbers for one or all of class names, function/method names, and variables. The options are ``--obfuscate`` or ``-O`` to obfuscate everything, ``--obfuscate-variables``, ``--obfuscate-functions``, and ``--obfuscate-classes`` to obfuscate things individually (say, if you wanted to keep your module usable by external programs). *Added in version 2.0*
34 | * Optionally, a value may be specified via --replacement-length to set the minimum length of random strings that are used to replace identifier names when obfuscating.
35 | * Optionally, if using Python 3, you may specify ``--nonlatin`` to use funky unicode characters when obfuscating. WARNING: This will result in some seriously hard-to-read code! **Tip:** Combine this setting with higher ``--replacement-length`` values to make the output even wackier. *Added in version 2.0*
36 | * Pyminifier can now minify/obfuscate an arbitrary number of Python scripts in one go. For example, ``pyminifier -O *.py`` will minify and obfuscate all files in the current directory ending in .py. To prevent issues with using differentiated obfuscated identifiers across multiple files, pyminifier will keep track of what replaces what via a lookup table to ensure foo_module.whatever is gets the same replacement across all source files. *Added in version 2.0*
37 | * Optionally, creates an executable zip archive (pyz) containing the minified/obfuscated source script and all implicit (local path) imported modules. This mechanism automatically figures out which source files to include in the .pyz archive by analyzing the script passed to pyminifier on the command line (listing all the modules your script uses is unnecessary). This is also the **ultimate** in minification/compression besting both the gzip and bzip2 compression mechanisms with the disadvantage that .pyz files cannot be imported into other Python scripts. *Added in version 2.0*
38 |
39 | Just how much space can be saved by pyminifier? Here's a comparison:
40 |
41 | * The pyminifier source (all six files) takes up about 164k.
42 | * Performing basic minification on all pyminifier source files reduces that to ~104k.
43 | * Minification plus obfuscation provides a further reduction to 92k.
44 | * Minification plus the base64-encoded gzip trick (--gzip) reduces it to 76k.
45 | * Minification plus gzip compression plus obfuscation is also 76k (demonstrating that obfuscation makes no difference when compression algorthms are used).
46 | * Using the --pyz option on pyminifier.py creates a ~14k .pyz file that includes all the aforementioned files.
47 |
48 | Various examples and edge cases are sprinkled throughout the pyminifier code so
49 | that it can be tested by minifying itself. The way to test is thus:
50 |
51 | .. code-block:: bash
52 |
53 | $ python __main__.py __main__.py > minified_pyminifier.py
54 | $ python minified_pyminifier.py __main__.py > this_should_be_identical.py
55 | $ diff minified_pyminifier.py this_should_be_identical.py
56 | $
57 |
58 | If you get an error executing minified_pyminifier.py or
59 | ``this_should_be_identical.py`` isn't identical to minified_pyminifier.py then
60 | something is broken.
61 |
62 | .. note::
63 |
64 | The test functions below are meaningless. They only serve as test/edge
65 | cases for testing pyminifier.
66 | """
67 |
68 | # Import built-in modules
69 | import os, sys, re, io
70 | from optparse import OptionParser
71 | from collections import Iterable
72 |
73 | # Import our own modules
74 | from . import minification
75 | from . import token_utils
76 | from . import obfuscate
77 | from . import compression
78 |
79 | py3 = False
80 | lzma = False
81 | if not isinstance(sys.version_info, tuple):
82 | if sys.version_info.major == 3:
83 | py3 = True
84 | try:
85 | import lzma
86 | except ImportError:
87 | pass
88 |
89 | # Regexes
90 | multiline_indicator = re.compile('\\\\(\s*#.*)?\n')
91 |
92 | # The test.+() functions below are for testing pyminifier...
93 | def test_decorator(f):
94 | """Decorator that does nothing"""
95 | return f
96 |
97 | def test_reduce_operators():
98 | """Test the case where an operator such as an open paren starts a line"""
99 | (a, b) = 1, 2 # The indentation level should be preserved
100 | pass
101 |
102 | def test_empty_functions():
103 | """
104 | This is a test function.
105 | This should be replaced with 'def test_empty_functions(): pass'
106 | """
107 |
108 | class test_class(object):
109 | "Testing indented decorators"
110 |
111 | @test_decorator
112 | def test_function(self):
113 | pass
114 |
115 | def test_function():
116 | """
117 | This function encapsulates the edge cases to prevent them from invading the
118 | global namespace.
119 | """
120 | # This tests method obfuscation:
121 | method_obfuscate = test_class()
122 | method_obfuscate.test_function()
123 | foo = ("The # character in this string should " # This comment
124 | "not result in a syntax error") # ...and this one should go away
125 | test_multi_line_list = [
126 | 'item1',
127 | 'item2',
128 | 'item3'
129 | ]
130 | test_multi_line_dict = {
131 | 'item1': 1,
132 | 'item2': 2,
133 | 'item3': 3
134 | }
135 | # It may seem strange but the code below tests our docstring removal code.
136 | test_string_inside_operators = imaginary_function(
137 | "This string was indented but the tokenizer won't see it that way."
138 | ) # To understand how this could mess up docstring removal code see the
139 | # minification.minification.remove_comments_and_docstrings() function
140 | # starting at this line:
141 | # "elif token_type == tokenize.STRING:"
142 | # This tests remove_extraneous_spaces():
143 | this_line_has_leading_indentation = '''<--That extraneous space should be
144 | removed''' # But not these spaces
145 |
146 | def is_iterable(obj):
147 | """
148 | Returns `True` if *obj* is iterable but *not* if *obj* is a string, bytes,
149 | or a bytearray.
150 | """
151 | if isinstance(obj, (str, bytes, bytearray)):
152 | return False
153 | return isinstance(obj, Iterable)
154 |
155 | def pyminify(options, files):
156 | """
157 | Given an *options* object (from `optparse.OptionParser` or similar),
158 | performs minification and/or obfuscation on the given *files* (any iterable
159 | containing file paths) based on said *options*.
160 |
161 | All accepted options can be listed by running ``python __main__.py -h`` or
162 | examining the :py:func:`__init__.main` function.
163 | """
164 | global name_generator
165 | if not is_iterable(files):
166 | print(
167 | "Error: The 'files' argument must be a list, tuple, etc of files. "
168 | "Strings and bytes won't work.")
169 | sys.exit(1)
170 | if options.pyz:
171 | # Check to make sure we were only passed one script (only one at a time)
172 | if len(files) > 1:
173 | print("ERROR: The --pyz option only works with one python file at "
174 | "a time.")
175 | print("(Dependencies will be automagically included in the "
176 | "resulting .pyz)")
177 | sys.exit(1)
178 | # Make our .pyz:
179 | compression.zip_pack(files, options)
180 | return None # Make sure we don't do anything else
181 | # Read in our prepend text (if any)
182 | prepend = None
183 | if options.prepend:
184 | try:
185 | prepend = open(options.prepend).read()
186 | except Exception as err:
187 | print("Error reading %s:" % options.prepend)
188 | print(err)
189 |
190 | obfuscations = (options.obfuscate, options.obf_classes,
191 | options.obf_functions, options.obf_variables,
192 | options.obf_builtins, options.obf_import_methods)
193 |
194 | # Automatically enable obfuscation if --nonlatin (implied if no explicit
195 | # obfuscation is stated)
196 | if options.use_nonlatin and not any(obfuscations):
197 | options.obfuscate = True
198 | if len(files) > 1: # We're dealing with more than one file
199 | name_generator = None # So we can tell if we need to obfuscate
200 | if any(obfuscations):
201 | # Put together that will be used for all obfuscation functions:
202 | identifier_length = int(options.replacement_length)
203 | if options.use_nonlatin:
204 | if sys.version_info[0] == 3:
205 | name_generator = obfuscate.obfuscation_machine(
206 | use_unicode=True, identifier_length=identifier_length
207 | )
208 | else:
209 | print(
210 | "ERROR: You can't use nonlatin characters without Python 3")
211 | sys.exit(2)
212 | else:
213 | name_generator = obfuscate.obfuscation_machine(
214 | identifier_length=identifier_length)
215 | table =[{}]
216 | cumulative_size = 0 # For size reduction stats
217 | cumulative_new = 0 # Ditto
218 | for sourcefile in files:
219 | # Record how big the file is so we can compare afterwards
220 | filesize = os.path.getsize(sourcefile)
221 | cumulative_size += filesize
222 | # Get the module name from the path
223 | module = os.path.split(sourcefile)[1]
224 | module = ".".join(module.split('.')[:-1])
225 | source = open(sourcefile).read()
226 | tokens = token_utils.listified_tokenizer(source)
227 | if not options.nominify: # Perform minification
228 | source = minification.minify(tokens, options)
229 | # Have to re-tokenize for obfucation (it is quick):
230 | tokens = token_utils.listified_tokenizer(source)
231 | # Perform obfuscation if any of the related options were set
232 | if name_generator:
233 | obfuscate.obfuscate(
234 | module,
235 | tokens,
236 | options,
237 | name_generator=name_generator,
238 | table=table
239 | )
240 | # Convert back to text
241 | result = ''
242 | if prepend:
243 | result += prepend
244 | result += token_utils.untokenize(tokens)
245 | # Compress it if we were asked to do so
246 | if options.bzip2:
247 | result = compression.bz2_pack(result)
248 | elif options.gzip:
249 | result = compression.gz_pack(result)
250 | elif lzma and options.lzma:
251 | result = compression.lzma_pack(result)
252 | result += (
253 | "# Created by pyminifier "
254 | "(https://github.com/liftoff/pyminifier)\n")
255 | # Either save the result to the output file or print it to stdout
256 | if not os.path.exists(options.destdir):
257 | os.mkdir(options.destdir)
258 | # Need the path where the script lives for the next steps:
259 | filepath = os.path.split(sourcefile)[1]
260 | path = options.destdir + '/' + filepath # Put everything in destdir
261 | f = open(path, 'w')
262 | f.write(result)
263 | f.close()
264 | new_filesize = os.path.getsize(path)
265 | cumulative_new += new_filesize
266 | percent_saved = round((float(new_filesize) / float(filesize)) * 100, 2) if float(filesize)!=0 else 0
267 | print((
268 | "{sourcefile} ({filesize}) reduced to {new_filesize} bytes "
269 | "({percent_saved}% of original size)").format(**locals()))
270 | p_saved = round(
271 | (float(cumulative_new) / float(cumulative_size) * 100), 2)
272 | print("Overall size reduction: {0}% of original size".format(p_saved))
273 | else:
274 | # Get the module name from the path
275 | _file = files[0]
276 | module = os.path.split(_file)[1]
277 | module = ".".join(module.split('.')[:-1])
278 | filesize = os.path.getsize(_file)
279 | source = open(_file).read()
280 | # Convert the tokens from a tuple of tuples to a list of lists so we can
281 | # update in-place.
282 | tokens = token_utils.listified_tokenizer(source)
283 | if not options.nominify: # Perform minification
284 | source = minification.minify(tokens, options)
285 | # Convert back to tokens in case we're obfuscating
286 | tokens = token_utils.listified_tokenizer(source)
287 | # Perform obfuscation if any of the related options were set
288 | if options.obfuscate or options.obf_classes or options.obf_functions \
289 | or options.obf_variables or options.obf_builtins \
290 | or options.obf_import_methods:
291 | identifier_length = int(options.replacement_length)
292 | name_generator = obfuscate.obfuscation_machine(
293 | identifier_length=identifier_length)
294 | obfuscate.obfuscate(module, tokens, options)
295 | # Convert back to text
296 | result = ''
297 | if prepend:
298 | result += prepend
299 | result += token_utils.untokenize(tokens)
300 | # Compress it if we were asked to do so
301 | if options.bzip2:
302 | result = compression.bz2_pack(result)
303 | elif options.gzip:
304 | result = compression.gz_pack(result)
305 | elif lzma and options.lzma:
306 | result = compression.lzma_pack(result)
307 | result += (
308 | "# Created by pyminifier "
309 | "(https://github.com/liftoff/pyminifier)\n")
310 | # Either save the result to the output file or print it to stdout
311 | if options.outfile:
312 | f = io.open(options.outfile, 'w', encoding='utf-8')
313 | f.write(result)
314 | f.close()
315 | new_filesize = os.path.getsize(options.outfile)
316 | percent_saved = round(float(new_filesize)/float(filesize) * 100, 2)
317 | print((
318 | "{_file} ({filesize}) reduced to {new_filesize} bytes "
319 | "({percent_saved}% of original size)".format(**locals())))
320 | else:
321 | print(result)
322 |
--------------------------------------------------------------------------------
/pyminifier/__main__.py:
--------------------------------------------------------------------------------
1 | from optparse import OptionParser
2 | import sys
3 |
4 | from . import pyminify
5 | from . import __version__
6 |
7 | py3 = False
8 | lzma = False
9 | if not isinstance(sys.version_info, tuple):
10 | if sys.version_info.major == 3:
11 | py3 = True
12 | try:
13 | import lzma
14 | except ImportError:
15 | pass
16 |
17 | def main():
18 | """
19 | Sets up our command line options, prints the usage/help (if warranted), and
20 | runs :py:func:`pyminifier.pyminify` with the given command line options.
21 | """
22 | usage = '%prog [options] ""'
23 | if '__main__.py' in sys.argv[0]: # python -m pyminifier
24 | usage = 'pyminifier [options] ""'
25 | parser = OptionParser(usage=usage, version=__version__)
26 | parser.disable_interspersed_args()
27 | parser.add_option(
28 | "-o", "--outfile",
29 | dest="outfile",
30 | default=None,
31 | help="Save output to the given file.",
32 | metavar=""
33 | )
34 | parser.add_option(
35 | "-d", "--destdir",
36 | dest="destdir",
37 | default="./minified",
38 | help=("Save output to the given directory. "
39 | "This option is required when handling multiple files. "
40 | "Defaults to './minified' and will be created if not present. "),
41 | metavar=""
42 | )
43 | parser.add_option(
44 | "--nominify",
45 | action="store_true",
46 | dest="nominify",
47 | default=False,
48 | help="Don't bother minifying (only used with --pyz).",
49 | )
50 | parser.add_option(
51 | "--use-tabs",
52 | action="store_true",
53 | dest="tabs",
54 | default=False,
55 | help="Use tabs for indentation instead of spaces.",
56 | )
57 | parser.add_option(
58 | "--bzip2",
59 | action="store_true",
60 | dest="bzip2",
61 | default=False,
62 | help=("bzip2-compress the result into a self-executing python script. "
63 | "Only works on stand-alone scripts without implicit imports.")
64 | )
65 | parser.add_option(
66 | "--gzip",
67 | action="store_true",
68 | dest="gzip",
69 | default=False,
70 | help=("gzip-compress the result into a self-executing python script. "
71 | "Only works on stand-alone scripts without implicit imports.")
72 | )
73 | if lzma:
74 | parser.add_option(
75 | "--lzma",
76 | action="store_true",
77 | dest="lzma",
78 | default=False,
79 | help=("lzma-compress the result into a self-executing python script. "
80 | "Only works on stand-alone scripts without implicit imports.")
81 | )
82 | parser.add_option(
83 | "--pyz",
84 | dest="pyz",
85 | default=None,
86 | help=("zip-compress the result into a self-executing python script. "
87 | "This will create a new file that includes any necessary implicit"
88 | " (local to the script) modules. Will include/process all files "
89 | "given as arguments to pyminifier.py on the command line."),
90 | metavar=".pyz"
91 | )
92 | parser.add_option(
93 | "-O", "--obfuscate",
94 | action="store_true",
95 | dest="obfuscate",
96 | default=False,
97 | help=(
98 | "Obfuscate all function/method names, variables, and classes. "
99 | "Default is to NOT obfuscate."
100 | )
101 | )
102 | parser.add_option(
103 | "--obfuscate-classes",
104 | action="store_true",
105 | dest="obf_classes",
106 | default=False,
107 | help="Obfuscate class names."
108 | )
109 | parser.add_option(
110 | "--obfuscate-functions",
111 | action="store_true",
112 | dest="obf_functions",
113 | default=False,
114 | help="Obfuscate function and method names."
115 | )
116 | parser.add_option(
117 | "--obfuscate-variables",
118 | action="store_true",
119 | dest="obf_variables",
120 | default=False,
121 | help="Obfuscate variable names."
122 | )
123 | parser.add_option(
124 | "--obfuscate-import-methods",
125 | action="store_true",
126 | dest="obf_import_methods",
127 | default=False,
128 | help="Obfuscate globally-imported mouled methods (e.g. 'Ag=re.compile')."
129 | )
130 | parser.add_option(
131 | "--obfuscate-builtins",
132 | action="store_true",
133 | dest="obf_builtins",
134 | default=False,
135 | help="Obfuscate built-ins (i.e. True, False, object, Exception, etc)."
136 | )
137 | parser.add_option(
138 | "--replacement-length",
139 | dest="replacement_length",
140 | default=1,
141 | help=(
142 | "The length of the random names that will be used when obfuscating "
143 | "identifiers."
144 | ),
145 | metavar="1"
146 | )
147 | parser.add_option(
148 | "--nonlatin",
149 | action="store_true",
150 | dest="use_nonlatin",
151 | default=False,
152 | help=(
153 | "Use non-latin (unicode) characters in obfuscation (Python 3 only)."
154 | " WARNING: This results in some SERIOUSLY hard-to-read code."
155 | )
156 | )
157 | parser.add_option(
158 | "--prepend",
159 | dest="prepend",
160 | default=None,
161 | help=(
162 | "Prepend the text in this file to the top of our output. "
163 | "e.g. A copyright notice."
164 | ),
165 | metavar=""
166 | )
167 | options, files = parser.parse_args()
168 | if not files:
169 | parser.print_help()
170 | sys.exit(2)
171 | pyminify(options, files)
172 |
173 |
174 | if __name__ == "__main__":
175 | main()
176 |
--------------------------------------------------------------------------------
/pyminifier/analyze.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | __doc__ = """\
4 | A module of useful functions for analyzing Python code.
5 | """
6 |
7 | # Import builtins
8 | import os, sys, re, tokenize, keyword
9 | try:
10 | import cStringIO as io
11 | except ImportError: # Ahh, Python 3
12 | import io
13 |
14 | # Globals
15 | py3 = False
16 |
17 | if not isinstance(sys.version_info, tuple):
18 | if sys.version_info.major == 3:
19 | py3 = True
20 |
21 | shebang = re.compile('^#\!.*$')
22 | encoding = re.compile(".*coding[:=]\s*([-\w.]+)")
23 | # __builtins__ is different for every module so we need a hard-coded list:
24 | builtins = [
25 | 'ArithmeticError',
26 | 'AssertionError',
27 | 'AttributeError',
28 | 'BaseException',
29 | 'BufferError',
30 | 'BytesWarning',
31 | 'DeprecationWarning',
32 | 'EOFError',
33 | 'Ellipsis',
34 | 'EnvironmentError',
35 | 'Exception',
36 | 'False',
37 | 'FloatingPointError',
38 | 'FutureWarning',
39 | 'GeneratorExit',
40 | 'IOError',
41 | 'ImportError',
42 | 'ImportWarning',
43 | 'IndentationError',
44 | 'IndexError',
45 | 'KeyError',
46 | 'KeyboardInterrupt',
47 | 'LookupError',
48 | 'MemoryError',
49 | 'NameError',
50 | 'None',
51 | 'NotImplemented',
52 | 'NotImplementedError',
53 | 'OSError',
54 | 'OverflowError',
55 | 'PendingDeprecationWarning',
56 | 'ReferenceError',
57 | 'RuntimeError',
58 | 'RuntimeWarning',
59 | 'StandardError',
60 | 'StopIteration',
61 | 'SyntaxError',
62 | 'SyntaxWarning',
63 | 'SystemError',
64 | 'SystemExit',
65 | 'TabError',
66 | 'True',
67 | 'TypeError',
68 | 'UnboundLocalError',
69 | 'UnicodeDecodeError',
70 | 'UnicodeEncodeError',
71 | 'UnicodeError',
72 | 'UnicodeTranslateError',
73 | 'UnicodeWarning',
74 | 'UserWarning',
75 | 'ValueError',
76 | 'Warning',
77 | 'ZeroDivisionError',
78 | '__IPYTHON__',
79 | '__IPYTHON__active',
80 | '__debug__',
81 | '__doc__',
82 | '__import__',
83 | '__name__',
84 | '__package__',
85 | 'abs',
86 | 'all',
87 | 'any',
88 | 'apply',
89 | 'basestring',
90 | 'bin',
91 | 'bool',
92 | 'buffer',
93 | 'bytearray',
94 | 'bytes',
95 | 'callable',
96 | 'chr',
97 | 'classmethod',
98 | 'cmp',
99 | 'coerce',
100 | 'compile',
101 | 'complex',
102 | 'copyright',
103 | 'credits',
104 | 'delattr',
105 | 'dict',
106 | 'dir',
107 | 'divmod',
108 | 'dreload',
109 | 'enumerate',
110 | 'eval',
111 | 'execfile',
112 | 'exit',
113 | 'file',
114 | 'filter',
115 | 'float',
116 | 'format',
117 | 'frozenset',
118 | 'getattr',
119 | 'globals',
120 | 'hasattr',
121 | 'hash',
122 | 'help',
123 | 'hex',
124 | 'id',
125 | 'input',
126 | 'int',
127 | 'intern',
128 | 'ip_set_hook',
129 | 'ipalias',
130 | 'ipmagic',
131 | 'ipsystem',
132 | 'isinstance',
133 | 'issubclass',
134 | 'iter',
135 | 'jobs',
136 | 'len',
137 | 'license',
138 | 'list',
139 | 'locals',
140 | 'long',
141 | 'map',
142 | 'max',
143 | 'min',
144 | 'next',
145 | 'object',
146 | 'oct',
147 | 'open',
148 | 'ord',
149 | 'pow',
150 | 'print',
151 | 'property',
152 | 'quit',
153 | 'range',
154 | 'raw_input',
155 | 'reduce',
156 | 'reload',
157 | 'repr',
158 | 'reversed',
159 | 'round',
160 | 'set',
161 | 'setattr',
162 | 'slice',
163 | 'sorted',
164 | 'staticmethod',
165 | 'str',
166 | 'sum',
167 | 'super',
168 | 'tuple',
169 | 'type',
170 | 'unichr',
171 | 'unicode',
172 | 'vars',
173 | 'xrange',
174 | 'zip'
175 | ]
176 |
177 | reserved_words = keyword.kwlist + builtins
178 |
179 | def enumerate_keyword_args(tokens):
180 | """
181 | Iterates over *tokens* and returns a dictionary with function names as the
182 | keys and lists of keyword arguments as the values.
183 | """
184 | keyword_args = {}
185 | inside_function = False
186 | for index, tok in enumerate(tokens):
187 | token_type = tok[0]
188 | token_string = tok[1]
189 | if token_type == tokenize.NEWLINE:
190 | inside_function = False
191 | if token_type == tokenize.NAME:
192 | if token_string == "def":
193 | function_name = tokens[index+1][1]
194 | inside_function = function_name
195 | keyword_args.update({function_name: []})
196 | elif inside_function:
197 | if tokens[index+1][1] == '=': # keyword argument
198 | keyword_args[function_name].append(token_string)
199 | return keyword_args
200 |
201 | def enumerate_imports(tokens):
202 | """
203 | Iterates over *tokens* and returns a list of all imported modules.
204 |
205 | .. note:: This ignores imports using the 'as' and 'from' keywords.
206 | """
207 | imported_modules = []
208 | import_line = False
209 | from_import = False
210 | for index, tok in enumerate(tokens):
211 | token_type = tok[0]
212 | token_string = tok[1]
213 | if token_type == tokenize.NEWLINE:
214 | import_line = False
215 | from_import = False
216 | elif token_string == "import":
217 | import_line = True
218 | elif token_string == "from":
219 | from_import = True
220 | elif import_line:
221 | if token_type == tokenize.NAME and tokens[index+1][1] != 'as':
222 | if not from_import:
223 | if token_string not in reserved_words:
224 | if token_string not in imported_modules:
225 | imported_modules.append(token_string)
226 | return imported_modules
227 |
228 | def enumerate_global_imports(tokens):
229 | """
230 | Returns a list of all globally imported modules (skips modules imported
231 | inside of classes, methods, or functions). Example::
232 |
233 | >>> enumerate_global_modules(tokens)
234 | ['sys', 'os', 'tokenize', 're']
235 |
236 | .. note::
237 |
238 | Does not enumerate imports using the 'from' or 'as' keywords.
239 | """
240 | imported_modules = []
241 | import_line = False
242 | from_import = False
243 | parent_module = ""
244 | function_count = 0
245 | indentation = 0
246 | for index, tok in enumerate(tokens):
247 | token_type = tok[0]
248 | token_string = tok[1]
249 | if token_type == tokenize.INDENT:
250 | indentation += 1
251 | elif token_type == tokenize.DEDENT:
252 | indentation -= 1
253 | elif token_type == tokenize.NEWLINE:
254 | import_line = False
255 | from_import = False
256 | elif token_type == tokenize.NAME:
257 | if token_string in ["def", "class"]:
258 | function_count += 1
259 | if indentation == function_count - 1:
260 | function_count -= 1
261 | elif function_count >= indentation:
262 | if token_string == "import":
263 | import_line = True
264 | elif token_string == "from":
265 | from_import = True
266 | elif import_line:
267 | if token_type == tokenize.NAME \
268 | and tokens[index+1][1] != 'as':
269 | if not from_import \
270 | and token_string not in reserved_words:
271 | if token_string not in imported_modules:
272 | if tokens[index+1][1] == '.': # module.module
273 | parent_module = token_string + '.'
274 | else:
275 | if parent_module:
276 | module_string = (
277 | parent_module + token_string)
278 | imported_modules.append(module_string)
279 | parent_module = ''
280 | else:
281 | imported_modules.append(token_string)
282 |
283 | return imported_modules
284 |
285 | # TODO: Finish this (even though it isn't used):
286 | def enumerate_dynamic_imports(tokens):
287 | """
288 | Returns a dictionary of all dynamically imported modules (those inside of
289 | classes or functions) in the form of {: []}
290 |
291 | Example:
292 | >>> enumerate_dynamic_modules(tokens)
293 | {'myfunc': ['zlib', 'base64']}
294 | """
295 | imported_modules = []
296 | import_line = False
297 | for index, tok in enumerate(tokens):
298 | token_type = tok[0]
299 | token_string = tok[1]
300 | if token_type == tokenize.NEWLINE:
301 | import_line = False
302 | elif token_string == "import":
303 | try:
304 | if tokens[index-1][0] == tokenize.NEWLINE:
305 | import_line = True
306 | except IndexError:
307 | import_line = True # Just means this is the first line
308 | elif import_line:
309 | if token_type == tokenize.NAME and tokens[index+1][1] != 'as':
310 | if token_string not in reserved_words:
311 | if token_string not in imported_modules:
312 | imported_modules.append(token_string)
313 | return imported_modules
314 |
315 | def enumerate_method_calls(tokens, modules):
316 | """
317 | Returns a list of all object (not module) method calls in the given tokens.
318 |
319 | *modules* is expected to be a list of all global modules imported into the
320 | source code we're working on.
321 |
322 | For example:
323 | >>> enumerate_method_calls(tokens)
324 | ['re.compile', 'sys.argv', 'f.write']
325 | """
326 | out = []
327 | for index, tok in enumerate(tokens):
328 | token_type = tok[0]
329 | token_string = tok[1]
330 | if token_type == tokenize.NAME:
331 | next_tok_string = tokens[index+1][1]
332 | if next_tok_string == '(': # Method call
333 | prev_tok_string = tokens[index-1][1]
334 | # Check if we're attached to an object or module
335 | if prev_tok_string == '.': # We're attached
336 | prev_prev_tok_string = tokens[index-2][1]
337 | if prev_prev_tok_string not in ['""',"''", ']', ')', '}']:
338 | if prev_prev_tok_string not in modules:
339 | to_replace = "%s.%s" % (
340 | prev_prev_tok_string, token_string)
341 | if to_replace not in out:
342 | out.append(to_replace)
343 | return out
344 |
345 | def enumerate_builtins(tokens):
346 | """
347 | Returns a list of all the builtins being used in *tokens*.
348 | """
349 | out = []
350 | for index, tok in enumerate(tokens):
351 | token_type = tok[0]
352 | token_string = tok[1]
353 | if token_string in builtins:
354 | # Note: I need to test if print can be replaced in Python 3
355 | special_special = ['print'] # Print is special in Python 2
356 | if py3:
357 | special_special = []
358 | if token_string not in special_special:
359 | if not token_string.startswith('__'): # Don't count magic funcs
360 | if tokens[index-1][1] != '.' and tokens[index+1][1] != '=':
361 | if token_string not in out:
362 | out.append(token_string)
363 | return out
364 |
365 | def enumerate_import_methods(tokens):
366 | """
367 | Returns a list of imported module methods (such as re.compile) inside
368 | *tokens*.
369 | """
370 | global_imports = enumerate_global_imports(tokens)
371 | out = []
372 | for item in global_imports:
373 | for index, tok in enumerate(tokens):
374 | try:
375 | next_tok = tokens[index+1]
376 | try:
377 | next_next_tok = tokens[index+2]
378 | except IndexError:
379 | # Pretend it is a newline
380 | next_next_tok = (54, '\n', (1, 1), (1, 2), '#\n')
381 | except IndexError: # Last token, no biggie
382 | # Pretend it is a newline here too
383 | next_tok = (54, '\n', (1, 1), (1, 2), '#\n')
384 | token_type = tok[0]
385 | token_string = tok[1]
386 | if token_string == item:
387 | if next_tok[1] == '.': # We're calling a method
388 | module_method = "%s.%s" % (token_string, next_next_tok[1])
389 | if module_method not in out:
390 | out.append(module_method)
391 | return out
392 |
393 | def enumerate_local_modules(tokens, path):
394 | """
395 | Returns a list of modules inside *tokens* that are local to *path*.
396 |
397 | **Note:** Will recursively look inside *path* for said modules.
398 | """
399 | # Have to get a list of all modules before we can do anything else
400 | modules = enumerate_imports(tokens)
401 | local_modules = []
402 | parent = ""
403 | # Now check the local dir for matching modules
404 | for root, dirs, files in os.walk(path):
405 | if not parent:
406 | parent = os.path.split(root)[1]
407 | for f in files:
408 | if f.endswith('.py'):
409 | f = f[:-3] # Strip .py
410 | module_tree = root.split(parent)[1].replace('/', '.')
411 | module_tree = module_tree.lstrip('.')
412 | if module_tree:
413 | module = "%s.%s" % (module_tree, f)
414 | else:
415 | module = f
416 | if not module in modules:
417 | local_modules.append(module)
418 | return local_modules
419 |
420 | def get_shebang(tokens):
421 | """
422 | Returns the shebang string in *tokens* if it exists. None if not.
423 | """
424 | # This (short) loop preserves shebangs and encoding strings:
425 | for tok in tokens[0:4]: # Will always be in the first four tokens
426 | line = tok[4]
427 | # Save the first comment line if it starts with a shebang
428 | # (e.g. '#!/usr/bin/env python')
429 | if shebang.match(line): # Must be first line
430 | return line
431 |
--------------------------------------------------------------------------------
/pyminifier/compression.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | __doc__ = """\
4 | compression.py - A module providing functions to turn a python script into a
5 | self-executing archive in a few different formats...
6 |
7 | **gz_pack format:**
8 |
9 | - Typically provides better compression than bzip2 (for Python scripts).
10 | - Scripts compressed via this method can still be imported as modules.
11 | - The resulting binary data is base64-encoded which isn't optimal compression.
12 |
13 | **bz2_pack format:**
14 |
15 | - In some cases may provide better compression than gzip.
16 | - Scripts compressed via this method can still be imported as modules.
17 | - The resulting binary data is base64-encoded which isn't optimal compression.
18 |
19 | **lzma_pack format:**
20 |
21 | - In some cases may provide better compression than bzip2.
22 | - Scripts compressed via this method can still be imported as modules.
23 | - The resulting binary data is base64-encoded which isn't optimal compression.
24 |
25 | The gz_pack, bz2_pack, and lzma_pack formats only work on individual .py
26 | files. To pack a number of files at once using this method use the
27 | ``--destdir`` command line option:
28 |
29 | .. code-block: shell
30 |
31 | $ pyminifier --gzip --destdir=/tmp/minified *.py
32 |
33 | **zip_pack format:**
34 |
35 | - Provides the best compression of Python scripts.
36 | - Resulting script cannot be imported as a module.
37 | - Any required modules that are local (implied path) will be automatically included in the archive.
38 | """
39 |
40 | # Import standard library modules
41 | import os, sys, tempfile, shutil
42 |
43 | # Import our own supporting modules
44 | from . import analyze, token_utils, minification, obfuscate
45 |
46 | py3 = False
47 | if not isinstance(sys.version_info, tuple):
48 | if sys.version_info.major == 3:
49 | py3 = True
50 |
51 | def bz2_pack(source):
52 | """
53 | Returns 'source' as a bzip2-compressed, self-extracting python script.
54 |
55 | .. note::
56 |
57 | This method uses up more space than the zip_pack method but it has the
58 | advantage in that the resulting .py file can still be imported into a
59 | python program.
60 | """
61 | import bz2, base64
62 | out = ""
63 | # Preserve shebangs (don't care about encodings for this)
64 | first_line = source.split('\n')[0]
65 | if analyze.shebang.match(first_line):
66 | if py3:
67 | if first_line.rstrip().endswith('python'): # Make it python3
68 | first_line = first_line.rstrip()
69 | first_line += '3' #!/usr/bin/env python3
70 | out = first_line + '\n'
71 | compressed_source = bz2.compress(source.encode('utf-8'))
72 | out += 'import bz2, base64\n'
73 | out += "exec(bz2.decompress(base64.b64decode('"
74 | out += base64.b64encode(compressed_source).decode('utf-8')
75 | out += "')))\n"
76 | return out
77 |
78 | def gz_pack(source):
79 | """
80 | Returns 'source' as a gzip-compressed, self-extracting python script.
81 |
82 | .. note::
83 |
84 | This method uses up more space than the zip_pack method but it has the
85 | advantage in that the resulting .py file can still be imported into a
86 | python program.
87 | """
88 | import zlib, base64
89 | out = ""
90 | # Preserve shebangs (don't care about encodings for this)
91 | first_line = source.split('\n')[0]
92 | if analyze.shebang.match(first_line):
93 | if py3:
94 | if first_line.rstrip().endswith('python'): # Make it python3
95 | first_line = first_line.rstrip()
96 | first_line += '3' #!/usr/bin/env python3
97 | out = first_line + '\n'
98 | compressed_source = zlib.compress(source.encode('utf-8'))
99 | out += 'import zlib, base64\n'
100 | out += "exec(zlib.decompress(base64.b64decode('"
101 | out += base64.b64encode(compressed_source).decode('utf-8')
102 | out += "')))\n"
103 | return out
104 |
105 | def lzma_pack(source):
106 | """
107 | Returns 'source' as a lzma-compressed, self-extracting python script.
108 |
109 | .. note::
110 |
111 | This method uses up more space than the zip_pack method but it has the
112 | advantage in that the resulting .py file can still be imported into a
113 | python program.
114 | """
115 | import lzma, base64
116 | out = ""
117 | # Preserve shebangs (don't care about encodings for this)
118 | first_line = source.split('\n')[0]
119 | if analyze.shebang.match(first_line):
120 | if py3:
121 | if first_line.rstrip().endswith('python'): # Make it python3
122 | first_line = first_line.rstrip()
123 | first_line += '3' #!/usr/bin/env python3
124 | out = first_line + '\n'
125 | compressed_source = lzma.compress(source.encode('utf-8'))
126 | out += 'import lzma, base64\n'
127 | out += "exec(lzma.decompress(base64.b64decode('"
128 | out += base64.b64encode(compressed_source).decode('utf-8')
129 | out += "')))\n"
130 | return out
131 |
132 | def prepend(line, path):
133 | """
134 | Appends *line* to the _beginning_ of the file at the given *path*.
135 |
136 | If *line* doesn't end in a newline one will be appended to the end of it.
137 | """
138 | if isinstance(line, str):
139 | line = line.encode('utf-8')
140 | if not line.endswith(b'\n'):
141 | line += b'\n'
142 | temp = tempfile.NamedTemporaryFile('wb')
143 | temp_name = temp.name # We really only need a random path-safe name
144 | temp.close()
145 | with open(temp_name, 'wb') as temp:
146 | temp.write(line)
147 | with open(path, 'rb') as r:
148 | temp.write(r.read())
149 | # Now replace the original with the modified version
150 | shutil.move(temp_name, path)
151 |
152 | def zip_pack(filepath, options):
153 | """
154 | Creates a zip archive containing the script at *filepath* along with all
155 | imported modules that are local to *filepath* as a self-extracting python
156 | script. A shebang will be appended to the beginning of the resulting
157 | zip archive which will allow it to
158 |
159 | If being run inside Python 3 and the `lzma` module is available the
160 | resulting 'pyz' file will use ZIP_LZMA compression to maximize compression.
161 |
162 | *options* is expected to be the the same options parsed from pyminifier.py
163 | on the command line.
164 |
165 | .. note::
166 |
167 | * The file resulting from this method cannot be imported as a module into another python program (command line execution only).
168 | * Any required local (implied path) modules will be automatically included (well, it does its best).
169 | * The result will be saved as a .pyz file (which is an extension I invented for this format).
170 | """
171 | import zipfile
172 | # Hopefully some day we'll be able to use ZIP_LZMA too as the compression
173 | # format to save even more space...
174 | compression_format = zipfile.ZIP_DEFLATED
175 | cumulative_size = 0 # For tracking size reduction stats
176 | # Record the filesize for later comparison
177 | cumulative_size += os.path.getsize(filepath)
178 | dest = options.pyz
179 | z = zipfile.ZipFile(dest, "w", compression_format)
180 | # Take care of minifying our primary script first:
181 | source = open(filepath).read()
182 | primary_tokens = token_utils.listified_tokenizer(source)
183 | # Preserve shebangs (don't care about encodings for this)
184 | shebang = analyze.get_shebang(primary_tokens)
185 | if not shebang:
186 | # We *must* have a shebang for this to work so make a conservative default:
187 | shebang = "#!/usr/bin/env python"
188 | if py3:
189 | if shebang.rstrip().endswith('python'): # Make it python3 (to be safe)
190 | shebang = shebang.rstrip()
191 | shebang += '3\n' #!/usr/bin/env python3
192 | if not options.nominify: # Minify as long as we don't have this option set
193 | source = minification.minify(primary_tokens, options)
194 | # Write out to a temporary file to add to our zip
195 | temp = tempfile.NamedTemporaryFile(mode='w')
196 | temp.write(source)
197 | temp.flush()
198 | # Need the path where the script lives for the next steps:
199 | path = os.path.split(filepath)[0]
200 | if not path:
201 | path = os.getcwd()
202 | main_py = path + '/__main__.py'
203 | if os.path.exists(main_py):
204 | # There's an existing __main__.py, use it
205 | z.write(main_py, '__main__.py')
206 | z.write(temp.name, os.path.split(filepath)[1])
207 | else:
208 | # No __main__.py so we rename our main script to be the __main__.py
209 | # This is so it will still execute as a zip
210 | z.write(filepath, '__main__.py')
211 | temp.close()
212 | # Now write any required modules into the zip as well
213 | local_modules = analyze.enumerate_local_modules(primary_tokens, path)
214 | name_generator = None # So we can tell if we need to obfuscate
215 | if options.obfuscate or options.obf_classes \
216 | or options.obf_functions or options.obf_variables \
217 | or options.obf_builtins or options.obf_import_methods:
218 | # Put together that will be used for all obfuscation functions:
219 | identifier_length = int(options.replacement_length)
220 | if options.use_nonlatin:
221 | if sys.version_info[0] == 3:
222 | name_generator = obfuscate.obfuscation_machine(
223 | use_unicode=True, identifier_length=identifier_length
224 | )
225 | else:
226 | print(
227 | "ERROR: You can't use nonlatin characters without Python 3")
228 | sys.exit(2)
229 | else:
230 | name_generator = obfuscate.obfuscation_machine(
231 | identifier_length=identifier_length)
232 | table =[{}]
233 | included_modules = []
234 | for module in local_modules:
235 | module = module.replace('.', '/')
236 | module = "%s.py" % module
237 | # Add the filesize to our total
238 | cumulative_size += os.path.getsize(module)
239 | # Also record that we've added it to the archive
240 | included_modules.append(module)
241 | # Minify these files too
242 | source = open(os.path.join(path, module)).read()
243 | tokens = token_utils.listified_tokenizer(source)
244 | maybe_more_modules = analyze.enumerate_local_modules(tokens, path)
245 | for mod in maybe_more_modules:
246 | if mod not in local_modules:
247 | local_modules.append(mod) # Extend the current loop, love it =)
248 | if not options.nominify:
249 | # Perform minification (this also handles obfuscation)
250 | source = minification.minify(tokens, options)
251 | # Have to re-tokenize for obfucation (it's quick):
252 | tokens = token_utils.listified_tokenizer(source)
253 | # Perform obfuscation if any of the related options were set
254 | if name_generator:
255 | obfuscate.obfuscate(
256 | module,
257 | tokens,
258 | options,
259 | name_generator=name_generator,
260 | table=table
261 | )
262 | # Convert back to text
263 | result = token_utils.untokenize(tokens)
264 | result += (
265 | "# Created by pyminifier "
266 | "(https://github.com/liftoff/pyminifier)\n")
267 | # Write out to a temporary file to add to our zip
268 | temp = tempfile.NamedTemporaryFile(mode='w')
269 | temp.write(source)
270 | temp.flush()
271 | z.write(temp.name, module)
272 | temp.close()
273 | z.close()
274 | # Finish up by writing the shebang to the beginning of the zip
275 | prepend(shebang, dest)
276 | os.chmod(dest, 0o755) # Make it executable (since we added the shebang)
277 | pyz_filesize = os.path.getsize(dest)
278 | percent_saved = round(float(pyz_filesize) / float(cumulative_size) * 100, 2)
279 | print('%s saved as compressed executable zip: %s' % (filepath, dest))
280 | print('The following modules were automatically included (as automagic '
281 | 'dependencies):\n')
282 | for module in included_modules:
283 | print('\t%s' % module)
284 | print('\nOverall size reduction: %s%% of original size' % percent_saved)
285 |
--------------------------------------------------------------------------------
/pyminifier/minification.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | __doc__ = """\
4 | Module for minification functions.
5 | """
6 |
7 | # Import built-in modules
8 | import re, tokenize, keyword
9 | try:
10 | import cStringIO as io
11 | except ImportError: # We're using Python 3
12 | import io
13 |
14 | # Import our own modules
15 | from . import analyze, token_utils
16 |
17 | # Compile our regular expressions for speed
18 | multiline_quoted_string = re.compile(r'(\'\'\'|\"\"\")')
19 | not_quoted_string = re.compile(r'(\".*\'\'\'.*\"|\'.*\"\"\".*\')')
20 | trailing_newlines = re.compile(r'\n\n')
21 | multiline_indicator = re.compile('\\\\(\s*#.*)?\n')
22 | left_of_equals = re.compile('^.*?=')
23 | # The above also removes trailing comments: "test = 'blah \ # comment here"
24 |
25 | # These aren't used but they're a pretty good reference:
26 | double_quoted_string = re.compile(r'((? last_lineno:
127 | last_col = 0
128 | if start_col > last_col:
129 | out += (" " * (start_col - last_col))
130 | # Remove comments:
131 | if token_type == tokenize.COMMENT:
132 | pass
133 | # This series of conditionals removes docstrings:
134 | elif token_type == tokenize.STRING:
135 | if prev_toktype != tokenize.INDENT:
136 | # This is likely a docstring; double-check we're not inside an operator:
137 | if prev_toktype != tokenize.NEWLINE:
138 | # Note regarding NEWLINE vs NL: The tokenize module
139 | # differentiates between newlines that start a new statement
140 | # and newlines inside of operators such as parens, brackes,
141 | # and curly braces. Newlines inside of operators are
142 | # NEWLINE and newlines that start new code are NL.
143 | # Catch whole-module docstrings:
144 | if start_col > 0:
145 | # Unlabelled indentation means we're inside an operator
146 | out += token_string
147 | # Note regarding the INDENT token: The tokenize module does
148 | # not label indentation inside of an operator (parens,
149 | # brackets, and curly braces) as actual indentation.
150 | # For example:
151 | # def foo():
152 | # "The spaces before this docstring are tokenize.INDENT"
153 | # test = [
154 | # "The spaces before this string do not get a token"
155 | # ]
156 | else:
157 | out += token_string
158 | prev_toktype = token_type
159 | last_col = end_col
160 | last_lineno = end_line
161 | return out
162 |
163 | def reduce_operators(source):
164 | """
165 | Remove spaces between operators in *source* and returns the result.
166 | Example::
167 |
168 | def foo(foo, bar, blah):
169 | test = "This is a %s" % foo
170 |
171 | Will become::
172 |
173 | def foo(foo,bar,blah):
174 | test="This is a %s"%foo
175 |
176 | .. note::
177 |
178 | Also removes trailing commas and joins disjointed strings like
179 | ``("foo" "bar")``.
180 | """
181 | io_obj = io.StringIO(source)
182 | prev_tok = None
183 | out_tokens = []
184 | out = ""
185 | last_lineno = -1
186 | last_col = 0
187 | nl_types = (tokenize.NL, tokenize.NEWLINE)
188 | joining_strings = False
189 | new_string = ""
190 | for tok in tokenize.generate_tokens(io_obj.readline):
191 | token_type = tok[0]
192 | token_string = tok[1]
193 | start_line, start_col = tok[2]
194 | end_line, end_col = tok[3]
195 | if start_line > last_lineno:
196 | last_col = 0
197 | if token_type != tokenize.OP:
198 | if start_col > last_col and token_type not in nl_types:
199 | if prev_tok[0] != tokenize.OP:
200 | out += (" " * (start_col - last_col))
201 | if token_type == tokenize.STRING:
202 | if prev_tok[0] == tokenize.STRING:
203 | # Join the strings into one
204 | string_type = token_string[0] # '' or ""
205 | prev_string_type = prev_tok[1][0]
206 | out = out.rstrip(" ") # Remove any spaces we inserted prev
207 | if not joining_strings:
208 | # Remove prev token and start the new combined string
209 | out = out[:(len(out)-len(prev_tok[1]))]
210 | prev_string = prev_tok[1].strip(prev_string_type)
211 | new_string = (
212 | prev_string + token_string.strip(string_type))
213 | joining_strings = True
214 | else:
215 | new_string += token_string.strip(string_type)
216 | else:
217 | if token_string in ('}', ')', ']'):
218 | if prev_tok[1] == ',':
219 | out = out.rstrip(',')
220 | if joining_strings:
221 | # NOTE: Using triple quotes so that this logic works with
222 | # mixed strings using both single quotes and double quotes.
223 | out += "'''" + new_string + "'''"
224 | joining_strings = False
225 | if token_string == '@': # Decorators need special handling
226 | if prev_tok[0] == tokenize.NEWLINE:
227 | # Ensure it gets indented properly
228 | out += (" " * (start_col - last_col))
229 | if not joining_strings:
230 | out += token_string
231 | last_col = end_col
232 | last_lineno = end_line
233 | prev_tok = tok
234 | return out
235 |
236 | def join_multiline_pairs(source, pair="()"):
237 | """
238 | Finds and removes newlines in multiline matching pairs of characters in
239 | *source*.
240 |
241 | By default it joins parens () but it will join any two characters given via
242 | the *pair* variable.
243 |
244 | .. note::
245 |
246 | Doesn't remove extraneous whitespace that ends up between the pair.
247 | Use `reduce_operators()` for that.
248 |
249 | Example::
250 |
251 | test = (
252 | "This is inside a multi-line pair of parentheses"
253 | )
254 |
255 | Will become::
256 |
257 | test = ( "This is inside a multi-line pair of parentheses" )
258 |
259 | """
260 | opener = pair[0]
261 | closer = pair[1]
262 | io_obj = io.StringIO(source)
263 | out_tokens = []
264 | open_count = 0
265 | for tok in tokenize.generate_tokens(io_obj.readline):
266 | token_type = tok[0]
267 | token_string = tok[1]
268 | if token_type == tokenize.OP and token_string in pair:
269 | if token_string == opener:
270 | open_count += 1
271 | elif token_string == closer:
272 | open_count -= 1
273 | out_tokens.append(tok)
274 | elif token_type in (tokenize.NL, tokenize.NEWLINE):
275 | if open_count == 0:
276 | out_tokens.append(tok)
277 | else:
278 | out_tokens.append(tok)
279 | return token_utils.untokenize(out_tokens)
280 |
281 | def dedent(source, use_tabs=False):
282 | """
283 | Minimizes indentation to save precious bytes. Optionally, *use_tabs*
284 | may be specified if you want to use tabulators (\t) instead of spaces.
285 |
286 | Example::
287 |
288 | def foo(bar):
289 | test = "This is a test"
290 |
291 | Will become::
292 |
293 | def foo(bar):
294 | test = "This is a test"
295 | """
296 | if use_tabs:
297 | indent_char = '\t'
298 | else:
299 | indent_char = ' '
300 | io_obj = io.StringIO(source)
301 | out = ""
302 | last_lineno = -1
303 | last_col = 0
304 | prev_start_line = 0
305 | indentation = ""
306 | indentation_level = 0
307 | for i, tok in enumerate(tokenize.generate_tokens(io_obj.readline)):
308 | token_type = tok[0]
309 | token_string = tok[1]
310 | start_line, start_col = tok[2]
311 | end_line, end_col = tok[3]
312 | if start_line > last_lineno:
313 | last_col = 0
314 | if token_type == tokenize.INDENT:
315 | indentation_level += 1
316 | continue
317 | if token_type == tokenize.DEDENT:
318 | indentation_level -= 1
319 | continue
320 | indentation = indent_char * indentation_level
321 | if start_line > prev_start_line:
322 | if token_string in (',', '.'):
323 | out += str(token_string)
324 | else:
325 | out += indentation + str(token_string)
326 | elif start_col > last_col:
327 | out += indent_char + str(token_string)
328 | else:
329 | out += token_string
330 | prev_start_line = start_line
331 | last_col = end_col
332 | last_lineno = end_line
333 | return out
334 |
335 | # TODO: Rewrite this to use tokens
336 | def fix_empty_methods(source):
337 | """
338 | Appends 'pass' to empty methods/functions (i.e. where there was nothing but
339 | a docstring before we removed it =).
340 |
341 | Example::
342 |
343 | # Note: This triple-single-quote inside a triple-double-quote is also a
344 | # pyminifier self-test
345 | def myfunc():
346 | '''This is just a placeholder function.'''
347 |
348 | Will become::
349 |
350 | def myfunc(): pass
351 | """
352 | def_indentation_level = 0
353 | output = ""
354 | just_matched = False
355 | previous_line = None
356 | method = re.compile(r'^\s*def\s*.*\(.*\):.*$')
357 | for line in source.split('\n'):
358 | if len(line.strip()) > 0: # Don't look at blank lines
359 | if just_matched == True:
360 | this_indentation_level = len(line.rstrip()) - len(line.strip())
361 | if def_indentation_level == this_indentation_level:
362 | # This method is empty, insert a 'pass' statement
363 | indent = " " * (def_indentation_level + 1)
364 | output += "%s\n%spass\n%s\n" % (previous_line, indent, line)
365 | else:
366 | output += "%s\n%s\n" % (previous_line, line)
367 | just_matched = False
368 | elif method.match(line):
369 | def_indentation_level = len(line) - len(line.strip())
370 | just_matched = True
371 | previous_line = line
372 | else:
373 | output += "%s\n" % line # Another self-test
374 | else:
375 | output += "\n"
376 | return output
377 |
378 | def remove_blank_lines(source):
379 | """
380 | Removes blank lines from *source* and returns the result.
381 |
382 | Example:
383 |
384 | .. code-block:: python
385 |
386 | test = "foo"
387 |
388 | test2 = "bar"
389 |
390 | Will become:
391 |
392 | .. code-block:: python
393 |
394 | test = "foo"
395 | test2 = "bar"
396 | """
397 | io_obj = io.StringIO(source)
398 | source = [a for a in io_obj.readlines() if a.strip()]
399 | return "".join(source)
400 |
401 | def minify(tokens, options):
402 | """
403 | Performs minification on *tokens* according to the values in *options*
404 | """
405 | # Remove comments
406 | remove_comments(tokens)
407 | # Remove docstrings
408 | remove_docstrings(tokens)
409 | result = token_utils.untokenize(tokens)
410 | # Minify our input script
411 | result = multiline_indicator.sub('', result)
412 | result = fix_empty_methods(result)
413 | result = join_multiline_pairs(result)
414 | result = join_multiline_pairs(result, '[]')
415 | result = join_multiline_pairs(result, '{}')
416 | result = remove_blank_lines(result)
417 | result = reduce_operators(result)
418 | result = dedent(result, use_tabs=options.tabs)
419 | return result
420 |
--------------------------------------------------------------------------------
/pyminifier/obfuscate.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | # -*- coding: utf-8 -*-
3 |
4 | __doc__ = """\
5 | A collection of functions for obfuscating code.
6 | """
7 |
8 | import os, sys, tokenize, keyword, sys, unicodedata
9 | from random import shuffle, choice
10 | from itertools import permutations
11 |
12 | # Import our own modules
13 | from . import analyze
14 | from . import token_utils
15 |
16 | if not isinstance(sys.version_info, tuple):
17 | if sys.version_info.major == 3:
18 | unichr = chr # So we can support both 2 and 3
19 |
20 | try:
21 | unichr(0x10000) # Will throw a ValueError on narrow Python builds
22 | HIGHEST_UNICODE = 0x10FFFF # 1114111
23 | except:
24 | HIGHEST_UNICODE = 0xFFFF # 65535
25 |
26 | # Reserved words can be overridden by the script that imports this module
27 | RESERVED_WORDS = keyword.kwlist + analyze.builtins
28 | VAR_REPLACEMENTS = {} # So we can reference what's already been replaced
29 | FUNC_REPLACEMENTS = {}
30 | CLASS_REPLACEMENTS = {}
31 | UNIQUE_REPLACEMENTS = {}
32 |
33 | def obfuscation_machine(use_unicode=False, identifier_length=1):
34 | """
35 | A generator that returns short sequential combinations of lower and
36 | upper-case letters that will never repeat.
37 |
38 | If *use_unicode* is ``True``, use nonlatin cryllic, arabic, and syriac
39 | letters instead of the usual ABCs.
40 |
41 | The *identifier_length* represents the length of the string to return using
42 | the aforementioned characters.
43 | """
44 | # This generates a list of the letters a-z:
45 | lowercase = list(map(chr, range(97, 123)))
46 | # Same thing but ALL CAPS:
47 | uppercase = list(map(chr, range(65, 90)))
48 | if use_unicode:
49 | # Python 3 lets us have some *real* fun:
50 | allowed_categories = ('LC', 'Ll', 'Lu', 'Lo', 'Lu')
51 | # All the fun characters start at 1580 (hehe):
52 | big_list = list(map(chr, range(1580, HIGHEST_UNICODE)))
53 | max_chars = 1000 # Ought to be enough for anybody :)
54 | combined = []
55 | rtl_categories = ('AL', 'R') # AL == Arabic, R == Any right-to-left
56 | last_orientation = 'L' # L = Any left-to-right
57 | # Find a good mix of left-to-right and right-to-left characters
58 | while len(combined) < max_chars:
59 | char = choice(big_list)
60 | if unicodedata.category(char) in allowed_categories:
61 | orientation = unicodedata.bidirectional(char)
62 | if last_orientation in rtl_categories:
63 | if orientation not in rtl_categories:
64 | combined.append(char)
65 | else:
66 | if orientation in rtl_categories:
67 | combined.append(char)
68 | last_orientation = orientation
69 | else:
70 | combined = lowercase + uppercase
71 | shuffle(combined) # Randomize it all to keep things interesting
72 | while True:
73 | for perm in permutations(combined, identifier_length):
74 | perm = "".join(perm)
75 | if perm not in RESERVED_WORDS: # Can't replace reserved words
76 | yield perm
77 | identifier_length += 1
78 |
79 | def apply_obfuscation(source):
80 | """
81 | Returns 'source' all obfuscated.
82 | """
83 | global keyword_args
84 | global imported_modules
85 | tokens = token_utils.listified_tokenizer(source)
86 | keyword_args = analyze.enumerate_keyword_args(tokens)
87 | imported_modules = analyze.enumerate_imports(tokens)
88 | variables = find_obfuscatables(tokens, obfuscatable_variable)
89 | classes = find_obfuscatables(tokens, obfuscatable_class)
90 | functions = find_obfuscatables(tokens, obfuscatable_function)
91 | for variable in variables:
92 | replace_obfuscatables(
93 | tokens, obfuscate_variable, variable, name_generator)
94 | for function in functions:
95 | replace_obfuscatables(
96 | tokens, obfuscate_function, function, name_generator)
97 | for _class in classes:
98 | replace_obfuscatables(tokens, obfuscate_class, _class, name_generator)
99 | return token_utils.untokenize(tokens)
100 |
101 | def find_obfuscatables(tokens, obfunc, ignore_length=False):
102 | """
103 | Iterates over *tokens*, which must be an equivalent output to what
104 | tokenize.generate_tokens() produces, calling *obfunc* on each with the
105 | following parameters:
106 |
107 | - **tokens:** The current list of tokens.
108 | - **index:** The current position in the list.
109 |
110 | *obfunc* is expected to return the token string if that token can be safely
111 | obfuscated **or** one of the following optional values which will instruct
112 | find_obfuscatables() how to proceed:
113 |
114 | - **'__skipline__'** Keep skipping tokens until a newline is reached.
115 | - **'__skipnext__'** Skip the next token in the sequence.
116 |
117 | If *ignore_length* is ``True`` then single-character obfuscatables will
118 | be obfuscated anyway (even though it wouldn't save any space).
119 | """
120 | global keyword_args
121 | keyword_args = analyze.enumerate_keyword_args(tokens)
122 | global imported_modules
123 | imported_modules = analyze.enumerate_imports(tokens)
124 | #print("imported_modules: %s" % imported_modules)
125 | skip_line = False
126 | skip_next = False
127 | obfuscatables = []
128 | for index, tok in enumerate(tokens):
129 | token_type = tok[0]
130 | if token_type == tokenize.NEWLINE:
131 | skip_line = False
132 | if skip_line:
133 | continue
134 | result = obfunc(tokens, index, ignore_length=ignore_length)
135 | if result:
136 | if skip_next:
137 | skip_next = False
138 | elif result == '__skipline__':
139 | skip_line = True
140 | elif result == '__skipnext__':
141 | skip_next = True
142 | elif result in obfuscatables:
143 | pass
144 | else:
145 | obfuscatables.append(result)
146 | else: # If result is empty we need to reset skip_next so we don't
147 | skip_next = False # accidentally skip the next identifier
148 | return obfuscatables
149 |
150 | # Note: I'm using 'tok' instead of 'token' since 'token' is a built-in module
151 | def obfuscatable_variable(tokens, index, ignore_length=False):
152 | """
153 | Given a list of *tokens* and an *index* (representing the current position),
154 | returns the token string if it is a variable name that can be safely
155 | obfuscated.
156 |
157 | Returns '__skipline__' if the rest of the tokens on this line should be skipped.
158 | Returns '__skipnext__' if the next token should be skipped.
159 |
160 | If *ignore_length* is ``True``, even variables that are already a single
161 | character will be obfuscated (typically only used with the ``--nonlatin``
162 | option).
163 | """
164 | tok = tokens[index]
165 | token_type = tok[0]
166 | token_string = tok[1]
167 | line = tok[4]
168 | if index > 0:
169 | prev_tok = tokens[index-1]
170 | else: # Pretend it's a newline (for simplicity)
171 | prev_tok = (54, '\n', (1, 1), (1, 2), '#\n')
172 | prev_tok_type = prev_tok[0]
173 | prev_tok_string = prev_tok[1]
174 | try:
175 | next_tok = tokens[index+1]
176 | except IndexError: # Pretend it's a newline
177 | next_tok = (54, '\n', (1, 1), (1, 2), '#\n')
178 | next_tok_string = next_tok[1]
179 | if token_string == "=":
180 | return '__skipline__'
181 | if token_type != tokenize.NAME:
182 | return None # Skip this token
183 | if token_string.startswith('__'):
184 | return None
185 | if next_tok_string == ".":
186 | if token_string in imported_modules:
187 | return None
188 | if prev_tok_string == 'import':
189 | return '__skipline__'
190 | if prev_tok_string == ".":
191 | return '__skipnext__'
192 | if prev_tok_string == "for":
193 | if len(token_string) > 2:
194 | return token_string
195 | if token_string == "for":
196 | return None
197 | if token_string in keyword_args.keys():
198 | return None
199 | if token_string in ["def", "class", 'if', 'elif', 'import']:
200 | return '__skipline__'
201 | if prev_tok_type != tokenize.INDENT and next_tok_string != '=':
202 | return '__skipline__'
203 | if not ignore_length:
204 | if len(token_string) < 3:
205 | return None
206 | if token_string in RESERVED_WORDS:
207 | return None
208 | return token_string
209 |
210 | def obfuscatable_class(tokens, index, **kwargs):
211 | """
212 | Given a list of *tokens* and an *index* (representing the current position),
213 | returns the token string if it is a class name that can be safely
214 | obfuscated.
215 | """
216 | tok = tokens[index]
217 | token_type = tok[0]
218 | token_string = tok[1]
219 | if index > 0:
220 | prev_tok = tokens[index-1]
221 | else: # Pretend it's a newline (for simplicity)
222 | prev_tok = (54, '\n', (1, 1), (1, 2), '#\n')
223 | prev_tok_string = prev_tok[1]
224 | if token_type != tokenize.NAME:
225 | return None # Skip this token
226 | if token_string.startswith('__'): # Don't mess with specials
227 | return None
228 | if prev_tok_string == "class":
229 | return token_string
230 |
231 | def obfuscatable_function(tokens, index, **kwargs):
232 | """
233 | Given a list of *tokens* and an *index* (representing the current position),
234 | returns the token string if it is a function or method name that can be
235 | safely obfuscated.
236 | """
237 | tok = tokens[index]
238 | token_type = tok[0]
239 | token_string = tok[1]
240 | if index > 0:
241 | prev_tok = tokens[index-1]
242 | else: # Pretend it's a newline (for simplicity)
243 | prev_tok = (54, '\n', (1, 1), (1, 2), '#\n')
244 | prev_tok_string = prev_tok[1]
245 | if token_type != tokenize.NAME:
246 | return None # Skip this token
247 | if token_string.startswith('__'): # Don't mess with specials
248 | return None
249 | if prev_tok_string == "def":
250 | return token_string
251 |
252 | def replace_obfuscatables(module, tokens, obfunc, replace, name_generator, table=None):
253 | """
254 | Iterates over *tokens*, which must be an equivalent output to what
255 | tokenize.generate_tokens() produces, replacing the given identifier name
256 | (*replace*) by calling *obfunc* on each token with the following parameters:
257 |
258 | - **module:** The name of the script we're currently obfuscating.
259 | - **tokens:** The current list of all tokens.
260 | - **index:** The current position.
261 | - **replace:** The token string that we're replacing.
262 | - **replacement:** A randomly generated, unique value that will be used to replace, *replace*.
263 | - **right_of_equal:** A True or False value representing whether or not the token is to the right of an equal sign. **Note:** This gets reset to False if a comma or open paren are encountered.
264 | - **inside_parens:** An integer that is incremented whenever an open paren is encountered and decremented when a close paren is encountered.
265 | - **inside_function:** If not False, the name of the function definition we're inside of (used in conjunction with *keyword_args* to determine if a safe replacement can be made).
266 |
267 | *obfunc* is expected to return the token string if that token can be safely
268 | obfuscated **or** one of the following optional values which will instruct
269 | find_obfuscatables() how to proceed:
270 |
271 | - **'__open_paren__'** Increment the inside_parens value
272 | - **'__close_paren__'** Decrement the inside_parens value
273 | - **'__comma__'** Reset the right_of_equal value to False
274 | - **'__right_of_equal__'** Sets the right_of_equal value to True
275 |
276 | **Note:** The right_of_equal and the inside_parens values are reset whenever a NEWLINE is encountered.
277 |
278 | When obfuscating a list of files, *table* is used to keep track of which
279 | obfuscatable identifiers are which inside each resulting file. It must be
280 | an empty dictionary that will be populated like so::
281 |
282 | {orig_name: obfuscated_name}
283 |
284 | This *table* of "what is what" will be used to ensure that references from
285 | one script/module that call another are kept in sync when they are replaced
286 | with obfuscated values.
287 | """
288 | # Pretend the first line is '#\n':
289 | skip_line = False
290 | skip_next = False
291 | right_of_equal = False
292 | inside_parens = 0
293 | inside_function = False
294 | indent = 0
295 | function_indent = 0
296 | replacement = next(name_generator)
297 | for index, tok in enumerate(tokens):
298 | token_type = tok[0]
299 | token_string = tok[1]
300 | if token_type == tokenize.NEWLINE:
301 | skip_line = False
302 | right_of_equal = False
303 | inside_parens = 0
304 | elif token_type == tokenize.INDENT:
305 | indent += 1
306 | elif token_type == tokenize.DEDENT:
307 | indent -= 1
308 | if inside_function and function_indent == indent:
309 | function_indent = 0
310 | inside_function = False
311 | if token_string == "def":
312 | function_indent = indent
313 | function_name = tokens[index+1][1]
314 | inside_function = function_name
315 | result = obfunc(
316 | tokens,
317 | index,
318 | replace,
319 | replacement,
320 | right_of_equal,
321 | inside_parens,
322 | inside_function
323 | )
324 | if result:
325 | if skip_next:
326 | skip_next = False
327 | elif skip_line:
328 | pass
329 | elif result == '__skipline__':
330 | skip_line = True
331 | elif result == '__skipnext__':
332 | skip_next = True
333 | elif result == '__open_paren__':
334 | right_of_equal = False
335 | inside_parens += 1
336 | elif result == '__close_paren__':
337 | inside_parens -= 1
338 | elif result == '__comma__':
339 | right_of_equal = False
340 | elif result == '__right_of_equal__':
341 | # We only care if we're right of the equal sign outside of
342 | # parens (which indicates arguments)
343 | if not inside_parens:
344 | right_of_equal = True
345 | else:
346 | if table: # Save it for later use in other files
347 | combined_name = "%s.%s" % (module, token_string)
348 | try: # Attempt to use an existing value
349 | tokens[index][1] = table[0][combined_name]
350 | except KeyError: # Doesn't exist, add it to table
351 | table[0].update({combined_name: result})
352 | tokens[index][1] = result
353 | else:
354 | tokens[index][1] = result
355 |
356 | def obfuscate_variable(
357 | tokens,
358 | index,
359 | replace,
360 | replacement,
361 | right_of_equal,
362 | inside_parens,
363 | inside_function):
364 | """
365 | If the token string inside *tokens[index]* matches *replace*, return
366 | *replacement*. *right_of_equal*, and *inside_parens* are used to determine
367 | whether or not this token is safe to obfuscate.
368 | """
369 | def return_replacement(replacement):
370 | VAR_REPLACEMENTS[replacement] = replace
371 | return replacement
372 | tok = tokens[index]
373 | token_type = tok[0]
374 | token_string = tok[1]
375 | if index > 0:
376 | prev_tok = tokens[index-1]
377 | else: # Pretend it's a newline (for simplicity)
378 | prev_tok = (54, '\n', (1, 1), (1, 2), '#\n')
379 | prev_tok_string = prev_tok[1]
380 | try:
381 | next_tok = tokens[index+1]
382 | except IndexError: # Pretend it's a newline
383 | next_tok = (54, '\n', (1, 1), (1, 2), '#\n')
384 | if token_string == "import":
385 | return '__skipline__'
386 | if next_tok[1] == '.':
387 | if token_string in imported_modules:
388 | return None
389 | if token_string == "=":
390 | return '__right_of_equal__'
391 | if token_string == "(":
392 | return '__open_paren__'
393 | if token_string == ")":
394 | return '__close_paren__'
395 | if token_string == ",":
396 | return '__comma__'
397 | if token_type != tokenize.NAME:
398 | return None # Skip this token
399 | if token_string.startswith('__'):
400 | return None
401 | if prev_tok_string == 'def':
402 | return '__skipnext__' # Don't want to touch functions
403 | if token_string == replace and prev_tok_string != '.':
404 | if inside_function:
405 | if token_string not in keyword_args[inside_function]:
406 | if not right_of_equal:
407 | if not inside_parens:
408 | return return_replacement(replacement)
409 | else:
410 | if next_tok[1] != '=':
411 | return return_replacement(replacement)
412 | elif not inside_parens:
413 | return return_replacement(replacement)
414 | else:
415 | if next_tok[1] != '=':
416 | return return_replacement(replacement)
417 | elif not right_of_equal:
418 | if not inside_parens:
419 | return return_replacement(replacement)
420 | else:
421 | if next_tok[1] != '=':
422 | return return_replacement(replacement)
423 | elif right_of_equal and not inside_parens:
424 | return return_replacement(replacement)
425 |
426 | def obfuscate_function(tokens, index, replace, replacement, *args):
427 | """
428 | If the token string (a function) inside *tokens[index]* matches *replace*,
429 | return *replacement*.
430 | """
431 | def return_replacement(replacement):
432 | FUNC_REPLACEMENTS[replacement] = replace
433 | return replacement
434 | tok = tokens[index]
435 | token_type = tok[0]
436 | token_string = tok[1]
437 | prev_tok = tokens[index-1]
438 | prev_tok_string = prev_tok[1]
439 | if token_type != tokenize.NAME:
440 | return None # Skip this token
441 | if token_string.startswith('__'):
442 | return None
443 | if token_string == replace:
444 | if prev_tok_string != '.':
445 | if token_string == replace:
446 | return return_replacement(replacement)
447 | else:
448 | parent_name = tokens[index-2][1]
449 | if parent_name in CLASS_REPLACEMENTS:
450 | # This should work for @classmethod methods
451 | return return_replacement(replacement)
452 | elif parent_name in VAR_REPLACEMENTS:
453 | # This covers regular ol' instance methods
454 | return return_replacement(replacement)
455 |
456 | def obfuscate_class(tokens, index, replace, replacement, *args):
457 | """
458 | If the token string (a class) inside *tokens[index]* matches *replace*,
459 | return *replacement*.
460 | """
461 | def return_replacement(replacement):
462 | CLASS_REPLACEMENTS[replacement] = replace
463 | return replacement
464 | tok = tokens[index]
465 | token_type = tok[0]
466 | token_string = tok[1]
467 | prev_tok = tokens[index-1]
468 | prev_tok_string = prev_tok[1]
469 | if token_type != tokenize.NAME:
470 | return None # Skip this token
471 | if token_string.startswith('__'):
472 | return None
473 | if prev_tok_string != '.':
474 | if token_string == replace:
475 | return return_replacement(replacement)
476 |
477 | def obfuscate_unique(tokens, index, replace, replacement, *args):
478 | """
479 | If the token string (a unique value anywhere) inside *tokens[index]*
480 | matches *replace*, return *replacement*.
481 |
482 | .. note::
483 |
484 | This function is only for replacing absolutely unique ocurrences of
485 | *replace* (where we don't have to worry about their position).
486 | """
487 | def return_replacement(replacement):
488 | UNIQUE_REPLACEMENTS[replacement] = replace
489 | return replacement
490 | tok = tokens[index]
491 | token_type = tok[0]
492 | token_string = tok[1]
493 | if token_type != tokenize.NAME:
494 | return None # Skip this token
495 | if token_string == replace:
496 | return return_replacement(replacement)
497 |
498 | def remap_name(name_generator, names, table=None):
499 | """
500 | Produces a series of variable assignments in the form of::
501 |
502 | =
503 |
504 | for each item in *names* using *name_generator* to come up with the
505 | replacement names.
506 |
507 | If *table* is provided, replacements will be looked up there before
508 | generating a new unique name.
509 | """
510 | out = ""
511 | for name in names:
512 | if table and name in table[0].keys():
513 | replacement = table[0][name]
514 | else:
515 | replacement = next(name_generator)
516 | out += "%s=%s\n" % (replacement, name)
517 | return out
518 |
519 | def insert_in_next_line(tokens, index, string):
520 | """
521 | Inserts the given string after the next newline inside tokens starting at
522 | *tokens[index]*. Indents must be a list of indentation tokens that will
523 | preceeed the insert (can be an empty list).
524 | """
525 | tokenized_string = token_utils.listified_tokenizer(string)
526 | for i, tok in list(enumerate(tokens[index:])):
527 | token_type = tok[0]
528 | if token_type in [tokenize.NL, tokenize.NEWLINE]:
529 | for count, item in enumerate(tokenized_string):
530 | tokens.insert(index+count+i+1, item)
531 | break
532 |
533 | def obfuscate_builtins(module, tokens, name_generator, table=None):
534 | """
535 | Inserts an assignment, ' = ' at
536 | the beginning of *tokens* (after the shebang and encoding if present) for
537 | every Python built-in function that is used inside *tokens*. Also, replaces
538 | all of said builti-in functions in *tokens* with each respective obfuscated
539 | identifer.
540 |
541 | Obfuscated identifier names are pulled out of name_generator via next().
542 |
543 | If *table* is provided, replacements will be looked up there before
544 | generating a new unique name.
545 | """
546 | used_builtins = analyze.enumerate_builtins(tokens)
547 | obfuscated_assignments = remap_name(name_generator, used_builtins, table)
548 | replacements = []
549 | for assignment in obfuscated_assignments.split('\n'):
550 | replacements.append(assignment.split('=')[0])
551 | replacement_dict = dict(zip(used_builtins, replacements))
552 | if table:
553 | table[0].update(replacement_dict)
554 | iter_replacements = iter(replacements)
555 | for builtin in used_builtins:
556 | replace_obfuscatables(
557 | module, tokens, obfuscate_unique, builtin, iter_replacements)
558 | # Check for shebangs and encodings before we do anything else
559 | skip_tokens = 0
560 | matched_shebang = False
561 | matched_encoding = False
562 | for tok in tokens[0:4]: # Will always be in the first four tokens
563 | line = tok[4]
564 | if analyze.shebang.match(line): # (e.g. '#!/usr/bin/env python')
565 | if not matched_shebang:
566 | matched_shebang = True
567 | skip_tokens += 1
568 | elif analyze.encoding.match(line): # (e.g. '# -*- coding: utf-8 -*-')
569 | if not matched_encoding:
570 | matched_encoding = True
571 | skip_tokens += 1
572 | insert_in_next_line(tokens, skip_tokens, obfuscated_assignments)
573 |
574 | def obfuscate_global_import_methods(module, tokens, name_generator, table=None):
575 | """
576 | Replaces the used methods of globally-imported modules with obfuscated
577 | equivalents. Updates *tokens* in-place.
578 |
579 | *module* must be the name of the module we're currently obfuscating
580 |
581 | If *table* is provided, replacements for import methods will be attempted
582 | to be looked up there before generating a new unique name.
583 | """
584 | global_imports = analyze.enumerate_global_imports(tokens)
585 | #print("global_imports: %s" % global_imports)
586 | local_imports = analyze.enumerate_local_modules(tokens, os.getcwd())
587 | #print("local_imports: %s" % local_imports)
588 | module_methods = analyze.enumerate_import_methods(tokens)
589 | #print("module_methods: %s" % module_methods)
590 | # Make a 1-to-1 mapping dict of module_method<->replacement:
591 | if table:
592 | replacement_dict = {}
593 | for module_method in module_methods:
594 | if module_method in table[0].keys():
595 | replacement_dict.update({module_method: table[0][module_method]})
596 | else:
597 | replacement_dict.update({module_method: next(name_generator)})
598 | # Update the global lookup table with the new entries:
599 | table[0].update(replacement_dict)
600 | else:
601 | method_map = [next(name_generator) for i in module_methods]
602 | replacement_dict = dict(zip(module_methods, method_map))
603 | import_line = False
604 | # Replace module methods with our obfuscated names in *tokens*
605 | for module_method in module_methods:
606 | for index, tok in enumerate(tokens):
607 | token_type = tok[0]
608 | token_string = tok[1]
609 | if token_type != tokenize.NAME:
610 | continue # Speedup
611 | tokens[index+1][1]
612 | if token_string == module_method.split('.')[0]:
613 | if tokens[index+1][1] == '.':
614 | if tokens[index+2][1] == module_method.split('.')[1]:
615 | if table: # Attempt to use an existing value
616 | tokens[index][1] = table[0][module_method]
617 | tokens[index+1][1] = ""
618 | tokens[index+2][1] = ""
619 | else:
620 | tokens[index][1] = replacement_dict[module_method]
621 | tokens[index+1][1] = ""
622 | tokens[index+2][1] = ""
623 | # Insert our map of replacement=what after each respective module import
624 | for module_method, replacement in replacement_dict.items():
625 | indents = []
626 | index = 0
627 | for tok in tokens[:]:
628 | token_type = tok[0]
629 | token_string = tok[1]
630 | if token_type == tokenize.NEWLINE:
631 | import_line = False
632 | elif token_type == tokenize.INDENT:
633 | indents.append(tok)
634 | elif token_type == tokenize.DEDENT:
635 | indents.pop()
636 | elif token_string == "import":
637 | import_line = True
638 | elif import_line:
639 | if token_string == module_method.split('.')[0]:
640 | # Insert the obfuscation assignment after the import
641 | imported_module = ".".join(module_method.split('.')[:-1])
642 | if table and imported_module in local_imports:
643 | line = "%s=%s.%s\n" % ( # This ends up being 6 tokens
644 | replacement_dict[module_method],
645 | imported_module,
646 | replacement_dict[module_method]
647 | )
648 | else:
649 | line = "%s=%s\n" % ( # This ends up being 6 tokens
650 | replacement_dict[module_method], module_method)
651 | for indent in indents: # Fix indentation
652 | line = "%s%s" % (indent[1], line)
653 | index += 1
654 | insert_in_next_line(tokens, index, line)
655 | index += 6 # To make up for the six tokens we inserted
656 | index += 1
657 |
658 | def obfuscate(module, tokens, options, name_generator=None, table=None):
659 | """
660 | Obfuscates *tokens* in-place. *options* is expected to be the options
661 | variable passed through from pyminifier.py.
662 |
663 | *module* must be the name of the module we're currently obfuscating
664 |
665 | If *name_generator* is provided it will be used to obtain replacement values
666 | for identifiers. If not, a new instance of
667 |
668 | If *table* is given (should be a list containing a single dictionary), it
669 | will be used to perform lookups of replacements and any new replacements
670 | will be added to it.
671 | """
672 | # Need a universal instance of our generator to avoid duplicates
673 | identifier_length = int(options.replacement_length)
674 | ignore_length = False
675 | if not name_generator:
676 | if options.use_nonlatin:
677 | ignore_length = True
678 | if sys.version_info[0] == 3:
679 | name_generator = obfuscation_machine(
680 | use_unicode=True, identifier_length=identifier_length)
681 | else:
682 | print(
683 | "ERROR: You can't use nonlatin characters without Python 3")
684 | else:
685 | name_generator = obfuscation_machine(
686 | identifier_length=identifier_length)
687 | if options.obfuscate:
688 | variables = find_obfuscatables(
689 | tokens, obfuscatable_variable, ignore_length=ignore_length)
690 | classes = find_obfuscatables(
691 | tokens, obfuscatable_class)
692 | functions = find_obfuscatables(
693 | tokens, obfuscatable_function)
694 | for variable in variables:
695 | replace_obfuscatables(
696 | module,
697 | tokens,
698 | obfuscate_variable,
699 | variable,
700 | name_generator,
701 | table
702 | )
703 | for function in functions:
704 | replace_obfuscatables(
705 | module,
706 | tokens,
707 | obfuscate_function,
708 | function,
709 | name_generator,
710 | table
711 | )
712 | for _class in classes:
713 | replace_obfuscatables(
714 | module, tokens, obfuscate_class, _class, name_generator, table)
715 | obfuscate_global_import_methods(module, tokens, name_generator, table)
716 | obfuscate_builtins(module, tokens, name_generator, table)
717 | else:
718 | if options.obf_classes:
719 | classes = find_obfuscatables(
720 | tokens, obfuscatable_class)
721 | for _class in classes:
722 | replace_obfuscatables(
723 | module,
724 | tokens,
725 | obfuscate_class,
726 | _class,
727 | name_generator,
728 | table
729 | )
730 | if options.obf_functions:
731 | functions = find_obfuscatables(
732 | tokens, obfuscatable_function)
733 | for function in functions:
734 | replace_obfuscatables(
735 | module,
736 | tokens,
737 | obfuscate_function,
738 | function,
739 | name_generator,
740 | table
741 | )
742 | if options.obf_variables:
743 | variables = find_obfuscatables(
744 | tokens, obfuscatable_variable)
745 | for variable in variables:
746 | replace_obfuscatables(
747 | module,
748 | tokens,
749 | obfuscate_variable,
750 | variable,
751 | name_generator,
752 | table
753 | )
754 | if options.obf_import_methods:
755 | obfuscate_global_import_methods(
756 | module, tokens, name_generator, table)
757 | if options.obf_builtins:
758 | obfuscate_builtins(module, tokens, name_generator, table)
759 |
760 | if __name__ == "__main__":
761 | global name_generator
762 | try:
763 | source = open(sys.argv[1]).read()
764 | except:
765 | print("Usage: %s " % sys.argv[0])
766 | sys.exit(1)
767 | if sys.version_info[0] == 3:
768 | name_generator = obfuscation_machine(use_unicode=True)
769 | else:
770 | name_generator = obfuscation_machine(identifier_length=1)
771 | source = apply_obfuscation(source)
772 | print(source)
773 |
--------------------------------------------------------------------------------
/pyminifier/token_utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 | __doc__ = """\
4 | A couple of functions for dealing with tokens generated by the `tokenize`
5 | module.
6 | """
7 |
8 | import tokenize
9 | try:
10 | import cStringIO as io
11 | except ImportError: # We're using Python 3
12 | import io
13 |
14 | def untokenize(tokens):
15 | """
16 | Converts the output of tokenize.generate_tokens back into a human-readable
17 | string (that doesn't contain oddly-placed whitespace everywhere).
18 |
19 | .. note::
20 |
21 | Unlike :meth:`tokenize.untokenize`, this function requires the 3rd and
22 | 4th items in each token tuple (though we can use lists *or* tuples).
23 | """
24 | out = ""
25 | last_lineno = -1
26 | last_col = 0
27 | for tok in tokens:
28 | token_string = tok[1]
29 | start_line, start_col = tok[2]
30 | end_line, end_col = tok[3]
31 | # The following two conditionals preserve indentation:
32 | if start_line > last_lineno:
33 | last_col = 0
34 | if start_col > last_col and token_string != '\n':
35 | out += (" " * (start_col - last_col))
36 | out += token_string
37 | last_col = end_col
38 | last_lineno = end_line
39 | return out
40 |
41 | def listified_tokenizer(source):
42 | """Tokenizes *source* and returns the tokens as a list of lists."""
43 | io_obj = io.StringIO(source)
44 | return [list(a) for a in tokenize.generate_tokens(io_obj.readline)]
45 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [bdist_rpm]
2 | release = 1
3 | packager = Dan McDougall
4 | vendor = Liftoff Software
5 | requires = python >= 2.6
6 | provides = pyminifier
7 | group = Applications/System
8 | doc_files = pyminifier/docs/build/html
9 | install_script = install-rpm.sh
10 |
11 | [install]
12 | # This is necessary to prevent *.pyo files from messing up bdist_rpm:
13 | optimize = 1
14 | # install-data=$HOME
15 |
16 | [sdist_dsc]
17 | debian-version: 1
18 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import pyminifier
3 | from setuptools import setup
4 | from distutils.command.install import INSTALL_SCHEMES
5 |
6 | for scheme in INSTALL_SCHEMES.values():
7 | scheme['data'] = scheme['purelib']
8 |
9 | extra = {}
10 |
11 | if isinstance(sys.version_info, tuple):
12 | major = sys.version_info[0]
13 | else:
14 | major = sys.version_info.major
15 |
16 | if major == 2:
17 | from distutils.command.build_py import build_py
18 | elif major == 3:
19 | extra['use_2to3'] = True # Automatically convert to Python 3; love it!
20 | try:
21 | from distutils.command.build_py import build_py_2to3 as build_py
22 | except ImportError:
23 | print("Python 3.X support requires the 2to3 tool.")
24 | print(
25 | "It normally comes with Python 3.X but (apparenty) not on your "
26 | "distribution.\nPlease find out what package you need to get 2to3"
27 | "and install it.")
28 | sys.exit(1)
29 |
30 | cmdclass = {'build_py': build_py}
31 |
32 | setup(
33 | name="pyminifier",
34 | version=pyminifier.__version__,
35 | description="Python code minifier, obfuscator, and compressor",
36 | author=pyminifier.__author__,
37 | cmdclass=cmdclass,
38 | author_email="daniel.mcdougall@liftoffsoftware.com",
39 | url="https://github.com/liftoff/pyminifier",
40 | license="Proprietary",
41 | packages=['pyminifier'],
42 | classifiers=[
43 | "Environment :: Console",
44 | "Intended Audience :: Developers",
45 | "Intended Audience :: System Administrators",
46 | "Programming Language :: Python",
47 | "Programming Language :: Python :: 2",
48 | "Programming Language :: Python :: 2.6",
49 | "Programming Language :: Python :: 2.7",
50 | "Programming Language :: Python :: 3",
51 | "Programming Language :: Python :: 3.1",
52 | "Programming Language :: Python :: 3.2",
53 | "Programming Language :: Python :: 3.3",
54 | "Programming Language :: Python :: 3.4",
55 | "License :: OSI Approved :: GNU Affero General Public License v3",
56 | "Topic :: Software Development :: Build Tools",
57 | "Topic :: Software Development :: Libraries :: Python Modules",
58 | ],
59 | provides=['pyminifier'],
60 | entry_points = {
61 | 'console_scripts': [
62 | 'pyminifier = pyminifier.__main__:main'
63 | ],
64 | },
65 | test_suite = "tests",
66 | **extra
67 | )
68 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/liftoff/pyminifier/087ea7b0c8c964f1f907c3f350f5ce281798db86/tests/__init__.py
--------------------------------------------------------------------------------
/tests/test_minification.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | import unittest
4 | import subprocess
5 | import tempfile
6 | import os
7 | import shutil
8 |
9 | testdir = os.path.abspath(os.path.split(__file__)[0])
10 | maindir = os.path.dirname(testdir)
11 |
12 |
13 | class TestPyMinify(unittest.TestCase):
14 | def setUp(self):
15 | self._testdir = tempfile.mkdtemp()
16 | self.testdir = os.path.join(self._testdir, 'pyminifier')
17 | os.mkdir(self.testdir)
18 | self.sourcedir = os.path.join(maindir, 'pyminifier')
19 |
20 | def minimy_file(self, inpath, cwd):
21 | proc = subprocess.Popen(
22 | ['pyminifier', inpath], cwd=cwd, stdout=subprocess.PIPE)
23 | data, err = proc.communicate()
24 | assert err is None
25 | return data
26 |
27 | def test_minify_self(self):
28 | """
29 | Test if a minified version of 'pyminifier' returns the same results as
30 | the original one
31 | """
32 | sourcefiles = [
33 | filename for filename
34 | in os.listdir(self.sourcedir) if filename.endswith('.py')]
35 | results = {}
36 |
37 | for filename in sourcefiles:
38 | source = os.path.join(self.sourcedir, filename)
39 | dest = os.path.join(self.testdir, filename)
40 | data = self.minimy_file(source, maindir)
41 | results[filename] = data
42 |
43 | with open(dest, 'wb') as destfile:
44 | destfile.write(data)
45 |
46 | for filename in sourcefiles:
47 | source = os.path.join(self.sourcedir, filename)
48 | res = self.minimy_file(source, cwd=self._testdir)
49 | self.assertEqual(res, results[filename])
50 |
51 | def tearDown(self):
52 | """
53 | Clean up after ourselves
54 | """
55 | shutil.rmtree(self.testdir)
56 |
57 | if __name__ == '__main__':
58 | unittest.main()
59 |
--------------------------------------------------------------------------------