├── .github
└── workflows
│ └── ci.yml
├── .gitignore
├── COPYING.md
├── README.md
├── README.org
├── default.nix
├── doc
├── links.org
├── nix.mac.org
├── nix.md
├── nix.org
└── nix.org.el
├── nix
├── ci.nix
├── default.nix
├── direnv-nix-lorelei.nix
├── env_name_cleanup.patch
├── external
│ ├── default.nix
│ ├── sources.json
│ └── sources.nix
├── home.nix
├── remove_trace.patch
└── test
│ ├── shell.nix
│ ├── test.bats
│ └── test.nix
└── support
├── dependencies-upgrade
├── docs-generate
└── tests-run
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: "CI"
2 | on:
3 | push:
4 | pull_request:
5 | jobs:
6 | build:
7 | strategy:
8 | matrix:
9 | os: [ubuntu-latest, macos-latest]
10 | name: ${{ matrix.os }} build
11 | runs-on: ${{ matrix.os }}
12 | steps:
13 | - uses: actions/checkout@v2
14 | - uses: cachix/install-nix-action@v14
15 | - uses: cachix/cachix-action@v10
16 | with:
17 | name: shajra
18 | signingKey: '${{ secrets.CACHIX_SIGNING_KEY }}'
19 | - run: cat ~/.config/nix/nix.conf
20 | - run: nix --print-build-logs build --file nix/ci.nix
21 | - run: nix path-info --file nix/ci.nix
22 | - run: support/tests-run
23 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | result*
2 | home-fake/
3 | nix-profile*
4 |
--------------------------------------------------------------------------------
/COPYING.md:
--------------------------------------------------------------------------------
1 | ### GNU GENERAL PUBLIC LICENSE
2 |
3 | Version 3, 29 June 2007
4 |
5 | Copyright (C) 2007 Free Software Foundation, Inc.
6 |
7 |
8 | Everyone is permitted to copy and distribute verbatim copies of this
9 | license document, but changing it is not allowed.
10 |
11 | ### Preamble
12 |
13 | The GNU General Public License is a free, copyleft license for
14 | software and other kinds of works.
15 |
16 | The licenses for most software and other practical works are designed
17 | to take away your freedom to share and change the works. By contrast,
18 | the GNU General Public License is intended to guarantee your freedom
19 | to share and change all versions of a program--to make sure it remains
20 | free software for all its users. We, the Free Software Foundation, use
21 | the GNU General Public License for most of our software; it applies
22 | also to any other work released this way by its authors. You can apply
23 | it to your programs, too.
24 |
25 | When we speak of free software, we are referring to freedom, not
26 | price. Our General Public Licenses are designed to make sure that you
27 | have the freedom to distribute copies of free software (and charge for
28 | them if you wish), that you receive source code or can get it if you
29 | want it, that you can change the software or use pieces of it in new
30 | free programs, and that you know you can do these things.
31 |
32 | To protect your rights, we need to prevent others from denying you
33 | these rights or asking you to surrender the rights. Therefore, you
34 | have certain responsibilities if you distribute copies of the
35 | software, or if you modify it: responsibilities to respect the freedom
36 | of others.
37 |
38 | For example, if you distribute copies of such a program, whether
39 | gratis or for a fee, you must pass on to the recipients the same
40 | freedoms that you received. You must make sure that they, too, receive
41 | or can get the source code. And you must show them these terms so they
42 | know their rights.
43 |
44 | Developers that use the GNU GPL protect your rights with two steps:
45 | (1) assert copyright on the software, and (2) offer you this License
46 | giving you legal permission to copy, distribute and/or modify it.
47 |
48 | For the developers' and authors' protection, the GPL clearly explains
49 | that there is no warranty for this free software. For both users' and
50 | authors' sake, the GPL requires that modified versions be marked as
51 | changed, so that their problems will not be attributed erroneously to
52 | authors of previous versions.
53 |
54 | Some devices are designed to deny users access to install or run
55 | modified versions of the software inside them, although the
56 | manufacturer can do so. This is fundamentally incompatible with the
57 | aim of protecting users' freedom to change the software. The
58 | systematic pattern of such abuse occurs in the area of products for
59 | individuals to use, which is precisely where it is most unacceptable.
60 | Therefore, we have designed this version of the GPL to prohibit the
61 | practice for those products. If such problems arise substantially in
62 | other domains, we stand ready to extend this provision to those
63 | domains in future versions of the GPL, as needed to protect the
64 | freedom of users.
65 |
66 | Finally, every program is threatened constantly by software patents.
67 | States should not allow patents to restrict development and use of
68 | software on general-purpose computers, but in those that do, we wish
69 | to avoid the special danger that patents applied to a free program
70 | could make it effectively proprietary. To prevent this, the GPL
71 | assures that patents cannot be used to render the program non-free.
72 |
73 | The precise terms and conditions for copying, distribution and
74 | modification follow.
75 |
76 | ### TERMS AND CONDITIONS
77 |
78 | #### 0. Definitions.
79 |
80 | "This License" refers to version 3 of the GNU General Public License.
81 |
82 | "Copyright" also means copyright-like laws that apply to other kinds
83 | of works, such as semiconductor masks.
84 |
85 | "The Program" refers to any copyrightable work licensed under this
86 | License. Each licensee is addressed as "you". "Licensees" and
87 | "recipients" may be individuals or organizations.
88 |
89 | To "modify" a work means to copy from or adapt all or part of the work
90 | in a fashion requiring copyright permission, other than the making of
91 | an exact copy. The resulting work is called a "modified version" of
92 | the earlier work or a work "based on" the earlier work.
93 |
94 | A "covered work" means either the unmodified Program or a work based
95 | on the Program.
96 |
97 | To "propagate" a work means to do anything with it that, without
98 | permission, would make you directly or secondarily liable for
99 | infringement under applicable copyright law, except executing it on a
100 | computer or modifying a private copy. Propagation includes copying,
101 | distribution (with or without modification), making available to the
102 | public, and in some countries other activities as well.
103 |
104 | To "convey" a work means any kind of propagation that enables other
105 | parties to make or receive copies. Mere interaction with a user
106 | through a computer network, with no transfer of a copy, is not
107 | conveying.
108 |
109 | An interactive user interface displays "Appropriate Legal Notices" to
110 | the extent that it includes a convenient and prominently visible
111 | feature that (1) displays an appropriate copyright notice, and (2)
112 | tells the user that there is no warranty for the work (except to the
113 | extent that warranties are provided), that licensees may convey the
114 | work under this License, and how to view a copy of this License. If
115 | the interface presents a list of user commands or options, such as a
116 | menu, a prominent item in the list meets this criterion.
117 |
118 | #### 1. Source Code.
119 |
120 | The "source code" for a work means the preferred form of the work for
121 | making modifications to it. "Object code" means any non-source form of
122 | a work.
123 |
124 | A "Standard Interface" means an interface that either is an official
125 | standard defined by a recognized standards body, or, in the case of
126 | interfaces specified for a particular programming language, one that
127 | is widely used among developers working in that language.
128 |
129 | The "System Libraries" of an executable work include anything, other
130 | than the work as a whole, that (a) is included in the normal form of
131 | packaging a Major Component, but which is not part of that Major
132 | Component, and (b) serves only to enable use of the work with that
133 | Major Component, or to implement a Standard Interface for which an
134 | implementation is available to the public in source code form. A
135 | "Major Component", in this context, means a major essential component
136 | (kernel, window system, and so on) of the specific operating system
137 | (if any) on which the executable work runs, or a compiler used to
138 | produce the work, or an object code interpreter used to run it.
139 |
140 | The "Corresponding Source" for a work in object code form means all
141 | the source code needed to generate, install, and (for an executable
142 | work) run the object code and to modify the work, including scripts to
143 | control those activities. However, it does not include the work's
144 | System Libraries, or general-purpose tools or generally available free
145 | programs which are used unmodified in performing those activities but
146 | which are not part of the work. For example, Corresponding Source
147 | includes interface definition files associated with source files for
148 | the work, and the source code for shared libraries and dynamically
149 | linked subprograms that the work is specifically designed to require,
150 | such as by intimate data communication or control flow between those
151 | subprograms and other parts of the work.
152 |
153 | The Corresponding Source need not include anything that users can
154 | regenerate automatically from other parts of the Corresponding Source.
155 |
156 | The Corresponding Source for a work in source code form is that same
157 | work.
158 |
159 | #### 2. Basic Permissions.
160 |
161 | All rights granted under this License are granted for the term of
162 | copyright on the Program, and are irrevocable provided the stated
163 | conditions are met. This License explicitly affirms your unlimited
164 | permission to run the unmodified Program. The output from running a
165 | covered work is covered by this License only if the output, given its
166 | content, constitutes a covered work. This License acknowledges your
167 | rights of fair use or other equivalent, as provided by copyright law.
168 |
169 | You may make, run and propagate covered works that you do not convey,
170 | without conditions so long as your license otherwise remains in force.
171 | You may convey covered works to others for the sole purpose of having
172 | them make modifications exclusively for you, or provide you with
173 | facilities for running those works, provided that you comply with the
174 | terms of this License in conveying all material for which you do not
175 | control copyright. Those thus making or running the covered works for
176 | you must do so exclusively on your behalf, under your direction and
177 | control, on terms that prohibit them from making any copies of your
178 | copyrighted material outside their relationship with you.
179 |
180 | Conveying under any other circumstances is permitted solely under the
181 | conditions stated below. Sublicensing is not allowed; section 10 makes
182 | it unnecessary.
183 |
184 | #### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
185 |
186 | No covered work shall be deemed part of an effective technological
187 | measure under any applicable law fulfilling obligations under article
188 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
189 | similar laws prohibiting or restricting circumvention of such
190 | measures.
191 |
192 | When you convey a covered work, you waive any legal power to forbid
193 | circumvention of technological measures to the extent such
194 | circumvention is effected by exercising rights under this License with
195 | respect to the covered work, and you disclaim any intention to limit
196 | operation or modification of the work as a means of enforcing, against
197 | the work's users, your or third parties' legal rights to forbid
198 | circumvention of technological measures.
199 |
200 | #### 4. Conveying Verbatim Copies.
201 |
202 | You may convey verbatim copies of the Program's source code as you
203 | receive it, in any medium, provided that you conspicuously and
204 | appropriately publish on each copy an appropriate copyright notice;
205 | keep intact all notices stating that this License and any
206 | non-permissive terms added in accord with section 7 apply to the code;
207 | keep intact all notices of the absence of any warranty; and give all
208 | recipients a copy of this License along with the Program.
209 |
210 | You may charge any price or no price for each copy that you convey,
211 | and you may offer support or warranty protection for a fee.
212 |
213 | #### 5. Conveying Modified Source Versions.
214 |
215 | You may convey a work based on the Program, or the modifications to
216 | produce it from the Program, in the form of source code under the
217 | terms of section 4, provided that you also meet all of these
218 | conditions:
219 |
220 | - a) The work must carry prominent notices stating that you modified
221 | it, and giving a relevant date.
222 | - b) The work must carry prominent notices stating that it is
223 | released under this License and any conditions added under
224 | section 7. This requirement modifies the requirement in section 4
225 | to "keep intact all notices".
226 | - c) You must license the entire work, as a whole, under this
227 | License to anyone who comes into possession of a copy. This
228 | License will therefore apply, along with any applicable section 7
229 | additional terms, to the whole of the work, and all its parts,
230 | regardless of how they are packaged. This License gives no
231 | permission to license the work in any other way, but it does not
232 | invalidate such permission if you have separately received it.
233 | - d) If the work has interactive user interfaces, each must display
234 | Appropriate Legal Notices; however, if the Program has interactive
235 | interfaces that do not display Appropriate Legal Notices, your
236 | work need not make them do so.
237 |
238 | A compilation of a covered work with other separate and independent
239 | works, which are not by their nature extensions of the covered work,
240 | and which are not combined with it such as to form a larger program,
241 | in or on a volume of a storage or distribution medium, is called an
242 | "aggregate" if the compilation and its resulting copyright are not
243 | used to limit the access or legal rights of the compilation's users
244 | beyond what the individual works permit. Inclusion of a covered work
245 | in an aggregate does not cause this License to apply to the other
246 | parts of the aggregate.
247 |
248 | #### 6. Conveying Non-Source Forms.
249 |
250 | You may convey a covered work in object code form under the terms of
251 | sections 4 and 5, provided that you also convey the machine-readable
252 | Corresponding Source under the terms of this License, in one of these
253 | ways:
254 |
255 | - a) Convey the object code in, or embodied in, a physical product
256 | (including a physical distribution medium), accompanied by the
257 | Corresponding Source fixed on a durable physical medium
258 | customarily used for software interchange.
259 | - b) Convey the object code in, or embodied in, a physical product
260 | (including a physical distribution medium), accompanied by a
261 | written offer, valid for at least three years and valid for as
262 | long as you offer spare parts or customer support for that product
263 | model, to give anyone who possesses the object code either (1) a
264 | copy of the Corresponding Source for all the software in the
265 | product that is covered by this License, on a durable physical
266 | medium customarily used for software interchange, for a price no
267 | more than your reasonable cost of physically performing this
268 | conveying of source, or (2) access to copy the Corresponding
269 | Source from a network server at no charge.
270 | - c) Convey individual copies of the object code with a copy of the
271 | written offer to provide the Corresponding Source. This
272 | alternative is allowed only occasionally and noncommercially, and
273 | only if you received the object code with such an offer, in accord
274 | with subsection 6b.
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 | - e) Convey the object code using peer-to-peer transmission,
288 | provided you inform other peers where the object code and
289 | Corresponding Source of the work are being offered to the general
290 | public at no charge under subsection 6d.
291 |
292 | A separable portion of the object code, whose source code is excluded
293 | from the Corresponding Source as a System Library, need not be
294 | included in conveying the object code work.
295 |
296 | A "User Product" is either (1) a "consumer product", which means any
297 | tangible personal property which is normally used for personal,
298 | family, or household purposes, or (2) anything designed or sold for
299 | incorporation into a dwelling. In determining whether a product is a
300 | consumer product, doubtful cases shall be resolved in favor of
301 | coverage. For a particular product received by a particular user,
302 | "normally used" refers to a typical or common use of that class of
303 | product, regardless of the status of the particular user or of the way
304 | in which the particular user actually uses, or expects or is expected
305 | to use, the product. A product is a consumer product regardless of
306 | whether the product has substantial commercial, industrial or
307 | non-consumer uses, unless such uses represent the only significant
308 | 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
312 | install and execute modified versions of a covered work in that User
313 | Product from a modified version of its Corresponding Source. The
314 | information must suffice to ensure that the continued functioning of
315 | the modified object code is in no case prevented or interfered with
316 | solely because 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
331 | updates for a work that has been modified or installed by the
332 | recipient, or for the User Product in which it has been modified or
333 | installed. Access to a network may be denied when the modification
334 | itself materially and adversely affects the operation of the network
335 | or violates the rules and protocols for communication across the
336 | network.
337 |
338 | Corresponding Source conveyed, and Installation Information provided,
339 | in accord with this section must be in a format that is publicly
340 | documented (and with an implementation available to the public in
341 | source code form), and must require no special password or key for
342 | unpacking, reading or copying.
343 |
344 | #### 7. Additional Terms.
345 |
346 | "Additional permissions" are terms that supplement the terms of this
347 | License by making exceptions from one or more of its conditions.
348 | Additional permissions that are applicable to the entire Program shall
349 | be treated as though they were included in this License, to the extent
350 | that they are valid under applicable law. If additional permissions
351 | apply only to part of the Program, that part may be used separately
352 | under those permissions, but the entire Program remains governed by
353 | this License without regard to the additional permissions.
354 |
355 | When you convey a copy of a covered work, you may at your option
356 | remove any additional permissions from that copy, or from any part of
357 | it. (Additional permissions may be written to require their own
358 | removal in certain cases when you modify the work.) You may place
359 | additional permissions on material, added by you to a covered work,
360 | for which you have or can give appropriate copyright permission.
361 |
362 | Notwithstanding any other provision of this License, for material you
363 | add to a covered work, you may (if authorized by the copyright holders
364 | of that material) supplement the terms of this License with terms:
365 |
366 | - a) Disclaiming warranty or limiting liability differently from the
367 | terms of sections 15 and 16 of this License; or
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 | - c) Prohibiting misrepresentation of the origin of that material,
372 | or requiring that modified versions of such material be marked in
373 | reasonable ways as different from the original version; or
374 | - d) Limiting the use for publicity purposes of names of licensors
375 | or authors of the material; or
376 | - e) Declining to grant rights under trademark law for use of some
377 | trade names, trademarks, or service marks; or
378 | - f) Requiring indemnification of licensors and authors of that
379 | material by anyone who conveys the material (or modified versions
380 | of it) with contractual assumptions of liability to the recipient,
381 | for any liability that these contractual assumptions directly
382 | impose on those licensors and authors.
383 |
384 | All other non-permissive additional terms are considered "further
385 | restrictions" within the meaning of section 10. If the Program as you
386 | received it, or any part of it, contains a notice stating that it is
387 | governed by this License along with a term that is a further
388 | restriction, you may remove that term. If a license document contains
389 | a further restriction but permits relicensing or conveying under this
390 | License, you may add to a covered work material governed by the terms
391 | of that license document, provided that the further restriction does
392 | not survive such relicensing or conveying.
393 |
394 | If you add terms to a covered work in accord with this section, you
395 | must place, in the relevant source files, a statement of the
396 | additional terms that apply to those files, or a notice indicating
397 | where to find the applicable terms.
398 |
399 | Additional terms, permissive or non-permissive, may be stated in the
400 | form of a separately written license, or stated as exceptions; the
401 | above requirements apply either way.
402 |
403 | #### 8. Termination.
404 |
405 | You may not propagate or modify a covered work except as expressly
406 | provided under this License. Any attempt otherwise to propagate or
407 | modify it is void, and will automatically terminate your rights under
408 | this License (including any patent licenses granted under the third
409 | paragraph of section 11).
410 |
411 | However, if you cease all violation of this License, then your license
412 | from a particular copyright holder is reinstated (a) provisionally,
413 | unless and until the copyright holder explicitly and finally
414 | terminates your license, and (b) permanently, if the copyright holder
415 | fails to notify you of the violation by some reasonable means prior to
416 | 60 days after the cessation.
417 |
418 | Moreover, your license from a particular copyright holder is
419 | reinstated permanently if the copyright holder notifies you of the
420 | violation by some reasonable means, this is the first time you have
421 | received notice of violation of this License (for any work) from that
422 | copyright holder, and you cure the violation prior to 30 days after
423 | your receipt of the notice.
424 |
425 | Termination of your rights under this section does not terminate the
426 | licenses of parties who have received copies or rights from you under
427 | this License. If your rights have been terminated and not permanently
428 | reinstated, you do not qualify to receive new licenses for the same
429 | material under section 10.
430 |
431 | #### 9. Acceptance Not Required for Having Copies.
432 |
433 | You are not required to accept this License in order to receive or run
434 | a copy of the Program. Ancillary propagation of a covered work
435 | occurring solely as a consequence of using peer-to-peer transmission
436 | to receive a copy likewise does not require acceptance. However,
437 | nothing other than this License grants you permission to propagate or
438 | modify any covered work. These actions infringe copyright if you do
439 | not accept this License. Therefore, by modifying or propagating a
440 | covered work, you indicate your acceptance of this License to do so.
441 |
442 | #### 10. Automatic Licensing of Downstream Recipients.
443 |
444 | Each time you convey a covered work, the recipient automatically
445 | receives a license from the original licensors, to run, modify and
446 | propagate that work, subject to this License. You are not responsible
447 | for enforcing compliance by third parties with this License.
448 |
449 | An "entity transaction" is a transaction transferring control of an
450 | organization, or substantially all assets of one, or subdividing an
451 | organization, or merging organizations. If propagation of a covered
452 | work results from an entity transaction, each party to that
453 | transaction who receives a copy of the work also receives whatever
454 | licenses to the work the party's predecessor in interest had or could
455 | give under the previous paragraph, plus a right to possession of the
456 | Corresponding Source of the work from the predecessor in interest, if
457 | the predecessor has it or can get it with reasonable efforts.
458 |
459 | You may not impose any further restrictions on the exercise of the
460 | rights granted or affirmed under this License. For example, you may
461 | not impose a license fee, royalty, or other charge for exercise of
462 | rights granted under this License, and you may not initiate litigation
463 | (including a cross-claim or counterclaim in a lawsuit) alleging that
464 | any patent claim is infringed by making, using, selling, offering for
465 | sale, or importing the Program or any portion of it.
466 |
467 | #### 11. Patents.
468 |
469 | A "contributor" is a copyright holder who authorizes use under this
470 | License of the Program or a work on which the Program is based. The
471 | work thus licensed is called the contributor's "contributor version".
472 |
473 | A contributor's "essential patent claims" are all patent claims owned
474 | or controlled by the contributor, whether already acquired or
475 | hereafter acquired, that would be infringed by some manner, permitted
476 | by this License, of making, using, or selling its contributor version,
477 | but do not include claims that would be infringed only as a
478 | consequence of further modification of the contributor version. For
479 | purposes of this definition, "control" includes the right to grant
480 | patent sublicenses in a manner consistent with the requirements of
481 | this License.
482 |
483 | Each contributor grants you a non-exclusive, worldwide, royalty-free
484 | patent license under the contributor's essential patent claims, to
485 | make, use, sell, offer for sale, import and otherwise run, modify and
486 | propagate the contents of its contributor version.
487 |
488 | In the following three paragraphs, a "patent license" is any express
489 | agreement or commitment, however denominated, not to enforce a patent
490 | (such as an express permission to practice a patent or covenant not to
491 | sue for patent infringement). To "grant" such a patent license to a
492 | party means to make such an agreement or commitment not to enforce a
493 | patent against the party.
494 |
495 | If you convey a covered work, knowingly relying on a patent license,
496 | and the Corresponding Source of the work is not available for anyone
497 | to copy, free of charge and under the terms of this License, through a
498 | publicly available network server or other readily accessible means,
499 | then you must either (1) cause the Corresponding Source to be so
500 | available, or (2) arrange to deprive yourself of the benefit of the
501 | patent license for this particular work, or (3) arrange, in a manner
502 | consistent with the requirements of this License, to extend the patent
503 | license to downstream recipients. "Knowingly relying" means you have
504 | actual knowledge that, but for the patent license, your conveying the
505 | covered work in a country, or your recipient's use of the covered work
506 | in a country, would infringe one or more identifiable patents in that
507 | country that you have reason to believe are valid.
508 |
509 | If, pursuant to or in connection with a single transaction or
510 | arrangement, you convey, or propagate by procuring conveyance of, a
511 | covered work, and grant a patent license to some of the parties
512 | receiving the covered work authorizing them to use, propagate, modify
513 | or convey a specific copy of the covered work, then the patent license
514 | you grant is automatically extended to all recipients of the covered
515 | work and works based on it.
516 |
517 | A patent license is "discriminatory" if it does not include within the
518 | scope of its coverage, prohibits the exercise of, or is conditioned on
519 | the non-exercise of one or more of the rights that are specifically
520 | granted under this License. You may not convey a covered work if you
521 | are a party to an arrangement with a third party that is in the
522 | business of distributing software, under which you make payment to the
523 | third party based on the extent of your activity of conveying the
524 | work, and under which the third party grants, to any of the parties
525 | who would receive the covered work from you, a discriminatory patent
526 | license (a) in connection with copies of the covered work conveyed by
527 | you (or copies made from those copies), or (b) primarily for and in
528 | connection with specific products or compilations that contain the
529 | covered work, unless you entered into that arrangement, or that patent
530 | license was granted, prior to 28 March 2007.
531 |
532 | Nothing in this License shall be construed as excluding or limiting
533 | any implied license or other defenses to infringement that may
534 | otherwise be available to you under applicable patent law.
535 |
536 | #### 12. No Surrender of Others' Freedom.
537 |
538 | If conditions are imposed on you (whether by court order, agreement or
539 | otherwise) that contradict the conditions of this License, they do not
540 | excuse you from the conditions of this License. If you cannot convey a
541 | covered work so as to satisfy simultaneously your obligations under
542 | this License and any other pertinent obligations, then as a
543 | consequence you may not convey it at all. For example, if you agree to
544 | terms that obligate you to collect a royalty for further conveying
545 | from those to whom you convey the Program, the only way you could
546 | satisfy both those terms and this License would be to refrain entirely
547 | from conveying the Program.
548 |
549 | #### 13. Use with the GNU Affero General Public License.
550 |
551 | Notwithstanding any other provision of this License, you have
552 | permission to link or combine any covered work with a work licensed
553 | under version 3 of the GNU Affero General Public License into a single
554 | combined work, and to convey the resulting work. The terms of this
555 | License will continue to apply to the part which is the covered work,
556 | but the special requirements of the GNU Affero General Public License,
557 | section 13, concerning interaction through a network will apply to the
558 | combination as such.
559 |
560 | #### 14. Revised Versions of this License.
561 |
562 | The Free Software Foundation may publish revised and/or new versions
563 | of the GNU General Public License from time to time. Such new versions
564 | will be similar in spirit to the present version, but may differ in
565 | detail to address new problems or concerns.
566 |
567 | Each version is given a distinguishing version number. If the Program
568 | specifies that a certain numbered version of the GNU General Public
569 | License "or any later version" applies to it, you have the option of
570 | following the terms and conditions either of that numbered version or
571 | of any later version published by the Free Software Foundation. If the
572 | Program does not specify a version number of the GNU General Public
573 | License, you may choose any version ever published by the Free
574 | Software Foundation.
575 |
576 | If the Program specifies that a proxy can decide which future versions
577 | of the GNU General Public License can be used, that proxy's public
578 | statement of acceptance of a version permanently authorizes you to
579 | choose that version for the Program.
580 |
581 | Later license versions may give you additional or different
582 | permissions. However, no additional obligations are imposed on any
583 | author or copyright holder as a result of your choosing to follow a
584 | later version.
585 |
586 | #### 15. Disclaimer of Warranty.
587 |
588 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
589 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
590 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
591 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
592 | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
593 | A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
594 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
595 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
596 | CORRECTION.
597 |
598 | #### 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
602 | CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
603 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
604 | ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
605 | NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
606 | LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
607 | TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
608 | PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
609 |
610 | #### 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | ### How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these
626 | terms.
627 |
628 | To do so, attach the following notices to the program. It is safest to
629 | attach them to the start of each source file to most effectively state
630 | the exclusion of warranty; and each file should have at least the
631 | "copyright" line and a pointer to where the full notice is found.
632 |
633 |
634 | Copyright (C)
635 |
636 | This program is free software: you can redistribute it and/or modify
637 | it under the terms of the GNU General Public License as published by
638 | the Free Software Foundation, either version 3 of the License, or
639 | (at your option) any later version.
640 |
641 | This program is distributed in the hope that it will be useful,
642 | but WITHOUT ANY WARRANTY; without even the implied warranty of
643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
644 | GNU General Public License for more details.
645 |
646 | You should have received a copy of the GNU General Public License
647 | along with this program. If not, see .
648 |
649 | Also add information on how to contact you by electronic and paper
650 | 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
661 | appropriate parts of the General Public License. Of course, your
662 | program's commands might be different; for a GUI interface, you would
663 | use an "about box".
664 |
665 | You should also get your employer (if you work as a programmer) or
666 | school, if any, to sign a "copyright disclaimer" for the program, if
667 | necessary. For more information on this, and how to apply and follow
668 | the GNU GPL, see .
669 |
670 | The GNU General Public License does not permit incorporating your
671 | program into proprietary programs. If your program is a subroutine
672 | library, you may consider it more useful to permit linking proprietary
673 | applications with the library. If this is what you want to do, use the
674 | GNU Lesser General Public License instead of this License. But first,
675 | please read .
676 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | - [About this project](#sec-1)
2 | - [About Direnv](#sec-1-1)
3 | - [About Nix integration](#sec-1-2)
4 | - [Installation](#sec-2)
5 | - [Nix package manager setup](#sec-2-1)
6 | - [Cache setup](#sec-2-2)
7 | - [Installation via `nix-env`](#install-nixenv)
8 | - [Direnv installation](#sec-2-3-1)
9 | - [Installing Lorelei](#sec-2-3-2)
10 | - [Installation via Home Manager](#install-homemanager)
11 | - [Configuration and usage](#sec-3)
12 | - [Terminal and editor configuration](#sec-3-1)
13 | - [Per-project configuration](#sec-3-2)
14 | - [Prior art](#sec-4)
15 | - [Known limitations](#sec-5)
16 | - [Release](#sec-6)
17 | - [License](#sec-7)
18 | - [Contribution](#sec-8)
19 |
20 | [](https://github.com/shajra/direnv-nix-lorelei/actions)
21 |
22 | # About this project
23 |
24 | Lorelei provides a [Direnv](https://direnv.net) extension to configure directory-level environment variables from a [Nix](https://nixos.org/nix) expression. This support improves upon the built-in Nix support of Direnv with the following features:
25 |
26 | - The calculation of your project's environment variables can be cached to avoid loading time.
27 |
28 | - The cache of environment variables can be configured to be invalidated when
29 | - the content of a file changes
30 | - a file's modification time changes (even if content does not)
31 | - a per-project `.direnv/delete_to_rebuild` file is deleted.
32 |
33 | - Additionally files to watch for cache invalidation can be automatically detected, though this detection is not comprehensive.
34 |
35 | - Programs referenced by active environment variables are prevented from being garbage collected by Nix.
36 |
37 | - You can also save a configurable number of previous environments from being garbage collected.
38 |
39 | Note, Lorelei only works with projects that have a Nix file that can be called with `nix-shell` (typically called "shell.nix"). For projects that provide a Nix environment with the not-yet-released Nix flakes feature, please consider using the `use_flake` function of the [nix-direnv](https://github.com/nix-community/nix-direnv) project, which you can use concurrently with Lorelei with no conflicts.
40 |
41 | ## About Direnv
42 |
43 | When we go into a project's directory we often want certain environment variables set specifically to a project's needs. A very common environment variable to specify per-project is `PATH` to make available development tools needed by a project. Different projects may depend on conflicting tools, such as different versions of a compiler.
44 |
45 | Direnv targets solving this problem. Once you set it up, you can hook your terminal shell to automatically load variables based upon your current working directory. Then, when you `cd` into the directory, the variables change automatically.
46 |
47 | Additionally, many popularly used programming editors have Direnv extensions/plugins. Rather than use editor-specific configuration to treat each project differently, we can configure these projects with Direnv. Any editor configured with a Direnv extension/plugin will then pick up the right environment based on the project of the edited file.
48 |
49 | Once we set up our editors and shells with Direnv, we can configure our project-specific environment in one place with Direnv. Also, since Nix is far less popularly used than Direnv, we don't have to worry about unsupported Nix integration with our editors or shells. Lorelei can provide all the Nix support we need for Direnv.
50 |
51 | ## About Nix integration
52 |
53 | Nix is a package manager (in the same sense as APT, RPM, Homebrew, or Chocolatey). As a package manager, Nix helps us get tools and libraries installed on our system. Nix goes a bit farther, by providing us some facilities to help us get these tools set up in a local environment called a *Nix shell*.
54 |
55 | We typically go into a directory with with a specially configured `shell.nix` file, and execute `nix-shell` to enter into an interactive Bash session with environment variables set up for working in our project.
56 |
57 | Direnv can help us get rid of the extra step of having to call `nix-shell`.
58 |
59 | Direnv actually comes with Nix support built-in, but this support is very basic. Specifically, it has no caching of calculated environments, or protection required dependencies from being garbage collected by Nix.
60 |
61 | See [the provided documentation on Nix](doc/nix.md) for more on what Nix is, why we're motivated to use it, and how to get set up with it for this project. Not covered in this documentation are details on how to set make a Nix expression to set up a Nix shell. There's just a lot of ways to do this for each programming langauge, and the [official Nixpkgs manual](https://nixos.org/nixpkgs/manual) is the best resource.
62 |
63 | # Installation
64 |
65 | Lorelei should work with either GNU/Linux or MacOS operating systems. Before we can configure specific projects/directories to use Direnv and Lorelei, we need to do the following:
66 |
67 | 1. install and configure Nix, if we haven't already
68 | 2. install Direnv
69 | 3. install Lorelei
70 | 4. create a symlink under `$XDG_CONFIG_HOME/direnv/lib` pointing to Lorelei's installed Bash functions.
71 |
72 | Beyond the installation of Nix, we have two ways to install packages and create the symlink:
73 |
74 | - use `nix-env` and create the symlink ourselves
75 | - use [Home Manager](https://github.com/nix-community/home-manager) to manage both packages and home directory configuration (including the symlink under under `$XDG_CONFIG_HOME/direnv/lib`).
76 |
77 | The following sections cover both these options. Home Manager introduces its own complexity and added work for configuration. But there can be a nice payoff if you opt to use Home Manager to manage more than just Lorelei.
78 |
79 | ## Nix package manager setup
80 |
81 | > **NOTE:** You don't need this step if you're running NixOS, which comes with Nix baked in.
82 |
83 | If you don't already have Nix, [the official installation script](https://nixos.org/learn.html) should work on a variety of UNIX-like operating systems:
84 |
85 | ```bash
86 | sh <(curl -L https://nixos.org/nix/install) --daemon
87 | ```
88 |
89 | If you're on a recent release of MacOS, you will need an extra switch:
90 |
91 | ```bash
92 | sh <(curl -L https://nixos.org/nix/install) --daemon \
93 | --darwin-use-unencrypted-nix-store-volume
94 | ```
95 |
96 | After installation, you may have to exit your terminal session and log back in to have environment variables configured to put Nix executables on your `PATH`.
97 |
98 | The `--daemon` switch installs Nix in the recommended multi-user mode. This requires the script to run commands with `sudo`. The script fairly verbosely reports everything it does and touches. If you later want to uninstall Nix, you can run the installation script again, and it will tell you what to do to get back to a clean state.
99 |
100 | The Nix manual describes [other methods of installing Nix](https://nixos.org/nix/manual/#chap-installation) that may suit you more.
101 |
102 | ## Cache setup
103 |
104 | It's recommended to configure Nix to use shajra.cachix.org as a Nix *substitutor*. This project pushes built Nix packages to [Cachix](https://cachix.org) as part of its continuous integration. Once configured, Nix will pull down these pre-built packages instead of building them locally (potentially saving a lot of time). This augments the default substitutor that pulls from cache.nixos.org.
105 |
106 | You can configure shajra.cachix.org as a substitutor with the following command:
107 |
108 | ```sh
109 | nix run \
110 | --file https://cachix.org/api/v1/install \
111 | cachix \
112 | --command cachix use shajra
113 | ```
114 |
115 | Cachix is a service that anyone can use. You can call this command later to add substitutors for someone else using Cachix, replacing "shajra" with their cache's name.
116 |
117 | If you've just run a multi-user Nix installation and are not yet a trusted user in `/etc/nix/nix.conf`, this command may not work. But it will report back some options to proceed.
118 |
119 | One option sets you up as a trusted user, and installs Cachix configuration for Nix locally at `~/.config/nix/nix.conf`. This configuration will be available immediately, and any subsequent invocation of Nix commands will take advantage of the Cachix cache.
120 |
121 | You can alternatively configure Cachix as a substitutor globally by running the above command as a root user (say with `sudo`), which sets up Cachix directly in `/etc/nix/nix.conf`. The invocation may give further instructions upon completion.
122 |
123 | ## Installation via `nix-env`
124 |
125 | This section covers the option of installing packages with `nix-env`, and not with Home Manager. If you're not as familiar with `nix-env`, you may be interested in this project's [supplemental documentation on Nix](doc/nix.md).
126 |
127 | If you've installed Home Manager, you may skip this section and try out [the next section on installation with Home manager](#install-homemanager).
128 |
129 | ### Direnv installation
130 |
131 | If you don't already have Direnv installed, you have the option of installing Direnv from this project (otherwise, you can skip this step):
132 |
133 | ```sh
134 | nix-env --install --file . --attr direnv 2>&1
135 | ```
136 |
137 | installing 'direnv-2.28.0'
138 |
139 | If you have `~/.nix-profile/bin` in your environment's `PATH`, you should be able to call the `direnv` executable. Here's a simple way of testing its availability.
140 |
141 | ```sh
142 | direnv version
143 | ```
144 |
145 | 2.28.0
146 |
147 | ### Installing Lorelei
148 |
149 | This project provides a Nix expression in the project's root `default.nix` file. From the root directory of a checkout of the project, you can install Lorelei as follows:
150 |
151 | ```sh
152 | nix-env --install --file . --attr direnv-nix-lorelei 2>&1
153 | ```
154 |
155 | installing 'direnv-nix-lorelei'
156 |
157 | This installation doesn't install a binary, but instead a shell library that you use as configuration for Direnv. Given a typical installation of Nix, this installation should be into the active Nix profile at `~/.nix-profile`. We can tie this library to Direnv with a symlink:
158 |
159 | ```sh
160 | mkdir --parents ~/.config/direnv/lib
161 | ln --force --symbolic --no-target-directory \
162 | ~/.nix-profile/share/direnv-nix-lorelei/nix-lorelei.bash \
163 | ~/.config/direnv/lib/nix-lorelei.sh
164 | ```
165 |
166 | ## Installation via Home Manager
167 |
168 | This section is for those those who are interested in Home Manager, and skipped [the prior section](#install-nixenv) on how to install the needed packages with `nix-env` and create the needed symlink directly with `ln`.
169 |
170 | Detailed instructions on the installation of Home Manager are beyond the scope of this document. Please refer to [Home Manager's manual](https://rycee.gitlab.io/home-manager/).
171 |
172 | Home Manager is configured with NixOS-style modules. These modules are Nix functions of a certain form. Modules can import other modules by their path. Some modules provide an configuration options, which are then imported by other modules on the user's side where these options are then employed to configure a particular machine.
173 |
174 | In our case, this project provides a module at the *attribute path* `direnv-nix-lorelei-home`. To configure a machine with Lorelei using Home Manager, we'll import this module, and then enable the provided options. Here's an commented example of such a configuration:
175 |
176 | ```nix
177 | { config, pkgs, lib, ... }:
178 |
179 | let
180 |
181 | # First we have to get the Lorelei source code from GitHub.
182 |
183 | # Unfortunately, can't use pkgs from above (infinite recursion)
184 | pkgs-bootstrap = import { config = {}; overlays = []; };
185 |
186 | lorelei-source = pkgs-bootstrap.fetchFromGitHub {
187 | owner = "shajra";
188 | repo = "direnv-nix-lorelei";
189 |
190 | # This is example Git commit ID to pin to. Choose another to upgrade to
191 | # a later version of Lorelei.
192 | rev = "8310119578f9bcedb1e4ca2580d3b11bd7d214f2";
193 |
194 | # Use pkgs.lib.fakeSha256 the first time using a new rev with Home
195 | # Manager, which will then report back the real value to use. A real
196 | # value will look something like this: sha256 =
197 | # "198h7ryqdv0h9lv3sixqxzdl8wf57lsvzzm8viipmk4pb0lsyckh";
198 | sha256 = lib.fakeSha256;
199 | };
200 |
201 | # Then we access the module it provides.
202 | module-lorelei = (import lorelei-source).direnv-nix-lorelei-home;
203 |
204 | in
205 |
206 | # Here's where we configure options provided by imported modules. As is typical,
207 | # the final modules used to configure a machine don't create more options.
208 | {
209 | # Here our configuration module imports the module Lorelei provides.
210 | imports = [ module-lorelei ];
211 |
212 | # Home manager already has a module that allows us to include Direnv on our
213 | # user's PATH.
214 | programs.direnv.enable = true;
215 |
216 | # Here we enable the option to have Home Manager set up the symlink under
217 | # $XDG_CONFIG_HOME/direnv/lib to enable Lorelei's usage with Direnv.
218 | programs.direnv-nix-lorelei.enable = true;
219 | }
220 | ```
221 |
222 | Not completely illustrated in the above example, the Lorelei Home Manager module provides two options:
223 |
224 | - `programs.direnv-nix-lorelei.enable`: to install Lorelei and configure Direnv to use it.
225 | - `programs.direnv-nix-lorelei.package`: in case you want to specify another version of Lorelei to use on the machine.
226 |
227 | If you're curious, you can read [the source code of the module](nix/home.nix) to see the specifications for these options.
228 |
229 | The example above has you going through a step to use `lib.fakeSha256` to get the real hash for Lorelei. These hashes are an important part of Nix's model of trusted code, but managing them when updating dependencies can be a chore. Eventually [Nix Flakes](https://nixos.wiki/wiki/Flakes) will release, which will help with that. In the meantime, you may be interested in the [Niv](https://github.com/nmattia/niv) project to manage these hashes when updating dependencies.
230 |
231 | If further interested, you may like looking at [a larger example](https://github.com/shajra/shajra-provisioning/blob/master/home/modules/base/default.nix) of Home Manager configuration of much more than just Lorelei.
232 |
233 | # Configuration and usage
234 |
235 | ## Terminal and editor configuration
236 |
237 | If you're absolutely new to Direnv, we won't get any benefit from the configuration described in this document until we integrate Direnv with either our terminal's shell, our editor of choice, or both.
238 |
239 | We delegate to the [official Direnv documentation](https://direnv.net/#docs) on how to do this configuration. Specifically, have a look at
240 |
241 | - [hooking Direnv into your preferred shell](https://direnv.net/docs/hook.html)
242 | - the [Direnv wiki for pages about editor integration](https://github.com/direnv/direnv/wiki#editor-integration).
243 |
244 | ## Per-project configuration
245 |
246 | If you have a project that can be used to enter a Nix shell with a call like
247 |
248 | ```sh
249 | nix-shell "$NIX_FILE"
250 | ```
251 |
252 | for some file `$NIX_FILE`, then at the root of the project you can create a `.envrc` to get started with Direnv:
253 |
254 | ```sh
255 | echo "use_nix_gcrooted -a \"$NIX_FILE\"" > .envrc
256 | ```
257 |
258 | As with `nix-shell` specifying a Nix file as a positional argument is optional if you're file is called `shell.nix`. Furthermore, if you don't use `shell.nix`, but use `default.nix` it is also optional.
259 |
260 | Finally, we can activate the configuration (Direnv has some security measures to prevent abuse from running arbitrary scripts):
261 |
262 | ```sh
263 | direnv allow
264 | ```
265 |
266 | At this point, if you have your terminal and editor configured to use Direnv, you should experience per-project environments serviced by Direnv.
267 |
268 | To learn more more about Lorelei's options, we can source the script and run the function outside Direnv. However, we need to be in a Bash shell:
269 |
270 | ```sh
271 | bash -c "
272 | . ~/.nix-profile/share/direnv-nix-lorelei/nix-lorelei.bash
273 | use_nix_gcrooted --help
274 | "
275 | ```
276 |
277 | USAGE: use_nix_gcrooted [OPTION]... [FILE]
278 |
279 | DESCRIPTION:
280 |
281 | A replacement for Direnv's use_nix. This function, will make
282 | sure calculated Nix expressions are GC rooted with Nix. By
283 | default the calculated environment is also cached, which is
284 | useful for Nix expressions that have costly evaluations. To
285 | invalidate the cache, files can be watched either by their
286 | content hash or their modification time. You can also delete
287 | .direnv/delete_to_rebuild to invalidate the cache.
288 |
289 | OPTIONS:
290 |
291 | -h --help print this help message
292 | -a --auto-watch-content watch autodetected files for contect
293 | changes
294 | -A --auto-watch-mtime watch autodetected files for
295 | modification times
296 | -d --auto-watch-deep deeper searching for -a and -A options
297 | -w --watch-content PATH watch a file's content for changes
298 | -W --watch-mtime PATH watch a file's modification time
299 | -C --ignore-cache recompute new environment every time
300 | -k --keep-last NUM protect last N caches from GC
301 | (default 5)
302 |
303 | Direnv needs to know when to consider recalculating an environment's variables. To do this, we need to register files to watch for changes. This is what the "watch" switches above help specify.
304 |
305 | With the `--auto-watch-content` and `--auto-watch-mtime` switches, you don't have to worry about which files to watch for changes. You can either watch these files when their modifications time change, or when their content actually changes (touching a file changes its modification time, but not its content).
306 |
307 | The `--auto-watch-content` and `--auto-watch-mtime` switches catch a good amount of Nix files, but won't catch everything you might have the idea to watch. If you want to specify files to watch explicitly, you can use the `--watch-content` and `--watch-mtime` switches.
308 |
309 | You can use the `--auto-watch-deep` switch to have the auto-watching features look a little deeper for files to watch. However, the evaluation time you'll face for an not-yet-cached environment will be notably longer for this deeper search (possibly twice as long). Note auto-watching without the `--auto-watch-deep` switch shouldn't add much evaluation overhead, so you should be able to use the normal shallower auto-detection without worrying about a slowdown.
310 |
311 | If for some (unlikely) reason, you want the benefits of protection from Nix garbage collection, but not cache the evaluation of environments, you can use `--ignore-cache`. Note, that you still need to specify files to watch for changes. With `--ignore-cache`, you'll recalculate the Nix expression for your project every time these watched files trigger Direnv to recalculate an environment.
312 |
313 | Lorelei keeps the last five environments from being garbage collected. You can change this with `--keep-last`.
314 |
315 | And finally, if you ever feel like you want to dump your cached environment and recalculate everything, just delete `.direnv/delete_to_rebuild`, which will be next to your project's `.envrc` file.
316 |
317 | Lorelei's metadata for your project is in two places:
318 |
319 | - your project's `.direnv` directory
320 | - your user's GC root directory: `/nix/var/nix/gcroots/per-user/$USER`
321 |
322 | You can delete this data to start fresh.
323 |
324 | The symlinks in the GC root directory have human readable names to assist manual curation if you need it.
325 |
326 | # Prior art
327 |
328 | There are four projects that were considered before writing Lorelei:
329 |
330 | - [Lorri](https://github.com/target/lorri)
331 | - [Sorri](https://github.com/nmattia/sorri)
332 | - [Nix-direnv](https://github.com/nix-community/nix-direnv)
333 | - [Nixify](https://github.com/kalbasit/nur-packages/blob/master/pkgs/nixify/envrc)
334 |
335 | Lorelei should subsume the features of all of these projects with the exception of Lorri's approach to calculating Direnv environments as a background process. You can think of the name "Lorelei" as a pun of "Lorri-lite," but "Lorelei" is also the name of a [Pogue's song](https://www.youtube.com/watch?v=VDw81PRP2SQ) you may enjoy.
336 |
337 | All of these different projects can save on the evaluation time of calculating a Nix expression by caching the Direnv environment. And all of these projects have some facility to protect dependencies referenced by Direnv environments from Nix's garbage collection.
338 |
339 | Lorri is the heaviest of these options. To use it, you start a daemon process that in the background watches files for changes and evaluates/builds environments. This way, the environment is ready before you actually enter the project.
340 |
341 | Also Lorri inspects Nix's build log to automatically detect which files need to be watched for changes. Unfortunately, this often misses useful files to watch in a project.
342 |
343 | Running a background process can be a heavy extra process, and introduces the surface area of complexity and exposure to defects (though the Lorri committers have been committed to fixing them). All of the other projects are lighter-weight than Lorri in this regard. They are just scripts with no requirements on a background process.
344 |
345 | Sorri copies a lot of code from Lorri, but removes the background process. So when you enter a Direnv directory, you will always experience the evaluation time of calculating a not-yet-cached Direnv environment. With Lorri this evaluation occurs in the background.
346 |
347 | Lorelei is different from Sorri in two main ways:
348 |
349 | - Lorelei gives much more control of cache invalidation beyond the auto-detection of files to watch for changes. These approaches are inspired by Nix-direnv and Nixify.
350 |
351 | - Rather than copying code from Lorri, we actually call Lorri code directly as a library.
352 |
353 | Lorri has been relatively active about refining the approach to calculating a Direnv environment, more so than any of the other projects. Sorri copies code, but leads to more work porting changes from Lorri to Sorri. Lorelei uses Nix to use Lorri's code directly. This eases maintenance, but does mean that you *have* to install Lorelei with Nix. However, this is not a bad idea, because Lorelei rigorously pins all of its dependencies, all the way down to `coreutils`. So by installing Lorelei with Nix, we get more precision.
354 |
355 | # Known limitations
356 |
357 | There's two known limitations of Lorelei:
358 |
359 | - Your project must have a Nix file that can be run with `nix-shell`.
360 | - Nix flakes aren't supported (yet).
361 |
362 | Lorelei delegates strongly to Lorri, so the limitation of requiring an explicit Nix file to import stems from that. This is not to say that this limitation can't be improved upon in the future.
363 |
364 | However, we probably don't want to support something like `nix-shell`'s `--packages` switch. This feature of `nix-shell` is generally discouraged by the Nix community because its implementation has a lot of non-intuitive warts. Nix will soon release a `nix shell` command that has the potential to more properly replace the functionality that `nix-shell`'s `--packages` switch provides. When this occurs, both the Lorri and Lorelei can reevaluate their respective implementation strategies.
365 |
366 | Also, soon to be released in a new version of Nix are [Nix flakes](https://nixos.wiki/wiki/Flakes). If you don't know what flakes are, you may want to wait until they stabilize and are officially released. If you're an early adopter of flakes, the [Nix-direnv](https://github.com/nix-community/nix-direnv) project has support for Nix flakes with it's `use_flake` function. Lorelei can be installed and used concurrently with other projects offering similar functionality (Lorri, Nix-direnv, and the rest). You just make different calls in your project's `.envrc` files. No core contributor of Lorelei is using this unreleased version of Nix supporting flakes, so we didn't want to provide something we had not tested ourselves.
367 |
368 | # Release
369 |
370 | The "main" branch of the repository on GitHub has the latest released version of this code. There is currently no commitment to either forward or backward compatibility.
371 |
372 | "user/shajra" branches are personal branches that may be force-pushed to. The "main" branch should not experience force-pushes and is recommended for general use.
373 |
374 | # License
375 |
376 | All files in this "direnv-nix-lorelei" project are licensed under the terms of GPLv3 or (at your option) any later version.
377 |
378 | Please see the [./COPYING.md](./COPYING.md) file for more details.
379 |
380 | # Contribution
381 |
382 | Feel free to file issues and submit pull requests with GitHub.
383 |
384 | There is only one author to date, so the following copyright covers all files in this project:
385 |
386 | Copyright © 2020 Sukant Hajra
387 |
--------------------------------------------------------------------------------
/README.org:
--------------------------------------------------------------------------------
1 | #+title: Lorelei, an Alternative Nix extension of Direnv
2 | #+setupfile: doc/links.org
3 |
4 | [[https://github.com/shajra/direnv-nix-lorelei/actions][https://github.com/shajra/direnv-nix-lorelei/workflows/CI/badge.svg]]
5 |
6 | * Org-mode setup :noexport:
7 |
8 | ** Formatting help
9 |
10 | This snippet can be used as a post-processing step to crop down the results from
11 | an evaluation of a source code block.
12 |
13 | #+name: drop
14 | #+begin_src emacs-lisp :var text="" :var n-dropped=0 :results silent
15 | (string-join (-drop n-dropped (split-string text "\n")) "\n")
16 | #+end_src
17 |
18 | ** Setup action
19 |
20 | The following helps (using Noweb) set up Nix environment variables for source
21 | block evaluation.
22 |
23 | #+name: nix-init
24 | #+begin_src sh :eval no
25 | export NIX_PROFILE=$(pwd)/nix-profile
26 | export NIX_PAGER=cat
27 | export PATH="$NIX_PROFILE/bin:$PATH"
28 | #+end_src
29 |
30 | Next we perform some side-effects to set up the evaluation of the whole
31 | document.
32 |
33 | #+name: cleanup
34 | #+begin_src sh :results output silent :noweb yes
35 | <>
36 | rm --force result*
37 | rm --force "$NIX_PROFILE"*
38 | #+end_src
39 |
40 | This is just a hack to deal with the fact that we never know what directory a
41 | session will start in, so we need a way to calculate the PWD to jump to it.
42 |
43 | #+name: pwd
44 | #+begin_src sh :results output silent
45 | echo cd "$(pwd)"
46 | #+end_src
47 |
48 | This begins a session with environment variables initialized.
49 |
50 | #+name: session-init
51 | #+begin_src sh :session env :results output silent :noweb yes
52 | <>
53 | <>
54 | #+end_src
55 |
56 | * About this project
57 |
58 | Lorelei provides a [[direnv][Direnv]] extension to configure directory-level environment
59 | variables from a [[nix][Nix]] expression. This support improves upon the built-in Nix
60 | support of Direnv with the following features:
61 |
62 | - The calculation of your project's environment variables can be cached to avoid
63 | loading time.
64 |
65 | - The cache of environment variables can be configured to be invalidated when
66 | - the content of a file changes
67 | - a file's modification time changes (even if content does not)
68 | - a per-project =.direnv/delete_to_rebuild= file is deleted.
69 |
70 | - Additionally files to watch for cache invalidation can be automatically
71 | detected, though this detection is not comprehensive.
72 |
73 | - Programs referenced by active environment variables are prevented from being
74 | garbage collected by Nix.
75 |
76 | - You can also save a configurable number of previous environments from being
77 | garbage collected.
78 |
79 | Note, Lorelei only works with projects that have a Nix file that can be called
80 | with =nix-shell= (typically called "shell.nix"). For projects that provide a Nix
81 | environment with the not-yet-released Nix flakes feature, please consider using
82 | the =use_flake= function of the [[nixdirenv][nix-direnv]] project, which you can use
83 | concurrently with Lorelei with no conflicts.
84 |
85 | ** About Direnv
86 |
87 | When we go into a project's directory we often want certain environment
88 | variables set specifically to a project's needs. A very common environment
89 | variable to specify per-project is =PATH= to make available development tools
90 | needed by a project. Different projects may depend on conflicting tools, such as
91 | different versions of a compiler.
92 |
93 | Direnv targets solving this problem. Once you set it up, you can hook your
94 | terminal shell to automatically load variables based upon your current working
95 | directory. Then, when you ~cd~ into the directory, the variables change
96 | automatically.
97 |
98 | Additionally, many popularly used programming editors have Direnv
99 | extensions/plugins. Rather than use editor-specific configuration to treat each
100 | project differently, we can configure these projects with Direnv. Any editor
101 | configured with a Direnv extension/plugin will then pick up the right
102 | environment based on the project of the edited file.
103 |
104 | Once we set up our editors and shells with Direnv, we can configure our
105 | project-specific environment in one place with Direnv. Also, since Nix is far
106 | less popularly used than Direnv, we don't have to worry about unsupported Nix
107 | integration with our editors or shells. Lorelei can provide all the Nix support
108 | we need for Direnv.
109 |
110 | ** About Nix integration
111 |
112 | Nix is a package manager (in the same sense as APT, RPM, Homebrew, or
113 | Chocolatey). As a package manager, Nix helps us get tools and libraries
114 | installed on our system. Nix goes a bit farther, by providing us some facilities
115 | to help us get these tools set up in a local environment called a /Nix shell/.
116 |
117 | We typically go into a directory with with a specially configured =shell.nix=
118 | file, and execute ~nix-shell~ to enter into an interactive Bash session with
119 | environment variables set up for working in our project.
120 |
121 | Direnv can help us get rid of the extra step of having to call =nix-shell=.
122 |
123 | Direnv actually comes with Nix support built-in, but this support is very basic.
124 | Specifically, it has no caching of calculated environments, or protection
125 | required dependencies from being garbage collected by Nix.
126 |
127 | See [[file:doc/nix.org][the provided documentation on Nix]] for more on what Nix is, why we're
128 | motivated to use it, and how to get set up with it for this project. Not covered
129 | in this documentation are details on how to set make a Nix expression to set up
130 | a Nix shell. There's just a lot of ways to do this for each programming
131 | langauge, and the [[nixpkgs-manual][official Nixpkgs manual]] is the best resource.
132 |
133 | * Installation
134 |
135 | Lorelei should work with either GNU/Linux or MacOS operating systems. Before we
136 | can configure specific projects/directories to use Direnv and Lorelei, we need
137 | to do the following:
138 |
139 | 1. install and configure Nix, if we haven't already
140 | 2. install Direnv
141 | 3. install Lorelei
142 | 4. create a symlink under =$XDG_CONFIG_HOME/direnv/lib= pointing to Lorelei's
143 | installed Bash functions.
144 |
145 | Beyond the installation of Nix, we have two ways to install packages and create
146 | the symlink:
147 |
148 | - use =nix-env= and create the symlink ourselves
149 | - use [[homemanager][Home Manager]] to manage both packages and home directory configuration
150 | (including the symlink under under =$XDG_CONFIG_HOME/direnv/lib=).
151 |
152 | The following sections cover both these options. Home Manager introduces its own
153 | complexity and added work for configuration. But there can be a nice payoff if
154 | you opt to use Home Manager to manage more than just Lorelei.
155 |
156 | #+include: "doc/nix.org::*Nix package manager setup"
157 |
158 | #+include: "doc/nix.org::*Cache setup"
159 |
160 | ** Installation via =nix-env=
161 | :PROPERTIES:
162 | :CUSTOM_ID: install-nixenv
163 | :END:
164 |
165 | This section covers the option of installing packages with =nix-env=, and not
166 | with Home Manager. If you're not as familiar with =nix-env=, you may be
167 | interested in this project's [[file:doc/nix.org][supplemental documentation on Nix]].
168 |
169 | If you've installed Home Manager, you may skip this section and try out [[#install-homemanager][the next
170 | section on installation with Home manager]].
171 |
172 | *** Direnv installation
173 |
174 | If you don't already have Direnv installed, you have the option of installing
175 | Direnv from this project (otherwise, you can skip this step):
176 |
177 | #+name: direnv-install
178 | #+begin_src sh :session env :results output :exports both
179 | nix-env --install --file . --attr direnv 2>&1
180 | #+end_src
181 |
182 | #+results: direnv-install
183 | : installing 'direnv-2.28.0'
184 |
185 | If you have =~/.nix-profile/bin= in your environment's =PATH=, you should be
186 | able to call the =direnv= executable. Here's a simple way of testing its
187 | availability.
188 |
189 | #+name: direnv-version
190 | #+begin_src sh :session env :results output :exports both
191 | direnv version
192 | #+end_src
193 |
194 | #+results: direnv-version
195 | : 2.28.0
196 |
197 | *** Installing Lorelei
198 |
199 | This project provides a Nix expression in the project's root =default.nix= file.
200 | From the root directory of a checkout of the project, you can install Lorelei as
201 | follows:
202 |
203 | #+name: lorelei-install
204 | #+begin_src sh :session env :results output :exports both
205 | nix-env --install --file . --attr direnv-nix-lorelei 2>&1
206 | #+end_src
207 |
208 | #+results: lorelei-install
209 | : installing 'direnv-nix-lorelei'
210 |
211 | This installation doesn't install a binary, but instead a shell library that you
212 | use as configuration for Direnv. Given a typical installation of Nix, this
213 | installation should be into the active Nix profile at =~/.nix-profile=. We can
214 | tie this library to Direnv with a symlink:
215 |
216 | #+begin_src sh :eval no
217 | mkdir --parents ~/.config/direnv/lib
218 | ln --force --symbolic --no-target-directory \
219 | ~/.nix-profile/share/direnv-nix-lorelei/nix-lorelei.bash \
220 | ~/.config/direnv/lib/nix-lorelei.sh
221 | #+end_src
222 |
223 | ** Installation via Home Manager
224 | :PROPERTIES:
225 | :CUSTOM_ID: install-homemanager
226 | :END:
227 |
228 | This section is for those those who are interested in Home Manager, and skipped
229 | [[#install-nixenv][the prior section]] on how to install the needed packages with =nix-env= and
230 | create the needed symlink directly with =ln=.
231 |
232 | Detailed instructions on the installation of Home Manager are beyond the scope
233 | of this document. Please refer to [[homemanager-manual][Home Manager's manual]].
234 |
235 | Home Manager is configured with NixOS-style modules. These modules are Nix
236 | functions of a certain form. Modules can import other modules by their path.
237 | Some modules provide an configuration options, which are then imported by other
238 | modules on the user's side where these options are then employed to configure a
239 | particular machine.
240 |
241 | In our case, this project provides a module at the /attribute path/
242 | =direnv-nix-lorelei-home=. To configure a machine with Lorelei using Home
243 | Manager, we'll import this module, and then enable the provided options. Here's
244 | an commented example of such a configuration:
245 |
246 | #+begin_src nix :eval no
247 | { config, pkgs, lib, ... }:
248 |
249 | let
250 |
251 | # First we have to get the Lorelei source code from GitHub.
252 |
253 | # Unfortunately, can't use pkgs from above (infinite recursion)
254 | pkgs-bootstrap = import { config = {}; overlays = []; };
255 |
256 | lorelei-source = pkgs-bootstrap.fetchFromGitHub {
257 | owner = "shajra";
258 | repo = "direnv-nix-lorelei";
259 |
260 | # This is example Git commit ID to pin to. Choose another to upgrade to
261 | # a later version of Lorelei.
262 | rev = "8310119578f9bcedb1e4ca2580d3b11bd7d214f2";
263 |
264 | # Use pkgs.lib.fakeSha256 the first time using a new rev with Home
265 | # Manager, which will then report back the real value to use. A real
266 | # value will look something like this: sha256 =
267 | # "198h7ryqdv0h9lv3sixqxzdl8wf57lsvzzm8viipmk4pb0lsyckh";
268 | sha256 = lib.fakeSha256;
269 | };
270 |
271 | # Then we access the module it provides.
272 | module-lorelei = (import lorelei-source).direnv-nix-lorelei-home;
273 |
274 | in
275 |
276 | # Here's where we configure options provided by imported modules. As is typical,
277 | # the final modules used to configure a machine don't create more options.
278 | {
279 | # Here our configuration module imports the module Lorelei provides.
280 | imports = [ module-lorelei ];
281 |
282 | # Home manager already has a module that allows us to include Direnv on our
283 | # user's PATH.
284 | programs.direnv.enable = true;
285 |
286 | # Here we enable the option to have Home Manager set up the symlink under
287 | # $XDG_CONFIG_HOME/direnv/lib to enable Lorelei's usage with Direnv.
288 | programs.direnv-nix-lorelei.enable = true;
289 | }
290 | #+end_src
291 |
292 | Not completely illustrated in the above example, the Lorelei Home Manager module
293 | provides two options:
294 | - =programs.direnv-nix-lorelei.enable=: to install Lorelei and configure Direnv
295 | to use it.
296 | - =programs.direnv-nix-lorelei.package=: in case you want to specify another
297 | version of Lorelei to use on the machine.
298 |
299 | If you're curious, you can read [[file:nix/home.nix][the source code of the module]] to see the
300 | specifications for these options.
301 |
302 | The example above has you going through a step to use =lib.fakeSha256= to get
303 | the real hash for Lorelei. These hashes are an important part of Nix's model of
304 | trusted code, but managing them when updating dependencies can be a chore.
305 | Eventually [[nix-flakes][Nix Flakes]] will release, which will help with that. In the meantime,
306 | you may be interested in the [[niv][Niv]] project to manage these hashes when updating
307 | dependencies.
308 |
309 | If further interested, you may like looking at [[shajra-provisioning-base][a larger example]] of Home Manager
310 | configuration of much more than just Lorelei.
311 |
312 | * Configuration and usage
313 |
314 | ** Terminal and editor configuration
315 |
316 | If you're absolutely new to Direnv, we won't get any benefit from the
317 | configuration described in this document until we integrate Direnv with either
318 | our terminal's shell, our editor of choice, or both.
319 |
320 | We delegate to the [[direnv-docs][official Direnv documentation]] on how to do this
321 | configuration. Specifically, have a look at
322 | - [[direnv-shell][hooking Direnv into your preferred shell]]
323 | - the [[direnv-editor][Direnv wiki for pages about editor integration]].
324 |
325 | ** Per-project configuration
326 |
327 | If you have a project that can be used to enter a Nix shell with a call like
328 |
329 | #+begin_src sh :eval no
330 | nix-shell "$NIX_FILE"
331 | #+end_src
332 |
333 | for some file =$NIX_FILE=, then at the root of the project you can create a
334 | =.envrc= to get started with Direnv:
335 |
336 | #+begin_src sh :eval no
337 | echo "use_nix_gcrooted -a \"$NIX_FILE\"" > .envrc
338 | #+end_src
339 |
340 | As with =nix-shell= specifying a Nix file as a positional argument is optional
341 | if you're file is called =shell.nix=. Furthermore, if you don't use =shell.nix=,
342 | but use =default.nix= it is also optional.
343 |
344 | Finally, we can activate the configuration (Direnv has some security measures to
345 | prevent abuse from running arbitrary scripts):
346 |
347 | #+begin_src sh :eval no
348 | direnv allow
349 | #+end_src
350 |
351 | At this point, if you have your terminal and editor configured to use Direnv,
352 | you should experience per-project environments serviced by Direnv.
353 |
354 | To learn more more about Lorelei's options, we can source the script and run the
355 | function outside Direnv. However, we need to be in a Bash shell:
356 |
357 | #+begin_src sh :eval no
358 | bash -c "
359 | . ~/.nix-profile/share/direnv-nix-lorelei/nix-lorelei.bash
360 | use_nix_gcrooted --help
361 | "
362 | #+end_src
363 |
364 | #+name: help
365 | #+begin_src sh :session env :results output :exports results :post drop(text=*this*, n-dropped=2)
366 | # DESIGN: dropping lines with post processing, and echoing a blank line is a
367 | # hack to deal with the PS2 prompt confusing Org evaluation
368 | bash -c "
369 | . \"$NIX_PROFILE/share/direnv-nix-lorelei/nix-lorelei.bash\"
370 | echo; use_nix_gcrooted --help
371 | "
372 | #+end_src
373 |
374 | #+results: help
375 | #+begin_example
376 | USAGE: use_nix_gcrooted [OPTION]... [FILE]
377 |
378 | DESCRIPTION:
379 |
380 | A replacement for Direnv's use_nix. This function, will make
381 | sure calculated Nix expressions are GC rooted with Nix. By
382 | default the calculated environment is also cached, which is
383 | useful for Nix expressions that have costly evaluations. To
384 | invalidate the cache, files can be watched either by their
385 | content hash or their modification time. You can also delete
386 | .direnv/delete_to_rebuild to invalidate the cache.
387 |
388 | OPTIONS:
389 |
390 | -h --help print this help message
391 | -a --auto-watch-content watch autodetected files for contect
392 | changes
393 | -A --auto-watch-mtime watch autodetected files for
394 | modification times
395 | -d --auto-watch-deep deeper searching for -a and -A options
396 | -w --watch-content PATH watch a file's content for changes
397 | -W --watch-mtime PATH watch a file's modification time
398 | -C --ignore-cache recompute new environment every time
399 | -k --keep-last NUM protect last N caches from GC
400 | (default 5)
401 | #+end_example
402 |
403 | Direnv needs to know when to consider recalculating an environment's variables.
404 | To do this, we need to register files to watch for changes. This is what the
405 | "watch" switches above help specify.
406 |
407 | With the =--auto-watch-content= and =--auto-watch-mtime= switches, you don't
408 | have to worry about which files to watch for changes. You can either watch these
409 | files when their modifications time change, or when their content actually
410 | changes (touching a file changes its modification time, but not its content).
411 |
412 | The =--auto-watch-content= and =--auto-watch-mtime= switches catch a good amount
413 | of Nix files, but won't catch everything you might have the idea to watch. If
414 | you want to specify files to watch explicitly, you can use the =--watch-content=
415 | and =--watch-mtime= switches.
416 |
417 | You can use the =--auto-watch-deep= switch to have the auto-watching features
418 | look a little deeper for files to watch. However, the evaluation time you'll
419 | face for an not-yet-cached environment will be notably longer for this deeper
420 | search (possibly twice as long). Note auto-watching without the
421 | =--auto-watch-deep= switch shouldn't add much evaluation overhead, so you should
422 | be able to use the normal shallower auto-detection without worrying about a
423 | slowdown.
424 |
425 | If for some (unlikely) reason, you want the benefits of protection from Nix
426 | garbage collection, but not cache the evaluation of environments, you can use
427 | =--ignore-cache=. Note, that you still need to specify files to watch for
428 | changes. With =--ignore-cache=, you'll recalculate the Nix expression for your
429 | project every time these watched files trigger Direnv to recalculate an
430 | environment.
431 |
432 | Lorelei keeps the last five environments from being garbage collected. You can
433 | change this with =--keep-last=.
434 |
435 | And finally, if you ever feel like you want to dump your cached environment and
436 | recalculate everything, just delete =.direnv/delete_to_rebuild=, which will be
437 | next to your project's =.envrc= file.
438 |
439 | Lorelei's metadata for your project is in two places:
440 | - your project's =.direnv= directory
441 | - your user's GC root directory: =/nix/var/nix/gcroots/per-user/$USER=
442 |
443 | You can delete this data to start fresh.
444 |
445 | The symlinks in the GC root directory have human readable names to assist manual
446 | curation if you need it.
447 |
448 | * Prior art
449 |
450 | There are four projects that were considered before writing Lorelei:
451 | - [[lorri][Lorri]]
452 | - [[sorri][Sorri]]
453 | - [[nixdirenv][Nix-direnv]]
454 | - [[nixify][Nixify]]
455 |
456 | Lorelei should subsume the features of all of these projects with the exception
457 | of Lorri's approach to calculating Direnv environments as a background process.
458 | You can think of the name "Lorelei" as a pun of "Lorri-lite," but "Lorelei" is
459 | also the name of a [[lorelei-song][Pogue's song]] you may enjoy.
460 |
461 | All of these different projects can save on the evaluation time of calculating a
462 | Nix expression by caching the Direnv environment. And all of these projects have
463 | some facility to protect dependencies referenced by Direnv environments from
464 | Nix's garbage collection.
465 |
466 | Lorri is the heaviest of these options. To use it, you start a daemon process
467 | that in the background watches files for changes and evaluates/builds
468 | environments. This way, the environment is ready before you actually enter the
469 | project.
470 |
471 | Also Lorri inspects Nix's build log to automatically detect which files need to
472 | be watched for changes. Unfortunately, this often misses useful files to watch
473 | in a project.
474 |
475 | Running a background process can be a heavy extra process, and introduces the
476 | surface area of complexity and exposure to defects (though the Lorri committers
477 | have been committed to fixing them). All of the other projects are
478 | lighter-weight than Lorri in this regard. They are just scripts with no
479 | requirements on a background process.
480 |
481 | Sorri copies a lot of code from Lorri, but removes the background process. So
482 | when you enter a Direnv directory, you will always experience the evaluation
483 | time of calculating a not-yet-cached Direnv environment. With Lorri this
484 | evaluation occurs in the background.
485 |
486 | Lorelei is different from Sorri in two main ways:
487 |
488 | - Lorelei gives much more control of cache invalidation beyond the
489 | auto-detection of files to watch for changes. These approaches are inspired by
490 | Nix-direnv and Nixify.
491 |
492 | - Rather than copying code from Lorri, we actually call Lorri code directly as a
493 | library.
494 |
495 | Lorri has been relatively active about refining the approach to calculating a
496 | Direnv environment, more so than any of the other projects. Sorri copies code,
497 | but leads to more work porting changes from Lorri to Sorri. Lorelei uses Nix to
498 | use Lorri's code directly. This eases maintenance, but does mean that you /have/
499 | to install Lorelei with Nix. However, this is not a bad idea, because Lorelei
500 | rigorously pins all of its dependencies, all the way down to =coreutils=. So by
501 | installing Lorelei with Nix, we get more precision.
502 |
503 | * Known limitations
504 |
505 | There's two known limitations of Lorelei:
506 | - Your project must have a Nix file that can be run with =nix-shell=.
507 | - Nix flakes aren't supported (yet).
508 |
509 | Lorelei delegates strongly to Lorri, so the limitation of requiring an explicit
510 | Nix file to import stems from that. This is not to say that this limitation
511 | can't be improved upon in the future.
512 |
513 | However, we probably don't want to support something like =nix-shell='s
514 | =--packages= switch. This feature of =nix-shell= is generally discouraged by the
515 | Nix community because its implementation has a lot of non-intuitive warts. Nix
516 | will soon release a =nix shell= command that has the potential to more properly
517 | replace the functionality that =nix-shell='s =--packages= switch provides. When
518 | this occurs, both the Lorri and Lorelei can reevaluate their respective
519 | implementation strategies.
520 |
521 | Also, soon to be released in a new version of Nix are [[nix-flakes][Nix flakes]]. If you don't
522 | know what flakes are, you may want to wait until they stabilize and are
523 | officially released. If you're an early adopter of flakes, the [[nixdirenv][Nix-direnv]]
524 | project has support for Nix flakes with it's =use_flake= function. Lorelei can
525 | be installed and used concurrently with other projects offering similar
526 | functionality (Lorri, Nix-direnv, and the rest). You just make different calls
527 | in your project's =.envrc= files. No core contributor of Lorelei is using this
528 | unreleased version of Nix supporting flakes, so we didn't want to provide
529 | something we had not tested ourselves.
530 |
531 | * Release
532 |
533 | The "main" branch of the repository on GitHub has the latest released version
534 | of this code. There is currently no commitment to either forward or backward
535 | compatibility.
536 |
537 | "user/shajra" branches are personal branches that may be force-pushed to. The
538 | "main" branch should not experience force-pushes and is recommended for
539 | general use.
540 |
541 | * License
542 |
543 | All files in this "direnv-nix-lorelei" project are licensed under the terms of
544 | GPLv3 or (at your option) any later version.
545 |
546 | Please see the [[./COPYING.md][./COPYING.md]] file for more details.
547 |
548 | * Contribution
549 |
550 | Feel free to file issues and submit pull requests with GitHub.
551 |
552 | There is only one author to date, so the following copyright covers all files in
553 | this project:
554 |
555 | Copyright © 2020 Sukant Hajra
556 |
557 | * Org-mode teardown :noexport:
558 |
559 | #+call: cleanup()
560 |
--------------------------------------------------------------------------------
/default.nix:
--------------------------------------------------------------------------------
1 | (import ./nix {}).distribution
2 |
--------------------------------------------------------------------------------
/doc/links.org:
--------------------------------------------------------------------------------
1 | #+link: cachix https://cachix.org
2 | #+link: direnv https://direnv.net
3 | #+link: direnv-docs https://direnv.net/#docs
4 | #+link: direnv-editor https://github.com/direnv/direnv/wiki#editor-integration
5 | #+link: direnv-shell https://direnv.net/docs/hook.html
6 | #+link: github-actions https://github.com/shajra/direnv-nix-lorelei/actions
7 | #+link: homemanager https://github.com/nix-community/home-manager
8 | #+link: homemanager-manual https://rycee.gitlab.io/home-manager/
9 | #+link: lorelei-song https://www.youtube.com/watch?v=VDw81PRP2SQ
10 | #+link: lorri https://github.com/target/lorri
11 | #+link: niv https://github.com/nmattia/niv
12 | #+link: nix https://nixos.org/nix
13 | #+link: nix-darwin https://daiderd.com/nix-darwin
14 | #+link: nixdirenv https://github.com/nix-community/nix-direnv
15 | #+link: nix-env https://nixos.org/nix/manual/#sec-nix-env
16 | #+link: nix-expr https://nixos.org/nix/manual/#ch-expression-language
17 | #+link: nix-flakes https://nixos.wiki/wiki/Flakes
18 | #+link: nixify https://github.com/kalbasit/nur-packages/blob/master/pkgs/nixify/envrc
19 | #+link: nix-install https://nixos.org/nix/manual/#chap-installation
20 | #+link: nix-learn https://nixos.org/learn.html
21 | #+link: nixos https://nixos.org
22 | #+link: nixpkgs https://github.com/NixOS/nixpkgs
23 | #+link: nixpkgs-manual https://nixos.org/nixpkgs/manual
24 | #+link: nix-tutorial https://github.com/shajra/example-nix/tree/master/tutorials/0-nix-intro
25 | #+link: shajra-provisioning-base https://github.com/shajra/shajra-provisioning/blob/master/home/modules/base/default.nix
26 | #+link: sorri https://github.com/nmattia/sorri
27 |
--------------------------------------------------------------------------------
/doc/nix.mac.org:
--------------------------------------------------------------------------------
1 | * About this file
2 |
3 | Though =nix.org= is copied across all my Nix projects, not all of the projects
4 | support MacOS. So this file has any snippets that reference Macs, which can then
5 | be commented out as necessary.
6 |
7 | * Mac installation
8 |
9 | If you're on a recent release of MacOS, you will need an extra switch:
10 |
11 | #+begin_src bash :eval no
12 | sh <(curl -L https://nixos.org/nix/install) --daemon \
13 | --darwin-use-unencrypted-nix-store-volume
14 | #+end_src
15 |
--------------------------------------------------------------------------------
/doc/nix.md:
--------------------------------------------------------------------------------
1 | - [About this document](#sec-1)
2 | - [How this project uses Nix](#sec-2)
3 | - [Motivation to use Nix](#sec-3)
4 | - [Level of commitment/risk](#sec-4)
5 | - [Installation and setup](#sec-5)
6 | - [Nix package manager setup](#sec-5-1)
7 | - [Cache setup](#sec-5-2)
8 | - [Working with Nix](#sec-6)
9 | - [Searching Nix files](#sec-6-1)
10 | - [Building Nix expressions](#sec-6-2)
11 | - [Running commands](#sec-6-3)
12 | - [Installing and uninstalling programs](#sec-6-4)
13 | - [Garbage collection](#sec-6-5)
14 | - [Understanding derivations](#nix-drv)
15 | - [Lazy evaluation](#sec-6-7)
16 | - [Next steps](#sec-7)
17 |
18 |
19 | # About this document
20 |
21 | This document is included for people somewhat new to Nix. Although the [official Nix documentation](https://nixos.org/learn.html) has gotten substantially better with time, this is an embedded guide to help get started with Nix so it's easier to use the rest of the project.
22 |
23 | Note that this document only covers the Nix package manager, not [NixOS](https://nixos.org) (a full Linux operating system built on top of Nix) or [Nix-Darwin](https://daiderd.com/nix-darwin) (a project that gives the benefits of NixOS for MacOS).
24 |
25 | # How this project uses Nix
26 |
27 | This project uses the [Nix package manager](https://nixos.org/nix) to download all necessary dependencies and build everything from source. In this regard, Nix is helpful as not just a package manager, but also a build tool. Nix helps us get from raw source files to not only built executables, but all the way to a Nix package, which we can install with Nix if we like.
28 |
29 | [This project's continuous integration (using GitHub Actions)](https://github.com/shajra/direnv-nix-lorelei/actions) caches built packages at [Cachix](https://cachix.org), a service for caching pre-built Nix packages. If you don't want to wait for a full local build when first using this project, setting up Nix to pull from Cachix is recommended.
30 |
31 | Within this project, the various files with a ".nix" extension are Nix files, each of which contains an expression written in the [Nix expression language](https://nixos.org/nix/manual/#ch-expression-language) used by the Nix package manager to specify packages. If you get proficient with this language, you can use these expressions as a starting point to compose your own packages beyond what's provided in this project.
32 |
33 | # Motivation to use Nix
34 |
35 | When making a new software project, wrangling dependencies can be a chore. For instance, GNU Make's makefiles often depend on executables and libraries that may not yet be available on a system. The makefiles in most projects don't assist with getting these dependencies at usable versions. And when projects document how to get and install dependencies, there can be a lot of room for error.
36 |
37 | Nix can build and install projects in a way that's precise, repeatable, and guaranteed not to conflict with anything already installed. Every single dependency needed to build a package is specified in Nix expressions. For each dependency needed to build a package, Nix will download the dependency, build it, and install it as a Nix package for use as a dependency. Nix can even concurrently install multiple versions of any dependency without conflicts.
38 |
39 | Every dependency of a Nix package is itself a Nix package. And Nix supports building packages for a variety of languages. Nix picks up where language-specific tooling stops, layering on top of the tools and techniques native to those ecosystems. Since each package is specified by a Nix expression, and because Nix expressions are designed to be composed together to make new ones, we can make our own expressions to specify new packages with dependencies that may not all come from the same language ecosystem.
40 |
41 | To underscore how repeatable and precise Nix builds are, it helps to know that Nix uniquely identifies packages by a hash derived from the hashes of requisite dependencies and configuration. This is a recursive hash calculation that assures that the smallest change to even a distant transitive dependency of a package changes its hash. When dependencies are downloaded, they are checked against the expected hash. Most Nix projects (this one included) are careful to pin dependencies to specific versions/hashes. Because of this, when building the same project with Nix on two different systems, we get an extremely high confidence we will get the same output, often bit-for-bit. This is a profound degree of precision relative to other popular package managers.
42 |
43 | The repeatability and precision of Nix enables caching services, which for Nix are called *substitutors*. Cachix is one such substitutor. Before building a package, the hash for the package is calculated. If any configured substitutor has a build for the hash, it's pulled down as a substitute. A certificate-based protocol is used to establish trust of substitutors. Between this protocol, and the algorithm for calculating hashes in Nix, you can have confidence that a package pulled from a substitutor will be identical to what you would have built locally.
44 |
45 | All of this makes Nix an attractive tool for managing almost any software project.
46 |
47 | # Level of commitment/risk
48 |
49 | Unless you're on NixOS, you're likely already using another package manager for your operating system already (APT, Yum, etc.). You don't have to worry about Nix or packages installed by Nix conflicting with anything already on your system. Running Nix along side other package managers is safe.
50 |
51 | All the files of a Nix package are located under `/nix` a directory, well isolated from any other package manager. Nix won't touch any directories like `/etc` or `/usr/local`. Nix then symlinks files under `/nix` to your home directory under dot-files like `~/.nix-profile`.
52 |
53 | Hopefully, this alleviates any worry about installing a complex program on your machine. Uninstallation is nearly as easy as deleting everything under `/nix`.
54 |
55 | # Installation and setup
56 |
57 | ## Nix package manager setup
58 |
59 | > **NOTE:** You don't need this step if you're running NixOS, which comes with Nix baked in.
60 |
61 | If you don't already have Nix, [the official installation script](https://nixos.org/learn.html) should work on a variety of UNIX-like operating systems:
62 |
63 | ```bash
64 | sh <(curl -L https://nixos.org/nix/install) --daemon
65 | ```
66 |
67 | If you're on a recent release of MacOS, you will need an extra switch:
68 |
69 | ```bash
70 | sh <(curl -L https://nixos.org/nix/install) --daemon \
71 | --darwin-use-unencrypted-nix-store-volume
72 | ```
73 |
74 | After installation, you may have to exit your terminal session and log back in to have environment variables configured to put Nix executables on your `PATH`.
75 |
76 | The `--daemon` switch installs Nix in the recommended multi-user mode. This requires the script to run commands with `sudo`. The script fairly verbosely reports everything it does and touches. If you later want to uninstall Nix, you can run the installation script again, and it will tell you what to do to get back to a clean state.
77 |
78 | The Nix manual describes [other methods of installing Nix](https://nixos.org/nix/manual/#chap-installation) that may suit you more.
79 |
80 | ## Cache setup
81 |
82 | It's recommended to configure Nix to use shajra.cachix.org as a Nix *substitutor*. This project pushes built Nix packages to [Cachix](https://cachix.org) as part of its continuous integration. Once configured, Nix will pull down these pre-built packages instead of building them locally (potentially saving a lot of time). This augments the default substitutor that pulls from cache.nixos.org.
83 |
84 | You can configure shajra.cachix.org as a substitutor with the following command:
85 |
86 | ```sh
87 | nix run \
88 | --file https://cachix.org/api/v1/install \
89 | cachix \
90 | --command cachix use shajra
91 | ```
92 |
93 | Cachix is a service that anyone can use. You can call this command later to add substitutors for someone else using Cachix, replacing "shajra" with their cache's name.
94 |
95 | If you've just run a multi-user Nix installation and are not yet a trusted user in `/etc/nix/nix.conf`, this command may not work. But it will report back some options to proceed.
96 |
97 | One option sets you up as a trusted user, and installs Cachix configuration for Nix locally at `~/.config/nix/nix.conf`. This configuration will be available immediately, and any subsequent invocation of Nix commands will take advantage of the Cachix cache.
98 |
99 | You can alternatively configure Cachix as a substitutor globally by running the above command as a root user (say with `sudo`), which sets up Cachix directly in `/etc/nix/nix.conf`. The invocation may give further instructions upon completion.
100 |
101 | # Working with Nix
102 |
103 | Though covering Nix comprehensively is beyond the scope of this document, we'll go over a few commands illustrating some usage of Nix with this project.
104 |
105 | ## Searching Nix files
106 |
107 | Each of the Nix files in this project (files with a ".nix" extension) contains exactly one Nix expression. This expression evaluates to one of the following values:
108 |
109 | - simple primitives and functions
110 | - *derivations* of packages that can be built and installed with Nix
111 | - containers of values, allowing a single value to provide multiple values of different types, including more containers of values.
112 |
113 | Once you learn the Nix language, you can read these files to see what kind of values they build. We can use the `nix search` command to see what package derivations a Nix expression contains. For example from the root directory of this project, we can execute:
114 |
115 | ```sh
116 | nix search --file default.nix --no-cache
117 | ```
118 |
119 | * direnv (direnv)
120 | A shell extension that manages your environment
121 |
122 | * direnv-nix-lorelei (direnv-nix-lorelei)
123 | Alternative Nix functions for Direnv
124 |
125 | If you don't get the results above, see the [section on understanding derivations](#nix-drv) for an explanation of a likely problem and workaround.
126 |
127 | Note that because for extremely large Nix expressions, searching can be slow, `nix search` by default returns results from searching an indexed cache. This cache is updated explicitly (with an `--update-cache` switch) but may be inconsistent with what you really want to search. It can be confusing to get incorrect results due to an inconsistent cache. However, because small local projects rarely have that many package derivations we don't really need the cache, and can bypass it with the `--no-cache` switch, as used above. This guarantees accurate results that are fast enough. So for the purposes of this project, it's recommended to always use `--no-cache`.
128 |
129 | The output of `nix search` is formatted as
130 |
131 | * attribute-path (name-of-package)
132 | Short description of package
133 |
134 | *Attribute paths* are used to select values from Nix sets that might be nested. A dot delimits *attributes* in the path. For instance an attribute path of `a.b` selects a value from a set with an `a` attribute that has set with a `b` attribute, that then has the value to select.
135 |
136 | If the Nix expression we're searching evaluates to a single derivation (not in a container), the attribute path will be missing from the `nix search` result.
137 |
138 | Many Nix commands evaluate Nix files. If you specify a directory instead, the command will look for a `default.nix` file within to evaluate. So from the root directory of this project, we could use `.` instead of `default.nix`:
139 |
140 | ```sh
141 | nix search --file . --no-cache
142 | ```
143 |
144 | In the remainder of this document, we'll use `.` instead of `default.nix` since this is conventional for Nix.
145 |
146 | ## Building Nix expressions
147 |
148 | The following result is one returned by our prior execution of `nix search --no-cache --file .`:
149 |
150 | * direnv-nix-lorelei (direnv-nix-lorelei)
151 | Alternative Nix functions for Direnv
152 |
153 | We can see that a package named "direnv-nix-lorelei" can be accessed with the `direnv-nix-lorelei` attribute path in the Nix expression in the project root's `default.nix`. Not shown in the search results above, this package happens to provide the library `nix-alt.sh`.
154 |
155 | We can build this package with `nix build` from the project root:
156 |
157 | ```sh
158 | nix build --file . direnv-nix-lorelei
159 | ```
160 |
161 | The positional arguments to `nix build` are *installables*, which can be referenced by attribute paths. If you supply none then all derivations found are built by default.
162 |
163 | All packages built by Nix are stored in `/nix/store`. Nix won't rebuild packages found there. Once a package is built, its content in `/nix/store` is read-only (until the package is garbage collected, discussed later).
164 |
165 | After a successful call of `nix build`, you'll see one or more symlinks for each package requested in the current working directory. These symlinks by default have a name prefixed with "result" and point back to the respective build in `/nix/store`:
166 |
167 | ```sh
168 | readlink result*
169 | ```
170 |
171 | /nix/store/q44il55npbs3pj2zpg0f828hy6miysn0-direnv-nix-lorelei
172 |
173 | Following these symlinks, we can see the files the project provides:
174 |
175 | ```sh
176 | tree -l result*
177 | ```
178 |
179 | result
180 | └── share
181 | └── direnv-nix-lorelei
182 | └── nix-lorelei.bash
183 |
184 | 2 directories, 1 file
185 |
186 | It's common to configure these "result" symlinks as ignored in source control tools (for instance, for Git within a `.gitignore` file).
187 |
188 | `nix build` has a `--no-link` switch in case you want to build packages without creating "result" symlinks. To get the paths where your packages are located, you can use `nix path-info` after a successful build:
189 |
190 | ```sh
191 | nix path-info --file . direnv-nix-lorelei
192 | ```
193 |
194 | /nix/store/q44il55npbs3pj2zpg0f828hy6miysn0-direnv-nix-lorelei
195 |
196 | ## Running commands
197 |
198 | We can run commands in Nix-curated environments with `nix run`. Nix will take executables found in packages, put them in an environment's `PATH`, and then execute a user-specified command.
199 |
200 | With `nix run`, you don't even have to build the package first with `nix build` or mess around with "result" symlinks. `nix run` will build the project if it's not yet been built.
201 |
202 | For example, to get the help message for the `direnv` executable provided by the `direnv` package selected by the `direnv` attribute path from `.`, we can call the following:
203 |
204 | ```sh
205 | nix run \
206 | --file . \
207 | direnv \
208 | --command direnv --help
209 | ```
210 |
211 | direnv v2.28.0
212 | Usage: direnv COMMAND [...ARGS]
213 |
214 | Available commands
215 | ------------------
216 | …
217 |
218 | Thus far, the argument of the `--file` switch has always referenced a Nix file on our local filesystem. However, it's possible to reference a Nix expression downloaded from the internet. The Nix ecosystem is supported by a giant GitHub repository of Nix expressions called [Nixpkgs](https://github.com/NixOS/nixpkgs). Special branches of this repository are considered *channels* in the Nix ecosystem. A Nixpkgs branch of "nixos-21.05" can be referenced by "channel:nixos-21.05" for `nix` subcommands that accept a `--file` switch.
219 |
220 | Again, as with `nix build`, attribute paths are specified as positional arguments to select packages.
221 |
222 | The command to run is specified after the `--command` switch. `nix run` runs the command in a shell set up with a `PATH` environment variable including all the `bin` directories provided by the selected packages.
223 |
224 | `nix run` also supports an `--ignore-environment` flag that restricts `PATH` to only packages selected, rather than extending the `PATH` of the caller's environment. With `--ignore-environment`, the invocation is more sandboxed.
225 |
226 | ## Installing and uninstalling programs
227 |
228 | We've seen that we can build programs with `nix build` and then execute them using the "result" symlink (`result/bin/*`). Additionally, we've seen that you can run programs with `nix run`. But these additional steps and switches/arguments can feel extraneous. It would be nice if we could just have the programs on our `PATH`. This is what `nix-env` is for.
229 |
230 | `nix-env` maintains a symlink tree, called a *profile*, of installed programs. The active profile is pointed to by a symlink at `~/.nix-profile`. By default, this profile points to `/nix/var/nix/profiles/per-user/$USER/profile`. But you can point your `~/.nix-profile` to any writable location with the `--switch-profile` switch:
231 |
232 | ```sh
233 | nix-env --switch-profile /nix/var/nix/profiles/per-user/$USER/another-profile
234 | ```
235 |
236 | This way, you can just put `~/.nix-profile/bin` on your `PATH`, and any programs installed in your currently active profile will be available for interactive use or scripts.
237 |
238 | We can query what's installed in the active profile with the `--query` switch:
239 |
240 | ```sh
241 | nix-env --query
242 | ```
243 |
244 | To install the `nix-alt.sh` library, which is accessed by the `direnv-nix-lorelei` in our top-level `default.nix` file, we'd run the following:
245 |
246 | ```sh
247 | nix-env --install --file . --attr direnv-nix-lorelei 2>&1
248 | ```
249 |
250 | installing 'direnv-nix-lorelei'
251 |
252 | We can see this installation by querying what's been installed:
253 |
254 | ```sh
255 | nix-env --query
256 | ```
257 |
258 | direnv-nix-lorelei
259 |
260 | And if we want to uninstall a program from our active profile, we do so by its name, in this case "direnv-nix-lorelei":
261 |
262 | ```sh
263 | nix-env --uninstall direnv-nix-lorelei 2>&1
264 | ```
265 |
266 | uninstalling 'direnv-nix-lorelei'
267 |
268 | Note that we've installed our package using its attribute path (`direnv-nix-lorelei`) within the referenced Nix expression. But we uninstall it using the package name ("direnv-nix-lorelei"), which may or may not be the same as the attribute path. When a package is installed, Nix keeps no reference to the expression that evaluated to the derivation of the installed package. The attribute path is only relevant to this expression. In fact, two different expressions could evaluate to the same derivation, but use different attribute paths. This is why we uninstall packages by their package name.
269 |
270 | Also, if you look at the location for your profile, you'll see that Nix retains the symlink trees of previous generations of your profile. In fact you can even rollback to a previous profile with the `--rollback` switch. You can delete old generations of your profile with the `--delete-generations` switch.
271 |
272 | See the [documentation for `nix-env`](https://nixos.org/nix/manual/#sec-nix-env) for more details.
273 |
274 | ## Garbage collection
275 |
276 | Every time you build a new version of your code, it's stored in `/nix/store`. There is a command called `nix-collect-garbage` that purges unneeded packages. Programs that should not be removed by `nix-collect-garbage` can by found by starting with symlinks stored as *garbage collection (GC) roots* under three locations:
277 |
278 | - `/nix/var/nix/gcroots`
279 | - `/nix/var/nix/profiles`
280 | - `/nix/var/nix/manifests`.
281 |
282 | For each package, Nix is aware of all references back to other packages in `/nix/store`, whether in text files or binaries. This helps Nix assure that dependencies of packages linked as GC roots won't be deleted.
283 |
284 | Each "result" symlink created by a `nix build` invocation has a symlink in `/nix/var/nix/gcroots/auto` pointing back it. So we've got symlinks in `/nix/var/nix/gcroots/auto` pointing to "result" symlinks in our projects, which then reference the actual built project in `/nix/store`. These chains of symlinks prevent packages built by `nix build` from being garbage collected.
285 |
286 | If you want a package you've built with `nix build` to be garbage collected, delete the "result" symlink created before calling `nix-collect-garbage`. Breaking symlink chains under `/nix/var/nix/gcroots` removes protection from garbage collection. `nix-collect-garbage` will clean up broken symlinks when it runs.
287 |
288 | Note that everything under `/nix/var/nix/profiles` is considered a GC root as well. This is why users by convention use this location to store their `nix-env` profiles.
289 |
290 | Also, note if you delete a “result\*” link and call `nix-collect-garbage`, though some garbage may be reclaimed, you may find that an old `nix-env` profile is keeping the program alive. As a convenience, `nix-collect-garbage` has a `--delete-old` switch that will delete these old profiles (it just calls `nix-env --delete-generations` on your behalf).
291 |
292 | It's also good to know that `nix-collect-garbage` won't delete packages referenced by any running processes. In the case of `nix run` no garbage collection root symlink is created under `/nix/var/nix/gcroots`, but while `nix run` is running `nix-collect-garbage` won't delete packages needed by the running command. However, once the `nix run` call exits, any packages pulled from a substitutor or built locally are candidates for deletion by `nix-collect-garbage`. If you called `nix run` again after garbage collecting, those packages may be pulled or built again.
293 |
294 | ## Understanding derivations
295 |
296 | We haven't detailed what happens when we build a Nix expression that evaluates to a package derivation. There are two important steps:
297 |
298 | 1. *instantiating* the derivation
299 | 2. *realizing* the instantiated derivation, which builds the final package.
300 |
301 | An instantiated derivation is effectively a script stored in `/nix/store` that Nix can run to build the final package (which also ends up in `/nix/store`). These instantiated derivations have a ".drv" extension, and if you look in `/nix/store` you may find some. Instantiated derivations have references to all necessary build dependencies, also in `/nix/store`, which means that everything is physically in place in `/nix/store` to build the package (no network connectivity is needed to realize an instantiated derivation).
302 |
303 | Note that both `nix build` and `nix run` perform both instantiation and realization of a derivation, so for the most part, we don't have to worry about the difference between instantiating and realizing a derivation.
304 |
305 | However, you may encounter a Nix expression where `nix search` returns nothing, though you're sure that there are derivations to select out. In this case, the Nix expression is using an advanced technique that unfortunately hides attributes from `nix search` until some derivations are instantiated into `/nix/store`. We can force the instantiation of these derivations without realizing their packages with the following command:
306 |
307 | ```sh
308 | nix show-derivation --file default.nix
309 | ```
310 |
311 | Once these derivations are instantiated, you may get more results with `nix search` for the occasional Nix expression that uses some advanced techniques.
312 |
313 | ## Lazy evaluation
314 |
315 | We haven't made a big deal of it, but the Nix language is *lazily evaluated*. This allows a single Nix expression to refer to several thousand packages, but without requiring us to evaluate everything when selecting out packages by attribute paths. In fact, the entire NixOS operating system is based heavily on a single single expression managed in a Git repository called [Nixpkgs](https://github.com/NixOS/nixpkgs).
316 |
317 | # Next steps
318 |
319 | This document has covered a fraction of Nix usage, hopefully enough to introduce Nix in the context of [this project](../README.md).
320 |
321 | An obvious place to start learning more about Nix is [the official documentation](https://nixos.org/learn.html). The author of this project also maintains another project with [a small tutorial on Nix](https://github.com/shajra/example-nix/tree/master/tutorials/0-nix-intro). This tutorial covers the Nix expression language in more detail.
322 |
323 | All the commands we've covered have more switches and options. See the respective man pages for more. Also, we didn't cover `nix-shell`, which can be used for setting up development environments. And we didn't cover much of [Nixpkgs](https://github.com/NixOS/nixpkgs), the gigantic repository of community-curated Nix expressions.
324 |
325 | The Nix ecosystem is vast. This project and documentation illustrates just a small sample of what Nix can do.
326 |
--------------------------------------------------------------------------------
/doc/nix.org:
--------------------------------------------------------------------------------
1 | #+title: Nix Setup and Usage
2 | #+setupfile: links.org
3 |
4 | * Org-mode setup :noexport:
5 |
6 | This document is written in a project-agnostic way so it can be copied to other
7 | projects that use Nix.
8 |
9 | ** Variables
10 |
11 | We set variables in =nix.org.el= and access those settings with the following
12 | macros and source code blocks (using Noweb).
13 |
14 | #+name: get
15 | #+begin_src emacs-lisp :var arg="" :eval yes :results silent
16 | (alist-get (intern arg) (car (read-from-string (f-read "nix.org.el"))))
17 | #+end_src
18 |
19 | #+macro: get (eval (concat $2 (alist-get (intern $1) (car (read-from-string (f-read "nix.org.el")))) $2))
20 | #+macro: package-attr {{{get(package-attr,=)}}}
21 | #+macro: package-name {{{get(package-name,")}}}
22 | #+macro: package-type {{{get(package-type)}}}
23 | #+macro: package-target {{{get(package-target,=)}}}
24 | #+macro: run-src {{{get(run-src,=)}}}
25 | #+macro: run-attr {{{get(run-attr,=)}}}
26 | #+macro: run-name {{{get(run-name,=)}}}
27 | #+macro: run-target {{{get(run-target,=)}}}
28 | #+macro: nixos-release {{{get(nixos-release)}}}
29 |
30 | ** Formatting help
31 |
32 | This snippet can be used as a post-processing step to crop down the results from
33 | an evaluation of a source code block.
34 |
35 | #+name: crop
36 | #+begin_src emacs-lisp :var text="" :var first-n=5 :var last-n=5 :results silent
37 | (let* ((ls (split-string text "\n"))
38 | (first-ls (-take first-n ls))
39 | (rest-first (-drop first-n ls))
40 | (rest-last (-drop-last (+ 1 last-n) rest-first))
41 | (last-ls (-take-last (+ 1 last-n) rest-first)))
42 | (string-join
43 | (if rest-last
44 | (append first-ls '("…") last-ls)
45 | (append first-ls last-ls))
46 | "\n"))
47 | #+end_src
48 |
49 | ** Setup action
50 |
51 | The following helps (using Noweb) set up Nix environment variables for source
52 | block evaluation.
53 |
54 | #+name: nix-init
55 | #+begin_src sh :eval no
56 | export NIX_PROFILE=$(pwd)/nix-profile
57 | export NIX_PAGER=cat
58 | export PATH="$NIX_PROFILE/bin:$PATH"
59 | #+end_src
60 |
61 | Next we perform some side-effects to set up the evaluation of the whole
62 | document.
63 |
64 | #+name: cleanup
65 | #+begin_src sh :dir .. :results output silent :noweb yes
66 | <>
67 | rm --force result*
68 | rm --force "$NIX_PROFILE"*
69 | #+end_src
70 |
71 | This is just a hack to deal with the fact that we never know what directory a
72 | session will start in, so we need a way to calculate the PWD to jump to it.
73 |
74 | #+name: pwd-parent
75 | #+begin_src sh :results output silent
76 | echo cd "$(pwd)/.."
77 | #+end_src
78 |
79 | This begins a session with environment variables initialized.
80 |
81 | #+name: session-init
82 | #+begin_src sh :session env :results output silent :noweb yes
83 | <>
84 | <>
85 | #+end_src
86 |
87 | * About this document
88 |
89 | This document is included for people somewhat new to Nix. Although the [[nix-learn][official
90 | Nix documentation]] has gotten substantially better with time, this is an embedded
91 | guide to help get started with Nix so it's easier to use the rest of the
92 | project.
93 |
94 | Note that this document only covers the Nix package manager, not [[nixos][NixOS]] (a full
95 | Linux operating system built on top of Nix) or [[nix-darwin][Nix-Darwin]] (a project that gives
96 | the benefits of NixOS for MacOS).
97 |
98 | * How this project uses Nix
99 |
100 | This project uses the [[nix][Nix package manager]] to download all necessary dependencies
101 | and build everything from source. In this regard, Nix is helpful as not just a
102 | package manager, but also a build tool. Nix helps us get from raw source files
103 | to not only built executables, but all the way to a Nix package, which we can
104 | install with Nix if we like.
105 |
106 | [[github-actions][This project's continuous integration (using GitHub Actions)]] caches built
107 | packages at [[cachix][Cachix]], a service for caching pre-built Nix packages. If you don't
108 | want to wait for a full local build when first using this project, setting up
109 | Nix to pull from Cachix is recommended.
110 |
111 | Within this project, the various files with a ".nix" extension are Nix files,
112 | each of which contains an expression written in the [[nix-expr][Nix expression language]] used
113 | by the Nix package manager to specify packages. If you get proficient with this
114 | language, you can use these expressions as a starting point to compose your own
115 | packages beyond what's provided in this project.
116 |
117 | * Motivation to use Nix
118 |
119 | When making a new software project, wrangling dependencies can be a chore. For
120 | instance, GNU Make's makefiles often depend on executables and libraries that
121 | may not yet be available on a system. The makefiles in most projects don't
122 | assist with getting these dependencies at usable versions. And when projects
123 | document how to get and install dependencies, there can be a lot of room for
124 | error.
125 |
126 | Nix can build and install projects in a way that's precise, repeatable, and
127 | guaranteed not to conflict with anything already installed. Every single
128 | dependency needed to build a package is specified in Nix expressions. For each
129 | dependency needed to build a package, Nix will download the dependency, build
130 | it, and install it as a Nix package for use as a dependency. Nix can even
131 | concurrently install multiple versions of any dependency without conflicts.
132 |
133 | Every dependency of a Nix package is itself a Nix package. And Nix supports
134 | building packages for a variety of languages. Nix picks up where
135 | language-specific tooling stops, layering on top of the tools and techniques
136 | native to those ecosystems. Since each package is specified by a Nix expression,
137 | and because Nix expressions are designed to be composed together to make new
138 | ones, we can make our own expressions to specify new packages with dependencies
139 | that may not all come from the same language ecosystem.
140 |
141 | To underscore how repeatable and precise Nix builds are, it helps to know that
142 | Nix uniquely identifies packages by a hash derived from the hashes of requisite
143 | dependencies and configuration. This is a recursive hash calculation that
144 | assures that the smallest change to even a distant transitive dependency of a
145 | package changes its hash. When dependencies are downloaded, they are checked
146 | against the expected hash. Most Nix projects (this one included) are careful to
147 | pin dependencies to specific versions/hashes. Because of this, when building the
148 | same project with Nix on two different systems, we get an extremely high
149 | confidence we will get the same output, often bit-for-bit. This is a profound
150 | degree of precision relative to other popular package managers.
151 |
152 | The repeatability and precision of Nix enables caching services, which for Nix
153 | are called /substitutors/. Cachix is one such substitutor. Before building a
154 | package, the hash for the package is calculated. If any configured substitutor
155 | has a build for the hash, it's pulled down as a substitute. A certificate-based
156 | protocol is used to establish trust of substitutors. Between this protocol, and
157 | the algorithm for calculating hashes in Nix, you can have confidence that a
158 | package pulled from a substitutor will be identical to what you would have built
159 | locally.
160 |
161 | All of this makes Nix an attractive tool for managing almost any software
162 | project.
163 |
164 | * Level of commitment/risk
165 |
166 | Unless you're on NixOS, you're likely already using another package manager for
167 | your operating system already (APT, Yum, etc.). You don't have to worry about
168 | Nix or packages installed by Nix conflicting with anything already on your
169 | system. Running Nix along side other package managers is safe.
170 |
171 | All the files of a Nix package are located under =/nix= a directory, well
172 | isolated from any other package manager. Nix won't touch any directories like
173 | =/etc= or =/usr/local=. Nix then symlinks files under =/nix= to your home
174 | directory under dot-files like =~/.nix-profile=.
175 |
176 | Hopefully, this alleviates any worry about installing a complex program on your
177 | machine. Uninstallation is nearly as easy as deleting everything under =/nix=.
178 |
179 | * Installation and setup
180 |
181 | ** Nix package manager setup
182 |
183 | #+begin_quote
184 | *_NOTE:_* You don't need this step if you're running NixOS, which comes with Nix
185 | baked in.
186 | #+end_quote
187 |
188 | If you don't already have Nix, [[nix-learn][the official installation script]] should work on a
189 | variety of UNIX-like operating systems:
190 |
191 | #+begin_src bash :eval no
192 | sh <(curl -L https://nixos.org/nix/install) --daemon
193 | #+end_src
194 |
195 | #+include: "nix.mac.org::*Mac installation" :only-contents t
196 |
197 | After installation, you may have to exit your terminal session and log back in
198 | to have environment variables configured to put Nix executables on your =PATH=.
199 |
200 | The =--daemon= switch installs Nix in the recommended multi-user mode. This
201 | requires the script to run commands with =sudo=. The script fairly verbosely
202 | reports everything it does and touches. If you later want to uninstall Nix, you
203 | can run the installation script again, and it will tell you what to do to get
204 | back to a clean state.
205 |
206 | The Nix manual describes [[nix-install][other methods of installing Nix]] that may suit you more.
207 |
208 | ** Cache setup
209 |
210 | It's recommended to configure Nix to use shajra.cachix.org as a Nix
211 | /substitutor/. This project pushes built Nix packages to [[cachix][Cachix]] as part of its
212 | continuous integration. Once configured, Nix will pull down these pre-built
213 | packages instead of building them locally (potentially saving a lot of time).
214 | This augments the default substitutor that pulls from cache.nixos.org.
215 |
216 | You can configure shajra.cachix.org as a substitutor with the following command:
217 |
218 | #+begin_src sh :eval no
219 | nix run \
220 | --file https://cachix.org/api/v1/install \
221 | cachix \
222 | --command cachix use shajra
223 | #+end_src
224 |
225 | Cachix is a service that anyone can use. You can call this command later to add
226 | substitutors for someone else using Cachix, replacing "shajra" with their
227 | cache's name.
228 |
229 | If you've just run a multi-user Nix installation and are not yet a trusted user
230 | in =/etc/nix/nix.conf=, this command may not work. But it will report back some
231 | options to proceed.
232 |
233 | One option sets you up as a trusted user, and installs Cachix configuration for
234 | Nix locally at =~/.config/nix/nix.conf=. This configuration will be available
235 | immediately, and any subsequent invocation of Nix commands will take advantage
236 | of the Cachix cache.
237 |
238 | You can alternatively configure Cachix as a substitutor globally by running the
239 | above command as a root user (say with =sudo=), which sets up Cachix directly in
240 | =/etc/nix/nix.conf=. The invocation may give further instructions upon
241 | completion.
242 |
243 | * Working with Nix
244 |
245 | Though covering Nix comprehensively is beyond the scope of this document, we'll
246 | go over a few commands illustrating some usage of Nix with this project.
247 |
248 | ** Searching Nix files
249 |
250 | Each of the Nix files in this project (files with a ".nix" extension) contains
251 | exactly one Nix expression. This expression evaluates to one of the following
252 | values:
253 |
254 | - simple primitives and functions
255 | - /derivations/ of packages that can be built and installed with Nix
256 | - containers of values, allowing a single value to provide multiple values of
257 | different types, including more containers of values.
258 |
259 | Once you learn the Nix language, you can read these files to see what kind of
260 | values they build. We can use the =nix search= command to see what package
261 | derivations a Nix expression contains. For example from the root directory of
262 | this project, we can execute:
263 |
264 | #+name: nix-derivation-show
265 | #+begin_src sh :dir .. :results output silent :exports none
266 | nix show-derivation --file default.nix >/dev/null 2>&1
267 | #+end_src
268 |
269 | #+begin_src sh :eval no
270 | nix search --file default.nix --no-cache
271 | #+end_src
272 |
273 | #+name: nix-search
274 | #+begin_src sh :dir .. :results output :exports results :post crop(text=*this*, first-n=9, last-n=0)
275 | nix search --file default.nix --no-cache | ansifilter
276 | #+end_src
277 |
278 | #+results: nix-search
279 | : * direnv (direnv)
280 | : A shell extension that manages your environment
281 | :
282 | : * direnv-nix-lorelei (direnv-nix-lorelei)
283 | : Alternative Nix functions for Direnv
284 | :
285 |
286 | If you don't get the results above, see the [[#nix-drv][section on understanding derivations]]
287 | for an explanation of a likely problem and workaround.
288 |
289 | Note that because for extremely large Nix expressions, searching can be slow,
290 | =nix search= by default returns results from searching an indexed cache. This
291 | cache is updated explicitly (with an =--update-cache= switch) but may be
292 | inconsistent with what you really want to search. It can be confusing to get
293 | incorrect results due to an inconsistent cache. However, because small local
294 | projects rarely have that many package derivations we don't really need the
295 | cache, and can bypass it with the =--no-cache= switch, as used above. This
296 | guarantees accurate results that are fast enough. So for the purposes of this
297 | project, it's recommended to always use =--no-cache=.
298 |
299 | The output of =nix search= is formatted as
300 |
301 | #+begin_example
302 | ,* attribute-path (name-of-package)
303 | Short description of package
304 | #+end_example
305 |
306 | /Attribute paths/ are used to select values from Nix sets that might be nested.
307 | A dot delimits /attributes/ in the path. For instance an attribute path of =a.b=
308 | selects a value from a set with an =a= attribute that has set with a =b=
309 | attribute, that then has the value to select.
310 |
311 | If the Nix expression we're searching evaluates to a single derivation (not in a
312 | container), the attribute path will be missing from the =nix search= result.
313 |
314 | Many Nix commands evaluate Nix files. If you specify a directory instead, the
315 | command will look for a =default.nix= file within to evaluate. So from the root
316 | directory of this project, we could use =.= instead of =default.nix=:
317 |
318 | #+name: nix-search-alt
319 | #+begin_src sh :dir .. :results output silent
320 | nix search --file . --no-cache
321 | #+end_src
322 |
323 | In the remainder of this document, we'll use =.= instead of =default.nix= since
324 | this is conventional for Nix.
325 |
326 | ** Building Nix expressions
327 |
328 | The following result is one returned by our prior execution of ~nix search
329 | --no-cache --file .~:
330 |
331 | #+name: nix-search-specific
332 | #+begin_src sh :dir .. :results output :exports results :noweb yes
333 | nix search --no-cache --file . | ansifilter \
334 | | grep --color=never --after-context=1 '* <> ('
335 | #+end_src
336 |
337 | #+results: nix-search-specific
338 | : * direnv-nix-lorelei (direnv-nix-lorelei)
339 | : Alternative Nix functions for Direnv
340 |
341 | We can see that a package named {{{package-name}}} can be accessed with the
342 | {{{package-attr}}} attribute path in the Nix expression in the project root's
343 | =default.nix=. Not shown in the search results above, this package happens to
344 | provide the {{{package-type}}} {{{package-target}}}.
345 |
346 | We can build this package with =nix build= from the project root:
347 |
348 | #+name: nix-build
349 | #+begin_src sh :dir .. :results output silent :noweb yes
350 | nix build --file . <>
351 | #+end_src
352 |
353 | The positional arguments to =nix build= are /installables/, which can be
354 | referenced by attribute paths. If you supply none then all derivations found are
355 | built by default.
356 |
357 | All packages built by Nix are stored in =/nix/store=. Nix won't rebuild packages
358 | found there. Once a package is built, its content in =/nix/store= is read-only
359 | (until the package is garbage collected, discussed later).
360 |
361 | After a successful call of =nix build=, you'll see one or more symlinks for each
362 | package requested in the current working directory. These symlinks by default
363 | have a name prefixed with "result" and point back to the respective build in
364 | =/nix/store=:
365 |
366 | #+name: nix-build-link
367 | #+begin_src sh :dir .. :results output :exports both
368 | readlink result*
369 | #+end_src
370 |
371 | #+results: nix-build-link
372 | : /nix/store/q44il55npbs3pj2zpg0f828hy6miysn0-direnv-nix-lorelei
373 |
374 | Following these symlinks, we can see the files the project provides:
375 |
376 | #+name: nix-build-tree
377 | #+begin_src sh :dir .. :results output :exports both :post crop(text=*this*, first-n=10, last-n=0)
378 | tree -l result*
379 | #+end_src
380 |
381 | #+results: nix-build-tree
382 | : result
383 | : └── share
384 | : └── direnv-nix-lorelei
385 | : └── nix-lorelei.bash
386 | :
387 | : 2 directories, 1 file
388 |
389 | It's common to configure these "result" symlinks as ignored in source control
390 | tools (for instance, for Git within a =.gitignore= file).
391 |
392 | =nix build= has a =--no-link= switch in case you want to build packages without
393 | creating "result" symlinks. To get the paths where your packages are located,
394 | you can use =nix path-info= after a successful build:
395 |
396 | #+name: nix-build-path
397 | #+begin_src sh :dir .. :results output :exports both :noweb yes
398 | nix path-info --file . <>
399 | #+end_src
400 |
401 | #+results: nix-build-path
402 | : /nix/store/q44il55npbs3pj2zpg0f828hy6miysn0-direnv-nix-lorelei
403 |
404 | ** Running commands
405 |
406 | We can run commands in Nix-curated environments with =nix run=. Nix will take
407 | executables found in packages, put them in an environment's =PATH=, and then
408 | execute a user-specified command.
409 |
410 | With =nix run=, you don't even have to build the package first with =nix build=
411 | or mess around with "result" symlinks. =nix run= will build the project if it's
412 | not yet been built.
413 |
414 | For example, to get the help message for the {{{run-target}}} executable
415 | provided by the {{{run-name}}} package selected by the {{{run-attr}}} attribute
416 | path from {{{run-src}}}, we can call the following:
417 |
418 | #+name: nix-run
419 | #+begin_src sh :dir .. :results output :exports both :noweb yes :post crop(text=*this*, first-n=5, last-n=0)
420 | nix run \
421 | --file <> \
422 | <> \
423 | --command <> --help
424 | #+end_src
425 |
426 | #+results: nix-run
427 | : direnv v2.28.0
428 | : Usage: direnv COMMAND [...ARGS]
429 | :
430 | : Available commands
431 | : ------------------
432 | : …
433 |
434 | Thus far, the argument of the =--file= switch has always referenced a Nix file
435 | on our local filesystem. However, it's possible to reference a Nix expression
436 | downloaded from the internet. The Nix ecosystem is supported by a giant GitHub
437 | repository of Nix expressions called [[nixpkgs][Nixpkgs]]. Special branches of this
438 | repository are considered /channels/ in the Nix ecosystem. A Nixpkgs branch of
439 | "{{{nixos-release}}}" can be referenced by "channel:{{{nixos-release}}}" for
440 | =nix= subcommands that accept a =--file= switch.
441 |
442 | Again, as with =nix build=, attribute paths are specified as positional
443 | arguments to select packages.
444 |
445 | The command to run is specified after the =--command= switch. =nix run= runs the
446 | command in a shell set up with a =PATH= environment variable including all the
447 | =bin= directories provided by the selected packages.
448 |
449 | =nix run= also supports an =--ignore-environment= flag that restricts =PATH= to
450 | only packages selected, rather than extending the =PATH= of the caller's
451 | environment. With =--ignore-environment=, the invocation is more sandboxed.
452 |
453 | ** Installing and uninstalling programs
454 |
455 | We've seen that we can build programs with =nix build= and then execute them
456 | using the "result" symlink (=result/bin/*=). Additionally, we've seen that you
457 | can run programs with =nix run=. But these additional steps and
458 | switches/arguments can feel extraneous. It would be nice if we could just have
459 | the programs on our =PATH=. This is what =nix-env= is for.
460 |
461 | =nix-env= maintains a symlink tree, called a /profile/, of installed programs.
462 | The active profile is pointed to by a symlink at =~/.nix-profile=. By default,
463 | this profile points to =/nix/var/nix/profiles/per-user/$USER/profile=. But you
464 | can point your =~/.nix-profile= to any writable location with the
465 | =--switch-profile= switch:
466 |
467 | #+begin_src sh :eval no
468 | nix-env --switch-profile /nix/var/nix/profiles/per-user/$USER/another-profile
469 | #+end_src
470 |
471 | This way, you can just put =~/.nix-profile/bin= on your =PATH=, and any programs
472 | installed in your currently active profile will be available for interactive use
473 | or scripts.
474 |
475 | We can query what's installed in the active profile with the =--query= switch:
476 |
477 | #+name: nix-env-query-1
478 | #+begin_src sh :session env :results output silent
479 | nix-env --query
480 | #+end_src
481 |
482 | To install the {{{package-target}}} {{{package-type}}}, which is accessed by the
483 | {{{package-attr}}} in our top-level =default.nix= file, we'd run the following:
484 |
485 | #+name: nix-env-install
486 | #+begin_src sh :session env :results output :exports both :noweb yes :post crop(text=*this*, first-n=1, last-n=3)
487 | nix-env --install --file . --attr <> 2>&1
488 | #+end_src
489 |
490 | #+results: nix-env-install
491 | : installing 'direnv-nix-lorelei'
492 |
493 | We can see this installation by querying what's been installed:
494 |
495 | #+name: nix-env-query-2
496 | #+begin_src sh :session env :results output :exports both
497 | nix-env --query
498 | #+end_src
499 |
500 | #+results: nix-env-query-2
501 | : direnv-nix-lorelei
502 |
503 | And if we want to uninstall a program from our active profile, we do so by its
504 | name, in this case {{{package-name}}}:
505 |
506 | #+name: nix-env-uninstall
507 | #+begin_src sh :session env :results output :exports both :noweb yes
508 | nix-env --uninstall <> 2>&1
509 | #+end_src
510 |
511 | #+results: nix-env-uninstall
512 | : uninstalling 'direnv-nix-lorelei'
513 |
514 | Note that we've installed our package using its attribute path
515 | ({{{package-attr}}}) within the referenced Nix expression. But we uninstall it
516 | using the package name ({{{package-name}}}), which may or may not be the same as
517 | the attribute path. When a package is installed, Nix keeps no reference to the
518 | expression that evaluated to the derivation of the installed package. The
519 | attribute path is only relevant to this expression. In fact, two different
520 | expressions could evaluate to the same derivation, but use different attribute
521 | paths. This is why we uninstall packages by their package name.
522 |
523 | Also, if you look at the location for your profile, you'll see that Nix retains
524 | the symlink trees of previous generations of your profile. In fact you can even
525 | rollback to a previous profile with the =--rollback= switch. You can delete old
526 | generations of your profile with the =--delete-generations= switch.
527 |
528 | See the [[nix-env][documentation for =nix-env=]] for more details.
529 |
530 | ** Garbage collection
531 |
532 | Every time you build a new version of your code, it's stored in =/nix/store=.
533 | There is a command called =nix-collect-garbage= that purges unneeded packages.
534 | Programs that should not be removed by =nix-collect-garbage= can by found by
535 | starting with symlinks stored as /garbage collection (GC) roots/ under three
536 | locations:
537 |
538 | - =/nix/var/nix/gcroots=
539 | - =/nix/var/nix/profiles=
540 | - =/nix/var/nix/manifests=.
541 |
542 | For each package, Nix is aware of all references back to other packages in
543 | =/nix/store=, whether in text files or binaries. This helps Nix assure that
544 | dependencies of packages linked as GC roots won't be deleted.
545 |
546 | Each "result" symlink created by a =nix build= invocation has a symlink in
547 | =/nix/var/nix/gcroots/auto= pointing back it. So we've got symlinks in
548 | =/nix/var/nix/gcroots/auto= pointing to "result" symlinks in our projects, which
549 | then reference the actual built project in =/nix/store=. These chains of
550 | symlinks prevent packages built by =nix build= from being garbage collected.
551 |
552 | If you want a package you've built with =nix build= to be garbage collected,
553 | delete the "result" symlink created before calling =nix-collect-garbage=.
554 | Breaking symlink chains under =/nix/var/nix/gcroots= removes protection from
555 | garbage collection. =nix-collect-garbage= will clean up broken symlinks when it
556 | runs.
557 |
558 | Note that everything under =/nix/var/nix/profiles= is considered a GC root as
559 | well. This is why users by convention use this location to store their =nix-env=
560 | profiles.
561 |
562 | Also, note if you delete a “result*” link and call =nix-collect-garbage=, though
563 | some garbage may be reclaimed, you may find that an old =nix-env= profile is
564 | keeping the program alive. As a convenience, =nix-collect-garbage= has a
565 | =--delete-old= switch that will delete these old profiles (it just calls
566 | ~nix-env --delete-generations~ on your behalf).
567 |
568 | It's also good to know that =nix-collect-garbage= won't delete packages
569 | referenced by any running processes. In the case of =nix run= no garbage
570 | collection root symlink is created under =/nix/var/nix/gcroots=, but while =nix
571 | run= is running =nix-collect-garbage= won't delete packages needed by the
572 | running command. However, once the =nix run= call exits, any packages pulled
573 | from a substitutor or built locally are candidates for deletion by
574 | =nix-collect-garbage=. If you called =nix run= again after garbage collecting,
575 | those packages may be pulled or built again.
576 |
577 | ** Understanding derivations
578 | :PROPERTIES:
579 | :CUSTOM_ID: nix-drv
580 | :END:
581 |
582 | We haven't detailed what happens when we build a Nix expression that evaluates
583 | to a package derivation. There are two important steps:
584 |
585 | 1. /instantiating/ the derivation
586 | 2. /realizing/ the instantiated derivation, which builds the final package.
587 |
588 | An instantiated derivation is effectively a script stored in =/nix/store= that
589 | Nix can run to build the final package (which also ends up in =/nix/store=).
590 | These instantiated derivations have a ".drv" extension, and if you look in
591 | =/nix/store= you may find some. Instantiated derivations have references to all
592 | necessary build dependencies, also in =/nix/store=, which means that everything
593 | is physically in place in =/nix/store= to build the package (no network
594 | connectivity is needed to realize an instantiated derivation).
595 |
596 | Note that both =nix build= and =nix run= perform both instantiation and
597 | realization of a derivation, so for the most part, we don't have to worry about
598 | the difference between instantiating and realizing a derivation.
599 |
600 | However, you may encounter a Nix expression where =nix search= returns nothing,
601 | though you're sure that there are derivations to select out. In this case, the
602 | Nix expression is using an advanced technique that unfortunately hides
603 | attributes from =nix search= until some derivations are instantiated into
604 | =/nix/store=. We can force the instantiation of these derivations without
605 | realizing their packages with the following command:
606 |
607 | #+name: nix-derivation-show-again
608 | #+begin_src sh :eval no
609 | nix show-derivation --file default.nix
610 | #+end_src
611 |
612 | Once these derivations are instantiated, you may get more results with =nix
613 | search= for the occasional Nix expression that uses some advanced techniques.
614 |
615 | ** Lazy evaluation
616 |
617 | We haven't made a big deal of it, but the Nix language is /lazily evaluated/.
618 | This allows a single Nix expression to refer to several thousand packages, but
619 | without requiring us to evaluate everything when selecting out packages by
620 | attribute paths. In fact, the entire NixOS operating system is based heavily on
621 | a single single expression managed in a Git repository called [[nixpkgs][Nixpkgs]].
622 |
623 | * Next steps
624 |
625 | This document has covered a fraction of Nix usage, hopefully enough to introduce
626 | Nix in the context of [[file:../README.org][this project]].
627 |
628 | An obvious place to start learning more about Nix is [[nix-learn][the official documentation]].
629 | The author of this project also maintains another project with [[nix-tutorial][a small tutorial
630 | on Nix]]. This tutorial covers the Nix expression language in more detail.
631 |
632 | All the commands we've covered have more switches and options. See the
633 | respective man pages for more. Also, we didn't cover =nix-shell=, which can be
634 | used for setting up development environments. And we didn't cover much of
635 | [[nixpkgs][Nixpkgs]], the gigantic repository of community-curated Nix expressions.
636 |
637 | The Nix ecosystem is vast. This project and documentation illustrates just a
638 | small sample of what Nix can do.
639 |
640 | * Org-mode teardown :noexport:
641 |
642 | #+call: cleanup()
643 |
--------------------------------------------------------------------------------
/doc/nix.org.el:
--------------------------------------------------------------------------------
1 | ((package-attr . "direnv-nix-lorelei")
2 | (package-name . "direnv-nix-lorelei")
3 | (package-type . "library")
4 | (package-target . "nix-alt.sh")
5 | (run-src . ".")
6 | (run-attr . "direnv")
7 | (run-name . "direnv")
8 | (run-target . "direnv")
9 | (nixos-release . "nixos-21.05"))
10 |
--------------------------------------------------------------------------------
/nix/ci.nix:
--------------------------------------------------------------------------------
1 | import ../.
2 |
--------------------------------------------------------------------------------
/nix/default.nix:
--------------------------------------------------------------------------------
1 | { externalOverrides ? {}
2 | }:
3 |
4 | let
5 |
6 | external = import ./external // externalOverrides;
7 |
8 | nix-project = import external.nix-project;
9 |
10 | nixpkgs = import external.nixpkgs-stable {
11 | config = {};
12 | overlays = [overlay];
13 | };
14 |
15 | lorri-stock = nixpkgs.applyPatches {
16 | name = "lorri-stock";
17 | src = external.lorri;
18 | patches = [./env_name_cleanup.patch];
19 | };
20 |
21 | lorri-patched = nixpkgs.applyPatches {
22 | name = "lorri-patched";
23 | src = external.lorri;
24 | patches = [
25 | ./remove_trace.patch
26 | ./env_name_cleanup.patch
27 | ];
28 | };
29 |
30 | overlay = self: _super: nix-project // rec {
31 | lorri-runtime =
32 | self.callPackage
33 | (import "${lorri-stock}/nix/runtime.nix")
34 | {};
35 | lorri-eval-stock = {src}:
36 | (import "${lorri-stock}/src/logged-evaluation.nix")
37 | { inherit src; runTimeClosure = lorri-runtime; };
38 | lorri-eval-patched = {src}:
39 | (import "${lorri-patched}/src/logged-evaluation.nix")
40 | { inherit src; runTimeClosure = lorri-runtime; };
41 | lorri-envrc =
42 | "${lorri-stock}/src/ops/direnv/envrc.bash";
43 | direnv-nix-lorelei =
44 | self.callPackage (import ./direnv-nix-lorelei.nix) {};
45 | direnv-nix-lorelei-home = ./home.nix;
46 | direnv-nix-lorelei-test = self.callPackage (import ./test/test.nix) {};
47 | };
48 |
49 | distribution = {
50 | inherit (nixpkgs)
51 | direnv
52 | direnv-nix-lorelei
53 | direnv-nix-lorelei-home;
54 | };
55 |
56 | build = distribution // {
57 | inherit (nixpkgs)
58 | direnv-nix-lorelei-test
59 | lorri-eval-patched
60 | lorri-eval-stock
61 | ;
62 | };
63 |
64 | in { inherit build distribution nix-project nixpkgs; }
65 |
--------------------------------------------------------------------------------
/nix/direnv-nix-lorelei.nix:
--------------------------------------------------------------------------------
1 | { coreutils
2 | , findutils
3 | , gnused
4 | , jq
5 | , lib
6 | , lorri-envrc
7 | , lorri-eval-stock
8 | , lorri-eval-patched
9 | , nix-project-lib
10 | , path
11 | , xxHash
12 | }:
13 |
14 | let
15 | name = "direnv-nix-lorelei";
16 | meta.description = "Alternative Nix functions for Direnv";
17 | packagePath = "direnv-nix-lorelei";
18 | baseName = "nix-lorelei";
19 | buildSource = lib.sourceFilesBySuffices ./. [
20 | ".json"
21 | ".nix"
22 | ".patch"
23 | ];
24 |
25 | in
26 |
27 | nix-project-lib.writeShellCheckedShareLib name packagePath
28 | {
29 | inherit meta baseName;
30 | }
31 | ''
32 | # shellcheck shell=bash
33 |
34 | _nixgc_usage()
35 | {
36 | "${coreutils}/bin/cat" - < "$build_proof"
276 | }
277 |
278 | _nixgc_record_hashes()
279 | {
280 | "${xxHash}/bin/xxhsum" "$@" > "$hash_cache"
281 | }
282 |
283 | _nixgc_rebuild_needed_hash()
284 | {
285 | local hash_cache="$1"; shift
286 | if ! [ -f "$hash_cache" ]
287 | then
288 | log_status "initializing hashes: $hash_cache"
289 | return 0
290 | fi
291 | if ! "${xxHash}/bin/xxhsum" --check "$hash_cache" >/dev/null
292 | then
293 | log_status "hash check invalidated cache"
294 | return 0
295 | else
296 | log_status "no watched hashes changed"
297 | return 1
298 | fi
299 | }
300 |
301 | _nixgc_watched_from_file()
302 | {
303 | local build_proof="$1"
304 | local hash_cache="$2"
305 | "${coreutils}/bin/cat" "$build_proof"
306 | "${gnused}/bin/sed" -n 's/.*\s\+\(.*\)/\1/p' < "$hash_cache"
307 | }
308 |
309 | _nixgc_rebuild()
310 | {
311 | local env_cache="$1"
312 | local shell_file=
313 | shell_file="$("${coreutils}/bin/readlink" -f "$2")"
314 | local keep_last="$3"
315 | local auto_watch_eval="$4"
316 | # DESIGN: https://github.com/koalaman/shellcheck/issues/817
317 | # shellcheck disable=SC2034
318 | local -n _auto_watch="$5"
319 |
320 | local cache_root
321 | cache_root="$("${coreutils}/bin/dirname" "$env_cache")"
322 |
323 | log_status "rebuilding with Nix"
324 | "${coreutils}/bin/rm" --recursive --force "$env_cache"
325 | "${coreutils}/bin/mkdir" --parents "$cache_root"
326 |
327 | local store_path=()
328 | local build_err=()
329 | _nixgc_build_autowatching \
330 | "$shell_file" "$auto_watch_eval" store_path _auto_watch build_err
331 | if [ -z "''${store_path[0]}" ]
332 | then
333 | for l in "''${build_err[@]}"
334 | do log_error "$l"
335 | done
336 | _nixgc_fail "ERROR: Nix build failed"
337 | fi
338 |
339 | local _pwd;
340 | _pwd="$(pwd)"
341 | _pwd="$("${coreutils}/bin/readlink" -f "$_pwd")"
342 | local pwd_hash
343 | pwd_hash="''${store_path[0]}"
344 | pwd_hash="''${pwd_hash#/nix/store/}"
345 | pwd_hash="''${pwd_hash%%-*}"
346 | local escaped_pwd="''${_pwd/\/}"
347 | escaped_pwd="''${escaped_pwd//\//:}"
348 |
349 | "${coreutils}/bin/ln" --force --symbolic --no-target-directory \
350 | "''${store_path[0]}" \
351 | "$env_cache-$pwd_hash"
352 |
353 | "${coreutils}/bin/ln" --force --symbolic --no-target-directory \
354 | "$env_cache-$pwd_hash" \
355 | "$env_cache"
356 |
357 | local gcroot="/nix/var/nix/gcroots/per-user/$USER"
358 | "${coreutils}/bin/ln" --force --symbolic --no-target-directory \
359 | "$env_cache-$pwd_hash" \
360 | "$gcroot/$escaped_pwd:$pwd_hash"
361 |
362 | "${findutils}/bin/find" "$cache_root" \
363 | -type l -wholename "$env_cache-*" -printf "%T+/%p\n" \
364 | | "${coreutils}/bin/sort" --reverse \
365 | | "${coreutils}/bin/tail" --lines=+"$(("$keep_last" + 1))" \
366 | | {
367 | while read -r line
368 | do
369 | local f="''${line#*/}"
370 | log_status "allowing GC (keeping last $keep_last): $f"
371 | "${coreutils}/bin/rm" "$f"
372 | done
373 | }
374 |
375 | "${findutils}/bin/find" -L "$gcroot" \
376 | -type l \
377 | -name "$escaped_pwd:*" \
378 | -exec "${coreutils}/bin/rm" {} +
379 | }
380 |
381 | _nixgc_build_autowatching()
382 | {
383 | local shell_file="$1"
384 | local auto_watch_eval="$2"
385 | local -n _out="$3"
386 | local -n _watched="$4"
387 | local -n _build_err="$5"
388 | local both=()
389 | local err=()
390 | mapfile -t both < <({
391 | { _nixgc_build "$shell_file" "$auto_watch_eval" \
392 | | _nixgc_capture o ;
393 | } 3>&1 1>&2 2>&3 | _nixgc_capture e ;
394 | } 2>&1)
395 | # DESIGN: https://github.com/koalaman/shellcheck/issues/817
396 | # shellcheck disable=SC2034
397 | mapfile -t _out < <(printf "%s\n" "''${both[@]}" | _nixgc_select_line o)
398 | # DESIGN: https://github.com/koalaman/shellcheck/issues/817
399 | # shellcheck disable=SC2034
400 | mapfile -t err < <(printf "%s\n" "''${both[@]}" | _nixgc_select_line e)
401 | # DESIGN: https://github.com/koalaman/shellcheck/issues/817
402 | # shellcheck disable=SC2034
403 | mapfile -t _watched < <(printf "%s\n" "''${err[@]}" \
404 | | _nixgc_capture_autowatchable)
405 | # DESIGN: https://github.com/koalaman/shellcheck/issues/817
406 | # shellcheck disable=SC2034
407 | mapfile -t _build_err < <(printf "%s\n" "''${err[@]}" \
408 | | "${gnused}/bin/sed" -n '/^error:/,$p')
409 | }
410 |
411 | _nixgc_build()
412 | {
413 | local shell_file="$1"
414 | local auto_watch_eval="$2"
415 | IN_NIX_SHELL=1 \
416 | nix-build \
417 | --show-trace \
418 | --verbose --verbose \
419 | --no-out-link \
420 | --arg src "$shell_file" \
421 | --expr "((import ${buildSource} {}).build.lorri-eval-$auto_watch_eval)"
422 | }
423 |
424 | _nixgc_select_line()
425 | {
426 | local prefix="$1"
427 | "${gnused}/bin/sed" -n "s/^$prefix: \(.*\)$/\1/p"
428 | }
429 |
430 | _nixgc_capture()
431 | {
432 | local prefix="$1"
433 | "${coreutils}/bin/stdbuf" -oL \
434 | "${gnused}/bin/sed" -n "s/\(.*\)/$prefix: \1/p"
435 | }
436 |
437 | _nixgc_capture_autowatchable()
438 | {
439 | "${gnused}/bin/sed" -n "
440 | # find paths and substitute the line for them
441 | s/\(copied source\|evaluating file\|trace: lorri read:\)[^']*'\([^']\+\)'.*/\2/;
442 | # delete /nix/store paths, lines with no found paths, and empty lines
443 | /^\(\/nix\/\|[^\/]\|$\)/d;
444 | # print paths found not in /nix/store
445 | p
446 | " | {
447 | while read -r f
448 | do
449 | if [ -d "$f" ]
450 | then echo "$f/default.nix"
451 | else echo "$f"
452 | fi
453 | done
454 | } | "${coreutils}/bin/sort" -u
455 | }
456 |
457 | _nixgc_import_env()
458 | {
459 | local EVALUATION_ROOT="$1"
460 | . "${lorri-envrc}"
461 | }
462 |
463 | _nixgc_fail()
464 | {
465 | log_error "$@"
466 | exit 1
467 | }
468 | ''
469 |
--------------------------------------------------------------------------------
/nix/env_name_cleanup.patch:
--------------------------------------------------------------------------------
1 | diff --git a/src/logged-evaluation.nix b/src/logged-evaluation.nix
2 | --- a/src/logged-evaluation.nix
3 | +++ b/src/logged-evaluation.nix
4 | @@ -55,7 +55,7 @@ let
5 | # actual environment from being deleted.
6 | keep-env-hack = drv: derivation (
7 | drv.drvAttrs // {
8 | - name = "lorri-keep-env-hack-${drv.name}";
9 | + name = "lorelei-${drv.name}";
10 |
11 | origExtraClosure = drv.extraClosure or [];
12 | extraClosure = runtimeCfg.closure;
13 |
--------------------------------------------------------------------------------
/nix/external/default.nix:
--------------------------------------------------------------------------------
1 | let
2 |
3 | srcs = import ./sources.nix;
4 |
5 | nixpkgs-bootstrap = import srcs.nixpkgs { config = {}; overlays = []; };
6 | isDarwin = nixpkgs-bootstrap.stdenv.isDarwin;
7 |
8 | nixpkgs-stable-linux = srcs.nixpkgs;
9 | nixpkgs-stable-darwin = srcs.nixpkgs-darwin;
10 | nixpkgs-stable =
11 | if isDarwin then nixpkgs-stable-darwin else nixpkgs-stable-linux;
12 |
13 | srcsMerged = srcs // {
14 | inherit nixpkgs-stable nixpkgs-stable-linux nixpkgs-stable-darwin;
15 | };
16 |
17 | in builtins.removeAttrs srcsMerged ["nixpkgs" "nixpkgs-darwin"]
18 |
--------------------------------------------------------------------------------
/nix/external/sources.json:
--------------------------------------------------------------------------------
1 | {
2 | "lorri": {
3 | "branch": "canon",
4 | "description": "Your project's nix-env",
5 | "homepage": "",
6 | "owner": "nix-community",
7 | "repo": "lorri",
8 | "rev": "780c9a9825969f1bd068690717341ba1d5a9538f",
9 | "sha256": "1njp38cvzkz1aq4nymdkxmwan8y17raqqq2qrclavdb2g492dwy7",
10 | "type": "tarball",
11 | "url": "https://github.com/nix-community/lorri/archive/780c9a9825969f1bd068690717341ba1d5a9538f.tar.gz",
12 | "url_template": "https://github.com///archive/.tar.gz"
13 | },
14 | "nix-project": {
15 | "branch": "main",
16 | "description": "Tools to manage a Nix-based project",
17 | "homepage": "",
18 | "owner": "shajra",
19 | "repo": "nix-project",
20 | "rev": "1604510c6972465635408e3279e59b2fda0ef595",
21 | "sha256": "16zxags4rnlbc29wbwyqjfcfksnrjxw2n46n4v9jl2nal94qgha9",
22 | "type": "tarball",
23 | "url": "https://github.com/shajra/nix-project/archive/1604510c6972465635408e3279e59b2fda0ef595.tar.gz",
24 | "url_template": "https://github.com///archive/.tar.gz"
25 | },
26 | "nixpkgs": {
27 | "branch": "nixos-21.05",
28 | "description": "A read-only mirror of NixOS/nixpkgs tracking the released channels. Send issues and PRs to",
29 | "homepage": "https://github.com/NixOS/nixpkgs",
30 | "owner": "NixOS",
31 | "repo": "nixpkgs",
32 | "rev": "6120ac5cd201f6cb593d1b80e861be0342495be9",
33 | "sha256": "04mrjxr1qsdcgcryx7yy72cgcw14c0770gfcgzrdfpnvmjdgbi9i",
34 | "type": "tarball",
35 | "url": "https://github.com/NixOS/nixpkgs/archive/6120ac5cd201f6cb593d1b80e861be0342495be9.tar.gz",
36 | "url_template": "https://github.com///archive/.tar.gz"
37 | },
38 | "nixpkgs-darwin": {
39 | "branch": "nixpkgs-21.05-darwin",
40 | "description": "A read-only mirror of NixOS/nixpkgs tracking the released channels. Send issues and PRs to",
41 | "homepage": "https://github.com/NixOS/nixpkgs",
42 | "owner": "NixOS",
43 | "repo": "nixpkgs",
44 | "rev": "3397f0ede9ea2ded1f8b6fa689dda71a7a67b806",
45 | "sha256": "0dx5hbwjbwy404ng5m3dv2rdfbsw58gxblcxfgdwmpyn2qx14sip",
46 | "type": "tarball",
47 | "url": "https://github.com/NixOS/nixpkgs/archive/3397f0ede9ea2ded1f8b6fa689dda71a7a67b806.tar.gz",
48 | "url_template": "https://github.com///archive/.tar.gz"
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/nix/external/sources.nix:
--------------------------------------------------------------------------------
1 | # This file has been generated by Niv.
2 |
3 | let
4 |
5 | #
6 | # The fetchers. fetch_ fetches specs of type .
7 | #
8 |
9 | fetch_file = pkgs: name: spec:
10 | let
11 | name' = sanitizeName name + "-src";
12 | in
13 | if spec.builtin or true then
14 | builtins_fetchurl { inherit (spec) url sha256; name = name'; }
15 | else
16 | pkgs.fetchurl { inherit (spec) url sha256; name = name'; };
17 |
18 | fetch_tarball = pkgs: name: spec:
19 | let
20 | name' = sanitizeName name + "-src";
21 | in
22 | if spec.builtin or true then
23 | builtins_fetchTarball { name = name'; inherit (spec) url sha256; }
24 | else
25 | pkgs.fetchzip { name = name'; inherit (spec) url sha256; };
26 |
27 | fetch_git = name: spec:
28 | let
29 | ref =
30 | if spec ? ref then spec.ref else
31 | if spec ? branch then "refs/heads/${spec.branch}" else
32 | if spec ? tag then "refs/tags/${spec.tag}" else
33 | abort "In git source '${name}': Please specify `ref`, `tag` or `branch`!";
34 | in
35 | builtins.fetchGit { url = spec.repo; inherit (spec) rev; inherit ref; };
36 |
37 | fetch_local = spec: spec.path;
38 |
39 | fetch_builtin-tarball = name: throw
40 | ''[${name}] The niv type "builtin-tarball" is deprecated. You should instead use `builtin = true`.
41 | $ niv modify ${name} -a type=tarball -a builtin=true'';
42 |
43 | fetch_builtin-url = name: throw
44 | ''[${name}] The niv type "builtin-url" will soon be deprecated. You should instead use `builtin = true`.
45 | $ niv modify ${name} -a type=file -a builtin=true'';
46 |
47 | #
48 | # Various helpers
49 | #
50 |
51 | # https://github.com/NixOS/nixpkgs/pull/83241/files#diff-c6f540a4f3bfa4b0e8b6bafd4cd54e8bR695
52 | sanitizeName = name:
53 | (
54 | concatMapStrings (s: if builtins.isList s then "-" else s)
55 | (
56 | builtins.split "[^[:alnum:]+._?=-]+"
57 | ((x: builtins.elemAt (builtins.match "\\.*(.*)" x) 0) name)
58 | )
59 | );
60 |
61 | # The set of packages used when specs are fetched using non-builtins.
62 | mkPkgs = sources: system:
63 | let
64 | sourcesNixpkgs =
65 | import (builtins_fetchTarball { inherit (sources.nixpkgs) url sha256; }) { inherit system; };
66 | hasNixpkgsPath = builtins.any (x: x.prefix == "nixpkgs") builtins.nixPath;
67 | hasThisAsNixpkgsPath = == ./.;
68 | in
69 | if builtins.hasAttr "nixpkgs" sources
70 | then sourcesNixpkgs
71 | else if hasNixpkgsPath && ! hasThisAsNixpkgsPath then
72 | import {}
73 | else
74 | abort
75 | ''
76 | Please specify either (through -I or NIX_PATH=nixpkgs=...) or
77 | add a package called "nixpkgs" to your sources.json.
78 | '';
79 |
80 | # The actual fetching function.
81 | fetch = pkgs: name: spec:
82 |
83 | if ! builtins.hasAttr "type" spec then
84 | abort "ERROR: niv spec ${name} does not have a 'type' attribute"
85 | else if spec.type == "file" then fetch_file pkgs name spec
86 | else if spec.type == "tarball" then fetch_tarball pkgs name spec
87 | else if spec.type == "git" then fetch_git name spec
88 | else if spec.type == "local" then fetch_local spec
89 | else if spec.type == "builtin-tarball" then fetch_builtin-tarball name
90 | else if spec.type == "builtin-url" then fetch_builtin-url name
91 | else
92 | abort "ERROR: niv spec ${name} has unknown type ${builtins.toJSON spec.type}";
93 |
94 | # If the environment variable NIV_OVERRIDE_${name} is set, then use
95 | # the path directly as opposed to the fetched source.
96 | replace = name: drv:
97 | let
98 | saneName = stringAsChars (c: if isNull (builtins.match "[a-zA-Z0-9]" c) then "_" else c) name;
99 | ersatz = builtins.getEnv "NIV_OVERRIDE_${saneName}";
100 | in
101 | if ersatz == "" then drv else
102 | # this turns the string into an actual Nix path (for both absolute and
103 | # relative paths)
104 | if builtins.substring 0 1 ersatz == "/" then /. + ersatz else /. + builtins.getEnv "PWD" + "/${ersatz}";
105 |
106 | # Ports of functions for older nix versions
107 |
108 | # a Nix version of mapAttrs if the built-in doesn't exist
109 | mapAttrs = builtins.mapAttrs or (
110 | f: set: with builtins;
111 | listToAttrs (map (attr: { name = attr; value = f attr set.${attr}; }) (attrNames set))
112 | );
113 |
114 | # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/lists.nix#L295
115 | range = first: last: if first > last then [] else builtins.genList (n: first + n) (last - first + 1);
116 |
117 | # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L257
118 | stringToCharacters = s: map (p: builtins.substring p 1 s) (range 0 (builtins.stringLength s - 1));
119 |
120 | # https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L269
121 | stringAsChars = f: s: concatStrings (map f (stringToCharacters s));
122 | concatMapStrings = f: list: concatStrings (map f list);
123 | concatStrings = builtins.concatStringsSep "";
124 |
125 | # https://github.com/NixOS/nixpkgs/blob/8a9f58a375c401b96da862d969f66429def1d118/lib/attrsets.nix#L331
126 | optionalAttrs = cond: as: if cond then as else {};
127 |
128 | # fetchTarball version that is compatible between all the versions of Nix
129 | builtins_fetchTarball = { url, name ? null, sha256 }@attrs:
130 | let
131 | inherit (builtins) lessThan nixVersion fetchTarball;
132 | in
133 | if lessThan nixVersion "1.12" then
134 | fetchTarball ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; }))
135 | else
136 | fetchTarball attrs;
137 |
138 | # fetchurl version that is compatible between all the versions of Nix
139 | builtins_fetchurl = { url, name ? null, sha256 }@attrs:
140 | let
141 | inherit (builtins) lessThan nixVersion fetchurl;
142 | in
143 | if lessThan nixVersion "1.12" then
144 | fetchurl ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; }))
145 | else
146 | fetchurl attrs;
147 |
148 | # Create the final "sources" from the config
149 | mkSources = config:
150 | mapAttrs (
151 | name: spec:
152 | if builtins.hasAttr "outPath" spec
153 | then abort
154 | "The values in sources.json should not have an 'outPath' attribute"
155 | else
156 | spec // { outPath = replace name (fetch config.pkgs name spec); }
157 | ) config.sources;
158 |
159 | # The "config" used by the fetchers
160 | mkConfig =
161 | { sourcesFile ? if builtins.pathExists ./sources.json then ./sources.json else null
162 | , sources ? if isNull sourcesFile then {} else builtins.fromJSON (builtins.readFile sourcesFile)
163 | , system ? builtins.currentSystem
164 | , pkgs ? mkPkgs sources system
165 | }: rec {
166 | # The sources, i.e. the attribute set of spec name to spec
167 | inherit sources;
168 |
169 | # The "pkgs" (evaluated nixpkgs) to use for e.g. non-builtin fetchers
170 | inherit pkgs;
171 | };
172 |
173 | in
174 | mkSources (mkConfig {}) // { __functor = _: settings: mkSources (mkConfig settings); }
175 |
--------------------------------------------------------------------------------
/nix/home.nix:
--------------------------------------------------------------------------------
1 | { config, lib, pkgs, ... }:
2 |
3 | with lib;
4 |
5 | let cfg = config.programs.direnv-nix-lorelei;
6 |
7 | in {
8 | options = {
9 | programs.direnv-nix-lorelei = {
10 | enable = mkOption {
11 | type = types.bool;
12 | default = false;
13 | defaultText = "false";
14 | description = ''
15 | Whether to enable direnv-nix-lorelei.
16 | '';
17 | };
18 | package = mkOption {
19 | type = types.package;
20 | default = (import ./. {}).distribution.direnv-nix-lorelei;
21 | description = ''
22 | The direnv-nix-lorelei package to use.
23 | '';
24 | };
25 | };
26 | };
27 |
28 | config = mkIf cfg.enable {
29 | xdg.configFile."direnv/lib/nix-lorelei.sh".source =
30 | "${cfg.package}/share/direnv-nix-lorelei/nix-lorelei.bash";
31 | };
32 | }
33 |
--------------------------------------------------------------------------------
/nix/remove_trace.patch:
--------------------------------------------------------------------------------
1 | diff -u a/src/logged-evaluation.nix b/src/logged-evaluation.nix
2 | --- a/src/logged-evaluation.nix
3 | +++ b/src/logged-evaluation.nix
4 | @@ -18,7 +18,7 @@ let
5 |
6 | imported =
7 | let
8 | - raw = overrides.scopedImport overrides src;
9 | + raw = import src;
10 | in
11 | if (builtins.isFunction raw)
12 | then raw {}
13 |
--------------------------------------------------------------------------------
/nix/test/shell.nix:
--------------------------------------------------------------------------------
1 | let pkgs = import { config = {}; overlays = []; };
2 | in pkgs.stdenv.mkDerivation rec {
3 | name = "direnv-nix-lorelei-testcase";
4 | DIRENV_NIX_LORELEI = name;
5 | nativeBuildInputs = [ pkgs.hello ];
6 | }
7 |
--------------------------------------------------------------------------------
/nix/test/test.bats:
--------------------------------------------------------------------------------
1 | setup_file()
2 | {
3 | local testhome
4 | testhome="$(readlink --canonicalize "$BATS_RUN_TMPDIR/testhome")"
5 |
6 | export HOME="$testhome"
7 | export XDG_CONFIG_HOME="$testhome/.config"
8 | export XDG_DATA_HOME="$testhome/.local/share"
9 | export SRC="$testhome/src"
10 |
11 | local lib="$XDG_CONFIG_HOME/direnv/lib"
12 |
13 | mkdir --parents "$lib" "$XDG_DATA_HOME" "$SRC"
14 | cp "$LORELEI/share/direnv-nix-lorelei/nix-lorelei.bash" "$lib/nix-lorelei.sh"
15 | cp "$SHELL_NIX" "$SRC/shell.nix"
16 | echo "use_nix_gcrooted -a" > "$SRC/.envrc"
17 |
18 | direnv allow "$SRC"
19 | }
20 |
21 | @test "Lorelei PATH augmented from build inputs" {
22 | run dash -c 'direnv exec "$SRC" hello -g "_hello there_" 2>&1 | tail -1'
23 | [ "$status" -eq 0 ]
24 | [ "$output" = "_hello there_" ]
25 | }
26 |
27 | @test "Lorelei gets other environment variables too" {
28 | run dash -c 'direnv exec "$SRC" dash -c '"'"' echo "$DIRENV_NIX_LORELEI" '"'"' 2>&1 | tail -1'
29 | [ "$status" -eq 0 ]
30 | [ "$output" = "direnv-nix-lorelei-testcase" ]
31 | }
32 |
33 | @test "Lorelei watches .envrc" {
34 | run grep .envrc "$SRC/.direnv/hashes"
35 | [ "$status" -eq 0 ]
36 | }
37 |
38 | @test "Lorelei watches shell.nix" {
39 | run grep "$SRC/shell.nix" "$SRC/.direnv/hashes"
40 | [ "$status" -eq 0 ]
41 | }
42 |
--------------------------------------------------------------------------------
/nix/test/test.nix:
--------------------------------------------------------------------------------
1 | { bats
2 | , coreutils
3 | , dash
4 | , direnv
5 | , direnv-nix-lorelei
6 | , gnugrep
7 | , ncurses
8 | , nix-project-lib
9 | , path
10 | }:
11 |
12 | let
13 | progName = "direnv-nix-lorelei-test";
14 | meta.description = "Test of Lorelei";
15 | in
16 |
17 | nix-project-lib.writeShellCheckedExe progName
18 | {
19 | inherit meta;
20 | path = [
21 | bats
22 | coreutils
23 | dash
24 | direnv
25 | gnugrep
26 | ncurses # DESIGN: for fancy Bats output
27 | ];
28 | }
29 | ''
30 | set -eu
31 | set -o pipefail
32 |
33 |
34 | . "${nix-project-lib.common}/share/nix-project/common.bash"
35 |
36 |
37 | NIX_EXE="$(command -v nix || true)"
38 |
39 |
40 | print_usage()
41 | {
42 | cat - <