Compare commits

...

No commits in common. "716c028bb159e62d3d295c5101d50ee117f027c6" and "0ba06d0f2cc096a9d575b913b7f7414484384fb6" have entirely different histories.

137 changed files with 6749 additions and 9778 deletions

1
.envrc
View file

@ -1 +0,0 @@
use flake

15
.gitignore vendored
View file

@ -1,19 +1,6 @@
# direnv
.direnv
# Nix
result
result-*
# pre-commit
.pre-commit-config.yaml
# Rust
**/target
# VSCode
# We have an opinionated setup for VSCode, so we want to keep the settings in the repo.
!.vscode
!.vscode/settings.json
# Extension recommendations should be kept in the repo.
!.vscode/extensions.json
/target

View file

@ -1,9 +0,0 @@
{
"recommendations": [
"mkhl.direnv",
"rust-lang.rust-analyzer"
],
"unwantedRecommendations": [
"llvm-vs-code-extensions.vscode-clangd"
]
}

16
.vscode/settings.json vendored
View file

@ -1,16 +0,0 @@
{
// Take from PATH, direnv
"rust-analyzer.server.path": "rust-analyzer",
"[nix]": {
"editor.tabSize": 2,
"editor.insertSpaces": true,
"editor.detectIndentation": false
},
"[rust]": {
"editor.tabSize": 4,
"editor.insertSpaces": true,
"editor.detectIndentation": false
},
}

View file

@ -1,90 +0,0 @@
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
### Added
- `primop::RecoverableError` for primop errors that should not be memoized in the thunk, allowing retry on next force. Required by Nix >= 2.34 ([release note](https://nix.dev/manual/nix/2.34/release-notes/rl-2.34.html#c-api-changes)) for recoverable errors to remain recoverable, as Nix 2.34 memoizes errors by default.
## [0.2.0] - 2026-01-13
### Added
- Workaround for automatic C library input propagation in downstream Nix builds. ([#27] by [@roberth])
- `EvalStateBuilder::load_ambient_settings()` to control whether global Nix settings are loaded. ([#36] by [@roberth])
### Fixed
- Path coercion failing with "path does not exist" errors due to missing `eval_state_builder_load()` call. ([#36] by [@aanderse])
### Changed
- Split `nix-bindings-util-sys` (which contained all low-level FFI bindings) into separate per-library `*-sys` crates. ([#27] by [@Ericson2314])
This allows downstream crates to depend on just the low-level bindings they need without pulling in higher-level crates.
## [0.1.0] - 2026-01-12
Initial release, extracted from the [nixops4 repository](https://github.com/nixops4/nixops4).
### Added
- `nix-bindings-store`: Rust bindings for Nix store operations
- Store opening (auto, from URI, from environment)
- Store path parsing and manipulation
- `Store::get_fs_closure` ([#12] by [@RossComputerGuy], [@roberth])
- `Clone` for `Derivation` ([#25] by [@Ericson2314])
- Store deduplication workaround for [nix#11979]
- aarch64 ABI support ([#26] by [@RossComputerGuy])
- `nix-bindings-expr`: Rust bindings for Nix expression evaluation
- `EvalState` for evaluating Nix expressions
- Value creation (int, string, attrs, thunks, primops, etc.)
- Value inspection/extraction (`require_*` functions)
- Attribute selection and manipulation
- Thread registration for GC safety
- `nix-bindings-fetchers`: Rust bindings for Nix fetchers
- `nix-bindings-flake`: Rust bindings for Nix flake operations
- Flake locking
- Flake overriding
- `nix-bindings-util`: Shared utilities
- Context management for Nix C API error handling
- Settings access
- `nix-bindings-util-sys`: Low-level FFI bindings for all Nix C libraries
### Contributors
Thanks to everyone who contributed to the initial development, some of whom may not be listed with individual changes above:
- [@aanderse]
- [@Ericson2314]
- [@ErinvanderVeen]
- [@numinit]
- [@prednaz]
- [@Radvendii]
- [@roberth]
- [@RossComputerGuy]
<!-- end of 0.1.0 release section -->
[@aanderse]: https://github.com/aanderse
[@Ericson2314]: https://github.com/Ericson2314
[@ErinvanderVeen]: https://github.com/ErinvanderVeen
[@numinit]: https://github.com/numinit
[@prednaz]: https://github.com/prednaz
[@Radvendii]: https://github.com/Radvendii
[@roberth]: https://github.com/roberth
[@RossComputerGuy]: https://github.com/RossComputerGuy
[#12]: https://github.com/nixops4/nix-bindings-rust/pull/12
[#25]: https://github.com/nixops4/nix-bindings-rust/pull/25
[#26]: https://github.com/nixops4/nix-bindings-rust/pull/26
[#27]: https://github.com/nixops4/nix-bindings-rust/pull/27
[#36]: https://github.com/nixops4/nix-bindings-rust/pull/36
[Unreleased]: https://github.com/nixops4/nix-bindings-rust/compare/0.2.0...HEAD
[0.2.0]: https://github.com/nixops4/nix-bindings-rust/compare/0.1.0...0.2.0
[0.1.0]: https://github.com/nixops4/nix-bindings-rust/releases/tag/0.1.0
[nix#11979]: https://github.com/NixOS/nix/issues/11979

1424
Cargo.lock generated

File diff suppressed because it is too large Load diff

View file

@ -1,24 +1,19 @@
[workspace]
members = [
"nix-bindings-bdwgc-sys",
"nix-bindings-util-sys",
"nix-bindings-store-sys",
"nix-bindings-expr-sys",
"nix-bindings-fetchers-sys",
"nix-bindings-flake-sys",
"nix-bindings-expr",
"nix-bindings-fetchers",
"nix-bindings-flake",
"nix-bindings-store",
"nix-bindings-util",
resolver = "3"
members = [
"nixide",
"nixide-sys"
]
resolver = "2"
[workspace.lints.rust]
warnings = "deny"
dead-code = "allow"
[workspace.dependencies]
cc = "1.2.56"
pkg-config = "0.3.32"
[workspace.lints.clippy]
type-complexity = "allow"
# We're still trying to make Nix more thread-safe, want forward-compat
arc-with-non-send-sync = "allow"
# Building bindgen with optimizations makes the build script run faster, more
# than it is offset by the additional build time added to the crate itself by
# enabling optimizations. Since we work with bindgen, might as well.
# P.S.: it ranges from 3x to 5x faster depending on my system, and it'll only
# get better as the C API expands in size. So all things considered this is a
# good thing :)
[profile.dev.package.bindgen]
opt-level = 3

721
LICENSE
View file

@ -1,501 +1,232 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see <https://www.gnu.org/licenses/>.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
nixide
Copyright (C) 2026 luminary
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
nixide Copyright (C) 2026 luminary
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
<signature of Moe Ghoul>, 1 April 1990
Moe Ghoul, President of Vice
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
That's all there is to it!
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <https://www.gnu.org/philosophy/why-not-lgpl.html>.

226
README.md
View file

@ -1,225 +1,3 @@
# Nix Bindings for Rust
# nixide
Rust bindings for the Nix [C API], providing safe, idiomatic Rust interfaces to Nix's core functionality including store operations, expression evaluation, and flake management.
## Overview
This workspace provides multiple crates that wrap different layers of the Nix C API:
- **`nix-bindings-util`** - Utility types and helpers (settings, context, version detection, string handling)
- **`nix-bindings-store`** - Store operations (paths, derivations, store management)
- **`nix-bindings-expr`** - Expression evaluation and type extraction
- **`nix-bindings-flake`** - Flake operations
- **`nix-bindings-fetchers`** - Fetcher functionality (requires Nix ≥ 2.29)
The `*-sys` crates contain generated FFI bindings and are not intended for direct use.
## Features
- **Nix evaluation** - Evaluate Nix expressions and create and extract values
- **Store integration** - Interact with the Nix store, manage paths, build derivations
- **Threading** - GC registration and memory management via `Drop`
- **Lazy evaluation** - Fine-grained control over evaluation strictness
- **Version compatibility** - Conditional compilation for different Nix versions
## Quick Start
Add the crates you need to your `Cargo.toml`:
```toml
[dependencies]
nix-bindings-store = { git = "https://github.com/nixops4/nix-bindings-rust" }
nix-bindings-expr = { git = "https://github.com/nixops4/nix-bindings-rust" }
```
Basic example:
```rust
use nix_bindings_expr::eval_state::{EvalState, init, gc_register_my_thread};
use nix_bindings_store::store::Store;
use std::collections::HashMap;
fn main() -> anyhow::Result<()> {
// Initialize Nix library and register thread with GC
init()?;
let guard = gc_register_my_thread()?;
// Open a store connection and create an evaluation state
let store = Store::open(None, HashMap::new())?;
let mut eval_state = EvalState::new(store, [])?;
// Evaluate a Nix expression
let value = eval_state.eval_from_string("[1 2 3]", "<example>")?;
// Extract typed values
let elements: Vec<_> = eval_state.require_list_strict(&value)?;
for element in elements {
let num = eval_state.require_int(&element)?;
println!("Element: {}", num);
}
drop(guard);
Ok(())
}
```
## Usage Examples
### Evaluating Nix Expressions
```rust
use nix_bindings_expr::eval_state::EvalState;
// Evaluate and extract different types
let int_value = eval_state.eval_from_string("42", "<example>")?;
let num = eval_state.require_int(&int_value)?;
let str_value = eval_state.eval_from_string("\"hello\"", "<example>")?;
let text = eval_state.require_string(&str_value)?;
let attr_value = eval_state.eval_from_string("{ x = 1; y = 2; }", "<example>")?;
let attrs = eval_state.require_attrs(&attr_value)?;
```
### Working with Lists
```rust
let list_value = eval_state.eval_from_string("[1 2 3 4 5]", "<example>")?;
// Lazy: check size without evaluating elements
let size = eval_state.require_list_size(&list_value)?;
// Selective: evaluate only accessed elements
if let Some(first) = eval_state.require_list_select_idx_strict(&list_value, 0)? {
let value = eval_state.require_int(&first)?;
}
// Strict: evaluate all elements
let all_elements: Vec<_> = eval_state.require_list_strict(&list_value)?;
```
### Thread Safety
Before using `EvalState` in a thread, register with the garbage collector:
```rust
use nix_bindings_expr::eval_state::{init, gc_register_my_thread};
init()?; // Once per process
let guard = gc_register_my_thread()?; // Once per thread
// ... use EvalState ...
drop(guard); // Unregister when done
```
For more examples, see the documentation in each crate's source code.
## Nix Version Compatibility
The crates use conditional compilation to support multiple Nix versions:
- **`nix-bindings-fetchers`** requires Nix ≥ 2.29
- Some features in other crates require specific Nix versions
The build system automatically detects the Nix version and enables appropriate features.
## Integration with Nix Projects
These crates use [nix-cargo-integration] for seamless integration with Nix builds. To use them in your Nix project:
```nix
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
flake-parts.url = "github:hercules-ci/flake-parts";
nix-cargo-integration.url = "github:90-008/nix-cargo-integration";
nix-bindings-rust.url = "github:nixops4/nix-bindings-rust";
};
outputs = inputs@{ flake-parts, ... }:
flake-parts.lib.mkFlake { inherit inputs; } {
imports = [
inputs.nix-cargo-integration.flakeModule
inputs.nix-bindings-rust.modules.flake.default
];
perSystem = { config, pkgs, ... }: {
# Optional: override Nix package
nix-bindings-rust.nixPackage = pkgs.nix;
nci.projects."myproject" = {
depsDrvConfig = {
imports = [ config.nix-bindings-rust.nciBuildConfig ];
};
};
};
};
}
```
See the [nix-cargo-integration documentation][nix-cargo-integration] for more options.
## Development
### Getting Started
```console
$ nix develop
```
### Building
```bash
# Build specific crates (release mode)
nix build .#nix-bindings-store-release
nix build .#nix-bindings-expr-release
# Build with Cargo (in dev shell)
cargo build
cargo build --release
```
### Testing
```bash
# Run tests for specific crates via Nix (recommended - includes proper store setup)
nix build .#checks.x86_64-linux.nix-bindings-store-tests
nix build .#checks.x86_64-linux.nix-bindings-expr-tests
# Run all checks (tests + clippy + formatting)
nix flake check
# Run tests with Cargo (in dev shell)
cargo test
# Run specific test
cargo test test_name
```
### Memory Testing
For FFI memory leak testing with valgrind, see [doc/hacking/test-ffi.md](doc/hacking/test-ffi.md).
### Code Formatting
```bash
treefmt
```
### IDE Setup
For VSCode, load the dev shell via Nix Env Selector extension or direnv.
## Documentation
- [API Reference](https://nixops4.github.io/nix-bindings-rust/development/)
- [Changelog](CHANGELOG.md)
- [Nix C API Reference][C API]
- [nix-cargo-integration][nix-cargo-integration]
- [Hacking Guide](doc/hacking/test-ffi.md)
## License
See [LICENSE](LICENSE) file in the repository.
[C API]: https://nix.dev/manual/nix/latest/c-api.html
[nix-cargo-integration]: https://github.com/90-008/nix-cargo-integration#readme
rust wrapper for libnix :3

24
TODO.md Normal file
View file

@ -0,0 +1,24 @@
- [ ] rename `AsInnerPtr::as_ptr` to `AsInnerPtr::as_mut_ptr`
- [ ] add NixError::from_nonnull that replaces calls to NonNull::new(...).ok_or(...)
- [ ] replace all `use nixide_sys as sys;` -> `use crate::sys;`
- [ ] store NonNull pointers in structs!
- [ ] improve documentation situation on context.rs
- [ ] rename `as_ptr()` to `as_inner_ptr()` or `inner_ptr()`?
- [ ] ^^^ this fn should be added to a trait (maybe just `trait NixStructWrapper : AsPtr { ... }`)
- [ ] ^^^ also make `as_ptr()` public
- [ ] add mutexs and make the library thread safe!!
- [ ] grep all `self.inner.as_ptr()` calls and replace them with `self.as_ptr()`
- [ ] `ErrorContext::peak` should return `Result<(), NixideError>` **not** `Option<NixideError>`
- [ ] `self.expect_type` should instead be a macro to preserve the trace macro location
- [ ] make `Value` an enum instead because like duhh
- [ ] ensure we're always calling `ctx.peak()` unless it's ACTUALLY not necessary
- [ ] replace *most* calls to `ErrorContext::peak()` with `ErrorContext::pop()`

View file

@ -1,18 +0,0 @@
# Rust bindgen uses Clang to generate bindings, but that means that it can't
# find the "system" or compiler headers when the stdenv compiler is GCC.
# This script tells it where to find them.
echo "Extending BINDGEN_EXTRA_CLANG_ARGS with system include paths..." 2>&1
BINDGEN_EXTRA_CLANG_ARGS="${BINDGEN_EXTRA_CLANG_ARGS:-}"
export BINDGEN_EXTRA_CLANG_ARGS
include_paths=$(
echo | $NIX_CC_UNWRAPPED -v -E -x c - 2>&1 \
| awk '/#include <...> search starts here:/{flag=1;next} \
/End of search list./{flag=0} \
flag==1 {print $1}'
)
for path in $include_paths; do
echo " - $path" 2>&1
BINDGEN_EXTRA_CLANG_ARGS="$BINDGEN_EXTRA_CLANG_ARGS -I$path"
done

View file

@ -1,259 +0,0 @@
{
inputs,
withSystem,
...
}:
{
imports = [
inputs.pre-commit-hooks-nix.flakeModule
inputs.hercules-ci-effects.flakeModule
inputs.treefmt-nix.flakeModule
];
perSystem =
{
config,
pkgs,
inputs',
...
}:
{
nix-bindings-rust.nixPackage = inputs'.nix.packages.default;
treefmt = {
# Used to find the project root
projectRootFile = "flake.lock";
programs.rustfmt = {
enable = true;
edition = "2021";
};
programs.nixfmt.enable = true;
programs.deadnix.enable = true;
#programs.clang-format.enable = true;
};
pre-commit.settings.hooks.treefmt.enable = true;
# Temporarily disable rustfmt due to configuration issues
# pre-commit.settings.hooks.rustfmt.enable = true;
pre-commit.settings.settings.rust.cargoManifestPath = "./Cargo.toml";
# Check that we're using ///-style doc comments in Rust code.
#
# Unfortunately, rustfmt won't do this for us yet - at least not
# without nightly, and it might do too much.
pre-commit.settings.hooks.rust-doc-comments = {
enable = true;
files = "\\.rs$";
entry = "${pkgs.writeScript "rust-doc-comments" ''
#!${pkgs.runtimeShell}
set -uxo pipefail
grep -n -C3 --color=always -F '/**' "$@"
r=$?
set -e
if [ $r -eq 0 ]; then
echo "Please replace /**-style comments by /// style comments in Rust code."
exit 1
fi
''}";
};
# Combined rustdoc for all crates with cross-linking.
# NOTE: nci.outputs.nix-bindings.docs uses doc-merge which doesn't support
# rustdoc's new sharded search index format (Rust 1.78+).
# See https://github.com/90-008/nix-cargo-integration/issues/198
# Instead, we build all workspace crates together so rustdoc can link them.
packages.docs =
let
# Use nix-bindings-flake (has most transitive deps) as base
base = config.nci.outputs.nix-bindings-flake.packages.release;
crates = [
"nix-bindings-bdwgc-sys"
"nix-bindings-util-sys"
"nix-bindings-util"
"nix-bindings-store-sys"
"nix-bindings-store"
"nix-bindings-expr-sys"
"nix-bindings-expr"
"nix-bindings-fetchers-sys"
"nix-bindings-fetchers"
"nix-bindings-flake-sys"
"nix-bindings-flake"
];
packageFlags = pkgs.lib.concatMapStringsSep " " (c: "-p ${c}") crates;
in
(base.extendModules {
modules = [
{
mkDerivation = {
# Build docs for all crates together (enabling cross-crate linking)
buildPhase = pkgs.lib.mkForce ''
cargo doc $cargoBuildFlags --no-deps --profile $cargoBuildProfile ${packageFlags}
'';
checkPhase = pkgs.lib.mkForce ":";
installPhase = pkgs.lib.mkForce ''
mv target/$CARGO_BUILD_TARGET/doc $out
# Find rustdoc assets (have hashes in filenames)
find_asset() {
local pattern="$1"
local matches=($out/static.files/$pattern)
if [[ ''${#matches[@]} -ne 1 || ! -e "''${matches[0]}" ]]; then
echo "Expected exactly one match for $pattern, found: ''${matches[*]}" >&2
exit 1
fi
basename "''${matches[0]}"
}
rustdoc_css=$(find_asset 'rustdoc-*.css')
normalize_css=$(find_asset 'normalize-*.css')
storage_js=$(find_asset 'storage-*.js')
cat > $out/index.html <<EOF
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>nix-bindings-rust</title>
<link rel="stylesheet" href="static.files/$normalize_css">
<link rel="stylesheet" href="static.files/$rustdoc_css">
<script src="static.files/$storage_js"></script>
<style>
body { max-width: 800px; margin: 2em auto; padding: 0 1em; }
h1 { border-bottom: 1px solid var(--border-color); padding-bottom: 0.5em; }
ul { list-style: none; padding: 0; }
li { margin: 0.5em 0; display: flex; align-items: baseline; }
.crate {
display: inline-block;
min-width: 14em;
background-color: var(--code-block-background-color);
padding: 0.2em 0.5em;
border-radius: 3px;
}
.desc { color: var(--main-color); opacity: 0.7; margin-left: 1em; }
details { margin-top: 1.5em; }
summary { cursor: pointer; }
</style>
</head>
<body>
<h1>nix-bindings-rust</h1>
<p>Rust bindings for the Nix C API</p>
<h2>Crates</h2>
<ul>
<li><span class="crate"><a href="nix_bindings_store/index.html">nix_bindings_store</a></span><span class="desc"> Store operations</span></li>
<li><span class="crate"><a href="nix_bindings_expr/index.html">nix_bindings_expr</a></span><span class="desc"> Expression evaluation</span></li>
<li><span class="crate"><a href="nix_bindings_fetchers/index.html">nix_bindings_fetchers</a></span><span class="desc"> Fetcher operations</span></li>
<li><span class="crate"><a href="nix_bindings_flake/index.html">nix_bindings_flake</a></span><span class="desc"> Flake operations</span></li>
<li><span class="crate"><a href="nix_bindings_util/index.html">nix_bindings_util</a></span><span class="desc"> Utilities</span></li>
</ul>
<details>
<summary><h2 style="display: inline;">Low-level bindings</h2></summary>
<p>
These <code>-sys</code> crates provide raw FFI bindings generated by
<a href="https://rust-lang.github.io/rust-bindgen/">bindgen</a>.
They expose the C API directly without safety wrappers.
Most users should prefer the high-level crates above.
</p>
<ul>
<li><span class="crate"><a href="nix_bindings_store_sys/index.html">nix_bindings_store_sys</a></span><span class="desc"> nix-store-c</span></li>
<li><span class="crate"><a href="nix_bindings_expr_sys/index.html">nix_bindings_expr_sys</a></span><span class="desc"> nix-expr-c</span></li>
<li><span class="crate"><a href="nix_bindings_fetchers_sys/index.html">nix_bindings_fetchers_sys</a></span><span class="desc"> nix-fetchers-c</span></li>
<li><span class="crate"><a href="nix_bindings_flake_sys/index.html">nix_bindings_flake_sys</a></span><span class="desc"> nix-flake-c</span></li>
<li><span class="crate"><a href="nix_bindings_util_sys/index.html">nix_bindings_util_sys</a></span><span class="desc"> nix-util-c</span></li>
<li><span class="crate"><a href="nix_bindings_bdwgc_sys/index.html">nix_bindings_bdwgc_sys</a></span><span class="desc"> Boehm GC</span></li>
</ul>
</details>
</body>
</html>
EOF
'';
};
}
];
}).config.public;
devShells.default = pkgs.mkShell {
name = "nix-bindings-devshell";
strictDeps = true;
inputsFrom = [ config.nci.outputs.nix-bindings.devShell ];
inherit (config.nci.outputs.nix-bindings.devShell.env)
LIBCLANG_PATH
NIX_CC_UNWRAPPED
;
NIX_DEBUG_INFO_DIRS =
let
# TODO: add to Nixpkgs lib
getDebug =
pkg:
if pkg ? debug then
pkg.debug
else if pkg ? lib then
pkg.lib
else
pkg;
in
"${getDebug config.packages.nix}/lib/debug";
buildInputs = [
config.packages.nix
];
nativeBuildInputs = [
config.treefmt.build.wrapper
pkgs.rust-analyzer
pkgs.nixfmt
pkgs.rustfmt
pkgs.pkg-config
pkgs.clang-tools # clangd
pkgs.valgrind
pkgs.gdb
pkgs.hci
# TODO: set up cargo-valgrind in shell and build
# currently both this and `cargo install cargo-valgrind`
# produce a binary that says ENOENT.
# pkgs.cargo-valgrind
];
shellHook = ''
${config.pre-commit.shellHook}
echo 1>&2 "Welcome to the development shell!"
'';
# rust-analyzer needs a NIX_PATH for some reason
NIX_PATH = "nixpkgs=${inputs.nixpkgs}";
};
};
herculesCI =
hci@{ lib, ... }:
{
ciSystems = [ "x86_64-linux" ];
onPush.default.outputs = {
effects.pushDocs = lib.optionalAttrs (hci.config.repo.branch == "main") (
withSystem "x86_64-linux" (
{ config, hci-effects, ... }:
hci-effects.gitWriteBranch {
git.checkout.remote.url = hci.config.repo.remoteHttpUrl;
git.checkout.forgeType = "github";
git.checkout.user = "x-access-token";
git.update.branch = "gh-pages";
contents = config.packages.docs;
destination = "development"; # directory
}
)
);
};
};
hercules-ci.flake-update = {
enable = true;
baseMerge.enable = true;
autoMergeMethod = "merge";
when = {
dayOfMonth = 1;
};
flakes = {
"." = { };
"dev" = { };
};
};
hercules-ci.cargo-publish = {
enable = true;
secretName = "crates-io";
assertVersions = true;
};
flake = { };
}

143
dev/flake.lock generated
View file

@ -1,143 +0,0 @@
{
"nodes": {
"flake-compat": {
"flake": false,
"locked": {
"lastModified": 1767039857,
"narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=",
"owner": "NixOS",
"repo": "flake-compat",
"rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "flake-compat",
"type": "github"
}
},
"flake-parts": {
"inputs": {
"nixpkgs-lib": [
"hercules-ci-effects",
"nixpkgs"
]
},
"locked": {
"lastModified": 1769996383,
"narHash": "sha256-AnYjnFWgS49RlqX7LrC4uA+sCCDBj0Ry/WOJ5XWAsa0=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "57928607ea566b5db3ad13af0e57e921e6b12381",
"type": "github"
},
"original": {
"id": "flake-parts",
"type": "indirect"
}
},
"gitignore": {
"inputs": {
"nixpkgs": [
"pre-commit-hooks-nix",
"nixpkgs"
]
},
"locked": {
"lastModified": 1709087332,
"narHash": "sha256-HG2cCnktfHsKV0s4XW83gU3F57gaTljL9KNSuG6bnQs=",
"owner": "hercules-ci",
"repo": "gitignore.nix",
"rev": "637db329424fd7e46cf4185293b9cc8c88c95394",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "gitignore.nix",
"type": "github"
}
},
"hercules-ci-effects": {
"inputs": {
"flake-parts": "flake-parts",
"nixpkgs": "nixpkgs"
},
"locked": {
"lastModified": 1771131391,
"narHash": "sha256-HPBNYf7HiKtBVy7/69vKpLYHX6wTcUxndxmybzDlXP8=",
"owner": "hercules-ci",
"repo": "hercules-ci-effects",
"rev": "0b152e0f7c5cc265a529cd63374b80e2771b207b",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "hercules-ci-effects",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1771008912,
"narHash": "sha256-gf2AmWVTs8lEq7z/3ZAsgnZDhWIckkb+ZnAo5RzSxJg=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "a82ccc39b39b621151d6732718e3e250109076fa",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"pre-commit-hooks-nix": {
"inputs": {
"flake-compat": "flake-compat",
"gitignore": "gitignore",
"nixpkgs": []
},
"locked": {
"lastModified": 1772024342,
"narHash": "sha256-+eXlIc4/7dE6EcPs9a2DaSY3fTA9AE526hGqkNID3Wg=",
"owner": "cachix",
"repo": "pre-commit-hooks.nix",
"rev": "6e34e97ed9788b17796ee43ccdbaf871a5c2b476",
"type": "github"
},
"original": {
"owner": "cachix",
"repo": "pre-commit-hooks.nix",
"type": "github"
}
},
"root": {
"inputs": {
"hercules-ci-effects": "hercules-ci-effects",
"pre-commit-hooks-nix": "pre-commit-hooks-nix",
"treefmt-nix": "treefmt-nix"
}
},
"treefmt-nix": {
"inputs": {
"nixpkgs": []
},
"locked": {
"lastModified": 1770228511,
"narHash": "sha256-wQ6NJSuFqAEmIg2VMnLdCnUc0b7vslUohqqGGD+Fyxk=",
"owner": "numtide",
"repo": "treefmt-nix",
"rev": "337a4fe074be1042a35086f15481d763b8ddc0e7",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "treefmt-nix",
"type": "github"
}
}
},
"root": "root",
"version": 7
}

View file

@ -1,11 +0,0 @@
{
description = "dependencies only";
inputs = {
pre-commit-hooks-nix.url = "github:cachix/pre-commit-hooks.nix";
pre-commit-hooks-nix.inputs.nixpkgs.follows = "";
hercules-ci-effects.url = "github:hercules-ci/hercules-ci-effects";
treefmt-nix.url = "github:numtide/treefmt-nix";
treefmt-nix.inputs.nixpkgs.follows = "";
};
outputs = { ... }: { };
}

View file

@ -1,25 +0,0 @@
# Testing FFI code
If `cargo-valgrind` is broken, you may run `valgrind` manually.
1. `cargo test -v`
2. find the relevant test suite executable in the log
- example: `/home/user/src/nix-bindings-rust/target/debug/deps/nix_util-036ec381a9e3fd6d`
3. `valgrind --leak-check=full <paste the test exe>`
4. check that
- `definitely lost: 0 bytes in 0 blocks`
## Paranoid check
Although normal valgrind tends to catch things, you may choose to enable `--show-leak-kinds=all`.
This will print a few false positive.
Acceptable leaks are those involving (and this may be Linux-specific)
- `call_init`: static initializers
- `nix::GlobalConfig::Register::Register`
- `_GLOBAL__sub_I_logging.cc`
- ...
- `new<test::test_main::{closure_env#0}>`: a leak in the rust test framework
When in doubt, compare the log to a run with your new test case commented out.

View file

@ -1,23 +0,0 @@
# Release process
This project uses simple tags, that trigger a release of all crates using Hercules CI.
Based on the [HCI Effects cargo publish workflow].
## Steps
1. Create a `release` branch
2. Decide the version bump (patch for fixes, minor for features, major for breaking changes)
3. Update `CHANGELOG.md`: make sure the Unreleased section is up to date, then change it to the new version and release date
4. Open a draft release PR and wait for CI to pass
5. Create and push a tag matching the version
6. Add a new Unreleased section to `CHANGELOG.md`
7. Bump version in all `Cargo.toml` files to the next patch version (e.g., `0.2.0``0.2.1`)
and run `cargo update --workspace` to update `Cargo.lock`,
so that `cargo publish --dry-run` passes on subsequent commits
8. Merge the release PR
---
Dissatisfied with the coarse grained release process? Complain to @roberth and he'll get it done for you.
[HCI Effects cargo publish workflow]: https://docs.hercules-ci.com/hercules-ci-effects/reference/flake-parts/cargo-publish/#_releasing_a_version

3
docs/ref.md Normal file
View file

@ -0,0 +1,3 @@
# Nix Bindgen-rs References
- https://github.com/NotAShelf/nix-bindings
- https://github.com/nixops4/nix-bindings-rust

403
flake.lock generated
View file

@ -1,414 +1,39 @@
{
"nodes": {
"crane": {
"flake": false,
"locked": {
"lastModified": 1758758545,
"narHash": "sha256-NU5WaEdfwF6i8faJ2Yh+jcK9vVFrofLcwlD/mP65JrI=",
"owner": "ipetkov",
"repo": "crane",
"rev": "95d528a5f54eaba0d12102249ce42f4d01f4e364",
"type": "github"
},
"original": {
"owner": "ipetkov",
"ref": "v0.21.1",
"repo": "crane",
"type": "github"
}
},
"dream2nix": {
"inputs": {
"nixpkgs": [
"nix-cargo-integration",
"nixpkgs"
],
"purescript-overlay": "purescript-overlay",
"pyproject-nix": "pyproject-nix"
},
"locked": {
"lastModified": 1765953015,
"narHash": "sha256-5FBZbbWR1Csp3Y2icfRkxMJw/a/5FGg8hCXej2//bbI=",
"owner": "nix-community",
"repo": "dream2nix",
"rev": "69eb01fa0995e1e90add49d8ca5bcba213b0416f",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "dream2nix",
"type": "github"
}
},
"flake-compat": {
"flake": false,
"locked": {
"lastModified": 1767039857,
"narHash": "sha256-vNpUSpF5Nuw8xvDLj2KCwwksIbjua2LZCqhV1LNRDns=",
"owner": "NixOS",
"repo": "flake-compat",
"rev": "5edf11c44bc78a0d334f6334cdaf7d60d732daab",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "flake-compat",
"type": "github"
}
},
"flake-compat_2": {
"flake": false,
"locked": {
"lastModified": 1696426674,
"narHash": "sha256-kvjfFW7WAETZlt09AgDn1MrtKzP7t90Vf7vypd3OL1U=",
"owner": "edolstra",
"repo": "flake-compat",
"rev": "0f9255e01c2351cc7d116c072cb317785dd33b33",
"type": "github"
},
"original": {
"owner": "edolstra",
"repo": "flake-compat",
"type": "github"
}
},
"flake-parts": {
"inputs": {
"nixpkgs-lib": "nixpkgs-lib"
},
"locked": {
"lastModified": 1769996383,
"narHash": "sha256-AnYjnFWgS49RlqX7LrC4uA+sCCDBj0Ry/WOJ5XWAsa0=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "57928607ea566b5db3ad13af0e57e921e6b12381",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "flake-parts",
"type": "github"
}
},
"flake-parts_2": {
"inputs": {
"nixpkgs-lib": [
"nix",
"nixpkgs"
]
},
"locked": {
"lastModified": 1733312601,
"narHash": "sha256-4pDvzqnegAfRkPwO3wmwBhVi/Sye1mzps0zHWYnP88c=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "205b12d8b7cd4802fbcb8e8ef6a0f1408781a4f9",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "flake-parts",
"type": "github"
}
},
"git-hooks-nix": {
"inputs": {
"flake-compat": [
"nix"
],
"gitignore": [
"nix"
],
"nixpkgs": [
"nix",
"nixpkgs"
],
"nixpkgs-stable": [
"nix",
"nixpkgs"
]
},
"locked": {
"lastModified": 1734279981,
"narHash": "sha256-NdaCraHPp8iYMWzdXAt5Nv6sA3MUzlCiGiR586TCwo0=",
"owner": "cachix",
"repo": "git-hooks.nix",
"rev": "aa9f40c906904ebd83da78e7f328cd8aeaeae785",
"type": "github"
},
"original": {
"owner": "cachix",
"repo": "git-hooks.nix",
"type": "github"
}
},
"mk-naked-shell": {
"flake": false,
"locked": {
"lastModified": 1681286841,
"narHash": "sha256-3XlJrwlR0nBiREnuogoa5i1b4+w/XPe0z8bbrJASw0g=",
"owner": "90-008",
"repo": "mk-naked-shell",
"rev": "7612f828dd6f22b7fb332cc69440e839d7ffe6bd",
"type": "github"
},
"original": {
"owner": "90-008",
"repo": "mk-naked-shell",
"type": "github"
}
},
"nix": {
"inputs": {
"flake-compat": "flake-compat",
"flake-parts": "flake-parts_2",
"git-hooks-nix": "git-hooks-nix",
"nixpkgs": [
"nixpkgs"
],
"nixpkgs-23-11": "nixpkgs-23-11",
"nixpkgs-regression": "nixpkgs-regression"
},
"locked": {
"lastModified": 1772224943,
"narHash": "sha256-jJIlRLPPVYu860MVFx4gsRx3sskmLDSRWXXue5tYncw=",
"owner": "NixOS",
"repo": "nix",
"rev": "0acd0566e85e4597269482824711bcde7b518600",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nix",
"type": "github"
}
},
"nix-cargo-integration": {
"inputs": {
"crane": "crane",
"dream2nix": "dream2nix",
"mk-naked-shell": "mk-naked-shell",
"nixpkgs": [
"nixpkgs"
],
"parts": "parts",
"rust-overlay": "rust-overlay",
"treefmt": "treefmt"
},
"locked": {
"lastModified": 1772260057,
"narHash": "sha256-NaUqM0i6XIGdgRNxxQ9sfgCAVeE2Ko9rz7e19RsNUKw=",
"owner": "90-008",
"repo": "nix-cargo-integration",
"rev": "c783c5dff02c06f2af6226d4dd4d494542d0a4d2",
"type": "github"
},
"original": {
"owner": "90-008",
"repo": "nix-cargo-integration",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1772198003,
"narHash": "sha256-I45esRSssFtJ8p/gLHUZ1OUaaTaVLluNkABkk6arQwE=",
"lastModified": 1773222311,
"narHash": "sha256-BHoB/XpbqoZkVYZCfXJXfkR+GXFqwb/4zbWnOr2cRcU=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "dd9b079222d43e1943b6ebd802f04fd959dc8e61",
"rev": "0590cd39f728e129122770c029970378a79d076a",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-unstable",
"ref": "nixos-25.11",
"repo": "nixpkgs",
"type": "github"
}
},
"nixpkgs-23-11": {
"locked": {
"lastModified": 1717159533,
"narHash": "sha256-oamiKNfr2MS6yH64rUn99mIZjc45nGJlj9eGth/3Xuw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "a62e6edd6d5e1fa0329b8653c801147986f8d446",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "a62e6edd6d5e1fa0329b8653c801147986f8d446",
"type": "github"
}
},
"nixpkgs-lib": {
"locked": {
"lastModified": 1769909678,
"narHash": "sha256-cBEymOf4/o3FD5AZnzC3J9hLbiZ+QDT/KDuyHXVJOpM=",
"owner": "nix-community",
"repo": "nixpkgs.lib",
"rev": "72716169fe93074c333e8d0173151350670b824c",
"type": "github"
},
"original": {
"owner": "nix-community",
"repo": "nixpkgs.lib",
"type": "github"
}
},
"nixpkgs-regression": {
"locked": {
"lastModified": 1643052045,
"narHash": "sha256-uGJ0VXIhWKGXxkeNnq4TvV3CIOkUJ3PAoLZ3HMzNVMw=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
"type": "github"
},
"original": {
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "215d4d0fd80ca5163643b03a33fde804a29cc1e2",
"type": "github"
}
},
"parts": {
"inputs": {
"nixpkgs-lib": [
"nix-cargo-integration",
"nixpkgs"
]
},
"locked": {
"lastModified": 1769996383,
"narHash": "sha256-AnYjnFWgS49RlqX7LrC4uA+sCCDBj0Ry/WOJ5XWAsa0=",
"owner": "hercules-ci",
"repo": "flake-parts",
"rev": "57928607ea566b5db3ad13af0e57e921e6b12381",
"type": "github"
},
"original": {
"owner": "hercules-ci",
"repo": "flake-parts",
"type": "github"
}
},
"purescript-overlay": {
"inputs": {
"flake-compat": "flake-compat_2",
"nixpkgs": [
"nix-cargo-integration",
"dream2nix",
"nixpkgs"
],
"slimlock": "slimlock"
},
"locked": {
"lastModified": 1728546539,
"narHash": "sha256-Sws7w0tlnjD+Bjck1nv29NjC5DbL6nH5auL9Ex9Iz2A=",
"owner": "thomashoneyman",
"repo": "purescript-overlay",
"rev": "4ad4c15d07bd899d7346b331f377606631eb0ee4",
"type": "github"
},
"original": {
"owner": "thomashoneyman",
"repo": "purescript-overlay",
"type": "github"
}
},
"pyproject-nix": {
"inputs": {
"nixpkgs": [
"nix-cargo-integration",
"dream2nix",
"nixpkgs"
]
},
"locked": {
"lastModified": 1763017646,
"narHash": "sha256-Z+R2lveIp6Skn1VPH3taQIuMhABg1IizJd8oVdmdHsQ=",
"owner": "pyproject-nix",
"repo": "pyproject.nix",
"rev": "47bd6f296502842643078d66128f7b5e5370790c",
"type": "github"
},
"original": {
"owner": "pyproject-nix",
"repo": "pyproject.nix",
"type": "github"
}
},
"root": {
"inputs": {
"flake-parts": "flake-parts",
"nix": "nix",
"nix-cargo-integration": "nix-cargo-integration",
"nixpkgs": "nixpkgs"
"nixpkgs": "nixpkgs",
"systems": "systems"
}
},
"rust-overlay": {
"inputs": {
"nixpkgs": [
"nix-cargo-integration",
"nixpkgs"
]
},
"systems": {
"locked": {
"lastModified": 1772247314,
"narHash": "sha256-x6IFQ9bL7YYfW2m2z8D3Em2YtAA3HE8kiCFwai2fwrw=",
"owner": "oxalica",
"repo": "rust-overlay",
"rev": "a1ab5e89ab12e1a37c0b264af6386a7472d68a15",
"lastModified": 1681028828,
"narHash": "sha256-Vy1rq5AaRuLzOxct8nz4T6wlgyUR7zLU309k9mBC768=",
"owner": "nix-systems",
"repo": "default",
"rev": "da67096a3b9bf56a91d16901293e51ba5b49a27e",
"type": "github"
},
"original": {
"owner": "oxalica",
"repo": "rust-overlay",
"type": "github"
}
},
"slimlock": {
"inputs": {
"nixpkgs": [
"nix-cargo-integration",
"dream2nix",
"purescript-overlay",
"nixpkgs"
]
},
"locked": {
"lastModified": 1688756706,
"narHash": "sha256-xzkkMv3neJJJ89zo3o2ojp7nFeaZc2G0fYwNXNJRFlo=",
"owner": "thomashoneyman",
"repo": "slimlock",
"rev": "cf72723f59e2340d24881fd7bf61cb113b4c407c",
"type": "github"
},
"original": {
"owner": "thomashoneyman",
"repo": "slimlock",
"type": "github"
}
},
"treefmt": {
"inputs": {
"nixpkgs": [
"nix-cargo-integration",
"nixpkgs"
]
},
"locked": {
"lastModified": 1770228511,
"narHash": "sha256-wQ6NJSuFqAEmIg2VMnLdCnUc0b7vslUohqqGGD+Fyxk=",
"owner": "numtide",
"repo": "treefmt-nix",
"rev": "337a4fe074be1042a35086f15481d763b8ddc0e7",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "treefmt-nix",
"owner": "nix-systems",
"repo": "default",
"type": "github"
}
}

309
flake.nix
View file

@ -1,227 +1,128 @@
{
description = "Rust bindings for the Nix C API";
description = "rust wrapper for libnix";
inputs = {
flake-parts.url = "github:hercules-ci/flake-parts";
nix.url = "github:NixOS/nix";
nix.inputs.nixpkgs.follows = "nixpkgs";
nix-cargo-integration.url = "github:90-008/nix-cargo-integration";
nix-cargo-integration.inputs.nixpkgs.follows = "nixpkgs";
nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";
nixpkgs.url = "github:NixOS/nixpkgs/nixos-25.11";
systems.url = "github:nix-systems/default";
};
outputs =
inputs@{ flake-parts, ... }:
flake-parts.lib.mkFlake { inherit inputs; } (
toplevel@{
outputs = {
self,
nixpkgs,
...
} @ inputs: let
systems = import inputs.systems;
mkPkgs = system: repo:
import repo {
inherit system;
allowUnfree = false;
allowBroken = false;
overlays = builtins.attrValues self.overlays or {};
};
forAllSystems = f:
nixpkgs.lib.genAttrs systems (system:
f rec {
inherit system;
inherit (pkgs) lib;
pkgs = mkPkgs system nixpkgs;
});
in {
overlays.default = self: super: {
libclang = super.llvmPackages_21.libclang;
};
devShells = forAllSystems (
{
pkgs,
lib,
...
}:
let
/**
Makes perSystem.nix-bindings-rust available.
*/
flake-parts-modules.basic =
{
flake-parts-lib,
...
}:
{
_file = ./flake.nix;
imports = [ ./input-propagation-workaround.nix ];
options.perSystem = flake-parts-lib.mkPerSystemOption (
{ pkgs, ... }:
{
options.nix-bindings-rust = {
nixPackage = lib.mkOption {
type = lib.types.package;
default = pkgs.nix;
defaultText = lib.literalMD "pkgs.nix";
description = ''
The Nix package to use when building the `nix-bindings-...` crates.
'';
};
nciBuildConfig = lib.mkOption {
type = lib.types.deferredModule;
description = ''
A module to load into your nix-cargo-integration
[`perSystem.nci.projects.<name>.depsDrvConfig`](https://flake.parts/options/nix-cargo-integration.html#opt-perSystem.nci.projects._name_.depsDrvConfig) or similar such options.
}: {
default = let
nixForBindings = pkgs.nixVersions.nix_2_32;
inherit (pkgs.rustc) llvmPackages;
in
pkgs.mkShell rec {
name = "nixide";
shell = "${pkgs.bash}/bin/bash";
strictDeps = true;
This provides common build configuration (pkg-config, libclang, etc.) and
automatically adds Nix C library build inputs based on which nix-bindings
crates are *direct* dependencies of your crate.
# packages we need at runtime
packages = with pkgs; [
rustc
llvmPackages.lld
lldb
To disable automatic build input detection:
```nix
nix-bindings-rust.inputPropagationWorkaround.enable = false;
```
cargo
cargo-c
cargo-llvm-cov
cargo-nextest
Example:
```nix
perSystem = perSystem@{ config, ... }: {
nci.projects."my_project".drvConfig = {
imports = [ perSystem.config.nix-bindings-rust.nciBuildConfig ];
};
}
```
'';
};
};
config.nix-bindings-rust = {
nciBuildConfig = {
mkDerivation = rec {
buildInputs = [
# stdbool.h
pkgs.stdenv.cc
];
nativeBuildInputs = [
pkgs.pkg-config
];
# bindgen uses clang to generate bindings, but it doesn't know where to
# find our stdenv cc's headers, so when it's gcc, we need to tell it.
postConfigure = lib.optionalString pkgs.stdenv.cc.isGNU ''
source ${./bindgen-gcc.sh}
'';
shellHook = postConfigure;
};
# NOTE: duplicated in flake.nix devShell
env = {
LIBCLANG_PATH = lib.makeLibraryPath [ pkgs.buildPackages.llvmPackages.clang-unwrapped ];
BINDGEN_EXTRA_CLANG_ARGS =
# Work around missing [[deprecated]] in clang
"-x c++ -std=c++2a";
}
// lib.optionalAttrs pkgs.stdenv.cc.isGNU {
# Avoid cc wrapper, because we only need to add the compiler/"system" dirs
NIX_CC_UNWRAPPED = "${pkgs.stdenv.cc.cc}/bin/gcc";
};
};
};
}
);
};
rust-analyzer-unwrapped
(rustfmt.override {asNightly = true;})
clippy
taplo
];
/**
A flake-parts module for dependents to import. Also dogfooded locally
(extra, not required for normal CI).
# packages we need at build time
nativeBuildInputs = with pkgs; [
pkg-config
glibc.dev
nixForBindings.dev
Adds flake checks that test the nix-bindings crates with the
dependent's nix package.
rustPlatform.bindgenHook
];
See https://github.com/nixops4/nix-bindings-rust?tab=readme-ov-file#integration-with-nix-projects
*/
flake-parts-modules.tested =
# Consumer toplevel
{ ... }:
{
_file = ./flake.nix;
imports = [ flake-parts-modules.basic ];
config.perSystem =
# Consumer perSystem
{
lib,
config,
system,
pkgs,
...
}:
let
# nix-bindings-rust's perSystem, but with the consumer's `pkgs`
nix-bindings-rust-perSystemConfig =
# Extending our own perSystem, not the consumer's perSystem!
toplevel.config.partitions.testing-support.module.nix-bindings-rust.internalWithSystem system
({ extendModules, ... }: extendModules)
{
modules = [
{
config = {
# Overriding our `perSystem` to use the consumer's `pkgs`
_module.args.pkgs = lib.mkForce pkgs;
# ... and `nixPackage`
nix-bindings-rust.nixPackage = lib.mkForce config.nix-bindings-rust.nixPackage;
};
}
];
};
in
{
key = "nix-bindings-rust-add-checks";
# Exclude clippy checks; those are part of this repo's local CI.
# This module is for dependents (and local dogfooding), which
# don't need to run clippy on nix-bindings-rust.
config.checks = lib.concatMapAttrs (
k: v:
lib.optionalAttrs (lib.strings.hasPrefix "nix-bindings-" k && !lib.strings.hasSuffix "-clippy" k) {
"dependency-${k}" = v;
}
) nix-bindings-rust-perSystemConfig.config.checks;
};
};
# packages we link against
buildInputs = with pkgs; [
stdenv.cc
flake-parts-modules.default = flake-parts-modules.tested;
nixForBindings
];
in
{
imports = [
inputs.nix-cargo-integration.flakeModule
inputs.flake-parts.flakeModules.partitions
inputs.flake-parts.flakeModules.modules
# dogfood
flake-parts-modules.tested
./nci.nix
];
systems = [
"x86_64-linux"
"aarch64-linux"
"x86_64-darwin"
"aarch64-darwin"
];
perSystem =
{
inputs',
...
}:
{
packages.nix = inputs'.nix.packages.nix;
};
# bindgen uses clang to generate bindings, but it doesn't know where to
# find our stdenv cc's headers, so when it's gcc, we need to tell it.
postConfigure = lib.optionalString pkgs.stdenv.cc.isGNU ''
#!/usr/bin/env bash
# REF: https://github.com/nixops4/nix-bindings-rust/blob/main/bindgen-gcc.sh
# Rust bindgen uses Clang to generate bindings, but that means that it can't
# find the "system" or compiler headers when the stdenv compiler is GCC.
# This script tells it where to find them.
partitionedAttrs.devShells = "dev";
partitionedAttrs.checks = "dev";
partitionedAttrs.herculesCI = "dev";
# Packages are basically just checks in this project; a library by
# itself is not useful. That's just not how the Rust integration works.
# By taking `packages` from `dev` we benefit from this dev-only definition:
# nix-bindings-rust.nixPackage = inputs'.nix.packages.default;
partitionedAttrs.packages = "dev";
echo "Extending BINDGEN_EXTRA_CLANG_ARGS with system include paths..." 2>&1
BINDGEN_EXTRA_CLANG_ARGS="$${BINDGEN_EXTRA_CLANG_ARGS:-}"
export BINDGEN_EXTRA_CLANG_ARGS
include_paths=$(
echo | $NIX_CC_UNWRAPPED -v -E -x c - 2>&1 \
| awk '/#include <...> search starts here:/{flag=1;next} \
/End of search list./{flag=0} \
flag==1 {print $1}'
)
for path in $include_paths; do
echo " - $path" 2>&1
BINDGEN_EXTRA_CLANG_ARGS="$BINDGEN_EXTRA_CLANG_ARGS -I$path"
done
'';
partitions.dev.extraInputsFlake = ./dev;
partitions.dev.module = {
imports = [ ./dev/flake-module.nix ];
};
shellHook = postConfigure;
# A partition that doesn't dogfood the flake-parts-modules.tested module
# so that we can actually retrieve `checks` without infinite recursions
# from trying to include the dogfooded attrs.
partitions.testing-support.module =
{ withSystem, ... }:
{
# Make a clean withSystem available for consumers
options.nix-bindings-rust.internalWithSystem = lib.mkOption { internal = true; };
config = {
nix-bindings-rust.internalWithSystem = withSystem;
perSystem = {
# Remove dogfooded checks. This configuration's checks are
# *consumed* by nix-bindings-rust-add-checks, so they should
# *NOT* also be *produced* by it.
disabledModules = [ { key = "nix-bindings-rust-add-checks"; } ];
};
env = let
inherit (llvmPackages) llvm libclang;
in {
LD_LIBRARY_PATH = builtins.toString (lib.makeLibraryPath buildInputs);
LIBCLANG_PATH = "${libclang.lib}/lib";
RUST_SRC_PATH = "${pkgs.rustPlatform.rustLibSrc}";
BINDGEN_EXTRA_CLANG_ARGS = "--sysroot=${pkgs.glibc.dev}";
# `cargo-llvm-cov` reads these environment variables to find these binaries,
# which are needed to run the tests
LLVM_COV = "${llvm}/bin/llvm-cov";
LLVM_PROFDATA = "${llvm}/bin/llvm-profdata";
};
};
# flake output attributes
flake = {
modules.flake = flake-parts-modules;
};
}
);
};
}

View file

@ -1,143 +0,0 @@
# Workaround for missing native input propagation in nix-cargo-integration
#
# Automatically adds Nix C library build inputs based on which nix-bindings
# crates are direct dependencies of the crate being built. The mapping is
# recursive, so depending on nix-bindings-flake will also bring in the
# transitive C library dependencies (nix-fetchers-c, nix-expr-c, etc.).
#
# Note: For multi-crate workspaces, if your crate A depends on your crate B
# which depends on nix-bindings, you'll need to add an A -> B mapping to
# `crateInputMapping` so that A also gets B's nix-bindings inputs.
{
perSystem =
{
lib,
config,
pkgs,
...
}:
let
cfg = config.nix-bindings-rust.inputPropagationWorkaround;
nixPackage = config.nix-bindings-rust.nixPackage;
nixLibs =
if nixPackage ? libs then
nixPackage.libs
else
# Fallback for older Nix versions without split libs
{
nix-util-c = nixPackage;
nix-store-c = nixPackage;
nix-expr-c = nixPackage;
nix-fetchers-c = nixPackage;
nix-flake-c = nixPackage;
};
# A module for nciBuildConfig that sets buildInputs based on nix-bindings dependencies.
# Uses options inspection to detect drvConfig vs depsDrvConfig context.
workaroundModule =
{
lib,
config,
options,
...
}:
let
# rust-cargo-lock exists in drvConfig but not depsDrvConfig
isDrvConfig = options ? rust-cargo-lock;
dreamLock = config.rust-cargo-lock.dreamLock;
depsList = dreamLock.dependencies.${config.name}.${config.version} or [ ];
# Convert list of deps to attrset keyed by name for efficient lookup
deps = builtins.listToAttrs (
map (dep: {
name = dep.name;
value = dep;
}) depsList
);
# Inputs for the crate itself if it's in the mapping
selfInputs = cfg.crateInputMapping.${config.name} or [ ];
# Inputs for direct dependencies that have mappings
depInputs = lib.concatLists (lib.attrValues (lib.intersectAttrs deps cfg.crateInputMapping));
allInputs = selfInputs ++ depInputs;
in
{
config = lib.optionalAttrs isDrvConfig {
mkDerivation.buildInputs = allInputs;
rust-crane.depsDrv.mkDerivation.buildInputs = allInputs;
};
};
in
{
options.nix-bindings-rust.inputPropagationWorkaround = {
enable = lib.mkOption {
type = lib.types.bool;
default = true;
description = ''
Whether to automatically add Nix C library build inputs based on
which nix-bindings crates are direct dependencies.
Set to `false` to disable automatic detection and specify buildInputs manually.
'';
};
crateInputMapping = lib.mkOption {
type = lib.types.lazyAttrsOf (lib.types.listOf lib.types.package);
description = ''
Mapping from crate names to build inputs. Entries can reference
other entries for transitive dependencies.
The input propagation workaround can see direct dependencies, so
if you have `my-crate -> nix-bindings`, that works out of the box.
If you have `my-other-crate -> my-crate -> nix-bindings`, then you
need to specify `my-other-crate -> my-crate` as follows:
```nix
nix-bindings-rust.inputPropagationWorkaround.crateInputMapping."my-other-crate" =
config.nix-bindings-rust.inputPropagationWorkaround.crateInputMapping."my-crate";
```
'';
default = { };
};
};
config = lib.mkIf cfg.enable {
nix-bindings-rust.inputPropagationWorkaround.crateInputMapping = {
# -sys crates with their transitive dependencies
"nix-bindings-bdwgc-sys" = [ pkgs.boehmgc ];
"nix-bindings-util-sys" = [ nixLibs.nix-util-c.dev ];
"nix-bindings-store-sys" = [
nixLibs.nix-store-c.dev
]
++ cfg.crateInputMapping."nix-bindings-util-sys";
"nix-bindings-expr-sys" = [
nixLibs.nix-expr-c.dev
]
++ cfg.crateInputMapping."nix-bindings-store-sys"
++ cfg.crateInputMapping."nix-bindings-bdwgc-sys";
"nix-bindings-fetchers-sys" = [
nixLibs.nix-fetchers-c.dev
]
++ cfg.crateInputMapping."nix-bindings-expr-sys";
"nix-bindings-flake-sys" = [
nixLibs.nix-flake-c.dev
]
++ cfg.crateInputMapping."nix-bindings-fetchers-sys"
++ cfg.crateInputMapping."nix-bindings-bdwgc-sys";
# High-level crates reference their -sys counterparts
"nix-bindings-bdwgc" = cfg.crateInputMapping."nix-bindings-bdwgc-sys";
"nix-bindings-util" = cfg.crateInputMapping."nix-bindings-util-sys";
"nix-bindings-store" = cfg.crateInputMapping."nix-bindings-store-sys";
"nix-bindings-expr" = cfg.crateInputMapping."nix-bindings-expr-sys";
"nix-bindings-fetchers" = cfg.crateInputMapping."nix-bindings-fetchers-sys";
"nix-bindings-flake" = cfg.crateInputMapping."nix-bindings-flake-sys";
};
nix-bindings-rust.nciBuildConfig.imports = [ workaroundModule ];
};
};
}

72
nci.nix
View file

@ -1,72 +0,0 @@
{
perSystem =
{ config, ... }:
let
cfg = config.nix-bindings-rust;
in
{
# https://flake.parts/options/nix-cargo-integration
nci.projects.nix-bindings = {
path = ./.;
profiles = {
dev.drvConfig.env.RUSTFLAGS = "-D warnings";
release.runTests = true;
};
drvConfig = {
imports = [
# Downstream projects import this into depsDrvConfig instead
cfg.nciBuildConfig
];
# Extra settings for running the tests
mkDerivation = {
# Prepare the environment for Nix to work.
# Nix does not provide a suitable environment for running itself in
# the sandbox - not by default. We configure it to use a relocated store.
preCheck = ''
# nix needs a home directory
export HOME="$(mktemp -d $TMPDIR/home.XXXXXX)"
# configure a relocated store
store_data=$(mktemp -d $TMPDIR/store-data.XXXXXX)
export NIX_REMOTE="$store_data"
export NIX_BUILD_HOOK=
export NIX_CONF_DIR=$store_data/etc
export NIX_LOCALSTATE_DIR=$store_data/nix/var
export NIX_LOG_DIR=$store_data/nix/var/log/nix
export NIX_STATE_DIR=$store_data/nix/var/nix
echo "Configuring relocated store at $NIX_REMOTE..."
# Create nix.conf with experimental features enabled
mkdir -p "$NIX_CONF_DIR"
echo "experimental-features = ca-derivations flakes" > "$NIX_CONF_DIR/nix.conf"
# Init ahead of time, because concurrent initialization is flaky
${cfg.nixPackage}/bin/nix-store --init
echo "Store initialized."
'';
};
};
};
nci.crates.nix-bindings-store =
let
addHarmoniaProfile = ''
cat >> Cargo.toml <<'EOF'
[profile.harmonia]
inherits = "release"
EOF
'';
in
{
profiles.harmonia = {
features = [ "harmonia" ];
runTests = true;
# Add harmonia profile to Cargo.toml for both deps and main builds
depsDrvConfig.mkDerivation.postPatch = addHarmoniaProfile;
drvConfig.mkDerivation.postPatch = addHarmoniaProfile;
};
};
};
}

View file

@ -1,19 +0,0 @@
[package]
name = "nix-bindings-bdwgc-sys"
version = "0.2.1"
edition = "2021"
build = "build.rs"
license = "LGPL-2.1"
description = "Low-level FFI bindings to the Boehm-Demers-Weiser garbage collector"
repository = "https://github.com/nixops4/nix-bindings-rust"
documentation = "https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_bdwgc_sys/"
readme = "README.md"
[lib]
path = "src/lib.rs"
[dependencies]
[build-dependencies]
bindgen = "0.69"
pkg-config = "0.3"

View file

@ -1,10 +0,0 @@
# nix-bindings-bdwgc-sys
This crate contains generated bindings for the Boehm-Demers-Weiser garbage collector (`bdw-gc`).
**You should not have to use this crate directly,** and so you should probably not add it to your dependencies.
[API Documentation](https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_bdwgc_sys/)
## Changelog
See the [nix-bindings-rust changelog](https://github.com/nixops4/nix-bindings-rust/blob/main/CHANGELOG.md).

View file

@ -1,27 +0,0 @@
use std::env;
use std::path::PathBuf;
fn main() {
println!("cargo:rerun-if-changed=include/bdwgc.h");
let mut args = Vec::new();
for path in pkg_config::probe_library("bdw-gc")
.unwrap()
.include_paths
.iter()
{
args.push(format!("-I{}", path.to_str().unwrap()));
}
let bindings = bindgen::Builder::default()
.header("include/bdwgc.h")
.clang_args(args)
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.generate()
.expect("Unable to generate bindings");
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}

View file

@ -1,2 +0,0 @@
#define GC_THREADS
#include <gc/gc.h>

View file

@ -1,30 +0,0 @@
//! Raw bindings to Nix C API
//!
//! This crate contains automatically generated bindings from the Nix C headers.
//! The bindings are generated by bindgen and include C-style naming conventions
//! and documentation comments that don't always conform to Rust standards.
//!
//! Normally you don't have to use this crate directly.
// This file must only contain generated code, so that the module-level
// #![allow(...)] attributes don't suppress warnings in hand-written code.
// If you need to add hand-written code, use a submodule to isolate the
// generated code. See:
// https://github.com/nixops4/nixops4/pull/138/commits/330c3881be3d3cf3e59adebbe0ab1c0f15f6d2c9
// Standard bindgen suppressions for C naming conventions
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
// Clippy suppressions for generated C bindings
// bindgen doesn't generate safety docs
#![allow(clippy::missing_safety_doc)]
// Rustdoc suppressions for generated C documentation
// The C headers contain Doxygen-style documentation that doesn't translate
// well to Rust's rustdoc format, causing various warnings:
#![allow(rustdoc::broken_intra_doc_links)] // @param[in]/[out] references don't resolve
#![allow(rustdoc::bare_urls)] // C docs may contain unescaped URLs
#![allow(rustdoc::invalid_html_tags)] // Doxygen HTML tags like <setting>
#![allow(rustdoc::invalid_codeblock_attributes)] // C code examples may use unsupported attributes
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));

View file

@ -1,21 +0,0 @@
[package]
name = "nix-bindings-expr-sys"
version = "0.2.1"
edition = "2021"
build = "build.rs"
license = "LGPL-2.1"
description = "Low-level FFI bindings to the Nix expression evaluator"
repository = "https://github.com/nixops4/nix-bindings-rust"
documentation = "https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_expr_sys/"
readme = "README.md"
[lib]
path = "src/lib.rs"
[dependencies]
nix-bindings-util-sys = { path = "../nix-bindings-util-sys", version = "0.2.1" }
nix-bindings-store-sys = { path = "../nix-bindings-store-sys", version = "0.2.1" }
[build-dependencies]
bindgen = "0.69"
pkg-config = "0.3"

View file

@ -1,11 +0,0 @@
# nix-bindings-expr-sys
This crate contains generated bindings for the Nix C API (`nix-expr-c`).
**You should not have to use this crate directly,** and so you should probably not add it to your dependencies.
Instead, use the `nix-bindings-expr` crate, which _should_ be sufficient.
[API Documentation](https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_expr_sys/)
## Changelog
See the [nix-bindings-rust changelog](https://github.com/nixops4/nix-bindings-rust/blob/main/CHANGELOG.md).

View file

@ -1,42 +0,0 @@
use std::path::PathBuf;
#[derive(Debug)]
struct StripNixPrefix;
impl bindgen::callbacks::ParseCallbacks for StripNixPrefix {
fn item_name(&self, name: &str) -> Option<String> {
name.strip_prefix("nix_").map(String::from)
}
}
fn main() {
println!("cargo:rerun-if-changed=include/nix-c-expr.h");
println!("cargo:rustc-link-lib=nixexprc");
let mut args = Vec::new();
for path in pkg_config::probe_library("nix-expr-c")
.unwrap()
.include_paths
.iter()
{
args.push(format!("-I{}", path.to_str().unwrap()));
}
let out_path = PathBuf::from(std::env::var("OUT_DIR").unwrap());
let bindings = bindgen::Builder::default()
.header("include/nix-c-expr.h")
.clang_args(args)
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.parse_callbacks(Box::new(StripNixPrefix))
// Blocklist symbols from nix-bindings-util-sys
.blocklist_file(".*nix_api_util\\.h")
// Blocklist symbols from nix-bindings-store-sys
.blocklist_file(".*nix_api_store\\.h")
.generate()
.expect("Unable to generate bindings");
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}

View file

@ -1,2 +0,0 @@
#include <nix_api_expr.h>
#include <nix_api_value.h>

View file

@ -1,34 +0,0 @@
//! Raw bindings to Nix C API
//!
//! This crate contains automatically generated bindings from the Nix C headers.
//! The bindings are generated by bindgen and include C-style naming conventions
//! and documentation comments that don't always conform to Rust standards.
//!
//! Normally you don't have to use this crate directly.
//! Instead use `nix-expr`.
// This file must only contain generated code, so that the module-level
// #![allow(...)] attributes don't suppress warnings in hand-written code.
// If you need to add hand-written code, use a submodule to isolate the
// generated code. See:
// https://github.com/nixops4/nixops4/pull/138/commits/330c3881be3d3cf3e59adebbe0ab1c0f15f6d2c9
// Standard bindgen suppressions for C naming conventions
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
// Clippy suppressions for generated C bindings
// bindgen doesn't generate safety docs
#![allow(clippy::missing_safety_doc)]
// Rustdoc suppressions for generated C documentation
// The C headers contain Doxygen-style documentation that doesn't translate
// well to Rust's rustdoc format, causing various warnings:
#![allow(rustdoc::broken_intra_doc_links)] // @param[in]/[out] references don't resolve
#![allow(rustdoc::bare_urls)] // C docs may contain unescaped URLs
#![allow(rustdoc::invalid_html_tags)] // Doxygen HTML tags like <setting>
#![allow(rustdoc::invalid_codeblock_attributes)] // C code examples may use unsupported attributes
use nix_bindings_store_sys::*;
use nix_bindings_util_sys::*;
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));

View file

@ -1,38 +0,0 @@
[package]
name = "nix-bindings-expr"
version = "0.2.1"
edition = "2021"
build = "build.rs"
license = "LGPL-2.1"
description = "Rust bindings to Nix expression evaluator"
repository = "https://github.com/nixops4/nix-bindings-rust"
documentation = "https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_expr/"
readme = "README.md"
[lib]
path = "src/lib.rs"
[dependencies]
anyhow = "1.0"
nix-bindings-store = { path = "../nix-bindings-store", version = "0.2.1" }
nix-bindings-util = { path = "../nix-bindings-util", version = "0.2.1" }
nix-bindings-bdwgc-sys = { path = "../nix-bindings-bdwgc-sys", version = "0.2.1" }
nix-bindings-util-sys = { path = "../nix-bindings-util-sys", version = "0.2.1" }
nix-bindings-store-sys = { path = "../nix-bindings-store-sys", version = "0.2.1" }
nix-bindings-expr-sys = { path = "../nix-bindings-expr-sys", version = "0.2.1" }
ctor = "0.2"
tempfile = "3.10"
cstr = "0.2"
[build-dependencies]
pkg-config = "0.3"
nix-bindings-util = { path = "../nix-bindings-util", version = "0.2.1" }
[lints.rust]
warnings = "deny"
dead-code = "allow"
[lints.clippy]
type-complexity = "allow"
# We're still trying to make Nix more thread-safe, want forward-compat
arc-with-non-send-sync = "allow"

View file

@ -1,9 +0,0 @@
# nix-bindings-expr
Rust bindings to the Nix expression evaluator.
[API Documentation](https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_expr/)
## Changelog
See the [nix-bindings-rust changelog](https://github.com/nixops4/nix-bindings-rust/blob/main/CHANGELOG.md).

View file

@ -1,6 +0,0 @@
use nix_bindings_util::nix_version::emit_version_cfg;
fn main() {
let nix_version = pkg_config::probe_library("nix-expr-c").unwrap().version;
emit_version_cfg(&nix_version, &["2.26", "2.34.0pre"]);
}

File diff suppressed because it is too large Load diff

View file

@ -1,3 +0,0 @@
pub mod eval_state;
pub mod primop;
pub mod value;

View file

@ -1,163 +0,0 @@
use crate::eval_state::{EvalState, EvalStateWeak};
use crate::value::Value;
use anyhow::Result;
use nix_bindings_expr_sys as raw;
use nix_bindings_util::check_call;
use nix_bindings_util_sys as raw_util;
use std::ffi::{c_int, c_void, CStr, CString};
use std::mem::ManuallyDrop;
use std::ptr::{null, null_mut};
/// A primop error that is not memoized in the thunk that triggered it,
/// allowing the thunk to be forced again.
///
/// Since [Nix 2.34](https://nix.dev/manual/nix/2.34/release-notes/rl-2.34.html#c-api-changes),
/// primop errors are memoized by default: once a thunk fails, forcing it
/// again returns the same error. Use `RecoverableError` for errors that
/// are transient, so the caller can retry.
///
/// On Nix < 2.34, all errors are already recoverable, so this type has
/// no additional effect.
///
/// Available since nix-bindings-expr 0.2.1.
#[derive(Debug)]
pub struct RecoverableError(String);
impl RecoverableError {
pub fn new(msg: impl Into<String>) -> Self {
RecoverableError(msg.into())
}
}
impl std::fmt::Display for RecoverableError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for RecoverableError {}
/// Metadata for a primop, used with `PrimOp::new`.
pub struct PrimOpMeta<'a, const N: usize> {
/// Name of the primop. Note that primops do not have to be registered as
/// builtins. Nonetheless, a name is required for documentation purposes, e.g.
/// :doc in the repl.
pub name: &'a CStr,
/// Documentation for the primop. This is displayed in the repl when using
/// :doc. The format is markdown.
pub doc: &'a CStr,
/// The number of arguments the function takes, as well as names for the
/// arguments, to be presented in the documentation (if applicable, e.g.
/// :doc in the repl).
pub args: [&'a CStr; N],
}
pub struct PrimOp {
pub(crate) ptr: *mut raw::PrimOp,
}
impl Drop for PrimOp {
fn drop(&mut self) {
unsafe {
raw::gc_decref(null_mut(), self.ptr as *mut c_void);
}
}
}
impl PrimOp {
/// Create a new primop with the given metadata and implementation.
///
/// When `f` returns an `Err`, the error is propagated to the Nix evaluator.
/// To return a [recoverable error](RecoverableError), include it in the
/// error chain (e.g. `Err(RecoverableError::new("...").into())`).
pub fn new<const N: usize>(
eval_state: &mut EvalState,
meta: PrimOpMeta<N>,
f: Box<dyn Fn(&mut EvalState, &[Value; N]) -> Result<Value>>,
) -> Result<PrimOp> {
assert!(N != 0);
let mut args = Vec::new();
for arg in meta.args {
args.push(arg.as_ptr());
}
args.push(null());
// Primops weren't meant to be dynamically created, as of writing.
// This leaks, and so do the primop fields in Nix internally.
let user_data = {
// We'll be leaking this Box.
// TODO: Use the GC with finalizer, if possible.
let user_data = ManuallyDrop::new(Box::new(PrimOpContext {
arity: N,
function: Box::new(move |eval_state, args| f(eval_state, args.try_into().unwrap())),
eval_state: eval_state.weak_ref(),
}));
user_data.as_ref() as *const PrimOpContext as *mut c_void
};
let op = unsafe {
check_call!(raw::alloc_primop(
&mut eval_state.context,
FUNCTION_ADAPTER,
N as c_int,
meta.name.as_ptr(),
args.as_mut_ptr(), /* TODO add an extra const to bindings to avoid mut here. */
meta.doc.as_ptr(),
user_data
))?
};
Ok(PrimOp { ptr: op })
}
}
/// The user_data for our Nix primops
struct PrimOpContext {
arity: usize,
function: Box<dyn Fn(&mut EvalState, &[Value]) -> Result<Value>>,
eval_state: EvalStateWeak,
}
unsafe extern "C" fn function_adapter(
user_data: *mut ::std::os::raw::c_void,
context_out: *mut raw_util::c_context,
_state: *mut raw::EvalState,
args: *mut *mut raw::Value,
ret: *mut raw::Value,
) {
let primop_info = (user_data as *const PrimOpContext).as_ref().unwrap();
let mut eval_state = primop_info.eval_state.upgrade().unwrap_or_else(|| {
panic!("Nix primop called after EvalState was dropped");
});
let args_raw_slice = unsafe { std::slice::from_raw_parts(args, primop_info.arity) };
let args_vec: Vec<Value> = args_raw_slice
.iter()
.map(|v| Value::new_borrowed(*v))
.collect();
let args_slice = args_vec.as_slice();
let r = primop_info.function.as_ref()(&mut eval_state, args_slice);
match r {
Ok(v) => unsafe {
raw::copy_value(context_out, ret, v.raw_ptr());
},
Err(e) => unsafe {
let err_code = error_code(&e);
let cstr = CString::new(e.to_string()).unwrap_or_else(|_e| {
CString::new("<rust nix-expr application error message contained null byte>")
.unwrap()
});
raw_util::set_err_msg(context_out, err_code, cstr.as_ptr());
},
}
}
fn error_code(e: &anyhow::Error) -> raw_util::err {
#[cfg(nix_at_least = "2.34.0pre")]
if e.downcast_ref::<RecoverableError>().is_some() {
return raw_util::err_NIX_ERR_RECOVERABLE;
}
raw_util::err_NIX_ERR_UNKNOWN
}
static FUNCTION_ADAPTER: raw::PrimOpFun = Some(function_adapter);

View file

@ -1,141 +0,0 @@
pub mod __private;
use nix_bindings_expr_sys as raw;
use nix_bindings_util::{check_call, context::Context};
use std::ptr::{null_mut, NonNull};
// TODO: test: cloning a thunk does not duplicate the evaluation.
pub type Int = i64;
/// The type discriminator of a [`Value`] that has successfully evaluated to at least [weak head normal form](https://nix.dev/manual/nix/latest/language/evaluation.html?highlight=WHNF#values).
///
/// Typically acquired with [`EvalState::value_type`][`crate::eval_state::EvalState::value_type`]
#[derive(Eq, PartialEq, Debug)]
pub enum ValueType {
/// A Nix [attribute set](https://nix.dev/manual/nix/stable/language/types.html#type-attrs)
AttrSet,
/// A Nix [boolean](https://nix.dev/manual/nix/stable/language/types.html#type-bool)
Bool,
/// A Nix external value (mostly-opaque value for plugins, linked applications)
External,
/// A Nix [float](https://nix.dev/manual/nix/stable/language/types.html#type-float)
Float,
/// A Nix [function](https://nix.dev/manual/nix/stable/language/types.html#type-function)
Function,
/// A Nix [integer](https://nix.dev/manual/nix/stable/language/types.html#type-int)
Int,
/// A Nix [list](https://nix.dev/manual/nix/stable/language/types.html#type-list)
List,
/// A Nix [`null`](https://nix.dev/manual/nix/stable/language/types.html#type-null)
Null,
/// A Nix [path value](https://nix.dev/manual/nix/stable/language/types.html#type-path)
Path,
/// A Nix [string](https://nix.dev/manual/nix/stable/language/types.html#type-string)
String,
/// An unknown value, presumably from a new, partially unsupported version of Nix
Unknown,
}
impl ValueType {
/// Convert a raw value type to a [`ValueType`].
///
/// Return [`None`] if the Value is still a thunk (i.e. not yet evaluated).
///
/// Return `Some(`[`ValueType::Unknown`]`)` if the value type is not recognized.
pub(crate) fn from_raw(raw: raw::ValueType) -> Option<ValueType> {
match raw {
raw::ValueType_NIX_TYPE_ATTRS => Some(ValueType::AttrSet),
raw::ValueType_NIX_TYPE_BOOL => Some(ValueType::Bool),
raw::ValueType_NIX_TYPE_EXTERNAL => Some(ValueType::External),
raw::ValueType_NIX_TYPE_FLOAT => Some(ValueType::Float),
raw::ValueType_NIX_TYPE_FUNCTION => Some(ValueType::Function),
raw::ValueType_NIX_TYPE_INT => Some(ValueType::Int),
raw::ValueType_NIX_TYPE_LIST => Some(ValueType::List),
raw::ValueType_NIX_TYPE_NULL => Some(ValueType::Null),
raw::ValueType_NIX_TYPE_PATH => Some(ValueType::Path),
raw::ValueType_NIX_TYPE_STRING => Some(ValueType::String),
raw::ValueType_NIX_TYPE_THUNK => None,
// This would happen if a new type of value is added in Nix.
_ => Some(ValueType::Unknown),
}
}
}
/// A pointer to a [value](https://nix.dev/manual/nix/latest/language/types.html) or [thunk](https://nix.dev/manual/nix/2.31/language/evaluation.html?highlight=thunk#laziness), to be used with [`EvalState`][`crate::eval_state::EvalState`] methods.
///
/// # Shared Evaluation State
///
/// Multiple `Value` instances can reference the same underlying Nix value.
/// This occurs when a `Value` is [cloned](Clone), or when multiple Nix
/// expressions reference the same binding.
///
/// When any reference to a thunk is evaluated—whether through
/// [`force`](crate::eval_state::EvalState::force), other `EvalState` methods,
/// or indirectly as a consequence of evaluating something else—all references
/// observe the evaluated result. This means
/// [`value_type_unforced`](crate::eval_state::EvalState::value_type_unforced)
/// can return `None` (thunk) initially but a specific type later, even without
/// directly operating on that `Value`. The state will not regress back to a
/// less determined state.
pub struct Value {
inner: NonNull<raw::Value>,
}
impl Value {
/// Take ownership of a new [`Value`].
///
/// This does not call [`nix_bindings_util_sys::gc_incref`], but does call [`nix_bindings_util_sys::gc_decref`] when [dropped][`Drop`].
///
/// # Safety
///
/// The caller must ensure that the provided `inner` has a positive reference count, and that `inner` is not used after the returned `Value` is dropped.
pub(crate) unsafe fn new(inner: *mut raw::Value) -> Self {
Value {
inner: NonNull::new(inner).unwrap(),
}
}
/// Borrow a reference to a [`Value`].
///
/// This calls [`nix_bindings_util_sys::value_incref`], and the returned Value will call [`nix_bindings_util_sys::value_decref`] when dropped.
///
/// # Safety
///
/// The caller must ensure that the provided `inner` has a positive reference count.
pub(crate) unsafe fn new_borrowed(inner: *mut raw::Value) -> Self {
let v = Value::new(inner);
unsafe { raw::value_incref(null_mut(), inner) };
v
}
/// # Safety
///
/// The caller must ensure that the returned pointer is not used after the `Value` is dropped.
pub(crate) unsafe fn raw_ptr(&self) -> *mut raw::Value {
self.inner.as_ptr()
}
}
impl Drop for Value {
fn drop(&mut self) {
unsafe {
// ignoring error because the only failure mode is leaking memory
raw::value_decref(null_mut(), self.inner.as_ptr());
}
}
}
impl Clone for Value {
fn clone(&self) -> Self {
// TODO: Is it worth allocating a new Context here? Ideally cloning is cheap.
// this is very unlikely to error, and it is not recoverable
// Maybe try without, and try again with context to report details?
unsafe {
check_call!(raw::value_incref(&mut Context::new(), self.inner.as_ptr())).unwrap();
}
// can't return an error here, but we don't want to ignore the error either as it means we could use-after-free
Value { inner: self.inner }
}
}
// Tested in eval_state.rs

View file

@ -1,26 +0,0 @@
//! Functions that are relevant for other bindings modules, but normally not end users.
use super::Value;
use nix_bindings_expr_sys as raw;
/// Take ownership of a new [`Value`].
///
/// This does not call `nix_gc_incref`, but does call `nix_gc_decref` when dropped.
///
/// # Safety
///
/// The caller must ensure that the provided `ptr` has a positive reference count,
/// and that `ptr` is not used after the returned `Value` is dropped.
pub unsafe fn raw_value_new(ptr: *mut raw::Value) -> Value {
Value::new(ptr)
}
/// Borrow a reference to a [`Value`].
///
/// This calls `value_incref`, and the returned Value will call `value_decref` when dropped.
///
/// # Safety
///
/// The caller must ensure that the provided `ptr` has a positive reference count.
pub unsafe fn raw_value_new_borrowed(ptr: *mut raw::Value) -> Value {
Value::new_borrowed(ptr)
}

View file

@ -1,20 +0,0 @@
[package]
name = "nix-bindings-fetchers-sys"
version = "0.2.1"
edition = "2021"
build = "build.rs"
license = "LGPL-2.1"
description = "Low-level FFI bindings to the nix-fetchers library"
repository = "https://github.com/nixops4/nix-bindings-rust"
documentation = "https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_fetchers_sys/"
readme = "README.md"
[lib]
path = "src/lib.rs"
[dependencies]
nix-bindings-util-sys = { path = "../nix-bindings-util-sys", version = "0.2.1" }
[build-dependencies]
bindgen = "0.69"
pkg-config = "0.3"

View file

@ -1,11 +0,0 @@
# nix-bindings-fetchers-sys
This crate contains generated bindings for the Nix C API (`nix-fetchers-c`).
**You should not have to use this crate directly,** and so you should probably not add it to your dependencies.
Instead, use the `nix-bindings-fetchers` crate, which _should_ be sufficient.
[API Documentation](https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_fetchers_sys/)
## Changelog
See the [nix-bindings-rust changelog](https://github.com/nixops4/nix-bindings-rust/blob/main/CHANGELOG.md).

View file

@ -1,40 +0,0 @@
use std::path::PathBuf;
#[derive(Debug)]
struct StripNixPrefix;
impl bindgen::callbacks::ParseCallbacks for StripNixPrefix {
fn item_name(&self, name: &str) -> Option<String> {
name.strip_prefix("nix_").map(String::from)
}
}
fn main() {
println!("cargo:rerun-if-changed=include/nix-c-fetchers.h");
println!("cargo:rustc-link-lib=nixfetchersc");
let mut args = Vec::new();
for path in pkg_config::probe_library("nix-fetchers-c")
.unwrap()
.include_paths
.iter()
{
args.push(format!("-I{}", path.to_str().unwrap()));
}
let out_path = PathBuf::from(std::env::var("OUT_DIR").unwrap());
let bindings = bindgen::Builder::default()
.header("include/nix-c-fetchers.h")
.clang_args(args)
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.parse_callbacks(Box::new(StripNixPrefix))
// Blocklist symbols from nix-bindings-util-sys
.blocklist_file(".*nix_api_util\\.h")
.generate()
.expect("Unable to generate bindings");
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}

View file

@ -1 +0,0 @@
#include <nix_api_fetchers.h>

View file

@ -1,33 +0,0 @@
//! Raw bindings to Nix C API
//!
//! This crate contains automatically generated bindings from the Nix C headers.
//! The bindings are generated by bindgen and include C-style naming conventions
//! and documentation comments that don't always conform to Rust standards.
//!
//! Normally you don't have to use this crate directly.
//! Instead use `nix-fetchers`.
// This file must only contain generated code, so that the module-level
// #![allow(...)] attributes don't suppress warnings in hand-written code.
// If you need to add hand-written code, use a submodule to isolate the
// generated code. See:
// https://github.com/nixops4/nixops4/pull/138/commits/330c3881be3d3cf3e59adebbe0ab1c0f15f6d2c9
// Standard bindgen suppressions for C naming conventions
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
// Clippy suppressions for generated C bindings
// bindgen doesn't generate safety docs
#![allow(clippy::missing_safety_doc)]
// Rustdoc suppressions for generated C documentation
// The C headers contain Doxygen-style documentation that doesn't translate
// well to Rust's rustdoc format, causing various warnings:
#![allow(rustdoc::broken_intra_doc_links)] // @param[in]/[out] references don't resolve
#![allow(rustdoc::bare_urls)] // C docs may contain unescaped URLs
#![allow(rustdoc::invalid_html_tags)] // Doxygen HTML tags like <setting>
#![allow(rustdoc::invalid_codeblock_attributes)] // C code examples may use unsupported attributes
use nix_bindings_util_sys::*;
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));

View file

@ -1,30 +0,0 @@
[package]
name = "nix-bindings-fetchers"
version = "0.2.1"
edition = "2021"
license = "LGPL-2.1"
description = "Rust bindings to Nix fetchers"
repository = "https://github.com/nixops4/nix-bindings-rust"
documentation = "https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_fetchers/"
readme = "README.md"
[lib]
path = "src/lib.rs"
[dependencies]
anyhow = "1.0"
nix-bindings-store = { path = "../nix-bindings-store", version = "0.2.1" }
nix-bindings-util = { path = "../nix-bindings-util", version = "0.2.1" }
nix-bindings-fetchers-sys = { path = "../nix-bindings-fetchers-sys", version = "0.2.1" }
ctor = "0.2"
tempfile = "3.10"
cstr = "0.2"
[lints.rust]
warnings = "deny"
dead-code = "allow"
[lints.clippy]
type-complexity = "allow"
# We're still trying to make Nix more thread-safe, want forward-compat
arc-with-non-send-sync = "allow"

View file

@ -1,9 +0,0 @@
# nix-bindings-fetchers
Rust bindings to the nix-fetchers library.
[API Documentation](https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_fetchers/)
## Changelog
See the [nix-bindings-rust changelog](https://github.com/nixops4/nix-bindings-rust/blob/main/CHANGELOG.md).

View file

@ -1,38 +0,0 @@
use anyhow::{Context as _, Result};
use nix_bindings_fetchers_sys as raw;
use nix_bindings_util::context::{self, Context};
use std::ptr::NonNull;
pub struct FetchersSettings {
pub(crate) ptr: NonNull<raw::fetchers_settings>,
}
impl Drop for FetchersSettings {
fn drop(&mut self) {
unsafe {
raw::fetchers_settings_free(self.ptr.as_ptr());
}
}
}
impl FetchersSettings {
pub fn new() -> Result<Self> {
let mut ctx = Context::new();
let ptr = unsafe { context::check_call!(raw::fetchers_settings_new(&mut ctx))? };
Ok(FetchersSettings {
ptr: NonNull::new(ptr).context("fetchers_settings_new unexpectedly returned null")?,
})
}
pub fn raw_ptr(&self) -> *mut raw::fetchers_settings {
self.ptr.as_ptr()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fetchers_settings_new() {
let _ = FetchersSettings::new().unwrap();
}
}

View file

@ -1,24 +0,0 @@
[package]
name = "nix-bindings-flake-sys"
version = "0.2.1"
edition = "2021"
build = "build.rs"
license = "LGPL-2.1"
description = "Low-level FFI bindings to Nix flakes"
repository = "https://github.com/nixops4/nix-bindings-rust"
documentation = "https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_flake_sys/"
readme = "README.md"
[lib]
path = "src/lib.rs"
[dependencies]
nix-bindings-util-sys = { path = "../nix-bindings-util-sys", version = "0.2.1" }
nix-bindings-store-sys = { path = "../nix-bindings-store-sys", version = "0.2.1" }
nix-bindings-expr-sys = { path = "../nix-bindings-expr-sys", version = "0.2.1" }
nix-bindings-fetchers-sys = { path = "../nix-bindings-fetchers-sys", version = "0.2.1" }
nix-bindings-bdwgc-sys = { path = "../nix-bindings-bdwgc-sys", version = "0.2.1" }
[build-dependencies]
bindgen = "0.69"
pkg-config = "0.3"

View file

@ -1,11 +0,0 @@
# nix-bindings-flake-sys
This crate contains generated bindings for the Nix C API (`nix-flake-c`).
**You should not have to use this crate directly,** and so you should probably not add it to your dependencies.
Instead, use the `nix-bindings-flake` crate, which _should_ be sufficient.
[API Documentation](https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_flake_sys/)
## Changelog
See the [nix-bindings-rust changelog](https://github.com/nixops4/nix-bindings-rust/blob/main/CHANGELOG.md).

View file

@ -1,56 +0,0 @@
use std::path::PathBuf;
#[derive(Debug)]
struct StripNixPrefix;
impl bindgen::callbacks::ParseCallbacks for StripNixPrefix {
fn item_name(&self, name: &str) -> Option<String> {
name.strip_prefix("nix_").map(String::from)
}
}
fn main() {
println!("cargo:rerun-if-changed=include/nix-c-flake.h");
println!("cargo:rustc-link-lib=nixflakec");
let mut args = Vec::new();
for path in pkg_config::probe_library("nix-flake-c")
.unwrap()
.include_paths
.iter()
{
args.push(format!("-I{}", path.to_str().unwrap()));
}
for path in pkg_config::probe_library("bdw-gc")
.unwrap()
.include_paths
.iter()
{
args.push(format!("-I{}", path.to_str().unwrap()));
}
let out_path = PathBuf::from(std::env::var("OUT_DIR").unwrap());
let bindings = bindgen::Builder::default()
.header("include/nix-c-flake.h")
.clang_args(args)
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.parse_callbacks(Box::new(StripNixPrefix))
// Blocklist symbols from nix-bindings-util-sys
.blocklist_file(".*nix_api_util\\.h")
// Blocklist symbols from nix-bindings-store-sys
.blocklist_file(".*nix_api_store\\.h")
// Blocklist symbols from nix-bindings-expr-sys
.blocklist_file(".*nix_api_expr\\.h")
.blocklist_file(".*nix_api_value\\.h")
// Blocklist symbols from nix-bindings-fetchers-sys
.blocklist_file(".*nix_api_fetchers\\.h")
// Blocklist symbols from nix-bindings-bdwgc-sys
.blocklist_file(".*/gc\\.h")
.generate()
.expect("Unable to generate bindings");
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}

View file

@ -1,3 +0,0 @@
#define GC_THREADS
#include <gc/gc.h>
#include <nix_api_flake.h>

View file

@ -1,35 +0,0 @@
//! Raw bindings to Nix C API
//!
//! This crate contains automatically generated bindings from the Nix C headers.
//! The bindings are generated by bindgen and include C-style naming conventions
//! and documentation comments that don't always conform to Rust standards.
//!
//! Normally you don't have to use this crate directly.
//! Instead use `nix-flake`.
// This file must only contain generated code, so that the module-level
// #![allow(...)] attributes don't suppress warnings in hand-written code.
// If you need to add hand-written code, use a submodule to isolate the
// generated code. See:
// https://github.com/nixops4/nixops4/pull/138/commits/330c3881be3d3cf3e59adebbe0ab1c0f15f6d2c9
// Standard bindgen suppressions for C naming conventions
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
// Clippy suppressions for generated C bindings
// bindgen doesn't generate safety docs
#![allow(clippy::missing_safety_doc)]
// Rustdoc suppressions for generated C documentation
// The C headers contain Doxygen-style documentation that doesn't translate
// well to Rust's rustdoc format, causing various warnings:
#![allow(rustdoc::broken_intra_doc_links)] // @param[in]/[out] references don't resolve
#![allow(rustdoc::bare_urls)] // C docs may contain unescaped URLs
#![allow(rustdoc::invalid_html_tags)] // Doxygen HTML tags like <setting>
#![allow(rustdoc::invalid_codeblock_attributes)] // C code examples may use unsupported attributes
use nix_bindings_expr_sys::*;
use nix_bindings_fetchers_sys::*;
use nix_bindings_util_sys::*;
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));

View file

@ -1,32 +0,0 @@
[package]
name = "nix-bindings-flake"
version = "0.2.1"
edition = "2021"
license = "LGPL-2.1"
description = "Rust bindings to Nix flakes"
repository = "https://github.com/nixops4/nix-bindings-rust"
documentation = "https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_flake/"
readme = "README.md"
[lib]
path = "src/lib.rs"
[dependencies]
anyhow = "1.0"
nix-bindings-expr = { path = "../nix-bindings-expr", version = "0.2.1" }
nix-bindings-fetchers = { path = "../nix-bindings-fetchers", version = "0.2.1" }
nix-bindings-store = { path = "../nix-bindings-store", version = "0.2.1" }
nix-bindings-util = { path = "../nix-bindings-util", version = "0.2.1" }
nix-bindings-flake-sys = { path = "../nix-bindings-flake-sys", version = "0.2.1" }
ctor = "0.2"
tempfile = "3.10"
cstr = "0.2"
[lints.rust]
warnings = "deny"
dead-code = "allow"
[lints.clippy]
type-complexity = "allow"
# We're still trying to make Nix more thread-safe, want forward-compat
arc-with-non-send-sync = "allow"

View file

@ -1,9 +0,0 @@
# nix-bindings-flake
Rust bindings to Nix flakes.
[API Documentation](https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_flake/)
## Changelog
See the [nix-bindings-rust changelog](https://github.com/nixops4/nix-bindings-rust/blob/main/CHANGELOG.md).

View file

@ -1,21 +0,0 @@
[package]
name = "nix-bindings-store-sys"
version = "0.2.1"
edition = "2021"
build = "build.rs"
license = "LGPL-2.1"
description = "Low-level FFI bindings to the Nix store library"
repository = "https://github.com/nixops4/nix-bindings-rust"
documentation = "https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_store_sys/"
readme = "README.md"
[lib]
path = "src/lib.rs"
[dependencies]
nix-bindings-util-sys = { path = "../nix-bindings-util-sys", version = "0.2.1" }
zerocopy = { version = "0.8", features = ["derive"] }
[build-dependencies]
bindgen = "0.69"
pkg-config = "0.3"

View file

@ -1,11 +0,0 @@
# nix-bindings-store-sys
This crate contains generated bindings for the Nix C API (`nix-store-c`).
**You should not have to use this crate directly,** and so you should probably not add it to your dependencies.
Instead, use the `nix-bindings-store` crate, which _should_ be sufficient.
[API Documentation](https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_store_sys/)
## Changelog
See the [nix-bindings-rust changelog](https://github.com/nixops4/nix-bindings-rust/blob/main/CHANGELOG.md).

View file

@ -1,57 +0,0 @@
use std::path::PathBuf;
#[derive(Debug)]
struct StripNixPrefix;
impl bindgen::callbacks::ParseCallbacks for StripNixPrefix {
fn item_name(&self, name: &str) -> Option<String> {
name.strip_prefix("nix_").map(String::from)
}
}
#[derive(Debug)]
struct AddZerocopyDerives {}
impl bindgen::callbacks::ParseCallbacks for AddZerocopyDerives {
fn add_derives(&self, info: &bindgen::callbacks::DeriveInfo<'_>) -> Vec<String> {
if info.name == "store_path_hash_part" {
vec![
"zerocopy::FromBytes".to_string(),
"zerocopy::IntoBytes".to_string(),
"zerocopy::Immutable".to_string(),
]
} else {
vec![]
}
}
}
fn main() {
println!("cargo:rerun-if-changed=include/nix-c-store.h");
println!("cargo:rustc-link-lib=nixstorec");
let mut args = Vec::new();
for path in pkg_config::probe_library("nix-store-c")
.unwrap()
.include_paths
.iter()
{
args.push(format!("-I{}", path.to_str().unwrap()));
}
let out_path = PathBuf::from(std::env::var("OUT_DIR").unwrap());
let bindings = bindgen::Builder::default()
.header("include/nix-c-store.h")
.clang_args(args)
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.parse_callbacks(Box::new(StripNixPrefix))
.parse_callbacks(Box::new(AddZerocopyDerives {}))
// Blocklist symbols from nix-bindings-util-sys
.blocklist_file(".*nix_api_util\\.h")
.generate()
.expect("Unable to generate bindings");
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}

View file

@ -1 +0,0 @@
#include <nix_api_store.h>

View file

@ -1,33 +0,0 @@
//! Raw bindings to Nix C API
//!
//! This crate contains automatically generated bindings from the Nix C headers.
//! The bindings are generated by bindgen and include C-style naming conventions
//! and documentation comments that don't always conform to Rust standards.
//!
//! Normally you don't have to use this crate directly.
//! Instead use `nix-store`.
// This file must only contain generated code, so that the module-level
// #![allow(...)] attributes don't suppress warnings in hand-written code.
// If you need to add hand-written code, use a submodule to isolate the
// generated code. See:
// https://github.com/nixops4/nixops4/pull/138/commits/330c3881be3d3cf3e59adebbe0ab1c0f15f6d2c9
// Standard bindgen suppressions for C naming conventions
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
// Clippy suppressions for generated C bindings
// bindgen doesn't generate safety docs
#![allow(clippy::missing_safety_doc)]
// Rustdoc suppressions for generated C documentation
// The C headers contain Doxygen-style documentation that doesn't translate
// well to Rust's rustdoc format, causing various warnings:
#![allow(rustdoc::broken_intra_doc_links)] // @param[in]/[out] references don't resolve
#![allow(rustdoc::bare_urls)] // C docs may contain unescaped URLs
#![allow(rustdoc::invalid_html_tags)] // Doxygen HTML tags like <setting>
#![allow(rustdoc::invalid_codeblock_attributes)] // C code examples may use unsupported attributes
use nix_bindings_util_sys::*;
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));

View file

@ -1,45 +0,0 @@
[package]
name = "nix-bindings-store"
version = "0.2.1"
edition = "2021"
build = "build.rs"
license = "LGPL-2.1"
description = "Rust bindings to Nix store library"
repository = "https://github.com/nixops4/nix-bindings-rust"
documentation = "https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_store/"
readme = "README.md"
[lib]
path = "src/lib.rs"
[dependencies]
anyhow = "1.0"
nix-bindings-util = { path = "../nix-bindings-util", version = "0.2.1" }
nix-bindings-util-sys = { path = "../nix-bindings-util-sys", version = "0.2.1" }
nix-bindings-store-sys = { path = "../nix-bindings-store-sys", version = "0.2.1" }
zerocopy = "0.8"
harmonia-store-core = { version = "0.0.0-alpha.0", optional = true }
serde_json = { version = "1.0", optional = true }
[dev-dependencies]
ctor = "0.2"
hex-literal = "0.4"
tempfile = "3.10"
serde_json = "1.0"
[build-dependencies]
pkg-config = "0.3"
# Needed for version parsing in build.rs
nix-bindings-util = { path = "../nix-bindings-util", version = "0.2.1" }
[features]
harmonia = [ "dep:harmonia-store-core", "dep:serde_json" ]
[lints.rust]
warnings = "deny"
dead-code = "allow"
[lints.clippy]
type-complexity = "allow"
# We're still trying to make Nix more thread-safe, want forward-compat
arc-with-non-send-sync = "allow"

View file

@ -1,9 +0,0 @@
# nix-bindings-store
Rust bindings to the Nix store library.
[API Documentation](https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_store/)
## Changelog
See the [nix-bindings-rust changelog](https://github.com/nixops4/nix-bindings-rust/blob/main/CHANGELOG.md).

View file

@ -1,6 +0,0 @@
use nix_bindings_util::nix_version::emit_version_cfg;
fn main() {
let nix_version = pkg_config::probe_library("nix-store-c").unwrap().version;
emit_version_cfg(&nix_version, &["2.26", "2.33.0pre", "2.33"]);
}

View file

@ -1,100 +0,0 @@
use anyhow::Context as _;
use super::Derivation;
impl Derivation {
/// Convert harmonia Derivation to nix-bindings Derivation.
///
/// This requires a Store instance because the Nix C API needs it for internal validation.
pub fn from_harmonia(
store: &mut crate::store::Store,
harmonia_drv: &harmonia_store_core::derivation::Derivation,
) -> anyhow::Result<Self> {
let json = serde_json::to_string(harmonia_drv)
.context("Failed to serialize harmonia Derivation to JSON")?;
store.derivation_from_json(&json)
}
}
impl TryFrom<&Derivation> for harmonia_store_core::derivation::Derivation {
type Error = anyhow::Error;
fn try_from(nix_drv: &Derivation) -> anyhow::Result<Self> {
let json = nix_drv
.to_json_string()
.context("Failed to convert nix Derivation to JSON")?;
serde_json::from_str(&json).context("Failed to parse JSON as harmonia Derivation")
}
}
#[cfg(test)]
mod tests {
use super::*;
fn create_harmonia_derivation() -> harmonia_store_core::derivation::Derivation {
use harmonia_store_core::derivation::{Derivation, DerivationOutput};
use harmonia_store_core::derived_path::OutputName;
use harmonia_store_core::store_path::StorePath;
use std::collections::{BTreeMap, BTreeSet};
use std::str::FromStr;
let system = format!("{}-{}", std::env::consts::ARCH, std::env::consts::OS);
let out_path = "8bs8sd27bzzy6w94fznjd2j8ldmdg7x6-myname";
let env = BTreeMap::from([
("builder".into(), "/bin/sh".into()),
("name".into(), "myname".into()),
("out".into(), format!("/{out_path}").into()),
("system".into(), system.clone().into()),
]);
let mut outputs = BTreeMap::new();
outputs.insert(
OutputName::from_str("out").unwrap(),
DerivationOutput::InputAddressed(StorePath::from_base_path(out_path).unwrap()),
);
Derivation {
args: vec!["-c".into(), "echo $name foo > $out".into()],
builder: "/bin/sh".into(),
env,
inputs: BTreeSet::new(),
name: b"myname".as_slice().try_into().unwrap(),
outputs,
platform: system.into(),
structured_attrs: None,
}
}
#[test]
fn derivation_round_trip_harmonia() {
let mut store = crate::store::Store::open(Some("dummy://"), []).unwrap();
let harmonia_drv = create_harmonia_derivation();
// Convert to nix-bindings Derivation
let nix_drv = Derivation::from_harmonia(&mut store, &harmonia_drv).unwrap();
// Convert back to harmonia Derivation
let harmonia_round_trip: harmonia_store_core::derivation::Derivation =
(&nix_drv).try_into().unwrap();
assert_eq!(harmonia_drv, harmonia_round_trip);
}
#[test]
fn derivation_clone() {
let mut store = crate::store::Store::open(Some("dummy://"), []).unwrap();
let harmonia_drv = create_harmonia_derivation();
let derivation = Derivation::from_harmonia(&mut store, &harmonia_drv).unwrap();
let cloned_derivation = derivation.clone();
let original_harmonia: harmonia_store_core::derivation::Derivation =
(&derivation).try_into().unwrap();
let cloned_harmonia: harmonia_store_core::derivation::Derivation =
(&cloned_derivation).try_into().unwrap();
assert_eq!(original_harmonia, cloned_harmonia);
}
}

View file

@ -1,92 +0,0 @@
#![cfg(nix_at_least = "2.33.0pre")]
use nix_bindings_store_sys as raw;
#[cfg(nix_at_least = "2.33")]
use nix_bindings_util::{
check_call,
context::Context,
result_string_init,
string_return::{callback_get_result_string, callback_get_result_string_data},
};
use std::ptr::NonNull;
/// A Nix derivation
///
/// **Requires Nix 2.33 or later.**
pub struct Derivation {
pub(crate) inner: NonNull<raw::derivation>,
}
impl Derivation {
pub(crate) fn new_raw(inner: NonNull<raw::derivation>) -> Self {
Derivation { inner }
}
/// Convert the derivation to JSON (which is encoded to a string).
///
/// **Requires Nix 2.33 or later.**
///
/// The JSON format follows the [Nix derivation JSON schema](https://nix.dev/manual/nix/latest/protocols/json/derivation.html).
/// Note that this format is experimental as of writing.
#[cfg(nix_at_least = "2.33")]
pub fn to_json_string(&self) -> anyhow::Result<String> {
let mut ctx = Context::new();
unsafe {
let mut r = result_string_init!();
check_call!(raw::derivation_to_json(
&mut ctx,
self.inner.as_ptr(),
Some(callback_get_result_string),
callback_get_result_string_data(&mut r)
))?;
r
}
}
/// This is a low level function that you shouldn't have to call unless you are developing the Nix bindings.
///
/// Construct a new `Derivation` by first cloning the C derivation.
///
/// # Safety
///
/// This does not take ownership of the C derivation, so it should be a borrowed pointer, or you should free it.
pub unsafe fn new_raw_clone(inner: NonNull<raw::derivation>) -> Self {
Self::new_raw(
NonNull::new(raw::derivation_clone(inner.as_ptr()))
.or_else(|| panic!("nix_derivation_clone returned a null pointer"))
.unwrap(),
)
}
/// This is a low level function that you shouldn't have to call unless you are developing the Nix bindings.
///
/// Get a pointer to the underlying Nix C API derivation.
///
/// # Safety
///
/// This function is unsafe because it returns a raw pointer. The caller must ensure that the pointer is not used beyond the lifetime of this `Derivation`.
pub unsafe fn as_ptr(&self) -> *mut raw::derivation {
self.inner.as_ptr()
}
}
impl Clone for Derivation {
fn clone(&self) -> Self {
unsafe { Self::new_raw_clone(self.inner) }
}
}
impl Drop for Derivation {
fn drop(&mut self) {
unsafe {
raw::derivation_free(self.inner.as_ptr());
}
}
}
#[cfg(feature = "harmonia")]
mod harmonia;
#[cfg(test)]
mod tests {}

View file

@ -1,3 +0,0 @@
pub mod derivation;
pub mod path;
pub mod store;

View file

@ -1,65 +0,0 @@
use anyhow::{Context as _, Result};
use super::{StorePath, STORE_PATH_HASH_SIZE};
impl TryFrom<&harmonia_store_core::store_path::StorePath> for StorePath {
type Error = anyhow::Error;
fn try_from(harmonia_path: &harmonia_store_core::store_path::StorePath) -> Result<Self> {
let hash: &[u8; STORE_PATH_HASH_SIZE] = harmonia_path.hash().as_ref();
StorePath::from_parts(hash, harmonia_path.name().as_ref())
}
}
impl TryFrom<&StorePath> for harmonia_store_core::store_path::StorePath {
type Error = anyhow::Error;
fn try_from(nix_path: &StorePath) -> Result<Self> {
let hash = nix_path
.hash()
.context("Failed to get hash from nix StorePath")?;
let harmonia_hash = harmonia_store_core::store_path::StorePathHash::new(hash);
let name = nix_path
.name()
.context("Failed to get name from nix StorePath")?;
let harmonia_name: harmonia_store_core::store_path::StorePathName = name
.parse()
.context("Failed to parse name as StorePathName")?;
Ok(harmonia_store_core::store_path::StorePath::from((
harmonia_hash,
harmonia_name,
)))
}
}
#[cfg(test)]
mod tests {
#[test]
fn store_path_round_trip_harmonia() {
let harmonia_path: harmonia_store_core::store_path::StorePath =
"g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo.drv".parse().unwrap();
let nix_path: crate::path::StorePath = (&harmonia_path).try_into().unwrap();
let harmonia_round_trip: harmonia_store_core::store_path::StorePath =
(&nix_path).try_into().unwrap();
assert_eq!(harmonia_path, harmonia_round_trip);
}
#[test]
fn store_path_harmonia_clone() {
let harmonia_path: harmonia_store_core::store_path::StorePath =
"g1w7hy3qg1w7hy3qg1w7hy3qg1w7hy3q-foo.drv".parse().unwrap();
let nix_path: crate::path::StorePath = (&harmonia_path).try_into().unwrap();
let cloned_path = nix_path.clone();
assert_eq!(nix_path.name().unwrap(), cloned_path.name().unwrap());
assert_eq!(nix_path.hash().unwrap(), cloned_path.hash().unwrap());
}
}

View file

@ -1,160 +0,0 @@
use std::ptr::NonNull;
use anyhow::{Context as _, Result};
use nix_bindings_store_sys as raw;
#[cfg(nix_at_least = "2.33")]
use nix_bindings_util::{check_call, context::Context};
use nix_bindings_util::{
result_string_init,
string_return::{callback_get_result_string, callback_get_result_string_data},
};
/// The size of a store path hash in bytes (20 bytes, decoded from nix32).
pub const STORE_PATH_HASH_SIZE: usize = 20;
#[cfg(nix_at_least = "2.33")]
const _: () = assert!(std::mem::size_of::<raw::store_path_hash_part>() == STORE_PATH_HASH_SIZE);
pub struct StorePath {
raw: NonNull<raw::StorePath>,
}
impl StorePath {
/// Get the name of the store path.
///
/// For a store path like `/nix/store/abc1234...-foo-1.2`, this function will return `foo-1.2`.
pub fn name(&self) -> Result<String> {
unsafe {
let mut r = result_string_init!();
raw::store_path_name(
self.as_ptr(),
Some(callback_get_result_string),
callback_get_result_string_data(&mut r),
);
r
}
}
/// Get the hash part of the store path.
///
/// This returns the decoded hash (not the nix32-encoded string).
#[cfg(nix_at_least = "2.33")]
pub fn hash(&self) -> Result<[u8; STORE_PATH_HASH_SIZE]> {
let mut result = [0u8; STORE_PATH_HASH_SIZE];
let hash_part: &mut raw::store_path_hash_part = zerocopy::transmute_mut!(&mut result);
let mut ctx = Context::new();
unsafe {
check_call!(raw::store_path_hash(&mut ctx, self.as_ptr(), hash_part))?;
}
Ok(result)
}
/// Create a StorePath from hash and name components.
#[cfg(nix_at_least = "2.33")]
pub fn from_parts(hash: &[u8; STORE_PATH_HASH_SIZE], name: &str) -> Result<Self> {
let hash_part: &raw::store_path_hash_part = zerocopy::transmute_ref!(hash);
let mut ctx = Context::new();
let out_path = unsafe {
check_call!(raw::store_create_from_parts(
&mut ctx,
hash_part,
name.as_ptr() as *const i8,
name.len()
))?
};
NonNull::new(out_path)
.map(|ptr| unsafe { Self::new_raw(ptr) })
.context("store_create_from_parts returned null")
}
/// This is a low level function that you shouldn't have to call unless you are developing the Nix bindings.
///
/// Construct a new `StorePath` by first cloning the C store path.
///
/// # Safety
///
/// This does not take ownership of the C store path, so it should be a borrowed pointer, or you should free it.
pub unsafe fn new_raw_clone(raw: NonNull<raw::StorePath>) -> Self {
Self::new_raw(
NonNull::new(raw::store_path_clone(raw.as_ptr()))
.or_else(|| panic!("nix_store_path_clone returned a null pointer"))
.unwrap(),
)
}
/// This is a low level function that you shouldn't have to call unless you are developing the Nix bindings.
///
/// Takes ownership of a C `nix_store_path`. It will be freed when the `StorePath` is dropped.
///
/// # Safety
///
/// The caller must ensure that the provided `NonNull<raw::StorePath>` is valid and that the ownership
/// semantics are correctly followed. The `raw` pointer must not be used after being passed to this function.
pub unsafe fn new_raw(raw: NonNull<raw::StorePath>) -> Self {
StorePath { raw }
}
/// This is a low level function that you shouldn't have to call unless you are developing the Nix bindings.
///
/// Get a pointer to the underlying Nix C API store path.
///
/// # Safety
///
/// This function is unsafe because it returns a raw pointer. The caller must ensure that the pointer is not used beyond the lifetime of this `StorePath`.
pub unsafe fn as_ptr(&self) -> *mut raw::StorePath {
self.raw.as_ptr()
}
}
impl Clone for StorePath {
fn clone(&self) -> Self {
unsafe { Self::new_raw_clone(self.raw) }
}
}
impl Drop for StorePath {
fn drop(&mut self) {
unsafe {
raw::store_path_free(self.as_ptr());
}
}
}
#[cfg(all(feature = "harmonia", nix_at_least = "2.33"))]
mod harmonia;
#[cfg(test)]
mod tests {
use super::*;
use hex_literal::hex;
#[test]
#[cfg(nix_at_least = "2.26" /* get_storedir */)]
fn store_path_name() {
let mut store = crate::store::Store::open(Some("dummy://"), []).unwrap();
let store_dir = store.get_storedir().unwrap();
let store_path_string =
format!("{store_dir}/rdd4pnr4x9rqc9wgbibhngv217w2xvxl-bash-interactive-5.2p26");
let store_path = store.parse_store_path(store_path_string.as_str()).unwrap();
assert_eq!(store_path.name().unwrap(), "bash-interactive-5.2p26");
}
#[test]
#[cfg(nix_at_least = "2.33")]
fn store_path_round_trip() {
let original_hash: [u8; STORE_PATH_HASH_SIZE] =
hex!("0123456789abcdef0011223344556677deadbeef");
let original_name = "foo.drv";
let store_path = StorePath::from_parts(&original_hash, original_name).unwrap();
// Round trip gets back what we started with
assert_eq!(store_path.hash().unwrap(), original_hash);
assert_eq!(store_path.name().unwrap(), original_name);
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,19 +0,0 @@
[package]
name = "nix-bindings-util-sys"
version = "0.2.1"
edition = "2021"
build = "build.rs"
license = "LGPL-2.1"
description = "Low-level FFI bindings to Nix utility library"
repository = "https://github.com/nixops4/nix-bindings-rust"
documentation = "https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_util_sys/"
readme = "README.md"
[lib]
path = "src/lib.rs"
[dependencies]
[build-dependencies]
bindgen = "0.69"
pkg-config = "0.3"

View file

@ -1,11 +0,0 @@
# nix-bindings-util-sys
This crate contains generated bindings for the Nix C API (`nix-util-c`).
**You should not have to use this crate directly,** and so you should probably not add it to your dependencies.
Instead, use the `nix-bindings-util` crate, which _should_ be sufficient.
[API Documentation](https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_util_sys/)
## Changelog
See the [nix-bindings-rust changelog](https://github.com/nixops4/nix-bindings-rust/blob/main/CHANGELOG.md).

View file

@ -1,52 +0,0 @@
use std::env;
use std::path::PathBuf;
#[derive(Debug)]
struct StripNixPrefix {}
impl bindgen::callbacks::ParseCallbacks for StripNixPrefix {
fn item_name(&self, name: &str) -> Option<String> {
name.strip_prefix("nix_").map(String::from)
}
}
fn main() {
// Tell cargo to invalidate the built crate whenever the wrapper changes
println!("cargo:rerun-if-changed=include/nix-c-util.h");
println!("cargo:rustc-link-lib=nixutil");
// https://rust-lang.github.io/rust-bindgen/library-usage.html
let bindings = bindgen::Builder::default()
.header("include/nix-c-util.h")
// Find the includes
.clang_args(c_headers())
// Tell cargo to invalidate the built crate whenever any of the
// included header files changed.
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
.parse_callbacks(Box::new(StripNixPrefix {}))
// Finish the builder and generate the bindings.
.generate()
// Unwrap the Result and panic on failure.
.expect("Unable to generate bindings");
// Write the bindings to the $OUT_DIR/bindings.rs file.
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}
fn c_headers() -> Vec<String> {
let mut args = Vec::new();
// args.push("-isystem".to_string());
for path in pkg_config::probe_library("nix-util-c")
.unwrap()
.include_paths
.iter()
{
args.push(format!("-I{}", path.to_str().unwrap()));
}
// write to stderr for debugging
eprintln!("c_headers: {:?}", args);
args
}

View file

@ -1 +0,0 @@
#include <nix_api_util.h>

View file

@ -1,31 +0,0 @@
//! Raw bindings to Nix C API
//!
//! This crate contains automatically generated bindings from the Nix C headers.
//! The bindings are generated by bindgen and include C-style naming conventions
//! and documentation comments that don't always conform to Rust standards.
//!
//! Normally you don't have to use this crate directly.
//! Instead use `nix-util`.
// This file must only contain generated code, so that the module-level
// #![allow(...)] attributes don't suppress warnings in hand-written code.
// If you need to add hand-written code, use a submodule to isolate the
// generated code. See:
// https://github.com/nixops4/nixops4/pull/138/commits/330c3881be3d3cf3e59adebbe0ab1c0f15f6d2c9
// Standard bindgen suppressions for C naming conventions
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
// Clippy suppressions for generated C bindings
// bindgen doesn't generate safety docs
#![allow(clippy::missing_safety_doc)]
// Rustdoc suppressions for generated C documentation
// The C headers contain Doxygen-style documentation that doesn't translate
// well to Rust's rustdoc format, causing various warnings:
#![allow(rustdoc::broken_intra_doc_links)] // @param[in]/[out] references don't resolve
#![allow(rustdoc::bare_urls)] // C docs may contain unescaped URLs
#![allow(rustdoc::invalid_html_tags)] // Doxygen HTML tags like <setting>
#![allow(rustdoc::invalid_codeblock_attributes)] // C code examples may use unsupported attributes
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));

View file

@ -1,28 +0,0 @@
[package]
name = "nix-bindings-util"
version = "0.2.1"
edition = "2021"
license = "LGPL-2.1"
description = "Rust bindings to Nix utility library"
repository = "https://github.com/nixops4/nix-bindings-rust"
documentation = "https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_util/"
readme = "README.md"
[lib]
path = "src/lib.rs"
[dependencies]
anyhow = "1.0"
nix-bindings-util-sys = { path = "../nix-bindings-util-sys", version = "0.2.1" }
[dev-dependencies]
ctor = "0.2"
[lints.rust]
warnings = "deny"
dead-code = "allow"
[lints.clippy]
type-complexity = "allow"
# We're still trying to make Nix more thread-safe, want forward-compat
arc-with-non-send-sync = "allow"

View file

@ -1,9 +0,0 @@
# nix-bindings-util
Rust bindings to the Nix utility library.
[API Documentation](https://nixops4.github.io/nix-bindings-rust/development/nix_bindings_util/)
## Changelog
See the [nix-bindings-rust changelog](https://github.com/nixops4/nix-bindings-rust/blob/main/CHANGELOG.md).

View file

@ -1,159 +0,0 @@
use anyhow::{bail, Result};
use nix_bindings_util_sys as raw;
use std::ptr::null_mut;
use std::ptr::NonNull;
/// A context for error handling, when interacting directly with the generated bindings for the C API in [nix_bindings_util_sys].
///
/// The `nix-store` and `nix-expr` libraries that consume this type internally store a private context in their `EvalState` and `Store` structs to avoid allocating a new context for each operation. The state of a context is irrelevant when used correctly (e.g. with [check_call!]), so it's safe to reuse, and safe to allocate more contexts in methods such as [Clone::clone].
pub struct Context {
inner: NonNull<raw::c_context>,
}
impl Default for Context {
fn default() -> Self {
Self::new()
}
}
impl Context {
pub fn new() -> Self {
let ctx = unsafe { raw::c_context_create() };
if ctx.is_null() {
// We've failed to allocate a (relatively small) Context struct.
// We're almost certainly going to crash anyways.
panic!("nix_c_context_create returned a null pointer");
}
Context {
inner: NonNull::new(ctx).unwrap(),
}
}
/// Access the C context pointer.
///
/// We recommend to use `check_call!` if possible.
pub fn ptr(&mut self) -> *mut raw::c_context {
self.inner.as_ptr()
}
/// Check the error code and return an error if it's not `NIX_OK`.
///
/// We recommend to use `check_call!` if possible.
pub fn check_err(&self) -> Result<()> {
let err = unsafe { raw::err_code(self.inner.as_ptr()) };
if err != raw::err_NIX_OK {
// msgp is a borrowed pointer (pointing into the context), so we don't need to free it
let msgp = unsafe { raw::err_msg(null_mut(), self.inner.as_ptr(), null_mut()) };
// Turn the i8 pointer into a Rust string by copying
let msg: &str = unsafe { core::ffi::CStr::from_ptr(msgp).to_str()? };
bail!("{}", msg);
}
Ok(())
}
pub fn clear(&mut self) {
unsafe {
raw::set_err_msg(self.inner.as_ptr(), raw::err_NIX_OK, c"".as_ptr());
}
}
pub fn check_err_and_clear(&mut self) -> Result<()> {
let r = self.check_err();
if r.is_err() {
self.clear();
}
r
}
pub fn check_one_call_or_key_none<T, F: FnOnce(*mut raw::c_context) -> T>(
&mut self,
f: F,
) -> Result<Option<T>> {
let t = f(self.ptr());
if unsafe { raw::err_code(self.inner.as_ptr()) == raw::err_NIX_ERR_KEY } {
self.clear();
return Ok(None);
}
self.check_err_and_clear()?;
Ok(Some(t))
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe {
raw::c_context_free(self.inner.as_ptr());
}
}
}
#[macro_export]
macro_rules! check_call {
($($f:ident)::+($ctx:expr $(, $arg:expr)*)) => {
{
let ctx : &mut $crate::context::Context = $ctx;
let ret = $($f)::*(ctx.ptr() $(, $arg)*);
match ctx.check_err() {
Ok(_) => Ok(ret),
Err(e) => {
ctx.clear();
Err(e)
}
}
}
}
}
pub use check_call;
// TODO: Generalize this macro to work with any error code or any error handling logic
#[macro_export]
macro_rules! check_call_opt_key {
($($f:ident)::+($ctx:expr, $($arg:expr),*)) => {
{
let ctx : &mut $crate::context::Context = $ctx;
let ret = $($f)::*(ctx.ptr(), $($arg,)*);
if unsafe { $crate::raw_sys::err_code(ctx.ptr()) == $crate::raw_sys::err_NIX_ERR_KEY } {
ctx.clear();
return Ok(None);
}
match ctx.check_err() {
Ok(_) => Ok(Some(ret)),
Err(e) => {
ctx.clear();
Err(e)
}
}
}
}
}
pub use check_call_opt_key;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn context_new_and_drop() {
// don't crash
let _c = Context::new();
}
fn set_dummy_err(ctx_ptr: *mut raw::c_context) {
unsafe {
raw::set_err_msg(
ctx_ptr,
raw::err_NIX_ERR_UNKNOWN,
c"dummy error message".as_ptr(),
);
}
}
#[test]
fn check_call_dynamic_context() {
let r = check_call!(set_dummy_err(&mut Context::new()));
assert!(r.is_err());
assert_eq!(r.unwrap_err().to_string(), "dummy error message");
}
}

View file

@ -1,8 +0,0 @@
pub mod context;
pub mod settings;
#[macro_use]
pub mod string_return;
pub mod nix_version;
// Re-export for use in macros
pub use nix_bindings_util_sys as raw_sys;

View file

@ -1,101 +0,0 @@
//! Nix version parsing and conditional compilation support.
/// Emit [`cargo:rustc-cfg`] directives for Nix version-based conditional compilation.
///
/// Call from build.rs with the Nix version and desired version gates.
///
/// [`cargo:rustc-cfg`]: https://doc.rust-lang.org/cargo/reference/build-scripts.html#rustc-cfg
///
/// # Example
///
/// ```
/// use nix_bindings_util::nix_version::emit_version_cfg;
/// # // Stub pkg_config so that we can render a full usage example
/// # mod pkg_config { pub fn probe_library(_: &str) -> Result<Library, ()> { Ok(Library { version: "2.33.0pre".into() }) }
/// # pub struct Library { pub version: String } }
///
/// let nix_version = pkg_config::probe_library("nix-store-c").unwrap().version;
/// emit_version_cfg(&nix_version, &["2.26", "2.33.0pre", "2.33"]);
/// ```
///
/// Emits `nix_at_least="2.26"` and `nix_at_least="2.33.0pre"` for version 2.33.0pre,
/// usable as `#[cfg(nix_at_least = "2.26")]`.
pub fn emit_version_cfg(nix_version: &str, relevant_versions: &[&str]) {
// Declare the known versions for cargo check-cfg
let versions = relevant_versions
.iter()
.map(|v| format!("\"{}\"", v))
.collect::<Vec<_>>()
.join(",");
println!(
"cargo:rustc-check-cfg=cfg(nix_at_least,values({}))",
versions
);
let nix_version = parse_version(nix_version);
for version_str in relevant_versions {
let version = parse_version(version_str);
if nix_version >= version {
println!("cargo:rustc-cfg=nix_at_least=\"{}\"", version_str);
}
}
}
/// Parse a Nix version string into a comparable tuple `(major, minor, patch)`.
///
/// Pre-release versions (containing `"pre"`) get patch = -1, sorting before stable releases.
/// Omitted patch defaults to 0.
///
/// # Examples
///
/// ```
/// use nix_bindings_util::nix_version::parse_version;
///
/// assert_eq!(parse_version("2.26"), (2, 26, 0));
/// assert_eq!(parse_version("2.33.0pre"), (2, 33, -1));
/// assert_eq!(parse_version("2.33"), (2, 33, 0));
/// assert_eq!(parse_version("2.33.1"), (2, 33, 1));
///
/// // Pre-release versions sort before stable
/// assert!(parse_version("2.33.0pre") < parse_version("2.33"));
/// ```
pub fn parse_version(version_str: &str) -> (u32, u32, i32) {
let parts = version_str.split('.').collect::<Vec<&str>>();
let major = parts[0].parse::<u32>().unwrap();
let minor = parts[1].parse::<u32>().unwrap();
let patch = if parts.get(2).is_some_and(|s| s.contains("pre")) {
-1i32
} else {
parts
.get(2)
.and_then(|s| s.parse::<i32>().ok())
.unwrap_or(0)
};
(major, minor, patch)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_version() {
assert_eq!(parse_version("2.26"), (2, 26, 0));
assert_eq!(parse_version("2.33.0pre"), (2, 33, -1));
assert_eq!(parse_version("2.33"), (2, 33, 0));
assert_eq!(parse_version("2.33.1"), (2, 33, 1));
}
#[test]
fn test_version_ordering() {
// Pre-release versions should sort before stable
assert!(parse_version("2.33.0pre") < parse_version("2.33"));
assert!(parse_version("2.33.0pre") < parse_version("2.33.0"));
// Normal version ordering
assert!(parse_version("2.26") < parse_version("2.33"));
assert!(parse_version("2.33") < parse_version("2.33.1"));
}
}

View file

@ -1,104 +0,0 @@
use anyhow::Result;
use nix_bindings_util_sys as raw;
use std::sync::Mutex;
use crate::{
check_call, context, result_string_init,
string_return::{callback_get_result_string, callback_get_result_string_data},
};
// Global mutex to protect concurrent access to Nix settings
// See the documentation on `set()` for important thread safety information.
static SETTINGS_MUTEX: Mutex<()> = Mutex::new(());
/// Set a Nix setting.
///
/// # Thread Safety
///
/// This function uses a mutex to serialize access through the Rust API.
/// However, the underlying Nix settings system uses global mutable state
/// without internal synchronization.
///
/// The mutex provides protection between Rust callers but cannot prevent:
/// - C++ Nix code from modifying settings concurrently
/// - Other Nix operations from reading settings during modification
///
/// For multi-threaded applications, ensure that no other Nix operations
/// are running while changing settings. Settings are best modified during
/// single-threaded initialization.
pub fn set(key: &str, value: &str) -> Result<()> {
// Lock the mutex to ensure thread-safe access to global settings
let guard = SETTINGS_MUTEX.lock().unwrap();
let mut ctx = context::Context::new();
let key = std::ffi::CString::new(key)?;
let value = std::ffi::CString::new(value)?;
unsafe {
check_call!(raw::setting_set(&mut ctx, key.as_ptr(), value.as_ptr()))?;
}
drop(guard);
Ok(())
}
/// Get a Nix setting.
///
/// # Thread Safety
///
/// See the documentation on [`set()`] for important thread safety information.
pub fn get(key: &str) -> Result<String> {
// Lock the mutex to ensure thread-safe access to global settings
let guard = SETTINGS_MUTEX.lock().unwrap();
let mut ctx = context::Context::new();
let key = std::ffi::CString::new(key)?;
let mut r: Result<String> = result_string_init!();
unsafe {
check_call!(raw::setting_get(
&mut ctx,
key.as_ptr(),
Some(callback_get_result_string),
callback_get_result_string_data(&mut r)
))?;
}
drop(guard);
r
}
#[cfg(test)]
mod tests {
use crate::check_call;
use super::*;
#[ctor::ctor]
fn setup() {
let mut ctx = context::Context::new();
unsafe {
check_call!(nix_bindings_util_sys::libutil_init(&mut ctx)).unwrap();
}
}
#[test]
fn set_get() {
// Something that shouldn't matter if it's a different value temporarily
let key = "json-log-path";
// Save the old value, in case it's important. Probably not.
// If this doesn't work, pick a different setting to test with
let old_value = get(key).unwrap();
let new_value = "/just/a/path/that/we/are/storing/into/some/option/for/testing/purposes";
let res_e = (|| {
set(key, new_value)?;
get(key)
})();
// Restore immediately; try not to affect other tests (if relevant).
set(key, old_value.as_str()).unwrap();
let res = res_e.unwrap();
assert_eq!(res, new_value);
}
}

View file

@ -1,88 +0,0 @@
use anyhow::Result;
/// Callback for nix_store_get_uri and other functions that return a string.
///
/// This function is used by the other nix_* crates, and you should never need to call it yourself.
///
/// Some functions in the nix library "return" strings without giving you ownership over them, by letting you pass a callback function that gets to look at that string. This callback simply turns that string pointer into an owned rust String.
///
/// # Safety
///
/// _Manual memory management_
///
/// Only for passing to the nix C API. Do not call this function directly.
pub unsafe extern "C" fn callback_get_result_string(
start: *const ::std::os::raw::c_char,
n: std::os::raw::c_uint,
user_data: *mut std::os::raw::c_void,
) {
let ret = user_data as *mut Result<String>;
if start.is_null() {
if n != 0 {
panic!("callback_get_result_string: start is null but n is not zero");
}
*ret = Ok(String::new());
return;
}
let slice = std::slice::from_raw_parts(start as *const u8, n as usize);
if (*ret).is_ok() {
panic!(
"callback_get_result_string: Result must be initialized to Err. Did Nix call us twice?"
);
}
*ret = String::from_utf8(slice.to_vec())
.map_err(|e| anyhow::format_err!("Nix string is not valid UTF-8: {}", e));
}
pub fn callback_get_result_string_data(vec: &mut Result<String>) -> *mut std::os::raw::c_void {
vec as *mut Result<String> as *mut std::os::raw::c_void
}
#[macro_export]
macro_rules! result_string_init {
() => {
Err(anyhow::anyhow!("String was not set by Nix C API"))
};
}
#[cfg(test)]
mod tests {
use super::*;
use nix_bindings_util_sys as raw;
/// Typecheck the function signature against the generated bindings in nix_bindings_util_sys.
static _CALLBACK_GET_RESULT_STRING: raw::get_string_callback = Some(callback_get_result_string);
#[test]
fn test_callback_get_result_string_empty() {
let mut ret: Result<String> = result_string_init!();
let start: *const std::os::raw::c_char = std::ptr::null();
let n: std::os::raw::c_uint = 0;
let user_data: *mut std::os::raw::c_void = callback_get_result_string_data(&mut ret);
unsafe {
callback_get_result_string(start, n, user_data);
}
let s = ret.unwrap();
assert_eq!(s, "");
}
#[test]
fn test_callback_result_string() {
let mut ret: Result<String> = result_string_init!();
let start = b"helloGARBAGE".as_ptr() as *const std::os::raw::c_char;
let n: std::os::raw::c_uint = 5;
let user_data: *mut std::os::raw::c_void = callback_get_result_string_data(&mut ret);
unsafe {
callback_get_result_string(start, n, user_data);
}
let s = ret.unwrap();
assert_eq!(s, "hello");
}
}

38
nixide-sys/Cargo.toml Normal file
View file

@ -0,0 +1,38 @@
[package]
name = "nixide-sys"
description = "Unsafe direct FFI bindings to libnix C API"
version = "0.1.0"
readme = "../README.md"
license = "GPL-3.0"
repository = "https://codeberg.org/luminary/nixide"
authors = [
"_cry64 <them@dobutterfliescry.net>",
"foxxyora <foxxyora@noreply.codeberg.org>"
]
edition = "2024"
build = "build.rs"
[package.metadata.docs.rs]
targets = [ "x86_64-unknown-linux-gnu" ]
[lib]
path = "lib.rs"
[features]
default = ["util"]
expr = []
fetchers = []
flakes = []
store = []
util = []
gc = []
[build-dependencies]
bindgen = { default-features = false, features = [ "logging", "runtime" ], version = "0.72.1" }
doxygen-bindgen = "0.1.3"
pkg-config.workspace = true
cc.workspace = true
[dev-dependencies]
serial_test = "3.4.0"

74
nixide-sys/build.rs Normal file
View file

@ -0,0 +1,74 @@
use std::env;
use std::path::PathBuf;
use bindgen::callbacks::ParseCallbacks;
#[derive(Debug)]
struct DoxygenCallbacks;
impl ParseCallbacks for DoxygenCallbacks {
fn process_comment(&self, comment: &str) -> Option<String> {
match doxygen_bindgen::transform(comment) {
Ok(res) => Some(res),
Err(err) => {
println!("cargo:warning=Problem processing doxygen comment: {comment}\n{err}");
None
}
}
}
}
fn main() {
// Invalidate the built crate whenever the wrapper changes
println!("cargo:rerun-if-changed=include/wrapper.h");
// Use pkg-config to find nix-store include and link paths
// This NEEDS to be included, or otherwise `nix_api_store.h` cannot
// be found.
let libs = [
"nix-main-c",
"nix-expr-c",
"nix-store-c",
"nix-util-c",
"nix-flake-c",
];
let lib_args: Vec<String> = libs
.iter()
.map(|&name| {
let lib = pkg_config::probe_library(name)
.expect(&format!("Unable to find .pc file for {}", name));
for p in lib.link_files {
println!("cargo:rustc-link-lib={}", p.display());
}
lib.include_paths
.into_iter()
.map(|p| format!("-I{}", p.display()))
})
.flatten()
.collect();
let bindings = bindgen::Builder::default()
.clang_args(lib_args)
// The input header we would like to generate bindings for
.header("include/wrapper.h")
// Invalidate the built crate when an included header file changes
.parse_callbacks(Box::new(bindgen::CargoCallbacks::new()))
// Add `doxygen_bindgen` callbacks
.parse_callbacks(Box::new(DoxygenCallbacks))
// Format generated bindings with rustfmt
.formatter(bindgen::Formatter::Rustfmt)
.rustfmt_configuration_file(std::fs::canonicalize(".rustfmt.toml").ok())
// Finish the builder and generate the bindings
.generate()
// Unwrap the Result and panic on failure
.expect("Unable to generate bindings");
// Write the bindings to the $OUT_DIR/bindings.rs file
let out_path = PathBuf::from(env::var("OUT_DIR").unwrap());
bindings
.write_to_file(out_path.join("bindings.rs"))
.expect("Couldn't write bindings!");
}

View file

@ -0,0 +1,23 @@
// Pure C API for store operations
#include <nix_api_store.h>
// Pure C API for error handling
#include <nix_api_util.h>
// Pure C API for the Nix evaluator
#include <nix_api_expr.h>
// Pure C API for external values
#include <nix_api_external.h>
// Pure C API for value manipulation
#include <nix_api_value.h>
// Pure C API for fetcher operations
#include <nix_api_fetchers.h>
// Pure C API for flake support
#include <nix_api_flake.h>
// Pure C API for main/CLI support
#include <nix_api_main.h>

17
nixide-sys/lib.rs Normal file
View file

@ -0,0 +1,17 @@
//! # nixide-sys
//!
//! Unsafe direct FFI bindings to libnix C API.
//!
//! ## Safety
//!
//! These bindings are generated automatically and map directly to the C API.
//! They are unsafe to use directly. Prefer using the high-level safe API in the
//! parent crate unless you know what you're doing.
#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
#![allow(rustdoc::bare_urls)]
#![allow(rustdoc::invalid_html_tags)]
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));

1235
nixide-sys/tests/eval.rs Normal file

File diff suppressed because it is too large Load diff

78
nixide-sys/tests/flake.rs Normal file
View file

@ -0,0 +1,78 @@
#![cfg(test)]
use std::ptr;
use nixide_sys::*;
use serial_test::serial;
#[test]
#[serial]
fn flake_settings_new_and_free() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
// Create new flake settings
let settings = nix_flake_settings_new(ctx);
assert!(!settings.is_null(), "nix_flake_settings_new returned null");
// Free flake settings (should not crash)
nix_flake_settings_free(settings);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn flake_settings_add_to_eval_state_builder() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, ptr::null(), ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let settings = nix_flake_settings_new(ctx);
assert!(!settings.is_null(), "nix_flake_settings_new returned null");
// Add flake settings to eval state builder
let err = nix_flake_settings_add_to_eval_state_builder(ctx, settings, builder);
// Accept OK or ERR_UNKNOWN (depends on Nix build/config)
assert!(
err == nix_err_NIX_OK || err == nix_err_NIX_ERR_UNKNOWN,
"nix_flake_settings_add_to_eval_state_builder returned unexpected error \
code: {err}"
);
nix_flake_settings_free(settings);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn flake_settings_null_context() {
// Passing NULL context should not crash, but may error
unsafe {
let settings = nix_flake_settings_new(ptr::null_mut());
// May return null if context is required
if !settings.is_null() {
nix_flake_settings_free(settings);
}
}
}

503
nixide-sys/tests/memory.rs Normal file
View file

@ -0,0 +1,503 @@
#![cfg(test)]
use std::ffi::CString;
use nixide_sys::*;
use serial_test::serial;
#[test]
#[serial]
fn value_reference_counting() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let load_err = nix_eval_state_builder_load(ctx, builder);
assert_eq!(load_err, nix_err_NIX_OK);
let state = nix_eval_state_build(ctx, builder);
assert!(!state.is_null());
// Create a value
let value = nix_alloc_value(ctx, state);
assert!(!value.is_null());
// Initialize with an integer
let init_err = nix_init_int(ctx, value, 42);
assert_eq!(init_err, nix_err_NIX_OK);
// Test value-specific reference counting
let incref_err = nix_value_incref(ctx, value);
assert_eq!(incref_err, nix_err_NIX_OK);
// Value should still be valid after increment
let int_val = nix_get_int(ctx, value);
assert_eq!(int_val, 42);
// Test decrement
let decref_err = nix_value_decref(ctx, value);
assert_eq!(decref_err, nix_err_NIX_OK);
// Value should still be valid (original reference still exists)
let int_val2 = nix_get_int(ctx, value);
assert_eq!(int_val2, 42);
// Final decrement (should not crash)
let final_decref_err = nix_value_decref(ctx, value);
assert_eq!(final_decref_err, nix_err_NIX_OK);
// Clean up
nix_state_free(state);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn general_gc_reference_counting() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let load_err = nix_eval_state_builder_load(ctx, builder);
assert_eq!(load_err, nix_err_NIX_OK);
let state = nix_eval_state_build(ctx, builder);
assert!(!state.is_null());
// Create a value for general GC testing
let value = nix_alloc_value(ctx, state);
assert!(!value.is_null());
let init_err = nix_init_string(
ctx,
value,
CString::new("test string for GC").unwrap().as_ptr(),
);
assert_eq!(init_err, nix_err_NIX_OK);
// Test general GC reference counting
let gc_incref_err = nix_gc_incref(ctx, value as *const ::std::os::raw::c_void);
assert_eq!(gc_incref_err, nix_err_NIX_OK);
// Value should still be accessible
let value_type = nix_get_type(ctx, value);
assert_eq!(value_type, ValueType_NIX_TYPE_STRING);
// Test GC decrement
let gc_decref_err = nix_gc_decref(ctx, value as *const ::std::os::raw::c_void);
assert_eq!(gc_decref_err, nix_err_NIX_OK);
// Final cleanup
nix_value_decref(ctx, value);
nix_state_free(state);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn manual_garbage_collection() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let load_err = nix_eval_state_builder_load(ctx, builder);
assert_eq!(load_err, nix_err_NIX_OK);
let state = nix_eval_state_build(ctx, builder);
assert!(!state.is_null());
// Create a few values to test basic GC functionality
let mut values = Vec::new();
for i in 0..3 {
let value = nix_alloc_value(ctx, state);
if !value.is_null() {
let init_err = nix_init_int(ctx, value, i);
if init_err == nix_err_NIX_OK {
values.push(value);
}
}
}
// Verify values are accessible before GC
for (i, &value) in values.iter().enumerate() {
let int_val = nix_get_int(ctx, value);
assert_eq!(int_val, i as i64);
}
// Clean up values before attempting GC to avoid signal issues
for value in values {
nix_value_decref(ctx, value);
}
nix_state_free(state);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn value_copying_and_memory_management() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let load_err = nix_eval_state_builder_load(ctx, builder);
assert_eq!(load_err, nix_err_NIX_OK);
let state = nix_eval_state_build(ctx, builder);
assert!(!state.is_null());
// Create original value
let original = nix_alloc_value(ctx, state);
assert!(!original.is_null());
let test_string = CString::new("test string for copying").unwrap();
let init_err = nix_init_string(ctx, original, test_string.as_ptr());
assert_eq!(init_err, nix_err_NIX_OK);
// Create copy
let copy = nix_alloc_value(ctx, state);
assert!(!copy.is_null());
let copy_err = nix_copy_value(ctx, copy, original);
assert_eq!(copy_err, nix_err_NIX_OK);
// Verify copy has same type and can be accessed
let original_type = nix_get_type(ctx, original);
let copy_type = nix_get_type(ctx, copy);
assert_eq!(original_type, copy_type);
assert_eq!(copy_type, ValueType_NIX_TYPE_STRING);
// Test string contents using callback
unsafe extern "C" fn string_callback(
start: *const ::std::os::raw::c_char,
n: ::std::os::raw::c_uint,
user_data: *mut ::std::os::raw::c_void,
) {
let s = unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
let s = std::str::from_utf8(s).unwrap_or("");
let result = unsafe { &mut *(user_data as *mut Option<String>) };
*result = Some(s.to_string());
}
let mut original_string: Option<String> = None;
let mut copy_string: Option<String> = None;
let _ = nix_get_string(
ctx,
original,
Some(string_callback),
&mut original_string as *mut Option<String> as *mut ::std::os::raw::c_void,
);
let _ = nix_get_string(
ctx,
copy,
Some(string_callback),
&mut copy_string as *mut Option<String> as *mut ::std::os::raw::c_void,
);
// Both should have the same string content
assert_eq!(original_string, copy_string);
assert!(original_string
.as_deref()
.unwrap_or("")
.contains("test string"));
// Test reference counting on both values
let incref_orig = nix_value_incref(ctx, original);
let incref_copy = nix_value_incref(ctx, copy);
assert_eq!(incref_orig, nix_err_NIX_OK);
assert_eq!(incref_copy, nix_err_NIX_OK);
// Values should still be accessible after increment
assert_eq!(nix_get_type(ctx, original), ValueType_NIX_TYPE_STRING);
assert_eq!(nix_get_type(ctx, copy), ValueType_NIX_TYPE_STRING);
// Clean up with decrements
nix_value_decref(ctx, original);
nix_value_decref(ctx, original); // extra decref from incref
nix_value_decref(ctx, copy);
nix_value_decref(ctx, copy); // extra decref from incref
nix_state_free(state);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn complex_value_memory_management() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let load_err = nix_eval_state_builder_load(ctx, builder);
assert_eq!(load_err, nix_err_NIX_OK);
let state = nix_eval_state_build(ctx, builder);
assert!(!state.is_null());
// Create a complex structure: list containing attribute sets
let list_builder = nix_make_list_builder(ctx, state, 2);
assert!(!list_builder.is_null());
// Create first element: attribute set
let attrs1 = nix_alloc_value(ctx, state);
assert!(!attrs1.is_null());
let bindings_builder1 = nix_make_bindings_builder(ctx, state, 2);
assert!(!bindings_builder1.is_null());
// Add attributes to first set
let key1 = CString::new("name").unwrap();
let val1 = nix_alloc_value(ctx, state);
assert!(!val1.is_null());
let name_str = CString::new("first").unwrap();
let _ = nix_init_string(ctx, val1, name_str.as_ptr());
let insert_err1 = nix_bindings_builder_insert(ctx, bindings_builder1, key1.as_ptr(), val1);
assert_eq!(insert_err1, nix_err_NIX_OK);
let key2 = CString::new("value").unwrap();
let val2 = nix_alloc_value(ctx, state);
assert!(!val2.is_null());
let _ = nix_init_int(ctx, val2, 42);
let insert_err2 = nix_bindings_builder_insert(ctx, bindings_builder1, key2.as_ptr(), val2);
assert_eq!(insert_err2, nix_err_NIX_OK);
let make_attrs_err1 = nix_make_attrs(ctx, attrs1, bindings_builder1);
assert_eq!(make_attrs_err1, nix_err_NIX_OK);
// Insert first attrs into list
let list_insert_err1 = nix_list_builder_insert(ctx, list_builder, 0, attrs1);
assert_eq!(list_insert_err1, nix_err_NIX_OK);
// Create second element
let attrs2 = nix_alloc_value(ctx, state);
assert!(!attrs2.is_null());
let bindings_builder2 = nix_make_bindings_builder(ctx, state, 1);
assert!(!bindings_builder2.is_null());
let key3 = CString::new("data").unwrap();
let val3 = nix_alloc_value(ctx, state);
assert!(!val3.is_null());
let data_str = CString::new("second").unwrap();
let _ = nix_init_string(ctx, val3, data_str.as_ptr());
let insert_err3 = nix_bindings_builder_insert(ctx, bindings_builder2, key3.as_ptr(), val3);
assert_eq!(insert_err3, nix_err_NIX_OK);
let make_attrs_err2 = nix_make_attrs(ctx, attrs2, bindings_builder2);
assert_eq!(make_attrs_err2, nix_err_NIX_OK);
let list_insert_err2 = nix_list_builder_insert(ctx, list_builder, 1, attrs2);
assert_eq!(list_insert_err2, nix_err_NIX_OK);
// Create final list
let final_list = nix_alloc_value(ctx, state);
assert!(!final_list.is_null());
let make_list_err = nix_make_list(ctx, list_builder, final_list);
assert_eq!(make_list_err, nix_err_NIX_OK);
// Test the complex structure
assert_eq!(nix_get_type(ctx, final_list), ValueType_NIX_TYPE_LIST);
assert_eq!(nix_get_list_size(ctx, final_list), 2);
// Access nested elements
let elem0 = nix_get_list_byidx(ctx, final_list, state, 0);
let elem1 = nix_get_list_byidx(ctx, final_list, state, 1);
assert!(!elem0.is_null() && !elem1.is_null());
assert_eq!(nix_get_type(ctx, elem0), ValueType_NIX_TYPE_ATTRS);
assert_eq!(nix_get_type(ctx, elem1), ValueType_NIX_TYPE_ATTRS);
// Test memory management with deep copying
let copied_list = nix_alloc_value(ctx, state);
assert!(!copied_list.is_null());
let copy_err = nix_copy_value(ctx, copied_list, final_list);
assert_eq!(copy_err, nix_err_NIX_OK);
// Force deep evaluation on copy
let deep_force_err = nix_value_force_deep(ctx, state, copied_list);
assert_eq!(deep_force_err, nix_err_NIX_OK);
// Both should still be accessible
assert_eq!(nix_get_list_size(ctx, final_list), 2);
assert_eq!(nix_get_list_size(ctx, copied_list), 2);
// Clean up all the values
nix_value_decref(ctx, copied_list);
nix_value_decref(ctx, final_list);
nix_value_decref(ctx, attrs2);
nix_value_decref(ctx, attrs1);
nix_value_decref(ctx, val3);
nix_value_decref(ctx, val2);
nix_value_decref(ctx, val1);
nix_state_free(state);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn memory_management_error_conditions() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
// Test reference counting with NULL pointers (should handle gracefully)
let null_incref_err = nix_gc_incref(ctx, std::ptr::null() as *const ::std::os::raw::c_void);
// XXX: May succeed or fail depending on implementation. We can't really
// know, so assert both.
assert!(null_incref_err == nix_err_NIX_OK || null_incref_err == nix_err_NIX_ERR_UNKNOWN);
let null_decref_err = nix_gc_decref(ctx, std::ptr::null() as *const ::std::os::raw::c_void);
assert!(null_decref_err == nix_err_NIX_OK || null_decref_err == nix_err_NIX_ERR_UNKNOWN);
let null_value_incref_err = nix_value_incref(ctx, std::ptr::null_mut());
// Some Nix APIs gracefully handle null pointers and return OK
assert!(
null_value_incref_err == nix_err_NIX_OK
|| null_value_incref_err == nix_err_NIX_ERR_UNKNOWN
);
let null_value_decref_err = nix_value_decref(ctx, std::ptr::null_mut());
// Some Nix APIs gracefully handle null pointers and return OK
assert!(
null_value_decref_err == nix_err_NIX_OK
|| null_value_decref_err == nix_err_NIX_ERR_UNKNOWN
);
// Test copy with NULL values
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let load_err = nix_eval_state_builder_load(ctx, builder);
assert_eq!(load_err, nix_err_NIX_OK);
let state = nix_eval_state_build(ctx, builder);
assert!(!state.is_null());
let valid_value = nix_alloc_value(ctx, state);
assert!(!valid_value.is_null());
// Test copying to/from NULL
let copy_from_null_err = nix_copy_value(ctx, valid_value, std::ptr::null_mut());
assert_ne!(copy_from_null_err, nix_err_NIX_OK);
let copy_to_null_err = nix_copy_value(ctx, std::ptr::null_mut(), valid_value);
assert_ne!(copy_to_null_err, nix_err_NIX_OK);
// Clean up
nix_value_decref(ctx, valid_value);
nix_state_free(state);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}

639
nixide-sys/tests/primop.rs Normal file
View file

@ -0,0 +1,639 @@
#![cfg(test)]
use std::{
ffi::CString,
sync::atomic::{AtomicU32, Ordering},
};
use nixide_sys::*;
use serial_test::serial;
#[derive(Debug)]
struct TestPrimOpData {
call_count: AtomicU32,
last_arg_value: AtomicU32,
}
// Simple PrimOp that adds 1 to an integer argument
unsafe extern "C" fn add_one_primop(
user_data: *mut ::std::os::raw::c_void,
context: *mut nix_c_context,
state: *mut EvalState,
args: *mut *mut nix_value,
ret: *mut nix_value,
) {
if user_data.is_null()
|| context.is_null()
|| state.is_null()
|| args.is_null()
|| ret.is_null()
{
let _ = unsafe {
nix_set_err_msg(
context,
nix_err_NIX_ERR_UNKNOWN,
b"Null pointer in add_one_primop\0".as_ptr() as *const _,
)
};
return;
}
let data = unsafe { &*(user_data as *const TestPrimOpData) };
data.call_count.fetch_add(1, Ordering::SeqCst);
// Get first argument
let arg = unsafe { *args.offset(0) };
if arg.is_null() {
let _ = unsafe {
nix_set_err_msg(
context,
nix_err_NIX_ERR_UNKNOWN,
b"Missing argument in add_one_primop\0".as_ptr() as *const _,
)
};
return;
}
// Force evaluation of argument
if unsafe { nix_value_force(context, state, arg) } != nix_err_NIX_OK {
return;
}
// Check if argument is integer
if unsafe { nix_get_type(context, arg) } != ValueType_NIX_TYPE_INT {
let _ = unsafe {
nix_set_err_msg(
context,
nix_err_NIX_ERR_UNKNOWN,
b"Expected integer argument in add_one_primop\0".as_ptr() as *const _,
)
};
return;
}
// Get integer value and add 1
let value = unsafe { nix_get_int(context, arg) };
data.last_arg_value.store(value as u32, Ordering::SeqCst);
// Set return value
let _ = unsafe { nix_init_int(context, ret, value + 1) };
}
// PrimOp that returns a constant string
unsafe extern "C" fn hello_world_primop(
_user_data: *mut ::std::os::raw::c_void,
context: *mut nix_c_context,
_state: *mut EvalState,
_args: *mut *mut nix_value,
ret: *mut nix_value,
) {
let hello = CString::new("Hello from Rust PrimOp!").unwrap();
let _ = unsafe { nix_init_string(context, ret, hello.as_ptr()) };
}
// PrimOp that takes multiple arguments and concatenates them
unsafe extern "C" fn concat_strings_primop(
_user_data: *mut ::std::os::raw::c_void,
context: *mut nix_c_context,
state: *mut EvalState,
args: *mut *mut nix_value,
ret: *mut nix_value,
) {
if context.is_null() || state.is_null() || args.is_null() || ret.is_null() {
return;
}
// This PrimOp expects exactly 2 string arguments
let mut result = String::new();
for i in 0..2 {
let arg = unsafe { *args.offset(i) };
if arg.is_null() {
let _ = unsafe {
nix_set_err_msg(
context,
nix_err_NIX_ERR_UNKNOWN,
b"Missing argument in concat_strings_primop\0".as_ptr() as *const _,
)
};
return;
}
// Force evaluation
if unsafe { nix_value_force(context, state, arg) } != nix_err_NIX_OK {
return;
}
// Check if it's a string
if unsafe { nix_get_type(context, arg) } != ValueType_NIX_TYPE_STRING {
let _ = unsafe {
static ITEMS: &[u8] = b"Expected string argument in concat_strings_primop\0";
nix_set_err_msg(context, nix_err_NIX_ERR_UNKNOWN, ITEMS.as_ptr() as *const _)
};
return;
}
// Get string value using callback
unsafe extern "C" fn string_callback(
start: *const ::std::os::raw::c_char,
n: ::std::os::raw::c_uint,
user_data: *mut ::std::os::raw::c_void,
) {
let s = unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
let s = std::str::from_utf8(s).unwrap_or("");
let result = unsafe { &mut *(user_data as *mut String) };
result.push_str(s);
}
let _ = unsafe {
nix_get_string(
context,
arg,
Some(string_callback),
&mut result as *mut String as *mut ::std::os::raw::c_void,
)
};
}
let result_cstr = CString::new(result).unwrap_or_else(|_| CString::new("").unwrap());
let _ = unsafe { nix_init_string(context, ret, result_cstr.as_ptr()) };
}
#[test]
#[serial]
fn primop_allocation_and_registration() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let load_err = nix_eval_state_builder_load(ctx, builder);
assert_eq!(load_err, nix_err_NIX_OK);
let state = nix_eval_state_build(ctx, builder);
assert!(!state.is_null());
// Create test data
let test_data = Box::new(TestPrimOpData {
call_count: AtomicU32::new(0),
last_arg_value: AtomicU32::new(0),
});
let test_data_ptr = Box::into_raw(test_data);
// Create argument names
let arg_names = [CString::new("x").unwrap()];
let arg_name_ptrs: Vec<*const _> = arg_names.iter().map(|s| s.as_ptr()).collect();
let mut arg_name_ptrs_null_terminated = arg_name_ptrs;
arg_name_ptrs_null_terminated.push(std::ptr::null());
let name = CString::new("addOne").unwrap();
let doc = CString::new("Add 1 to the argument").unwrap();
// Allocate PrimOp
let primop = nix_alloc_primop(
ctx,
Some(add_one_primop),
1, // arity
name.as_ptr(),
arg_name_ptrs_null_terminated.as_mut_ptr(),
doc.as_ptr(),
test_data_ptr as *mut ::std::os::raw::c_void,
);
if !primop.is_null() {
// Register the PrimOp globally
let register_err = nix_register_primop(ctx, primop);
// Registration may fail in some environments, but allocation should work
assert!(
register_err == nix_err_NIX_OK || register_err == nix_err_NIX_ERR_UNKNOWN,
"Unexpected error code: {register_err}"
);
// Test using the PrimOp by creating a value with it
let primop_value = nix_alloc_value(ctx, state);
assert!(!primop_value.is_null());
let init_err = nix_init_primop(ctx, primop_value, primop);
assert_eq!(init_err, nix_err_NIX_OK);
// Clean up value
nix_value_decref(ctx, primop_value);
}
// Clean up
let _ = Box::from_raw(test_data_ptr);
nix_state_free(state);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn primop_function_call() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let load_err = nix_eval_state_builder_load(ctx, builder);
assert_eq!(load_err, nix_err_NIX_OK);
let state = nix_eval_state_build(ctx, builder);
assert!(!state.is_null());
// Create test data
let test_data = Box::new(TestPrimOpData {
call_count: AtomicU32::new(0),
last_arg_value: AtomicU32::new(0),
});
let test_data_ptr = Box::into_raw(test_data);
// Create simple hello world PrimOp (no arguments)
let name = CString::new("helloWorld").unwrap();
let doc = CString::new("Returns hello world string").unwrap();
let mut empty_args: Vec<*const ::std::os::raw::c_char> = vec![std::ptr::null()];
let hello_primop = nix_alloc_primop(
ctx,
Some(hello_world_primop),
0, // arity
name.as_ptr(),
empty_args.as_mut_ptr(),
doc.as_ptr(),
std::ptr::null_mut(),
);
if !hello_primop.is_null() {
// Create a value with the PrimOp
let primop_value = nix_alloc_value(ctx, state);
assert!(!primop_value.is_null());
let init_err = nix_init_primop(ctx, primop_value, hello_primop);
assert_eq!(init_err, nix_err_NIX_OK);
// Call the PrimOp (no arguments)
let result = nix_alloc_value(ctx, state);
assert!(!result.is_null());
let call_err = nix_value_call(ctx, state, primop_value, std::ptr::null_mut(), result);
if call_err == nix_err_NIX_OK {
// Force the result
let force_err = nix_value_force(ctx, state, result);
assert_eq!(force_err, nix_err_NIX_OK);
// Check if result is a string
let result_type = nix_get_type(ctx, result);
if result_type == ValueType_NIX_TYPE_STRING {
// Get string value
unsafe extern "C" fn string_callback(
start: *const ::std::os::raw::c_char,
n: ::std::os::raw::c_uint,
user_data: *mut ::std::os::raw::c_void,
) {
let s =
unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
let s = std::str::from_utf8(s).unwrap_or("");
let result = unsafe { &mut *(user_data as *mut Option<String>) };
*result = Some(s.to_string());
}
let mut string_result: Option<String> = None;
let _ = nix_get_string(
ctx,
result,
Some(string_callback),
&mut string_result as *mut Option<String> as *mut ::std::os::raw::c_void,
);
// Verify we got the expected string
assert!(string_result
.as_deref()
.unwrap_or("")
.contains("Hello from Rust"));
}
}
nix_value_decref(ctx, result);
nix_value_decref(ctx, primop_value);
}
// Clean up
let _ = Box::from_raw(test_data_ptr);
nix_state_free(state);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn primop_with_arguments() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let load_err = nix_eval_state_builder_load(ctx, builder);
assert_eq!(load_err, nix_err_NIX_OK);
let state = nix_eval_state_build(ctx, builder);
assert!(!state.is_null());
// Create test data
let test_data = Box::new(TestPrimOpData {
call_count: AtomicU32::new(0),
last_arg_value: AtomicU32::new(0),
});
let test_data_ptr = Box::into_raw(test_data);
// Create add one PrimOp
let arg_names = [CString::new("x").unwrap()];
let arg_name_ptrs: Vec<*const _> = arg_names.iter().map(|s| s.as_ptr()).collect();
let mut arg_name_ptrs_null_terminated = arg_name_ptrs;
arg_name_ptrs_null_terminated.push(std::ptr::null());
let name = CString::new("addOne").unwrap();
let doc = CString::new("Add 1 to the argument").unwrap();
let add_primop = nix_alloc_primop(
ctx,
Some(add_one_primop),
1, // arity
name.as_ptr(),
arg_name_ptrs_null_terminated.as_mut_ptr(),
doc.as_ptr(),
test_data_ptr as *mut ::std::os::raw::c_void,
);
if !add_primop.is_null() {
// Create a value with the PrimOp
let primop_value = nix_alloc_value(ctx, state);
assert!(!primop_value.is_null());
let init_err = nix_init_primop(ctx, primop_value, add_primop);
assert_eq!(init_err, nix_err_NIX_OK);
// Create an integer argument
let arg_value = nix_alloc_value(ctx, state);
assert!(!arg_value.is_null());
let init_arg_err = nix_init_int(ctx, arg_value, 42);
assert_eq!(init_arg_err, nix_err_NIX_OK);
// Call the PrimOp with the argument
let result = nix_alloc_value(ctx, state);
assert!(!result.is_null());
let call_err = nix_value_call(ctx, state, primop_value, arg_value, result);
if call_err == nix_err_NIX_OK {
// Force the result
let force_err = nix_value_force(ctx, state, result);
assert_eq!(force_err, nix_err_NIX_OK);
// Check if result is an integer
let result_type = nix_get_type(ctx, result);
if result_type == ValueType_NIX_TYPE_INT {
let result_value = nix_get_int(ctx, result);
assert_eq!(result_value, 43); // 42 + 1
// Verify callback was called
let test_data_ref = &*test_data_ptr;
assert_eq!(test_data_ref.call_count.load(Ordering::SeqCst), 1);
assert_eq!(test_data_ref.last_arg_value.load(Ordering::SeqCst), 42);
}
}
nix_value_decref(ctx, result);
nix_value_decref(ctx, arg_value);
nix_value_decref(ctx, primop_value);
}
// Clean up
let _ = Box::from_raw(test_data_ptr);
nix_state_free(state);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn primop_multi_argument() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let load_err = nix_eval_state_builder_load(ctx, builder);
assert_eq!(load_err, nix_err_NIX_OK);
let state = nix_eval_state_build(ctx, builder);
assert!(!state.is_null());
// Create concat strings PrimOp
let arg_names = [CString::new("s1").unwrap(), CString::new("s2").unwrap()];
let arg_name_ptrs: Vec<*const _> = arg_names.iter().map(|s| s.as_ptr()).collect();
let mut arg_name_ptrs_null_terminated = arg_name_ptrs;
arg_name_ptrs_null_terminated.push(std::ptr::null());
let name = CString::new("concatStrings").unwrap();
let doc = CString::new("Concatenate two strings").unwrap();
let concat_primop = nix_alloc_primop(
ctx,
Some(concat_strings_primop),
2, // arity
name.as_ptr(),
arg_name_ptrs_null_terminated.as_mut_ptr(),
doc.as_ptr(),
std::ptr::null_mut(),
);
if !concat_primop.is_null() {
// Create a value with the PrimOp
let primop_value = nix_alloc_value(ctx, state);
assert!(!primop_value.is_null());
let init_err = nix_init_primop(ctx, primop_value, concat_primop);
assert_eq!(init_err, nix_err_NIX_OK);
// Create string arguments
let arg1 = nix_alloc_value(ctx, state);
let arg2 = nix_alloc_value(ctx, state);
assert!(!arg1.is_null() && !arg2.is_null());
let hello_cstr = CString::new("Hello, ").unwrap();
let world_cstr = CString::new("World!").unwrap();
let init_arg1_err = nix_init_string(ctx, arg1, hello_cstr.as_ptr());
let init_arg2_err = nix_init_string(ctx, arg2, world_cstr.as_ptr());
assert_eq!(init_arg1_err, nix_err_NIX_OK);
assert_eq!(init_arg2_err, nix_err_NIX_OK);
// Test multi-argument call using nix_value_call_multi
let mut args = [arg1, arg2];
let result = nix_alloc_value(ctx, state);
assert!(!result.is_null());
let call_err =
nix_value_call_multi(ctx, state, primop_value, 2, args.as_mut_ptr(), result);
if call_err == nix_err_NIX_OK {
// Force the result
let force_err = nix_value_force(ctx, state, result);
assert_eq!(force_err, nix_err_NIX_OK);
// Check if result is a string
let result_type = nix_get_type(ctx, result);
if result_type == ValueType_NIX_TYPE_STRING {
unsafe extern "C" fn string_callback(
start: *const ::std::os::raw::c_char,
n: ::std::os::raw::c_uint,
user_data: *mut ::std::os::raw::c_void,
) {
let s =
unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
let s = std::str::from_utf8(s).unwrap_or("");
let result = unsafe { &mut *(user_data as *mut Option<String>) };
*result = Some(s.to_string());
}
let mut string_result: Option<String> = None;
let _ = nix_get_string(
ctx,
result,
Some(string_callback),
&mut string_result as *mut Option<String> as *mut ::std::os::raw::c_void,
);
// Verify concatenation worked
assert_eq!(string_result.as_deref(), Some("Hello, World!"));
}
}
nix_value_decref(ctx, result);
nix_value_decref(ctx, arg2);
nix_value_decref(ctx, arg1);
nix_value_decref(ctx, primop_value);
}
nix_state_free(state);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn primop_error_handling() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let err = nix_libexpr_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let builder = nix_eval_state_builder_new(ctx, store);
assert!(!builder.is_null());
let load_err = nix_eval_state_builder_load(ctx, builder);
assert_eq!(load_err, nix_err_NIX_OK);
let state = nix_eval_state_build(ctx, builder);
assert!(!state.is_null());
// Test invalid PrimOp allocation (NULL callback)
let name = CString::new("invalid").unwrap();
let doc = CString::new("Invalid PrimOp").unwrap();
let mut empty_args: Vec<*const ::std::os::raw::c_char> = vec![std::ptr::null()];
let _invalid_primop = nix_alloc_primop(
ctx,
None, // NULL callback should cause error
0,
name.as_ptr(),
empty_args.as_mut_ptr(),
doc.as_ptr(),
std::ptr::null_mut(),
);
// Test initializing value with NULL PrimOp (should fail)
let test_value = nix_alloc_value(ctx, state);
assert!(!test_value.is_null());
nix_value_decref(ctx, test_value);
nix_state_free(state);
nix_eval_state_builder_free(builder);
nix_store_free(store);
nix_c_context_free(ctx);
}
}

278
nixide-sys/tests/store.rs Normal file
View file

@ -0,0 +1,278 @@
#![cfg(test)]
use std::{ffi::CString, ptr};
use nixide_sys::*;
use serial_test::serial;
#[test]
#[serial]
fn libstore_init_and_open_free() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
// Open the default store (NULL URI, NULL params)
let store = nix_store_open(ctx, ptr::null(), ptr::null_mut());
assert!(!store.is_null());
// Free the store and context
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn parse_and_clone_free_store_path() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, ptr::null(), ptr::null_mut());
assert!(!store.is_null());
// Parse a store path (I'm using a dummy path, will likely be invalid but
// should not segfault) XXX: store_path may be null if path is invalid,
// but should not crash
let path_str = CString::new("/nix/store/dummy-path").unwrap();
let store_path = nix_store_parse_path(ctx, store, path_str.as_ptr());
if !store_path.is_null() {
// Clone and free
let cloned = nix_store_path_clone(store_path);
assert!(!cloned.is_null());
nix_store_path_free(cloned);
nix_store_path_free(store_path);
}
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn store_get_uri_and_storedir() {
unsafe extern "C" fn string_callback(
start: *const ::std::os::raw::c_char,
n: ::std::os::raw::c_uint,
user_data: *mut ::std::os::raw::c_void,
) {
let s = unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
let s = std::str::from_utf8(s).unwrap();
let out = user_data.cast::<Option<String>>();
unsafe { *out = Some(s.to_string()) };
}
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, ptr::null(), ptr::null_mut());
assert!(!store.is_null());
let mut uri: Option<String> = None;
let res = nix_store_get_uri(ctx, store, Some(string_callback), (&raw mut uri).cast());
assert_eq!(res, nix_err_NIX_OK);
assert!(uri.is_some());
let mut storedir: Option<String> = None;
let res = nix_store_get_storedir(
ctx,
store,
Some(string_callback),
(&raw mut storedir).cast(),
);
assert_eq!(res, nix_err_NIX_OK);
assert!(storedir.is_some());
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn libstore_init_no_load_config() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libstore_init_no_load_config(ctx);
assert_eq!(err, nix_err_NIX_OK);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn store_is_valid_path_and_real_path() {
unsafe extern "C" fn string_callback(
start: *const ::std::os::raw::c_char,
n: ::std::os::raw::c_uint,
user_data: *mut ::std::os::raw::c_void,
) {
let s = unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
let s = std::str::from_utf8(s).unwrap();
let out = user_data.cast::<Option<String>>();
unsafe { *out = Some(s.to_string()) };
}
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
// Use a dummy path (should not be valid, but should not crash)
let path_str = CString::new("/nix/store/dummy-path").unwrap();
let store_path = nix_store_parse_path(ctx, store, path_str.as_ptr());
if !store_path.is_null() {
let valid = nix_store_is_valid_path(ctx, store, store_path);
assert!(!valid, "Dummy path should not be valid");
let mut real_path: Option<String> = None;
let res = nix_store_real_path(
ctx,
store,
store_path,
Some(string_callback),
(&raw mut real_path).cast(),
);
// May fail, but should not crash
assert!(res == nix_err_NIX_OK || res == nix_err_NIX_ERR_UNKNOWN);
nix_store_path_free(store_path);
}
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn store_path_name() {
unsafe extern "C" fn string_callback(
start: *const ::std::os::raw::c_char,
n: ::std::os::raw::c_uint,
user_data: *mut ::std::os::raw::c_void,
) {
let s = unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
let s = std::str::from_utf8(s).unwrap();
let out = user_data.cast::<Option<String>>();
unsafe { *out = Some(s.to_string()) };
}
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let path_str = CString::new("/nix/store/foo-bar-baz").unwrap();
let store_path = nix_store_parse_path(ctx, store, path_str.as_ptr());
if !store_path.is_null() {
let mut name: Option<String> = None;
nix_store_path_name(store_path, Some(string_callback), (&raw mut name).cast());
// Should extract the name part ("foo-bar-baz")
assert!(name.as_deref().unwrap_or("").contains("foo-bar-baz"));
nix_store_path_free(store_path);
}
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn store_get_version() {
unsafe extern "C" fn string_callback(
start: *const ::std::os::raw::c_char,
n: ::std::os::raw::c_uint,
user_data: *mut ::std::os::raw::c_void,
) {
let s = unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
let s = std::str::from_utf8(s).unwrap();
let out = user_data.cast::<Option<String>>();
unsafe { *out = Some(s.to_string()) };
}
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
let mut version: Option<String> = None;
let res =
nix_store_get_version(ctx, store, Some(string_callback), (&raw mut version).cast());
assert_eq!(res, nix_err_NIX_OK);
// Version may be empty for dummy stores, but should not crash
assert!(version.is_some());
nix_store_free(store);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn store_realise_and_copy_closure() {
unsafe extern "C" fn realise_callback(
_userdata: *mut ::std::os::raw::c_void,
outname: *const ::std::os::raw::c_char,
out: *const StorePath,
) {
// Just check that callback is called with non-null pointers
assert!(!outname.is_null());
assert!(!out.is_null());
}
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libstore_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
let store = nix_store_open(ctx, std::ptr::null(), std::ptr::null_mut());
assert!(!store.is_null());
// Use a dummy path (should not crash, may not realise)
let path_str = CString::new("/nix/store/dummy-path").unwrap();
let store_path = nix_store_parse_path(ctx, store, path_str.as_ptr());
if !store_path.is_null() {
// Realise (should fail, but must not crash)
let _ = nix_store_realise(
ctx,
store,
store_path,
std::ptr::null_mut(),
Some(realise_callback),
);
// Copy closure to same store (should fail, but must not crash)
let _ = nix_store_copy_closure(ctx, store, store, store_path);
nix_store_path_free(store_path);
}
nix_store_free(store);
nix_c_context_free(ctx);
}
}

152
nixide-sys/tests/util.rs Normal file
View file

@ -0,0 +1,152 @@
#![cfg(test)]
use std::ffi::{CStr, CString};
use nixide_sys::*;
use serial_test::serial;
#[test]
#[serial]
fn context_create_and_free() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn libutil_init() {
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn version_get() {
unsafe {
let version_ptr = nix_version_get();
assert!(!version_ptr.is_null());
let version = CStr::from_ptr(version_ptr).to_string_lossy();
assert!(!version.is_empty(), "Version string should not be empty");
assert!(
version.chars().next().unwrap().is_ascii_digit(),
"Version string should start with a digit: {version}"
);
}
}
#[test]
#[serial]
fn setting_set_and_get() {
unsafe extern "C" fn string_callback(
start: *const ::std::os::raw::c_char,
n: ::std::os::raw::c_uint,
user_data: *mut ::std::os::raw::c_void,
) {
let s = unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
let s = std::str::from_utf8(s).unwrap();
let out = user_data.cast::<Option<String>>();
*unsafe { &mut *out } = Some(s.to_string());
}
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
// Set a setting (use a dummy/extra setting to avoid breaking global config)
let key = CString::new("extra-test-setting").unwrap();
let value = CString::new("test-value").unwrap();
let set_err = nix_setting_set(ctx, key.as_ptr(), value.as_ptr());
// Setting may not exist, but should not crash
assert!(
set_err == nix_err_NIX_OK || set_err == nix_err_NIX_ERR_KEY,
"Unexpected error code: {set_err}"
);
// Try to get the setting (may not exist, but should not crash)
let mut got: Option<String> = None;
let get_err = nix_setting_get(
ctx,
key.as_ptr(),
Some(string_callback),
(&raw mut got).cast(),
);
assert!(
get_err == nix_err_NIX_OK || get_err == nix_err_NIX_ERR_KEY,
"Unexpected error code: {get_err}"
);
// If OK, we should have gotten a value
if get_err == nix_err_NIX_OK {
assert_eq!(got.as_deref(), Some("test-value"));
}
nix_c_context_free(ctx);
}
}
#[test]
#[serial]
fn error_handling_apis() {
unsafe extern "C" fn string_callback(
start: *const ::std::os::raw::c_char,
n: ::std::os::raw::c_uint,
user_data: *mut ::std::os::raw::c_void,
) {
let s = unsafe { std::slice::from_raw_parts(start.cast::<u8>(), n as usize) };
let s = std::str::from_utf8(s).unwrap();
let out = user_data.cast::<Option<String>>();
*unsafe { &mut *out } = Some(s.to_string());
}
unsafe {
let ctx = nix_c_context_create();
assert!(!ctx.is_null());
let err = nix_libutil_init(ctx);
assert_eq!(err, nix_err_NIX_OK);
// Set an error message
let msg = CString::new("custom error message").unwrap();
let set_err = nix_set_err_msg(ctx, nix_err_NIX_ERR_UNKNOWN, msg.as_ptr());
assert_eq!(set_err, nix_err_NIX_ERR_UNKNOWN);
// Get error code
let code = nix_err_code(ctx);
assert_eq!(code, nix_err_NIX_ERR_UNKNOWN);
// Get error message
let mut len: std::os::raw::c_uint = 0;
let err_msg_ptr = nix_err_msg(ctx, ctx, &mut len as *mut _);
if !err_msg_ptr.is_null() && len > 0 {
let err_msg = std::str::from_utf8(std::slice::from_raw_parts(
err_msg_ptr as *const u8,
len as usize,
))
.unwrap();
assert!(err_msg.contains("custom error message"));
}
// Get error info message (should work, but may be empty)
let mut info: Option<String> = None;
let _ = nix_err_info_msg(ctx, ctx, Some(string_callback), (&raw mut info).cast());
// Get error name (should work, but may be empty)
let mut name: Option<String> = None;
let _ = nix_err_name(ctx, ctx, Some(string_callback), (&raw mut name).cast());
// Clear error
nix_clear_err(ctx);
let code_after_clear = nix_err_code(ctx);
assert_eq!(code_after_clear, nix_err_NIX_OK);
nix_c_context_free(ctx);
}
}

32
nixide/Cargo.toml Normal file
View file

@ -0,0 +1,32 @@
[package]
name = "nixide"
description = "Safe & oxidized bindings to the Nix API"
version = "0.1.0"
readme = "../README.md"
license = "GPL-3.0"
repository = "https://codeberg.org/luminary/nixide"
authors = [
"_cry64 <them@dobutterfliescry.net>",
"foxxyora <foxxyora@noreply.codeberg.org>",
]
edition = "2024"
[lib]
path = "src/lib.rs"
[features]
default = ["util"]
expr = []
fetchers = []
flakes = []
store = []
util = []
gc = []
[dependencies]
libc = "0.2.183"
stdext = "0.3.3"
nixide-sys = { path = "../nixide-sys", version = "0.1.0" }
[dev-dependencies]
serial_test = "3.4.0"

View file

@ -0,0 +1,357 @@
// XXX: TODO: create wrappers methods to access more than just `info->msg()`
// struct ErrorInfo
// {
// Verbosity level;
// HintFmt msg;
// std::shared_ptr<const Pos> pos;
// std::list<Trace> traces;
// /**
// * Some messages are generated directly by expressions; notably `builtins.warn`, `abort`, `throw`.
// * These may be rendered differently, so that users can distinguish them.
// */
// bool isFromExpr = false;
// /**
// * Exit status.
// */
// unsigned int status = 1;
// Suggestions suggestions;
// static std::optional<std::string> programName;
// };
use std::ffi::c_uint;
use std::ffi::c_void;
use std::ptr::NonNull;
use super::{NixError, NixideResult};
use crate::stdext::CCharPtrExt as _;
use crate::sys;
use crate::util::panic_issue_call_failed;
use crate::util::wrap;
use crate::util::wrappers::AsInnerPtr;
/// This object stores error state.
///
/// Passed as a first parameter to functions that can fail, to store error
/// information.
///
/// # Warning
///
/// These can be reused between different function calls,
/// but make sure not to use them for multiple calls simultaneously
/// (which can happen in callbacks).
///
/// # Nix C++ API Internals
///
/// ```cpp
/// struct nix_c_context
/// {
/// nix_err last_err_code = NIX_OK;
/// /* WARNING: The last error message. Always check last_err_code.
/// WARNING: This may not have been cleared, so that clearing is fast. */
/// std::optional<std::string> last_err = {};
/// std::optional<nix::ErrorInfo> info = {};
/// std::string name = "";
/// };
/// ```
///
/// The [sys::nix_c_context] struct is laid out so that it can also be
/// cast to a [sys::nix_err] to inspect directly:
/// ```c
/// assert(*(nix_err*)ctx == NIX_OK);
/// ```
pub(crate) struct ErrorContext {
// XXX: TODO: add a RwLock to this (maybe Arc<RwLock>? or is that excessive?)
inner: NonNull<sys::nix_c_context>,
}
impl AsInnerPtr<sys::nix_c_context> for ErrorContext {
#[inline]
unsafe fn as_ptr(&self) -> *mut sys::nix_c_context {
self.inner.as_ptr()
}
#[inline]
unsafe fn as_ref(&self) -> &sys::nix_c_context {
unsafe { self.inner.as_ref() }
}
#[inline]
unsafe fn as_mut(&mut self) -> &mut sys::nix_c_context {
unsafe { self.inner.as_mut() }
}
}
impl Into<NixideResult<()>> for &ErrorContext {
/// # Panics
///
/// This function will panic in the event that `context.get_err() == Some(err) && err == sys::nix_err_NIX_OK`
/// since `nixide::ErrorContext::get_err` is expected to return `None` to indicate `sys::nix_err_NIX_OK`.
///
/// This function will panic in the event that `value != sys::nix_err_NIX_OK`
/// but that `context.get_code() == sys::nix_err_NIX_OK`
fn into(self) -> NixideResult<()> {
let inner = match self.get_err() {
Some(err) => err,
None => return Ok(()),
};
let msg = match self.get_msg() {
Some(msg) => msg,
None => return Ok(()),
};
let err = match inner {
sys::nix_err_NIX_OK => unreachable!(),
sys::nix_err_NIX_ERR_OVERFLOW => NixError::Overflow,
sys::nix_err_NIX_ERR_KEY => NixError::KeyNotFound(None),
sys::nix_err_NIX_ERR_NIX_ERROR => NixError::ExprEval {
name: self
.get_nix_err_name()
.unwrap_or_else(|| panic_issue_call_failed!()),
info_msg: self
.get_nix_err_info_msg()
.unwrap_or_else(|| panic_issue_call_failed!()),
},
sys::nix_err_NIX_ERR_UNKNOWN => NixError::Unknown,
err => NixError::Undocumented(err),
};
Err(new_nixide_error!(NixError, inner, err, msg))
}
}
impl ErrorContext {
/// Create a new error context.
///
/// # Errors
///
/// Returns an error if no memory can be allocated for
/// the underlying [sys::nix_c_context] struct.
pub fn new() -> Self {
match NonNull::new(unsafe { sys::nix_c_context_create() }) {
Some(inner) => ErrorContext { inner },
None => panic!("[nixide] CRITICAL FAILURE: Out-Of-Memory condition reached - `sys::nix_c_context_create` allocation failed!"),
}
// Initialize required libraries
// XXX: TODO: move this to a separate init function (maybe a Nix::init() function)
// unsafe {
// NixErrorCode::from(
// sys::nix_libutil_init(ctx.inner.as_ptr()),
// "nix_libutil_init",
// )?;
// NixErrorCode::from(
// sys::nix_libstore_init(ctx.inner.as_ptr()),
// "nix_libstore_init",
// )?;
// NixErrorCode::from(
// sys::nix_libexpr_init(ctx.inner.as_ptr()),
// "nix_libexpr_init",
// )?;
// };
}
/// Check the error code and return an error if it's not `NIX_OK`.
pub fn peak(&self) -> NixideResult<()> {
self.into()
}
///
/// Equivalent to running `self.peak()` then `self.clear()`
pub fn pop(&mut self) -> NixideResult<()> {
self.peak().and_then(|_| Ok(self.clear()))
}
/// # Nix C++ API Internals
///
/// ```cpp
/// void nix_clear_err(nix_c_context * context)
/// {
/// if (context)
/// context->last_err_code = NIX_OK;
/// }
/// ```
///
/// `nix_clear_err` only modifies the `last_err_code`, it does not
/// clear all attributes of a `nix_c_context` struct. Hence all uses
/// of `nix_c_context` must be careful to check the `last_err_code` regularly.
pub fn clear(&mut self) {
unsafe {
// NOTE: previous nixops4 used the line: (maybe for compatability with old versions?)
// sys::nix_set_err_msg(self.inner.as_ptr(), sys::nix_err_NIX_OK, c"".as_ptr());
sys::nix_clear_err(self.as_ptr());
}
}
/// Returns [None] if [self.code] is [sys::nix_err_NIX_OK], and [Some] otherwise.
///
/// # Nix C++ API Internals
/// ```cpp
/// nix_err nix_err_code(const nix_c_context * read_context)
/// {
/// return read_context->last_err_code;
/// }
/// ```
/// This function **never fails**.
pub(super) fn get_err(&self) -> Option<sys::nix_err> {
let err = unsafe { sys::nix_err_code(self.as_ptr()) };
match err {
sys::nix_err_NIX_OK => None,
_ => Some(err),
}
}
/// Returns [None] if [self.code] is [sys::nix_err_NIX_OK], and [Some] otherwise.
///
/// # Nix C++ API Internals
/// ```cpp
/// const char * nix_err_msg(nix_c_context * context, const nix_c_context * read_context, unsigned int * n)
/// {
/// if (context)
/// context->last_err_code = NIX_OK;
/// if (read_context->last_err && read_context->last_err_code != NIX_OK) {
/// if (n)
/// *n = read_context->last_err->size();
/// return read_context->last_err->c_str();
/// }
/// nix_set_err_msg(context, NIX_ERR_UNKNOWN, "No error message");
/// return nullptr;
/// }
/// ```
///
/// # Note
/// On failure [sys::nix_err_name] does the following if the error
/// has the error code [sys::nix_err_NIX_OK]:
/// ```cpp
/// nix_set_err_msg(context, NIX_ERR_UNKNOWN, "No error message");
/// return nullptr;
/// ```
/// Hence we can just test whether the returned pointer is a `NULL` pointer,
/// and avoid passing in a [sys::nix_c_context] struct.
pub(super) fn get_msg(&self) -> Option<String> {
let ctx = ErrorContext::new();
unsafe {
// NOTE: an Err here only occurs when `self.get_code() == Ok(())`
let mut n: c_uint = 0;
sys::nix_err_msg(ctx.as_ptr(), self.as_ptr(), &mut n)
.to_utf8_string_n(n as usize)
.ok()
}
}
/// Returns [None] if [self.code] is [sys::nix_err_NIX_OK], and [Some] otherwise.
///
/// # Nix C++ API Internals
///
/// ```cpp
/// // NOTE(nixide): the implementation of `nix_err_info_msg` is identical to `nix_err_name`
/// nix_err nix_err_info_msg(
/// nix_c_context * context,
/// const nix_c_context * read_context,
/// nix_get_string_callback callback,
/// void * user_data)
/// {
/// if (context)
/// context->last_err_code = NIX_OK;
/// if (read_context->last_err_code != NIX_ERR_NIX_ERROR) {
/// // NOTE(nixide): `nix_set_err_msg` throws a `nix::Error` exception if `context == nullptr`
/// return nix_set_err_msg(context, NIX_ERR_UNKNOWN, "Last error was not a nix error");
/// }
/// // NOTE(nixide): `call_nix_get_string_callback` always returns `NIX_OK`
/// return call_nix_get_string_callback(read_context->info->msg.str(), callback, user_data);
/// }
/// ```
///
/// `nix_err_info_msg` accepts two `nix_c_context*`:
/// * `nix_c_context* context` - errors from the function call are logged here
/// * `const nix_c_context* read_context` - the context to read `info_msg` from
///
/// `nix_set_err_msg` will cause undefined behaviour if `context` is a null pointer (see below)
/// due to [https://github.com/rust-lang/rust-bindgen/issues/1208].
/// So we should never assigned it [std::ptr::null_mut].
/// ```cpp
/// if (context == nullptr) {
/// throw nix::Error("Nix C api error: %s", msg);
/// }
/// ```
pub(super) fn get_nix_err_name(&self) -> Option<String> {
#[allow(unused_unsafe)] // XXX: TODO: remove this `unused_unsafe`
unsafe {
// NOTE: an Err here only occurs when "Last error was not a nix error"
wrap::nix_string_callback!(|callback, userdata: *mut __UserData, ctx: &ErrorContext| {
sys::nix_err_name(
ctx.as_ptr(),
self.as_ptr(),
Some(callback),
userdata as *mut c_void,
)
})
.ok()
}
}
/// Returns [None] if [self.code] is [sys::nix_err_NIX_OK], and [Some] otherwise.
///
/// # Nix C++ API Internals
///
/// ```cpp
/// // NOTE(nixide): the implementation of `nix_err_info_msg` is identical to `nix_err_name`
/// nix_err nix_err_info_msg(
/// nix_c_context * context,
/// const nix_c_context * read_context,
/// nix_get_string_callback callback,
/// void * user_data)
/// {
/// if (context)
/// context->last_err_code = NIX_OK;
/// if (read_context->last_err_code != NIX_ERR_NIX_ERROR) {
/// // NOTE(nixide): `nix_set_err_msg` throws a `nix::Error` exception if `context == nullptr`
/// return nix_set_err_msg(context, NIX_ERR_UNKNOWN, "Last error was not a nix error");
/// }
/// // NOTE(nixide): `call_nix_get_string_callback` always returns `NIX_OK`
/// return call_nix_get_string_callback(read_context->info->msg.str(), callback, user_data);
/// }
/// ```
///
/// `nix_err_info_msg` accepts two `nix_c_context*`:
/// * `nix_c_context* context` - errors from the function call are logged here
/// * `const nix_c_context* read_context` - the context to read `info_msg` from
///
/// `nix_set_err_msg` will cause undefined behaviour if `context` is a null pointer (see below)
/// due to [https://github.com/rust-lang/rust-bindgen/issues/1208].
/// So we should never assigned it [std::ptr::null_mut].
/// ```cpp
/// if (context == nullptr) {
/// throw nix::Error("Nix C api error: %s", msg);
/// }
/// ```
pub(super) fn get_nix_err_info_msg(&self) -> Option<String> {
#[allow(unused_unsafe)] // XXX: TODO: remove this `unused_unsafe`
unsafe {
// NOTE: an Err here only occurs when "Last error was not a nix error"
wrap::nix_string_callback!(|callback, userdata, ctx: &ErrorContext| {
sys::nix_err_info_msg(
ctx.as_ptr(),
self.as_ptr(),
Some(callback),
userdata as *mut c_void,
)
})
.ok()
}
}
}
impl Drop for ErrorContext {
fn drop(&mut self) {
unsafe {
sys::nix_c_context_free(self.inner.as_ptr());
}
}
}

151
nixide/src/errors/error.rs Normal file
View file

@ -0,0 +1,151 @@
use std::fmt::{Display, Formatter, Result as FmtResult};
use super::NixError;
use crate::sys;
pub type NixideResult<T> = Result<T, NixideError>;
#[derive(Debug, Clone)]
pub enum NixideError {
/// # Warning
/// [NixideErrorVariant::NixError] is **not the same** as [sys::nix_err_NIX_ERR_NIX_ERROR],
/// that is instead mapped to [NixError::ExprEval]
NixError {
trace: String,
inner: sys::nix_err,
err: NixError,
msg: String,
},
/// Returned if a C string `*const c_char` contained a `\0` byte prematurely.
StringNulByte { trace: String },
/// Returned if a C string is not encoded in UTF-8.
StringNotUtf8 { trace: String },
/// Equivalent to the standard [std::ffi::NulError] type.
NullPtr { trace: String },
/// Invalid Argument
InvalidArg {
trace: String,
name: &'static str,
reason: String,
},
/// Invalid Type
InvalidType {
trace: String,
expected: &'static str,
got: String,
},
}
macro_rules! new_nixide_error {
(NixError, $inner:expr, $err:expr, $msg:expr) => {{
crate::NixideError::NixError {
trace: ::stdext::debug_name!(),
inner: $inner,
err: $err,
msg: $msg,
}
}};
(StringNulByte) => {{
crate::NixideError::StringNulByte {
trace: ::stdext::debug_name!(),
}
}};
(StringNotUtf8) => {{
crate::NixideError::StringNotUtf8 {
trace: ::stdext::debug_name!(),
}
}};
(NullPtr) => {{
crate::NixideError::NullPtr {
trace: ::stdext::debug_name!(),
}
}};
(InvalidArg, $name:expr, $reason:expr) => {{
crate::NixideError::InvalidArg {
trace: ::stdext::debug_name!(),
name: $name,
reason: $reason,
}
}};
(InvalidType, $expected:expr, $got:expr) => {{
crate::NixideError::InvalidType {
trace: ::stdext::debug_name!(),
expected: $expected,
got: $got,
}
}};
}
pub(crate) use new_nixide_error;
#[allow(unused_macros)]
macro_rules! retrace_nixide_error {
($x:expr) => {{
crate::errors::new_nixide_error!($x.err)
}};
}
pub(crate) use retrace_nixide_error;
impl std::error::Error for NixideError {}
impl Display for NixideError {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
NixideError::NixError {
trace,
inner,
err,
msg,
} => {
write!(f, "[nixide ~ {trace}]{err} (nix_err={inner}): {msg}")
}
NixideError::StringNulByte { trace } => {
write!(f, "[nixide ~ {trace}] Got premature `\\0` (NUL) byte")
}
NixideError::StringNotUtf8 { trace } => {
write!(f, "[nixide ~ {trace}] Expected UTF-8 encoded string")
}
NixideError::NullPtr { trace } => write!(f, "[nixide ~ {trace}] Got null pointer"),
NixideError::InvalidArg {
trace,
name,
reason,
} => {
write!(
f,
"[nixide ~ {trace}] Invalid argument `{name}`: reason \"{reason}\""
)
}
NixideError::InvalidType {
trace,
expected,
got,
} => write!(
f,
"[nixide ~ {trace}] Got invalid type: expected `{expected}` but got `{got}`"
),
}
}
}
// pub trait AsErr<T> {
// fn as_err(self) -> Result<(), T>;
// }
// impl AsErr<NixideError> for Option<NixideError> {
// fn as_err(self) -> Result<(), NixideError> {
// match self {
// Some(err) => Err(err),
// None => Ok(()),
// }
// }
// }

9
nixide/src/errors/mod.rs Normal file
View file

@ -0,0 +1,9 @@
#[macro_use]
mod error;
mod context;
mod nix_error;
pub(crate) use context::ErrorContext;
pub(crate) use error::{new_nixide_error, retrace_nixide_error};
pub use error::{NixideError, NixideResult};
pub use nix_error::NixError;

View file

@ -0,0 +1,115 @@
use std::fmt::{Display, Formatter, Result as FmtResult};
use crate::sys;
/// Standard (nix_err) and some additional error codes
/// produced by the libnix C API.
#[derive(Debug, Clone)]
pub enum NixError {
/// A generic Nix error occurred.
///
/// # Reason
///
/// This error code is returned when a generic Nix error occurs
/// during nixexpr evaluation.
///
/// # Nix C++ API Internals
///
/// ```cpp
/// // `NIX_ERR_NIX_ERROR` variant of the `nix_err` enum type
/// NIX_ERR_NIX_ERROR = -4
/// ```
ExprEval { name: String, info_msg: String },
/// A key/index access error occurred in C API functions.
///
/// # Reason
///
/// This error code is returned when accessing a key, index, or identifier that
/// does not exist in C API functions. Common scenarios include:
/// - Setting keys that don't exist (nix_setting_get, nix_setting_set)
/// - List indices that are out of bounds (nix_get_list_byidx*)
/// - Attribute names that don't exist (nix_get_attr_byname*)
/// - Attribute indices that are out of bounds (nix_get_attr_byidx*, nix_get_attr_name_byidx)
///
/// This error typically indicates incorrect usage or assumptions about data structure
/// contents, rather than internal Nix evaluation errors.
///
/// # Note
///
/// This error code should ONLY be returned by C API functions themselves,
/// not by underlying Nix evaluation. For example, evaluating `{}.foo` in Nix
/// will throw a normal error (NIX_ERR_NIX_ERROR), not NIX_ERR_KEY.
///
/// # Nix C++ API Internals
///
/// ```cpp
/// // `NIX_ERR_KEY` variant of the `nix_err` enum type
/// NIX_ERR_KEY = -3
/// ```
KeyNotFound(Option<String>),
/// An overflow error occurred.
///
/// # Reason
///
/// This error code is returned when an overflow error occurred during the
/// function execution.
///
/// # Nix C++ API Internals
///
/// ```cpp
/// // `NIX_ERR_OVERFLOW` variant of the `nix_err` enum type
/// NIX_ERR_OVERFLOW = -2
/// ```
Overflow,
/// An unknown error occurred.
///
/// # Reason
///
/// This error code is returned when an unknown error occurred during the
/// function execution.
///
/// # Nix C++ API Internals
///
/// ```cpp
/// // `NIX_ERR_OVERFLOW` variant of the `nix_err` enum type
/// NIX_ERR_UNKNOWN = -1
/// ```
Unknown,
///
/// An undocumented error occurred.
///
/// # Reason
///
/// The libnix C API defines `enum nix_err` as a signed integer value.
/// In the (unexpected) event libnix returns an error code with an
/// invalid enum value, or one I new addition I didn't know existed,
/// then an [NixError::Undocumented] is considered to have occurred.
///
/// # Nix C++ API Internals
///
/// [NixError::Undocumented] has no equivalent in the `libnix` api.
/// This is solely a language difference between C++ and Rust, since
/// [sys::nix_err] is defined over the *"continuous" (not realy)*
/// type [std::os::raw::c_int].
Undocumented(sys::nix_err),
}
impl Display for NixError {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
match self {
NixError::ExprEval { name, info_msg } => write!(f, "[libnix] NixExpr evaluation failed [name=\"{name}\", info_msg=\"{info_msg}\"]"),
NixError::KeyNotFound(Some(key)) => write!(f, "[libnix] Key not found \"{key}\""),
NixError::KeyNotFound(None) => write!(f, "[libnix] Key not found"),
NixError::Overflow => write!(f, "[libnix] Overflow error"),
NixError::Unknown => write!(f, "[libnix] Unknown error"),
NixError::Undocumented(err) => write!(
f,
"[libnix] An undocumented nix_err({err}) [please open an issue on https://github.com/cry128/nixide]"
),
}
}
}

View file

@ -0,0 +1,109 @@
use std::ffi::CString;
use std::ptr::NonNull;
use std::sync::Arc;
use crate::errors::new_nixide_error;
use super::Value;
use crate::errors::ErrorContext;
use crate::sys;
use crate::util::wrap;
use crate::util::wrappers::AsInnerPtr;
use crate::{NixideResult, Store};
/// Nix evaluation state for evaluating expressions.
///
/// This provides the main interface for evaluating Nix expressions
/// and creating values.
pub struct EvalState {
inner: NonNull<sys::EvalState>,
// XXX: TODO: is an `Arc<Store>` necessary or just a `Store`
store: Arc<Store>,
}
impl AsInnerPtr<sys::EvalState> for EvalState {
#[inline]
unsafe fn as_ptr(&self) -> *mut sys::EvalState {
self.inner.as_ptr()
}
#[inline]
unsafe fn as_ref(&self) -> &sys::EvalState {
unsafe { self.inner.as_ref() }
}
#[inline]
unsafe fn as_mut(&mut self) -> &mut sys::EvalState {
unsafe { self.inner.as_mut() }
}
}
impl EvalState {
/// Construct a new EvalState directly from its attributes
pub(super) fn new(inner: NonNull<sys::EvalState>, store: Arc<Store>) -> Self {
Self { inner, store }
}
#[inline]
pub(crate) unsafe fn store_ref(&self) -> &Store {
self.store.as_ref()
}
/// Evaluate a Nix expression from a string.
///
/// # Arguments
///
/// * `expr` - The Nix expression to evaluate
/// * `path` - The path to use for error reporting (e.g., "<eval>")
///
/// # Errors
///
/// Returns an error if evaluation fails.
pub fn eval_from_string(&self, expr: &str, path: &str) -> NixideResult<Value> {
let expr_c = CString::new(expr).or(Err(new_nixide_error!(StringNulByte)))?;
let path_c = CString::new(path).or(Err(new_nixide_error!(StringNulByte)))?;
// Allocate value for result
let value = self.new_value()?;
// Evaluate expression
wrap::nix_fn!(|ctx: &ErrorContext| unsafe {
sys::nix_expr_eval_from_string(
ctx.as_ptr(),
self.as_ptr(),
expr_c.as_ptr(),
path_c.as_ptr(),
value.as_ptr(),
);
value
})
}
/// Allocate a new value.
///
/// # Errors
///
/// Returns an error if value allocation fails.
pub(self) fn new_value(&self) -> NixideResult<Value> {
// XXX: TODO: should this function be `Value::new` instead?
let inner = wrap::nix_ptr_fn!(|ctx: &ErrorContext| unsafe {
sys::nix_alloc_value(ctx.as_ptr(), self.as_ptr())
})?;
Ok(Value::new(inner, self))
}
}
impl Drop for EvalState {
fn drop(&mut self) {
// SAFETY: We own the state and it's valid until drop
unsafe {
sys::nix_state_free(self.inner.as_ptr());
}
}
}
// SAFETY: EvalState can be shared between threads
unsafe impl Send for EvalState {}
unsafe impl Sync for EvalState {}

View file

@ -0,0 +1,85 @@
use std::ptr::NonNull;
use std::sync::Arc;
use super::EvalState;
use crate::errors::{ErrorContext, NixideResult};
use crate::sys;
use crate::util::wrap;
use crate::util::wrappers::AsInnerPtr;
use crate::Store;
/// Builder for Nix evaluation state.
///
/// This allows configuring the evaluation environment before creating
/// the evaluation state.
pub struct EvalStateBuilder {
inner: NonNull<sys::nix_eval_state_builder>,
store: Arc<Store>,
}
impl AsInnerPtr<sys::nix_eval_state_builder> for EvalStateBuilder {
#[inline]
unsafe fn as_ptr(&self) -> *mut sys::nix_eval_state_builder {
self.inner.as_ptr()
}
#[inline]
unsafe fn as_ref(&self) -> &sys::nix_eval_state_builder {
unsafe { self.inner.as_ref() }
}
#[inline]
unsafe fn as_mut(&mut self) -> &mut sys::nix_eval_state_builder {
unsafe { self.inner.as_mut() }
}
}
impl EvalStateBuilder {
/// Create a new evaluation state builder.
///
/// # Arguments
///
/// * `store` - The Nix store to use for evaluation
///
/// # Errors
///
/// Returns an error if the builder cannot be created.
pub fn new(store: &Arc<Store>) -> NixideResult<Self> {
let inner = wrap::nix_ptr_fn!(|ctx: &ErrorContext| unsafe {
sys::nix_eval_state_builder_new(ctx.as_ptr(), store.as_ptr())
})?;
Ok(EvalStateBuilder {
inner,
store: Arc::clone(store),
})
}
/// Build the evaluation state.
///
/// # Errors
///
/// Returns an error if the evaluation state cannot be built.
pub fn build(self) -> NixideResult<EvalState> {
// Load configuration first
wrap::nix_fn!(|ctx: &ErrorContext| unsafe {
sys::nix_eval_state_builder_load(ctx.as_ptr(), self.as_ptr())
})?;
// Build the state
let inner = wrap::nix_ptr_fn!(|ctx: &ErrorContext| unsafe {
sys::nix_eval_state_build(ctx.as_ptr(), self.as_ptr())
})?;
Ok(EvalState::new(inner, self.store.clone()))
}
}
impl Drop for EvalStateBuilder {
fn drop(&mut self) {
// SAFETY: We own the builder and it's valid until drop
unsafe {
sys::nix_eval_state_builder_free(self.inner.as_ptr());
}
}
}

16
nixide/src/expr/mod.rs Normal file
View file

@ -0,0 +1,16 @@
#[cfg(test)]
mod tests;
mod evalstate;
mod evalstatebuilder;
mod realised_string;
mod value;
mod values;
mod valuetype;
pub use evalstate::EvalState;
pub use evalstatebuilder::EvalStateBuilder;
pub use realised_string::RealisedString;
pub use value::Value;
pub use values::{NixInt, NixValue};
pub use valuetype::ValueType;

View file

@ -0,0 +1,121 @@
use std::ffi::c_char;
use std::ptr::NonNull;
use std::sync::Arc;
use crate::errors::ErrorContext;
use crate::expr::values::NixString;
use crate::stdext::CCharPtrExt;
use crate::sys;
use crate::util::wrappers::AsInnerPtr;
use crate::util::LazyArray;
use crate::util::{panic_issue_call_failed, wrap};
use crate::{EvalState, NixideResult, StorePath};
pub struct RealisedString {
inner: NonNull<sys::nix_realised_string>,
// pub path: LazyCell<StorePath, Box<fn() -> StorePath>>,
pub path: StorePath,
pub children: LazyArray<StorePath, fn(&LazyArray<StorePath, fn(usize) -> StorePath>, usize) -> StorePath>>,
}
impl AsInnerPtr<sys::nix_realised_string> for RealisedString {
#[inline]
unsafe fn as_ptr(&self) -> *mut sys::nix_realised_string {
self.inner.as_ptr()
}
#[inline]
unsafe fn as_ref(&self) -> &sys::nix_realised_string {
unsafe { self.inner.as_ref() }
}
#[inline]
unsafe fn as_mut(&mut self) -> &mut sys::nix_realised_string {
unsafe { self.inner.as_mut() }
}
}
impl Drop for RealisedString {
fn drop(&mut self) {
unsafe {
sys::nix_realised_string_free(self.as_ptr());
}
}
}
impl RealisedString {
/// Realise a string context.
///
/// This will
/// - realise the store paths referenced by the string's context, and
/// - perform the replacement of placeholders.
/// - create temporary garbage collection roots for the store paths, for
/// the lifetime of the current process.
/// - log to stderr
///
/// # Arguments
///
/// * value - Nix value, which must be a string
/// * state - Nix evaluator state
/// * isIFD - If true, disallow derivation outputs if setting `allow-import-from-derivation` is false.
/// You should set this to true when this call is part of a primop.
/// You should set this to false when building for your application's purpose.
///
/// # Returns
///
/// NULL if failed, or a new nix_realised_string, which must be freed with nix_realised_string_free
pub fn new(value: &NixString, state: &Arc<EvalState>) -> NixideResult<Self> {
let inner = wrap::nix_ptr_fn!(|ctx: &ErrorContext| unsafe {
sys::nix_string_realise(
ctx.as_ptr(),
state.as_ptr(),
value.as_ptr(),
false, // don't copy more
)
})?;
fn delegate(
inner: &LazyArray<StorePath, Box<dyn Fn(usize) -> StorePath>>,
index: usize,
) -> StorePath {
// XXX: TODO
// inner[index]
StorePath::fake_path(unsafe { state.store_ref() }).unwrap()
}
let size = unsafe { sys::nix_realised_string_get_store_path_count(inner.as_ptr()) };
Ok(Self {
inner,
path: Self::parse_path(inner.as_ptr(), state),
// children: LazyArray::new(size, delegate as fn(usize) -> StorePath),
children: LazyArray::<StorePath, Box<dyn Fn(usize) -> StorePath>>::new(
size,
Box::new(delegate),
),
})
}
fn parse_path(
realised_string: *mut sys::nix_realised_string,
state: &Arc<EvalState>,
) -> StorePath {
let buffer_ptr = unsafe { sys::nix_realised_string_get_buffer_start(realised_string) };
let buffer_size = unsafe { sys::nix_realised_string_get_buffer_size(realised_string) };
let path_str = (buffer_ptr as *const c_char)
.to_utf8_string_n(buffer_size)
.unwrap_or_else(|err| {
panic_issue_call_failed!(
"`sys::nix_realised_string_get_buffer_(start|size)` invalid UTF-8 ({})",
err
)
});
StorePath::parse(unsafe { state.store_ref() }, &path_str).unwrap_or_else(|err| {
panic_issue_call_failed!(
"`sys::nix_realised_string_get_buffer_(start|size)` invalid store path ({})",
err
)
})
}
}

142
nixide/src/expr/tests.rs Normal file
View file

@ -0,0 +1,142 @@
use std::sync::Arc;
use serial_test::serial;
use super::{EvalStateBuilder, ValueType};
use crate::Store;
#[test]
#[serial]
fn test_eval_state_builder() {
let store = Arc::new(Store::open(None).expect("Failed to open store"));
let _state = EvalStateBuilder::new(&store)
.expect("Failed to create builder")
.build()
.expect("Failed to build state");
// State should be dropped automatically
}
#[test]
#[serial]
fn test_simple_evaluation() {
let store = Arc::new(Store::open(None).expect("Failed to open store"));
let state = EvalStateBuilder::new(&store)
.expect("Failed to create builder")
.build()
.expect("Failed to build state");
let result = state
.eval_from_string("1 + 2", "<eval>")
.expect("Failed to evaluate expression");
assert_eq!(result.value_type(), ValueType::Int);
assert_eq!(result.as_int().expect("Failed to get int value"), 3);
}
#[test]
#[serial]
fn test_value_types() {
let store = Arc::new(Store::open(None).expect("Failed to open store"));
let state = EvalStateBuilder::new(&store)
.expect("Failed to create builder")
.build()
.expect("Failed to build state");
// Test integer
let int_val = state
.eval_from_string("42", "<eval>")
.expect("Failed to evaluate int");
assert_eq!(int_val.value_type(), ValueType::Int);
assert_eq!(int_val.as_int().expect("Failed to get int"), 42);
// Test boolean
let bool_val = state
.eval_from_string("true", "<eval>")
.expect("Failed to evaluate bool");
assert_eq!(bool_val.value_type(), ValueType::Bool);
assert!(bool_val.as_bool().expect("Failed to get bool"));
// Test string
let str_val = state
.eval_from_string("\"hello\"", "<eval>")
.expect("Failed to evaluate string");
assert_eq!(str_val.value_type(), ValueType::String);
assert_eq!(str_val.as_string().expect("Failed to get string"), "hello");
}
#[test]
#[serial]
fn test_value_formatting() {
let store = Arc::new(Store::open(None).expect("Failed to open store"));
let state = EvalStateBuilder::new(&store)
.expect("Failed to create builder")
.build()
.expect("Failed to build state");
// Test integer formatting
let int_val = state
.eval_from_string("42", "<eval>")
.expect("Failed to evaluate int");
assert_eq!(format!("{int_val}"), "42");
assert_eq!(format!("{int_val:?}"), "Value::Int(42)");
assert_eq!(int_val.to_nix_string().expect("Failed to format"), "42");
// Test boolean formatting
let bool_val = state
.eval_from_string("true", "<eval>")
.expect("Failed to evaluate bool");
assert_eq!(format!("{bool_val}"), "true");
assert_eq!(format!("{bool_val:?}"), "Value::Bool(true)");
assert_eq!(bool_val.to_nix_string().expect("Failed to format"), "true");
let false_val = state
.eval_from_string("false", "<eval>")
.expect("Failed to evaluate bool");
assert_eq!(format!("{false_val}"), "false");
assert_eq!(
false_val.to_nix_string().expect("Failed to format"),
"false"
);
// Test string formatting
let str_val = state
.eval_from_string("\"hello world\"", "<eval>")
.expect("Failed to evaluate string");
assert_eq!(format!("{str_val}"), "hello world");
assert_eq!(format!("{str_val:?}"), "Value::String(\"hello world\")");
assert_eq!(
str_val.to_nix_string().expect("Failed to format"),
"\"hello world\""
);
// Test string with quotes
let quoted_str = state
.eval_from_string("\"say \\\"hello\\\"\"", "<eval>")
.expect("Failed to evaluate quoted string");
assert_eq!(format!("{quoted_str}"), "say \"hello\"");
assert_eq!(
quoted_str.to_nix_string().expect("Failed to format"),
"\"say \\\"hello\\\"\""
);
// Test null formatting
let null_val = state
.eval_from_string("null", "<eval>")
.expect("Failed to evaluate null");
assert_eq!(format!("{null_val}"), "null");
assert_eq!(format!("{null_val:?}"), "Value::Null");
assert_eq!(null_val.to_nix_string().expect("Failed to format"), "null");
// Test collection formatting
let attrs_val = state
.eval_from_string("{ a = 1; }", "<eval>")
.expect("Failed to evaluate attrs");
assert_eq!(format!("{attrs_val}"), "{ <attrs> }");
assert_eq!(format!("{attrs_val:?}"), "Value::Attrs({ <attrs> })");
let list_val = state
.eval_from_string("[ 1 2 3 ]", "<eval>")
.expect("Failed to evaluate list");
assert_eq!(format!("{list_val}"), "[ <list> ]");
assert_eq!(format!("{list_val:?}"), "Value::List([ <list> ])");
}

Some files were not shown because too many files have changed in this diff Show more