gouick/helpers/file.go
2022-07-15 11:49:53 +00:00

141 lines
2.5 KiB
Go

package helpers
import (
"fmt"
"io/fs"
"io/ioutil"
"os"
"path/filepath"
"github.com/juju/errors"
log "github.com/sirupsen/logrus"
)
func IsStrapProject() (bool, error) {
currentPath, err := os.Getwd()
if err != nil {
return false, err
}
if !fileExists(fmt.Sprintf("%s/%s", currentPath, configFile)) {
return false, nil
}
return true, nil
}
func IsGoProject() (bool, error) {
currentPath, err := os.Getwd()
if err != nil {
return false, err
}
if fileExists(fmt.Sprintf("%s/%s", currentPath, "go.mod")) {
return true, nil
}
if fileExists(fmt.Sprintf("%s/%s", currentPath, "go.sum")) {
return true, nil
}
return false, nil
}
func fileExists(filename string) bool {
info, err := os.Stat(filename)
if errors.Is(err, fs.ErrNotExist) {
return false
}
return !info.IsDir()
}
// isDirectoryWritable
func isDirectoryWritable(path string) (bool, error) {
dirInfo, err := os.Stat(path)
if err != nil {
if errors.Is(err, fs.ErrPermission) {
return false, errors.NewForbidden(err, "directory is not readeable")
} else if errors.Is(err, fs.ErrNotExist) {
return false, errors.NewNotFound(err, "directory does not exit")
} else {
return false, errors.Trace(err)
}
}
if !dirInfo.IsDir() {
return false, errors.NotSupportedf("given path is not a directory")
}
if dirInfo.Mode().Perm()&(1<<(uint(7))) == 0 {
return false, nil
}
return true, nil
}
// createDirectory
func createDirectory(path string) error {
// no need to check if path exist
// MkdirAll will do it for us
err := os.MkdirAll(path, os.ModePerm)
if err != nil {
return errors.Trace(err)
}
return nil
}
// CheckAndCreateDir will check if path is writable and create directory if needed
func CheckAndCreateDir(path string) error {
dirWritable, err := isDirectoryWritable(path)
if dirWritable {
return nil
} else if err != nil && !errors.Is(err, errors.NotFound) {
log.Warnf("impossible to check if the directory is writable")
return err
} else if err == nil && !dirWritable {
log.Warnf("directory is not writable")
return errors.Forbiddenf("directory is not writable")
}
err = createDirectory(path)
if err != nil {
log.Warnf("impossible to create directory (%s), please try again", err.Error())
return err
}
return nil
}
func RemoveDirectoryContent(path string) error {
dir, err := ioutil.ReadDir(path)
if err != nil {
return errors.Trace(err)
}
for _, d := range dir {
err := os.RemoveAll(
filepath.Join(
[]string{"path", d.Name()}...,
),
)
if err != nil {
return errors.Trace(err)
}
}
return nil
}