file.go 909 B

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