├── .github
└── workflows
│ └── test.yml
├── .gitignore
├── LICENSE
├── Makefile
├── README.org
├── docker
├── .emacs
└── Dockerfile
├── melpazoid.yml
├── melpazoid
├── melpazoid.el
└── melpazoid.py
├── pyproject.toml
└── setup.py
/.github/workflows/test.yml:
--------------------------------------------------------------------------------
1 | name: test
2 | on: [push, pull_request]
3 |
4 | jobs:
5 | build:
6 | runs-on: ubuntu-latest
7 | strategy:
8 | matrix:
9 | python-version: ["3.10"]
10 | steps:
11 | - uses: actions/checkout@v2
12 | - name: Set up Python ${{ matrix.python-version }}
13 | uses: actions/setup-python@v1
14 | with:
15 | python-version: ${{ matrix.python-version }}
16 | - name: Install
17 | run: |
18 | sudo apt-get install emacs
19 | emacs --version
20 | python -m pip install --upgrade pip
21 | pip install . mypy pytest ruff
22 | - name: Test
23 | run: make test-melpazoid
24 |
25 | - name: Test 'shx' Pull Request # a small package with few dependencies
26 | env:
27 | CI_BRANCH: master # always build the master branch for this repo
28 | EXIST_OK: true # we expect that it already exists on MELPA
29 | run: MELPA_PR_URL=https://github.com/melpa/melpa/pull/4749 make
30 |
31 | - name: Test 'kanban' Recipe # notably this is a Mercurial recipe
32 | env:
33 | CI_BRANCH: default # always build the default branch on this repo
34 | EXPECT_ERROR: 2 # we expect it to have some nags
35 | run: RECIPE='(kanban :fetcher hg :url "https://hg.sr.ht/~arnebab/kanban.el")' make
36 |
37 | - name: Test 'magit' Recipe # magit is a large recipe
38 | env:
39 | CI_BRANCH: main # always build the master branch on this repo
40 | EXPECT_ERROR: 2 # we expect it to have some nags
41 | run:
42 | RECIPE='(magit :fetcher github
43 | :repo "magit/magit"
44 | :files ("lisp/magit" "lisp/magit*.el" "lisp/git-rebase.el" "Documentation/magit.texi" "Documentation/AUTHORS.md" "LICENSE"
45 | (:exclude "lisp/magit-libgit.el")))'
46 | make
47 | - name: Test local 'melpazoid'
48 | env:
49 | CI_BRANCH: master
50 | run: python melpazoid/melpazoid.py . --license --recipe '(melpazoid :fetcher github :repo "riscy/melpazoid" :files ("melpazoid/melpazoid.el"))'
51 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | _requirements.el
2 | _reminders.json
3 | pkg
4 | *.elc
5 |
6 | .hypothesis
7 | .mypy_cache
8 | .pytest_cache
9 | __pycache__
--------------------------------------------------------------------------------
/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 |
635 | Copyright (C)
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 | Copyright (C)
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 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | IMAGE_NAME = melpazoid
2 | DOCKER ?= docker
3 | DOCKER_OPTIONS = --cap-drop all --security-opt=no-new-privileges --pids-limit=50
4 | DOCKER_OUTPUT ?= --progress=plain # e.g. '--progress=plain' xor '--quiet'
5 |
6 | .PHONY: run
7 | run:
8 | python3 melpazoid/melpazoid.py
9 |
10 | # https://cheatsheetseries.owasp.org/cheatsheets/Docker_Security_Cheat_Sheet.html
11 | .PHONY: test
12 | test: image
13 | @$(DOCKER) run --rm --network=none ${DOCKER_OPTIONS} ${IMAGE_NAME}
14 |
15 | .PHONY: term
16 | term: image
17 | $(DOCKER) run -it --rm --entrypoint=/bin/bash ${DOCKER_OPTIONS} ${IMAGE_NAME}
18 |
19 | .PHONY: image
20 | image:
21 | @$(DOCKER) build --build-arg PACKAGE_MAIN ${DOCKER_OUTPUT} \
22 | --tag ${IMAGE_NAME} -f docker/Dockerfile .
23 |
24 | .PHONY: test-melpazoid
25 | test-melpazoid:
26 | rm -rf _requirements.el
27 | mypy --strict --non-interactive --install-types melpazoid
28 | pytest --doctest-modules --durations=5
29 | ruff check . --extend-select=ISC001
30 | ruff format --check .
31 |
--------------------------------------------------------------------------------
/README.org:
--------------------------------------------------------------------------------
1 | #+TITLE: melpazoid 🤖
2 | #+OPTIONS: toc:3 author:t creator:nil num:nil
3 | #+AUTHOR: Chris Rayner
4 | #+EMAIL: dchrisrayner@gmail.com
5 |
6 | [[https://github.com/riscy/melpazoid/actions][https://github.com/riscy/melpazoid/workflows/test/badge.svg]]
7 |
8 | /melpazoid/ is a bundle of scripts for testing Emacs packages, primarily
9 | submissions to [[https://github.com/melpa/][MELPA]]. I've been using this to help check MELPA [[https://github.com/melpa/melpa/pulls][pull requests]].
10 |
11 | (Note: it is not necessary to use melpazoid to get your package on MELPA, but
12 | maybe it will help.)
13 |
14 | The ambition is checks that run in a "clean" environment, either through CI or
15 | through a container on your local machine. Feedback and pull requests are
16 | welcome ([[https://github.com/riscy/melpazoid/search?q=TODO&unscoped_q=TODO][search for TODO]]s, [[https://github.com/riscy/melpazoid/issues][raise an issue]])
17 |
18 | The checks are a combination of:
19 | 1. [[https://www.gnu.org/software/emacs/manual/html_node/elisp/Byte-Compilation.html#Byte-Compilation][byte-compile-file]]
20 | 2. [[https://www.emacswiki.org/emacs/CheckDoc][checkdoc]]
21 | 3. [[https://github.com/purcell/package-lint][package-lint]]
22 | 4. a license checker (in [[https://github.com/riscy/melpazoid/blob/master/melpazoid/melpazoid.py][melpazoid.py]])
23 | 5. some elisp checks (in [[https://github.com/riscy/melpazoid/blob/master/melpazoid/melpazoid.el][melpazoid.el]])
24 |
25 | 1--4 are on the [[https://github.com/melpa/melpa/blob/master/.github/PULL_REQUEST_TEMPLATE.md][MELPA checklist]]. Normally the build will exit with a failure if
26 | there is any byte-compile or package-lint =error= -- leeway is given for any
27 | =warning=. The license checker (4) is currently very crude. The elisp checks (5)
28 | are not foolproof, sometimes opinionated, and may raise false positives.
29 |
30 | * Usage
31 | You can add melpazoid to your CI and use it locally.
32 | ** Add it to GitHub actions
33 | The very easiest is if your package is hosted on GitHub. Just run the
34 | following from your project root:
35 | #+begin_src bash
36 | mkdir -p .github/workflows
37 | curl -o .github/workflows/melpazoid.yml \
38 | https://raw.githubusercontent.com/riscy/melpazoid/master/melpazoid.yml
39 | #+end_src
40 | then edit the file (~.github/workflows/melpazoid.yml~) and change the values
41 | of ~RECIPE~ and ~EXIST_OK~ to fit. Instructions are in the file.
42 | ** Use it locally
43 | You will need Python ≥ 3.6 and Docker. An image will be built with
44 | (hopefully) all of your requirements installed. By default, it will be run
45 | with no network access. The output scroll will report any discovered issues.
46 | *** Test an open MELPA PR
47 | If you've already opened a PR against MELPA, you can use the Makefile.
48 | #+begin_src bash
49 | MELPA_PR_URL=https://github.com/melpa/melpa/pull/6718 make
50 | #+end_src
51 | *** Test a recipe
52 | If you just have a recipe, you can use the Makefile:
53 | #+begin_src bash
54 | RECIPE='(shx :repo "riscy/shx-for-emacs" :fetcher github)' make
55 | #+end_src
56 | Note the apostrophes around the RECIPE. You can also test a specific branch:
57 | #+begin_src bash
58 | RECIPE='(shx :repo "riscy/shx-for-emacs" :fetcher github :branch "develop")' make
59 | #+end_src
60 | *** Test a recipe for a package on your machine
61 | Use the Makefile:
62 | #+begin_src bash
63 | RECIPE='(shx :repo "riscy/shx-for-emacs" :fetcher github)' \
64 | LOCAL_REPO='~/my-emacs-packages/shx-for-emacs' make
65 | #+end_src
66 | Instead of cloning from ~riscy/shx-for-emacs~ in this example, melpazoid
67 | will use the files in ~LOCAL_REPO~.
68 | *** Only test a package's licenses
69 | If you only wish to use melpazoid's (very basic) license checks, refer to the
70 | following examples:
71 |
72 | #+begin_src bash
73 | python3 melpazoid/melpazoid.py --license ../melpa/recipes/magit # a recipe file
74 | python3 melpazoid/melpazoid.py --license --recipe='(shx :repo "riscy/shx-for-emacs" :fetcher github)'
75 | #+end_src
76 | *** Run in an unending loop
77 | Just run melpazoid.py directly, or use ~make~ by itself.
78 |
--------------------------------------------------------------------------------
/docker/.emacs:
--------------------------------------------------------------------------------
1 | (add-to-list 'load-path (getenv "ELISP_PATH"))
2 | (package-initialize)
3 |
--------------------------------------------------------------------------------
/docker/Dockerfile:
--------------------------------------------------------------------------------
1 | # Based on:
2 | #
3 | FROM ubuntu:24.04
4 |
5 | RUN apt-get update \
6 | && apt-get -y install curl gnupg openssh-client wget \
7 | && apt-get -y --no-install-recommends install software-properties-common \
8 | && add-apt-repository ppa:ubuntuhandbook1/emacs \
9 | && apt-get -y install emacs emacs-common \
10 | && apt-get -y purge software-properties-common \
11 | && apt-get -y autoremove \
12 | && rm -rf /var/lib/apt/lists/* /root/.cache/*
13 |
14 | ENV WORKSPACE "/workspace"
15 | ENV ELISP_PATH "${WORKSPACE}/pkg"
16 |
17 | RUN useradd emacser -d $WORKSPACE \
18 | && mkdir -p $ELISP_PATH \
19 | && chown -R emacser $WORKSPACE
20 | USER emacser:emacser
21 |
22 | COPY _requirements.el $WORKSPACE
23 | RUN emacs --script $WORKSPACE/_requirements.el
24 |
25 | COPY --chown=emacser:emacser docker/.emacs $WORKSPACE
26 | COPY --chown=emacser:emacser pkg $ELISP_PATH
27 | COPY --chown=emacser:emacser melpazoid/melpazoid.el $ELISP_PATH
28 |
29 | ARG PACKAGE_MAIN
30 | ENV PACKAGE_MAIN "${PACKAGE_MAIN}"
31 |
32 | WORKDIR $ELISP_PATH
33 | CMD ["emacs", "--quick", "--batch", "--load=melpazoid.el"]
34 |
--------------------------------------------------------------------------------
/melpazoid.yml:
--------------------------------------------------------------------------------
1 | # melpazoid build checks.
2 |
3 | # If your package is on GitHub, enable melpazoid's checks by copying this file
4 | # to .github/workflows/melpazoid.yml and modifying RECIPE and EXIST_OK below.
5 |
6 | name: melpazoid
7 | on: [push, pull_request]
8 |
9 | jobs:
10 | build:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - uses: actions/checkout@v3
14 | - name: Set up Python 3.10
15 | uses: actions/setup-python@v4
16 | with:
17 | python-version: '3.10'
18 | - name: Install
19 | run: |
20 | python -m pip install --upgrade pip
21 | sudo apt-get install emacs && emacs --version
22 | git clone https://github.com/riscy/melpazoid.git ~/melpazoid
23 | pip install ~/melpazoid
24 | - name: Run
25 | env:
26 | LOCAL_REPO: ${{ github.workspace }}
27 | # RECIPE is your recipe as written for MELPA:
28 | RECIPE: (shx :fetcher github :repo "riscy/shx-for-emacs")
29 | # set this to false (or remove it) if the package isn't on MELPA:
30 | EXIST_OK: true
31 | run: echo $GITHUB_REF && make -C ~/melpazoid
32 |
--------------------------------------------------------------------------------
/melpazoid/melpazoid.el:
--------------------------------------------------------------------------------
1 | ;;; melpazoid.el --- A MELPA review tool -*- lexical-binding: t -*-
2 |
3 | ;; Authors: Chris Rayner (dchrisrayner@gmail.com)
4 | ;; Created: June 9 2019
5 | ;; Keywords: tools, convenience
6 | ;; URL: https://github.com/riscy/melpazoid
7 | ;; Package-Requires: ((emacs "25.1") (pkg-info "0.6") (epl "0.9"))
8 | ;; SPDX-License-Identifier: GPL-3.0-or-later
9 | ;; Version: 0.0.0
10 |
11 | ;;; Commentary:
12 |
13 | ;; A MELPA review tool to run the MELPA checklist in addition
14 | ;; to some other checks that might point to other issues.
15 |
16 | ;;; Code:
17 |
18 | ;; NOTE: avoid top-level "require"s - these can influence `melpazoid-byte-compile'
19 |
20 | (defconst melpazoid-buffer "*melpazoid*" "Name of the melpazoid buffer.")
21 | (defvar melpazoid-can-modify-buffers nil "Whether melpazoid can modify buffers.")
22 | (defvar melpazoid--pending "" "Text that will (maybe) be appended to the report.")
23 |
24 | (defun melpazoid-byte-compile (filename)
25 | "Wrapper for running `byte-compile-file' against FILENAME."
26 | (melpazoid-insert "\n⸺ `%s` with byte-compile using Emacs %s:"
27 | (file-name-nondirectory filename)
28 | emacs-version)
29 | (melpazoid--remove-no-compile)
30 | (ignore-errors (kill-buffer "*Compile-Log*"))
31 | (let ((inhibit-message t)
32 | (load-path (append (melpazoid--package-load-paths) load-path)))
33 | (byte-compile-file filename))
34 | (with-current-buffer (get-buffer-create "*Compile-Log*")
35 | (if (melpazoid--buffer-almost-empty-p)
36 | (melpazoid-discard-pending)
37 | (goto-char (point-min))
38 | (forward-line 2)
39 | (melpazoid-insert "```")
40 | (melpazoid-insert
41 | (melpazoid--newline-trim (buffer-substring (point) (point-max))))
42 | (melpazoid-insert "```")
43 | (melpazoid-commit-pending))))
44 |
45 | (defun melpazoid--remove-no-compile ()
46 | "Remove `no-byte-compile' directive.
47 | It should only be set to t for themes."
48 | (save-excursion
49 | (when melpazoid-can-modify-buffers
50 | (goto-char (point-min))
51 | (while (re-search-forward "no-byte-compile:[\s\t]*t" nil t)
52 | (delete-char -1)
53 | (insert "nil")
54 | (melpazoid-insert "- Temporarily ignoring `no-byte-compile` flag")
55 | (save-buffer)))))
56 |
57 | (defun melpazoid--package-load-paths ()
58 | "Return a list of package load-paths.
59 | Normally these would be resolved by `package-initialize', but
60 | running that function requires bringing in dependencies that can
61 | affect the output of `byte-compile-file'."
62 | (let ((package-paths nil)
63 | (package-user-dir (locate-user-emacs-file "elpa")))
64 | (dolist (subdir (directory-files package-user-dir))
65 | (unless (member subdir '("." ".." "archives"))
66 | (push (expand-file-name subdir package-user-dir) package-paths)))
67 | package-paths))
68 |
69 | (defun melpazoid--buffer-almost-empty-p ()
70 | "Return non-nil if current buffer is almost empty."
71 | (<= (- (point-max) (point)) 3))
72 |
73 | (defvar checkdoc-version)
74 | (defvar checkdoc-proper-noun-list)
75 | (defvar checkdoc-verb-check-experimental-flag)
76 | (defun melpazoid-checkdoc (filename)
77 | "Wrapper for running `checkdoc-file' against FILENAME."
78 | (require 'checkdoc)
79 | (melpazoid-insert "\n⸺ `%s` with checkdoc %s (fix *within reason*):"
80 | (file-name-nondirectory filename)
81 | checkdoc-version)
82 | (ignore-errors (kill-buffer "*Warnings*"))
83 | (let ((sentence-end-double-space nil) ; be a little more lenient
84 | (checkdoc-proper-noun-list nil)
85 | (checkdoc-verb-check-experimental-flag nil)
86 | (inhibit-message t))
87 | (checkdoc-file filename))
88 | (if (not (get-buffer "*Warnings*"))
89 | (melpazoid-discard-pending)
90 | (let* ((issues
91 | (with-current-buffer "*Warnings*"
92 | (buffer-substring (point-min) (point-max))))
93 | (issues (melpazoid--newline-trim issues))
94 | (issues (replace-regexp-in-string "^Warning (emacs): \n" "" issues)))
95 | (melpazoid-insert "```")
96 | (melpazoid-insert issues)
97 | (melpazoid-insert "```")
98 | (melpazoid-commit-pending))))
99 |
100 | (defvar package-archives)
101 | (defvar package-lint-main-file)
102 | (declare-function package-lint-current-buffer "ext:package-lint.el" t t)
103 | (declare-function pkg-info-format-version "ext:pkg-info.el" t t)
104 | (declare-function pkg-info-package-version "ext:pkg-info.el" t t)
105 | (defun melpazoid-package-lint ()
106 | "Wrapper for running `package-lint' against the current buffer."
107 | (require 'package)
108 | (add-to-list 'package-archives '("melpa" . "http://melpa.org/packages/"))
109 | (package-initialize)
110 | (require 'package-lint)
111 | (require 'pkg-info)
112 | (ignore-errors (kill-buffer "*Package-Lint*"))
113 | (let ((package-lint-main-file (melpazoid--package-lint-main-file)))
114 | (melpazoid-insert
115 | "\n⸺ `%s` with package-lint %s%s:"
116 | (buffer-name)
117 | (pkg-info-format-version (pkg-info-package-version "package-lint"))
118 | (if package-lint-main-file
119 | (format " and `package-lint-main-file` = %S" package-lint-main-file)
120 | "")
121 | (ignore-errors (package-lint-current-buffer))))
122 | (with-current-buffer (get-buffer-create "*Package-Lint*")
123 | (let ((issues
124 | (melpazoid--newline-trim (buffer-substring (point-min) (point-max)))))
125 | (if (or (string= "No issues found." issues) (string= "" issues))
126 | (melpazoid-discard-pending)
127 | (melpazoid-insert "```")
128 | (melpazoid-insert issues)
129 | (melpazoid-insert "```")
130 | (melpazoid-commit-pending)))))
131 |
132 | (defun melpazoid-elint ()
133 | "Experimental elint call."
134 | (melpazoid-insert "\nelint (experimental):")
135 | (ignore-errors (kill-buffer "*Elint*"))
136 | (elint-file (buffer-file-name))
137 | (with-current-buffer "*Elint*"
138 | (goto-char (point-min))
139 | (forward-line 3)
140 | (if (melpazoid--buffer-almost-empty-p)
141 | (melpazoid-discard-pending)
142 | (forward-line)
143 | (melpazoid-insert "```")
144 | (melpazoid-insert (buffer-substring (point) (point-max)))
145 | (melpazoid-insert "```")))
146 | (melpazoid-commit-pending))
147 |
148 | (defun melpazoid--package-lint-main-file ()
149 | "Return suitable value for `package-lint-main-file'."
150 | (let ((package-main (getenv "PACKAGE_MAIN")))
151 | (cond
152 | ((null package-main)
153 | nil)
154 | ((string= package-main "")
155 | nil)
156 | (t package-main))))
157 |
158 | (defun melpazoid-check-declare ()
159 | "Wrapper for `melpazoid' check-declare.
160 | NOTE: this sometimes backfires when running checks automatically inside
161 | a Docker container, e.g. kellyk/emacs does not include the .el files."
162 | (melpazoid-insert "\ncheck-declare-file (optional):")
163 | (ignore-errors (kill-buffer "*Check Declarations Warnings*"))
164 | (check-declare-file (buffer-file-name (current-buffer)))
165 | (with-current-buffer (get-buffer-create "*Check Declarations Warnings*")
166 | (if (melpazoid--buffer-almost-empty-p)
167 | (melpazoid-discard-pending)
168 | (melpazoid-insert "```")
169 | (melpazoid-insert (buffer-substring (point-min) (point-max)))
170 | (melpazoid-insert "```")
171 | (melpazoid-commit-pending))))
172 |
173 | (defun melpazoid-check-experimentals ()
174 | "Run miscs checker."
175 | (melpazoid-check-commentary)
176 | (melpazoid-check-sharp-quotes)
177 | (melpazoid-check-misc)
178 | (melpazoid-check-theme)
179 |
180 | (unless (equal melpazoid--pending "")
181 | (setq melpazoid--pending
182 | (format
183 | "\n⸺ `%s` with [melpazoid](https://github.com/riscy/melpazoid):\n```\n%s```\n"
184 | (buffer-name)
185 | melpazoid--pending))
186 | (melpazoid-commit-pending)))
187 |
188 | (defun melpazoid-check-theme ()
189 | "Check that the name given to autothemer matches the filename."
190 | ;; autothemer
191 | (save-excursion
192 | (goto-char (point-min))
193 | (while (re-search-forward
194 | "(autothemer-deftheme[[:space:]\n]+\\(\\<\\w+\\>\\)" nil t)
195 | (let ((autothemer-name (concat (match-string 1) "-theme"))
196 | (basename (file-name-base (buffer-file-name))))
197 | (unless (string= autothemer-name basename)
198 | (melpazoid--annotate-line
199 | (format "Theme `%s` does not match filename %s.el"
200 | autothemer-name basename)))))))
201 |
202 | (defun melpazoid-check-commentary ()
203 | "Check the commentary."
204 | (require 'lisp-mnt)
205 | (let ((filename (file-name-nondirectory (buffer-file-name)))
206 | (commentary (lm-commentary)))
207 | (when commentary
208 | (when (and
209 | (< (length commentary) 20)
210 | (string= filename (or (melpazoid--package-lint-main-file) filename)))
211 | (melpazoid-insert "- `;;; Commentary` in main file should not be a stub"))
212 | (when (let ((case-fold-search t)) (string-match "See .*README" commentary))
213 | (melpazoid-insert "- `;;; Commentary` should usually not redirect to README"))
214 | (with-temp-buffer
215 | (insert commentary)
216 | (goto-char 0)
217 | (if (re-search-forward ".\\{90\\}" nil t)
218 | (melpazoid-insert
219 | "- `;;; Commentary` is much wider than 80 characters"))
220 | (goto-char 0)
221 | (if (re-search-forward "^;; T[Oo][Dd][Oo]" nil t)
222 | (melpazoid-insert
223 | "- Separate TODOs from `;;; Commentary:` with a `;;; TODO:` section"))
224 | (goto-char 0)
225 | (if (re-search-forward "^;;;;" nil t)
226 | (melpazoid-insert
227 | "- `;;; Commentary` decoration like `;;;;...` will appear downstream"))))))
228 |
229 | (defun melpazoid-check-mixed-indentation ()
230 | "Check for a mix of tabs and spaces."
231 | (goto-char (point-min))
232 | (if (re-search-forward "^[\t]+[ ]+" nil t)
233 | (melpazoid--annotate-line
234 | "Mixed tab/space indentation, consider `(setq indent-tabs-mode nil)` in your personal config")))
235 |
236 | (defun melpazoid-check-sharp-quotes ()
237 | "Check for missing sharp quotes."
238 | (melpazoid-misc
239 | "#'(lambda " "There is no need to quote lambdas (neither #' nor ')")
240 | (melpazoid-misc
241 | "[^#]'(lambda " "Quoting this lambda may prevent it from being compiled")
242 | (let ((msg "It's safer to sharp-quote function names; use `#'`"))
243 | (melpazoid-misc "(apply-on-rectangle '[^,]" msg)
244 | (melpazoid-misc "(apply-partially '[^,]" msg)
245 | (melpazoid-misc "(apply '[^,]" msg)
246 | (melpazoid-misc "(cancel-function-timers '[^,]" msg)
247 | (melpazoid-misc "(seq-do '[^,]" msg)
248 | (melpazoid-misc "(seq-do-indexed '[^,]" msg)
249 | (melpazoid-misc "(seq-filter '[^,]" msg)
250 | (melpazoid-misc "(seq-mapcat '[^,]" msg)
251 | (melpazoid-misc "(seq-map '[^,]" msg)
252 | (melpazoid-misc "(seq-map-indexed '[^,]" msg)
253 | (melpazoid-misc "(seq-mapn '[^,]" msg)
254 | (melpazoid-misc "(mapconcat '[^,]" msg)
255 | (melpazoid-misc "(setq indent-line-function '[^,]" msg)
256 | (melpazoid-misc "(setq-local indent-line-function '[^,]" msg)
257 | (melpazoid-misc "(map-filter '[^,]" msg)
258 | (melpazoid-misc "(map-remove '[^,]" msg)
259 | (melpazoid-misc "(mapcar '[^,]" msg)
260 | (melpazoid-misc "(funcall '[^,]" msg)
261 | (melpazoid-misc "(cl-assoc-if '[^,]" msg)
262 | (melpazoid-misc "(call-interactively '" msg)
263 | (melpazoid-misc "(callf '[^,]" msg)
264 | (melpazoid-misc "(run-at-time[^(#]*[^#]'" msg)
265 | (melpazoid-misc "(seq-find '" msg)
266 | (melpazoid-misc "(add-hook '[^[:space:]]+ '[^(]" msg)
267 | (melpazoid-misc "(remove-hook '[^[:space:]]+ '" msg)
268 | (melpazoid-misc "(advice-add '[^#)]*)" msg)
269 | (melpazoid-misc "(advice-remove '[^#)]*)" msg)
270 | (melpazoid-misc "(defalias '[^#()]*)" msg)
271 | (melpazoid-misc "(define-obsolete-function-alias '[[:graph:]]+ '[[:graph:]]" msg)
272 | (melpazoid-misc "(run-with-idle-timer[^(#]*[^#]'" msg)))
273 |
274 | (defun melpazoid-check-picky ()
275 | "Miscellaneous checker (picky edition)."
276 | (melpazoid-check-mixed-indentation)
277 | (melpazoid-misc "^(autoload" "It may be simpler to just `require` this dependency") ; nofmt
278 | (melpazoid-misc "http://" "Prefer `https` over `http` if possible ([why?](https://news.ycombinator.com/item?id=22933774))" nil t t) ; nofmt
279 | (melpazoid-misc "(when (not " "Optionally use `unless ...` instead of `when (not ...)`") ; nofmt
280 | (melpazoid-misc "(when (null " "Optionally use `unless ...` instead of `when (null ...)`") ; nofmt
281 | (melpazoid-misc "line-number-at-pos" "line-number-at-pos is surprisingly slow - avoid it")
282 | (melpazoid-misc ")\n\n\n+(" "Prefer one blank line between this top-level form and the next") ; nofmt
283 | (melpazoid-misc ";; Package-Version" "Prefer `;; Version` over `;; Package-Version` (MELPA automatically adds `Package-Version`)" nil t nil t) ; nofmt
284 | (melpazoid-misc "^;;; Commentary:\n;;\n" "Use a blank line instead of `;;` by itself under your `;;; Commentary` header"))
285 |
286 | (defun melpazoid-check-misc ()
287 | "Miscellaneous checker."
288 | ;; comment style
289 | (melpazoid-misc "^ ;[^;]" "Single-line comments should usually begin with `;;`" t nil) ; nofmt
290 | (melpazoid-misc "\n;;; .*\n;;; " "Triple semicolons `;;;` are usually for section headings" t nil) ; no fmt
291 | (melpazoid-misc "\n.*lexical-binding:" "`lexical-binding` must be on the end of the first line" nil t)
292 | (melpazoid-misc "(with-temp-buffer (set-buffer " "Either `with-temp-buffer` or `set-buffer` is unnecessary here") ; nofmt
293 | (melpazoid-misc "Copyright.*Free Software Foundation" "Have you done the paperwork to assign this copyright?" nil t nil t) ; nofmt
294 | (melpazoid-misc "This file is part of GNU Emacs." "This may be a copy-paste error?" nil t nil t)
295 | (melpazoid-misc "`[A-Z]+'" "Only use back/front quotes to link to top-level elisp symbols" nil t t)
296 | (melpazoid-misc ";; fill-column:" "Prefer `byte-compile-docstring-max-column` over `fill-column`" nil t) ; nofmt
297 | ;; paths
298 | (melpazoid-misc "~/.emacs" "Could you use `user-emacs-directory` instead?" nil nil t) ; nofmt
299 | (melpazoid-misc "~/.emacs.el" "Could you use `user-emacs-directory` instead?" nil nil t) ; nofmt
300 | (melpazoid-misc "~/.emacs.d/init.el" "Could you use `user-emacs-directory` instead?" nil nil t) ; nofmt
301 | (melpazoid-misc "~/.config/emacs" "Could you use `user-emacs-directory` instead?" nil nil t) ; nofmt
302 | (melpazoid-misc "\"/tmp/" "Use `(temporary-file-directory)` instead of /tmp in code") ; nofmt
303 | ;; possible hacks
304 | (melpazoid-misc "^(fset" "Ensure this top-level `fset` isn't being used as a surrogate `defalias` or `define-obsolete-function-alias`") ; nofmt
305 | (melpazoid-misc "(fmakunbound" "`fmakunbound` should rarely occur in packages") ; nofmt
306 | (melpazoid-misc "(with-no-warnings" "Avoid `with-no-warnings` if the root cause can be addressed") ; nofmt
307 | (melpazoid-misc "([^ ]*read-string \"[^\"]+[^ \"]\")" "`read-string` prompts should often end with a space" t) ; nofmt
308 | (melpazoid-misc "(string-match[^(](symbol-name" "Prefer to use `eq` on symbols") ; nofmt
309 | (melpazoid-misc "(defcustom [^ ]*--" "Customizable variables shouldn't be private" t) ; nofmt
310 | ;; scoping
311 | (melpazoid-misc "(eval-when-compile (progn" "No `progn` required under `eval-when-compile`") ; nofmt
312 | (melpazoid-misc "(ignore-errors (progn" "No `progn` required under `ignore-errors`") ; nofmt
313 | (melpazoid-misc "(unless .+ (progn" "`unless` body does not need to be wrapped in `progn`") ; nofmt
314 | (melpazoid-misc "(ignore-errors (re-search-[fb]" "Use `re-search-*`'s NOERROR argument") ; nofmt
315 | (melpazoid-misc "(setq inhibit-read-only t" "Use `(let ((inhibit-read-only t)) ...)`") ; nofmt
316 | (melpazoid-misc "(ignore-errors (search-[fb]" "Use `search-*`'s NOERROR argument") ; nofmt
317 | (melpazoid-misc "(ignore-errors (require '" "Use `require`'s NOERROR argument") ; nofmt
318 | ;; simplified conditionals
319 | (melpazoid-misc "([<>eq/=]+ (point) (line-beginning-position))" "Could this point/line-beginning-position comparison use `bolp`?") ; nofmt
320 | (melpazoid-misc "([<>eq/=]+ (point) (line-end-position))" "Could this point/line-end-position comparison use `eolp`?") ; nofmt
321 | (melpazoid-misc "([<>eq/=]+ (point) (point-at-bol))" "Could this `point`/`point-at-bol` comparison use `bolp`?") ; nofmt
322 | (melpazoid-misc "([<>eq/=]+ (point) (point-at-eol))" "Could this `point`/`point-at-eol` comparison use `eolp`?") ; nofmt
323 | (melpazoid-misc "([<>eq/=]+ (point) (pos-bol))" "Could this `point`/`pos-bol` comparison use `bolp`?") ; nofmt
324 | (melpazoid-misc "([<>eq/=]+ (point) (pos-eol))" "Could this `point`/`pos-eol` comparison use `eolp`?") ; nofmt
325 | (melpazoid-misc "([<>eq/=]+ (point) (point-max))" "Could this `point`/`point-max` comparison use `eobp`?") ; nofmt
326 | (melpazoid-misc "([<>eq/=]+ (point) (point-min))" "Could this `point`/`point-min` comparison use `bobp`?") ; nofmt
327 | (melpazoid-misc "(goto-char (point-at-bol))" "Consider `beginning-of-line`")
328 | (melpazoid-misc "(goto-char (point-at-eol))" "Consider `end-of-line`")
329 | (melpazoid-misc "(goto-char (line-beginning-position))" "Consider `beginning-of-line`") ; nofmt
330 | (melpazoid-misc "(goto-char (line-end-position))" "Consider `end-of-line`")
331 | (melpazoid-misc "(goto-char (point-at-bol))" "Consider `beginning-of-line`") ; nofmt
332 | (melpazoid-misc "(goto-char (point-at-eol))" "Consider `end-of-line`")
333 | (melpazoid-misc "(progn (beginning-of-line) (point))" "Consider `line-beginning-position`") ; nofmt
334 | (melpazoid-misc "(progn (end-of-line) (point))" "Consider `point-at-eol`") ; nofmt
335 | ;; boolean expressions
336 | (melpazoid-misc "(eq [^()]*\\.*)" "You can use `not` or `null`")
337 | (melpazoid-misc "(not (not " "This double negation can be collapsed") ; nofmt
338 | (melpazoid-misc "(not (null " "This double negation can be collapsed (`not` aliases `null`)") ; nofmt
339 | (melpazoid-misc "(unless (not " "Use `when ...` instead of `unless (not ...)`") ; nofmt
340 | (melpazoid-misc "(unless (null " "Use `when ...` instead of `unless (null ...)`") ; nofmt
341 | ;; working with modes
342 | (melpazoid-misc "(equal major-mode \"" "Prefer e.g. `(derived-mode-p 'xyz)` over string comparison") ; nofmt
343 | (melpazoid-misc "(eq major-mode '" "You may want to consider `(derived-mode-p 'xyz)`") ; nofmt
344 | (melpazoid-misc "(setq mode-name \"" "`setq mode-name` is unnecessary if you use `define-derived-mode`") ; nofmt
345 | (melpazoid-misc "(string-equal major-mode" "Prefer `(derived-mode-p 'xyz)`")
346 | (melpazoid-misc "(string= major-mode" "Prefer `(derived-mode-p 'xyz)`")
347 | (melpazoid-misc "lighter \"[^\"]+ \"" "Lighter should start, but not end, with a space" t) ; nofmt
348 | (melpazoid-misc "lighter \"[^ \"]" "Lighter should start with a space" t)
349 | (melpazoid-misc "(setq auto-mode-alist" "Prefer `(add-to-list 'auto-mode-alist ...)`") ; nofmt
350 | (melpazoid-misc "(push '([^)]+) auto-mode-alist)" "Prefer `(add-to-list 'auto-mode-alist ...)`")
351 | ;; modifying Emacs on load
352 | ;; https://www.gnu.org/software/emacs/manual/html_node/elisp/Coding-Conventions.html
353 | (melpazoid-misc "^(add-hook" "Loading a package should rarely add hooks" nil t) ; nofmt
354 | (melpazoid-misc "(add-to-list 'auto-mode-alist.*\\$" "Terminate auto-mode-alist entries with `\\\\'`") ; nofmt
355 | (melpazoid-misc "^(advice-add" "Loading a package should not add advice" nil t) ; nofmt
356 | (melpazoid-misc "^(defadvice" "Loading a package should not add advice" nil t) ; nofmt
357 | (melpazoid-misc "^(setq " "Top-level `setq` should usually be replaced by `defvar` or `defconst`") ; nofmt
358 | (melpazoid-misc "^(setq-default " "Top-level `setq-default` should usually be replaced by `defvar-local`") ; nofmt
359 | (melpazoid-misc "^(make-variable-buffer-local" "Prefer `defvar-local`, or `defcustom` with `:local t`") ; nofmt
360 | ;; Keybindings
361 | ;; https://www.gnu.org/software/emacs/manual/html_node/elisp/Tips-for-Defining.html
362 | (melpazoid-misc "(global-set-key" "Don't set global bindings; tell users how in your `;;; Commentary`.") ; nofmt
363 | (melpazoid-misc "^(bind-keys" "Top-level `bind-keys` can overwrite bindings. Try: `(defvar my-map (let ((km (make-sparse-keymap))) (bind-keys ...) km))`") ; nofmt
364 | (melpazoid-misc "^(define-key" "Top-level `define-key` can overwrite bindings. Try: `(defvar my-map (let ((km (make-sparse-keymap))) (define-key ...) km))`") ; nofmt
365 | ;; f-strings
366 | (melpazoid-misc "format-time-string .*%+4Y-%m-%d" "Consider using %F instead of %+4Y-%m-%d in time strings" nil nil t) ; nofmt
367 | (melpazoid-misc "format-time-string .*%Y-%m-%d" "Consider using %F instead of %Y-%m-%d in time strings" nil nil t) ; nofmt
368 | (melpazoid-misc "format-time-string .*%H:%M:%S" "Consider using %T instead of %H:%M:%S in time strings" nil nil t) ; nofmt
369 | (melpazoid-misc "format-time-string .*%I:%M:%S %p" "Consider using %r instead of %I:%M:%S %p in time strings" nil nil t) ; nofmt
370 | (melpazoid-misc "format-time-string .*%m/%d/%y" "Consider using %D instead of %m/%d/%y in time strings" nil nil t) ; nofmt
371 | (melpazoid-misc "format-time.string .*%H:%M[^:]" "Consider using %R instead of %H:%M in time strings" nil nil t)
372 | (melpazoid-misc "(error (format " "No `format` required; `error` takes an f-string") ; nofmt
373 | (melpazoid-misc "(message (format " "No `format` required; `message` takes an f-string") ; nofmt
374 | (melpazoid-misc "(user-error (format " "No `format` required; `user-error` takes an f-string") ; nofmt
375 | (melpazoid-misc "(insert (concat" "`concat` may be unneeded; `insert` can take multiple arguments") ; nofmt
376 | (melpazoid-misc "(warn (format " "No `format` required; `warn` takes an f-string") ; nofmt
377 | ;; n.b. the opposite, (concat (format ...)), often can't be combined cleanly:
378 | (melpazoid-misc "(format (concat" "Can the `format` and `concat` be combined?") ; nofmt
379 | )
380 |
381 | (defun melpazoid-misc (regexp msg &optional no-smart-space include-comments include-strings case-insensitive)
382 | "If a search for REGEXP passes, report MSG as a misc check.
383 | If NO-SMART-SPACE is nil, use smart spaces -- i.e. replace all
384 | SPC characters in REGEXP with [[:space:]]+. If INCLUDE-COMMENTS
385 | then also scan comments for REGEXP; similar for INCLUDE-STRINGS.
386 | CASE-INSENSITIVE determines the case-sensitivity of the matches."
387 | (unless no-smart-space
388 | (setq regexp (replace-regexp-in-string " " "[[:space:]\n]+" regexp)))
389 | (save-excursion
390 | (goto-char (point-min))
391 | (let ((case-fold-search case-insensitive))
392 | (while (re-search-forward regexp nil t)
393 | (save-excursion
394 | (goto-char (match-beginning 0))
395 | (when (and
396 | (or include-comments (not (nth 4 (syntax-ppss))))
397 | (or include-strings (not (nth 3 (syntax-ppss)))))
398 | (melpazoid--annotate-line msg)))))))
399 |
400 | (defun melpazoid--annotate-line (msg)
401 | "Annotate the current line with MSG."
402 | (melpazoid-insert "- %s#L%s: %s"
403 | (file-name-nondirectory (buffer-file-name))
404 | (line-number-at-pos)
405 | msg))
406 |
407 | (defun melpazoid-insert (f-str &rest objects)
408 | "Insert string F-STR into the melpazoid output.
409 | OBJECTS are objects to interpolate into the string using `format'."
410 | (unless objects (setq f-str (replace-regexp-in-string "%" "%%" f-str)))
411 | (setq melpazoid--pending
412 | (concat melpazoid--pending (apply #'format f-str objects) "\n")))
413 |
414 | (defun melpazoid-discard-pending ()
415 | "Clear the current value in `melpazoid--pending'."
416 | (setq melpazoid--pending ""))
417 |
418 | (defun melpazoid-commit-pending ()
419 | "Commit whatever is accrued to the report with PREFIX and SUFFIX."
420 | (if noninteractive
421 | (send-string-to-terminal melpazoid--pending)
422 | (with-current-buffer (get-buffer-create melpazoid-buffer)
423 | (insert melpazoid--pending)))
424 | (melpazoid-discard-pending))
425 |
426 | (defun melpazoid--newline-trim (str)
427 | "Sanitize STR by removing newlines."
428 | (let* ((str (replace-regexp-in-string "[\n]+$" "" str))
429 | (str (replace-regexp-in-string "^[\n]+" "" str)))
430 | str))
431 |
432 | ;;;###autoload
433 | (defun melpazoid (&optional filename)
434 | "Check current buffer, or FILENAME's buffer if given."
435 | (interactive)
436 | (melpazoid--reset-state)
437 | (let ((filename (or filename (buffer-file-name (current-buffer)))))
438 | (save-window-excursion
439 | (set-buffer (find-file filename))
440 | (melpazoid-byte-compile filename)
441 | (melpazoid-checkdoc filename)
442 | ;; (melpazoid-check-declare)
443 | (melpazoid-package-lint)
444 | ;; (melpazoid-elint)
445 | (melpazoid-check-experimentals))
446 | (pop-to-buffer melpazoid-buffer)
447 | (goto-char (point-min))))
448 |
449 | (defun melpazoid--reset-state ()
450 | "Reset melpazoid's current state variables."
451 | (melpazoid-discard-pending)
452 | (ignore-errors (kill-buffer melpazoid-buffer)))
453 |
454 | (defun melpazoid--check-file-p (filename)
455 | "Return non-nil if FILENAME should be checked."
456 | (and
457 | (not (string= (file-name-base filename) "melpazoid"))
458 | (not (string-match ".*-pkg[.]el$" filename))
459 | (not (string-match "[.]el~$" filename)) ; file-name-extension misses these
460 | (not (string-match "^[.]#" filename)) ; file storing unsaved changes
461 | (string= (file-name-extension filename) "el")))
462 |
463 | (when noninteractive
464 | (setq melpazoid-can-modify-buffers t)
465 | (add-to-list 'load-path ".")
466 |
467 | (let (filenames)
468 | ;; Check every elisp file in `default-directory' (except melpazoid.el)
469 | (dolist (filename (directory-files "."))
470 | (when (melpazoid--check-file-p filename)
471 | (setq filenames (cons filename filenames))))
472 |
473 | ;; run byte-compile BEFORE other checks, because the other checks might
474 | ;; bring in arbitrary dependencies that will affect the compile runtime
475 | (dolist (filename filenames nil)
476 | (melpazoid-byte-compile filename))
477 | (dolist (filename filenames nil)
478 | (set-buffer (find-file filename))
479 | (melpazoid-package-lint))
480 | (dolist (filename filenames nil)
481 | (set-buffer (find-file filename))
482 | (melpazoid-check-experimentals))
483 | (dolist (filename filenames nil)
484 | (melpazoid-checkdoc filename))
485 |
486 | ;; check whether FILENAMEs can be simply loaded
487 | (let ((load-error nil))
488 | (melpazoid-insert "\n`#'load`-check on each file:")
489 | (melpazoid-insert "```")
490 | (dolist (filename filenames nil)
491 | (melpazoid-insert "Loading %s" filename)
492 | (condition-case err
493 | (load (expand-file-name filename) nil t t)
494 | (error
495 | (setq load-error t)
496 | (melpazoid-insert " %s:Error: Emacs %s:\n %S"
497 | filename emacs-version err))))
498 | (melpazoid-insert "```")
499 | (when load-error (melpazoid-commit-pending)))))
500 |
501 | (provide 'melpazoid)
502 | ;;; melpazoid.el ends here
503 |
--------------------------------------------------------------------------------
/melpazoid/melpazoid.py:
--------------------------------------------------------------------------------
1 | """
2 | usage: melpazoid.py [-h] [--license] [--recipe RECIPE] [target]
3 |
4 | positional arguments:
5 | target a recipe, a path to a recipe or package, or a MELPA PR URL
6 |
7 | optional arguments:
8 | -h, --help show this help message and exit
9 | --license only check licenses
10 | --recipe RECIPE a valid MELPA recipe
11 | """
12 |
13 | from __future__ import annotations
14 |
15 | __author__ = 'Chris Rayner '
16 | __license__ = 'SPDX-License-Identifier: GPL-3.0-or-later'
17 | import argparse
18 | import configparser
19 | import functools
20 | import json
21 | import operator
22 | import os
23 | import re
24 | import shlex
25 | import shutil
26 | import subprocess
27 | import sys
28 | import tempfile
29 | import time
30 | import urllib.error
31 | import urllib.request
32 | from pathlib import Path
33 | from typing import TYPE_CHECKING, Any, TextIO
34 |
35 | if TYPE_CHECKING:
36 | from collections.abc import Iterator
37 |
38 | _RETURN_CODE = 0 # eventual return code when run as script
39 | _MELPAZOID_ROOT = (Path(__file__).parent if '__file__' in vars() else Path.cwd()).parent
40 |
41 | # define the colors of the report (or none), per https://no-color.org
42 | # https://misc.flogisoft.com/bash/tip_colors_and_formatting
43 | NO_COLOR = os.environ.get('NO_COLOR', False)
44 | CLR_OFF = '' if NO_COLOR else '\033[0m'
45 | CLR_ERROR = '' if NO_COLOR else '\033[31m'
46 | CLR_WARN = '' if NO_COLOR else '\033[33m'
47 | CLR_INFO = '' if NO_COLOR else '\033[32m'
48 |
49 | MELPA_PR = r'https?://github.com/melpa/melpa/pull/([0-9]+)'
50 |
51 |
52 | def _return_code(return_code: int | None = None) -> int:
53 | """Return (and optionally set) the current return code.
54 | If return_code matches env var EXPECT_ERROR, return 0 --
55 | this is useful for running CI checks on melpazoid itself.
56 | """
57 | global _RETURN_CODE # noqa: PLW0603
58 | if return_code is not None:
59 | _RETURN_CODE = return_code
60 | expect_error = int(os.environ.get('EXPECT_ERROR', 0))
61 | return 0 if expect_error == _RETURN_CODE else _RETURN_CODE
62 |
63 |
64 | def is_recipe(recipe: str) -> bool:
65 | """Validate whether the recipe looks correct.
66 | >>> assert is_recipe('(abc :repo "xyz" :fetcher github) ; abc recipe!')
67 | >>> assert not is_recipe('(a/b :repo "xyz" :fetcher github)')
68 | >>> assert not is_recipe('??')
69 | """
70 | try:
71 | tokens = _tokenize_expression(recipe)
72 | except ValueError:
73 | return False
74 | len_minimal_recipe = 7 # 1 for name, 2 for repo, 2 for fetcher, 2 for parens
75 | if len(tokens) < len_minimal_recipe or tokens[0] != '(' or tokens[-1] != ')':
76 | return False
77 | if not re.match(r"[A-Za-z\-]", tokens[1]):
78 | return False
79 | try:
80 | return bool(_recipe_struct_elisp(recipe))
81 | except ChildProcessError:
82 | return False
83 |
84 |
85 | def _note(message: str, color: str = '', highlight: str = '') -> None:
86 | """Print a note, possibly in color, possibly highlighting specific text."""
87 | if highlight:
88 | print(re.sub(f"({highlight})", f"{color}\\g<1>{CLR_OFF}", message))
89 | else:
90 | print(f"{color}{message}{CLR_OFF}")
91 |
92 |
93 | def _fail(message: str, color: str = CLR_ERROR, highlight: str = '') -> None:
94 | _note(message, color, highlight)
95 | _return_code(2)
96 |
97 |
98 | def check_containerized_build(recipe: str, elisp_dir: Path) -> None:
99 | """Build a Docker container to run checks on elisp_dir, given a recipe."""
100 | if not is_recipe(recipe):
101 | _fail(f"Not a valid recipe: {recipe}")
102 | return
103 |
104 | files = [f.relative_to(elisp_dir) for f in _files_in_recipe(recipe, elisp_dir)]
105 | elisp_files = [file_.name for file_ in files if file_.name.endswith('.el')]
106 | if len(elisp_files) != len(set(elisp_files)):
107 | _fail(f"Multiple .el files with the same name: {' '.join(sorted(elisp_files))}")
108 | return
109 |
110 | pkg_dir = _MELPAZOID_ROOT / 'pkg'
111 | shutil.rmtree(pkg_dir, ignore_errors=True)
112 | for ii, file in enumerate(files):
113 | files[ii] = pkg_dir / (file.name if file.name.endswith('.el') else file)
114 | files[ii].parent.mkdir(parents=True, exist_ok=True)
115 | # shutil.copy/copytree won't work here because file can be a file or a dir:
116 | subprocess.run(['cp', '-r', str(elisp_dir / file), files[ii]], check=True)
117 | _write_requirements(files)
118 |
119 | _note(f"")
120 | run_env = dict(os.environ, DOCKER_OUTPUT='--quiet') # or --progress=plain
121 | cmd = ['make', '-C', str(_MELPAZOID_ROOT), 'image']
122 | subprocess.run(cmd, check=True, env=run_env)
123 |
124 | _note('\n')
125 | cmd = ['make', '-C', str(_MELPAZOID_ROOT), 'test']
126 | main_file = _main_file(files, recipe)
127 | if main_file and sum(f.name.endswith('.el') for f in pkg_dir.iterdir()) > 1:
128 | cmd.append(f"PACKAGE_MAIN={main_file.name}")
129 | run_result = subprocess.run(cmd, capture_output=True, check=False, env=run_env)
130 | lines = run_result.stdout.decode().strip().split('\n')
131 | if run_result.stderr:
132 | lines += ['\nStderr output while compiling/loading:']
133 | lines += ['```', run_result.stderr.decode().strip(), '```']
134 | for line in lines:
135 | # byte-compile-file writes ":Error: ", package-lint ": error: "
136 | if ':Error: ' in line or ': error: ' in line:
137 | _fail(line, highlight=r' ?[Ee]rror:')
138 | elif ':Warning: ' in line or ': warning: ' in line:
139 | _note(line, CLR_WARN, highlight=r' ?[Ww]arning:')
140 | elif line.startswith('### '):
141 | _note(line, CLR_INFO)
142 | elif not line.startswith('make[1]: Leaving directory'):
143 | print(line)
144 | print_packaging(recipe, elisp_dir)
145 |
146 |
147 | def _files_in_recipe(recipe: str, elisp_dir: Path) -> list[Path]:
148 | """Return a file listing, relative to elisp_dir.
149 | Raise ChildProcessError if the recipe does not work against elisp_dir.
150 | >>> _files_in_recipe('(melpazoid :fetcher github :repo "xyz")', Path('melpazoid'))
151 | [PosixPath('melpazoid/melpazoid.el')]
152 | """
153 | filenames = eval_elisp(
154 | f"""
155 | (require 'package-build)
156 | (setq package-build-working-dir "{elisp_dir.parent}")
157 | (setq rcp {_recipe_struct_elisp(recipe)})
158 | (send-string-to-terminal
159 | (mapconcat #'car (package-build-expand-files-spec rcp t) "\n"))
160 | """
161 | ).split('\n')
162 | files = [elisp_dir / filename for filename in filenames]
163 | return sorted(file for file in files if file.exists())
164 |
165 |
166 | def _default_recipe(recipe: str) -> str:
167 | """Simplify the given recipe by removing ':files'.
168 | >>> _default_recipe('(recipe :fetcher hg :repo "a/b" :branch na :files ("*.el"))')
169 | '(recipe :fetcher hg :repo "a/b" :branch na)'
170 | >>> _default_recipe('(recipe :fetcher hg :url "a/b")')
171 | '(recipe :fetcher hg :url "a/b")'
172 | """
173 | tokens = _tokenize_expression(recipe)
174 | fetcher = tokens.index(':fetcher')
175 | repo = tokens.index(':repo' if ':repo' in tokens else ':url')
176 | indices = [1, fetcher, fetcher + 1, repo, repo + 1]
177 | if ':branch' in tokens:
178 | branch = tokens.index(':branch')
179 | indices += [branch, branch + 1]
180 | return '(' + ' '.join(operator.itemgetter(*indices)(tokens)) + ')'
181 |
182 |
183 | def _tokenize_expression(expression: str) -> list[str]:
184 | """Turn an elisp expression into a list of tokens.
185 | Raise ValueError if the expression can't be parsed.
186 | >>> _tokenize_expression('(shx :repo "riscy/xyz" :fetcher github) ; comment')
187 | ['(', 'shx', ':repo', '"riscy/xyz"', ':fetcher', 'github', ')']
188 | """
189 | lexer = shlex.shlex(expression)
190 | lexer.quotes = '"'
191 | lexer.commenters = ';'
192 | lexer.wordchars = lexer.wordchars + "':-"
193 | tokens = list(lexer)
194 | unbalanced_parens = 0
195 | for t in tokens:
196 | if t == '(':
197 | unbalanced_parens += 1
198 | if t == ')':
199 | unbalanced_parens -= 1
200 | if unbalanced_parens < 0:
201 | break
202 | if unbalanced_parens == 0:
203 | return tokens
204 | raise ValueError(f"Unbalanced expression: {expression}")
205 |
206 |
207 | def package_name(recipe: str) -> str:
208 | """Return the package's name, based on the recipe.
209 | >>> package_name('(shx :files ...)')
210 | 'shx'
211 | """
212 | return _tokenize_expression(recipe)[1]
213 |
214 |
215 | def _main_file(files: list[Path], recipe: str) -> Path | None:
216 | """Figure out the 'main' file of the recipe, per MELPA convention.
217 | >>> _main_file([Path('pkg/a.el'), Path('pkg/b.el')], '(a :files ...)')
218 | PosixPath('pkg/a.el')
219 | >>> _main_file([Path('a.el'), Path('b.el')], '(b :files ...)')
220 | PosixPath('b.el')
221 | >>> _main_file([Path('a.el'), Path('a-pkg.el')], '(a :files ...)')
222 | PosixPath('a-pkg.el')
223 | """
224 | name = package_name(recipe)
225 | try:
226 | return next(
227 | el
228 | # the code in #'package-build--build-multi-file-package that
229 | # determines the 'main' file is not quite exposed but it first
230 | # looks for name-pkg.el, then name-pkg.el.in, and then name.el,
231 | # which happens to match sorted() order:
232 | for el in sorted(files)
233 | if el.name in (f"{name}-pkg.el", f"{name}-pkg.el.in", f"{name}.el")
234 | )
235 | except StopIteration:
236 | return None
237 |
238 |
239 | def _write_requirements(files: list[Path]) -> None:
240 | """Create a little elisp script that Docker will run as setup."""
241 | with Path('_requirements.el').open('w', encoding='utf-8') as requirements_el:
242 | requirements_el.write(
243 | f";; {time.strftime('%Y-%m-%d')} ; helps to invalidate old Docker cache\n\n"
244 | + ";; NOTE: emacs --script will set `load-file-name' to \n"
245 | + ";; which can disrupt the compilation of packages that use that variable:\n"
246 | + "(setq load-file-name nil)\n"
247 | + ";; (setq network-security-level 'low) ; expired certs last resort\n"
248 | + "(require 'package)\n"
249 | + "(package-initialize)\n"
250 | + """(add-to-list 'package-archives '("melpa" . "http://melpa.org/packages/"))\n"""
251 | + "(package-refresh-contents)\n"
252 | + "(setq package-install-upgrade-built-in t)\n"
253 | + "(package-install 'pkg-info)\n"
254 | + "(package-install 'package-lint)\n"
255 | )
256 | for req in requirements(files):
257 | req_, *version_maybe = req.split()
258 | version = version_maybe[0].strip('"') if version_maybe else 'N/A'
259 | if req_ == 'emacs':
260 | continue
261 | if '"' in req_: # common failure mode: misplaced quotation marks
262 | _fail(f"- Package names should not be quoted: `{req}`")
263 | continue
264 | if req_ == 'marginalia':
265 | _fail(
266 | "- Don't require marginalia: https://github.com/minad/marginalia#adding-custom-annotators-or-classifiers"
267 | )
268 | # always install the latest available version of the dependency.
269 | requirements_el.write(
270 | f'\n(message "Installing {req_} {version} or later")\n'
271 | + f"(ignore-errors (package-install (cadr (assq '{req_} package-archive-contents))))\n"
272 | )
273 |
274 |
275 | def requirements(files: list[Path]) -> set[str]:
276 | """Return (downcased) requirements given a listing of files.
277 | If a recipe is given, use it to determine which file is the main file;
278 | otherwise scan every .el file for requirements.
279 | """
280 | reqs: set[str] = set()
281 | for file_ in (f for f in files if f.is_file()):
282 | with file_.open(encoding='utf-8', errors='replace') as stream:
283 | try:
284 | if file_.name.endswith('-pkg.el'):
285 | reqs = reqs.union(_reqs_from_pkg_el(stream))
286 | elif file_.name.endswith('.el'):
287 | reqs = reqs.union(_reqs_from_el_file(stream))
288 | except ValueError as err:
289 | _fail(f"- Couldn't parse requirements in {file_.name}: {err}")
290 | return reqs
291 |
292 |
293 | def _reqs_from_pkg_el(pkg_el: TextIO) -> set[str]:
294 | """Pull the requirements out of a -pkg.el file.
295 | >>> import io
296 | >>> sorted(_reqs_from_pkg_el(io.StringIO(
297 | ... '''(define-package "x" "1.2" "A pkg." '(a (b "31.5")))''')))
298 | ['a', 'b "31.5"']
299 | """
300 | # TODO: fails if EXTRA-PROPERTIES args were given to #'define-package
301 | reqs = pkg_el.read()
302 | reqs = ' '.join(_tokenize_expression(reqs)[5:-1])
303 | reqs = reqs[reqs.find("' (") + 2 :]
304 | reqs = reqs[: reqs.find(') )') + 3]
305 | return {
306 | req.replace(')', '').strip().lower()
307 | for req in re.split('[()]', reqs)
308 | if req.strip()
309 | }
310 |
311 |
312 | def _reqs_from_el_file(el_file: TextIO) -> set[str]:
313 | """Hacky function to pull the requirements out of an elisp file.
314 | >>> import io
315 | >>> _reqs_from_el_file(io.StringIO(';; package-requires: ((emacs "24.4"))'))
316 | {'emacs "24.4"'}
317 | """
318 | # TODO: if Package-Requires crosses multiple lines, parsing will fail.
319 | # This is also currently an issue with package-lint (2024/09/02)
320 | for line in el_file:
321 | match = re.match(r'[; ]*Package-Requires[ ]*:[ ]*(.*)$', line, re.I)
322 | if match:
323 | _tokenize_expression(match.groups()[0])
324 | return {
325 | req.replace(')', '').strip().lower()
326 | for req in re.split('[()]', match.groups()[0])
327 | if req.strip()
328 | }
329 | return set()
330 |
331 |
332 | def _check_license_api(clone_address: str) -> bool:
333 | """Use the GitHub or GitLab API to check for a license.
334 | Return False if unable to check (e.g. it's not on GitHub).
335 | >>> _check_license_api('https://github.com/riscy/elfmt')
336 | True
337 | """
338 | repo_info = _repo_info_api(clone_address)
339 | if repo_info is None:
340 | return False
341 |
342 | license_ = repo_info.get('license')
343 | if not license_:
344 | _fail('- Add a LICENSE file to the repository')
345 | print(' See: https://github.com/licensee/licensee')
346 | return True
347 |
348 | gpl_compatible_licensee_licenses = {
349 | 'Apache License 2.0',
350 | 'BSD 2-Clause "Simplified" License',
351 | 'BSD 3-Clause "New" or "Revised" License',
352 | 'BSD Zero Clause License', # https://github.com/melpa/melpa/pull/7189
353 | 'Creative Commons Zero v1.0 Universal',
354 | 'Do What The F*ck You Want To Public License',
355 | 'GNU Affero General Public License v3.0',
356 | # re: GPL v2.0 see https://github.com/johannes-mueller/company-wordfreq.el/issues/6
357 | 'GNU General Public License v2.0 or later',
358 | 'GNU General Public License v3.0 only',
359 | 'GNU General Public License v3.0 or later',
360 | 'GNU General Public License v3.0',
361 | 'GNU Lesser General Public License v3.0',
362 | 'ISC License',
363 | 'MIT License',
364 | 'Mozilla Public License 2.0',
365 | 'The Unlicense',
366 | 'Vim License',
367 | }
368 |
369 | if license_.get('name') in gpl_compatible_licensee_licenses:
370 | pass
371 | elif license_.get('name') == 'Other':
372 | _note('- Try to use a standard license file format for your repo', CLR_WARN)
373 | print(' This helps detection tools like: https://github.com/licensee/licensee')
374 | else:
375 | _note(f"- License {license_.get('name')} may not be compatible", CLR_WARN)
376 | return True
377 |
378 |
379 | @functools.lru_cache
380 | def _repo_info_api(clone_address: str) -> dict[str, Any] | None:
381 | """Use the GitHub or GitLab API to fetch details about a repository.
382 | Raise urllib.error.URLError if API request fails.
383 | """
384 | repo_info: dict[str, Any]
385 | if clone_address.endswith('.git'):
386 | clone_address = clone_address[:-4]
387 | match = re.search(r'github.com/([^"]*)', clone_address, flags=re.I)
388 | if match:
389 | project_id = match.groups()[0].rstrip('/')
390 | repo_info = json.loads(_url_get(f"https://api.github.com/repos/{project_id}"))
391 | return repo_info
392 |
393 | match = re.search(r'gitlab.com/([^"]*)', clone_address, flags=re.I)
394 | if match:
395 | project_id = match.groups()[0].rstrip('/').replace('/', '%2F')
396 | gitlab_projects = 'https://gitlab.com/api/v4/projects'
397 | repo_info = json.loads(_url_get(f"{gitlab_projects}/{project_id}?license=true"))
398 | # HACK: align GitLab API response with typical GitHub api response
399 | repo_info['updated_at'] = repo_info['last_activity_at']
400 | repo_info['watchers_count'] = repo_info['star_count']
401 | return repo_info
402 |
403 | return None
404 |
405 |
406 | def _check_license_file(elisp_dir: Path) -> None:
407 | """Scan any COPYING or LICENSE files."""
408 | license_names = (
409 | 'copying',
410 | 'copying.txt',
411 | 'license',
412 | 'license.md',
413 | 'license.txt',
414 | 'licenses',
415 | 'unlicense',
416 | )
417 | has_license_file = False
418 | for license_ in elisp_dir.iterdir():
419 | # handles e.g. LICENSE.GPL, LICENSE.APACHE
420 | if not any(license_.name.lower().startswith(name) for name in license_names):
421 | continue
422 | has_license_file = True
423 | if license_.is_dir():
424 | licenses = ', '.join(f"`{f.name}`" for f in license_.iterdir())
425 | print(f"- {license_.name} directory: {licenses}")
426 | return
427 | with license_.open(encoding='utf-8', errors='replace') as stream:
428 | excerpt = ' '.join(stream.read(200).split())[:50]
429 | print(f"- {license_.name} excerpt: `{excerpt}`...")
430 | if not has_license_file:
431 | _fail('- Add a GPL-compatible LICENSE file to the repository')
432 |
433 |
434 | def _check_file_for_license_boilerplate(el_file: TextIO) -> str | None:
435 | """Check an elisp file for some license boilerplate.
436 | >>> import io
437 | >>> _check_file_for_license_boilerplate(io.StringIO('SPDX-License-Identifier: ISC'))
438 | 'ISC License'
439 | >>> _check_file_for_license_boilerplate(
440 | ... io.StringIO('This program is free software: you can redistribute it'))
441 | 'GPL*'
442 | """
443 | text = el_file.read()
444 | match = re.search(r'SPDX-License-Identifier:[ ]*(.+)', text, flags=re.I)
445 | if match:
446 | # TODO: one can AND and OR licenses together
447 | # https://spdx.github.io/spdx-spec/v2.3/SPDX-license-expressions/
448 | license_id = match.groups()[0]
449 | license_ = _spdx_license(license_id)
450 | if license_ is None:
451 | _fail(f"- Invalid SPDX id `{license_id}`; check https://spdx.dev/ids/")
452 | return None
453 | if not license_['isFsfLibre']:
454 | _fail(f"- Non-free/libre license: {match.groups()[0]}")
455 | return str(license_['name'])
456 |
457 | gpl_compatible_license_excerpts = {
458 | # NOTE: consider using https://github.com/emacscollective/elx instead
459 | 'Apache License 2.0': 'Licensed under the Apache License, Version 2.0',
460 | 'BSD*': 'Redistribution and use in source and binary forms',
461 | 'FSFAP': 'Copying and distribution of this file, with or without',
462 | 'GPL*': 'is free software.* you can redistribute it',
463 | '0BSD/ISC License': 'Permission to use, copy, modify, and/or distribute this',
464 | 'MIT License': 'Permission is hereby granted, free of charge, to any person',
465 | 'MPL-2': 'This source code form is subject to the terms of the Mozilla',
466 | 'The Unlicense': 'This is free and unencumbered software released into',
467 | }
468 | for license_key, license_text in gpl_compatible_license_excerpts.items():
469 | if re.search(license_text, text, re.IGNORECASE):
470 | return license_key
471 | return None
472 |
473 |
474 | @functools.lru_cache
475 | def _spdx_license(license_id: str) -> dict[str, Any] | None:
476 | for operator_ in (' OR ', ' AND ', ' WITH '):
477 | # the SPDX API does not handle SPDX expressions; take a stab at it here:
478 | if operator_ in license_id:
479 | _note(f"- Reviewer note: nontrivial SPDX license '{license_id}'", CLR_INFO)
480 | license_id = license_id.split(operator_)[0]
481 | break
482 | license_id = license_id.replace(' ', '-')
483 | try:
484 | response = _url_get(f'https://spdx.org/licenses/{license_id.strip()}.json')
485 | return dict(json.loads(response))
486 | except urllib.error.HTTPError:
487 | return None
488 |
489 |
490 | def print_packaging(recipe: str, elisp_dir: Path) -> None:
491 | """Print additional details (how it's licensed, what files, etc.)"""
492 | print('\n⸺ Package and license:')
493 | _check_recipe(recipe, elisp_dir)
494 | _check_package_requires(recipe, elisp_dir)
495 | _check_url(recipe, elisp_dir)
496 | _check_license(recipe, elisp_dir)
497 | _check_other(recipe, elisp_dir)
498 | _check_package_tags(recipe)
499 | for file_ in (_MELPAZOID_ROOT / 'pkg').rglob('*'):
500 | relpath = file_.relative_to(_MELPAZOID_ROOT)
501 | if file_.is_dir():
502 | continue
503 | with file_.open(encoding='utf-8', errors='replace') as stream:
504 | boilerplate = _check_file_for_license_boilerplate(stream)
505 | print(f"- {relpath}: {boilerplate or 'license unknown'}")
506 | if repo_info := _repo_info_api(_clone_address(recipe)):
507 | print('- Repository:', (repo_info['license'] or {}).get('name', 'Unlicensed'))
508 | if repo_info.get('archived'):
509 | _fail('- GitHub repository is archived')
510 |
511 |
512 | def _check_url(recipe: str, elisp_dir: Path) -> None:
513 | for file in _files_in_recipe(recipe, elisp_dir):
514 | if not file.name.endswith('.el') or file.name.endswith('-pkg.el'):
515 | continue
516 | with file.open(encoding='utf-8', errors='replace') as stream:
517 | text = stream.read()
518 | url_match = re.search(r';; URL:[ ]*(.+)', text, flags=re.I)
519 | if url_match:
520 | url = url_match.groups()[0]
521 | if not _url_ok(url):
522 | _fail(f"- Unreachable package URL in {file.name}: {url!r}")
523 |
524 |
525 | def _check_package_tags(recipe: str) -> None:
526 | # Example of rationale: https://github.com/melpa/melpa/pull/9074
527 | clone_address = _clone_address(recipe)
528 | if clone_address.endswith('.git'):
529 | clone_address = clone_address[:-4]
530 | if match := re.search(r'github.com/([^"]*)', clone_address, flags=re.I):
531 | repo = match.groups()[0].rstrip('/')
532 | if tags := json.loads(_url_get(f"https://api.github.com/repos/{repo}/tags")):
533 | reminder = f"- In case you haven't, ensure GitHub release {tags[0]['name']} is up-to-date with your current code and `Package-Version`"
534 | _note(reminder, CLR_WARN)
535 |
536 |
537 | def _check_other(recipe: str, elisp_dir: Path) -> None:
538 | files_in_recipe = _files_in_recipe(recipe, elisp_dir)
539 | if not any(file.name == f"{package_name(recipe)}.el" for file in files_in_recipe):
540 | _fail(f"- MELPA requires a file called {package_name(recipe)}.el")
541 | for file in files_in_recipe:
542 | if not file.name.endswith('.el'):
543 | continue
544 | relpath = file.relative_to(elisp_dir)
545 | if file.name == f"{package_name(recipe)}-pkg.el":
546 | _note(
547 | f"- {relpath} -- consider excluding; "
548 | + f"MELPA can create one from {package_name(recipe)}.el",
549 | CLR_WARN,
550 | )
551 | continue
552 | if file.name.endswith('-pkg.el'):
553 | _fail(f"- {relpath} -- files ending in `-pkg.el` are only for packaging")
554 | continue
555 | prefix = package_name(recipe)
556 | prefix = prefix[:-5] if prefix.endswith('-mode') else prefix
557 | if not re.match(f"^{prefix}[-.]", file.name):
558 | _fail(f"- {relpath} -- not in package namespace `{prefix}-`")
559 | with file.open(encoding='utf-8', errors='replace') as stream:
560 | try:
561 | header = stream.readline()
562 | header = header.split('-*-')[0]
563 | header = header.split(' --- ')[1]
564 | header = header.strip()
565 | except IndexError:
566 | _fail(f"- {relpath} -- no packaging header")
567 |
568 |
569 | def _check_license(recipe: str, elisp_dir: Path) -> None:
570 | if not _check_license_api(_clone_address(recipe)):
571 | _check_license_file(elisp_dir)
572 | for file in _files_in_recipe(recipe, elisp_dir):
573 | if not file.name.endswith('.el'):
574 | continue
575 | relpath = file.relative_to(elisp_dir)
576 | with file.open(encoding='utf-8', errors='replace') as stream:
577 | if not _check_file_for_license_boilerplate(stream):
578 | _fail(
579 | f"- {relpath} needs *formal* license boilerplate and/or an"
580 | + " [SPDX-License-Identifier](https://spdx.dev/ids/)"
581 | )
582 |
583 |
584 | def _check_recipe(recipe: str, elisp_dir: Path) -> None:
585 | files = _files_in_recipe(recipe, elisp_dir)
586 | for specifier in (':branch', ':commit', ':version-regexp'):
587 | if specifier in recipe:
588 | _note(f"- Avoid `{specifier}` in recipes except in unusual cases", CLR_WARN)
589 | if not _main_file(files, recipe):
590 | _fail(f"- No 'main' file found, e.g. '{package_name(recipe)}.el'")
591 | if ':url' in recipe and 'https://github.com' in recipe:
592 | _fail('- Use `:fetcher github :repo ` instead of `:url`')
593 | if ':repo' in recipe and recipe.index(':fetcher') > recipe.index(':repo'):
594 | _note('- Please specify `:fetcher` before `:repo` in your recipe', CLR_WARN)
595 | if ':url' in recipe and recipe.index(':fetcher') > recipe.index(':url'):
596 | _note('- Please specify `:fetcher` before `:url` in your recipe', CLR_WARN)
597 | if ':files' in recipe:
598 | try:
599 | files_default_recipe = _files_in_recipe(_default_recipe(recipe), elisp_dir)
600 | except ChildProcessError:
601 | _note(f"")
602 | files_default_recipe = []
603 | if files == files_default_recipe:
604 | _note(f"- Prefer default recipe: `{_default_recipe(recipe)}`", CLR_WARN)
605 | return
606 | if '"*.el"' in recipe and ':defaults' not in recipe:
607 | new_recipe = ' '.join(recipe.replace('"*.el"', ':defaults').split())
608 | if files == _files_in_recipe(new_recipe, elisp_dir):
609 | _note(f"- Prefer equivalent recipe: `{new_recipe}`", CLR_WARN)
610 | return
611 | _note('- Prefer :defaults instead of *.el, if possible')
612 | if '"*.el"' in recipe:
613 | _note(f"- Prefer `{package_name(recipe)}*.el` over `*.el`", CLR_WARN)
614 |
615 |
616 | def _check_package_requires(recipe: str, elisp_dir: Path) -> None:
617 | """Print the list of Package-Requires from the 'main' file.
618 | Report on any mismatches between this file and other files, since the ones
619 | in the other files will be ignored.
620 | """
621 | files = _files_in_recipe(recipe, elisp_dir)
622 | main_file = _main_file(files, recipe)
623 | if not main_file:
624 | _fail("- Can't check Package-Requires if there is no 'main' file")
625 | return
626 | main_file_requirements = requirements([main_file])
627 | for file in files:
628 | file_requirements = requirements([file])
629 | if file_requirements - main_file_requirements > set():
630 | _fail(
631 | f"- {main_file.name} must include all of the "
632 | + f"Package-Requires listed in {file.name}, including: "
633 | + ', '.join(sorted(file_requirements - main_file_requirements))
634 | )
635 | compat = next((r for r in main_file_requirements if r.startswith('compat ')), None)
636 | if compat:
637 | _note(f"- Reviewer note: this package depends on {compat}", CLR_INFO)
638 |
639 |
640 | def check_package_name(name: str) -> None:
641 | """Print list of similar, or at least similarly named, packages.
642 | Report any occurrences of invalid/reserved package names.
643 | This function will print nothing if there are no issues.
644 | """
645 | # is the package name implicitly reserved?
646 | reserved_names = (
647 | # used by distel
648 | '^erl$',
649 | '^derl$',
650 | '^epmd$',
651 | '^erlext$',
652 | '^mcase$',
653 | '^net-fsm$',
654 | # other
655 | '^git-rebase$',
656 | '^helm-source-',
657 | )
658 | name_reserved = any(re.match(reserved, name) for reserved in reserved_names)
659 | if name_reserved:
660 | print('\n⸺ Package name:')
661 | _fail(f"- Error: `{name}` is reserved\n", highlight='Error')
662 | return
663 |
664 | # is the package name an Emacs builtin?
665 | try:
666 | eval_elisp(f"(require '{name})")
667 | except ChildProcessError:
668 | pass
669 | else:
670 | print('\n⸺ Package name:')
671 | _fail(f"- Error: `{name}` is an Emacs builtin\n", highlight='Error')
672 | return
673 |
674 | # do other packages have the same name (within some magin)?
675 | emacsmirror = emacsmirror_packages()
676 | same_names = [name, f"{name}-mode"]
677 | same_names += [name[:-5]] if name.endswith('-mode') else []
678 | same_names += [name[:-1]] if name.endswith('s') else []
679 | same_names += ['org-' + name[3:]] if name.startswith('ox-') else []
680 | same_names += ['ox-' + name[4:]] if name.startswith('org-') else []
681 | same_names = [name_ for name_ in same_names if name_ in emacsmirror]
682 | resolved_same = {name_: url for name_, url in emacsmirror.items() if name_ == name}
683 | resolved_same.update(emacsattic_packages(*same_names))
684 | resolved_same.update(emacswiki_packages(*same_names))
685 | resolved_same.update(elpa_packages(*same_names))
686 | resolved_same.update(melpa_packages(*same_names))
687 | if resolved_same:
688 | print('\n⸺ Package name:')
689 | conflicting_packages = '\n'.join(
690 | f"- `{name_}` may already exist: {url}"
691 | for name_, url in resolved_same.items()
692 | )
693 | _fail(conflicting_packages + '\n')
694 | return
695 |
696 | # do other packages have similar names, especially namespace conflicts
697 | # (to save network calls, we only scan packages listed on emacsmirror):
698 | tokens = name.split('-')
699 | prefices = ['-'.join(tokens[: i + 1]) for i in range(len(tokens))]
700 | similar_names = { # packages that are implicitly a parent of 'name'
701 | name_: url
702 | for name_, url in emacsmirror.items()
703 | if any(name_ == prefix for prefix in prefices)
704 | }
705 | similar_names.update(
706 | { # packages that 'name' is implicitly a parent of
707 | name_: url
708 | for name_, url in emacsmirror.items()
709 | if name_.startswith(f"{name}-")
710 | }
711 | )
712 | if similar_names:
713 | similar_names.update(melpa_packages(*similar_names.keys()))
714 | similar_names.update(elpa_packages(*similar_names.keys()))
715 | print('\n⸺ Package name:')
716 | for name_, url in similar_names.items():
717 | print(f"- `{name_}` is similar: {url}")
718 |
719 |
720 | @functools.lru_cache
721 | def emacsattic_packages(*keywords: str) -> dict[str, str]:
722 | """(Obsolete) packages on Emacsattic matching 'keywords'.
723 | q.v. https://github.com/melpa/melpa/pull/8621#issuecomment-1616925395
724 | >>> emacsattic_packages('sos')
725 | {'sos': 'https://github.com/emacsattic/sos'}
726 | """
727 | packages = {kw: f"https://github.com/emacsattic/{kw}" for kw in keywords}
728 | return {kw: url for kw, url in packages.items() if _pkg_ok(url)}
729 |
730 |
731 | @functools.lru_cache
732 | def emacswiki_packages(*keywords: str) -> dict[str, str]:
733 | """Packages on emacswiki.org mirror matching 'keywords'.
734 | >>> emacswiki_packages('rss')
735 | {'rss': 'https://github.com/emacsmirror/emacswiki.org/blob/master/rss.el'}
736 | """
737 | packages = {}
738 | for keyword in set(keywords):
739 | el_file = keyword if keyword.endswith('.el') else keyword + '.el'
740 | pkg = f"https://github.com/emacsmirror/emacswiki.org/blob/master/{el_file}"
741 | if _pkg_ok(pkg):
742 | packages[keyword] = pkg
743 | return packages
744 |
745 |
746 | @functools.lru_cache
747 | def emacsmirror_packages() -> dict[str, str]:
748 | """All mirrored packages."""
749 | epkgs = 'https://raw.githubusercontent.com/emacsmirror/epkgs/master/.gitmodules'
750 | epkgs_parser = configparser.ConfigParser()
751 | epkgs_parser.read_string(_url_get(epkgs))
752 | return {
753 | epkg.split('"')[1]: data['url'] + ' (via emacsmirror)'
754 | for epkg, data in epkgs_parser.items()
755 | if epkg != 'DEFAULT'
756 | }
757 |
758 |
759 | @functools.lru_cache
760 | def elpa_packages(*keywords: str) -> dict[str, str]:
761 | """ELPA packages matching keywords.
762 | >>> elpa_packages('git-modes')
763 | {'git-modes (nongnu)': 'https://elpa.nongnu.org/nongnu/git-modes.html'}
764 | >>> sorted(elpa_packages('ivy'))
765 | ['ivy', 'ivy (devel)']
766 | """
767 | # q.v. http://elpa.gnu.org/packages/archive-contents
768 | elpa = 'https://elpa.gnu.org'
769 | nongnu_elpa = 'https://elpa.nongnu.org'
770 | sources = {
771 | # note: devel CAN have unique packages, e.g. shell-quasiquote (2025/02/12)
772 | **{f"{kw} (devel)": f"{elpa}/devel/{kw}.html" for kw in keywords},
773 | **{kw: f"{elpa}/packages/{kw}.html" for kw in keywords},
774 | **{f"{kw} (nongnu)": f"{nongnu_elpa}/nongnu/{kw}.html" for kw in keywords},
775 | }
776 | return {kw: url for kw, url in sources.items() if _pkg_ok(url)}
777 |
778 |
779 | @functools.lru_cache
780 | def melpa_packages(*keywords: str) -> dict[str, str]:
781 | """MELPA packages matching keywords.
782 | >>> melpa_packages('highlight-symbol')
783 | {'highlight-symbol': 'https://melpa.org/#/highlight-symbol'}
784 | """
785 | # q.v. 'http://melpa.org/archive.json'
786 | sources = {
787 | kw: f"https://github.com/melpa/melpa/blob/master/recipes/{kw}"
788 | for kw in keywords
789 | }
790 | return {
791 | kw: f"https://melpa.org/#/{kw}" for kw, url in sources.items() if _pkg_ok(url)
792 | }
793 |
794 |
795 | @functools.lru_cache
796 | def _pkg_ok(url: str) -> bool:
797 | """Cached wrapped around _url_ok."""
798 | return _url_ok(url)
799 |
800 |
801 | def check_melpa_recipe(recipe: str) -> None:
802 | """Check a MELPA recipe definition."""
803 | _return_code(0)
804 | with tempfile.TemporaryDirectory() as tmpdir:
805 | # package-build prefers the directory to be named after the package:
806 | elisp_dir = Path(tmpdir) / package_name(recipe)
807 | clone_address = _clone_address(recipe)
808 | local_repo = _local_repo()
809 | if local_repo:
810 | print(f"Using local repository at {local_repo}")
811 | shutil.copytree(local_repo, elisp_dir)
812 | check_containerized_build(recipe, elisp_dir)
813 | elif _clone(clone_address, elisp_dir, _branch(recipe), _fetcher(recipe)):
814 | check_containerized_build(recipe, elisp_dir)
815 |
816 |
817 | def check_license(recipe: str) -> None:
818 | """Check license for a given recipe."""
819 | # TODO: DRY up wrt check_melpa_recipe
820 | _return_code(0)
821 | with tempfile.TemporaryDirectory() as tmpdir:
822 | # package-build prefers the directory to be named after the package:
823 | elisp_dir = Path(tmpdir) / package_name(recipe)
824 | clone_address = _clone_address(recipe)
825 | local_repo = _local_repo()
826 | if local_repo:
827 | print(f"Using local repository at {local_repo}")
828 | shutil.copytree(local_repo, elisp_dir)
829 | _check_license(recipe, elisp_dir)
830 | elif _clone(clone_address, elisp_dir, _branch(recipe), _fetcher(recipe)):
831 | _check_license(recipe, elisp_dir)
832 |
833 |
834 | def _fetcher(recipe: str) -> str:
835 | """Get the 'fetcher' property from a recipe.
836 | >>> _fetcher('(recipe :repo a/b :fetcher hg)')
837 | 'hg'
838 | """
839 | tokenized_recipe = _tokenize_expression(recipe)
840 | return tokenized_recipe[tokenized_recipe.index(':fetcher') + 1]
841 |
842 |
843 | def _local_repo() -> Path | None:
844 | if not os.environ.get('LOCAL_REPO'):
845 | return None
846 | return Path.expanduser(Path(os.environ['LOCAL_REPO']))
847 |
848 |
849 | def _clone(repo: str, into: Path, branch: str | None, fetcher: str) -> bool:
850 | """Try to clone the repository; return whether we succeeded."""
851 | _note(f"")
852 |
853 | # check if we're being used in GitHub CI -- if so, modify the branch
854 | if not branch and 'RECIPE' in os.environ:
855 | branch = (
856 | os.environ.get('CI_BRANCH', '')
857 | or os.path.split(os.environ.get('GITHUB_REF', ''))[-1]
858 | or os.environ.get('TRAVIS_PULL_REQUEST_BRANCH', '')
859 | or os.environ.get('TRAVIS_BRANCH', '')
860 | )
861 | if branch:
862 | _note(f"CI workflow detected; using branch '{branch}'", CLR_INFO)
863 |
864 | into.mkdir()
865 | scm = 'hg' if fetcher == 'hg' else 'git'
866 | if scm == 'git':
867 | options = ['--single-branch']
868 | if branch:
869 | options += ['--branch', branch]
870 | if fetcher in {'github', 'gitlab', 'bitbucket'}:
871 | options += ['--depth', '1']
872 | elif scm == 'hg':
873 | options = ['--branch', branch if branch else 'default']
874 | scm_command = [scm, 'clone', *options, repo, str(into)]
875 | run_result = subprocess.run(scm_command, capture_output=True, check=False)
876 | if run_result.returncode != 0:
877 | _fail(f"Unable to clone:\n {' '.join(scm_command)}")
878 | _fail(run_result.stderr.decode())
879 | return False
880 | return True
881 |
882 |
883 | def _branch(recipe: str) -> str | None:
884 | """Return the recipe's branch if available, else the empty string.
885 | >>> _branch('(shx :branch "develop" ...)')
886 | 'develop'
887 | >>> assert _branch('(shx ...)') is None
888 | """
889 | tokenized_recipe = _tokenize_expression(recipe)
890 | if ':branch' not in tokenized_recipe:
891 | return None
892 | return tokenized_recipe[tokenized_recipe.index(':branch') + 1].strip('"')
893 |
894 |
895 | def check_melpa_pr(pr_url: str) -> None:
896 | """Check a PR on MELPA."""
897 | _return_code(0)
898 | match = re.match(MELPA_PR, pr_url)
899 | assert match
900 | changed_files = _pr_changed_files(pr_number=match.groups()[0])
901 |
902 | for changed_file in changed_files:
903 | filename = changed_file['filename']
904 | if not filename.startswith('recipes/'):
905 | _note(f"Skipping {filename} (file is not in ./recipes/)")
906 | continue
907 |
908 | if changed_file['status'] == 'removed':
909 | _note(f"Skipping {filename} (file was removed in this PR)")
910 | continue
911 |
912 | recipe = _url_get(changed_file['raw_url'])
913 | if Path(filename).name != package_name(recipe):
914 | _fail(f"'{filename}' does not match '{package_name(recipe)}'")
915 | continue
916 |
917 | try:
918 | _recipe_struct_elisp(recipe)
919 | except ChildProcessError as err:
920 | _fail(f"Invalid recipe in PR `{recipe.strip()}`: {err}")
921 | continue
922 |
923 | with tempfile.TemporaryDirectory() as tmpdir:
924 | # package-build prefers the directory to be named after the package:
925 | elisp_dir = Path(tmpdir) / package_name(recipe)
926 | if _clone(
927 | _clone_address(recipe),
928 | into=elisp_dir,
929 | branch=_branch(recipe),
930 | fetcher=_fetcher(recipe),
931 | ):
932 | check_containerized_build(recipe, elisp_dir)
933 | if os.environ.get('EXIST_OK', '').lower() != 'true':
934 | check_package_name(package_name(recipe))
935 | print('\n\n')
946 |
947 |
948 | @functools.lru_cache(maxsize=3) # cached to avoid rate limiting
949 | def _pr_changed_files(pr_number: str) -> list[dict[str, Any]]:
950 | """Get data from GitHub API."""
951 | pr_files_url = f"https://api.github.com/repos/melpa/melpa/pulls/{pr_number}/files"
952 | return list(json.loads(_url_get(pr_files_url)))
953 |
954 |
955 | def _prettify_recipe(recipe: str) -> str:
956 | # re: formatting see https://github.com/melpa/melpa/pull/8072
957 | return ' '.join(recipe.split()).replace(' :', '\n :')
958 |
959 |
960 | @functools.lru_cache
961 | def _clone_address(recipe: str) -> str:
962 | """Fetch the upstream repository URL for the recipe.
963 | Throw a ChildProcessError if Emacs encounters a problem.
964 | >>> _clone_address('(shx :repo "riscy/shx-for-emacs" :fetcher github)')
965 | 'https://github.com/riscy/shx-for-emacs'
966 | >>> _clone_address('(pmdm :fetcher hg :url "https://hg.serna.eu/emacs/pmdm")')
967 | 'https://hg.serna.eu/emacs/pmdm'
968 | """
969 | return eval_elisp(
970 | f"""
971 | (require 'package-recipe)
972 | (send-string-to-terminal
973 | (oref {_recipe_struct_elisp(recipe)} url))
974 | """
975 | )
976 |
977 |
978 | @functools.lru_cache
979 | def _recipe_struct_elisp(recipe: str) -> str:
980 | """Turn the recipe into a serialized 'package-recipe' object.
981 | Throw a ChildProcessError if Emacs encounters a problem.
982 | >>> _recipe_struct_elisp('(melpazoid :fetcher github :repo "xyz")')
983 | '#s(package-github-recipe "melpazoid" "https://github.com/xyz" "xyz" ...'
984 | """
985 | name = package_name(recipe)
986 | with tempfile.TemporaryDirectory() as tmpdir:
987 | (Path(tmpdir) / name).write_text(recipe, 'utf-8')
988 | return eval_elisp(
989 | f"""
990 | (require 'package-build)
991 | (require 'package-recipe)
992 | (setq package-build-recipes-dir "{tmpdir}")
993 | (send-string-to-terminal (format "%S" (package-recipe-lookup "{name}")))
994 | """
995 | )
996 |
997 |
998 | def eval_elisp(script: str) -> str:
999 | """Run an elisp script in a package-build context.
1000 | >>> eval_elisp('(send-string-to-terminal "Hello world")')
1001 | 'Hello world'
1002 | >>> eval_elisp("(require 'package-build) (require 'package-recipe)")
1003 | ''
1004 | """
1005 | with tempfile.TemporaryDirectory() as tmpdir:
1006 | for filename, content in _package_build_files().items():
1007 | (Path(tmpdir) / filename).write_text(content, 'utf-8')
1008 | script = f"""(progn (add-to-list 'load-path "{tmpdir}") {script})"""
1009 | result = subprocess.run(
1010 | ['emacs', '--quick', '--batch', '--eval', script],
1011 | capture_output=True,
1012 | check=False,
1013 | text=True,
1014 | )
1015 | if result.returncode != 0:
1016 | raise ChildProcessError(f"Emacs crashed ({result.stderr}) on: {script!r}")
1017 | return str(result.stdout.strip())
1018 |
1019 |
1020 | @functools.lru_cache
1021 | def _package_build_files() -> dict[str, str]:
1022 | """Grab the required package-build files from the MELPA repo."""
1023 | return {
1024 | filename: _url_get(
1025 | 'https://raw.githubusercontent.com/melpa/melpa/master/'
1026 | f"package-build/{filename}"
1027 | )
1028 | for filename in [
1029 | 'package-build-badges.el',
1030 | 'package-build.el',
1031 | 'package-recipe-mode.el',
1032 | 'package-recipe.el',
1033 | ]
1034 | }
1035 |
1036 |
1037 | def _check_loop() -> None:
1038 | """Check MELPA recipes and pull requests in a loop."""
1039 | while True:
1040 | try:
1041 | for target in _fetch_targets():
1042 | start = time.perf_counter()
1043 | if is_recipe(target):
1044 | _note(f"")
1045 | check_melpa_recipe(target)
1046 | elif re.match(MELPA_PR, target):
1047 | _note(f"")
1048 | check_melpa_pr(target)
1049 | if _return_code() != 0:
1050 | _fail(f'')
1051 | else:
1052 | _note(f'')
1053 | except KeyboardInterrupt: # noqa: PERF203
1054 | breakpoint() # noqa: T100
1055 |
1056 |
1057 | def _fetch_targets() -> Iterator[str]:
1058 | """Repeatedly yield PR URL's."""
1059 | previous_target = None
1060 | if shutil.which('pbpaste'):
1061 | print('Monitoring the clipboard for recipes and PRs...')
1062 | while True:
1063 | if shutil.which('pbpaste'):
1064 | possible_target = subprocess.check_output('pbpaste').decode()
1065 | else:
1066 | possible_target = input("Enter recipe or URL for MELPA PR: ")
1067 | target = None
1068 | melpa_pr_match = re.match(MELPA_PR, possible_target)
1069 | if melpa_pr_match:
1070 | target = melpa_pr_match.string[: melpa_pr_match.end()]
1071 | elif is_recipe(possible_target):
1072 | target = _prettify_recipe(possible_target)
1073 | if target and target != previous_target:
1074 | previous_target = target
1075 | yield target
1076 | time.sleep(1)
1077 |
1078 |
1079 | def _argparse_target(target: str) -> str:
1080 | """For near-term backward compatibility this parser just sets env vars."""
1081 | if re.match(MELPA_PR, target):
1082 | os.environ['MELPA_PR_URL'] = target
1083 | elif Path(target).is_file():
1084 | potential_recipe = Path(target).read_text('utf-8')
1085 | if not is_recipe(potential_recipe):
1086 | raise argparse.ArgumentTypeError(f"{target!r} contains an invalid recipe")
1087 | os.environ['RECIPE'] = potential_recipe
1088 | elif Path(target).is_dir():
1089 | os.environ['LOCAL_REPO'] = target
1090 | else:
1091 | raise argparse.ArgumentTypeError(f"{target!r} must be a MELPA PR or local path")
1092 | return target
1093 |
1094 |
1095 | def _argparse_recipe(recipe: str) -> str:
1096 | """For near-term backward compatibility this parser just sets env vars."""
1097 | if not is_recipe(recipe):
1098 | raise argparse.ArgumentTypeError(f"{recipe!r} must be a valid MELPA recipe")
1099 | os.environ['RECIPE'] = recipe
1100 | return recipe
1101 |
1102 |
1103 | def _url_get(url: str, retry: int = 3) -> str:
1104 | if not url.startswith(('http://', 'https://')):
1105 | raise ValueError(url)
1106 | try:
1107 | with urllib.request.urlopen(url) as response: # noqa: S310
1108 | return str(response.read().decode())
1109 | except urllib.error.URLError as err:
1110 | if retry < 1:
1111 | raise
1112 | print(f'Retrying {url} in 10 seconds: {err}')
1113 | time.sleep(10)
1114 | return _url_get(url, retry - 1)
1115 |
1116 |
1117 | def _url_ok(url: str) -> bool:
1118 | if not url.startswith(('http://', 'https://')):
1119 | raise ValueError(url)
1120 | if ' ' in url:
1121 | return False
1122 | try:
1123 | with urllib.request.urlopen(
1124 | urllib.request.Request(
1125 | url, method='HEAD', headers={'User-Agent': 'Mozilla/5.0'}
1126 | )
1127 | ):
1128 | return True
1129 | except urllib.error.URLError:
1130 | return False
1131 |
1132 |
1133 | def _main() -> None:
1134 | parser = argparse.ArgumentParser()
1135 | target_help = 'a recipe, a path to a recipe or package, or a MELPA PR URL'
1136 | parser.add_argument('target', help=target_help, nargs='?', type=_argparse_target)
1137 | parser.add_argument('--license', help='only check licenses', action='store_true')
1138 | parser.add_argument('--recipe', help='a valid MELPA recipe', type=_argparse_recipe)
1139 | pargs = parser.parse_args()
1140 |
1141 | if pargs.license:
1142 | if not os.environ.get('RECIPE'):
1143 | _fail('Set a recipe using `target` or with: [--recipe RECIPE]')
1144 | return
1145 | check_license(os.environ['RECIPE'])
1146 | elif 'MELPA_PR_URL' in os.environ:
1147 | check_melpa_pr(os.environ['MELPA_PR_URL'])
1148 | elif 'RECIPE' in os.environ:
1149 | check_melpa_recipe(os.environ['RECIPE'])
1150 | elif 'LOCAL_REPO' in os.environ:
1151 | _fail('Set a recipe with: [--recipe RECIPE]')
1152 | else:
1153 | _check_loop()
1154 |
1155 |
1156 | if __name__ == '__main__':
1157 | _main()
1158 | sys.exit(_return_code())
1159 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = "melpazoid"
3 | requires-python = ">=3.10"
4 | dynamic = ["authors", "description", "license", "version"]
5 |
6 | [tool.ruff.format]
7 | quote-style = "preserve"
8 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | setup(
4 | name='melpazoid',
5 | version='0.0',
6 | description='For testing Emacs packages.',
7 | author='D. Chris Rayner',
8 | author_email='dchrisrayner@gmail.com',
9 | packages=['melpazoid'],
10 | license='GPL-3.0-or-later',
11 | url='https://github.com/riscy/melpazoid',
12 | )
13 |
--------------------------------------------------------------------------------