about summary refs log tree commit diff
path: root/users/sterni/nix/build/toPlainText/default.nix
blob: c59e372d3b50be1e777dfeb4beab303286056c6a (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
{ pkgs, depot, lib, ... }:

{ fmt ? null
, passthru ? { }
, ...
}@args:

let
  inherit (depot.nix) getBins utils;

  bins = getBins pkgs.lowdown [
    "lowdown"
  ] // getBins pkgs.mandoc [
    "mandoc"
  ] // getBins pkgs.gnused [
    "sed"
  ];

  actions = {
    mdoc = ''
      ${bins.mandoc} -T utf8 "${thing}" > "$out"
    '';

    # Use lowdown's terminal target, but strip all ANSI SGR escape sequences
    markdown = ''
      ${bins.lowdown} -Tterm "${thing}" \
      | ${bins.sed} -e 's|\\x1b\\[[;0-9]*m||g' \
      > "$out"
    '';

    plain = ''
      cp --reflink=auto "${thing}" "$out"
    '';
  };

  thingType = builtins.head (
    builtins.filter (x: x != null) (
      builtins.map (t: if args ? ${t} then t else null) (
        builtins.attrNames actions
      )
    )
  );

  thing = args.${thingType};
  name = args.name or utils.storePathName thing;
in

pkgs.runCommand name
{
  inherit passthru;
}
  (
    actions.${thingType} + lib.optionalString (fmt != null) ''
      fmt -w "${lib.escapeShellArg (toString fmt)}" "$out"
    ''
  )