Skip to content

Commit

Permalink
Added logic to generate a temp directory
Browse files Browse the repository at this point in the history
  • Loading branch information
techiemac committed Nov 14, 2021
1 parent fc704b5 commit 4c7d776
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 6 deletions.
11 changes: 11 additions & 0 deletions pkg/fshelper/fshelper.go
@@ -0,0 +1,11 @@
package fshelper

// TempDirExecFunc is the function that runs in the temp path
type TempDirExecFunc func(path string) error

type FsHelper interface {
CreatePath(filename string) error
ReadJson(filename string, obj interface{}) error
WriteJson(filename string, obj interface{}) error
RunInTempDir(useFullPath bool, exec TempDirExecFunc) error
}
6 changes: 0 additions & 6 deletions pkg/fshelper/loader.go
Expand Up @@ -7,12 +7,6 @@ import (
"path/filepath"
)

type FsHelper interface {
CreatePath(filename string) error
ReadJson(filename string, obj interface{}) error
WriteJson(filename string, obj interface{}) error
}

type FsHelp struct {
Fs afero.Fs
}
Expand Down
44 changes: 44 additions & 0 deletions pkg/fshelper/runner.go
@@ -0,0 +1,44 @@
package fshelper

import (
"log"
"os"
"path"
)

const TempDirName = "swiztmpdir"

// RunInTempDir runs the specified function in a temporary directory that gets cleaned up
func (f FsHelp) RunInTempDir(useFullPath bool, exec TempDirExecFunc) error {
log.Printf("[DEBUG] Creating temp dir %v", TempDirName)

// Create dir
err := f.Fs.Mkdir(TempDirName, 0700)
if err != nil {
return err
}

dir := TempDirName
if useFullPath {
wdDir, wdErr := os.Getwd()
if wdErr != nil {
return wdErr
}
dir = path.Join(wdDir, TempDirName)
}

// Execute
err = exec(dir)
if err != nil {
return err
}

// Clean up
log.Printf("[DEBUG] Cleaning up temp directory")
err = os.RemoveAll(TempDirName)
if err != nil {
log.Printf("[WARN] Error removing temporary directory %v", TempDirName)
}

return nil
}

0 comments on commit 4c7d776

Please sign in to comment.