src/hg/lib/bamFile.c 1.16

1.16 2009/11/30 23:46:52 angie
Since samtools' bam_index_load saves .bai files to the current directory, change to a trashDir when calling it (instead of using a locally hacked samtools).
Index: src/hg/lib/bamFile.c
===================================================================
RCS file: /projects/compbio/cvsroot/kent/src/hg/lib/bamFile.c,v
retrieving revision 1.15
retrieving revision 1.16
diff -b -B -U 4 -r1.15 -r1.16
--- src/hg/lib/bamFile.c	20 Nov 2009 17:51:56 -0000	1.15
+++ src/hg/lib/bamFile.c	30 Nov 2009 23:46:52 -0000	1.16
@@ -138,17 +138,39 @@
     }
 return cloneString(fileOrUrl);
 }
 
+static char *getSamDir()
+/* Return the name of a trash dir for samtools to run in (it creates files in current dir)
+ * and make sure the directory exists. */
+{
+static char *samDir = NULL;
+char *dirName = "samtools";
+if (samDir == NULL)
+    {
+    mkdirTrashDirectory(dirName);
+    size_t len = strlen(trashDir()) + 1 + strlen(dirName) + 1;
+    samDir = needMem(len);
+    safef(samDir, len, "%s/%s", trashDir(), dirName);
+    }
+return samDir;
+}
+
 boolean bamFileExists(char *fileOrUrl)
 /* Return TRUE if we can successfully open the bam file and its index file. */
 {
 char *bamFileName = samtoolsFileName(fileOrUrl);
 samfile_t *fh = samopen(bamFileName, "rb", NULL);
 if (fh != NULL)
     {
     // When file is an URL, this caches the index file in addition to validating:
+    // Since samtools's url-handling code saves the .bai file to the current directory,
+    // chdir to a trash directory before calling bam_index_load, then chdir back.
+    char *runDir = getCurrentDir();
+    char *samDir = getSamDir();
+    setCurrentDir(samDir);
     bam_index_t *idx = bam_index_load(bamFileName);
+    setCurrentDir(runDir);
     samclose(fh);
     if (idx == NULL)
 	{
 	warn("bamFileExists: failed to read index corresponding to %s", bamFileName);
@@ -176,9 +198,15 @@
 if (ret != 0)
     // If the bam file does not cover the current chromosome, OK
     return;
 
+// Since samtools' url-handling code saves the .bai file to the current directory,
+// chdir to a trash directory before calling bam_index_load, then chdir back.
+char *runDir = getCurrentDir();
+char *samDir = getSamDir();
+setCurrentDir(samDir);
 bam_index_t *idx = bam_index_load(bamFileName);
+setCurrentDir(runDir);
 if (idx == NULL)
     errAbort("bam_index_load(%s) failed.", bamFileName);
 ret = bam_fetch(fh->x.bam, idx, chromId, start, end, callbackData, callbackFunc);
 if (ret != 0)