file.go 904 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package util
  2. import (
  3. "bufio"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strings"
  8. "github.com/logrusorgru/aurora"
  9. )
  10. const NL = "\n"
  11. func CreateIfNotExist(file string) (*os.File, error) {
  12. _, err := os.Stat(file)
  13. if !os.IsNotExist(err) {
  14. return nil, fmt.Errorf("%s already exist", file)
  15. }
  16. return os.Create(file)
  17. }
  18. func RemoveIfExist(filename string) error {
  19. if !FileExists(filename) {
  20. return nil
  21. }
  22. return os.Remove(filename)
  23. }
  24. func RemoveOrQuit(filename string) error {
  25. if !FileExists(filename) {
  26. return nil
  27. }
  28. fmt.Printf("%s exists, overwrite it?\nEnter to overwrite or Ctrl-C to cancel...",
  29. aurora.BgRed(aurora.Bold(filename)))
  30. bufio.NewReader(os.Stdin).ReadBytes('\n')
  31. return os.Remove(filename)
  32. }
  33. func FileExists(file string) bool {
  34. _, err := os.Stat(file)
  35. return err == nil
  36. }
  37. func FileNameWithoutExt(file string) string {
  38. return strings.TrimSuffix(file, filepath.Ext(file))
  39. }