From e7a2705bb3818db7647c7a37ef675760c323bd26 Mon Sep 17 00:00:00 2001
From: Justin Bedo <cu@cua0.org>
Date: Thu, 2 May 2019 07:45:02 +1000
Subject: samtools-merge: detect correct sorting

---
 tools/samtools-merge.nix | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

(limited to 'tools')

diff --git a/tools/samtools-merge.nix b/tools/samtools-merge.nix
index 9b7d133..81b0c15 100644
--- a/tools/samtools-merge.nix
+++ b/tools/samtools-merge.nix
@@ -10,7 +10,8 @@ with lib;
 
 let
   inherit (bionix.types) matchFiletype matchSorting;
-  inputIsHomogenous = length (unique (map (matchFiletype "samtools-merge" {bam = x: x // {sorting = matchSorting "samtools-merge" {coord = _: "coord";} x;};}) inputs)) == 1;
+  inputIsHomogenous = length (unique (map (matchFiletype "samtools-merge" {bam = x: x // {sorting = matchSorting "samtools-merge" {coord = _: "coord"; name = _: "name"; } x;};}) inputs)) == 1;
+  nameSorted = matchFiletype "samtools-merge" { bam = x: matchSorting "samtools-merge" {coord = _: false; name = _: true;} x;} (lib.head inputs);
 in
 
 assert inputIsHomogenous;
@@ -19,7 +20,9 @@ stage {
   name = "samtools-merge";
   buildInputs = with pkgs; [ samtools ];
   buildCommand = ''
-    samtools merge ${optionalString (flags != null) flags} out.bam ${concatStringsSep " " inputs}
+    samtools merge ${optionalString (flags != null) flags} \
+      ${if nameSorted then "-n" else ""} \
+      out.bam ${concatStringsSep " " inputs}
 
     # Merge is non-deterministic with PG lines; if files have clashing PG IDs then a random
     # suffix is appended to make it unique. PG lines are stripped in the following to
-- 
cgit v1.2.3