files.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package util
  2. import (
  3. "io/ioutil"
  4. "os"
  5. "path/filepath"
  6. )
  7. const goctlDir = ".goctl"
  8. func GetGoctlHome() (string, error) {
  9. home, err := os.UserHomeDir()
  10. if err != nil {
  11. return "", err
  12. }
  13. return filepath.Join(home, goctlDir), nil
  14. }
  15. func GetTemplateDir(category string) (string, error) {
  16. goctlHome, err := GetGoctlHome()
  17. if err != nil {
  18. return "", err
  19. }
  20. return filepath.Join(goctlHome, category), nil
  21. }
  22. func InitTemplates(category string, templates map[string]string) error {
  23. dir, err := GetTemplateDir(category)
  24. if err != nil {
  25. return err
  26. }
  27. if err := MkdirIfNotExist(dir); err != nil {
  28. return err
  29. }
  30. for k, v := range templates {
  31. if err := createTemplate(filepath.Join(dir, k), v, false); err != nil {
  32. return err
  33. }
  34. }
  35. return nil
  36. }
  37. func CreateTemplate(category, name, content string) error {
  38. dir, err := GetTemplateDir(category)
  39. if err != nil {
  40. return err
  41. }
  42. return createTemplate(filepath.Join(dir, name), content, true)
  43. }
  44. func Clean(category string) error {
  45. dir, err := GetTemplateDir(category)
  46. if err != nil {
  47. return err
  48. }
  49. return os.RemoveAll(dir)
  50. }
  51. func LoadTemplate(category, file, builtin string) (string, error) {
  52. dir, err := GetTemplateDir(category)
  53. if err != nil {
  54. return "", err
  55. }
  56. file = filepath.Join(dir, file)
  57. if !FileExists(file) {
  58. return builtin, nil
  59. }
  60. content, err := ioutil.ReadFile(file)
  61. if err != nil {
  62. return "", err
  63. }
  64. return string(content), nil
  65. }
  66. func createTemplate(file, content string, force bool) error {
  67. if FileExists(file) && !force {
  68. return nil
  69. }
  70. f, err := os.Create(file)
  71. if err != nil {
  72. return err
  73. }
  74. defer f.Close()
  75. _, err = f.WriteString(content)
  76. return err
  77. }