【问题标题】:How to read file and apply substitutions to its content?如何读取文件并对其内容应用替换?
【发布时间】:2021-06-13 23:36:49
【问题描述】:

我有一个长字符串,我想将它提取到一个单独的文件中。

prepare = lib.hm.dag.entryAfter ["writeBoundary"] '' very long script with ${...} '';

我可以用builtins.readFile 阅读它,但它不能代替${...} nix 占位符。

如何从文件中读取字符串并解析其中的 nix 变量?

【问题讨论】:

    标签: nix


    【解决方案1】:

    您可以使用substitute bash 函数系列(请参阅Nixpkgs manual)或使用substituteAll Nix 函数,该函数生成执行替换的派生。

    substituteAll { src = ./sample.sh; inherit bash; hi = hello; }
    

    sample.sh:

    #!@bash@/bin/bash
    @hi@
    

    结果:

    $ nix repl <nixpkgs>
    
    nix-repl> substituteAll { src = ./sample.sh; inherit bash; hi = hello; }
    «derivation /nix/store/7klv763a0ipgvwf3j84aazkzx2d5rljz-sample.sh.drv»
    
    nix-repl> :b substituteAll { src = ./sample.sh; inherit bash; hi = hello; }
    
    this derivation produced the following outputs:
      out -> /nix/store/v03hpzw9ykrbyqpmalnijnyibq3waqhw-sample.sh
    
    nix-repl> 
    

    /nix/store/v03hpzw9ykrbyqpmalnijnyibq3waqhw-sample.sh:

    #!/nix/store/a4yw1svqqk4d8lhwinn9xp847zz9gfma-bash-4.4-p23/bin/bash
    /nix/store/jmmw0d3nmklwafcwylvrjb9v69wrbcxf-hello-2.10
    

    【讨论】:

    • 有没有办法将整个集合传递给这个函数?即@pkgs.coreutils.out@
    • 您可以编写一个函数来实现类似的功能,但派生将取决于所有属性,这可能是不可取的,当然对于pkgs。 (substituteAll ({ src = ./sample.sh; } // yourOwnFlatteningFunction x))。也许一个不错的选择是将''-quoted Nix 字符串放在自己的文件中,使其成为pkgs 的函数并使用import ./sample.sh pkgs
    猜你喜欢
    • 2013-03-14
    • 2018-05-14
    • 2021-05-08
    • 2016-10-14
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多