aboutsummaryrefslogtreecommitdiff
path: root/tools/samtools-view.nix
blob: 4966b1335e3f14ec784c45ce961ce22eac068b29 (plain)
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
{
  bionix,
  nameSort ? false,
  flags ? null,
  outfmt ? null,
  targets ? null,
}: input:
with bionix;
with lib;
with types;
assert (matchFiletype "samtools-view" {
    bam = _: true;
    sam = _: true;
    cram = _: true;
  }
  input); let
  handleTarget = x: let
    type = builtins.typeOf x;
    handler = handlers."${type}" or (builtins.throw "samtools-view:unhandled target type:${type}");
    handlers = {
      string = handleTarget [x];
      list = let
        file = pkgs.writeText "target.bed" (concatStringsSep "\n" x);
      in "--target-file ${file}";
      path = "--target-file ${x}";
      set = "--target-file ${x}";
    };
  in
    handler;

  outfmtR =
    if outfmt != null
    then
      (
        if builtins.typeOf outfmt == "string"
        then
          {
            "bam" = toBam;
            "cram" = toCram;
            "sam" = toSam;
          }
          ."${outfmt}"
        else outfmt
      )
      input
    else input.filetype;
  fa = ref: matchFiletype "samtools-view-ref" {fa = _: ref;} ref;
  outfmtFlags = matchFiletype "samtools-view-outfmt" {
    bam = _: "-O BAM";
    sam = _: "-O SAM";
    cram = x: "-O CRAM -T ${fa x.ref}";
  } {filetype = outfmtR;};
in
  stage {
    name = "samtools-view";
    buildInputs = with pkgs; [samtools];
    buildCommand = ''
      samtools view \
        ${optionalString (targets != null) (handleTarget targets)} \
        ${outfmtFlags} ${optionalString (flags != null) flags} ${input} > $out
    '';
    passthru.filetype = outfmtR;
  }