From a82b521d04214f05dc6717b950712925357c0658 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Wed, 18 Feb 2026 16:35:00 +0100 Subject: [PATCH 01/19] README: oops, finish lead sentence --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a82f2cc..e16b97f 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Dynix — WIP modular dynamicism for NixOS systems -Dynix is a prototype for modifying an append-only NixOS configuration, and dynamically +Dynix is a prototype for modifying an append-only NixOS configuration, and dynamically applying that configuration. ## Running the tests From ec8f61f4d97b1e4d6b31ea2410b972ea712d9b2a Mon Sep 17 00:00:00 2001 From: Qyriad Date: Thu, 5 Mar 2026 15:44:58 +0100 Subject: [PATCH 02/19] remove unused finalAttrs/self --- package.nix | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/package.nix b/package.nix index 309f2d4..6bc26bd 100644 --- a/package.nix +++ b/package.nix @@ -48,9 +48,7 @@ in { # SUB-DERIVATONS # - dynixCommand = stdenv.mkDerivation (finalAttrs: let - commandSelf = finalAttrs.finalPackage; - in { + dynixCommand = stdenv.mkDerivation { pname = "${self.pname}-command"; inherit (self) version; inherit (self) strictDeps __structuredAttrs; @@ -80,11 +78,9 @@ in { meta = { mainProgram = "dynix"; }; - }); + }; - dynixModules = stdenv.mkDerivation (finalAttrs: let - modulesSelf = finalAttrs.finalPackage; - in { + dynixModules = stdenv.mkDerivation { pname = "${self.pname}-modules"; inherit (self) version; inherit (self) strictDeps __structuredAttrs; @@ -109,7 +105,7 @@ in { runHook postInstall ''; - }); + }; # # ---------------------------------------------------------------------------- From 9301d5f6a9c25f755b42625e564107754bcdfb22 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Thu, 5 Mar 2026 15:44:58 +0100 Subject: [PATCH 03/19] note IFD in tests --- tests/default.nix | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/default.nix b/tests/default.nix index 02842fa..929458e 100644 --- a/tests/default.nix +++ b/tests/default.nix @@ -32,6 +32,8 @@ ./module-allow-rebuild-in-vm.nix # For the VM node, and the in-VM configuration.nix ./dynix-vm-configuration.nix + # NOTE: if `dynix` is a package (which it usually is), then + # this is IFD. dynix.dynix ]; From a8a2d6e0430bfbf4ed94e14cd2f9ce521602a449 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Thu, 5 Mar 2026 15:44:58 +0100 Subject: [PATCH 04/19] don't include build dependencies for the nixos-rebuilds *in* the VMs --- tests/dynix-vm-configuration.nix | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/dynix-vm-configuration.nix b/tests/dynix-vm-configuration.nix index fbc6193..59ee1ec 100644 --- a/tests/dynix-vm-configuration.nix +++ b/tests/dynix-vm-configuration.nix @@ -15,7 +15,6 @@ in ]; system.switch.enable = true; - system.includeBuildDependencies = true; documentation.enable = false; boot.loader.grub = { From 442728a5cac1e8bd9136196bf3f6b1b30f9fed51 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Thu, 5 Mar 2026 15:44:58 +0100 Subject: [PATCH 05/19] do less string coercion in test modules in case that reduces copies idk honestly but these tests take sooo long I'm paranoid --- tests/dynix-vm-configuration.nix | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/dynix-vm-configuration.nix b/tests/dynix-vm-configuration.nix index 59ee1ec..9148302 100644 --- a/tests/dynix-vm-configuration.nix +++ b/tests/dynix-vm-configuration.nix @@ -1,6 +1,6 @@ { pkgs, lib, modulesPath, ... }: let - moduleList = import "${modulesPath}/module-list.nix"; + moduleList = import (modulesPath + "/module-list.nix"); dynixFromSearchPath = let res = builtins.tryEval ; @@ -8,7 +8,7 @@ let in { imports = [ - "${modulesPath}/testing/test-instrumentation.nix" + (modulesPath + "/testing/test-instrumentation.nix") ] ++ lib.concatLists [ dynixFromSearchPath moduleList @@ -26,7 +26,7 @@ in nix = { package = pkgs.lixPackageSets.latest.lix; nixPath = [ - "nixpkgs=${pkgs.path}" + ("nixpkgs=" + pkgs.path) "/nix/var/nix/profiles/per-user/root/profile/share/nixos/modules" ]; From 301fe041c42549f76ed51304b7b344ae3e5085c0 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Thu, 5 Mar 2026 15:44:58 +0100 Subject: [PATCH 06/19] add --no-reexec to nixos-rebuild in the VM tests --- tests/distccd/test-script.py | 4 ++-- tests/gotosocial/test-script.py | 4 ++-- tests/harmonia/test-script.py | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/tests/distccd/test-script.py b/tests/distccd/test-script.py index 3678155..8a34d8a 100644 --- a/tests/distccd/test-script.py +++ b/tests/distccd/test-script.py @@ -94,7 +94,7 @@ assert args.job_lifetime == 900, f'{args.job_lifetime} != 900' assert args.log_level == 'warning', f'{args.log_level=} != warning' with machine.nested("must succeed: initial nixos-rebuild switch"): - machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") + machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec --fallback") # Config should not have changed. args = get_cli_args() @@ -122,7 +122,7 @@ assert args.job_lifetime == 900, f'{args.job_lifetime} != 900' assert args.log_level == new_log_level, f'{args.log_level=} != {new_log_level=}' # And this should set everything back. -machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") +machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec --fallback") args = get_cli_args() assert args.jobs == 12, f'{args.jobs=} != 12' assert args.job_lifetime == 900, f'{args.job_lifetime} != 900' diff --git a/tests/gotosocial/test-script.py b/tests/gotosocial/test-script.py index 51a303f..d41d3d1 100644 --- a/tests/gotosocial/test-script.py +++ b/tests/gotosocial/test-script.py @@ -76,7 +76,7 @@ dynix_out = machine.succeed("dynix --version") assert "dynix" in dynix_out, f"dynix not in {dynix_out=}" machine.log("REBUILDING configuration inside VM") -machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") +machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec --fallback") machine.wait_for_unit("gotosocial.service") # Make sure the config before any dynamic changes is what we expect. @@ -107,7 +107,7 @@ except StopIteration: assert new_app_name in application_name, f"'{new_app_name}' should be in {application_name=}" machine.log("REBUILDING configuration inside VM") -machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") +machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec --fallback") machine.wait_for_unit("gotosocial.service") diff --git a/tests/harmonia/test-script.py b/tests/harmonia/test-script.py index bdac573..376e946 100644 --- a/tests/harmonia/test-script.py +++ b/tests/harmonia/test-script.py @@ -82,7 +82,7 @@ assert int(config_toml['workers']) == 4, f"{config_toml['workers']=} != 4" assert int(config_toml['max_connection_rate']) == 256, f"{config_toml['max_connection_rate']=} != 256" with machine.nested("must succeed: initial nixos-rebuild switch"): - machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") + machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec -v --fallback") # Config should not have changed. config_toml = get_config_file() @@ -108,7 +108,7 @@ assert int(config_toml['max_connection_rate']) == new_max_connection_rate, f"{co assert int(config_toml['workers']) == new_workers, f"{config_toml['workers']=} != {new_workers}" # And this should set everything back. -machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --fallback") +machine.succeed("env PAGER= nixos-rebuild switch --log-format raw-with-logs --no-reexec -v --fallback") machine.wait_for_unit("harmonia.service") config_toml = get_config_file() assert int(config_toml['max_connection_rate']) == 256, f'{config_toml["max_connection_rate"]=} != 256' From 5d541b9b3039d6c7ae4cfcbf124c4e2b39fd17e3 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Thu, 5 Mar 2026 15:44:58 +0100 Subject: [PATCH 07/19] by default, don't use a tmpfs for the /nix/store in the VM tests --- tests/README.md | 6 ++++++ tests/module-allow-rebuild-in-vm.nix | 8 +++++++- 2 files changed, 13 insertions(+), 1 deletion(-) create mode 100644 tests/README.md diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..6ef7869 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,6 @@ +# Notes for running the tests + +The VM tests do Nix builds inside the VMs, so they have writable Nix stores. +Writable Nix stores in NixOS VM tests are, by default, tmpfs, but to speed up IO for the in-VM `nixos-rebuild`s, `./module-allow-rebuild-in-vm.nix` instead sets `virtualisation.writableStoreUseTmpfs = false;`, and allocates a much larger root filesystem for the VM. +Specifically, each VM test allocates 20 GiB. +If you are running low on disk space, disable `virtualisation.writableStoreUseTmpfs` in `./module-allow-rebuild-in-vm`. diff --git a/tests/module-allow-rebuild-in-vm.nix b/tests/module-allow-rebuild-in-vm.nix index 96280fe..fa14e9f 100644 --- a/tests/module-allow-rebuild-in-vm.nix +++ b/tests/module-allow-rebuild-in-vm.nix @@ -1,4 +1,4 @@ -{ name, config, ... }: +{ name, lib, config, ... }: { system.includeBuildDependencies = true; @@ -12,6 +12,12 @@ mountHostNixStore = true; installBootLoader = true; + # Moderately improves performance of `nixos-rebuild` inside the VM on my machine, + # (205.48 seconds to 186.42 seconds), but we have to allocate much more space. + writableStoreUseTmpfs = false; + # 20 GiB ought to be enough. + diskSize = lib.mkIf (!config.virtualisation.writableStoreUseTmpfs) (20 * 1024); + # With how much memory Nix eval uses, this is essentially required. memorySize = 8192; cores = 8; From d681b96bc49ab1e119b3d7c2d8d4691fe309cf44 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Thu, 5 Mar 2026 16:19:06 +0100 Subject: [PATCH 08/19] license under the European Union Public License 1.2 --- .editorconfig | 4 + .gitignore | 4 + Cargo.lock.license | 3 + Cargo.toml | 5 + LICENSE | 287 ++++++++++++++++++++++++ LICENSES/EUPL-1.1.txt | 157 +++++++++++++ README.md | 6 + default.nix | 4 + flake.lock.license | 3 + flake.nix | 4 + modules/dynamicism/default.nix | 4 + modules/dynamicism/distccd.nix | 4 + modules/dynamicism/dynamicism.nix | 4 + modules/dynamicism/gotosocial.nix | 4 + modules/dynamicism/harmonia.nix | 4 + modules/dynamicism/lib.nix | 4 + modules/dynamicism/submodule.nix | 4 + modules/dynamicism/tzupdate.nix | 4 + package.nix | 12 + shell.nix | 4 + src/args.rs | 4 + src/color.rs | 4 + src/lib.rs | 4 + src/line.rs | 4 + src/main.rs | 4 + src/nixcmd.rs | 4 + src/source.rs | 4 + tests/README.md | 6 + tests/default.nix | 4 + tests/distccd/configuration.nix | 4 + tests/distccd/test-script.py | 4 + tests/distccd/test.nix | 4 + tests/dynix-vm-configuration.nix | 4 + tests/gotosocial/configuration.nix | 4 + tests/gotosocial/test-script.py | 4 + tests/gotosocial/test.nix | 4 + tests/harmonia/configuration.nix | 4 + tests/harmonia/test-script.py | 4 + tests/harmonia/test.nix | 4 + tests/mk-test-configuration-dot-nix.nix | 4 + tests/module-allow-rebuild-in-vm.nix | 4 + 41 files changed, 611 insertions(+) create mode 100644 Cargo.lock.license create mode 100644 LICENSE create mode 100644 LICENSES/EUPL-1.1.txt create mode 100644 flake.lock.license diff --git a/.editorconfig b/.editorconfig index 4753adb..ec1575b 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + [*] end_of_line = lf insert_final_newline = true diff --git a/.gitignore b/.gitignore index ea8c4bf..de75ea9 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,5 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + /target diff --git a/Cargo.lock.license b/Cargo.lock.license new file mode 100644 index 0000000..39b098c --- /dev/null +++ b/Cargo.lock.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2026 Qyriad + +SPDX-License-Identifier: EUPL-1.1 diff --git a/Cargo.toml b/Cargo.toml index 2e6dd55..41fe13c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,7 +1,12 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + [package] name = "dynix" version = "0.1.0" edition = "2024" +license = "EUPL-1.2" [[bin]] name = "dynix" diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4153cd3 --- /dev/null +++ b/LICENSE @@ -0,0 +1,287 @@ + EUROPEAN UNION PUBLIC LICENCE v. 1.2 + EUPL © the European Union 2007, 2016 + +This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined +below) which is provided under the terms of this Licence. Any use of the Work, +other than as authorised under this Licence is prohibited (to the extent such +use is covered by a right of the copyright holder of the Work). + +The Work is provided under the terms of this Licence when the Licensor (as +defined below) has placed the following notice immediately following the +copyright notice for the Work: + + Licensed under the EUPL + +or has expressed by any other means his willingness to license under the EUPL. + +1. Definitions + +In this Licence, the following terms have the following meaning: + +- ‘The Licence’: this Licence. + +- ‘The Original Work’: the work or software distributed or communicated by the + Licensor under this Licence, available as Source Code and also as Executable + Code as the case may be. + +- ‘Derivative Works’: the works or software that could be created by the + Licensee, based upon the Original Work or modifications thereof. This Licence + does not define the extent of modification or dependence on the Original Work + required in order to classify a work as a Derivative Work; this extent is + determined by copyright law applicable in the country mentioned in Article 15. + +- ‘The Work’: the Original Work or its Derivative Works. + +- ‘The Source Code’: the human-readable form of the Work which is the most + convenient for people to study and modify. + +- ‘The Executable Code’: any code which has generally been compiled and which is + meant to be interpreted by a computer as a program. + +- ‘The Licensor’: the natural or legal person that distributes or communicates + the Work under the Licence. + +- ‘Contributor(s)’: any natural or legal person who modifies the Work under the + Licence, or otherwise contributes to the creation of a Derivative Work. + +- ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of + the Work under the terms of the Licence. + +- ‘Distribution’ or ‘Communication’: any act of selling, giving, lending, + renting, distributing, communicating, transmitting, or otherwise making + available, online or offline, copies of the Work or providing access to its + essential functionalities at the disposal of any other natural or legal + person. + +2. Scope of the rights granted by the Licence + +The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, +sublicensable licence to do the following, for the duration of copyright vested +in the Original Work: + +- use the Work in any circumstance and for all usage, +- reproduce the Work, +- modify the Work, and make Derivative Works based upon the Work, +- communicate to the public, including the right to make available or display + the Work or copies thereof to the public and perform publicly, as the case may + be, the Work, +- distribute the Work or copies thereof, +- lend and rent the Work or copies thereof, +- sublicense rights in the Work or copies thereof. + +Those rights can be exercised on any media, supports and formats, whether now +known or later invented, as far as the applicable law permits so. + +In the countries where moral rights apply, the Licensor waives his right to +exercise his moral right to the extent allowed by law in order to make effective +the licence of the economic rights here above listed. + +The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to +any patents held by the Licensor, to the extent necessary to make use of the +rights granted on the Work under this Licence. + +3. Communication of the Source Code + +The Licensor may provide the Work either in its Source Code form, or as +Executable Code. If the Work is provided as Executable Code, the Licensor +provides in addition a machine-readable copy of the Source Code of the Work +along with each copy of the Work that the Licensor distributes or indicates, in +a notice following the copyright notice attached to the Work, a repository where +the Source Code is easily and freely accessible for as long as the Licensor +continues to distribute or communicate the Work. + +4. Limitations on copyright + +Nothing in this Licence is intended to deprive the Licensee of the benefits from +any exception or limitation to the exclusive rights of the rights owners in the +Work, of the exhaustion of those rights or of other applicable limitations +thereto. + +5. Obligations of the Licensee + +The grant of the rights mentioned above is subject to some restrictions and +obligations imposed on the Licensee. Those obligations are the following: + +Attribution right: The Licensee shall keep intact all copyright, patent or +trademarks notices and all notices that refer to the Licence and to the +disclaimer of warranties. The Licensee must include a copy of such notices and a +copy of the Licence with every copy of the Work he/she distributes or +communicates. The Licensee must cause any Derivative Work to carry prominent +notices stating that the Work has been modified and the date of modification. + +Copyleft clause: If the Licensee distributes or communicates copies of the +Original Works or Derivative Works, this Distribution or Communication will be +done under the terms of this Licence or of a later version of this Licence +unless the Original Work is expressly distributed only under this version of the +Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee +(becoming Licensor) cannot offer or impose any additional terms or conditions on +the Work or Derivative Work that alter or restrict the terms of the Licence. + +Compatibility clause: If the Licensee Distributes or Communicates Derivative +Works or copies thereof based upon both the Work and another work licensed under +a Compatible Licence, this Distribution or Communication can be done under the +terms of this Compatible Licence. For the sake of this clause, ‘Compatible +Licence’ refers to the licences listed in the appendix attached to this Licence. +Should the Licensee's obligations under the Compatible Licence conflict with +his/her obligations under this Licence, the obligations of the Compatible +Licence shall prevail. + +Provision of Source Code: When distributing or communicating copies of the Work, +the Licensee will provide a machine-readable copy of the Source Code or indicate +a repository where this Source will be easily and freely available for as long +as the Licensee continues to distribute or communicate the Work. + +Legal Protection: This Licence does not grant permission to use the trade names, +trademarks, service marks, or names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the copyright notice. + +6. Chain of Authorship + +The original Licensor warrants that the copyright in the Original Work granted +hereunder is owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each Contributor warrants that the copyright in the modifications he/she brings +to the Work are owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each time You accept the Licence, the original Licensor and subsequent +Contributors grant You a licence to their contributions to the Work, under the +terms of this Licence. + +7. Disclaimer of Warranty + +The Work is a work in progress, which is continuously improved by numerous +Contributors. It is not a finished work and may therefore contain defects or +‘bugs’ inherent to this type of development. + +For the above reason, the Work is provided under the Licence on an ‘as is’ basis +and without warranties of any kind concerning the Work, including without +limitation merchantability, fitness for a particular purpose, absence of defects +or errors, accuracy, non-infringement of intellectual property rights other than +copyright as stated in Article 6 of this Licence. + +This disclaimer of warranty is an essential part of the Licence and a condition +for the grant of any rights to the Work. + +8. Disclaimer of Liability + +Except in the cases of wilful misconduct or damages directly caused to natural +persons, the Licensor will in no event be liable for any direct or indirect, +material or moral, damages of any kind, arising out of the Licence or of the use +of the Work, including without limitation, damages for loss of goodwill, work +stoppage, computer failure or malfunction, loss of data or any commercial +damage, even if the Licensor has been advised of the possibility of such damage. +However, the Licensor will be liable under statutory product liability laws as +far such laws apply to the Work. + +9. Additional agreements + +While distributing the Work, You may choose to conclude an additional agreement, +defining obligations or services consistent with this Licence. However, if +accepting obligations, You may act only on your own behalf and on your sole +responsibility, not on behalf of the original Licensor or any other Contributor, +and only if You agree to indemnify, defend, and hold each Contributor harmless +for any liability incurred by, or claims asserted against such Contributor by +the fact You have accepted any warranty or additional liability. + +10. Acceptance of the Licence + +The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ +placed under the bottom of a window displaying the text of this Licence or by +affirming consent in any other similar way, in accordance with the rules of +applicable law. Clicking on that icon indicates your clear and irrevocable +acceptance of this Licence and all of its terms and conditions. + +Similarly, you irrevocably accept this Licence and all of its terms and +conditions by exercising any rights granted to You by Article 2 of this Licence, +such as the use of the Work, the creation by You of a Derivative Work or the +Distribution or Communication by You of the Work or copies thereof. + +11. Information to the public + +In case of any Distribution or Communication of the Work by means of electronic +communication by You (for example, by offering to download the Work from a +remote location) the distribution channel or media (for example, a website) must +at least provide to the public the information requested by the applicable law +regarding the Licensor, the Licence and the way it may be accessible, concluded, +stored and reproduced by the Licensee. + +12. Termination of the Licence + +The Licence and the rights granted hereunder will terminate automatically upon +any breach by the Licensee of the terms of the Licence. + +Such a termination will not terminate the licences of any person who has +received the Work from the Licensee under the Licence, provided such persons +remain in full compliance with the Licence. + +13. Miscellaneous + +Without prejudice of Article 9 above, the Licence represents the complete +agreement between the Parties as to the Work. + +If any provision of the Licence is invalid or unenforceable under applicable +law, this will not affect the validity or enforceability of the Licence as a +whole. Such provision will be construed or reformed so as necessary to make it +valid and enforceable. + +The European Commission may publish other linguistic versions or new versions of +this Licence or updated versions of the Appendix, so far this is required and +reasonable, without reducing the scope of the rights granted by the Licence. New +versions of the Licence will be published with a unique version number. + +All linguistic versions of this Licence, approved by the European Commission, +have identical value. Parties can take advantage of the linguistic version of +their choice. + +14. Jurisdiction + +Without prejudice to specific agreement between parties, + +- any litigation resulting from the interpretation of this License, arising + between the European Union institutions, bodies, offices or agencies, as a + Licensor, and any Licensee, will be subject to the jurisdiction of the Court + of Justice of the European Union, as laid down in article 272 of the Treaty on + the Functioning of the European Union, + +- any litigation arising between other parties and resulting from the + interpretation of this License, will be subject to the exclusive jurisdiction + of the competent court where the Licensor resides or conducts its primary + business. + +15. Applicable Law + +Without prejudice to specific agreement between parties, + +- this Licence shall be governed by the law of the European Union Member State + where the Licensor has his seat, resides or has his registered office, + +- this licence shall be governed by Belgian law if the Licensor has no seat, + residence or registered office inside a European Union Member State. + +Appendix + +‘Compatible Licences’ according to Article 5 EUPL are: + +- GNU General Public License (GPL) v. 2, v. 3 +- GNU Affero General Public License (AGPL) v. 3 +- Open Software License (OSL) v. 2.1, v. 3.0 +- Eclipse Public License (EPL) v. 1.0 +- CeCILL v. 2.0, v. 2.1 +- Mozilla Public Licence (MPL) v. 2 +- GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 +- Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for + works other than software +- European Union Public Licence (EUPL) v. 1.1, v. 1.2 +- Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong + Reciprocity (LiLiQ-R+). + +The European Commission may update this Appendix to later versions of the above +licences without producing a new version of the EUPL, as long as they provide +the rights granted in Article 2 of this Licence and protect the covered Source +Code from exclusive appropriation. + +All other changes or additions to this Appendix require the production of a new +EUPL version. diff --git a/LICENSES/EUPL-1.1.txt b/LICENSES/EUPL-1.1.txt new file mode 100644 index 0000000..3e0d612 --- /dev/null +++ b/LICENSES/EUPL-1.1.txt @@ -0,0 +1,157 @@ +European Union Public Licence V. 1.1 + +EUPL (c) the European Community 2007 + +This European Union Public Licence (the "EUPL") applies to the Work or Software (as defined below) which is provided under the terms of this Licence. Any use of the Work, other than as authorised under this Licence is prohibited (to the extent such use is covered by a right of the copyright holder of the Work). + +The Original Work is provided under the terms of this Licence when the Licensor (as defined below) has placed the following notice immediately following the copyright notice for the Original Work: + + Licensed under the EUPL V.1.1 + +or has expressed by any other mean his willingness to license under the EUPL. + +1. Definitions + +In this Licence, the following terms have the following meaning: + + - The Licence: this Licence. + + - The Original Work or the Software: the software distributed and/or communicated by the Licensor under this Licence, available as Source Code and also as Executable Code as the case may be. + + - Derivative Works: the works or software that could be created by the Licensee, based upon the Original Work or modifications thereof. This Licence does not define the extent of modification or dependence on the Original Work required in order to classify a work as a Derivative Work; this extent is determined by copyright law applicable in the country mentioned in Article 15. + + - The Work: the Original Work and/or its Derivative Works. + + - The Source Code: the human-readable form of the Work which is the most convenient for people to study and modify. + + - The Executable Code: any code which has generally been compiled and which is meant to be interpreted by a computer as a program. + + - The Licensor: the natural or legal person that distributes and/or communicates the Work under the Licence. + + - Contributor(s): any natural or legal person who modifies the Work under the Licence, or otherwise contributes to the creation of a Derivative Work. + + - The Licensee or "You": any natural or legal person who makes any usage of the Software under the terms of the Licence. + + - Distribution and/or Communication: any act of selling, giving, lending, renting, distributing, communicating, transmitting, or otherwise making available, on-line or off-line, copies of the Work or providing access to its essential functionalities at the disposal of any other natural or legal person. + +2. Scope of the rights granted by the Licence + +The Licensor hereby grants You a world-wide, royalty-free, non-exclusive, sublicensable licence to do the following, for the duration of copyright vested in the Original Work: + + - use the Work in any circumstance and for all usage, + + - reproduce the Work, + + - modify the Original Work, and make Derivative Works based upon the Work, + + - communicate to the public, including the right to make available or display the Work or copies thereof to the public and perform publicly, as the case may be, the Work, + + - distribute the Work or copies thereof, + + - lend and rent the Work or copies thereof, + + - sub-license rights in the Work or copies thereof. + +Those rights can be exercised on any media, supports and formats, whether now known or later invented, as far as the applicable law permits so. + +In the countries where moral rights apply, the Licensor waives his right to exercise his moral right to the extent allowed by law in order to make effective the licence of the economic rights here above listed. + +The Licensor grants to the Licensee royalty-free, non exclusive usage rights to any patents held by the Licensor, to the extent necessary to make use of the rights granted on the Work under this Licence. + +3. Communication of the Source Code + +The Licensor may provide the Work either in its Source Code form, or as Executable Code. If the Work is provided as Executable Code, the Licensor provides in addition a machine-readable copy of the Source Code of the Work along with each copy of the Work that the Licensor distributes or indicates, in a notice following the copyright notice attached to the Work, a repository where the Source Code is easily and freely accessible for as long as the Licensor continues to distribute and/or communicate the Work. + +4. Limitations on copyright + +Nothing in this Licence is intended to deprive the Licensee of the benefits from any exception or limitation to the exclusive rights of the rights owners in the Original Work or Software, of the exhaustion of those rights or of other applicable limitations thereto. + +5. Obligations of the Licensee + +The grant of the rights mentioned above is subject to some restrictions and obligations imposed on the Licensee. Those obligations are the following: + +Attribution right: the Licensee shall keep intact all copyright, patent or trademarks notices and all notices that refer to the Licence and to the disclaimer of warranties. The Licensee must include a copy of such notices and a copy of the Licence with every copy of the Work he/she distributes and/or communicates. The Licensee must cause any Derivative Work to carry prominent notices stating that the Work has been modified and the date of modification. + +Copyleft clause: If the Licensee distributes and/or communicates copies of the Original Works or Derivative Works based upon the Original Work, this Distribution and/or Communication will be done under the terms of this Licence or of a later version of this Licence unless the Original Work is expressly distributed only under this version of the Licence. The Licensee (becoming Licensor) cannot offer or impose any additional terms or conditions on the Work or Derivative Work that alter or restrict the terms of the Licence. + +Compatibility clause: If the Licensee Distributes and/or Communicates Derivative Works or copies thereof based upon both the Original Work and another work licensed under a Compatible Licence, this Distribution and/or Communication can be done under the terms of this Compatible Licence. For the sake of this clause, "Compatible Licence," refers to the licences listed in the appendix attached to this Licence. Should the Licensee's obligations under the Compatible Licence conflict with his/her obligations under this Licence, the obligations of the Compatible Licence shall prevail. + +Provision of Source Code: When distributing and/or communicating copies of the Work, the Licensee will provide a machine-readable copy of the Source Code or indicate a repository where this Source will be easily and freely available for as long as the Licensee continues to distribute and/or communicate the Work. + +Legal Protection: This Licence does not grant permission to use the trade names, trademarks, service marks, or names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the copyright notice. + +6. Chain of Authorship + +The original Licensor warrants that the copyright in the Original Work granted hereunder is owned by him/her or licensed to him/her and that he/she has the power and authority to grant the Licence. + +Each Contributor warrants that the copyright in the modifications he/she brings to the Work are owned by him/her or licensed to him/her and that he/she has the power and authority to grant the Licence. + +Each time You accept the Licence, the original Licensor and subsequent Contributors grant You a licence to their contributions to the Work, under the terms of this Licence. + +7. Disclaimer of Warranty + +The Work is a work in progress, which is continuously improved by numerous contributors. It is not a finished work and may therefore contain defects or "bugs" inherent to this type of software development. + +For the above reason, the Work is provided under the Licence on an "as is" basis and without warranties of any kind concerning the Work, including without limitation merchantability, fitness for a particular purpose, absence of defects or errors, accuracy, non-infringement of intellectual property rights other than copyright as stated in Article 6 of this Licence. + +This disclaimer of warranty is an essential part of the Licence and a condition for the grant of any rights to the Work. + +8. Disclaimer of Liability + +Except in the cases of wilful misconduct or damages directly caused to natural persons, the Licensor will in no event be liable for any direct or indirect, material or moral, damages of any kind, arising out of the Licence or of the use of the Work, including without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, loss of data or any commercial damage, even if the Licensor has been advised of the possibility of such damage. However, the Licensor will be liable under statutory product liability laws as far such laws apply to the Work. + +9. Additional agreements + +While distributing the Original Work or Derivative Works, You may choose to conclude an additional agreement to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or services consistent with this Licence. However, in accepting such obligations, You may act only on your own behalf and on your sole responsibility, not on behalf of the original Licensor or any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against such Contributor by the fact You have accepted any such warranty or additional liability. + +10. Acceptance of the Licence + +The provisions of this Licence can be accepted by clicking on an icon "I agree" placed under the bottom of a window displaying the text of this Licence or by affirming consent in any other similar way, in accordance with the rules of applicable law. Clicking on that icon indicates your clear and irrevocable acceptance of this Licence and all of its terms and conditions. + +Similarly, you irrevocably accept this Licence and all of its terms and conditions by exercising any rights granted to You by Article 2 of this Licence, such as the use of the Work, the creation by You of a Derivative Work or the Distribution and/or Communication by You of the Work or copies thereof. + +11. Information to the public + +In case of any Distribution and/or Communication of the Work by means of electronic communication by You (for example, by offering to download the Work from a remote location) the distribution channel or media (for example, a website) must at least provide to the public the information requested by the applicable law regarding the Licensor, the Licence and the way it may be accessible, concluded, stored and reproduced by the Licensee. + +12. Termination of the Licence + +The Licence and the rights granted hereunder will terminate automatically upon any breach by the Licensee of the terms of the Licence. Such a termination will not terminate the licences of any person who has received the Work from the Licensee under the Licence, provided such persons remain in full compliance with the Licence. + +13. Miscellaneous + +Without prejudice of Article 9 above, the Licence represents the complete agreement between the Parties as to the Work licensed hereunder. + +If any provision of the Licence is invalid or unenforceable under applicable law, this will not affect the validity or enforceability of the Licence as a whole. Such provision will be construed and/or reformed so as necessary to make it valid and enforceable. + +The European Commission may publish other linguistic versions and/or new versions of this Licence, so far this is required and reasonable, without reducing the scope of the rights granted by the Licence. New versions of the Licence will be published with a unique version number. + +All linguistic versions of this Licence, approved by the European Commission, have identical value. Parties can take advantage of the linguistic version of their choice. + +14. Jurisdiction + +Any litigation resulting from the interpretation of this License, arising between the European Commission, as a Licensor, and any Licensee, will be subject to the jurisdiction of the Court of Justice of the European Communities, as laid down in article 238 of the Treaty establishing the European Community. + +Any litigation arising between Parties, other than the European Commission, and resulting from the interpretation of this License, will be subject to the exclusive jurisdiction of the competent court where the Licensor resides or conducts its primary business. + +15. Applicable Law + +This Licence shall be governed by the law of the European Union country where the Licensor resides or has his registered office. + +This licence shall be governed by the Belgian law if: + + - a litigation arises between the European Commission, as a Licensor, and any Licensee; + + - the Licensor, other than the European Commission, has no residence or registered office inside a European Union country. + + + +Appendix + +"Compatible Licences" according to article 5 EUPL are: + + - GNU General Public License (GNU GPL) v. 2 + - Open Software License (OSL) v. 2.1, v. 3.0 + - Common Public License v. 1.0 + - Eclipse Public License v. 1.0 + - Cecill v. 2.0 diff --git a/README.md b/README.md index e16b97f..32c52f5 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,9 @@ + + # Dynix — WIP modular dynamicism for NixOS systems Dynix is a prototype for modifying an append-only NixOS configuration, and dynamically applying that configuration. diff --git a/default.nix b/default.nix index 64072a2..5c43a55 100644 --- a/default.nix +++ b/default.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs ? import { }, qpkgs ? let diff --git a/flake.lock.license b/flake.lock.license new file mode 100644 index 0000000..39b098c --- /dev/null +++ b/flake.lock.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2026 Qyriad + +SPDX-License-Identifier: EUPL-1.1 diff --git a/flake.nix b/flake.nix index 276cfb0..798c7e7 100644 --- a/flake.nix +++ b/flake.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { inputs = { nixpkgs = { diff --git a/modules/dynamicism/default.nix b/modules/dynamicism/default.nix index 1fca96c..9703245 100644 --- a/modules/dynamicism/default.nix +++ b/modules/dynamicism/default.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { ... }: { diff --git a/modules/dynamicism/distccd.nix b/modules/dynamicism/distccd.nix index 3b87764..bf027f2 100644 --- a/modules/dynamicism/distccd.nix +++ b/modules/dynamicism/distccd.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, ... }: let cfg = config.services.distccd; diff --git a/modules/dynamicism/dynamicism.nix b/modules/dynamicism/dynamicism.nix index 75f9fcb..3f98b09 100644 --- a/modules/dynamicism/dynamicism.nix +++ b/modules/dynamicism/dynamicism.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, options, ... }: let inherit (lib.options) diff --git a/modules/dynamicism/gotosocial.nix b/modules/dynamicism/gotosocial.nix index b1fedc6..449d714 100644 --- a/modules/dynamicism/gotosocial.nix +++ b/modules/dynamicism/gotosocial.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, ... }: let settingsFormat = pkgs.formats.yaml { }; diff --git a/modules/dynamicism/harmonia.nix b/modules/dynamicism/harmonia.nix index e4284d0..8dbfead 100644 --- a/modules/dynamicism/harmonia.nix +++ b/modules/dynamicism/harmonia.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, ... }: let cfg = config.dynamicism.for.harmonia; diff --git a/modules/dynamicism/lib.nix b/modules/dynamicism/lib.nix index ec41ab7..d3db655 100644 --- a/modules/dynamicism/lib.nix +++ b/modules/dynamicism/lib.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { lib ? import , }: let diff --git a/modules/dynamicism/submodule.nix b/modules/dynamicism/submodule.nix index 4100217..15b5774 100644 --- a/modules/dynamicism/submodule.nix +++ b/modules/dynamicism/submodule.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { name, lib, diff --git a/modules/dynamicism/tzupdate.nix b/modules/dynamicism/tzupdate.nix index 73f634d..b284cf9 100644 --- a/modules/dynamicism/tzupdate.nix +++ b/modules/dynamicism/tzupdate.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, ... }: let cfg = config.dynamicism.for.tzupdate; diff --git a/package.nix b/package.nix index 6bc26bd..6b7cee9 100644 --- a/package.nix +++ b/package.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { lib, clangStdenv, @@ -77,6 +81,8 @@ in { meta = { mainProgram = "dynix"; + description = "The Rust part of Dynix"; + inherit (self.meta) license; }; }; @@ -105,6 +111,11 @@ in { runHook postInstall ''; + + meta = { + description = "The NixOS modules part of Dynix"; + inherit (self.meta) license; + }; }; # @@ -150,6 +161,7 @@ in { The `dynix` passthru attr is a shortcut for the modules output *with* the modules prefix, and thus `dynix.dynix` can be passed directly to `imports = [`. ''; + license = with lib.licenses; [ eupl12 ]; mainProgram = "dynix"; outputsToInstall = [ "out" "modules" ]; }; diff --git a/shell.nix b/shell.nix index 4b93b7f..37ad241 100644 --- a/shell.nix +++ b/shell.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs ? import { config = { diff --git a/src/args.rs b/src/args.rs index 0028e0f..5a0bda7 100644 --- a/src/args.rs +++ b/src/args.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + use std::{ env, sync::{Arc, LazyLock}, diff --git a/src/color.rs b/src/color.rs index 1e420f6..9c6591c 100644 --- a/src/color.rs +++ b/src/color.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + use std::{ env, sync::{LazyLock, OnceLock}, diff --git a/src/lib.rs b/src/lib.rs index cf7839a..e82f63d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + use std::{ iter, sync::{Arc, LazyLock}, diff --git a/src/line.rs b/src/line.rs index e7ec169..c1470c9 100644 --- a/src/line.rs +++ b/src/line.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + use std::num::NonZeroU64; #[allow(unused_imports)] diff --git a/src/main.rs b/src/main.rs index ef00265..196b904 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + use std::io::{self, IsTerminal}; use std::process::ExitCode; use std::{error::Error as StdError, sync::Arc}; diff --git a/src/nixcmd.rs b/src/nixcmd.rs index 3121565..980d8a0 100644 --- a/src/nixcmd.rs +++ b/src/nixcmd.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + #[allow(unused_imports)] use crate::prelude::*; diff --git a/src/source.rs b/src/source.rs index c0099a1..ae90189 100644 --- a/src/source.rs +++ b/src/source.rs @@ -1,3 +1,7 @@ +// SPDX-FileCopyrightText: 2026 Qyriad +// +// SPDX-License-Identifier: EUPL-1.1 + use std::{ cell::{Ref, RefCell}, hash::Hash, diff --git a/tests/README.md b/tests/README.md index 6ef7869..1a560ef 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,3 +1,9 @@ + + # Notes for running the tests The VM tests do Nix builds inside the VMs, so they have writable Nix stores. diff --git a/tests/default.nix b/tests/default.nix index 929458e..57b1c94 100644 --- a/tests/default.nix +++ b/tests/default.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs ? import { }, qpkgs ? let diff --git a/tests/distccd/configuration.nix b/tests/distccd/configuration.nix index b0d90b5..05bea65 100644 --- a/tests/distccd/configuration.nix +++ b/tests/distccd/configuration.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { ... }: { diff --git a/tests/distccd/test-script.py b/tests/distccd/test-script.py index 8a34d8a..a5e35ee 100644 --- a/tests/distccd/test-script.py +++ b/tests/distccd/test-script.py @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + import argparse import functools import shlex diff --git a/tests/distccd/test.nix b/tests/distccd/test.nix index ad9ac73..852eac2 100644 --- a/tests/distccd/test.nix +++ b/tests/distccd/test.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { mkDynixConfigurationDotNix, config, ... }: let testName = config.name; diff --git a/tests/dynix-vm-configuration.nix b/tests/dynix-vm-configuration.nix index 9148302..2e299c3 100644 --- a/tests/dynix-vm-configuration.nix +++ b/tests/dynix-vm-configuration.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, modulesPath, ... }: let moduleList = import (modulesPath + "/module-list.nix"); diff --git a/tests/gotosocial/configuration.nix b/tests/gotosocial/configuration.nix index 8ada5c8..a069b34 100644 --- a/tests/gotosocial/configuration.nix +++ b/tests/gotosocial/configuration.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { pkgs, lib, config, modulesPath, ... }: let name = config.networking.hostName; diff --git a/tests/gotosocial/test-script.py b/tests/gotosocial/test-script.py index d41d3d1..eca3044 100644 --- a/tests/gotosocial/test-script.py +++ b/tests/gotosocial/test-script.py @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + from pathlib import Path import shlex import textwrap diff --git a/tests/gotosocial/test.nix b/tests/gotosocial/test.nix index ccb71f6..9215d1e 100644 --- a/tests/gotosocial/test.nix +++ b/tests/gotosocial/test.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { mkDynixConfigurationDotNix, config, ... }: let testName = config.name; diff --git a/tests/harmonia/configuration.nix b/tests/harmonia/configuration.nix index d5cc833..2fd2bcf 100644 --- a/tests/harmonia/configuration.nix +++ b/tests/harmonia/configuration.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { ... }: { diff --git a/tests/harmonia/test-script.py b/tests/harmonia/test-script.py index 376e946..c40e130 100644 --- a/tests/harmonia/test-script.py +++ b/tests/harmonia/test-script.py @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + import functools from pathlib import Path import shlex diff --git a/tests/harmonia/test.nix b/tests/harmonia/test.nix index 25fcfbf..8fcc19b 100644 --- a/tests/harmonia/test.nix +++ b/tests/harmonia/test.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { mkDynixConfigurationDotNix, config, ... }: let testName = config.name; diff --git a/tests/mk-test-configuration-dot-nix.nix b/tests/mk-test-configuration-dot-nix.nix index 6b7dc25..fd9c5a8 100644 --- a/tests/mk-test-configuration-dot-nix.nix +++ b/tests/mk-test-configuration-dot-nix.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { lib, stdenvNoCC, diff --git a/tests/module-allow-rebuild-in-vm.nix b/tests/module-allow-rebuild-in-vm.nix index fa14e9f..50a002e 100644 --- a/tests/module-allow-rebuild-in-vm.nix +++ b/tests/module-allow-rebuild-in-vm.nix @@ -1,3 +1,7 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + { name, lib, config, ... }: { From fa81457170baabb04afd2766d1709d879c7646f9 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Thu, 5 Mar 2026 16:19:06 +0100 Subject: [PATCH 09/19] packaging: checkMeta --- default.nix | 2 +- flake.nix | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/default.nix b/default.nix index 5c43a55..d6a38de 100644 --- a/default.nix +++ b/default.nix @@ -3,7 +3,7 @@ # SPDX-License-Identifier: EUPL-1.1 { - pkgs ? import { }, + pkgs ? import { config.checkMeta = true; }, qpkgs ? let src = fetchTarball "https://github.com/Qyriad/nur-packages/archive/main.tar.gz"; in import src { inherit pkgs; }, diff --git a/flake.nix b/flake.nix index 798c7e7..6d53131 100644 --- a/flake.nix +++ b/flake.nix @@ -26,7 +26,7 @@ fenix, qyriad-nur, }: flake-utils.lib.eachDefaultSystem (system: let - pkgs = import nixpkgs { inherit system; }; + pkgs = import nixpkgs { inherit system; config.checkMeta = true; }; qpkgs = import qyriad-nur { inherit pkgs; }; inherit (qpkgs) lib; fenixLib = import fenix { inherit pkgs; }; From e42e76d16759782b3a57e84ed70947a5179d1876 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Thu, 5 Mar 2026 17:23:17 +0100 Subject: [PATCH 10/19] flake.lock: Update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Flake lock file updates: • Updated input 'fenix': 'github:nix-community/fenix/2e3759c5ef51f320eb0aaf83f2a32baae33db237' (2026-02-16) → 'github:nix-community/fenix/6dfabfd5c569304182ca0b670c0d5765acbd1081' (2026-03-05) • Updated input 'nixpkgs': 'github:NixOS/nixpkgs/fef9403a3e4d31b0a23f0bacebbec52c248fbb51' (2026-02-08) → 'github:NixOS/nixpkgs/66d9241e3dc2296726dc522e62dbfe89c7b449f3' (2026-03-05) • Updated input 'qyriad-nur': 'github:Qyriad/nur-packages/23716e0347215a721f9489515a0c3dc91122c7d5' (2026-02-06) → 'github:Qyriad/nur-packages/3d535db1396b61d78fb5e3debcaf8c8bc0aa13ee' (2026-03-03) --- flake.lock | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/flake.lock b/flake.lock index f07fa2c..52ff876 100644 --- a/flake.lock +++ b/flake.lock @@ -3,11 +3,11 @@ "fenix": { "flake": false, "locked": { - "lastModified": 1771226183, - "narHash": "sha256-AbaMtaLbe37l2VI/KSRk63PuBnX/YDDFL0G1eFMbvwI=", + "lastModified": 1772694321, + "narHash": "sha256-nfKwfaD9brXQSxWEkXAEoDZZVhhHPP7A6CH5pLnY6kQ=", "owner": "nix-community", "repo": "fenix", - "rev": "2e3759c5ef51f320eb0aaf83f2a32baae33db237", + "rev": "6dfabfd5c569304182ca0b670c0d5765acbd1081", "type": "github" }, "original": { @@ -37,11 +37,11 @@ "nixpkgs": { "flake": false, "locked": { - "lastModified": 1770537093, - "narHash": "sha256-pF1quXG5wsgtyuPOHcLfYg/ft/QMr8NnX0i6tW2187s=", + "lastModified": 1772674223, + "narHash": "sha256-/suKbHSaSmuC9UY7G0VRQ3aO+QKqxAQPQ19wG7QNkF8=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "fef9403a3e4d31b0a23f0bacebbec52c248fbb51", + "rev": "66d9241e3dc2296726dc522e62dbfe89c7b449f3", "type": "github" }, "original": { @@ -54,11 +54,11 @@ "qyriad-nur": { "flake": false, "locked": { - "lastModified": 1770385314, - "narHash": "sha256-zDlvon/yF9STxGi3l38j9EgTFHBHOjCJlP8mMX7zw5M=", + "lastModified": 1772549724, + "narHash": "sha256-JaCtNNo62qk/dgxcNgSHRrVgsH0y+RBD3tuUzB3Fqis=", "owner": "Qyriad", "repo": "nur-packages", - "rev": "23716e0347215a721f9489515a0c3dc91122c7d5", + "rev": "3d535db1396b61d78fb5e3debcaf8c8bc0aa13ee", "type": "github" }, "original": { From b49032d5f4e6f922ae2bab6200018e01f59a532c Mon Sep 17 00:00:00 2001 From: Qyriad Date: Tue, 10 Mar 2026 16:19:22 +0100 Subject: [PATCH 11/19] flake.lock: Update MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Flake lock file updates: • Updated input 'fenix': 'github:nix-community/fenix/6dfabfd5c569304182ca0b670c0d5765acbd1081' (2026-03-05) → 'github:nix-community/fenix/64407ddb1932af06ed5cd711f6a2ed946b2548b9' (2026-03-10) • Updated input 'nixpkgs': 'github:NixOS/nixpkgs/66d9241e3dc2296726dc522e62dbfe89c7b449f3' (2026-03-05) → 'github:NixOS/nixpkgs/608d0cadfed240589a7eea422407a547ad626a14' (2026-03-08) • Updated input 'qyriad-nur': 'github:Qyriad/nur-packages/3d535db1396b61d78fb5e3debcaf8c8bc0aa13ee' (2026-03-03) → 'github:Qyriad/nur-packages/c94411f1020bc95f6f90f3d3b8ec1207ab635cd9' (2026-03-10) --- flake.lock | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/flake.lock b/flake.lock index 52ff876..3173a57 100644 --- a/flake.lock +++ b/flake.lock @@ -3,11 +3,11 @@ "fenix": { "flake": false, "locked": { - "lastModified": 1772694321, - "narHash": "sha256-nfKwfaD9brXQSxWEkXAEoDZZVhhHPP7A6CH5pLnY6kQ=", + "lastModified": 1773126504, + "narHash": "sha256-/iXlg2V5UMlgCmyRHkPHjlD6NdMfFOnwFMvH7REigD4=", "owner": "nix-community", "repo": "fenix", - "rev": "6dfabfd5c569304182ca0b670c0d5765acbd1081", + "rev": "64407ddb1932af06ed5cd711f6a2ed946b2548b9", "type": "github" }, "original": { @@ -37,11 +37,11 @@ "nixpkgs": { "flake": false, "locked": { - "lastModified": 1772674223, - "narHash": "sha256-/suKbHSaSmuC9UY7G0VRQ3aO+QKqxAQPQ19wG7QNkF8=", + "lastModified": 1772956932, + "narHash": "sha256-M0yS4AafhKxPPmOHGqIV0iKxgNO8bHDWdl1kOwGBwRY=", "owner": "NixOS", "repo": "nixpkgs", - "rev": "66d9241e3dc2296726dc522e62dbfe89c7b449f3", + "rev": "608d0cadfed240589a7eea422407a547ad626a14", "type": "github" }, "original": { @@ -54,11 +54,11 @@ "qyriad-nur": { "flake": false, "locked": { - "lastModified": 1772549724, - "narHash": "sha256-JaCtNNo62qk/dgxcNgSHRrVgsH0y+RBD3tuUzB3Fqis=", + "lastModified": 1773152764, + "narHash": "sha256-y1DgLrzhBUwAFMuk4rUT4aHSXwPeteQOJCukAXb6FdE=", "owner": "Qyriad", "repo": "nur-packages", - "rev": "3d535db1396b61d78fb5e3debcaf8c8bc0aa13ee", + "rev": "c94411f1020bc95f6f90f3d3b8ec1207ab635cd9", "type": "github" }, "original": { From b48209a33accaa9a8766b6dc77782a6f9f997c63 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Tue, 10 Mar 2026 18:46:55 +0100 Subject: [PATCH 12/19] fix a bunch of warnings! --- src/args.rs | 62 --------------------------------------------------- src/color.rs | 11 ++++----- src/lib.rs | 13 ++++------- src/line.rs | 3 --- src/main.rs | 1 - src/source.rs | 4 ++-- 6 files changed, 10 insertions(+), 84 deletions(-) diff --git a/src/args.rs b/src/args.rs index 5a0bda7..8c528a2 100644 --- a/src/args.rs +++ b/src/args.rs @@ -11,50 +11,6 @@ use clap::ColorChoice; use crate::prelude::*; -//#[derive(Debug, Clone, PartialEq)] -//#[derive(clap::Args)] -//#[group(required = true, multiple = false)] -//pub enum Config -//{ -// Flake, -//} - -#[derive(Debug, Clone, PartialEq)] -pub struct NixOsOption { - name: String, - value: String, -} - -#[derive(Debug, Clone, PartialEq)] -pub struct NixOptionParseError(pub Box); - -impl Display for NixOptionParseError { - fn fmt(&self, f: &mut Formatter) -> FmtResult { - write!(f, "{}", self.0) - } -} - -impl From for NixOptionParseError { - fn from(value: String) -> Self { - Self(value.into_boxed_str()) - } -} - -impl StdError for NixOptionParseError {} - -impl FromStr for NixOsOption { - type Err = NixOptionParseError; - - fn from_str(s: &str) -> Result { - // FIXME: allow escaping equals sign? - let Some(delim) = s.find('=') else { - return Err(format!("equals sign not found in {}", s).into()); - }; - - todo!(); - } -} - #[derive(Debug, Clone, PartialEq, clap::Parser)] pub struct AppendCmd { #[arg(required = true)] @@ -64,15 +20,10 @@ pub struct AppendCmd { pub value: Arc, } -#[derive(Debug, Clone, PartialEq, clap::Parser)] -pub struct DeltaCmd {} - #[derive(Debug, Clone, PartialEq, clap::Subcommand)] #[command(flatten_help = true)] pub enum Subcommand { Append(AppendCmd), - // TODO: rename - Delta(DeltaCmd), } static DEFAULT_PATH: LazyLock> = LazyLock::new(|| { @@ -114,16 +65,3 @@ pub struct Args { #[command(subcommand)] pub subcommand: Subcommand, } -///// Flakeref to a base configuration to modify. -//#[arg(group = "config", long, default_value("."))] -//#[arg(long, default_value(Some(".")))] -//flake: Option>>, -// -//#[arg(group = "config", long)] -//expr: Option, - -//impl Parser { -// fn eval_cmd(&self) { -// todo!(); -// } -//} diff --git a/src/color.rs b/src/color.rs index 9c6591c..f51dc77 100644 --- a/src/color.rs +++ b/src/color.rs @@ -2,6 +2,9 @@ // // SPDX-License-Identifier: EUPL-1.1 +// The entire point of this module. +#![allow(clippy::declare_interior_mutable_const)] + use std::{ env, sync::{LazyLock, OnceLock}, @@ -22,13 +25,7 @@ fn is_color_reqd() -> bool { fn is_clicolor_forced() -> bool { env::var("CLICOLOR_FORCE") - .map(|value| { - if value.is_empty() || value == "0" { - false - } else { - true - } - }) + .map(|value| !(value.is_empty() || value == "0")) .unwrap_or(false) } diff --git a/src/lib.rs b/src/lib.rs index e82f63d..58d98a1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -41,7 +41,7 @@ pub(crate) mod prelude { use prelude::*; pub mod args; -pub use args::{AppendCmd, Args, DeltaCmd}; +pub use args::{AppendCmd, Args}; mod color; pub use color::{_CLI_ENABLE_COLOR, SHOULD_COLOR}; pub mod line; @@ -80,11 +80,6 @@ static MK_OVERRIDE_RE: LazyLock = LazyLock::new(|| { Regex::new(r"(?-u)\bmkOverride\s+\((?[\d-]+)\)").unwrap() }); -#[tracing::instrument(level = "debug")] -pub fn do_delta(args: Arc, delta_args: DeltaCmd) -> Result<(), BoxDynError> { - todo!(); -} - #[tracing::instrument(level = "debug")] pub fn do_append(args: Arc, append_args: AppendCmd) -> Result<(), BoxDynError> { let filepath = Path::new(&args.file); @@ -109,9 +104,9 @@ pub fn do_append(args: Arc, append_args: AppendCmd) -> Result<(), BoxDynEr let new_pri_line = get_next_prio_line( source_file.clone(), - append_args.name.into(), + append_args.name, new_pri, - append_args.value.into(), + append_args.value, )?; debug!("new_pri_line={new_pri_line}"); @@ -154,7 +149,7 @@ fn maybe_extract_prio_from_line(line: &SourceLine) -> Option { pub fn get_where(dynamic_nix: SourceFile) -> Result { let lines = dynamic_nix.lines()?; let prio = lines - .into_iter() + .iter() .filter_map(maybe_extract_prio_from_line) .sorted_unstable() .next() // Priorities with lower integer values are "stronger" priorities. diff --git a/src/line.rs b/src/line.rs index c1470c9..aa0d706 100644 --- a/src/line.rs +++ b/src/line.rs @@ -7,7 +7,6 @@ use std::num::NonZeroU64; #[allow(unused_imports)] use crate::prelude::*; - #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Line(pub u64); @@ -43,5 +42,3 @@ impl Line { self.0 + 1 } } - -pub struct Lines(Vec); diff --git a/src/main.rs b/src/main.rs index 196b904..c45a56a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -34,7 +34,6 @@ fn main_wrapped() -> Result<(), Box> { use dynix::args::Subcommand::*; match &args.subcommand { Append(append_args) => dynix::do_append(args.clone(), append_args.clone())?, - Delta(delta_args) => dynix::do_delta(args.clone(), delta_args.clone())?, }; } diff --git a/src/source.rs b/src/source.rs index ae90189..287f72e 100644 --- a/src/source.rs +++ b/src/source.rs @@ -40,7 +40,7 @@ pub fn replace_file<'a>( drop(writer); // Rename the temporary file to the new file, which is atomic (TODO: I think). - fs_err::rename(&tmp_path, &path)?; + fs_err::rename(&tmp_path, path)?; Ok(()) } @@ -62,7 +62,7 @@ impl SourceLine { } pub fn text_bytes(&self) -> Arc<[u8]> { - let len: usize = self.text.as_bytes().len(); + let len: usize = self.text.len(); // We need to consume an Arc, but we are &self. let text = Arc::clone(&self.text); From 61e66599f76d2a15efe9490c2d89259f8b1ca1d5 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Tue, 10 Mar 2026 19:35:15 +0100 Subject: [PATCH 13/19] maint: update Cargo.lock clap v4.5.58 -> v4.5.60 clap_builder v4.5.58 -> v4.5.60 libc v0.2.182 -> v0.2.183 linux-raw-sys v0.11.0 -> v0.12.1 owo-colors v4.2.3 -> v4.3.0 pin-project-lite v0.2.16 -> v0.2.17 quote v1.0.44 -> v1.0.45 regex-syntax v0.8.9 -> v0.8.10 rustix v1.1.3 -> v1.1.4 syn v2.0.116 -> v2.0.117 --- Cargo.lock | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index cba4ce7..f1f3373 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -87,9 +87,9 @@ checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" [[package]] name = "clap" -version = "4.5.58" +version = "4.5.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "63be97961acde393029492ce0be7a1af7e323e6bae9511ebfac33751be5e6806" +checksum = "2797f34da339ce31042b27d23607e051786132987f595b02ba4f6a6dffb7030a" dependencies = [ "clap_builder", "clap_derive", @@ -97,9 +97,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.58" +version = "4.5.60" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7f13174bda5dfd69d7e947827e5af4b0f2f94a4a3ee92912fba07a66150f21e2" +checksum = "24a241312cea5059b13574bb9b3861cabf758b879c15190b37b6d6fd63ab6876" dependencies = [ "anstream", "anstyle", @@ -273,15 +273,15 @@ checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" [[package]] name = "libc" -version = "0.2.182" +version = "0.2.183" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112" +checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" [[package]] name = "linux-raw-sys" -version = "0.11.0" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" [[package]] name = "lock_api" @@ -348,9 +348,9 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" [[package]] name = "owo-colors" -version = "4.2.3" +version = "4.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c6901729fa79e91a0913333229e9ca5dc725089d1c363b2f4b4760709dc4a52" +checksum = "d211803b9b6b570f68772237e415a029d5a50c65d382910b879fb19d3271f94d" dependencies = [ "supports-color 2.1.0", "supports-color 3.0.2", @@ -381,9 +381,9 @@ dependencies = [ [[package]] name = "pin-project-lite" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" [[package]] name = "proc-macro2" @@ -408,9 +408,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.44" +version = "1.0.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" dependencies = [ "proc-macro2", ] @@ -455,15 +455,15 @@ checksum = "cab834c73d247e67f4fae452806d17d3c7501756d98c8808d7c9c7aa7d18f973" [[package]] name = "regex-syntax" -version = "0.8.9" +version = "0.8.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c" +checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a" [[package]] name = "rustix" -version = "1.1.3" +version = "1.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" dependencies = [ "bitflags", "errno", @@ -575,9 +575,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.116" +version = "2.0.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3df424c70518695237746f84cede799c9c58fcb37450d7b23716568cc8bc69cb" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" dependencies = [ "proc-macro2", "quote", From 117652a6a6ee616635d8e1c6536fa9d8b546df87 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Tue, 10 Mar 2026 19:56:41 +0100 Subject: [PATCH 14/19] maint: put cargo completions in the dev shell --- package.nix | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/package.nix b/package.nix index 6b7cee9..8725d02 100644 --- a/package.nix +++ b/package.nix @@ -127,9 +127,14 @@ in { mkShell, python3Packages, fenixToolchain, + cargo, }: let mkShell' = mkShell.override { inherit stdenv; }; pyEnv = python3Packages.python.withPackages (p: [ p.beartype ]); + # Fenix's Cargo doesn't have completions, but Nixpkgs' does. + cargoCompletions = linkFarm "cargo-bash-completions" { + "share/bash-completion" = cargo + "/share/bash-completion"; + }; in mkShell' { name = "devshell-for-${self.name}"; inputsFrom = [ self ]; @@ -137,12 +142,15 @@ in { pyEnv stdenv.cc fenixToolchain + cargoCompletions ]; env.PYTHONPATH = [ "${pyEnv}/${pyEnv.sitePackages}" # Cursed. "${path}/nixos/lib/test-driver/src" ] |> lib.concatStringsSep ":"; + + passthru = { inherit cargoCompletions; }; }; passthru.modulesPath = self.modules + "/share/nixos/modules"; From a9068f86f37fd88cf7b23f06c85022bfd2131bfc Mon Sep 17 00:00:00 2001 From: Qyriad Date: Wed, 11 Mar 2026 14:26:59 +0100 Subject: [PATCH 15/19] maint: remove unnecessary srcs/phases in derivations --- package.nix | 13 ++----------- 1 file changed, 2 insertions(+), 11 deletions(-) diff --git a/package.nix b/package.nix index 8725d02..e5c4f98 100644 --- a/package.nix +++ b/package.nix @@ -28,24 +28,15 @@ in { outputs = [ "out" "modules" ]; + # These are propagated to sub-derivations. doCheck = true; doInstallCheck = true; - phases = [ "unpackPhase" "patchPhase" "installPhase" ]; - - src = linkFarm "dynix-source" { - inherit (self) dynixCommand dynixModules; - }; - - installPhase = '' - runHook preInstall - + buildCommand = '' mkdir -p "$out" cp -r --reflink=auto "$dynixCommand/"* "$out/" mkdir -p "$modules" cp -r --reflink=auto "$dynixModules/"* "$modules/" - - runHook postInstall ''; # From a72a48f92b212733364d967fbef2488275f8c2bf Mon Sep 17 00:00:00 2001 From: Qyriad Date: Wed, 11 Mar 2026 14:26:59 +0100 Subject: [PATCH 16/19] add types in preparation for non-blocking stdin --- Cargo.lock | 1 + Cargo.toml | 1 + src/daemon_io.rs | 106 +++++++++++++++++++++++++++++++++++++++++++++++ src/lib.rs | 4 +- 4 files changed, 111 insertions(+), 1 deletion(-) create mode 100644 src/daemon_io.rs diff --git a/Cargo.lock b/Cargo.lock index f1f3373..9c57e7d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -160,6 +160,7 @@ dependencies = [ "libc", "regex", "regex-lite", + "rustix", "serde", "serde_json", "tap", diff --git a/Cargo.toml b/Cargo.toml index 41fe13c..3223b6b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -29,6 +29,7 @@ itertools = "0.14.0" libc = { version = "0.2.180", features = ["extra_traits"] } regex = { version = "1.12.3", optional = true } regex-lite = { version = "0.1.9", optional = true } +rustix = { version = "1.1.4", features = ["event", "fs"] } serde = { version = "1.0.228", features = ["derive"] } serde_json = "1.0.149" tap = "1.0.1" diff --git a/src/daemon_io.rs b/src/daemon_io.rs new file mode 100644 index 0000000..f080ca8 --- /dev/null +++ b/src/daemon_io.rs @@ -0,0 +1,106 @@ +use std::{ + mem::ManuallyDrop, + os::{ + fd::{AsFd, AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}, + unix::prelude::RawFd, + }, +}; + +use rustix::{ + fs::{OFlags, fcntl_getfl, fcntl_setfl}, + io::Errno, +}; + +use crate::prelude::*; + +/// An [`OwnedFd`] that captures file status flags on init and restores them on: +/// +/// - [`IntoRawFd`] +/// - [`drop()`] +#[derive(Debug)] +pub struct OwnedFdWithFlags { + fd: OwnedFd, + oflags: OFlags, +} + +impl OwnedFdWithFlags { + pub fn new(fd: OwnedFd) -> Result { + let oflags = fcntl_getfl(&fd)?; + Ok(Self { fd, oflags }) + } + + /// If, for some ungodly reason, `fcntl(F_GETFL)` fails, then empty flags are used. + /// Empty flags should not be restored on close. + /// + /// I'm pretty sure this should never happen if the program is IO-safe. + pub fn new_with_fallback(fd: OwnedFd) -> Self { + let oflags = Self::get_flags_or_log(fd.as_fd()); + Self { fd, oflags } + } +} + +impl Drop for OwnedFdWithFlags { + fn drop(&mut self) { + self.restore_flags_or_log(); + } +} + +/// Private helpers. +impl OwnedFdWithFlags { + fn restore_flags_or_log(&self) { + // As far as we can tell there's no such thing as a file with entirely empty + // flags (at minimum, it needs read/write mode, right?). + // So empty `oflags` is our sentinel that `fcntl(F_GETFL)` somehow failed. + // Empty oflags is our sentinel that + if self.oflags.is_empty() { + return; + } + + if let Err(e) = fcntl_setfl(&self.fd, self.oflags) { + error!( + "fcntl(F_SETFL) to restore flags {:?} on fd {:?} failed: {e}\nIO safety violation?", + self.oflags, self.fd, + ); + }; + } + + fn get_flags_or_log(fd: BorrowedFd) -> OFlags { + fcntl_getfl(fd) + .tap_err(|e| error!("fcntl(F_GETFL) failed on fd {fd:?}: {e}\nIO-safety violation?")) + .unwrap_or(OFlags::empty()) + } +} + +impl AsRawFd for OwnedFdWithFlags { + fn as_raw_fd(&self) -> RawFd { + AsRawFd::as_raw_fd(&self.fd) + } +} + +impl IntoRawFd for OwnedFdWithFlags { + fn into_raw_fd(self) -> RawFd { + self.restore_flags_or_log(); + ManuallyDrop::new(self).fd.as_raw_fd() + } +} + +impl FromRawFd for OwnedFdWithFlags { + unsafe fn from_raw_fd(fd: RawFd) -> Self { + let fd = unsafe { OwnedFd::from_raw_fd(fd) }; + let oflags = Self::get_flags_or_log(fd.as_fd()); + Self { fd, oflags } + } +} + +impl AsFd for OwnedFdWithFlags { + fn as_fd(&self) -> BorrowedFd<'_> { + AsFd::as_fd(&self.fd) + } +} + +impl From for OwnedFdWithFlags { + fn from(fd: OwnedFd) -> Self { + let oflags = Self::get_flags_or_log(fd.as_fd()); + Self { fd, oflags } + } +} diff --git a/src/lib.rs b/src/lib.rs index 58d98a1..7533c04 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -33,7 +33,7 @@ pub(crate) mod prelude { #[cfg(unix)] pub use fs_err::os::unix::fs::{FileExt, OpenOptionsExt}; - pub use tap::{Pipe, Tap}; + pub use tap::{Pipe, Tap, TapFallible}; pub use tracing::{Level, debug, error, info, trace, warn}; } @@ -44,6 +44,8 @@ pub mod args; pub use args::{AppendCmd, Args}; mod color; pub use color::{_CLI_ENABLE_COLOR, SHOULD_COLOR}; +mod daemon_io; +pub use daemon_io::OwnedFdWithFlags; pub mod line; mod nixcmd; pub use line::Line; From 74c2eaf66d6367a1588bfdec3c2654ae41f6c7d5 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Wed, 11 Mar 2026 14:26:59 +0100 Subject: [PATCH 17/19] some semblance of an event loop --- Cargo.lock | 49 ++++++++++ Cargo.toml | 9 +- rustfmt.toml | 6 ++ src/args.rs | 10 +- src/daemon.rs | 244 +++++++++++++++++++++++++++++++++++++++++++++++ src/daemon_io.rs | 60 ++++++++++-- src/lib.rs | 19 +++- src/main.rs | 1 + 8 files changed, 384 insertions(+), 14 deletions(-) create mode 100644 rustfmt.toml create mode 100644 src/daemon.rs diff --git a/Cargo.lock b/Cargo.lock index 9c57e7d..e641a9a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -73,6 +73,17 @@ version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af" +[[package]] +name = "bstr" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63044e1ae8e69f3b5a92c736ca6269b8d12fa7efe39bf34ddb06d102cf0e2cab" +dependencies = [ + "memchr", + "regex-automata", + "serde", +] + [[package]] name = "cfg-if" version = "1.0.4" @@ -85,6 +96,12 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" +[[package]] +name = "circular-buffer" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c638459986b83c2b885179bd4ea6a2cbb05697b001501a56adb3a3d230803b" + [[package]] name = "clap" version = "4.5.60" @@ -153,16 +170,21 @@ checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555" name = "dynix" version = "0.1.0" dependencies = [ + "bitflags", + "bstr", + "circular-buffer", "clap", "command-error", "fs-err", "itertools", "libc", + "mio", "regex", "regex-lite", "rustix", "serde", "serde_json", + "sync-fd", "tap", "tracing", "tracing-human-layer", @@ -314,6 +336,18 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "mio" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a69bcab0ad47271a0234d9422b131806bf3968021e5dc9328caf2d4cd58557fc" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys 0.61.2", +] + [[package]] name = "nix" version = "0.30.1" @@ -585,6 +619,15 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync-fd" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5666edb8017247cac3f25fe3f2a8c889177d8adda7ce7d29a1f7278e2858aee2" +dependencies = [ + "libc", +] + [[package]] name = "tap" version = "1.0.1" @@ -734,6 +777,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + [[package]] name = "windows" version = "0.61.3" diff --git a/Cargo.toml b/Cargo.toml index 3223b6b..b63a6a9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -22,16 +22,21 @@ regex-full = ["dep:regex"] regex-lite = ["dep:regex-lite"] [dependencies] +bitflags = { version = "2.11.0", features = ["std"] } +bstr = "1.12.1" +circular-buffer = "1.2.0" clap = { version = "4.5.54", features = ["color", "derive"] } command-error = "0.8.0" fs-err = "3.2.2" itertools = "0.14.0" libc = { version = "0.2.180", features = ["extra_traits"] } +mio = { version = "1.1.1", features = ["os-ext", "os-poll"] } regex = { version = "1.12.3", optional = true } regex-lite = { version = "0.1.9", optional = true } -rustix = { version = "1.1.4", features = ["event", "fs"] } -serde = { version = "1.0.228", features = ["derive"] } +rustix = { version = "1.1.4", features = ["event", "fs", "termios"] } +serde = { version = "1.0.228", features = ["derive", "rc"] } serde_json = "1.0.149" +sync-fd = "0.1.0" tap = "1.0.1" tracing = { version = "0.1.44", features = ["attributes"] } tracing-human-layer = "0.2.1" diff --git a/rustfmt.toml b/rustfmt.toml new file mode 100644 index 0000000..d662dc1 --- /dev/null +++ b/rustfmt.toml @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: 2026 Qyriad +# +# SPDX-License-Identifier: EUPL-1.1 + +match_block_trailing_comma = true +merge_derives = false diff --git a/src/args.rs b/src/args.rs index 8c528a2..65232a7 100644 --- a/src/args.rs +++ b/src/args.rs @@ -12,6 +12,7 @@ use clap::ColorChoice; use crate::prelude::*; #[derive(Debug, Clone, PartialEq, clap::Parser)] +#[command(long_about = None)] pub struct AppendCmd { #[arg(required = true)] pub name: Arc, @@ -20,10 +21,17 @@ pub struct AppendCmd { pub value: Arc, } +/// Accept commands over (default stdin). +#[derive(Debug, Clone, PartialEq, clap::Parser)] +#[command(long_about = None)] +pub struct DaemonCmd { + // FIXME: support Unix sockets. +} + #[derive(Debug, Clone, PartialEq, clap::Subcommand)] -#[command(flatten_help = true)] pub enum Subcommand { Append(AppendCmd), + Daemon(DaemonCmd), } static DEFAULT_PATH: LazyLock> = LazyLock::new(|| { diff --git a/src/daemon.rs b/src/daemon.rs new file mode 100644 index 0000000..48498b9 --- /dev/null +++ b/src/daemon.rs @@ -0,0 +1,244 @@ +use std::{ + io, + ops::Deref, + os::fd::{AsFd, BorrowedFd, OwnedFd}, + time::Duration, +}; + +use circular_buffer::CircularBuffer; + +use mio::{Events, Interest, Poll, Token, unix::SourceFd}; + +use rustix::{ + buffer::{Buffer, spare_capacity}, + fs::{OFlags, fcntl_setfl}, + io::Errno, + termios::{ + ControlModes, InputModes, LocalModes, OptionalActions, OutputModes, SpecialCodeIndex, + SpecialCodes, Termios, tcgetattr, tcsetattr, + }, +}; + +use serde::{Deserialize, Serialize}; +use serde_json::StreamDeserializer; + +use crate::prelude::*; + +use crate::OwnedFdWithFlags; + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[derive(Deserialize, Serialize)] +#[serde(untagged)] +pub enum ConvenientAttrPath { + Dotted(Box), + Split(Box<[Box]>), +} + +impl ConvenientAttrPath { + pub fn clone_from_dotted(s: &str) -> Self { + Self::Dotted(Box::from(s)) + } + + pub fn clone_from_split(s: &[&str]) -> Self { + Self::from_str_iter(s.into_iter().map(Deref::deref)) + } + + pub fn from_str_iter<'i, I>(iter: I) -> Self + where + I: Iterator, + { + let boxed = iter.map(|s| Box::from(s)); + Self::Split(Box::from_iter(boxed)) + } +} + +impl<'i> FromIterator<&'i str> for ConvenientAttrPath { + fn from_iter(iter: I) -> Self + where + I: IntoIterator, + { + Self::from_str_iter(iter.into_iter()) + } +} + +impl FromIterator> for ConvenientAttrPath { + fn from_iter(iter: I) -> Self + where + I: IntoIterator>, + { + Self::Split(Box::from_iter(iter)) + } +} + +#[derive(Debug, Clone, PartialEq)] +#[derive(serde::Deserialize, serde::Serialize)] +#[serde(tag = "action", content = "args", rename_all = "snake_case")] +pub enum DaemonCmd { + Append { + name: ConvenientAttrPath, + value: Box, + }, +} + +const TIMEOUT_NEVER: Option = None; + +#[derive(Debug)] +pub struct Daemon { + fd: OwnedFdWithFlags, + poll_error_buffer: CircularBuffer, + fd_error_buffer: CircularBuffer, + + cmd_buffer: Vec, + next_timeout: Option, +} + +impl Daemon { + /// Panics if we cannot make `fd` non-blocking. + pub fn new(fd: OwnedFd) -> Self { + let fd = OwnedFdWithFlags::new_with_fallback(fd); + + // Make non-blocking. + //fcntl_setfl(fd.as_fd(), fd.oflags().union(OFlags::NONBLOCK)) + // .tap_err(|e| error!("F_SETFL O_NONBLOCK failed on fd {:?}: {e}", fd.as_fd())) + // .unwrap(); + + Self { + fd, + poll_error_buffer: Default::default(), + fd_error_buffer: Default::default(), + cmd_buffer: Vec::with_capacity(1024), + next_timeout: TIMEOUT_NEVER, + } + } + + /// This panics if stdin cannot be opened. + /// + /// If you want to handle that error, use [`Daemon::from_raw_parts()`]. + pub fn from_stdin() -> Self { + let stdin = io::stdin(); + let fd = stdin + .as_fd() + .try_clone_to_owned() + .expect("dynix daemon could not open stdin; try a Unix socket?"); + + debug!("opened daemon to stdin file descriptor {fd:?}"); + + Self::new(fd) + } + + //pub unsafe fn from_raw_parts(fd: OwnedFd) -> Self { + // Self { + // fd: OwnedFdWithFlags::new_with_fallback(fd), + // } + //} + + pub fn fd(&self) -> BorrowedFd<'_> { + self.fd.as_fd() + } +} + +const ERROR_BUFFER_LEN: usize = 8; + +/// Private helpers. +impl Daemon { + fn read_cmd(&mut self) -> Result<(), IoError> { + if self.cmd_buffer.len() == self.cmd_buffer.capacity() { + self.cmd_buffer.reserve(1024); + } + + let _count = rustix::io::read(&self.fd, spare_capacity(&mut self.cmd_buffer))?; + + // The buffer might have existing data from the last read. + let deserializer = serde_json::Deserializer::from_slice(&self.cmd_buffer); + let stream: StreamDeserializer<_, DaemonCmd> = deserializer.into_iter(); + for cmd in stream { + let cmd = match cmd { + Ok(cmd) => cmd, + Err(e) if e.is_eof() => { + self.next_timeout = Some(Duration::from_secs(4)); + warn!("Didn't get a valid daemon command; giving the other side 4 seconds..."); + return Ok(()); + }, + Err(e) => { + warn!("error deserializing command: {e}"); + warn!("error count: {}", self.fd_error_buffer.len()); + self.cmd_buffer.clear(); + // Don't propagate the error unless we have too many. + self.fd_error_buffer.try_push_back(e.into()).tap_err(|e| { + error!( + "Accumulated too many errors for daemon fd {:?}: {e}", + self.fd(), + ) + })?; + return Ok(()); + }, + }; + debug!("got cmd: {cmd:?}"); + } + + self.cmd_buffer.clear(); + + Ok(()) + } + + pub(crate) fn enter_loop(&mut self) -> Result, IoError> { + let raw_fd = self.fd.as_raw_fd(); + let mut daemon_source = SourceFd(&raw_fd); + const DAEMON: Token = Token(0); + let mut poll = Poll::new().unwrap_or_else(|e| unreachable!("creating new mio Poll: {e}")); + + poll.registry() + .register(&mut daemon_source, DAEMON, Interest::READABLE) + .unwrap_or_else(|e| unreachable!("registering mio Poll for daemon fd {raw_fd:?}: {e}")); + + let mut events = Events::with_capacity(1024); + + let example = DaemonCmd::Append { + //name: ConvenientAttrPath::Dotted(Box::from( + // "services.gotosocial.settings.application-name", + //)), + //name: ConvenientAttrPath::Split(Box::from([ + // Box::from("services"), + // Box::from("gotosocial"), + //])), + name: ConvenientAttrPath::clone_from_split(&[ + "services", + "gotosocial", + "settings", + "application-name", + ]), + value: Box::from("foo"), + }; + + //let example_as_json = serde_json::to_string_pretty(&example).unwrap(); + //info!("{}", example_as_json); + + loop { + match poll.poll(&mut events, self.next_timeout.take()) { + Ok(_) => { + if events.is_empty() { + warn!("timeout expired"); + self.cmd_buffer.clear(); + } else { + let _ = self.poll_error_buffer.pop_front(); + } + }, + Err(e) => { + warn!("mio Poll::poll() error: {e}"); + self.poll_error_buffer.try_push_back(e).tap_err(|e| { + error!("accumulated too many errors for mio::Poll::poll(): {e}") + })?; + }, + } + + for event in &events { + match event.token() { + DAEMON => { + self.read_cmd().unwrap(); + }, + _ => unreachable!(), + } + } + } + } +} diff --git a/src/daemon_io.rs b/src/daemon_io.rs index f080ca8..40beed1 100644 --- a/src/daemon_io.rs +++ b/src/daemon_io.rs @@ -17,7 +17,6 @@ use crate::prelude::*; /// /// - [`IntoRawFd`] /// - [`drop()`] -#[derive(Debug)] pub struct OwnedFdWithFlags { fd: OwnedFd, oflags: OFlags, @@ -29,14 +28,34 @@ impl OwnedFdWithFlags { Ok(Self { fd, oflags }) } + pub fn as_ref_owned(&self) -> &OwnedFd { + &self.fd + } + /// If, for some ungodly reason, `fcntl(F_GETFL)` fails, then empty flags are used. /// Empty flags should not be restored on close. /// /// I'm pretty sure this should never happen if the program is IO-safe. pub fn new_with_fallback(fd: OwnedFd) -> Self { - let oflags = Self::get_flags_or_log(fd.as_fd()); + let oflags = Self::get_flags_or_log(&fd); Self { fd, oflags } } + + pub fn oflags(&self) -> OFlags { + self.oflags + } +} + +impl Debug for OwnedFdWithFlags { + fn fmt(&self, f: &mut Formatter) -> FmtResult { + let mut flags_str: String = Default::default(); + bitflags::parser::to_writer(&self.oflags, &mut flags_str)?; + + f.debug_struct("OwnedFdWithFlags") + .field("fd", &self.fd) + .field("oflags", &flags_str) + .finish() + } } impl Drop for OwnedFdWithFlags { @@ -56,15 +75,19 @@ impl OwnedFdWithFlags { return; } - if let Err(e) = fcntl_setfl(&self.fd, self.oflags) { - error!( + match fcntl_setfl(&self.fd, self.oflags) { + Ok(_) => (), + // EBADF + //Err(Errno::BADF) => (), + Err(e) => error!( "fcntl(F_SETFL) to restore flags {:?} on fd {:?} failed: {e}\nIO safety violation?", self.oflags, self.fd, - ); - }; + ), + } } - fn get_flags_or_log(fd: BorrowedFd) -> OFlags { + fn get_flags_or_log(fd: Fd) -> OFlags { + let fd = fd.as_fd(); fcntl_getfl(fd) .tap_err(|e| error!("fcntl(F_GETFL) failed on fd {fd:?}: {e}\nIO-safety violation?")) .unwrap_or(OFlags::empty()) @@ -87,7 +110,7 @@ impl IntoRawFd for OwnedFdWithFlags { impl FromRawFd for OwnedFdWithFlags { unsafe fn from_raw_fd(fd: RawFd) -> Self { let fd = unsafe { OwnedFd::from_raw_fd(fd) }; - let oflags = Self::get_flags_or_log(fd.as_fd()); + let oflags = Self::get_flags_or_log(&fd); Self { fd, oflags } } } @@ -104,3 +127,24 @@ impl From for OwnedFdWithFlags { Self { fd, oflags } } } + +impl Read for &OwnedFdWithFlags { + fn read(&mut self, buf: &mut [u8]) -> Result { + debug_assert!(buf.len() > 0); + loop { + buf.fill(0); + match rustix::io::read(self.as_ref_owned(), &mut *buf) { + Ok(count) => { + debug_assert!(count <= buf.len()); + return Ok(count); + }, + Err(e) if e.kind() == IoErrorKind::Interrupted => continue, + Err(e) if e.kind() == IoErrorKind::WouldBlock => return Ok(0), + Err(e) => { + let e = IoError::from_raw_os_error(e.raw_os_error()); + return Err(e); + }, + } + } + } +} diff --git a/src/lib.rs b/src/lib.rs index 7533c04..3997aec 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,8 +13,8 @@ pub(crate) mod prelude { pub use std::{ error::Error as StdError, ffi::{OsStr, OsString}, - fmt::{Display, Formatter, Result as FmtResult}, - io::{Error as IoError, Read, Seek, SeekFrom, Write}, + fmt::{Debug, Display, Formatter, Result as FmtResult}, + io::{Error as IoError, ErrorKind as IoErrorKind, Read, Seek, SeekFrom, Write}, path::{Path, PathBuf}, process::{Command, ExitCode}, str::FromStr, @@ -33,6 +33,8 @@ pub(crate) mod prelude { #[cfg(unix)] pub use fs_err::os::unix::fs::{FileExt, OpenOptionsExt}; + pub use bstr::ByteSlice; + pub use tap::{Pipe, Tap, TapFallible}; pub use tracing::{Level, debug, error, info, trace, warn}; @@ -44,11 +46,13 @@ pub mod args; pub use args::{AppendCmd, Args}; mod color; pub use color::{_CLI_ENABLE_COLOR, SHOULD_COLOR}; +mod daemon; +pub use daemon::Daemon; mod daemon_io; pub use daemon_io::OwnedFdWithFlags; pub mod line; -mod nixcmd; pub use line::Line; +mod nixcmd; pub mod source; pub use source::{SourceFile, SourceLine}; @@ -67,6 +71,8 @@ use _regex::Regex; use itertools::Itertools; use serde::{Deserialize, Serialize}; +use crate::args::DaemonCmd; + pub const ASCII_WHITESPACE: &[char] = &['\t', '\n', '\x0C', '\r', ' ']; /// Regex pattern to extract the priority in a `lib.mkOverride` call. @@ -118,6 +124,13 @@ pub fn do_append(args: Arc, append_args: AppendCmd) -> Result<(), BoxDynEr Ok(()) } +//#[tracing::instrument(level = "debug")] +pub fn do_daemon(args: Arc, daemon_args: DaemonCmd) -> Result<(), BoxDynError> { + let mut daemon = Daemon::from_stdin(); + daemon.enter_loop().unwrap(); + todo!(); +} + #[derive(Debug, Clone, PartialEq, Hash, Serialize, Deserialize)] pub struct DefinitionWithLocation { pub file: Box, diff --git a/src/main.rs b/src/main.rs index c45a56a..940ce0a 100644 --- a/src/main.rs +++ b/src/main.rs @@ -34,6 +34,7 @@ fn main_wrapped() -> Result<(), Box> { use dynix::args::Subcommand::*; match &args.subcommand { Append(append_args) => dynix::do_append(args.clone(), append_args.clone())?, + Daemon(daemon_args) => dynix::do_daemon(args.clone(), daemon_args.clone())?, }; } From 470fe05b76ffd790ccf14a873de37a2a6aaf0b80 Mon Sep 17 00:00:00 2001 From: Qyriad Date: Tue, 17 Mar 2026 14:33:31 +0100 Subject: [PATCH 18/19] cli: default RUST_LOG if it's not set --- src/main.rs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/src/main.rs b/src/main.rs index 940ce0a..a54078e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -2,6 +2,7 @@ // // SPDX-License-Identifier: EUPL-1.1 +use std::env; use std::io::{self, IsTerminal}; use std::process::ExitCode; use std::{error::Error as StdError, sync::Arc}; @@ -12,6 +13,13 @@ use tracing_subscriber::util::SubscriberInitExt; use tracing_subscriber::{EnvFilter, layer::SubscriberExt}; fn main_wrapped() -> Result<(), Box> { + // Default RUST_LOG to warn if it's not specified. + if let None = env::var_os("RUST_LOG") { + unsafe { + env::set_var("RUST_LOG", "warn"); + } + } + let args = Arc::new(dynix::Args::parse()); let success = dynix::_CLI_ENABLE_COLOR.set(match args.color { @@ -47,6 +55,6 @@ fn main() -> ExitCode { Err(e) => { eprintln!("dynix: error: {}", e); ExitCode::FAILURE - } + }, } } From 398fccc5d0971e99c8e2fffdcafde0cb016b7c9a Mon Sep 17 00:00:00 2001 From: Qyriad Date: Thu, 19 Mar 2026 12:36:46 +0100 Subject: [PATCH 19/19] some semblance of socket support --- Cargo.lock | 19 +++++ Cargo.toml | 7 +- src/args.rs | 11 ++- src/boxext.rs | 27 ++++++ src/daemon.rs | 209 ++++++++++++++++++++++++++++++++++++++++++----- src/daemon_io.rs | 2 +- src/lib.rs | 24 +++++- 7 files changed, 271 insertions(+), 28 deletions(-) create mode 100644 src/boxext.rs diff --git a/Cargo.lock b/Cargo.lock index e641a9a..fabdb82 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -160,6 +160,23 @@ dependencies = [ "utf8-command", ] +[[package]] +name = "const-str" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18f12cc9948ed9604230cdddc7c86e270f9401ccbe3c2e98a4378c5e7632212f" + +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "dyn-clone" version = "1.0.20" @@ -175,6 +192,8 @@ dependencies = [ "circular-buffer", "clap", "command-error", + "const-str", + "displaydoc", "fs-err", "itertools", "libc", diff --git a/Cargo.toml b/Cargo.toml index b63a6a9..ed6bd37 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,13 +27,16 @@ bstr = "1.12.1" circular-buffer = "1.2.0" clap = { version = "4.5.54", features = ["color", "derive"] } command-error = "0.8.0" +const-str = "1.1.0" +displaydoc = "0.2.5" fs-err = "3.2.2" itertools = "0.14.0" libc = { version = "0.2.180", features = ["extra_traits"] } -mio = { version = "1.1.1", features = ["os-ext", "os-poll"] } +#macro_rules_attribute = { version = "0.2.2", features = ["better-docs", "verbose-expansions"] } +mio = { version = "1.1.1", features = ["os-ext", "os-poll", "net"] } regex = { version = "1.12.3", optional = true } regex-lite = { version = "0.1.9", optional = true } -rustix = { version = "1.1.4", features = ["event", "fs", "termios"] } +rustix = { version = "1.1.4", features = ["event", "fs", "net", "process", "termios"] } serde = { version = "1.0.228", features = ["derive", "rc"] } serde_json = "1.0.149" sync-fd = "0.1.0" diff --git a/src/args.rs b/src/args.rs index 65232a7..5c9bb73 100644 --- a/src/args.rs +++ b/src/args.rs @@ -25,7 +25,16 @@ pub struct AppendCmd { #[derive(Debug, Clone, PartialEq, clap::Parser)] #[command(long_about = None)] pub struct DaemonCmd { - // FIXME: support Unix sockets. + /// Read from stdin instead of a Unix socket. + #[arg(long)] + pub stdin: bool, + + /// Manually specify the full alternative path to the server socket. + /// + /// If not specified and `--stdin` is not specified, defaults to $XDG_RUNTIME_DIR/dynix.sock + #[arg(long)] + #[arg(conflicts_with = "stdin")] + pub socket: Option, } #[derive(Debug, Clone, PartialEq, clap::Subcommand)] diff --git a/src/boxext.rs b/src/boxext.rs new file mode 100644 index 0000000..03200ec --- /dev/null +++ b/src/boxext.rs @@ -0,0 +1,27 @@ +use std::{ffi::OsStr, path::Path, ptr}; + +/// Until [`Box::map()`] is stable, there's no way to do this that is safe, stable, and +/// allocationless. +pub trait BoxedPathExt { + fn into_boxed_os_str(self) -> Box; +} + +impl BoxedPathExt for Box { + fn into_boxed_os_str(self) -> Box { + let path_mut_ptr: *mut Path = Box::into_raw(self); + + // SAFETY: we just got `path_mut_ptr` from a valid Box. + let os_str_mut_ptr: *mut OsStr = unsafe { + let os_str_mut_ref = path_mut_ptr + .as_mut() + .expect("avoided undefined behavior") + .as_mut_os_str(); + + ptr::from_mut(os_str_mut_ref) + }; + + // SAFETY: allocation came from `Box::into_raw()`, and we are not extending + // its lifetime. There are also no shared or exclusive references. + unsafe { Box::::from_raw(os_str_mut_ptr) } + } +} diff --git a/src/daemon.rs b/src/daemon.rs index 48498b9..506527a 100644 --- a/src/daemon.rs +++ b/src/daemon.rs @@ -1,18 +1,21 @@ use std::{ - io, + env, io, ops::Deref, - os::fd::{AsFd, BorrowedFd, OwnedFd}, + os::fd::{AsFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd, RawFd}, + sync::LazyLock, time::Duration, }; use circular_buffer::CircularBuffer; -use mio::{Events, Interest, Poll, Token, unix::SourceFd}; +use mio::{Events, Interest, Poll, Token, net::UnixListener, unix::SourceFd}; use rustix::{ buffer::{Buffer, spare_capacity}, - fs::{OFlags, fcntl_setfl}, + fs::{FileType, OFlags, Stat, fcntl_setfl}, io::Errno, + net::SocketFlags, + process::Uid, termios::{ ControlModes, InputModes, LocalModes, OptionalActions, OutputModes, SpecialCodeIndex, SpecialCodes, Termios, tcgetattr, tcsetattr, @@ -26,6 +29,23 @@ use crate::prelude::*; use crate::OwnedFdWithFlags; +pub static UID: LazyLock = LazyLock::new(|| rustix::process::getuid()); + +pub static USER_SOCKET_DIR: LazyLock<&'static Path> = LazyLock::new(|| { + let dir: Box = env::var_os("XDG_RUNTIME_DIR") + .map(PathBuf::from) + .unwrap_or_else(|| ["/", "run", "user", &UID.to_string()].into_iter().collect()) + .into_boxed_path(); + + Box::leak(dir) +}); + +pub static TMPDIR: LazyLock<&'static Path> = LazyLock::new(|| { + let dir: Box = env::temp_dir().into_boxed_path(); + + Box::leak(dir) +}); + #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Deserialize, Serialize)] #[serde(untagged)] @@ -85,6 +105,7 @@ const TIMEOUT_NEVER: Option = None; #[derive(Debug)] pub struct Daemon { fd: OwnedFdWithFlags, + path: Box, poll_error_buffer: CircularBuffer, fd_error_buffer: CircularBuffer, @@ -93,17 +114,17 @@ pub struct Daemon { } impl Daemon { - /// Panics if we cannot make `fd` non-blocking. - pub fn new(fd: OwnedFd) -> Self { + pub fn new(fd: OwnedFd, name_or_path: Box) -> Self { let fd = OwnedFdWithFlags::new_with_fallback(fd); - // Make non-blocking. - //fcntl_setfl(fd.as_fd(), fd.oflags().union(OFlags::NONBLOCK)) - // .tap_err(|e| error!("F_SETFL O_NONBLOCK failed on fd {:?}: {e}", fd.as_fd())) - // .unwrap(); + debug!( + "opened daemon to {} file descriptor {fd:?}", + name_or_path.display(), + ); Self { fd, + path: name_or_path, poll_error_buffer: Default::default(), fd_error_buffer: Default::default(), cmd_buffer: Vec::with_capacity(1024), @@ -111,6 +132,48 @@ impl Daemon { } } + pub fn from_unix_socket_path(path: &Path) -> Result { + // We unconditionally unlink() `path` before binding, but completely ignore the result. + let _ = rustix::fs::unlink(path); + let listener = UnixListener::bind(path) + .tap_err(|e| error!("failed to bind AF_UNIX socket at {}: {e}", path.display()))?; + //let (stream, _addr) = listener.accept().unwrap_or_else(|e| todo!("error: {e}")); + //warn!("stream is: {stream:?} ({})", stream.as_raw_fd()); + let listener_owned_fd = OwnedFd::from(listener); + rustix::net::sockopt::set_socket_keepalive(&listener_owned_fd, true).unwrap(); + let path: Box = path.to_path_buf().into_boxed_path().into_boxed_os_str(); + + Ok(Self::new(listener_owned_fd, path)) + } + + pub fn open_default_socket() -> Result { + use IoErrorKind::*; + let preferred = USER_SOCKET_DIR.join("dynix.sock").into_boxed_path(); + let constructed = match Self::from_unix_socket_path(&preferred) { + Ok(v) => v, + Err(e) if e.kind() == Unsupported => { + // + return Err(e); + }, + Err(e) => { + warn!( + "failed binding AF_UNIX socket at {}: {e}; trying elsewhere", + preferred.display() + ); + + let fallback = TMPDIR.join("dynix.sock").into_boxed_path(); + Self::from_unix_socket_path(&fallback).tap_err(|e| { + error!( + "failed binding AF_UNIX socket at {}: {e}", + fallback.display() + ) + })? + }, + }; + + Ok(constructed) + } + /// This panics if stdin cannot be opened. /// /// If you want to handle that error, use [`Daemon::from_raw_parts()`]. @@ -121,9 +184,7 @@ impl Daemon { .try_clone_to_owned() .expect("dynix daemon could not open stdin; try a Unix socket?"); - debug!("opened daemon to stdin file descriptor {fd:?}"); - - Self::new(fd) + Self::new(fd, Box::from(OsStr::new("«stdin»"))) } //pub unsafe fn from_raw_parts(fd: OwnedFd) -> Self { @@ -141,12 +202,18 @@ const ERROR_BUFFER_LEN: usize = 8; /// Private helpers. impl Daemon { - fn read_cmd(&mut self) -> Result<(), IoError> { + fn read_cmd(&mut self, fd: Option<&dyn AsFd>) -> Result<(), IoError> { + let fd = match fd.as_ref() { + Some(fd) => fd.as_fd(), + None => self.fd.as_fd(), + }; + if self.cmd_buffer.len() == self.cmd_buffer.capacity() { self.cmd_buffer.reserve(1024); } - let _count = rustix::io::read(&self.fd, spare_capacity(&mut self.cmd_buffer))?; + let _count = rustix::io::read(fd, spare_capacity(&mut self.cmd_buffer)) + .tap_err(|e| error!("read() on daemon fd {fd:?} failed: {e}"))?; // The buffer might have existing data from the last read. let deserializer = serde_json::Deserializer::from_slice(&self.cmd_buffer); @@ -165,10 +232,7 @@ impl Daemon { self.cmd_buffer.clear(); // Don't propagate the error unless we have too many. self.fd_error_buffer.try_push_back(e.into()).tap_err(|e| { - error!( - "Accumulated too many errors for daemon fd {:?}: {e}", - self.fd(), - ) + error!("Accumulated too many errors for daemon fd {fd:?}: {e}") })?; return Ok(()); }, @@ -185,6 +249,8 @@ impl Daemon { let raw_fd = self.fd.as_raw_fd(); let mut daemon_source = SourceFd(&raw_fd); const DAEMON: Token = Token(0); + let mut next_token_number: usize = 1; + let mut extra_tokens: Vec<(Token, RawFd)> = Default::default(); let mut poll = Poll::new().unwrap_or_else(|e| unreachable!("creating new mio Poll: {e}")); poll.registry() @@ -234,11 +300,112 @@ impl Daemon { for event in &events { match event.token() { DAEMON => { - self.read_cmd().unwrap(); + let is_sock = rustix::fs::fstat(&self.fd) + .map(|Stat { st_mode, .. }| st_mode) + .map(FileType::from_raw_mode) + .map(FileType::is_socket) + .unwrap_or(false); + + if !is_sock { + self.read_cmd(None).unwrap(); + continue; + } + + // Accept, first. + let flags = SocketFlags::NONBLOCK | SocketFlags::CLOEXEC; + let stream_fd = match rustix::net::accept_with(&self.fd, flags) { + Ok(stream) => { + debug!( + "Accepted connection from socket {:?} as stream {:?}", + self.fd, stream, + ); + stream + }, + Err(e) => { + error!("accept4 on daemon socket failed: {e}"); + self.fd_error_buffer.try_push_back(e.into()).tap_err(|e| { + error!( + "Accumulated too many errors for daemon fd {:?}: {e}", + self.fd + ) + })?; + continue; + }, + }; + + let mut stream_fd = stream_fd.into_raw_fd(); + + // And add this stream to our poll interest list. + if let Err(idx) = + extra_tokens.binary_search_by_key(&stream_fd, |(_, fd)| fd.as_raw_fd()) + { + let token = Token(next_token_number); + extra_tokens.insert(idx, (token, stream_fd)); + next_token_number = next_token_number.wrapping_add(1); + let mut source = SourceFd(&mut stream_fd); + poll.registry() + .register(&mut source, token, Interest::READABLE) + .unwrap(); + } + + // Wait for the next poll to handle. + + //match self.read_cmd(Some(&stream_fd)) { + // Ok(()) => (), + // Err(e) if e.kind() == IoErrorKind::WouldBlock => { + // continue; + // }, + // Err(e) => { + // self.fd_error_buffer.try_push_back(e.into()).tap_err(|e| { + // error!( + // "Accumulated too many errors for fd {:?} {e}", + // &stream_fd, + // ) + // })?; + // }, + //} + }, + other_token => { + let index = match extra_tokens + .binary_search_by_key(&other_token, |&(t, _)| t) + { + Ok(index) => index, + Err(index) => unreachable!( + "tried to get index ({index}) for non-existent token {other_token:?}" + ), + }; + + // This must be a stream fd. + let (_, stream_fd) = extra_tokens[index]; + // SAFETY: oh boy. + let stream_fd = unsafe { BorrowedFd::borrow_raw(stream_fd) }; + self.read_cmd(Some(&stream_fd)).unwrap(); }, - _ => unreachable!(), } } } } + + fn get_fallback_fd_name(fd: Fd) -> Option> { + let dev_fd_path = Path::new("/dev/fd").join(fd.as_raw_fd().to_string()); + + fs_err::read_link(dev_fd_path) + .map(PathBuf::into_os_string) + .map(OsString::into_boxed_os_str) + .ok() + } +} + +impl Drop for Daemon { + fn drop(&mut self) { + let probably_synthetic = self + .path + .to_str() + .map(|p| p.starts_with("«") && p.ends_with("»")) + .unwrap_or(false); + if probably_synthetic { + return; + } + let _ = rustix::fs::unlink(&*self.path); + } } diff --git a/src/daemon_io.rs b/src/daemon_io.rs index 40beed1..891a518 100644 --- a/src/daemon_io.rs +++ b/src/daemon_io.rs @@ -52,7 +52,7 @@ impl Debug for OwnedFdWithFlags { bitflags::parser::to_writer(&self.oflags, &mut flags_str)?; f.debug_struct("OwnedFdWithFlags") - .field("fd", &self.fd) + .field("fd", &self.fd.as_raw_fd()) .field("oflags", &flags_str) .finish() } diff --git a/src/lib.rs b/src/lib.rs index 3997aec..e0211ec 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -38,12 +38,15 @@ pub(crate) mod prelude { pub use tap::{Pipe, Tap, TapFallible}; pub use tracing::{Level, debug, error, info, trace, warn}; + + pub use crate::boxext::BoxedPathExt; } use prelude::*; pub mod args; pub use args::{AppendCmd, Args}; +mod boxext; mod color; pub use color::{_CLI_ENABLE_COLOR, SHOULD_COLOR}; mod daemon; @@ -54,6 +57,7 @@ pub mod line; pub use line::Line; mod nixcmd; pub mod source; +use rustix::fs::Mode; pub use source::{SourceFile, SourceLine}; #[cfg(all(not(feature = "regex-full"), not(feature = "regex-lite")))] @@ -125,10 +129,24 @@ pub fn do_append(args: Arc, append_args: AppendCmd) -> Result<(), BoxDynEr } //#[tracing::instrument(level = "debug")] -pub fn do_daemon(args: Arc, daemon_args: DaemonCmd) -> Result<(), BoxDynError> { - let mut daemon = Daemon::from_stdin(); +pub fn do_daemon(_args: Arc, daemon_args: DaemonCmd) -> Result<(), BoxDynError> { + // FIXME: make configurable? + let _ = rustix::process::umask(Mode::from_bits_retain(0o600).complement()); + + let mut daemon = match daemon_args { + DaemonCmd { stdin: true, .. } => Daemon::from_stdin(), + DaemonCmd { socket: None, .. } => Daemon::open_default_socket()?, + DaemonCmd { + socket: Some(socket), + .. + } => Daemon::from_unix_socket_path(&socket)?, + }; + daemon.enter_loop().unwrap(); - todo!(); + + info!("daemon has exited"); + + Ok(()) } #[derive(Debug, Clone, PartialEq, Hash, Serialize, Deserialize)]