Skip to content

Commit

Permalink
ensure odir is an empty dir
Browse files Browse the repository at this point in the history
  • Loading branch information
magodo committed Oct 14, 2021
1 parent 1cf9525 commit 8ace0cc
Showing 1 changed file with 25 additions and 14 deletions.
39 changes: 25 additions & 14 deletions internal/meta/meta_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"path"
"path/filepath"
Expand Down Expand Up @@ -55,23 +56,33 @@ func newMetaImpl(rg string, outputDir string) (Meta, error) {
wsp := filepath.Join(rootDir, rg)

if outputDir != "" {
currentWorkingDirectory, err := os.Getwd()
if err != nil {
return nil, fmt.Errorf("error finding the current working directory: %w", err)
}
wsp = outputDir

wsp = filepath.Join(currentWorkingDirectory, outputDir)
_, err = os.Stat(wsp)
if !os.IsNotExist(err) {
return nil, fmt.Errorf("already existing workspace %q: %w", wsp, err)
// Ensure wsp is an empty directory
stat, err := os.Stat(wsp)
if os.IsNotExist(err) {
return nil, fmt.Errorf("the output directory %q doesn't exist", wsp)
}
if !stat.IsDir() {
return nil, fmt.Errorf("the output path %q is not a directory", wsp)
}
}

if err := os.RemoveAll(wsp); err != nil {
return nil, fmt.Errorf("removing existing workspace %q: %w", wsp, err)
}
if err := os.MkdirAll(wsp, 0755); err != nil {
return nil, fmt.Errorf("creating workspace %q: %w", wsp, err)
f, err := os.Open(wsp)
if err != nil {
return nil, err
}
_, err = f.Readdirnames(1) // Or f.Readdir(1)
f.Close()
if err != io.EOF {
return nil, fmt.Errorf("the output directory %q is not empty", wsp)
}
} else {
if err := os.RemoveAll(wsp); err != nil {
return nil, fmt.Errorf("removing existing workspace %q: %w", wsp, err)
}
if err := os.MkdirAll(wsp, 0755); err != nil {
return nil, fmt.Errorf("creating workspace %q: %w", wsp, err)
}
}

// Authentication
Expand Down

0 comments on commit 8ace0cc

Please sign in to comment.