file.go 887 B

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