This commit is contained in:
lassulus 2025-05-26 16:51:59 +02:00
commit 81e0aadf20
5 changed files with 113 additions and 0 deletions

27
flake.lock generated Normal file
View file

@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1748026106,
"narHash": "sha256-6m1Y3/4pVw1RWTsrkAK2VMYSzG4MMIj7sqUy7o8th1o=",
"owner": "nixos",
"repo": "nixpkgs",
"rev": "063f43f2dbdef86376cc29ad646c45c46e93234c",
"type": "github"
},
"original": {
"owner": "nixos",
"ref": "nixos-unstable",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

16
flake.nix Normal file
View file

@ -0,0 +1,16 @@
{
inputs.nixpkgs.url = "github:nixos/nixpkgs/nixos-unstable";
outputs = { nixpkgs, ... }: let
supportedArchitectures = [
"aarch64-darwin"
"aarch64-linux"
"x86_64-darwin"
"x86_64-linux"
];
in {
packages = nixpkgs.lib.genAttrs supportedArchitectures (system: {
nix_templater = nixpkgs.legacyPackages.${system}.callPackage ./pkgs/nix_templater {};
});
legacyPackages = nixpkgs.lib.genAttrs supportedArchitectures (system: import ./lib.nix { pkgs = nixpkgs.legacyPackages.${system}; });
};
}

29
lib.nix Normal file
View file

@ -0,0 +1,29 @@
{ pkgs, text_templater }:
rec {
fileContents = file: {
outPath = "<${builtins.placeholder "nix_template"}${toString file}${builtins.placeholder "nix_template"}>";
file = file;
};
template_text = { name, text, outPath }:
pkgs.runCommand name {
textBeforeTemplate = text;
script = ''
${text_templater}/bin/text_templater ${builtins.placeholder "out"}/template ${builtins.placeholder "nix_template"} "${outPath}"
'';
passAsFile = [ "script" "textBeforeTemplate" ];
} ''
mkdir -p $out/bin
cp $textBeforeTemplatePath $out/template
cp $scriptPath $out/bin/${name}
chmod +x $out/bin/${name}
'';
test = template_text {
name = "test";
text = ''
blablabla ${fileContents (pkgs.writeText "lol" "lol")}
'';
outPath = "./test";
};
}

View file

@ -0,0 +1,10 @@
{ writeShellApplication, python3 }:
writeShellApplication {
name = "text_templater";
runtimeInputs = [
python3
];
text = ''
python ${./replace.py} "$@"
'';
}

View file

@ -0,0 +1,31 @@
import sys
from pathlib import Path
tempalte_file = sys.argv[1]
magic_string = sys.argv[2]
outfile = sys.argv[3]
if Path(outfile).exists():
print(f"{outfile} already exists, aborting")
sys.exit(1)
template_bytes = Path(tempalte_file).read_bytes()
loc = 0
output = b""
while True:
magic_start = template_bytes[loc:].find(f"<{magic_string}".encode())
if magic_start == -1:
output += template_bytes[loc:]
break
magic_end = template_bytes[loc + magic_start :].find(f"{magic_string}>".encode())
magic_file = template_bytes[
(loc + magic_start + len(magic_string) + 1) : loc + magic_start + magic_end
]
output += template_bytes[loc : loc + magic_start]
# TODO handle errors better here
output += Path(magic_file.decode()).read_bytes()
loc = loc + magic_start + magic_end + len(magic_string) + 1
Path(outfile).write_bytes(output)