jet/internal/utils/filesys/filesys.go

59 lines
1.4 KiB
Go
Raw Permalink Normal View History

2023-07-21 14:11:31 +02:00
package filesys
import (
"errors"
2023-07-21 14:11:31 +02:00
"fmt"
"go/format"
"os"
"path/filepath"
"strings"
)
// FormatAndSaveGoFile saves go file at folder dir, with name fileName and contents text.
func FormatAndSaveGoFile(dirPath, fileName string, text []byte) error {
newGoFilePath := filepath.Join(dirPath, fileName)
if !strings.HasSuffix(newGoFilePath, ".go") {
newGoFilePath += ".go"
}
file, err := os.Create(newGoFilePath) // #nosec 304
2023-07-21 14:11:31 +02:00
if err != nil {
return err
}
defer file.Close()
p, err := format.Source(text)
// if there is a format error we will write unformulated text for debug purposes
if err != nil {
_, writeErr := file.Write(text)
if writeErr != nil {
return errors.Join(writeErr, fmt.Errorf("failed to format '%s', check '%s' for syntax errors: %w", fileName, newGoFilePath, err))
}
2023-07-21 14:11:31 +02:00
return fmt.Errorf("failed to format '%s', check '%s' for syntax errors: %w", fileName, newGoFilePath, err)
}
_, err = file.Write(p)
if err != nil {
return fmt.Errorf("failed to save '%s' file: %w", newGoFilePath, err)
}
return nil
}
// EnsureDirPathExist ensures dir path exists. If path does not exist, creates new path.
func EnsureDirPathExist(dirPath string) error {
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
err := os.MkdirAll(dirPath, 0o750)
2023-07-21 14:11:31 +02:00
if err != nil {
return fmt.Errorf("can't create directory - %s: %w", dirPath, err)
}
}
return nil
}