├── .gitignore
├── .gitmodules
├── ChangeLog.md
├── LICENSE
├── README.md
├── Setup.hs
├── TODO.org
├── default.nix
├── default.overrides.nix
├── elpa-devel-packages.sh
├── elpa-packages.sh
├── elpa2nix.hs
├── emacs2nix.cabal
├── hnix.nix
├── melpa-packages.sh
├── melpa-stable-packages.sh
├── melpa2nix.hs
├── names.nix
├── nixpkgs.lock.json
├── nixpkgs.nix
├── nongnu-devel-packages.sh
├── nongnu-packages.sh
├── package.nix
├── package.yaml
├── scripts
├── build.el
├── dump-recipes.el
└── elpa2json.el
├── shell-fetch.nix
├── shell.nix
├── shell.overrides.nix
└── src
├── Distribution
├── Bzr.hs
├── Elpa.hs
├── Emacs
│ └── Name.hs
├── Git.hs
├── Hg.hs
├── Melpa.hs
├── Melpa
│ ├── Fetcher.hs
│ ├── Melpa.hs
│ └── PkgInfo.hs
├── Nix
│ ├── Builtin.hs
│ ├── Exception.hs
│ ├── Fetch.hs
│ ├── Hash.hs
│ ├── Index.hs
│ ├── Name.hs
│ └── Package
│ │ ├── Elpa.hs
│ │ └── Melpa.hs
├── SVN.hs
└── Wiki.hs
├── Exceptions.hs
├── Exceptions
└── TH.hs
└── Process.hs
/.gitignore:
--------------------------------------------------------------------------------
1 | /dist/
2 | /Setup*
3 | *.prof
4 | /.shell.drv
5 | /.result*
6 | /dist-newstyle/
7 | .envrc
8 | TAGS
9 | tags
10 |
--------------------------------------------------------------------------------
/.gitmodules:
--------------------------------------------------------------------------------
1 | [submodule "hnix"]
2 | path = hnix
3 | url = https://github.com/jwiegley/hnix.git
4 |
--------------------------------------------------------------------------------
/ChangeLog.md:
--------------------------------------------------------------------------------
1 | # Revision history for melpa2nix
2 |
3 | ## 0.1.0.0 -- YYYY-mm-dd
4 |
5 | * First version. Released on an unsuspecting world.
6 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # emacs2nix
2 |
3 | Automatically generate Nix expressions for Emacs packages.
4 |
5 | Be sure to run
6 | ```
7 | git submodule update --init
8 | ```
9 | before building this package!
10 |
11 | The scripts `elpa-packages.sh`, `nongnu-packages.sh`, `nongnu-devel-packages.sh`,
12 | `melpa-packages.sh`, and `melpa-stable-packages.sh` regenerate each package
13 | set. They require Nix to build.
14 |
15 | To update the ELPA packages, run
16 | ```.bash
17 | # For ELPA packages
18 | ./elpa-packages.sh \
19 | -o $NIXPKGS/pkgs/applications/editors/emacs-modes/elpa-generated.nix \
20 | --names names.nix
21 | ```
22 | `$NIXPKGS` should be the path to the Nixpkgs clone which you are updating.
23 |
24 | To update the MELPA packages, run
25 | ```.bash
26 | # Use melpa-stable-packages.sh to update melpa-stable-generated.nix instead
27 | ./melpa-packages.sh \
28 | --melpa $MELPA \
29 | -o $NIXPKGS/pkgs/applications/editors/emacs-modes/melpa-generated.nix \
30 | --names names.nix
31 | ```
32 | `$MELPA` should be tho path to a clone of the [MELPA](https://github.com/milkypostman/melpa)
33 | repository.
34 |
35 | To run one of the `elpa2nix` or `melpa2nix` commands outside the shell script
36 | wrappers, first enter a Nix shell with the command
37 | ```
38 | nix-shell -A env
39 | ```
40 | which will ensure that all the runtime dependencies are present.
41 |
--------------------------------------------------------------------------------
/Setup.hs:
--------------------------------------------------------------------------------
1 | import Distribution.Simple
2 | main = defaultMain
3 |
--------------------------------------------------------------------------------
/TODO.org:
--------------------------------------------------------------------------------
1 | * DONE Check packages.json for hashes and avoid prefetching unchanged packages
2 | CLOSED: [2015-05-20 Wed 18:57]
3 | * DONE Keep repositories to avoid re-downloading just to get versions
4 | CLOSED: [2015-05-20 Wed 18:57]
5 | * DONE Use multiple threads
6 | CLOSED: [2015-05-20 Wed 18:57]
7 | * DONE Completely separate ELPA and MELPA packages
8 | CLOSED: [2015-08-21 Fri 12:26]
9 | * DONE Take an optional list of packages to update on the command line
10 | CLOSED: [2015-08-21 Fri 13:11]
11 | * DONE Re-use existing output
12 | CLOSED: [2015-08-21 Fri 13:45]
13 | * DONE Remove obsolete modules
14 | CLOSED: [2015-08-21 Fri 13:57]
15 | * DONE Generate packages from MELPA Stable
16 | CLOSED: [2015-08-21 Fri 14:16]
17 | * TODO Generate readable errors
18 | * TODO Don't complain if a package lacks a stable version
19 | * DONE Avoid changing recipe revision every time
20 |
21 | - State "DONE" from "TODO" [2018-06-08 Fri 09:56]
22 |
23 | The source file list is expanded from the recipe and passed to Git to limit the range of commits considered. For Git-based packages, the recipe and source revisions are changed only when the package is actually updated.
24 |
25 | * TODO Get package descriptions
26 | * DONE Get package licenses
27 |
28 | - State "DONE" from "TODO" [2018-06-08 Fri 09:56]
29 |
30 | All Emacs packages must be licensed GPL-3.
31 |
32 | * TODO Keep a bidirectional map of names
33 |
34 | A bidirectional map of names is useful to get Emacs names after parsing the package index from Nix. Keeping the map in the Nixpkgs tree makes it configurable.
35 |
36 | * TODO Define exceptions ad hoc
37 |
38 | * TODO Switch to async-pool
39 |
40 | melpa2nix spawns thousands of threads when it starts, using a semaphore to allow a select few to run at a time. Instead, use async-pool to establish a TaskGroup allowing only the selected number of threads to spawn at a time.
41 |
42 | * DONE Switch to hpack
43 |
44 | - State "DONE" from "TODO" [2018-06-08 Fri 16:17]
45 | The .cabal file is a mess of duplicated information. Switch to hpack for a clean package definition.
46 |
47 | * TODO Generate commit message and changelog
48 |
--------------------------------------------------------------------------------
/default.nix:
--------------------------------------------------------------------------------
1 | let nixpkgs = import ./nixpkgs.nix; in
2 |
3 | let
4 |
5 | inherit (nixpkgs) pkgs;
6 | inherit (pkgs) haskellPackages lib;
7 |
8 |
9 | blacklistDirs = [ ".git" "dist" "dist-newstyle" ];
10 | whitelistExts = [ ".cabal" ".el" ".hs" ];
11 | whitelistNames = [ "COPYING" "LICENSE" ];
12 |
13 | filterSrc =
14 | let
15 | overrideSrc = drv: f:
16 | let inherit (pkgs.haskell.lib) overrideCabal; in
17 | overrideCabal drv (args: args // { src = f args.src; });
18 | predicate = path: type:
19 | let inherit (lib) any elem hasSuffix; in
20 | let baseName = baseNameOf path; in
21 | if type == "directory"
22 | then !(elem baseName blacklistDirs)
23 | else any (suf: hasSuffix suf baseName) whitelistExts
24 | || any (name: baseName == name) whitelistNames;
25 | in
26 | drv: overrideSrc drv (src: builtins.filterSource predicate src);
27 |
28 | drv = filterSrc (haskellPackages.callPackage ./package.nix {});
29 |
30 | in
31 |
32 | drv
33 |
--------------------------------------------------------------------------------
/default.overrides.nix:
--------------------------------------------------------------------------------
1 | self: super:
2 | let lib = self.haskell.lib; in
3 | {
4 | haskellPackages = super.haskellPackages.override (args: {
5 | overrides = self: super:
6 | (args.overrides or (self: super: super)) self super // {
7 | # Tests cannot be run from Nix builder
8 | hnix = lib.dontCheck (self.callPackage ./hnix.nix {});
9 | ghc-heap-view = lib.disableLibraryProfiling super.ghc-heap-view;
10 | ghc-datasize = lib.disableLibraryProfiling super.ghc-datasize;
11 | };
12 | });
13 | }
14 |
--------------------------------------------------------------------------------
/elpa-devel-packages.sh:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env nix-shell
2 | #! nix-shell shell-fetch.nix -i bash
3 |
4 | # usage: ./elpa-packages.sh -o PATH
5 |
6 | elpa2nix https://elpa.gnu.org/devel/ "$@"
7 |
--------------------------------------------------------------------------------
/elpa-packages.sh:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env nix-shell
2 | #! nix-shell shell-fetch.nix -i bash
3 |
4 | # usage: ./elpa-packages.sh -o PATH
5 |
6 | elpa2nix https://elpa.gnu.org/packages/ "$@"
7 |
--------------------------------------------------------------------------------
/elpa2nix.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE DeriveDataTypeable #-}
22 | {-# LANGUAGE OverloadedStrings #-}
23 | {-# LANGUAGE RecordWildCards #-}
24 | {-# LANGUAGE ViewPatterns #-}
25 |
26 | module Main (main) where
27 |
28 | import Control.Arrow ( (>>>) )
29 | import Control.Concurrent ( setNumCapabilities )
30 | import Control.Concurrent.Async ( Concurrently(..) )
31 | import Control.Exception
32 | import Control.Monad ( join, when )
33 | import Data.Aeson ( FromJSON(..), json' )
34 | import Data.Aeson.Types ( parseEither )
35 | import Data.ByteString ( ByteString )
36 | import Data.Function ( (&) )
37 | import Data.HashMap.Strict ( HashMap )
38 | import Data.Map.Strict ( Map )
39 | import qualified Data.Map.Strict as M
40 | import Data.Maybe ( catMaybes )
41 | import Data.Monoid ((<>))
42 | import Data.Text ( Text )
43 | import qualified Data.Text as T
44 | import Data.Typeable ( Typeable )
45 | import Nix.Expr ( NExpr )
46 | import Options.Applicative
47 | import System.FilePath ( (>), (<.>) )
48 | import System.IO ( hClose )
49 | import qualified System.IO.Streams as S
50 | import qualified System.IO.Streams.Attoparsec as S
51 | import System.IO.Temp ( withSystemTempFile )
52 |
53 | import Paths_emacs2nix
54 |
55 | import Distribution.Elpa ( Elpa )
56 | import qualified Distribution.Elpa as Elpa
57 | import qualified Distribution.Emacs.Name as Emacs
58 | import qualified Distribution.Nix.Fetch as Nix
59 | import Distribution.Nix.Index
60 | import Distribution.Nix.Name ( Name )
61 | import qualified Distribution.Nix.Name as Nix
62 | import Distribution.Nix.Package.Elpa ( Package )
63 | import qualified Distribution.Nix.Package.Elpa as Nix
64 | import Exceptions
65 | import Process
66 |
67 | main :: IO ()
68 | main = join (execParser (info (helper <*> parser) desc))
69 | where
70 | desc = fullDesc <> progDesc "Generate Nix expressions from ELPA"
71 |
72 | parser :: Parser (IO ())
73 | parser =
74 | elpa2nix
75 | <$> (threads <|> pure 0)
76 | <*> output
77 | <*> server
78 | <*> names
79 | <*> indexOnly
80 | where
81 | threads = option auto
82 | (long "threads" <> short 't'
83 | <> metavar "N"
84 | <> help "use N threads; default is number of CPUs")
85 | output = strOption
86 | (long "output" <> short 'o'
87 | <> metavar "FILE"
88 | <> help "write output to FILE")
89 | server = strArgument
90 | (metavar "URL"
91 | <> help "get packages from server at URL")
92 | names = strOption
93 | (long "names"
94 | <> metavar "FILE"
95 | <> help "map Emacs package names to Nix package names using FILE")
96 | indexOnly = flag False True
97 | (long "index-only"
98 | <> help "don't update packages, only update the index file")
99 |
100 | elpa2nix :: Int -> FilePath -> String -> FilePath -> Bool -> IO ()
101 | elpa2nix threads output server namesMapFile indexOnly =
102 | catchPretty_ $ do
103 | when (threads > 0) (setNumCapabilities threads)
104 |
105 | namesMap <- Nix.readNames namesMapFile
106 | archives <- getPackages server
107 |
108 | updated <- if indexOnly
109 | then pure []
110 | else runConcurrently (traverse (updatePackage server namesMap) (M.toList archives))
111 |
112 | existing <- readIndex output
113 |
114 | let packages = M.union (M.fromList (catMaybes updated)) existing
115 |
116 | writeIndex output packages
117 |
118 | updatePackage :: String -> HashMap Emacs.Name Name -> (Text, Elpa)
119 | -> Concurrently (Maybe (Name, NExpr))
120 | updatePackage server namesMap elpa = Concurrently $ do
121 | hashed <- hashPackage server namesMap elpa
122 | pure (toExpression <$> hashed)
123 | where
124 | toExpression pkg = (Nix.pname pkg, Nix.expression pkg server)
125 |
126 | -- * Error types
127 |
128 | newtype ArchiveError = ArchiveError SomeException
129 | deriving (Show, Typeable)
130 |
131 | instance Exception ArchiveError
132 |
133 | -- * getPackages
134 |
135 | getPackages :: String -> IO (Map Text Elpa)
136 | getPackages uri = mapException ArchiveError $ do
137 | let args = [uri > "archive-contents"]
138 | withSystemTempFile "elpa2nix-archive-contents-" $ \path h -> do
139 | runInteractiveProcess "curl" args Nothing Nothing $ \out -> do
140 | tmp <- S.handleToOutputStream h >>= S.atEndOfOutput (hClose h)
141 | S.connect out tmp
142 | readArchive path
143 |
144 | -- * readArchive
145 |
146 | type InputByteStream = S.InputStream ByteString
147 |
148 | data ParseArchiveError = ParseArchiveError String
149 | deriving (Show, Typeable)
150 |
151 | instance Exception ParseArchiveError
152 |
153 | readArchive :: FilePath -> IO (Map Text Elpa)
154 | readArchive path = mapException ArchiveError $ do
155 | let
156 | args = ["--eval", eval]
157 | eval = "(print-archive-contents-as-json " ++ show path ++ ")"
158 | emacs args $ \out -> do
159 | result <- parseJsonFromStream out
160 | case result of
161 | Left parseError -> throwIO (ParseArchiveError parseError)
162 | Right pkgs -> pure pkgs
163 |
164 | emacs :: [String] -> (InputByteStream -> IO a) -> IO a
165 | emacs args go = do
166 | load <- getDataFileName "scripts/elpa2json.el"
167 | let
168 | args' = [ "-Q", "--batch", "--load", load ] ++ args
169 | runInteractiveProcess "emacs" args' Nothing Nothing go
170 |
171 | parseJsonFromStream :: FromJSON a => InputByteStream -> IO (Either String a)
172 | parseJsonFromStream stream = parseEither parseJSON <$> S.parseFromStream json' stream
173 |
174 | -- * hashPackage
175 |
176 | data DistNotImplemented = DistNotImplemented Text
177 | deriving (Show, Typeable)
178 |
179 | instance Exception DistNotImplemented
180 |
181 | hashPackage :: String -> HashMap Emacs.Name Name -> (Text, Elpa)
182 | -> IO (Maybe Package)
183 | hashPackage server namesMap (name, pkg) =
184 | catchPretty $ do
185 | let
186 | -- ver can not be completely correct but works well for now
187 | -- see doc string of version-regexp-alist and version-to-list
188 | ver = (Elpa.ver pkg) &
189 | ((map (T.pack . show))
190 | >>> (T.intercalate ".")
191 | >>> (T.replace ".-4." "snapshot")
192 | >>> (T.replace ".-3." "alpha")
193 | >>> (T.replace ".-2." "beta")
194 | >>> (T.replace ".-1." "pre"))
195 | basename
196 | | null (Elpa.ver pkg) = T.unpack name
197 | | otherwise = T.unpack (name <> "-" <> ver)
198 |
199 | ext <- case Elpa.dist pkg of
200 | "single" -> pure "el"
201 | "tar" -> pure "tar"
202 | other -> throwIO (DistNotImplemented other)
203 | let
204 | url = server > basename <.> ext
205 | fetch = Nix.URL { Nix.url = T.pack url
206 | , Nix.sha256 = Nothing
207 | , Nix.name = Nothing
208 | }
209 |
210 | (_, fetcher) <- Nix.prefetch name fetch
211 |
212 | nixName <- Nix.getName namesMap (Emacs.Name name)
213 | nixDeps <- mapM (Nix.getName namesMap . Emacs.Name)
214 | $ filter (\dep -> dep /= "emacs") -- filter dummy dep emacs to reduce closure size
215 | $ (maybe [] M.keys (Elpa.deps pkg))
216 |
217 | pure Nix.Package
218 | { Nix.pname = nixName
219 | , Nix.ename = name
220 | , Nix.version = ver
221 | , Nix.fetch = fetcher
222 | , Nix.deps = nixDeps
223 | }
224 |
--------------------------------------------------------------------------------
/emacs2nix.cabal:
--------------------------------------------------------------------------------
1 | -- This file has been generated from package.yaml by hpack version 0.27.0.
2 | --
3 | -- see: https://github.com/sol/hpack
4 | --
5 | -- hash: c1e00f0cc0fbdee53d812a448ab58378e69de319add96dd1a3dcefca1aa81a7b
6 |
7 | name: emacs2nix
8 | version: 0.1.0.0
9 | synopsis: Generate Nix expressions for Emacs packages
10 | description: melpa2nix uses package recipes provided by MELPA to generate Nix expressions used in Nixpkgs.
11 | .
12 | elpa2nix generates Nix expressions from ELPA.
13 | category: Distribution
14 | homepage: https://github.com/ttuegel/emacs2nix#readme
15 | bug-reports: https://github.com/ttuegel/emacs2nix/issues
16 | author: Thomas Tuegel
17 | maintainer: ttuegel@mailbox.org
18 | copyright: (C) 2018 Thomas Tuegel
19 | license: GPL-3
20 | license-file: LICENSE
21 | build-type: Simple
22 | cabal-version: >= 1.10
23 |
24 | data-files:
25 | scripts/build.el
26 | scripts/dump-recipes.el
27 | scripts/elpa2json.el
28 |
29 | source-repository head
30 | type: git
31 | location: https://github.com/ttuegel/emacs2nix
32 |
33 | library
34 | exposed-modules:
35 | Distribution.Bzr
36 | Distribution.Elpa
37 | Distribution.Git
38 | Distribution.Hg
39 | Distribution.Emacs.Name
40 | Distribution.Melpa
41 | Distribution.Melpa.Fetcher
42 | Distribution.Melpa.Melpa
43 | Distribution.Melpa.PkgInfo
44 | Distribution.Nix.Builtin
45 | Distribution.Nix.Exception
46 | Distribution.Nix.Fetch
47 | Distribution.Nix.Hash
48 | Distribution.Nix.Index
49 | Distribution.Nix.Name
50 | Distribution.Nix.Package.Elpa
51 | Distribution.Nix.Package.Melpa
52 | Distribution.SVN
53 | Distribution.Wiki
54 | Exceptions
55 | Process
56 | other-modules:
57 | Exceptions.TH
58 | Paths_emacs2nix
59 | hs-source-dirs:
60 | src
61 | ghc-options: -Wall
62 | build-depends:
63 | aeson >=0.8
64 | , ansi-wl-pprint >=0.6
65 | , async >=2.0
66 | , attoparsec >=0.13
67 | , base >=4.7 && <5
68 | , bytestring >=0.10
69 | , containers >=0.5
70 | , data-fix >=0.0.1
71 | , directory >=1.2
72 | , errors >=2
73 | , exceptions >=0.8
74 | , filepath >=1.3
75 | , hashable >=1.2
76 | , hnix
77 | , http-streams >=0.7.2.0
78 | , io-streams >=1.3
79 | , scientific >=0.3
80 | , taggy >=0.2
81 | , template-haskell >=2.12
82 | , temporary >=1.2
83 | , text >=1.2
84 | , time >=1.5
85 | , transformers >=0.4
86 | , unordered-containers >=0.2
87 | , uri-encode >= 1.5
88 | default-language: Haskell2010
89 |
90 | executable elpa2nix
91 | main-is: elpa2nix.hs
92 | other-modules:
93 | Paths_emacs2nix
94 | ghc-options: -Wall -threaded
95 | build-depends:
96 | aeson >=0.8
97 | , ansi-wl-pprint >=0.6
98 | , async >=2.0
99 | , attoparsec >=0.13
100 | , base >=4.7 && <5
101 | , bytestring >=0.10
102 | , containers >=0.5
103 | , data-fix >=0.0.1
104 | , directory >=1.2
105 | , emacs2nix
106 | , errors >=2
107 | , exceptions >=0.8
108 | , filepath >=1.3
109 | , hashable >=1.2
110 | , hnix
111 | , http-streams >=0.7.2.0
112 | , io-streams >=1.3
113 | , optparse-applicative >=0.11
114 | , scientific >=0.3
115 | , taggy >=0.2
116 | , template-haskell >=2.12
117 | , temporary >=1.2
118 | , text >=1.2
119 | , time >=1.5
120 | , transformers >=0.4
121 | , unordered-containers >=0.2
122 | , uri-encode >= 1.5
123 | default-language: Haskell2010
124 |
125 | executable melpa2nix
126 | main-is: melpa2nix.hs
127 | other-modules:
128 | Paths_emacs2nix
129 | ghc-options: -Wall -threaded
130 | build-depends:
131 | aeson >=0.8
132 | , ansi-wl-pprint >=0.6
133 | , async >=2.0
134 | , attoparsec >=0.13
135 | , base >=4.7 && <5
136 | , bytestring >=0.10
137 | , containers >=0.5
138 | , data-fix >=0.0.1
139 | , directory >=1.2
140 | , emacs2nix
141 | , errors >=2
142 | , exceptions >=0.8
143 | , filepath >=1.3
144 | , hashable >=1.2
145 | , hnix
146 | , http-streams >=0.7.2.0
147 | , io-streams >=1.3
148 | , optparse-applicative >=0.11
149 | , scientific >=0.3
150 | , taggy >=0.2
151 | , template-haskell >=2.12
152 | , temporary >=1.2
153 | , text >=1.2
154 | , time >=1.5
155 | , transformers >=0.4
156 | , unordered-containers >=0.2
157 | , uri-encode >= 1.5
158 | default-language: Haskell2010
159 |
--------------------------------------------------------------------------------
/hnix.nix:
--------------------------------------------------------------------------------
1 | { mkDerivation, aeson, ansi-wl-pprint, array, base
2 | , base16-bytestring, binary, bytestring, compact, containers
3 | , criterion, cryptohash-md5, cryptohash-sha1, cryptohash-sha256
4 | , cryptohash-sha512, data-fix, deepseq, deriving-compat, Diff
5 | , directory, exceptions, filepath, generic-random, ghc-datasize
6 | , Glob, hashable, hashing, haskeline, hedgehog, http-client
7 | , http-client-tls, http-types, interpolate, lens-family
8 | , lens-family-core, lens-family-th, logict, megaparsec, monadlist
9 | , mtl, optparse-applicative, pretty-show, process, regex-tdfa
10 | , regex-tdfa-text, repline, scientific, semigroups, serialise
11 | , split, stdenv, syb, tasty, tasty-hedgehog, tasty-hunit
12 | , tasty-quickcheck, tasty-th, template-haskell, text, these, time
13 | , transformers, unix, unordered-containers, vector, xml
14 | }:
15 | mkDerivation {
16 | pname = "hnix";
17 | version = "0.5.1";
18 | src = ./hnix;
19 | isLibrary = true;
20 | isExecutable = true;
21 | libraryHaskellDepends = [
22 | aeson ansi-wl-pprint array base base16-bytestring binary bytestring
23 | compact containers cryptohash-md5 cryptohash-sha1 cryptohash-sha256
24 | cryptohash-sha512 data-fix deepseq deriving-compat directory
25 | exceptions filepath ghc-datasize hashable hashing haskeline
26 | http-client http-client-tls http-types interpolate lens-family
27 | lens-family-core lens-family-th logict megaparsec monadlist mtl
28 | optparse-applicative pretty-show process regex-tdfa regex-tdfa-text
29 | scientific semigroups serialise split syb template-haskell text
30 | these time transformers unix unordered-containers vector xml
31 | ];
32 | executableHaskellDepends = [
33 | aeson ansi-wl-pprint base base16-bytestring bytestring compact
34 | containers cryptohash-md5 cryptohash-sha1 cryptohash-sha256
35 | cryptohash-sha512 data-fix deepseq exceptions filepath hashing
36 | haskeline mtl optparse-applicative pretty-show repline serialise
37 | template-haskell text time transformers unordered-containers
38 | ];
39 | testHaskellDepends = [
40 | ansi-wl-pprint base base16-bytestring bytestring compact containers
41 | cryptohash-md5 cryptohash-sha1 cryptohash-sha256 cryptohash-sha512
42 | data-fix deepseq Diff directory exceptions filepath generic-random
43 | Glob hashing hedgehog interpolate megaparsec mtl
44 | optparse-applicative pretty-show process serialise split tasty
45 | tasty-hedgehog tasty-hunit tasty-quickcheck tasty-th
46 | template-haskell text time transformers unix unordered-containers
47 | ];
48 | benchmarkHaskellDepends = [
49 | ansi-wl-pprint base base16-bytestring bytestring compact containers
50 | criterion cryptohash-md5 cryptohash-sha1 cryptohash-sha256
51 | cryptohash-sha512 data-fix deepseq exceptions filepath hashing mtl
52 | optparse-applicative serialise template-haskell text time
53 | transformers unordered-containers
54 | ];
55 | homepage = "https://github.com/haskell-nix/hnix#readme";
56 | description = "Haskell implementation of the Nix language";
57 | license = stdenv.lib.licenses.bsd3;
58 | }
59 |
--------------------------------------------------------------------------------
/melpa-packages.sh:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env nix-shell
2 | #! nix-shell shell-fetch.nix -i bash
3 |
4 | # usage: ./melpa-packages.sh --melpa PATH_TO_MELPA_CLONE
5 |
6 | melpa2nix --work /tmp/melpa2nix "$@"
7 |
--------------------------------------------------------------------------------
/melpa-stable-packages.sh:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env nix-shell
2 | #! nix-shell shell-fetch.nix -i bash
3 |
4 | # usage: ./melpa-packages.sh --melpa PATH_TO_MELPA_CLONE
5 |
6 | melpa2nix --stable --work /tmp/melpa2nix "$@"
7 |
--------------------------------------------------------------------------------
/melpa2nix.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE LambdaCase #-}
22 | {-# LANGUAGE OverloadedStrings #-}
23 | {-# LANGUAGE RecordWildCards #-}
24 |
25 | module Main where
26 |
27 | import Control.Concurrent ( getNumCapabilities, setNumCapabilities )
28 | import Control.Monad ( join )
29 | import Data.HashSet ( HashSet )
30 | import qualified Data.HashSet as HashSet
31 | import Data.Monoid ( (<>) )
32 | import Data.Text ( Text )
33 | import qualified Data.Text as T
34 | import Options.Applicative
35 | import System.Environment ( setEnv, unsetEnv )
36 |
37 | import qualified Distribution.Emacs.Name as Emacs
38 | import Distribution.Melpa
39 | import Distribution.Melpa.Melpa ( Stable (..) )
40 | import qualified Distribution.Nix.Name as Nix.Name
41 | import Exceptions
42 |
43 | main :: IO ()
44 | main =
45 | (catchPretty_ . joinParser)
46 | (info (helper <*> parser) desc)
47 | where
48 | desc = fullDesc <> progDesc "Generate Nix expressions from MELPA recipes"
49 |
50 | joinParser :: ParserInfo (IO ()) -> IO ()
51 | joinParser = join . execParser
52 |
53 | parser :: Parser (IO ())
54 | parser =
55 | melpa2nix
56 | <$> (threads <|> pure 0)
57 | <*> melpa
58 | <*> stable
59 | <*> work
60 | <*> output
61 | <*> names
62 | <*> indexOnly
63 | <*> packages
64 | where
65 | threads = option auto (long "threads" <> short 't' <> metavar "N"
66 | <> help "use N threads; default is number of CPUs")
67 | melpa = strOption (long "melpa" <> metavar "DIR"
68 | <> help "path to MELPA repository")
69 | stable = Stable <$> switch (long "stable" <> help "generate packages from MELPA Stable")
70 | work = strOption (long "work" <> metavar "DIR"
71 | <> help "path to temporary workspace")
72 | output = strOption (long "output" <> short 'o' <> metavar "FILE"
73 | <> help "dump MELPA data to FILE")
74 | names = strOption (long "names" <> metavar "FILE"
75 | <> help "map Emacs names to Nix names using FILE")
76 | indexOnly = flag False True
77 | (long "index-only"
78 | <> help "don't update packages, only update the index file")
79 | packages = HashSet.fromList . map T.pack
80 | <$> many (strArgument
81 | (metavar "PACKAGE" <> help "only work on PACKAGE"))
82 |
83 | melpa2nix :: Int -- ^ number of threads to use
84 | -> FilePath -- ^ path to MELPA repository
85 | -> Stable -- ^ generate packages from MELPA Stable
86 | -> FilePath -- ^ temporary workspace
87 | -> FilePath -- ^ dump MELPA recipes here
88 | -> FilePath -- ^ map of Emacs names to Nix names
89 | -> Bool -- ^ only generate the index
90 | -> HashSet Text
91 | -> IO ()
92 | melpa2nix nthreads melpaDir stable workDir melpaOut namesFile indexOnly packages =
93 | do
94 | -- set number of threads before beginning
95 | if nthreads > 0
96 | then setNumCapabilities nthreads
97 | else getNumCapabilities >>= setNumCapabilities . (* 4)
98 |
99 | names <- Nix.Name.readNames namesFile
100 |
101 | selected <- getSelectedNames names (HashSet.map Emacs.Name packages)
102 |
103 | -- Force our TZ to match the melpa build machines
104 | setEnv "TZ" "PST8PDT"
105 | -- Any operation requiring a password should fail
106 | unsetEnv "SSH_ASKPASS"
107 | updateMelpa melpaDir stable workDir melpaOut indexOnly names selected
108 |
--------------------------------------------------------------------------------
/names.nix:
--------------------------------------------------------------------------------
1 | {
2 | "@" = "at";
3 | "0blayout" = "_0blayout";
4 | "0xc" = "_0xc";
5 | "2048-game" = "_2048-game";
6 | "4clojure" = "_4clojure";
7 | "desktop+" = "desktop-plus";
8 | "filesets+" = "filesets-plus";
9 | "ghub+" = "ghub-plus";
10 | "git-gutter+" = "git-gutter-plus";
11 | "git-gutter-fringe+" = "git-gutter-fringe-plus";
12 | "ido-completing-read+" = "ido-completing-read-plus";
13 | "image+" = "image-plus";
14 | "image-dired+" = "image-dired-plus";
15 | "markdown-mode+" = "markdown-mode-plus";
16 | "package+" = "package-plus";
17 | "rect+" = "rect-plus";
18 | "shell-command+" = "shell-command-plus";
19 | "term+" = "term-plus";
20 | "term+key-intercept" = "term-plus-key-intercept";
21 | "term+mux" = "term-plus-mux";
22 | "xml+" = "xml-plus";
23 | }
24 |
--------------------------------------------------------------------------------
/nixpkgs.lock.json:
--------------------------------------------------------------------------------
1 | {
2 | "url": "https://github.com/NixOS/nixpkgs-channels",
3 | "rev": "5b468ea6b1d8d243847a05bdf5603e8abdfd7b4e",
4 | "date": "2018-05-24T16:42:16+02:00",
5 | "sha256": "0yj31a11h0mj9d5jyz95ynh5791nd0y1xzqk7ba3qrikljqg3lvb",
6 | "fetchSubmodules": true
7 | }
8 |
--------------------------------------------------------------------------------
/nixpkgs.nix:
--------------------------------------------------------------------------------
1 | let
2 | inherit ((import {}).pkgs) fetchgit lib;
3 | lock = builtins.fromJSON (builtins.readFile ./nixpkgs.lock.json);
4 | bootstrap = fetchgit {
5 | inherit (lock) url rev sha256 fetchSubmodules;
6 | };
7 | defaultOverrides =
8 | let file = ./default.overrides.nix; in
9 | lib.optional
10 | (builtins.pathExists file)
11 | (import file);
12 | shellOverrides =
13 | let file = ./shell.overrides.nix; in
14 | lib.optional
15 | (lib.inNixShell && builtins.pathExists file)
16 | (import file);
17 | userShellOverrides =
18 | let
19 | file =
20 | builtins.getEnv "HOME" + "/.config/nixpkgs/shell.overrides.nix";
21 | in
22 | lib.optional
23 | (lib.inNixShell && builtins.pathExists file)
24 | (import file);
25 | in
26 | import bootstrap
27 | {
28 | config.allowUnfree = true;
29 | overlays = defaultOverrides ++ shellOverrides ++ userShellOverrides;
30 | }
31 |
--------------------------------------------------------------------------------
/nongnu-devel-packages.sh:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env nix-shell
2 | #! nix-shell shell-fetch.nix -i bash
3 |
4 | # usage: ./nongnu-devel-packages.sh -o PATH
5 |
6 | elpa2nix https://elpa.nongnu.org/nongnu-devel/ "$@"
7 |
--------------------------------------------------------------------------------
/nongnu-packages.sh:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env nix-shell
2 | #! nix-shell shell-fetch.nix -i bash
3 |
4 | # usage: ./nongnu-packages.sh -o PATH
5 |
6 | elpa2nix https://elpa.nongnu.org/nongnu/ "$@"
7 |
--------------------------------------------------------------------------------
/package.nix:
--------------------------------------------------------------------------------
1 | { mkDerivation, aeson, ansi-wl-pprint, async, attoparsec, base
2 | , bytestring, containers, data-fix, directory, errors, exceptions
3 | , filepath, hashable, hnix, http-streams, io-streams
4 | , optparse-applicative, scientific, stdenv, taggy, template-haskell
5 | , temporary, text, time, transformers, unordered-containers, uri-encode
6 | }:
7 | mkDerivation {
8 | pname = "emacs2nix";
9 | version = "0.1.0.0";
10 | src = ./.;
11 | isLibrary = true;
12 | isExecutable = true;
13 | enableSeparateDataOutput = true;
14 | libraryHaskellDepends = [
15 | aeson ansi-wl-pprint async attoparsec base bytestring containers
16 | data-fix directory errors exceptions filepath hashable hnix
17 | http-streams io-streams scientific taggy template-haskell temporary
18 | text time transformers unordered-containers uri-encode
19 | ];
20 | executableHaskellDepends = [
21 | aeson ansi-wl-pprint async attoparsec base bytestring containers
22 | data-fix directory errors exceptions filepath hashable hnix
23 | http-streams io-streams optparse-applicative scientific taggy
24 | template-haskell temporary text time transformers
25 | unordered-containers uri-encode
26 | ];
27 | homepage = "https://github.com/ttuegel/emacs2nix#readme";
28 | description = "Generate Nix expressions for Emacs packages";
29 | license = stdenv.lib.licenses.gpl3;
30 | }
31 |
--------------------------------------------------------------------------------
/package.yaml:
--------------------------------------------------------------------------------
1 | name: emacs2nix
2 | version: 0.1.0.0
3 | synopsis: Generate Nix expressions for Emacs packages
4 | description: |
5 | melpa2nix uses package recipes provided by MELPA to generate Nix expressions used in Nixpkgs.
6 |
7 | elpa2nix generates Nix expressions from ELPA.
8 | license: GPL-3
9 | license-file: LICENSE
10 | author: Thomas Tuegel
11 | maintainer: ttuegel@mailbox.org
12 | copyright: (C) 2018 Thomas Tuegel
13 | category: Distribution
14 |
15 | github: ttuegel/emacs2nix
16 |
17 | data-files:
18 | - scripts/*.el
19 |
20 | dependencies:
21 | - base >= 4.7 && < 5
22 | - aeson >= 0.8
23 | - ansi-wl-pprint >= 0.6
24 | - async >= 2.0
25 | - attoparsec >= 0.13
26 | - bytestring >= 0.10
27 | - containers >= 0.5
28 | - data-fix >= 0.0.1
29 | - directory >= 1.2
30 | - errors >= 2
31 | - exceptions >= 0.8
32 | - filepath >= 1.3
33 | - hashable >= 1.2
34 | - hnix
35 | - http-streams >= 0.7.2.0
36 | - io-streams >= 1.3
37 | - scientific >= 0.3
38 | - taggy >= 0.2
39 | - template-haskell >= 2.12
40 | - temporary >= 1.2
41 | - text >= 1.2
42 | - time >= 1.5
43 | - transformers >= 0.4
44 | - unordered-containers >= 0.2
45 | - uri-encode >= 1.5
46 |
47 | ghc-options: -Wall
48 |
49 | library:
50 | exposed-modules:
51 | - Distribution.Bzr
52 | - Distribution.Elpa
53 | - Distribution.Git
54 | - Distribution.Hg
55 | - Distribution.Emacs.Name
56 | - Distribution.Melpa
57 | - Distribution.Melpa.Fetcher
58 | - Distribution.Melpa.Melpa
59 | - Distribution.Melpa.PkgInfo
60 | - Distribution.Nix.Builtin
61 | - Distribution.Nix.Exception
62 | - Distribution.Nix.Fetch
63 | - Distribution.Nix.Hash
64 | - Distribution.Nix.Index
65 | - Distribution.Nix.Name
66 | - Distribution.Nix.Package.Elpa
67 | - Distribution.Nix.Package.Melpa
68 | - Distribution.SVN
69 | - Distribution.Wiki
70 | - Exceptions
71 | - Process
72 | source-dirs: src
73 |
74 | executables:
75 | melpa2nix:
76 | main: melpa2nix.hs
77 | ghc-options: -threaded
78 | dependencies:
79 | - emacs2nix
80 | - optparse-applicative >= 0.11
81 |
82 | elpa2nix:
83 | main: elpa2nix.hs
84 | ghc-options: -threaded
85 | dependencies:
86 | - emacs2nix
87 | - optparse-applicative >= 0.11
88 |
--------------------------------------------------------------------------------
/scripts/build.el:
--------------------------------------------------------------------------------
1 | (require 'package)
2 | (package-initialize)
3 |
4 | (require 'package-build)
5 | (require 'package-recipe)
6 |
7 | (setq package-build-verbose nil)
8 | (setq package-build-working-dir (expand-file-name "working/"))
9 | (setq package-build-archive-dir (expand-file-name "packages/"))
10 | (setq package-build-recipes-dir (expand-file-name "recipes/"))
11 |
12 | (defun pkg-info-for-json (info)
13 | "Convert INFO into a data structure which will serialize to JSON in the desired shape.
14 | Differs from `package-build--pkg-info-for-json' by ignoring `:props'."
15 | (let ((ver (elt info 0))
16 | (deps (elt info 1))
17 | (desc (elt info 2))
18 | (type (elt info 3)))
19 | (list :ver ver
20 | :deps (cl-mapcan (lambda (dep)
21 | (list (intern (format ":%s" (car dep)))
22 | (cadr dep)))
23 | deps)
24 | :desc desc
25 | :type type)))
26 |
27 | (defun build-1 (name)
28 | (let* ((rcp (package-recipe-lookup name))
29 | (version (package-build--checkout rcp))
30 | (pkg-info (cdr (package-build--package rcp version))))
31 | (princ (json-encode (pkg-info-for-json pkg-info)))))
32 |
33 | (defun build ()
34 | (if (not noninteractive)
35 | (error "`build' is to be used only with -batch"))
36 | (pcase command-line-args-left
37 | (`(,name) (build-1 name))))
38 |
39 | (defun build-stable ()
40 | (if (not noninteractive)
41 | (error "`build-stable' is to be used only with -batch"))
42 | (setq package-build-stable t)
43 | (build))
44 |
45 | (defun files-1 (name)
46 | (let* ((rcp (package-recipe-lookup name))
47 | (version (package-build--checkout rcp)))
48 | (princ (json-encode (package-build--expand-source-file-list rcp)))))
49 |
50 | (defun files ()
51 | (pcase command-line-args-left
52 | (`(,name) (files-1 name))))
53 |
--------------------------------------------------------------------------------
/scripts/dump-recipes.el:
--------------------------------------------------------------------------------
1 | (require 'package)
2 | (package-initialize)
3 |
4 | (require 'package-recipe)
5 | (require 'package-build)
6 |
7 | (require 'json)
8 |
9 | (defun read-recipe (name)
10 | "Return a recipe plist for the package named NAME.
11 | If no such recipe file exists or if the contents of the recipe
12 | file is invalid, then raise an error."
13 | ;; Adapted from `package-recipe-lookup' to return a plist
14 | ;; rather than an EIEIO object.
15 | (let ((file (expand-file-name name package-build-recipes-dir)))
16 | (if (file-exists-p file)
17 | (let* ((recipe (with-temp-buffer
18 | (insert-file-contents file)
19 | (read (current-buffer)))))
20 | (package-recipe--validate recipe name)
21 | recipe)
22 | (error "No such recipe: %s" name))))
23 |
24 | (defun dump-recipes-json ()
25 | (if (not noninteractive)
26 | (error "`dump-recipes-json' is to be used only with -batch"))
27 | (pcase command-line-args-left
28 | (`(,recipes-dir)
29 | (progn
30 | (setq package-build-recipes-dir recipes-dir)
31 | (let* ((recipes (mapcar #'read-recipe (package-recipe-recipes))))
32 | (princ (json-encode recipes)))))))
33 |
--------------------------------------------------------------------------------
/scripts/elpa2json.el:
--------------------------------------------------------------------------------
1 | (require 'json)
2 |
3 | (defun pb/sym-to-keyword (s)
4 | "Return a version of symbol S as a :keyword."
5 | (intern (concat ":" (symbol-name s))))
6 |
7 | (defun pb/pkg-info-for-json (info)
8 | "Convert INFO into a data structure which will serialize to JSON in the desired shape."
9 | (let* ((ver (elt info 0))
10 | (deps (elt info 1))
11 | (desc (elt info 2))
12 | (type (elt info 3)))
13 | (list :ver ver
14 | :deps (apply 'append
15 | (mapcar (lambda (dep)
16 | (list (pb/sym-to-keyword (car dep))
17 | (cadr dep)))
18 | deps))
19 | :desc desc
20 | :dist type)))
21 |
22 | (defun packages-for-json (packages)
23 | "Return the packages list in a form suitable for JSON encoding."
24 | (apply 'append
25 | (mapcar (lambda (entry)
26 | (list (pb/sym-to-keyword (car entry))
27 | (pb/pkg-info-for-json (cdr entry))))
28 | packages)))
29 |
30 | (defun print-archive-contents-as-json (archive-contents)
31 | "Print the packages listed in file ARCHIVE-CONTENTS in JSON encoding."
32 | (let ((packages (cdr (read (find-file-noselect archive-contents)))))
33 | (princ (json-encode (packages-for-json packages)))))
34 |
--------------------------------------------------------------------------------
/shell-fetch.nix:
--------------------------------------------------------------------------------
1 | let
2 | emacs2nix = import ./default.nix;
3 | nixpkgs = import {};
4 |
5 | in
6 |
7 | with nixpkgs;
8 |
9 | stdenv.mkDerivation {
10 | name = "interactive-${emacs2nix.name}-environment";
11 | nativeBuildInputs = [
12 | emacs nix nix-prefetch-scripts
13 | breezy cvs curl fossil git mercurial subversion
14 | emacs2nix
15 | ];
16 | shellHook = ''
17 | export SSL_CERT_FILE="${cacert}/etc/ssl/certs/ca-bundle.crt"
18 | '';
19 | }
20 |
--------------------------------------------------------------------------------
/shell.nix:
--------------------------------------------------------------------------------
1 | (import ./.).env
2 |
--------------------------------------------------------------------------------
/shell.overrides.nix:
--------------------------------------------------------------------------------
1 | self: super:
2 | {
3 | haskellPackages = super.haskellPackages.override (args: {
4 | overrides = self: super_:
5 | let
6 | super = (args.overrides or (self: super: super)) self super_;
7 | in
8 | super // {
9 | ghcWithPackages = self.ghcWithHoogle;
10 | };
11 | });
12 | }
13 |
--------------------------------------------------------------------------------
/src/Distribution/Bzr.hs:
--------------------------------------------------------------------------------
1 | {-
2 | emacs2nix - Generate Nix expressions for Emacs packages
3 | Copyright (C) 2018 Thomas Tuegel
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 |
18 | -}
19 |
20 |
21 | {-# LANGUAGE OverloadedStrings #-}
22 |
23 | module Distribution.Bzr ( revision ) where
24 |
25 | import qualified Data.Char as Char
26 | import Data.Text ( Text )
27 | import qualified Data.Text as Text
28 | import qualified System.IO.Streams as Stream
29 |
30 | import Exceptions
31 | import Process ( runInteractiveProcess )
32 |
33 | -- | Find the latest revision in a Bazaar repository.
34 | revision :: FilePath -> IO Text
35 | revision tmp =
36 | do
37 | let args = [ "log", "-l1", tmp ]
38 | runInteractiveProcess "bzr" args Nothing Nothing $ \out -> do
39 | revs <- Stream.mapMaybe revno =<< (Stream.lines out >>= Stream.decodeUtf8)
40 | maybe (throwM NoRevision) pure =<< Stream.read revs
41 | where
42 | revno = (Text.takeWhile Char.isDigit . Text.strip <$>) . Text.stripPrefix "revno:"
43 |
--------------------------------------------------------------------------------
/src/Distribution/Elpa.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE DeriveGeneric #-}
22 |
23 | module Distribution.Elpa ( Elpa(..) ) where
24 |
25 | import Data.Aeson ( FromJSON(..), ToJSON(..) )
26 | import Data.Map.Strict ( Map )
27 | import Data.Text ( Text )
28 | import GHC.Generics
29 |
30 | data Elpa =
31 | Elpa
32 | { ver :: [Integer]
33 | , deps :: Maybe (Map Text [Integer])
34 | , dist :: Text -- TODO: replace with an enumeration
35 | , broken :: Maybe Bool
36 | }
37 | deriving (Eq, Generic, Read, Show)
38 |
39 | instance FromJSON Elpa
40 | instance ToJSON Elpa
41 |
--------------------------------------------------------------------------------
/src/Distribution/Emacs/Name.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 |
22 | {-# LANGUAGE GeneralizedNewtypeDeriving #-}
23 |
24 | module Distribution.Emacs.Name ( Name (..) ) where
25 |
26 | import Data.Hashable ( Hashable )
27 | import Data.Text ( Text )
28 |
29 |
30 | newtype Name = Name { fromName :: Text }
31 | deriving (Eq, Hashable, Ord, Show)
32 |
--------------------------------------------------------------------------------
/src/Distribution/Git.hs:
--------------------------------------------------------------------------------
1 |
2 | {-
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2018 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 |
22 | {-# LANGUAGE OverloadedStrings #-}
23 |
24 | module Distribution.Git ( revision ) where
25 |
26 | import Data.Maybe ( maybeToList )
27 | import Data.Semigroup ( (<>) )
28 | import Data.Text ( Text )
29 | import qualified Data.Text as Text
30 | import qualified System.IO.Streams as Stream
31 |
32 | import Exceptions
33 | import Process ( runInteractiveProcess )
34 |
35 | -- | Find the latest revision in a Git repository.
36 | --
37 | -- The revision will be the latest one which changes the given files
38 | -- (or which changes /any/ file, if no file names are given).
39 | --
40 | -- If the branch name is given, the revision will be the latest in that branch.
41 | -- Otherwise, the latest revision of the current branch will be found.
42 | revision :: FilePath -- ^ repository
43 | -> Maybe Text -- ^ branch name
44 | -> [FilePath] -- ^ file names
45 | -> IO Text
46 | revision src branch files =
47 | do
48 | runInteractiveProcess "git" args (Just src) Nothing $ \out -> do
49 | revs <- Stream.lines out >>= Stream.decodeUtf8
50 | maybe (throwM NoRevision) pure =<< Stream.read revs
51 | where
52 | args = [ "log", "--first-parent", "-n1", "--pretty=format:%H" ]
53 | -- package-build does not fetch all branches by default, so they
54 | -- must be referred to under the origin/ prefix
55 | ++ maybeToList (Text.unpack . (<>) "origin/" <$> branch)
56 | ++ ("--" : files)
57 |
--------------------------------------------------------------------------------
/src/Distribution/Hg.hs:
--------------------------------------------------------------------------------
1 | {-
2 | emacs2nix - Generate Nix expressions for Emacs packages
3 | Copyright (C) 2018 Thomas Tuegel
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 |
18 | -}
19 |
20 |
21 | {-# LANGUAGE OverloadedStrings #-}
22 |
23 | module Distribution.Hg ( revision ) where
24 |
25 | import qualified Data.Char as Char
26 | import Data.Text ( Text )
27 | import qualified Data.Text as Text
28 | import qualified System.IO.Streams as Stream
29 |
30 | import Exceptions
31 | import Process ( runInteractiveProcess )
32 |
33 |
34 | -- | Find the latest revision in a Mercurial repository.
35 | revision :: FilePath -> IO Text
36 | revision source = do
37 | runInteractiveProcess "hg" ["tags"] (Just source) Nothing $ \out -> do
38 | revs <- Stream.mapMaybe getRev =<< (Stream.lines out >>= Stream.decodeUtf8)
39 | maybe (throwM NoRevision) pure =<< Stream.read revs
40 | where
41 | getRev txt = do
42 | afterTip <- Text.strip <$> Text.stripPrefix "tip" txt
43 | let
44 | (_, after) = Text.breakOn ":" afterTip
45 | rev = (Text.strip . Text.takeWhile Char.isHexDigit . Text.drop 1) after
46 | if Text.null rev
47 | then Nothing
48 | else return rev
49 |
--------------------------------------------------------------------------------
/src/Distribution/Melpa.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE NamedFieldPuns #-}
22 | {-# LANGUAGE OverloadedStrings #-}
23 | {-# LANGUAGE RecordWildCards #-}
24 | {-# LANGUAGE ScopedTypeVariables #-}
25 | {-# LANGUAGE ViewPatterns #-}
26 |
27 | module Distribution.Melpa ( updateMelpa, getSelectedNames, getRecipeNames ) where
28 |
29 | import Control.Concurrent ( getNumCapabilities )
30 | import Control.Concurrent.Async ( Concurrently(..) )
31 | import Control.Concurrent.QSem
32 | import Control.Monad.IO.Class
33 | import Data.Aeson.Parser ( json' )
34 | import Data.Aeson.Types
35 | import Data.Foldable ( toList )
36 | import Data.HashMap.Strict ( HashMap )
37 | import qualified Data.HashMap.Strict as HashMap
38 | import Data.HashSet ( HashSet )
39 | import qualified Data.HashSet as HashSet
40 | import qualified Data.Map.Strict as Map
41 | import Data.Semigroup
42 | import Data.Text ( Text )
43 | import qualified Data.Text as T
44 | import Data.Typeable ( Typeable )
45 | import System.Directory ( createDirectoryIfMissing, copyFile )
46 | import System.FilePath
47 | import qualified System.IO.Streams.Attoparsec as S
48 | import qualified Text.PrettyPrint.ANSI.Leijen as Pretty
49 |
50 | import qualified Distribution.Emacs.Name as Emacs
51 | import qualified Distribution.Git as Git
52 | import Distribution.Melpa.Fetcher
53 | import Distribution.Melpa.Melpa
54 | import Distribution.Melpa.PkgInfo
55 | import qualified Distribution.Nix.Fetch as Nix
56 | import qualified Distribution.Nix.Hash as Nix
57 | import Distribution.Nix.Index
58 | import qualified Distribution.Nix.Name as Nix
59 | import qualified Distribution.Nix.Package.Melpa as Recipe ( Recipe(..) )
60 | import qualified Distribution.Nix.Package.Melpa as Nix
61 | import Exceptions
62 | import Process
63 | import Paths_emacs2nix ( getDataFileName )
64 |
65 | updateMelpa :: FilePath
66 | -> Stable
67 | -> FilePath -- ^ temporary workspace
68 | -> FilePath -- ^ dump MELPA recipes here
69 | -> Bool -- ^ only generate the index
70 | -> HashMap Emacs.Name Nix.Name
71 | -> HashSet Nix.Name
72 | -> IO ()
73 | updateMelpa melpaDir stable workDir melpaOut indexOnly names selected = do
74 | melpaCommit <- Git.revision melpaDir Nothing []
75 | let melpa = Melpa {..}
76 |
77 | recipes <- getRecipeNames names =<< readRecipes melpa
78 |
79 | let
80 | select
81 | | HashSet.null selected = id
82 | | otherwise = Map.filterWithKey (\name _ -> HashSet.member name selected)
83 |
84 | createDirectoryIfMissing True workDir
85 |
86 | sem <- newQSem =<< getNumCapabilities
87 |
88 | let
89 | update name recipe =
90 | Concurrently
91 | $ bracket (waitQSem sem) (\_ -> signalQSem sem)
92 | $ \_ -> getPackage melpa stable workDir names name recipe
93 | toMap = Map.fromList . HashMap.toList
94 | updates <-
95 | runConcurrently
96 | $ if indexOnly
97 | then pure Map.empty
98 | else Map.traverseMaybeWithKey update (select $ toMap recipes)
99 |
100 | existing <- readIndex melpaOut
101 |
102 | let
103 | -- | Was the recipe removed?
104 | removed name = not (HashMap.member name recipes)
105 | updated
106 | | indexOnly = Map.union (Nix.expression <$> updates) existing
107 | | otherwise =
108 | Map.union (Nix.expression <$> updates)
109 | $ Map.filterWithKey (\k _ -> (not . removed) k) (select existing)
110 |
111 | writeIndex melpaOut updated
112 |
113 |
114 | getKeyNames
115 | :: HashMap Emacs.Name Nix.Name
116 | -> HashMap Emacs.Name a
117 | -> IO (HashMap Nix.Name a)
118 | getKeyNames names _keyed =
119 | do
120 | _keyed <- traverse getName (HashMap.toList _keyed)
121 | maybe (throwM DeferredErrors) (pure . HashMap.fromList) (sequenceA _keyed)
122 | where
123 | getName (ename, a) =
124 | catchPretty $ (,) <$> Nix.getName names ename <*> pure a
125 |
126 |
127 | getSelectedNames
128 | :: HashMap Emacs.Name Nix.Name
129 | -> HashSet Emacs.Name
130 | -> IO (HashSet Nix.Name)
131 | getSelectedNames names packages =
132 | HashSet.fromMap <$> getKeyNames names (HashSet.toMap packages)
133 |
134 |
135 | getRecipeNames
136 | :: HashMap Emacs.Name Nix.Name
137 | -> HashMap Emacs.Name Fetcher
138 | -> IO (HashMap Nix.Name Fetcher)
139 | getRecipeNames = getKeyNames
140 |
141 |
142 | {-|
143 |
144 | To create an expression for an Emacs package, we need several pieces of
145 | information:
146 |
147 | 1. name
148 | 2. version
149 | 3. source
150 | a. the method to fetch the source
151 | b. the commit (or other token) to fetch the source reproducibly
152 | c. the hash of the source
153 | 4. dependencies
154 | 5. exact recipe
155 |
156 | The name is available from the enumerated list of recipes or the arguments
157 | on the command line. The version and source can be obtained after the package
158 | is unpacked by 'package-build'. The dependencies are most easily determined
159 | after the package is built by 'package-build'. It is not strictly necessary to
160 | build every package just to write the Nix expression, but the build status can
161 | be used to mark packages broken as appropriate. The exact recipe is available
162 | at any time; we track this so that the Nix expression will reproduce the exact
163 | build even if the recipe is changed upstream.
164 |
165 | As elucidated above, there are two phases of the 'package-build' workflow which
166 | we must execute: 'package-build-checkout' (to checkout the package) and
167 | 'package-build-package' (to build the checked-out source). 'package-build'
168 | expects to be run from the MELPA tree, so in order to build each package in
169 | isolation (and to keep the MELPA tree clean) we construct enough of a "fake"
170 | tree that 'package-build' is happy. For our purposes, it suffices to create a
171 | directory with one recipe (the target package) in the "recipes"
172 | subdirectory. 'package-build' will create a "working" subdirectory with the
173 | package source and a "packages" subdirectory with the build product.
174 |
175 | -}
176 |
177 | getPackage :: Melpa -> Stable -> FilePath
178 | -> HashMap Emacs.Name Nix.Name
179 | -> Nix.Name
180 | -> Fetcher
181 | -> IO (Maybe Nix.Package)
182 | getPackage melpa@(Melpa {..}) stable tmpDir namesMap name fetcher =
183 | catchPretty $ inContext ("package " <> Pretty.string sname) $ do
184 | let
185 | recipeFile = recipeFileName melpa tname
186 |
187 | packageDir = tmpDir > sname
188 | recipesDir = packageDir > "recipes"
189 | workingDir = packageDir > "working"
190 | archiveDir = packageDir > "packages"
191 | sourceDir = workingDir > sname
192 |
193 | createDirectoryIfMissing True recipesDir
194 | createDirectoryIfMissing True workingDir
195 | createDirectoryIfMissing True archiveDir
196 | copyFile recipeFile (recipesDir > sname)
197 |
198 | melpaRecipe <- freezeRecipe melpa tname
199 | pkgInfo <- build melpa stable tname packageDir
200 | (_, fetch) <- Nix.prefetch tname =<< freeze fetcher melpa sourceDir
201 |
202 | nixName <- Nix.getName namesMap ename
203 | nixDeps <- mapM (Nix.getName namesMap . Emacs.Name) (toList $ deps pkgInfo)
204 |
205 | pure
206 | Nix.Package
207 | { Nix.pname = nixName
208 | , Nix.version = version pkgInfo
209 | , Nix.fetch = fetch
210 | , Nix.deps = nixDeps
211 | , Nix.recipe = melpaRecipe
212 | }
213 | where
214 | Nix.Name { ename } = name
215 | tname = Emacs.fromName ename
216 | sname = T.unpack tname
217 |
218 | build :: Melpa -> Stable -> Text -> FilePath -> IO PkgInfo
219 | build melpa Stable {..} name packageDir =
220 | do
221 | buildEl <- getDataFileName "scripts/build.el"
222 | let
223 | args =
224 | [ "-Q", "--batch"
225 | , "-L", packageBuildDir melpa
226 | , "-l", buildEl
227 | , "-f", if stable then "build-stable" else "build"
228 | , T.unpack name
229 | ]
230 | cwd = Just packageDir
231 | runInteractiveProcess "emacs" args cwd Nothing $ \out -> do
232 | r <- liftIO (parseEither parsePkgInfo <$> S.parseFromStream json' out)
233 | case r of
234 | Left err -> throwM (ParsePkgInfoError err)
235 | Right pkgInfo -> pure pkgInfo
236 |
237 | recipeFileName :: Melpa -> Text -> FilePath
238 | recipeFileName Melpa {..} (T.unpack -> name) = melpaDir > "recipes" > name
239 |
240 | freezeRecipe :: Melpa -> Text -> IO Nix.Recipe
241 | freezeRecipe melpa@(Melpa {..}) name = do
242 | let recipe = recipeFileName melpa name
243 | hash <- Nix.hash recipe
244 | commit <- Git.revision melpaDir Nothing [recipe]
245 | pure
246 | Nix.Recipe
247 | { Recipe.ename = name
248 | , Recipe.commit = commit
249 | , Recipe.sha256 = hash
250 | }
251 |
252 | data NoVersion = NoVersion
253 | deriving (Show, Typeable)
254 |
255 | instance Exception NoVersion
256 |
257 | data ParsePkgInfoError = ParsePkgInfoError String
258 | deriving (Show, Typeable)
259 |
260 | instance Exception ParsePkgInfoError
261 |
--------------------------------------------------------------------------------
/src/Distribution/Melpa/Fetcher.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2018 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 |
22 | {-# LANGUAGE OverloadedStrings #-}
23 | {-# LANGUAGE RecordWildCards #-}
24 | {-# LANGUAGE ViewPatterns #-}
25 |
26 | module Distribution.Melpa.Fetcher ( Fetcher (..), readRecipes ) where
27 |
28 | import Data.Aeson.Types ( (.:), (.:?) )
29 | import qualified Data.Aeson as Aeson
30 | import qualified Data.Aeson.Types as Aeson
31 | import Data.HashMap.Strict ( HashMap )
32 | import qualified Data.HashMap.Strict as HashMap
33 | import Data.Monoid
34 | import Data.Text ( Text )
35 | import qualified Data.Text as Text
36 | import System.FilePath
37 | import qualified System.IO.Streams as Stream
38 | import qualified System.IO.Streams.Attoparsec as Stream
39 |
40 | import qualified Distribution.Bzr as Bzr
41 | import qualified Distribution.Emacs.Name as Emacs
42 | import qualified Distribution.Git as Git
43 | import qualified Distribution.Hg as Hg
44 | import Distribution.Melpa.Melpa
45 | import qualified Distribution.Nix.Fetch as Nix
46 | import qualified Distribution.SVN as SVN
47 | import qualified Distribution.Wiki as Wiki
48 | import Paths_emacs2nix ( getDataFileName )
49 | import Exceptions
50 | import Process
51 |
52 |
53 | -- | A @Fetcher@ is parsed from a MELPA recipe and can be frozen to (ultimately)
54 | -- produce a Nix expression which will fetch the exact source of the package.
55 | -- @Fetcher@ can be parsed from JSON with 'parseFetcher'. Calling @freeze@ with
56 | -- the local path to the package source produces a 'Nix.Fetch' which is used
57 | -- to retrieve an exact version of the package source.
58 | newtype Fetcher = Fetcher { freeze :: Melpa -> FilePath -> IO Nix.Fetch }
59 |
60 |
61 | -- | Read recipes from MELPA into a map from package name to the 'Fetcher' for
62 | -- each package. The map keys are the /Emacs/ package names (not yet
63 | -- sanitized for Nix). A @HashMap@ is used because random access is required
64 | -- to check if recipes have been deleted.
65 | readRecipes :: Melpa -> IO (HashMap Emacs.Name Fetcher)
66 | readRecipes melpa = do
67 | let recipesDir = melpaDir melpa > "recipes"
68 | dumpRecipesEl <- getDataFileName "scripts/dump-recipes.el"
69 | let args = [ "-Q"
70 | , "--batch"
71 | , "-L", packageBuildDir melpa
72 | , "-l", dumpRecipesEl
73 | , "-f", "dump-recipes-json", recipesDir
74 | ]
75 | runInteractiveProcess "emacs" args Nothing Nothing $ \out ->
76 | do
77 | value <- Stream.parseFromStream Aeson.json' out
78 | case Aeson.parseEither parseFetchers value of
79 | Left err ->
80 | do
81 | let msg = "error reading recipes: " <> Text.pack err
82 | Stream.write (Just msg) =<< Stream.encodeUtf8 Stream.stderr
83 | return HashMap.empty
84 | Right recipes -> return recipes
85 |
86 |
87 | -- | Parse a map of package names to MELPA recipes from the JSON encoding of
88 | -- MELPA recipes.
89 | parseFetchers :: Aeson.Value -> Aeson.Parser (HashMap Emacs.Name Fetcher)
90 | parseFetchers = Aeson.withObject "recipes" parseFetcher1
91 | where
92 | mapKeys f = HashMap.fromList . map mapKey1 . HashMap.toList
93 | where
94 | mapKey1 (k, v) = (f k, v)
95 | parseFetcher1 =
96 | HashMap.traverseWithKey parseFetcher . mapKeys Emacs.Name
97 |
98 |
99 | -- | Parse a 'Fetcher' from the JSON encoding of a MELPA recipe.
100 | parseFetcher :: Emacs.Name -> Aeson.Value -> Aeson.Parser Fetcher
101 | parseFetcher (Emacs.fromName -> name) =
102 | Aeson.withObject "recipe" $ \rcp ->
103 | do
104 | fetcher <- rcp .: "fetcher"
105 | case fetcher :: Text of
106 | "bitbucket" ->
107 | do
108 | repo <- rcp .: "repo"
109 | let url = "https://bitbucket.com/" <> repo
110 | pure Fetcher
111 | { freeze = \_ src -> Nix.fetchHg url <$> Hg.revision src }
112 | "bzr" ->
113 | do
114 | url <- rcp .: "url"
115 | pure Fetcher
116 | { freeze = \_ src -> Nix.fetchBzr url <$> Bzr.revision src }
117 | "git" ->
118 | do
119 | url <- rcp .: "url"
120 | branch <- rcp .:? "branch"
121 | pure Fetcher
122 | { freeze = \melpa src ->
123 | do
124 | files <- getFiles melpa name
125 | Nix.fetchGit url branch <$> Git.revision src branch files
126 | }
127 | "github" ->
128 | do
129 | (owner, Text.drop 1 -> repo) <- Text.breakOn "/" <$> rcp .: "repo"
130 | pure Fetcher
131 | { freeze = \melpa src ->
132 | do
133 | files <- getFiles melpa name
134 | Nix.fetchGitHub owner repo <$> Git.revision src Nothing files
135 | }
136 | "gitlab" ->
137 | do
138 | (owner, Text.drop 1 -> repo) <- Text.breakOn "/" <$> rcp .: "repo"
139 | pure Fetcher
140 | { freeze = \melpa src ->
141 | do
142 | files <- getFiles melpa name
143 | Nix.fetchGitLab owner repo <$> Git.revision src Nothing files
144 | }
145 | "cvs" ->
146 | do
147 | cvsRoot <- rcp .: "url"
148 | cvsModule <- rcp .: "module"
149 | pure Fetcher { freeze = \_ _ -> pure $ Nix.fetchCVS cvsRoot cvsModule }
150 | "hg" ->
151 | do
152 | url <- rcp .: "url"
153 | pure Fetcher
154 | { freeze = \_ src -> Nix.fetchHg url <$> Hg.revision src }
155 | "svn" ->
156 | do
157 | url <- rcp .: "url"
158 | pure Fetcher
159 | { freeze = \_ src -> Nix.fetchSVN url <$> SVN.revision src }
160 | "wiki" ->
161 | do
162 | url <- rcp .:? "url"
163 | pure Fetcher
164 | { freeze = \_ _ ->
165 | do
166 | rev <- Wiki.revision name url
167 | pure $ Nix.fetchURL rev (Just $ name <> ".el")
168 | }
169 | _ -> fail ("fetcher `" ++ Text.unpack fetcher ++ "' not implemented")
170 |
171 |
172 | getFiles :: Melpa -> Text -> IO [FilePath]
173 | getFiles melpa name =
174 | do
175 | buildEl <- getDataFileName "scripts/build.el"
176 | let
177 | args =
178 | [ "-Q", "--batch"
179 | , "-L", packageBuildDir melpa
180 | , "-l", buildEl
181 | , "-f", "files"
182 | , Text.unpack name
183 | ]
184 | cwd = Just (melpaDir melpa)
185 | runInteractiveProcess "emacs" args cwd Nothing $ \out -> do
186 | r <- Aeson.parseEither Aeson.parseJSON <$> Stream.parseFromStream Aeson.json' out
187 | case r of
188 | Left err -> throwM (ParseFilesError err)
189 | Right pkgInfo -> pure pkgInfo
190 |
--------------------------------------------------------------------------------
/src/Distribution/Melpa/Melpa.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE OverloadedStrings #-}
22 | {-# LANGUAGE RecordWildCards #-}
23 | {-# LANGUAGE ScopedTypeVariables #-}
24 | {-# LANGUAGE ViewPatterns #-}
25 |
26 | module Distribution.Melpa.Melpa
27 | ( Melpa (..), packageBuildDir
28 | , ParseMelpaError (..)
29 | , Stable (..)
30 | ) where
31 |
32 | import Control.Exception ( Exception )
33 | import Data.Text ( Text )
34 | import Data.Typeable ( Typeable )
35 | import System.FilePath
36 |
37 |
38 | data Melpa =
39 | Melpa
40 | { melpaDir :: FilePath
41 | , melpaCommit :: Text
42 | }
43 |
44 | data ParseMelpaError = ParseMelpaError String
45 | deriving (Show, Typeable)
46 |
47 | instance Exception ParseMelpaError
48 |
49 |
50 | newtype Stable = Stable { stable :: Bool }
51 |
52 |
53 | packageBuildDir :: Melpa -> FilePath
54 | packageBuildDir Melpa {..} = melpaDir > "package-build"
55 |
--------------------------------------------------------------------------------
/src/Distribution/Melpa/PkgInfo.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE LambdaCase #-}
22 | {-# LANGUAGE OverloadedStrings #-}
23 | {-# LANGUAGE RecordWildCards #-}
24 | {-# LANGUAGE ScopedTypeVariables #-}
25 | {-# LANGUAGE ViewPatterns #-}
26 |
27 | module Distribution.Melpa.PkgInfo ( PkgInfo (..), parsePkgInfo ) where
28 |
29 | import Data.Aeson.Types
30 | import Data.Foldable ( toList )
31 | import qualified Data.HashMap.Strict as HashMap
32 | import Data.Scientific ( floatingOrInteger )
33 | import Data.Set ( Set )
34 | import qualified Data.Set as Set
35 | import Data.Text ( Text )
36 | import Data.Version ( Version, makeVersion )
37 |
38 |
39 | data PkgInfo =
40 | PkgInfo
41 | { version :: !Version
42 | , deps :: !(Set Text)
43 | }
44 |
45 |
46 | parseVersion :: Value -> Parser Version
47 | parseVersion =
48 | withArray "version" $ fmap makeVersion . traverse parseNatural . toList
49 | where
50 | parseNatural =
51 | withScientific "natural number" $ \x ->
52 | case floatingOrInteger x of
53 | Left (r :: Double) -> fail ("not an integer: " ++ show r)
54 | Right i -> pure i
55 |
56 |
57 | parsePkgInfo :: Value -> Parser PkgInfo
58 | parsePkgInfo =
59 | withObject "pkg-info" $ \obj ->
60 | do
61 | version <- parseVersion =<< obj .: "ver"
62 | deps <- parseDeps =<< obj .: "deps"
63 | pure PkgInfo {..}
64 | where
65 | parseDeps =
66 | \case
67 | Null -> pure Set.empty
68 | Object o -> pure (Set.fromList $ toList $ HashMap.keys o)
69 | _ -> fail "expected map of dependencies or null"
70 |
--------------------------------------------------------------------------------
/src/Distribution/Nix/Builtin.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE OverloadedStrings #-}
22 |
23 | module Distribution.Nix.Builtin (optionalBuiltins) where
24 |
25 | import qualified Data.Set as S
26 | import Data.Text (Text)
27 | import Nix.Expr
28 |
29 | optionalBuiltins :: Text -> (Text, Maybe NExpr)
30 | optionalBuiltins dep
31 | | S.member dep builtin = (dep, Just (mkSym "null"))
32 | | otherwise = (dep, Nothing)
33 | where
34 | builtin = S.fromList
35 | [ "allout", "allout-widgets"
36 | , "ansi-color"
37 | , "antlr-mode"
38 | , "artist"
39 | , "bs"
40 | , "cedet"
41 | , "cfengine"
42 | , "chart"
43 | , "checkdoc"
44 | , "cl-lib"
45 | , "cl-print"
46 | , "cwarn"
47 | , "delim-col"
48 | , "dunnet"
49 | , "ebnf2ps"
50 | , "ede"
51 | , "ediff"
52 | , "edmacro"
53 | , "eieio", "eieio-core"
54 | , "epg"
55 | , "erc"
56 | , "ert"
57 | , "eshell"
58 | , "feedmail"
59 | , "find-cmd"
60 | , "finder"
61 | , "flymake"
62 | , "foldout"
63 | , "footnote"
64 | , "gamegrid"
65 | , "gnus"
66 | , "hippie-exp"
67 | , "htmlfontify"
68 | , "icalendar"
69 | , "idlwave"
70 | , "image-dired"
71 | , "info-xref"
72 | , "inversion"
73 | , "isearchb"
74 | , "js", "json"
75 | , "linum"
76 | , "master"
77 | , "md4"
78 | , "meta-mode"
79 | , "mh-e"
80 | , "mixal-mode"
81 | , "newsticker"
82 | , "ntlm"
83 | , "package"
84 | , "printing"
85 | , "ps-mode"
86 | , "ps-print"
87 | , "pulse"
88 | , "python"
89 | , "regi"
90 | , "remember"
91 | , "repeat"
92 | , "ruby-mode"
93 | , "ruler-mode"
94 | , "savehist"
95 | , "semantic"
96 | , "sh-script"
97 | , "sql"
98 | , "srecode"
99 | , "tabulated-list"
100 | , "tetris"
101 | , "thingatpt"
102 | , "tildify"
103 | , "timeclock"
104 | , "url"
105 | , "vera-mode"
106 | , "viper"
107 | , "wdired"
108 | , "whitespace"
109 | , "woman"
110 | ]
111 |
--------------------------------------------------------------------------------
/src/Distribution/Nix/Exception.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE DeriveDataTypeable #-}
22 |
23 | module Distribution.Nix.Exception where
24 |
25 | import Control.Exception
26 | import Data.Typeable
27 |
28 | data NixError = InvalidIndex FilePath
29 | | PrettyFailed
30 | deriving (Show, Typeable)
31 |
32 | instance Exception NixError
33 |
--------------------------------------------------------------------------------
/src/Distribution/Nix/Fetch.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE DeriveDataTypeable #-}
22 | {-# LANGUAGE OverloadedStrings #-}
23 | {-# LANGUAGE RecordWildCards #-}
24 |
25 | module Distribution.Nix.Fetch where
26 |
27 | import Control.Error
28 | import Control.Exception
29 | import Control.Monad.IO.Class
30 | import Data.ByteString (ByteString)
31 | import Data.Monoid
32 | import Data.Text (Text)
33 | import qualified Data.Text as T
34 | import Data.Typeable (Typeable)
35 | import Network.URI.Encode (encodeText)
36 | import Nix.Expr
37 | import System.Environment (getEnvironment)
38 | import qualified System.IO.Streams as S
39 | import qualified System.IO.Streams.Attoparsec as S
40 | import Data.Aeson ( (.:!), withObject )
41 | import Data.Aeson.Parser ( json' )
42 | import Data.Aeson.Types ( parseEither )
43 |
44 | import Process
45 |
46 | data Fetch = URL { url :: Text, sha256 :: Maybe Text, name :: Maybe Text }
47 | | Git { url :: Text, rev :: Text, branchName :: Maybe Text, sha256 :: Maybe Text }
48 | | Bzr { url :: Text, rev :: Text, sha256 :: Maybe Text }
49 | | CVS { cvsRoot :: Text, cvsModule :: Maybe Text, sha256 :: Maybe Text }
50 | | Hg { url :: Text, rev :: Text, sha256 :: Maybe Text }
51 | | SVN { url :: Text, rev :: Text, sha256 :: Maybe Text }
52 | | GitHub { owner :: Text, repo :: Text, rev :: Text, sha256 :: Maybe Text }
53 | | GitLab { owner :: Text, repo :: Text, rev :: Text, sha256 :: Maybe Text }
54 |
55 |
56 | fetchURL :: Text -> Maybe Text -> Fetch
57 | fetchURL url name = URL {..} where sha256 = Nothing
58 |
59 | fetchGit :: Text -> Maybe Text -> Text -> Fetch
60 | fetchGit url branchName rev = Git {..} where sha256 = Nothing
61 |
62 | fetchBzr :: Text -> Text -> Fetch
63 | fetchBzr url rev = Bzr {..} where sha256 = Nothing
64 |
65 | fetchCVS :: Text -> Maybe Text -> Fetch
66 | fetchCVS cvsRoot cvsModule = CVS {..} where sha256 = Nothing
67 |
68 | fetchHg :: Text -> Text -> Fetch
69 | fetchHg url rev = Hg {..} where sha256 = Nothing
70 |
71 | fetchSVN :: Text -> Text -> Fetch
72 | fetchSVN url rev = SVN {..} where sha256 = Nothing
73 |
74 | fetchGitHub :: Text -> Text -> Text -> Fetch
75 | fetchGitHub owner repo rev = GitHub {..} where sha256 = Nothing
76 |
77 | fetchGitLab :: Text -> Text -> Text -> Fetch
78 | fetchGitLab owner repo rev = GitLab {..} where sha256 = Nothing
79 |
80 | importFetcher :: Fetch -> Text
81 | importFetcher (URL {}) = "fetchurl"
82 | importFetcher (Git {}) = "fetchgit"
83 | importFetcher (Bzr {}) = "fetchbzr"
84 | importFetcher (CVS {}) = "fetchcvs"
85 | importFetcher (Hg {}) = "fetchhg"
86 | importFetcher (SVN {}) = "fetchsvn"
87 | importFetcher (GitHub {}) = "fetchFromGitHub"
88 | importFetcher (GitLab {}) = "fetchFromGitLab"
89 |
90 | fetchExpr :: Fetch -> NExpr
91 | fetchExpr (URL {..}) = ((@@) (mkSym "fetchurl") . mkNonRecSet . catMaybes)
92 | [ Just ("url" `bindTo` mkStr url)
93 | , bindTo "sha256" . mkStr <$> sha256
94 | , bindTo "name" . mkStr <$> name
95 | ]
96 | fetchExpr (Git {..}) = ((@@) (mkSym "fetchgit") . mkNonRecSet . catMaybes)
97 | [ Just ("url" `bindTo` mkStr url)
98 | , Just ("rev" `bindTo` mkStr rev)
99 | , bindTo "branchName" . mkStr <$> branchName
100 | , bindTo "sha256" . mkStr <$> sha256
101 | ]
102 | fetchExpr (Bzr {..}) = ((@@) (mkSym "fetchbzr") . mkNonRecSet . catMaybes)
103 | [ Just ("url" `bindTo` mkStr url)
104 | , Just ("rev" `bindTo` mkStr rev)
105 | , bindTo "sha256" . mkStr <$> sha256
106 | ]
107 | fetchExpr (CVS {..}) = ((@@) (mkSym "fetchcvs") . mkNonRecSet . catMaybes)
108 | [ Just ("cvsRoot" `bindTo` mkStr cvsRoot)
109 | , bindTo "module" . mkStr <$> cvsModule
110 | , bindTo "sha256" . mkStr <$> sha256
111 | ]
112 | fetchExpr (Hg {..}) = ((@@) (mkSym "fetchhg") . mkNonRecSet . catMaybes)
113 | [ Just ("url" `bindTo` mkStr url)
114 | , Just ("rev" `bindTo` mkStr rev)
115 | , bindTo "sha256" . mkStr <$> sha256
116 | ]
117 | fetchExpr (SVN {..}) = ((@@) (mkSym "fetchsvn") . mkNonRecSet . catMaybes)
118 | [ Just ("url" `bindTo` mkStr url)
119 | , Just ("rev" `bindTo` mkStr rev)
120 | , bindTo "sha256" . mkStr <$> sha256
121 | ]
122 | fetchExpr (GitHub {..}) = ((@@) (mkSym "fetchFromGitHub") . mkNonRecSet . catMaybes)
123 | [ Just ("owner" `bindTo` mkStr owner)
124 | , Just ("repo" `bindTo` mkStr repo)
125 | , Just ("rev" `bindTo` mkStr rev)
126 | , bindTo "sha256" . mkStr <$> sha256
127 | ]
128 | fetchExpr (GitLab {..}) = ((@@) (mkSym "fetchFromGitLab") . mkNonRecSet . catMaybes)
129 | [ Just ("owner" `bindTo` mkStr owner)
130 | , Just ("repo" `bindTo` mkStr repo)
131 | , Just ("rev" `bindTo` mkStr rev)
132 | , bindTo "sha256" . mkStr <$> sha256
133 | ]
134 |
135 | newtype FetchError = FetchError SomeException
136 | deriving (Show, Typeable)
137 |
138 | instance Exception FetchError
139 |
140 | prefetchHelper :: String -> [String]
141 | -> (S.InputStream ByteString -> IO a)
142 | -> IO a
143 | prefetchHelper fetcher args go = mapException FetchError helper
144 | where
145 | helper = do
146 | env <- addToEnv [("PRINT_PATH", "1")]
147 | runInteractiveProcess fetcher args Nothing (Just env) go
148 |
149 | addToEnv :: [(String, String)] -> IO [(String, String)]
150 | addToEnv env = (++ env) <$> getEnvironment
151 |
152 | data BadPrefetchOutput = BadPrefetchOutput
153 | deriving (Show, Typeable)
154 |
155 | instance Exception BadPrefetchOutput
156 |
157 | prefetch :: Text -> Fetch -> IO (FilePath, Fetch)
158 |
159 | prefetch _ fetch@(URL {..}) = do
160 | let args = [T.unpack url]
161 | prefetchHelper "nix-prefetch-url" args $ \out -> do
162 | hashes <- liftIO (S.lines out >>= S.decodeUtf8 >>= S.toList)
163 | case hashes of
164 | (hash:path:_) -> pure (T.unpack path, fetch { sha256 = Just hash })
165 | _ -> throwIO BadPrefetchOutput
166 |
167 | prefetch _ fetch@(Git {..}) = do
168 | let
169 | args = [ "--fetch-submodules"
170 | , "--url", T.unpack url, "--rev", T.unpack rev
171 | ] ++ fromMaybe [] branch
172 | branch = do
173 | name <- branchName
174 | pure ["--branch-name", T.unpack name]
175 | jsonp = withObject "need an object" (\o -> o .:! "sha256")
176 | prefetchHelper "nix-prefetch-git" args $ \out -> do
177 | sha256_ <- liftIO $ parseEither jsonp <$> S.parseFromStream json' out
178 | pathes <- liftIO (S.lines out >>= S.decodeUtf8 >>= S.toList)
179 | case (sha256_, pathes) of
180 | (Right sha, (_:path:_)) -> pure (T.unpack path, fetch { sha256 = sha })
181 | _ -> throwIO BadPrefetchOutput
182 |
183 | prefetch _ fetch@(Bzr {..}) = do
184 | let args = [T.unpack url, T.unpack rev]
185 | prefetchHelper "nix-prefetch-bzr" args $ \out -> do
186 | hashes <- liftIO (S.lines out >>= S.decodeUtf8 >>= S.toList)
187 | case hashes of
188 | (_:hash:path:_) -> pure (T.unpack path, fetch { sha256 = Just hash })
189 | _ -> throwIO BadPrefetchOutput
190 |
191 | prefetch _ fetch@(Hg {..}) = do
192 | let args = [T.unpack url, T.unpack rev]
193 | prefetchHelper "nix-prefetch-hg" args $ \out -> do
194 | hashes <- liftIO (S.lines out >>= S.decodeUtf8 >>= S.toList)
195 | case hashes of
196 | (hash:path:_) -> pure (T.unpack path, fetch { sha256 = Just hash })
197 | _ -> throwIO BadPrefetchOutput
198 |
199 | prefetch name fetch@(CVS {..}) = do
200 | let args = [T.unpack cvsRoot, T.unpack (fromMaybe name cvsModule)]
201 | prefetchHelper "nix-prefetch-cvs" args $ \out -> do
202 | hashes <- liftIO (S.lines out >>= S.decodeUtf8 >>= S.toList)
203 | case hashes of
204 | (hash:path:_) -> pure (T.unpack path, fetch { sha256 = Just hash })
205 | _ -> throwIO BadPrefetchOutput
206 |
207 | prefetch _ fetch@(SVN {..}) = do
208 | let args = [T.unpack url, T.unpack rev]
209 | prefetchHelper "nix-prefetch-svn" args $ \out -> do
210 | hashes <- liftIO (S.lines out >>= S.decodeUtf8 >>= S.toList)
211 | case hashes of
212 | (_:hash:path:_) -> pure (T.unpack path, fetch { sha256 = Just hash })
213 | _ -> throwIO BadPrefetchOutput
214 |
215 | prefetch _ fetch@(GitHub {..}) = do
216 | let
217 | args = ["--name", T.unpack name, "--unpack", T.unpack url]
218 | url = "https://github.com/" <> owner <> "/" <> repo <> "/archive/" <> rev <> ".tar.gz"
219 | name = repo <> "-" <> rev <> "-src"
220 | prefetchHelper "nix-prefetch-url" args $ \out -> do
221 | hashes <- liftIO (S.lines out >>= S.decodeUtf8 >>= S.toList)
222 | case hashes of
223 | (hash:path:_) -> pure (T.unpack path, fetch { sha256 = Just hash })
224 | _ -> throwIO BadPrefetchOutput
225 |
226 | prefetch _ fetch@(GitLab {..}) = do
227 | let
228 | args = ["--name", T.unpack name, "--unpack", T.unpack url]
229 | slug = encodeText $ owner <> "/" <> repo
230 | escapedRev = encodeText rev
231 | url = "https://gitlab.com/api/v4/projects/" <> slug
232 | <> "/repository/archive.tar.gz?sha=" <> escapedRev
233 | name = repo <> "-" <> rev <> "-src"
234 | prefetchHelper "nix-prefetch-url" args $ \out -> do
235 | hashes <- liftIO (S.lines out >>= S.decodeUtf8 >>= S.toList)
236 | case hashes of
237 | (hash:path:_) -> pure (T.unpack path, fetch { sha256 = Just hash })
238 | _ -> throwIO BadPrefetchOutput
239 |
--------------------------------------------------------------------------------
/src/Distribution/Nix/Hash.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE DeriveDataTypeable #-}
22 |
23 | module Distribution.Nix.Hash where
24 |
25 | import Control.Exception
26 | import Data.Text (Text)
27 | import Data.Typeable (Typeable)
28 | import qualified System.IO.Streams as S
29 |
30 | import Process
31 |
32 | data NoHashOutput = NoHashOutput
33 | deriving (Show, Typeable)
34 |
35 | instance Exception NoHashOutput
36 |
37 | newtype NixHashError = NixHashError SomeException
38 | deriving (Show, Typeable)
39 |
40 | instance Exception NixHashError
41 |
42 | hash :: FilePath -> IO Text
43 | hash filename
44 | = mapException NixHashError
45 | (runInteractiveProcess "nix-hash" args Nothing Nothing getHash)
46 | where
47 | args = [ "--type", "sha256", "--base32", "--flat", filename ]
48 | getHash out = do
49 | hashes <- S.lines out >>= S.decodeUtf8 >>= S.toList
50 | case hashes of
51 | (theHash : _) -> pure theHash
52 | _ -> throwIO NoHashOutput
53 |
--------------------------------------------------------------------------------
/src/Distribution/Nix/Index.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE FlexibleInstances #-}
22 | {-# LANGUAGE LambdaCase #-}
23 | {-# LANGUAGE RankNTypes #-}
24 | {-# LANGUAGE OverloadedStrings #-}
25 | {-# LANGUAGE TupleSections #-}
26 | {-# LANGUAGE TypeSynonymInstances #-}
27 | {-# LANGUAGE ViewPatterns #-}
28 |
29 | module Distribution.Nix.Index ( readIndex, writeIndex ) where
30 |
31 | import Control.Exception
32 | import Data.Fix
33 | import Data.List ( isPrefixOf )
34 | import Data.List.NonEmpty ( NonEmpty (..) )
35 | import Data.Map.Strict ( Map )
36 | import qualified Data.Map.Strict as Map
37 | import Data.Maybe ( isJust )
38 | import Data.Text ( Text )
39 | import qualified Data.Text as Text
40 | import Nix.Parser ( NAssoc (..), OperatorInfo (..), Result (..), getBinaryOperator, getUnaryOperator, parseNixFile )
41 | import Nix.Pretty hiding ( exprFNixDoc, prettyNix, prettyParams, prettyParamSet )
42 | import Nix.Expr
43 | import Prelude hiding ( (<$>) )
44 | import System.Directory ( doesFileExist )
45 | import System.IO.Streams ( OutputStream )
46 | import qualified System.IO.Streams as S
47 | import Text.PrettyPrint.ANSI.Leijen hiding ( sep )
48 |
49 | import qualified Distribution.Emacs.Name as Emacs
50 | import Distribution.Nix.Exception
51 | import qualified Distribution.Nix.Name as Nix
52 |
53 | readIndex :: FilePath -- ^ output file
54 | -> IO (Map Nix.Name NExpr)
55 | readIndex output = parseOutputOrDefault =<< doesFileExist output
56 | where
57 | die = throwIO (InvalidIndex output)
58 |
59 | parseOutputOrDefault exists
60 | | exists = do
61 | result <- parseNixFile output
62 | case result of
63 | Failure _ -> die
64 | Success parsed ->
65 | maybe die pure (getFunctionBody parsed >>= getPackages)
66 | | otherwise = pure Map.empty
67 |
68 | writeIndex :: FilePath -- ^ output file
69 | -> Map Nix.Name NExpr
70 | -> IO ()
71 | writeIndex output packages = do
72 | S.withFileAsOutput output (write (packageIndex packages))
73 | where
74 | write index out = do
75 | let rendered = renderSmart 1.0 80 (prettyNix index)
76 | displayStream rendered =<< S.encodeUtf8 out
77 | S.write (Just "\n") =<< S.encodeUtf8 out
78 |
79 | getFunctionBody :: NExpr -> Maybe NExpr
80 | getFunctionBody (Fix (NAbs _ body)) = Just body
81 | getFunctionBody _ = Nothing
82 |
83 | getPackages :: NExpr -> Maybe (Map Nix.Name NExpr)
84 | getPackages (Fix (NSet bindings)) =
85 | let
86 | getEname (Fix (NAbs _ (Fix (NBinary NApp (Fix (NSym _)) (Fix (NSet bindings')))))) =
87 | lookup (StaticKey "ename" :| []) $ map (\(NamedVar name value _) -> (name, value)) bindings'
88 | getEname _ = Nothing
89 | getDrv (Fix (NBinary NApp (Fix (NBinary NApp (Fix (NSym "callPackage")) drv)) (Fix (NSet [])))) =
90 | Just drv
91 | getDrv _ = Nothing
92 | getPackage (NamedVar (StaticKey name :| []) expr _) =
93 | case getDrv expr >>= getEname of
94 | Just (Fix (NStr (DoubleQuoted [Plain ename]))) ->
95 | Just (Nix.Name { Nix.fromName = name, Nix.ename = Emacs.Name ename }, expr)
96 | _ -> Nothing
97 | getPackage _ = Nothing
98 | in
99 | fmap Map.fromList (traverse getPackage bindings)
100 | getPackages _ = Nothing
101 |
102 | packageIndex :: Map Nix.Name NExpr -> NExpr
103 | packageIndex (Map.toList -> packages) = mkFunction args body where
104 | args = mkParamset [("callPackage", Nothing)] False
105 | body = (mkNonRecSet . map bindPackage) packages
106 | bindPackage (name, expr) = bindTo (Nix.fromName name) expr
107 |
108 | displayStream :: SimpleDoc -> OutputStream Text -> IO ()
109 | displayStream sdoc out = display sdoc where
110 | display SFail = throwIO PrettyFailed
111 | display SEmpty = return ()
112 | display (SChar c sdoc') = S.write (Just (Text.singleton c)) out >> display sdoc'
113 | display (SText _ t sdoc') = S.write (Just (Text.pack t)) out >> display sdoc'
114 | display (SLine i sdoc') = S.write (Just (Text.cons '\n' (indentation i))) out >> display sdoc'
115 | display (SSGR _ sdoc') = display sdoc'
116 | indentation i = Text.replicate i (Text.singleton ' ')
117 |
118 | prettyParams :: Params NixDoc -> Doc
119 | prettyParams (Param n) = text $ Text.unpack n
120 | prettyParams (ParamSet s v mname) = prettyParamSet s v <> case mname of
121 | Nothing -> empty
122 | Just name | Text.null name -> empty
123 | | otherwise -> text "@" <> text (Text.unpack name)
124 |
125 | prettyParamSet :: ParamSet NixDoc -> Bool -> Doc
126 | prettyParamSet args var =
127 | encloseSep (lbrace <> space) (align (space <> rbrace)) sep (prettyArgs ++ prettyVariadic)
128 | where
129 | prettyArgs = (Map.elems . Map.mapWithKey prettySetArg . Map.fromList) args
130 | prettySetArg n maybeDef = case maybeDef of
131 | Nothing -> text (Text.unpack n)
132 | Just v -> text (Text.unpack n) <+> text "?" <+> withoutParens v
133 | prettyVariadic = [text "..." | var]
134 | sep = align (comma <> space)
135 |
136 | exprFNixDoc :: NExprF NixDoc -> NixDoc
137 | exprFNixDoc = \case
138 | NConstant atom -> prettyAtom atom
139 | NStr str -> simpleExpr $ prettyString str
140 | NList [] -> simpleExpr $ lbracket <> rbracket
141 | NList xs -> simpleExpr $ group $
142 | nest 2 (vsep $ lbracket : map (wrapParens appOpNonAssoc) xs) <$> rbracket
143 | NSet [] -> simpleExpr $ lbrace <> rbrace
144 | NSet xs -> simpleExpr $ group $
145 | nest 2 (vsep $ lbrace : map prettyBind xs) <$> rbrace
146 | NRecSet [] -> simpleExpr $ recPrefix <> lbrace <> rbrace
147 | NRecSet xs -> simpleExpr $ group $
148 | nest 2 (vsep $ recPrefix <> lbrace : map prettyBind xs) <$> rbrace
149 | NAbs args body -> leastPrecedence $
150 | nest 2 ((prettyParams args <> colon) <$> withoutParens body)
151 | NBinary NApp fun arg ->
152 | mkNixDoc (wrapParens appOp fun <+> wrapParens appOpNonAssoc arg) appOp
153 | NBinary op r1 r2 -> flip mkNixDoc opInfo $ hsep
154 | [ wrapParens (f NAssocLeft) r1
155 | , text $ Text.unpack $ operatorName opInfo
156 | , wrapParens (f NAssocRight) r2
157 | ]
158 | where
159 | opInfo = getBinaryOperator op
160 | f x | associativity opInfo /= x = opInfo { associativity = NAssocNone }
161 | | otherwise = opInfo
162 | NUnary op r1 ->
163 | mkNixDoc (text (Text.unpack (operatorName opInfo)) <> wrapParens opInfo r1) opInfo
164 | where opInfo = getUnaryOperator op
165 | NSelect r attr o ->
166 | (if isJust o then leastPrecedence else flip mkNixDoc selectOp) $
167 | wrapPath selectOp r <> dot <> prettySelector attr <> ordoc
168 | where ordoc = maybe empty (((space <> text "or") <+>) . wrapParens selectOp) o
169 | NHasAttr r attr ->
170 | mkNixDoc (wrapParens hasAttrOp r <+> text "?" <+> prettySelector attr) hasAttrOp
171 | NEnvPath p -> simpleExpr $ text ("<" ++ p ++ ">")
172 | NLiteralPath p -> pathExpr $ text $ case p of
173 | "./" -> "./."
174 | "../" -> "../."
175 | ".." -> "../."
176 | txt | "/" `isPrefixOf` txt -> txt
177 | | "~/" `isPrefixOf` txt -> txt
178 | | "./" `isPrefixOf` txt -> txt
179 | | "../" `isPrefixOf` txt -> txt
180 | | otherwise -> "./" ++ txt
181 | NSym name -> simpleExpr $ text (Text.unpack name)
182 | NLet binds body -> leastPrecedence $ group $ text "let" <$> indent 2 (
183 | vsep (map prettyBind binds)) <$> text "in" <+> withoutParens body
184 | NIf cond trueBody falseBody -> leastPrecedence $
185 | group $ nest 2 $ (text "if" <+> withoutParens cond) <$>
186 | ( align (text "then" <+> withoutParens trueBody)
187 | <$> align (text "else" <+> withoutParens falseBody)
188 | )
189 | NWith scope body -> leastPrecedence $
190 | text "with" <+> withoutParens scope <> semi <$> align (withoutParens body)
191 | NAssert cond body -> leastPrecedence $
192 | text "assert" <+> withoutParens cond <> semi <$> align (withoutParens body)
193 | where
194 | recPrefix = text "rec" <> space
195 |
196 | prettyNix :: NExpr -> Doc
197 | prettyNix = withoutParens . cata exprFNixDoc
198 |
--------------------------------------------------------------------------------
/src/Distribution/Nix/Name.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE DeriveDataTypeable #-}
22 | {-# LANGUAGE DuplicateRecordFields #-}
23 | {-# LANGUAGE ExistentialQuantification #-}
24 | {-# LANGUAGE GeneralizedNewtypeDeriving #-}
25 | {-# LANGUAGE OverloadedStrings #-}
26 | {-# LANGUAGE RecordWildCards #-}
27 | {-# LANGUAGE StandaloneDeriving #-}
28 | {-# LANGUAGE TemplateHaskell #-}
29 | {-# LANGUAGE ViewPatterns #-}
30 |
31 | module Distribution.Nix.Name
32 | ( Name (..)
33 | , readNames
34 | , fromText, getName
35 | , InvalidName (..)
36 | , ReadNamesError (..)
37 | , ParseNixError (..)
38 | ) where
39 |
40 | import qualified Data.Char as Char
41 | import Data.Fix ( Fix (..) )
42 | import Data.Hashable
43 | import Data.HashMap.Strict ( HashMap )
44 | import qualified Data.HashMap.Strict as HashMap
45 | import Data.Maybe ( fromMaybe )
46 | import Data.Monoid
47 | import Data.Set ( Set )
48 | import qualified Data.Set as Set
49 | import Data.Text ( Text )
50 | import qualified Data.Text as Text
51 | import Data.Time.Clock ( getCurrentTime )
52 | import Nix.Exec ( evalExprLoc, runLazyM )
53 | import Nix.Normal ( normalForm )
54 | import Nix.Options ( defaultOptions )
55 | import Nix.Parser
56 | import Nix.Value
57 | import Text.PrettyPrint.ANSI.Leijen ( Doc, Pretty (..) )
58 | import qualified Text.PrettyPrint.ANSI.Leijen as Pretty
59 |
60 | import qualified Distribution.Emacs.Name as Emacs
61 | import Exceptions
62 |
63 |
64 | -- | A valid Nix package name.
65 | data Name =
66 | Name
67 | {
68 | fromName :: Text,
69 | ename :: Emacs.Name
70 | }
71 | deriving (Eq, Ord, Show)
72 |
73 | instance Hashable Name where
74 | hashWithSalt salt name = hashWithSalt salt (fromName name)
75 |
76 |
77 | data InvalidName = forall e. (Exception e, Pretty e) => InvalidName e
78 | mkException 'PrettyException ''InvalidName
79 |
80 | instance Pretty InvalidName where
81 | pretty (InvalidName e) =
82 | "invalid name: " <> Pretty.pretty e
83 |
84 |
85 | -- | An exception thrown if @invalidName@ is invalid because it begins with a
86 | -- digit.
87 | --
88 | -- Parent: 'InvalidName'
89 | data LeadingDigit = LeadingDigit { invalidName :: Text }
90 | mkException 'InvalidName ''LeadingDigit
91 |
92 | instance Pretty LeadingDigit where
93 | pretty LeadingDigit {..} =
94 | "'" <> Pretty.string (Text.unpack invalidName) <> "' begins with a digit"
95 |
96 |
97 | -- | An exception thrown if @invalidName@ is invalid due to the illegal
98 | -- character @illegalChar@.
99 | --
100 | -- Parent: 'InvalidName'
101 | data IllegalChar = IllegalChar { invalidName :: Text, illegalChar :: Char }
102 | mkException 'InvalidName ''IllegalChar
103 |
104 | instance Pretty IllegalChar where
105 | pretty IllegalChar {..} =
106 | "'" <> Pretty.string (Text.unpack invalidName)
107 | <> "' contains illegal character '" <> Pretty.char illegalChar <> "'"
108 |
109 | -- | Characters that may not appear in a Nix identifier.
110 | illegalChars :: Set Char
111 | illegalChars = Set.fromList ['@', '+']
112 |
113 |
114 | -- | Decode a valid Nix package name from 'Text'; if the name is invalid, an
115 | -- exception is thrown. Valid Nix names must not begin with a digit or contain
116 | -- the characters in 'illegalChars'.
117 | --
118 | -- Throws: 'LeadingDigit', 'IllegalChar'
119 | fromText :: MonadThrow m => Emacs.Name -> m Name
120 | fromText name =
121 | case getFirst (Text.foldl' firstIllegal mempty txt) of
122 | Nothing
123 | | leadingDigit -> throwM (LeadingDigit { invalidName = txt })
124 | | otherwise -> pure Name { fromName = txt, ename = name }
125 | Just illegal ->
126 | throwM (IllegalChar { invalidName = txt, illegalChar = illegal })
127 | where
128 | txt = Emacs.fromName name
129 | leadingDigit = Char.isDigit (Text.head txt)
130 |
131 | -- | Find the first illegal character in the name.
132 | firstIllegal a c
133 | | Set.member c illegalChars = a <> pure c
134 | | otherwise = a <> mempty
135 |
136 |
137 | -- | Decode a Nix package name using the provided map. The name is decoded with
138 | -- 'fromText' if it is not in the map.
139 | --
140 | -- Throws: 'LeadingDigit', 'IllegalChar'
141 | getName :: MonadThrow m => HashMap Emacs.Name Name -> Emacs.Name -> m Name
142 | getName nameMap name =
143 | fromMaybe (fromText name) (pure <$> HashMap.lookup name nameMap)
144 |
145 |
146 | data ParseNixError = ParseNixError { reason :: Doc }
147 | mkException 'PrettyException ''ParseNixError
148 |
149 |
150 | instance Pretty ParseNixError where
151 | pretty ParseNixError {..} = reason
152 |
153 |
154 | -- | @ReadNamesError@ is thrown by 'readNames' if the Nix expression can be
155 | -- parsed and evaluated, but the resulting value is not a valid map of Emacs
156 | -- names to Nix names.
157 | data ReadNamesError =
158 | ReadNamesError
159 | { filePath :: FilePath
160 | , attr :: Maybe Text
161 | , reason :: Doc
162 | }
163 | mkException 'PrettyException ''ReadNamesError
164 |
165 | instance Pretty ReadNamesError where
166 | pretty ReadNamesError {..} =
167 | Pretty.hsep
168 | [ (Pretty.bold . Pretty.string) filePath <> Pretty.colon
169 | , maybe Pretty.empty
170 | (\d -> (Pretty.bold . Pretty.text . Text.unpack) d <> Pretty.colon)
171 | attr
172 | , reason
173 | ]
174 |
175 | -- | Read the map of names from a file, which should contain a Nix expression.
176 | readNames :: FilePath
177 | -> IO (HashMap Emacs.Name Name)
178 | readNames filename =
179 | do
180 | result <- parseNixFileLoc filename
181 | case result of
182 | Failure err -> throwM (ParseNixError err)
183 | Success parsed ->
184 | do
185 | time <- getCurrentTime
186 | let opts = defaultOptions time
187 | getSet =<< runLazyM opts (normalForm =<< evalExprLoc parsed)
188 | where
189 | mapKeys f =
190 | HashMap.fromList . map (\(k, v) -> (f k, v)) . HashMap.toList
191 |
192 | getSet value =
193 | case unFix value of
194 | NVSetF names _ ->
195 | HashMap.traverseWithKey getBound (mapKeys Emacs.Name names)
196 | NVConstantF {} -> found "constant"
197 | NVStrF {} -> found "string"
198 | NVPathF {} -> found "path"
199 | NVListF {} -> found "list"
200 | NVClosureF {} -> found "closure"
201 | NVBuiltinF {} -> found "builtin"
202 | where
203 | found what =
204 | throwM ReadNamesError
205 | { filePath = filename
206 | , attr = Nothing
207 | , reason =
208 | Pretty.hsep
209 | [ "expected"
210 | , Pretty.bold "set" <> Pretty.comma
211 | , "but found"
212 | , (Pretty.bold . Pretty.text) what
213 | ]
214 | }
215 |
216 | getBound ename0 value =
217 | case unFix value of
218 | NVStrF name _ -> pure Name { fromName = name, ename = ename0 }
219 | NVSetF {} -> found "set"
220 | NVConstantF {} -> found "constant"
221 | NVPathF {} -> found "path"
222 | NVListF {} -> found "list"
223 | NVClosureF {} -> found "closure"
224 | NVBuiltinF {} -> found "builtin"
225 | where
226 | found what =
227 | throwM ReadNamesError
228 | { filePath = filename
229 | , attr = Just (Emacs.fromName ename0)
230 | , reason =
231 | Pretty.hsep
232 | [ "expected"
233 | , Pretty.bold "string" <> Pretty.comma
234 | , "but found"
235 | , (Pretty.bold . Pretty.text) what
236 | ]
237 | }
238 |
--------------------------------------------------------------------------------
/src/Distribution/Nix/Package/Elpa.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE OverloadedLists #-}
22 | {-# LANGUAGE OverloadedStrings #-}
23 | {-# LANGUAGE RecordWildCards #-}
24 |
25 | module Distribution.Nix.Package.Elpa ( Package(..), expression ) where
26 |
27 | import Data.Fix
28 | import Data.Text ( Text )
29 | import qualified Data.Text as T
30 | import Nix.Expr
31 | import System.FilePath ( (>), (<.>) )
32 |
33 | import Distribution.Nix.Builtin
34 | import Distribution.Nix.Fetch ( Fetch, fetchExpr, importFetcher )
35 | import Distribution.Nix.Name
36 |
37 | data Package
38 | = Package
39 | { pname :: !Name
40 | , ename :: !Text
41 | , version :: !Text
42 | , fetch :: !Fetch
43 | , deps :: ![Name]
44 | }
45 |
46 | expression :: Package -> String -> NExpr
47 | expression (Package {..}) server = (mkSym "callPackage") @@ drv @@ emptySet where
48 | drv = mkFunction args body
49 | emptySet = mkNonRecSet []
50 | requires = map fromName deps
51 | args = (flip mkParamset False . map optionalBuiltins)
52 | ("lib" : "elpaBuild" : importFetcher fetch : requires)
53 | body = ((@@) (mkSym "elpaBuild") . mkNonRecSet)
54 | [ "pname" `bindTo` mkStr (fromName pname)
55 | , "ename" `bindTo` mkStr ename
56 | , "version" `bindTo` mkStr version
57 | , "src" `bindTo` fetchExpr fetch
58 | , "packageRequires" `bindTo` mkList (map mkSym requires)
59 | , "meta" `bindTo` meta
60 | ]
61 | where
62 | meta = mkNonRecSet
63 | [ "homepage" `bindTo` mkStr homepage
64 | , "license" `bindTo` license
65 | ]
66 | where
67 | homepage = T.pack $ server > T.unpack ename <.> "html"
68 | license = Fix (NSelect (mkSym "lib") [StaticKey "licenses", StaticKey "free"] Nothing)
69 |
--------------------------------------------------------------------------------
/src/Distribution/Nix/Package/Melpa.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE DuplicateRecordFields #-}
22 | {-# LANGUAGE NamedFieldPuns #-}
23 | {-# LANGUAGE OverloadedLists #-}
24 | {-# LANGUAGE OverloadedStrings #-}
25 | {-# LANGUAGE RecordWildCards #-}
26 |
27 | module Distribution.Nix.Package.Melpa ( Package(..), Recipe(..), expression ) where
28 |
29 | import Data.Fix
30 | import Data.Text ( Text )
31 | import qualified Data.Text as T
32 | import Data.Version ( Version, showVersion )
33 | import Nix.Expr
34 |
35 | import Distribution.Nix.Builtin
36 | import Distribution.Nix.Fetch ( Fetch, fetchExpr, importFetcher )
37 | import Distribution.Nix.Name
38 |
39 | data Package
40 | = Package
41 | { pname :: !Name
42 | , version :: !Version
43 | , fetch :: !Fetch
44 | , deps :: ![Name]
45 | , recipe :: !Recipe
46 | }
47 |
48 | data Recipe
49 | = Recipe { ename :: !Text
50 | , commit :: !Text
51 | , sha256 :: !Text
52 | }
53 |
54 | expression :: Package -> NExpr
55 | expression (Package {..}) = (mkSym "callPackage") @@ drv @@ emptySet where
56 | drv = mkFunction args body
57 | emptySet = mkNonRecSet []
58 | requires = map fromName deps
59 | args = (flip mkParamset False . map optionalBuiltins)
60 | ("lib" : "melpaBuild" : "fetchurl" : importFetcher fetch : requires)
61 | body = ((@@) (mkSym "melpaBuild") . mkNonRecSet)
62 | [ "pname" `bindTo` mkStr (fromName pname)
63 | , "ename" `bindTo` mkStr ename
64 | , "version" `bindTo` mkStr (T.pack $ showVersion version)
65 | , "src" `bindTo` fetchExpr fetch
66 | , "recipe" `bindTo` fetchRecipe
67 | , "packageRequires" `bindTo` mkList (map mkSym requires)
68 | , "meta" `bindTo` meta
69 | ]
70 | where
71 | Recipe { ename, commit } = recipe
72 | meta = mkNonRecSet
73 | [ "homepage" `bindTo` mkStr homepage
74 | , "license" `bindTo` license
75 | ]
76 | where
77 | homepage = T.append "https://melpa.org/#/" ename
78 | license =
79 | Fix (NSelect (mkSym "lib")
80 | [StaticKey "licenses", StaticKey "free"] Nothing)
81 | fetchRecipe = ((@@) (mkSym "fetchurl") . mkNonRecSet)
82 | [ "url" `bindTo` mkStr
83 | (T.concat
84 | [ "https://raw.githubusercontent.com/milkypostman/melpa/"
85 | , commit
86 | , "/recipes/"
87 | , ename
88 | ])
89 | , "sha256" `bindTo` mkStr (sha256 recipe)
90 | , "name" `bindTo` mkStr "recipe"
91 | ]
92 |
--------------------------------------------------------------------------------
/src/Distribution/SVN.hs:
--------------------------------------------------------------------------------
1 | {-
2 | emacs2nix - Generate Nix expressions for Emacs packages
3 | Copyright (C) 2018 Thomas Tuegel
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 |
18 | -}
19 |
20 |
21 | {-# LANGUAGE OverloadedStrings #-}
22 |
23 | module Distribution.SVN ( revision ) where
24 |
25 | import Data.Text ( Text )
26 | import qualified Data.Text as Text
27 | import qualified System.IO.Streams as Stream
28 |
29 | import Exceptions
30 | import Process ( runInteractiveProcess )
31 |
32 |
33 | -- | Find the latest revision in a Subversion repository.
34 | revision :: FilePath -> IO Text
35 | revision tmp = do
36 | runInteractiveProcess "svn" ["info"] (Just tmp) Nothing $ \out -> do
37 | revs <- Stream.mapMaybe getRev =<< (Stream.lines out >>= Stream.decodeUtf8)
38 | maybe (throwM NoRevision) pure =<< Stream.read revs
39 | where
40 | getRev = (<$>) Text.strip . Text.stripPrefix "Revision:"
41 |
--------------------------------------------------------------------------------
/src/Distribution/Wiki.hs:
--------------------------------------------------------------------------------
1 | {-
2 | emacs2nix - Generate Nix expressions for Emacs packages
3 | Copyright (C) 2018 Thomas Tuegel
4 |
5 | This program is free software: you can redistribute it and/or modify
6 | it under the terms of the GNU General Public License as published by
7 | the Free Software Foundation, either version 3 of the License, or
8 | (at your option) any later version.
9 |
10 | This program is distributed in the hope that it will be useful,
11 | but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | GNU General Public License for more details.
14 |
15 | You should have received a copy of the GNU General Public License
16 | along with this program. If not, see .
17 |
18 | -}
19 |
20 |
21 | {-# LANGUAGE OverloadedStrings #-}
22 |
23 | module Distribution.Wiki ( revision ) where
24 |
25 | import Data.ByteString ( ByteString )
26 | import qualified Data.ByteString.Lazy as ByteString.Lazy
27 | import Data.Maybe ( fromMaybe )
28 | import Data.Semigroup ( (<>) )
29 | import Data.Text ( Text )
30 | import qualified Data.Text as Text
31 | import qualified Data.Text.Lazy as Lazy ( Text )
32 | import qualified Data.Text.Encoding as Text
33 | import qualified Data.Text.Lazy.Encoding as Text.Lazy
34 | import qualified Data.Text.Read as Text
35 | import qualified Network.Http.Client as HTTP
36 | import Text.Taggy.Parser ( taggyWith )
37 | import Text.Taggy.Types ( Tag (..), Attribute(..) )
38 |
39 |
40 | defaultURL :: Text -> Maybe Integer -> Text
41 | defaultURL name rev =
42 | let
43 | query = (\r -> "?revision=" <> Text.pack (show r)) <$> rev
44 | in
45 | "https://www.emacswiki.org/emacs/download/" <> name <> ".el" <> fromMaybe "" query
46 |
47 |
48 | -- | Find the latest revision of an EmacsWiki file. The revision is a permanent
49 | -- URL referring to a specific version of the file.
50 | revision :: Text -> Maybe Text -> IO Text
51 | revision _ (Just url) = pure url
52 | revision name Nothing =
53 | do
54 | body <- getAsText revisionsPageUrl
55 | return $ defaultURL name $ findLatestRevision $ taggyWith True body
56 | where
57 | revisionsPageUrl :: ByteString
58 | revisionsPageUrl = Text.encodeUtf8 $ "https://www.emacswiki.org/emacs?action=history;id=" <> name <> ".el"
59 |
60 | defaultRevisionAttr = Attribute "href" (defaultURL name Nothing)
61 |
62 | getAsText :: ByteString -> IO Lazy.Text
63 | getAsText url = Text.Lazy.decodeUtf8 . ByteString.Lazy.fromStrict <$> HTTP.get url HTTP.concatHandler
64 |
65 | readDecimal :: Text -> Maybe Integer
66 | readDecimal aText =
67 | case Text.decimal aText of
68 | Left _ -> Nothing
69 | Right (i, _) -> Just i
70 |
71 | revisionPrefix = "Revision "
72 |
73 | findLatestRevision [] = Nothing
74 | findLatestRevision (TagOpen "a" attrs _ : TagText aText : tags)
75 | | elem defaultRevisionAttr attrs && Text.isPrefixOf revisionPrefix aText =
76 | readDecimal $ Text.drop (Text.length revisionPrefix) aText
77 | | otherwise = findLatestRevision tags
78 | findLatestRevision (_:tags) = findLatestRevision tags
79 |
--------------------------------------------------------------------------------
/src/Exceptions.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2018 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 |
22 | {-# LANGUAGE DeriveDataTypeable #-}
23 | {-# LANGUAGE ExistentialQuantification #-}
24 | {-# LANGUAGE OverloadedStrings #-}
25 | {-# LANGUAGE RecordWildCards #-}
26 | {-# LANGUAGE StandaloneDeriving #-}
27 | {-# LANGUAGE TemplateHaskell #-}
28 |
29 | module Exceptions
30 | ( module Control.Monad.Catch
31 | , NoRevision (..)
32 | , Died (..)
33 | , ProcessFailed (..)
34 | , ProcessingFailed (..)
35 | , ParseFilesError (..)
36 | , ManyExceptions (..), manyExceptions
37 | , PrettyException (..), catchPretty, catchPretty_
38 | , mkException
39 | , Context (..), inContext
40 | , DeferredErrors (..)
41 | ) where
42 |
43 | import Control.Monad.Catch
44 | import Data.Semigroup
45 | import Data.Text ( Text )
46 | import qualified Data.Text as Text
47 | import Text.PrettyPrint.ANSI.Leijen ( Doc, Pretty, (<+>) )
48 | import qualified Text.PrettyPrint.ANSI.Leijen as Pretty
49 |
50 | import Exceptions.TH
51 |
52 |
53 | data NoRevision = NoRevision
54 | mkException 'SomeException ''NoRevision
55 |
56 |
57 | data ProcessFailed = ProcessFailed String [String] SomeException
58 | mkException 'SomeException ''ProcessFailed
59 |
60 |
61 | data ProcessingFailed = ProcessingFailed Text Text SomeException
62 | mkException 'SomeException ''ProcessingFailed
63 |
64 |
65 | data ParseFilesError = ParseFilesError String
66 | mkException 'SomeException ''ParseFilesError
67 |
68 |
69 | data PrettyException = forall e. (Exception e, Pretty e) => PrettyException e
70 | mkException 'SomeException ''PrettyException
71 |
72 | instance Pretty PrettyException where
73 | pretty (PrettyException e) = Pretty.pretty e
74 |
75 |
76 | catchPretty :: IO a -> IO (Maybe a)
77 | catchPretty action = catch (Just <$> action) handler
78 | where
79 | handler (PrettyException e) =
80 | do
81 | Pretty.putDoc (Pretty.pretty e)
82 | pure Nothing
83 |
84 |
85 | catchPretty_ :: IO () -> IO ()
86 | catchPretty_ action = catch action handler
87 | where
88 | handler (PrettyException e) = Pretty.putDoc (Pretty.pretty e)
89 |
90 |
91 | data ManyExceptions = forall e. (Exception e, Pretty e) => ManyExceptions [e]
92 | mkException 'PrettyException ''ManyExceptions
93 |
94 | instance Pretty ManyExceptions where
95 | pretty (ManyExceptions es) =
96 | (Pretty.align . Pretty.vsep) (Pretty.pretty <$> es)
97 |
98 |
99 | manyExceptions :: (Exception e, Pretty e) => [e] -> ManyExceptions
100 | manyExceptions = ManyExceptions
101 |
102 |
103 | data Context =
104 | forall e. (Exception e, Pretty e) =>
105 | Context { context :: Doc, exception :: e }
106 | mkException 'PrettyException ''Context
107 |
108 | instance Pretty Context where
109 | pretty Context {..} =
110 | "in " <> context <> ": " <> Pretty.pretty exception
111 |
112 |
113 | mapExceptionM :: (Exception e1, Exception e2, MonadCatch m, MonadThrow m)
114 | => (e1 -> e2) -> m a -> m a
115 | mapExceptionM f = handle (\e1 -> throwM (f e1))
116 |
117 |
118 | inContext :: (MonadCatch m, MonadThrow m) => Doc -> m a -> m a
119 | inContext context =
120 | mapExceptionM (\(PrettyException exception) -> Context {..})
121 |
122 |
123 | data DeferredErrors = DeferredErrors
124 | mkException 'PrettyException ''DeferredErrors
125 |
126 |
127 | instance Pretty DeferredErrors where
128 | pretty DeferredErrors = "deferred error(s) above"
129 |
130 |
131 | data Died = Died Int Text
132 | mkException 'PrettyException ''Died
133 |
134 |
135 | instance Pretty Died where
136 | pretty (Died exit err) =
137 | Pretty.vsep
138 | [ "died with exit code" <+> Pretty.pretty exit <> ":"
139 | , Pretty.string (Text.unpack err)
140 | ]
141 |
--------------------------------------------------------------------------------
/src/Exceptions/TH.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2018 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 |
22 | {-# LANGUAGE StandaloneDeriving #-}
23 | {-# LANGUAGE TemplateHaskell #-}
24 |
25 | module Exceptions.TH where
26 |
27 | import Control.Exception
28 | import Data.Typeable
29 | import Language.Haskell.TH
30 | import qualified Language.Haskell.TH.Lib as TH
31 |
32 |
33 | -- | Declare a heirarchical instance of 'Exception' for the type @child@ wrapped
34 | -- in the @parent@ data constructor. The parent name is a /value/ name (quoted
35 | -- with @'@ in Template Haskell) for a data constructor in case the parent type
36 | -- has multiple constructors. The child name is a /type/ name (quoted with @''@
37 | -- in Template Haskell).
38 | --
39 | -- The required instances of 'Show' and 'Typeable' are automatically derived.
40 | -- The exception type need only be declared.
41 | mkException :: Name -- ^ parent exception constructor name
42 | -> Name -- ^ child exception type name
43 | -> Q [Dec]
44 | mkException parent child =
45 | do
46 | e <- newName "e"
47 | [d|
48 | deriving instance Show $(TH.conT child)
49 | deriving instance Typeable $(TH.conT child)
50 |
51 | instance Exception $(TH.conT child) where
52 | toException $(TH.varP e) = toException ($(TH.conE parent) $(TH.varE e))
53 | fromException f =
54 | do
55 | $(TH.conP parent [TH.varP e]) <- fromException f
56 | cast $(TH.varE e)
57 | |]
58 |
--------------------------------------------------------------------------------
/src/Process.hs:
--------------------------------------------------------------------------------
1 | {-
2 |
3 | emacs2nix - Generate Nix expressions for Emacs packages
4 | Copyright (C) 2016 Thomas Tuegel
5 |
6 | This program is free software: you can redistribute it and/or modify
7 | it under the terms of the GNU General Public License as published by
8 | the Free Software Foundation, either version 3 of the License, or
9 | (at your option) any later version.
10 |
11 | This program is distributed in the hope that it will be useful,
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | GNU General Public License for more details.
15 |
16 | You should have received a copy of the GNU General Public License
17 | along with this program. If not, see .
18 |
19 | -}
20 |
21 | {-# LANGUAGE DeriveDataTypeable #-}
22 | {-# LANGUAGE OverloadedStrings #-}
23 |
24 | module Process where
25 |
26 | import Control.Concurrent.Async (Concurrently(..))
27 | import Data.ByteString (ByteString)
28 | import Data.Monoid ((<>))
29 | import Data.Text (Text)
30 | import qualified Data.Text as T
31 | import System.Exit (ExitCode(..))
32 | import System.IO.Streams (InputStream)
33 | import qualified System.IO.Streams as S
34 | import qualified Text.PrettyPrint.ANSI.Leijen as Pretty
35 |
36 | import Exceptions
37 |
38 |
39 | slurp :: InputStream ByteString -> IO Text
40 | slurp stream = S.fold (<>) T.empty =<< S.decodeUtf8 stream
41 |
42 | runInteractiveProcess
43 | :: String -> [String] -> Maybe FilePath -> Maybe [(String, String)]
44 | -> (InputStream ByteString -> IO a)
45 | -> IO a
46 | runInteractiveProcess cmd args cwd env withOutput =
47 | inContext ("process " <> Pretty.string (S.showCommandForUser cmd args)) $ do
48 | (_, out, err, pid) <- S.runInteractiveProcess cmd args cwd env
49 | let
50 | getOutput =
51 | Concurrently
52 | (catch
53 | (fmap Right $ withOutput out)
54 | (\e -> (fmap (Left . ((,) e)) (slurp out))))
55 | ---- Maybe catch exceptions that might occur by just slurping the input stream
56 | ---- couldn't get this to type (Ambigous exception type)
57 | -- (\e -> catch
58 | -- (fmap (Left . ((,) e)) (slurp out))
59 | -- -- (Left (e, slurp out))
60 | -- (\ei -> pure $ Left (e, T.pack $ "INPUT ERROR " ++ show ei))))
61 | getErrors = Concurrently $ slurp err
62 | wait = Concurrently (S.waitForProcess pid)
63 | (output, errorMessage, exit) <- runConcurrently ((,,) <$> getOutput <*> getErrors <*> wait)
64 | case (exit, output) of
65 | (ExitSuccess, Right v) -> pure v
66 | (ExitSuccess, Left (ex, leftover)) -> throwM $ ProcessingFailed leftover errorMessage ex
67 | (ExitFailure code, _) -> throwM $ Died code errorMessage
68 |
--------------------------------------------------------------------------------