about summary refs log tree commit diff
path: root/pkgs/build-support/writers/scripts.nix
blob: 999c8b4f2ae470570fa324e87b290b3935982c8e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
{
  buildPackages,
  gixy,
  lib,
  libiconv,
  makeBinaryWrapper,
  mkNugetDeps,
  mkNugetSource,
  pkgs,
  stdenv,
}:
let
  inherit (lib)
    concatMapStringsSep
    elem
    escapeShellArg
    last
    optionalString
    strings
    types
    ;
in
rec {
  /**
    `makeScriptWriter` returns a derivation which creates an executable script.

    # Inputs

    config (AttrSet)
    : `interpreter` (String)
      : the [interpreter](https://en.wikipedia.org/wiki/Shebang_(Unix)) to use for the script.
    : `check` (String)
      : A command to check the script. For example, this could be a linting check.
    : `makeWrapperArgs` (Optional, [ String ], Default: [])
      : Arguments forwarded to (`makeWrapper`)[#fun-makeWrapper].

    `nameOrPath` (String)
    : The name of the script or the path to the script.

      When a `string` starting with "/" is passed, the script will be created at the specified path in $out.
      I.e. `"/bin/hello"` will create a script at `$out/bin/hello`.

      Any other `string` is interpreted as a filename.
      It must be a [POSIX filename](https://en.wikipedia.org/wiki/Filename) starting with a letter, digit, dot, or underscore.
      Spaces or special characters are not allowed.

    `content` (String)
    : The content of the script.

    :::{.note}
    This function is used as base implementation for other high-level writer functions.

    For example, `writeBash` can (roughly) be implemented as:

    ```nix
    writeBash = makeScriptWriter { interpreter = "${pkgs.bash}/bin/bash"; }
    ```
    :::

    # Examples
    :::{.example}
    ## `pkgs.writers.makeScriptWriter` dash example

    ```nix-repl
    :b makeScriptWriter { interpreter = "${pkgs.dash}/bin/dash"; } "hello" "echo hello world"
    -> /nix/store/indvlr9ckmnv4f0ynkmasv2h4fxhand0-hello
    ```

    The above example creates a script named `hello` that outputs `hello world` when executed.

    ```sh
    > /nix/store/indvlr9ckmnv4f0ynkmasv2h4fxhand0-hello
    hello world
    ```
    :::

    :::{.example}
    ## `pkgs.writers.makeScriptWriter` python example

    ```nix-repl
    :b makeScriptWriter { interpreter = "${pkgs.python3}/bin/python"; } "python-hello" "print('hello world')"
    -> /nix/store/4kvby1hqr45ffcdrvfpnpj62hanskw93-python-hello
    ```

    ```sh
    > /nix/store/4kvby1hqr45ffcdrvfpnpj62hanskw93-python-hello
    hello world
    ```
    :::
  */
  makeScriptWriter =
    {
      interpreter,
      check ? "",
      makeWrapperArgs ? [ ],
    }:
    nameOrPath: content:
    assert
      (types.path.check nameOrPath)
      || (builtins.match "([0-9A-Za-z._])[0-9A-Za-z._-]*" nameOrPath != null);
    assert (types.path.check content) || (types.str.check content);
    let
      nameIsPath = types.path.check nameOrPath;
      name = last (builtins.split "/" nameOrPath);
      path = if nameIsPath then nameOrPath else "/bin/${name}";
      # The inner derivation which creates the executable under $out/bin (never at $out directly)
      # This is required in order to support wrapping, as wrapped programs consist of
      # at least two files: the executable and the wrapper.
      inner =
        pkgs.runCommandLocal name
          (
            {
              inherit makeWrapperArgs;
              nativeBuildInputs = [ makeBinaryWrapper ];
              meta.mainProgram = name;
            }
            // (
              if (types.str.check content) then
                {
                  inherit content interpreter;
                  passAsFile = [ "content" ];
                }
              else
                {
                  inherit interpreter;
                  contentPath = content;
                }
            )
          )
          ''
            # On darwin a script cannot be used as an interpreter in a shebang but
            # there doesn't seem to be a limit to the size of shebang and multiple
            # arguments to the interpreter are allowed.
            if [[ -n "${toString pkgs.stdenvNoCC.hostPlatform.isDarwin}" ]] && isScript $interpreter
            then
              wrapperInterpreterLine=$(head -1 "$interpreter" | tail -c+3)
              # Get first word from the line (note: xargs echo remove leading spaces)
              wrapperInterpreter=$(echo "$wrapperInterpreterLine" | xargs echo | cut -d " " -f1)

              if isScript $wrapperInterpreter
              then
                echo "error: passed interpreter ($interpreter) is a script which has another script ($wrapperInterpreter) as an interpreter, which is not supported."
                exit 1
              fi

              # This should work as long as wrapperInterpreter is a shell, which is
              # the case for programs wrapped with makeWrapper, like
              # python3.withPackages etc.
              interpreterLine="$wrapperInterpreterLine $interpreter"
            else
              interpreterLine=$interpreter
            fi

            echo "#! $interpreterLine" > $out
            cat "$contentPath" >> $out
            ${optionalString (check != "") ''
              ${check} $out
            ''}
            chmod +x $out

            # Relocate executable
            # Wrap it if makeWrapperArgs are specified
            mv $out tmp
              mkdir -p $out/$(dirname "${path}")
              mv tmp $out/${path}
            if [ -n "''${makeWrapperArgs+''${makeWrapperArgs[@]}}" ]; then
                wrapProgram $out/${path} ''${makeWrapperArgs[@]}
            fi
          '';
    in
    if nameIsPath then
      inner
    # In case nameOrPath is a name, the user intends the executable to be located at $out.
    # This is achieved by creating a separate derivation containing a symlink at $out linking to ${inner}/bin/${name}.
    # This breaks the override pattern.
    # In case this turns out to be a problem, we can still add more magic
    else
      pkgs.runCommandLocal name { } ''
        ln -s ${inner}/bin/${name} $out
      '';

  /**
    `makeBinWriter` returns a derivation which compiles the given script into an executable format.

    :::{.note}
    This function is the base implementation for other compile language `writers`, such as `writeHaskell` and `writeRust`.
    :::

    # Inputs

    config (AttrSet)
    : `compileScript` (String)
      : The script that compiles the given content into an executable.

    : `strip` (Boolean, Default: true)
      : Whether to [strip](https://nixos.org/manual/nixpkgs/stable/#ssec-fixup-phase) the executable or not.

    : `makeWrapperArgs` (Optional, [ String ], Default: [])
      : Arguments forwarded to (`makeWrapper`)[#fun-makeWrapper]

    `nameOrPath` (String)
    : The name of the script or the path to the script.

      When a `string` starting with "/" is passed, the script will be created at the specified path in $out.
      For example, `"/bin/hello"` will create a script at `$out/bin/hello`.

      Any other `string` is interpreted as a filename.
      It must be a [POSIX filename](https://en.wikipedia.org/wiki/Filename) starting with a letter, digit, dot, or underscore.
      Spaces or special characters are not allowed.

    # Examples
    :::{.example}
    ## `pkgs.writers.makeBinWriter` example

    ```c
    // main.c
    #include <stdio.h>

    int main()
    {
        printf("Hello, World!\n");
        return 0;
    }
    ```

    ```nix-repl
    :b makeBinWriter { compileScript = "${pkgs.gcc}/bin/gcc -o $out $contentPath"; } "hello" ./main.c
    out -> /nix/store/f6crc8mwj3lvcxqclw7n09cm8nb6kxbh-hello
    ```

    The above example creates an executable named `hello` that outputs `Hello, World!` when executed.

    ```sh
    > /nix/store/f6crc8mwj3lvcxqclw7n09cm8nb6kxbh-hello
    Hello, World!
    ```
    :::
  */
  makeBinWriter =
    {
      compileScript,
      strip ? true,
      makeWrapperArgs ? [ ],
    }:
    nameOrPath: content:
    assert
      (types.path.check nameOrPath)
      || (builtins.match "([0-9A-Za-z._])[0-9A-Za-z._-]*" nameOrPath != null);
    assert (types.path.check content) || (types.str.check content);
    let
      nameIsPath = types.path.check nameOrPath;
      name = last (builtins.split "/" nameOrPath);
      path = if nameIsPath then nameOrPath else "/bin/${name}";
      # The inner derivation which creates the executable under $out/bin (never at $out directly)
      # This is required in order to support wrapping, as wrapped programs consist of at least two files: the executable and the wrapper.
      inner =
        pkgs.runCommandLocal name
          (
            {
              inherit makeWrapperArgs;
              nativeBuildInputs = [ makeBinaryWrapper ];
              meta.mainProgram = name;
            }
            // (
              if (types.str.check content) then
                {
                  inherit content;
                  passAsFile = [ "content" ];
                }
              else
                { contentPath = content; }
            )
          )
          ''
            ${compileScript}
            ${lib.optionalString strip "${lib.getBin buildPackages.bintools-unwrapped}/bin/${buildPackages.bintools-unwrapped.targetPrefix}strip -S $out"}
            # Sometimes binaries produced for darwin (e. g. by GHC) won't be valid
            # mach-o executables from the get-go, but need to be corrected somehow
            # which is done by fixupPhase.
            ${lib.optionalString pkgs.stdenvNoCC.hostPlatform.isDarwin "fixupPhase"}
            mv $out tmp
            mkdir -p $out/$(dirname "${path}")
            mv tmp $out/${path}
            if [ -n "''${makeWrapperArgs+''${makeWrapperArgs[@]}}" ]; then
              wrapProgram $out/${path} ''${makeWrapperArgs[@]}
            fi
          '';
    in
    if nameIsPath then
      inner
    # In case nameOrPath is a name, the user intends the executable to be located at $out.
    # This is achieved by creating a separate derivation containing a symlink at $out linking to ${inner}/bin/${name}.
    # This breaks the override pattern.
    # In case this turns out to be a problem, we can still add more magic
    else
      pkgs.runCommandLocal name { } ''
        ln -s ${inner}/bin/${name} $out
      '';

  /**
    Like writeScript but the first line is a shebang to bash
    Can be called with or without extra arguments.

    # Examples
    :::{.example}

    ## Without arguments

    ```nix
    writeBash "example" ''
    echo hello world
    ''
    ```

    ## With arguments

    ```nix
    writeBash "example"
    {
      makeWrapperArgs = [
        "--prefix" "PATH" ":" "${lib.makeBinPath [ pkgs.hello ]}"
      ];
    }
    ''
      hello
    ''
    ```
    :::
  */
  writeBash =
    name: argsOrScript:
    if lib.isAttrs argsOrScript && !lib.isDerivation argsOrScript then
      makeScriptWriter (argsOrScript // { interpreter = "${lib.getExe pkgs.bash}"; }) name
    else
      makeScriptWriter { interpreter = "${lib.getExe pkgs.bash}"; } name argsOrScript;

  /**
    Like writeScriptBin but the first line is a shebang to bash

    Can be called with or without extra arguments.

    ## Examples
    :::{.example}
    ## `pkgs.writers.writeBashBin` example without arguments

    ```nix
    writeBashBin "example" ''
      echo hello world
    ''
    ```
    :::

    :::{.example}
    ## `pkgs.writers.writeBashBin` example with arguments

    ```nix
    writeBashBin "example"
    {
      makeWrapperArgs = [
        "--prefix" "PATH" ":" "${lib.makeBinPath [ pkgs.hello ]}"
      ];
    }
    ''
      hello
    ''
    ```
    :::
  */
  writeBashBin = name: writeBash "/bin/${name}";

  /**
    Like writeScript but the first line is a shebang to dash

    Can be called with or without extra arguments.

    # Example
    :::{.example}
    ## `pkgs.writers.writeDash` example without arguments

    ```nix
    writeDash "example" ''
      echo hello world
    ''
    ```
    :::

    :::{.example}
    ## `pkgs.writers.writeDash` example with arguments

    ```nix
    writeDash "example"
    {
      makeWrapperArgs = [
        "--prefix" "PATH" ":" "${lib.makeBinPath [ pkgs.hello ]}"
      ];
    }
    ''
      hello
    ''
    ```
    :::
  */
  writeDash =
    name: argsOrScript:
    if lib.isAttrs argsOrScript && !lib.isDerivation argsOrScript then
      makeScriptWriter (argsOrScript // { interpreter = "${lib.getExe pkgs.dash}"; }) name
    else
      makeScriptWriter { interpreter = "${lib.getExe pkgs.dash}"; } name argsOrScript;

  /**
    Like writeScriptBin but the first line is a shebang to dash

    Can be called with or without extra arguments.

    # Examples
    :::{.example}
    ## `pkgs.writers.writeDashBin` without arguments

    ```nix
    writeDashBin "example" ''
      echo hello world
    ''
    ```
    :::

    :::{.example}
    ## `pkgs.writers.writeDashBin` with arguments

    ```nix
    writeDashBin "example"
    {
      makeWrapperArgs = [
        "--prefix" "PATH" ":" "${lib.makeBinPath [ pkgs.hello ]}"
      ];
    }
    ''
      hello
    ''
    ```
    :::
  */
  writeDashBin = name: writeDash "/bin/${name}";

  /**
    Like writeScript but the first line is a shebang to fish

    Can be called with or without extra arguments.

    :::{.example}
    ## `pkgs.writers.writeFish` without arguments

    ```nix
    writeFish "example" ''
      echo hello world
    ''
    ```
    :::

    :::{.example}
    ## `pkgs.writers.writeFish` with arguments

    ```nix
    writeFish "example"
    {
      makeWrapperArgs = [
        "--prefix" "PATH" ":" "${lib.makeBinPath [ pkgs.hello ]}"
      ];
    }
    ''
      hello
    ''
    ```
    :::
  */
  writeFish =
    name: argsOrScript:
    if lib.isAttrs argsOrScript && !lib.isDerivation argsOrScript then
      makeScriptWriter (
        argsOrScript
        // {
          interpreter = "${lib.getExe pkgs.fish} --no-config";
          check = "${lib.getExe pkgs.fish} --no-config --no-execute"; # syntax check only
        }
      ) name
    else
      makeScriptWriter {
        interpreter = "${lib.getExe pkgs.fish} --no-config";
        check = "${lib.getExe pkgs.fish} --no-config --no-execute"; # syntax check only
      } name argsOrScript;

  /**
    Like writeScriptBin but the first line is a shebang to fish

    Can be called with or without extra arguments.

    # Examples
    :::{.example}
    ## `pkgs.writers.writeFishBin` without arguments

    ```nix
    writeFishBin "example" ''
      echo hello world
    ''
    ```
    :::

    :::{.example}
    ## `pkgs.writers.writeFishBin` with arguments

    ```nix
    writeFishBin "example"
    {
      makeWrapperArgs = [
        "--prefix" "PATH" ":" "${lib.makeBinPath [ pkgs.hello ]}"
      ];
    }
    ''
      hello
    ''
    ```
    :::
  */
  writeFishBin = name: writeFish "/bin/${name}";

  /**
    writeHaskell takes a name, an attrset with libraries and haskell version (both optional)
    and some haskell source code and returns an executable.

    # Examples
    :::{.example}
    ## `pkgs.writers.writeHaskell` usage example

    ```nix
    writeHaskell "missiles" { libraries = [ pkgs.haskellPackages.acme-missiles ]; } ''
      import Acme.Missiles

      main = launchMissiles
    '';
    ```
    :::
  */
  writeHaskell =
    name:
    {
      ghc ? pkgs.ghc,
      ghcArgs ? [ ],
      libraries ? [ ],
      makeWrapperArgs ? [ ],
      strip ? true,
      threadedRuntime ? true,
    }:
    let
      appendIfNotSet = el: list: if elem el list then list else list ++ [ el ];
      ghcArgs' = if threadedRuntime then appendIfNotSet "-threaded" ghcArgs else ghcArgs;

    in
    makeBinWriter {
      compileScript = ''
        cp $contentPath tmp.hs
        ${(ghc.withPackages (_: libraries))}/bin/ghc ${lib.escapeShellArgs ghcArgs'} tmp.hs
        mv tmp $out
      '';
      inherit makeWrapperArgs strip;
    } name;

  /**
    writeHaskellBin takes the same arguments as writeHaskell but outputs a directory (like writeScriptBin)
  */
  writeHaskellBin = name: writeHaskell "/bin/${name}";

  /**
    Like writeScript but the first line is a shebang to nu

    Can be called with or without extra arguments.

    # Examples
    :::{.example}
    ## `pkgs.writers.writeNu` without arguments

    ```nix
    writeNu "example" ''
      echo hello world
    ''
    ```
    :::

    :::{.example}
    ## `pkgs.writers.writeNu` with arguments

    ```nix
    writeNu "example"
      {
        makeWrapperArgs = [
          "--prefix" "PATH" ":" "${lib.makeBinPath [ pkgs.hello ]}"
        ];
      }
      ''
        hello
      ''
    ```
    :::
  */
  writeNu =
    name: argsOrScript:
    if lib.isAttrs argsOrScript && !lib.isDerivation argsOrScript then
      makeScriptWriter (
        argsOrScript // { interpreter = "${lib.getExe pkgs.nushell} --no-config-file"; }
      ) name
    else
      makeScriptWriter { interpreter = "${lib.getExe pkgs.nushell} --no-config-file"; } name argsOrScript;

  /**
    Like writeScriptBin but the first line is a shebang to nu

    Can be called with or without extra arguments.

    # Examples
    :::{.example}
    ## `pkgs.writers.writeNuBin` without arguments

    ```nix
    writeNuBin "example" ''
      echo hello world
    ''
    ```
    :::

    :::{.example}
    ## `pkgs.writers.writeNuBin` with arguments

    ```nix
    writeNuBin "example"
      {
        makeWrapperArgs = [
          "--prefix" "PATH" ":" "${lib.makeBinPath [ pkgs.hello ]}"
        ];
      }
      ''
        hello
      ''
    ```
    :::
  */
  writeNuBin = name: writeNu "/bin/${name}";

  /**
    makeRubyWriter takes ruby and compatible rubyPackages and produces ruby script writer,
    If any libraries are specified, ruby.withPackages is used as interpreter, otherwise the "bare" ruby is used.
  */
  makeRubyWriter =
    ruby: rubyPackages: buildRubyPackages: name:
    {
      libraries ? [ ],
      ...
    }@args:
    makeScriptWriter (
      (builtins.removeAttrs args [ "libraries" ])
      // {
        interpreter =
          if libraries == [ ] then "${ruby}/bin/ruby" else "${(ruby.withPackages (ps: libraries))}/bin/ruby";
        # Rubocop doesn't seem to like running in this fashion.
        #check = (writeDash "rubocop.sh" ''
        #  exec ${lib.getExe buildRubyPackages.rubocop} "$1"
        #'');
      }
    ) name;

  /**
    Like writeScript but the first line is a shebang to ruby

    # Examples
    :::{.example}
    ## `pkgs.writers.writeRuby` usage example

    ```nix
    writeRuby "example" { libraries = [ pkgs.rubyPackages.git ]; } ''
     puts "hello world"
    ''
    ```

    :::
  */
  writeRuby = makeRubyWriter pkgs.ruby pkgs.rubyPackages buildPackages.rubyPackages;

  writeRubyBin = name: writeRuby "/bin/${name}";

  /**
    makeLuaWriter takes lua and compatible luaPackages and produces lua script writer,
    which validates the script with luacheck at build time. If any libraries are specified,
    lua.withPackages is used as interpreter, otherwise the "bare" lua is used.
  */
  makeLuaWriter =
    lua: luaPackages: buildLuaPackages: name:
    {
      libraries ? [ ],
      ...
    }@args:
    makeScriptWriter (
      (builtins.removeAttrs args [ "libraries" ])
      // {
        interpreter = lua.interpreter;
        # if libraries == []
        # then lua.interpreter
        # else (lua.withPackages (ps: libraries)).interpreter
        # This should support packages! I just cant figure out why some dependency collision happens whenever I try to run this.
        check = (
          writeDash "luacheck.sh" ''
            exec ${buildLuaPackages.luacheck}/bin/luacheck "$1"
          ''
        );
      }
    ) name;

  /**
    writeLua takes a name an attributeset with libraries and some lua source code and
    returns an executable (should also work with luajit)

    # Examples
    :::{.example}
    ## `pkgs.writers.writeLua` usage example

    ```nix
    writeLua "test_lua" { libraries = [ pkgs.luaPackages.say ]; } ''
      s = require("say")
      s:set_namespace("en")

      s:set('money', 'I have %s dollars')
      s:set('wow', 'So much money!')

      print(s('money', {1000})) -- I have 1000 dollars

      s:set_namespace("fr") -- switch to french!
      s:set('wow', "Tant d'argent!")

      print(s('wow')) -- Tant d'argent!
      s:set_namespace("en")  -- switch back to english!
      print(s('wow')) -- So much money!
    ''
    ```

    :::
  */
  writeLua = makeLuaWriter pkgs.lua pkgs.luaPackages buildPackages.luaPackages;

  writeLuaBin = name: writeLua "/bin/${name}";

  writeRust =
    name:
    {
      makeWrapperArgs ? [ ],
      rustc ? pkgs.rustc,
      rustcArgs ? [ ],
      strip ? true,
    }:
    let
      darwinArgs = lib.optionals stdenv.hostPlatform.isDarwin [ "-L${lib.getLib libiconv}/lib" ];
    in
    makeBinWriter {
      compileScript = ''
        cp "$contentPath" tmp.rs
        PATH=${lib.makeBinPath [ pkgs.gcc ]} ${rustc}/bin/rustc ${lib.escapeShellArgs rustcArgs} ${lib.escapeShellArgs darwinArgs} -o "$out" tmp.rs
      '';
      inherit makeWrapperArgs strip;
    } name;

  writeRustBin = name: writeRust "/bin/${name}";

  /**
    writeJS takes a name an attributeset with libraries and some JavaScript sourcecode and
    returns an executable

    # Inputs

    `name`

    : 1\. Function argument

    `attrs`

    : 2\. Function argument

    `content`

    : 3\. Function argument

    # Examples
    :::{.example}
    ## `pkgs.writers.writeJS` usage example

    ```nix
    writeJS "example" { libraries = [ pkgs.uglify-js ]; } ''
      var UglifyJS = require("uglify-js");
      var code = "function add(first, second) { return first + second; }";
      var result = UglifyJS.minify(code);
      console.log(result.code);
    ''
    ```

    :::
  */
  writeJS =
    name:
    {
      libraries ? [ ],
    }:
    content:
    let
      node-env = pkgs.buildEnv {
        name = "node";
        paths = libraries;
        pathsToLink = [ "/lib/node_modules" ];
      };
    in
    writeDash name ''
      export NODE_PATH=${node-env}/lib/node_modules
      exec ${lib.getExe pkgs.nodejs} ${pkgs.writeText "js" content} "$@"
    '';

  /**
    writeJSBin takes the same arguments as writeJS but outputs a directory (like writeScriptBin)
  */
  writeJSBin = name: writeJS "/bin/${name}";

  awkFormatNginx = builtins.toFile "awkFormat-nginx.awk" ''
    awk -f
    {sub(/^[ \t]+/,"");idx=0}
    /\{/{ctx++;idx=1}
    /\}/{ctx--}
    {id="";for(i=idx;i<ctx;i++)id=sprintf("%s%s", id, "\t");printf "%s%s\n", id, $0}
  '';

  writeNginxConfig =
    name: text:
    pkgs.runCommandLocal name
      {
        inherit text;
        passAsFile = [ "text" ];
        nativeBuildInputs = [ gixy ];
      } # sh
      ''
        # nginx-config-formatter has an error - https://github.com/1connect/nginx-config-formatter/issues/16
        awk -f ${awkFormatNginx} "$textPath" | sed '/^\s*$/d' > $out
        gixy $out
      '';

  /**
    writePerl takes a name an attributeset with libraries and some perl sourcecode and
    returns an executable

    # Examples
    :::{.example}
    ## `pkgs.writers.writePerl` usage example

    ```nix
    writePerl "example" { libraries = [ pkgs.perlPackages.boolean ]; } ''
      use boolean;
      print "Howdy!\n" if true;
    ''
    ```

    :::
  */
  writePerl =
    name:
    {
      libraries ? [ ],
      ...
    }@args:
    makeScriptWriter (
      (builtins.removeAttrs args [ "libraries" ])
      // {
        interpreter = "${lib.getExe (pkgs.perl.withPackages (p: libraries))}";
      }
    ) name;

  /**
    writePerlBin takes the same arguments as writePerl but outputs a directory (like writeScriptBin)
  */
  writePerlBin = name: writePerl "/bin/${name}";

  /**
    makePythonWriter takes python and compatible pythonPackages and produces python script writer,
    which validates the script with flake8 at build time. If any libraries are specified,
    python.withPackages is used as interpreter, otherwise the "bare" python is used.

    # Inputs

    `python`

    : 1\. Function argument

    `pythonPackages`

    : 2\. Function argument

    `buildPythonPackages`

    : 3\. Function argument

    `name`

    : 4\. Function argument

    `attrs`

    : 5\. Function argument
  */
  makePythonWriter =
    python: pythonPackages: buildPythonPackages: name:
    {
      libraries ? [ ],
      flakeIgnore ? [ ],
      doCheck ? true,
      ...
    }@args:
    let
      ignoreAttribute =
        optionalString (flakeIgnore != [ ])
          "--ignore ${concatMapStringsSep "," escapeShellArg flakeIgnore}";
    in
    makeScriptWriter (
      (builtins.removeAttrs args [
        "libraries"
        "flakeIgnore"
        "doCheck"
      ])
      // {
        interpreter =
          if pythonPackages != pkgs.pypy2Packages || pythonPackages != pkgs.pypy3Packages then
            if libraries == [ ] then python.interpreter else (python.withPackages (ps: libraries)).interpreter
          else
            python.interpreter;
        check = optionalString (python.isPy3k && doCheck) (
          writeDash "pythoncheck.sh" ''
            exec ${buildPythonPackages.flake8}/bin/flake8 --show-source ${ignoreAttribute} "$1"
          ''
        );
      }
    ) name;

  /**
    writePyPy2 takes a name an attributeset with libraries and some pypy2 sourcecode and
    returns an executable

    # Examples
    :::{.example}
    ## `pkgs.writers.writePyPy2` usage example

    ```nix
    writePyPy2 "test_pypy2" { libraries = [ pkgs.pypy2Packages.enum ]; } ''
      from enum import Enum

      class Test(Enum):
          a = "success"

      print Test.a
    ''
    ```

    :::
  */
  writePyPy2 = makePythonWriter pkgs.pypy2 pkgs.pypy2Packages buildPackages.pypy2Packages;

  /**
    writePyPy2Bin takes the same arguments as writePyPy2 but outputs a directory (like writeScriptBin)
  */
  writePyPy2Bin = name: writePyPy2 "/bin/${name}";

  /**
    writePython3 takes a name an attributeset with libraries and some python3 sourcecode and
    returns an executable

    # Examples
    :::{.example}
    ## `pkgs.writers.writePython3` usage example

    ```nix
    writePython3 "test_python3" { libraries = [ pkgs.python3Packages.pyyaml ]; } ''
      import yaml

      y = yaml.safe_load("""
        - test: success
      """)
      print(y[0]['test'])
    ''
    ```

    :::
  */
  writePython3 = makePythonWriter pkgs.python3 pkgs.python3Packages buildPackages.python3Packages;

  # writePython3Bin takes the same arguments as writePython3 but outputs a directory (like writeScriptBin)
  writePython3Bin = name: writePython3 "/bin/${name}";

  /**
    writePyPy3 takes a name an attributeset with libraries and some pypy3 sourcecode and
    returns an executable

    # Examples
    :::{.example}
    ## `pkgs.writers.writePyPy3` usage example

    ```nix
    writePyPy3 "test_pypy3" { libraries = [ pkgs.pypy3Packages.pyyaml ]; } ''
      import yaml

      y = yaml.safe_load("""
        - test: success
      """)
      print(y[0]['test'])
    ''
    ```

    :::
  */
  writePyPy3 = makePythonWriter pkgs.pypy3 pkgs.pypy3Packages buildPackages.pypy3Packages;

  /**
    writePyPy3Bin takes the same arguments as writePyPy3 but outputs a directory (like writeScriptBin)
  */
  writePyPy3Bin = name: writePyPy3 "/bin/${name}";

  makeFSharpWriter =
    {
      dotnet-sdk ? pkgs.dotnet-sdk,
      fsi-flags ? "",
      libraries ? _: [ ],
      ...
    }@args:
    nameOrPath:
    let
      fname = last (builtins.split "/" nameOrPath);
      path = if strings.hasSuffix ".fsx" nameOrPath then nameOrPath else "${nameOrPath}.fsx";
      _nugetDeps = mkNugetDeps {
        name = "${fname}-nuget-deps";
        nugetDeps = libraries;
      };

      nuget-source = mkNugetSource {
        name = "${fname}-nuget-source";
        description = "Nuget source with the dependencies for ${fname}";
        deps = [ _nugetDeps ];
      };

      fsi = writeBash "fsi" ''
        export HOME=$NIX_BUILD_TOP/.home
        export DOTNET_SKIP_FIRST_TIME_EXPERIENCE=1
        export DOTNET_CLI_TELEMETRY_OPTOUT=1
        export DOTNET_NOLOGO=1
        script="$1"; shift
        ${lib.getExe dotnet-sdk} fsi --quiet --nologo --readline- ${fsi-flags} "$@" < "$script"
      '';

    in
    content:
    makeScriptWriter
      (
        (builtins.removeAttrs args [
          "dotnet-sdk"
          "fsi-flags"
          "libraries"
        ])
        // {
          interpreter = fsi;
        }
      )
      path
      ''
        #i "nuget: ${nuget-source}/lib"
        ${content}
        exit 0
      '';

  writeFSharp = makeFSharpWriter { };

  writeFSharpBin = name: writeFSharp "/bin/${name}";
}