11import * as Debug from "debug" ;
22import { mkdir , mkdtemp , rm , stat , writeFile } from "fs/promises" ;
3+ import * as os from "os" ;
34import * as path from "path" ;
45import { FilePathToContent , FilesByDirMap } from "./types" ;
56const debug = Debug ( "snyk" ) ;
@@ -22,7 +23,7 @@ interface ScanPaths {
2223async function createTempProjectDir (
2324 projectDir : string ,
2425) : Promise < { tmpDir : string ; tempProjectRoot : string } > {
25- const tmpDir = await mkdtemp ( "snyk" ) ;
26+ const tmpDir = await mkdtemp ( path . join ( os . tmpdir ( ) , "snyk-" ) ) ;
2627
2728 const tempProjectRoot = path . join ( tmpDir , projectDir ) ;
2829
@@ -76,20 +77,23 @@ async function persistNodeModules(
7677 fileNamesGroupedByDirectory : FilesByDirMap ,
7778) : Promise < ScanPaths > {
7879 const modules = fileNamesGroupedByDirectory . get ( project ) ;
79- const tmpDir : string = "" ;
80- const tempProjectRoot : string = "" ;
8180
8281 if ( ! modules || modules . size === 0 ) {
8382 debug ( `Empty application directory tree.` ) ;
84-
85- return {
86- tempDir : tmpDir ,
87- tempProjectPath : tempProjectRoot ,
88- } ;
83+ return { tempDir : "" , tempProjectPath : "" } ;
8984 }
9085
86+ // Create the temp directory first so we can return it in the catch block
87+ // for cleanup. Previously, the outer tmpDir/tempProjectRoot were always
88+ // empty strings, meaning any temp directory created before a failure in
89+ // saveOnDisk or later steps would be leaked (caller couldn't clean it up).
90+ let tmpDir = "" ;
91+ let tempProjectRoot = "" ;
92+
9193 try {
92- const { tmpDir, tempProjectRoot } = await createTempProjectDir ( project ) ;
94+ const created = await createTempProjectDir ( project ) ;
95+ tmpDir = created . tmpDir ;
96+ tempProjectRoot = created . tempProjectRoot ;
9397
9498 await saveOnDisk ( tmpDir , modules , filePathToContent ) ;
9599
@@ -122,7 +126,10 @@ async function persistNodeModules(
122126 }
123127}
124128
125- async function createFile ( filePath , fileContent ) : Promise < void > {
129+ async function createFile (
130+ filePath : string ,
131+ fileContent : string ,
132+ ) : Promise < void > {
126133 try {
127134 await mkdir ( path . dirname ( filePath ) , { recursive : true } ) ;
128135 await writeFile ( filePath , fileContent , "utf-8" ) ;
0 commit comments