profile.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. package profile
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "runtime"
  7. "strings"
  8. "github.com/spf13/viper"
  9. "github.com/usememos/memos/server/version"
  10. )
  11. // Profile is the configuration to start main server.
  12. type Profile struct {
  13. // Mode can be "prod" or "dev" or "demo"
  14. Mode string `json:"mode"`
  15. // Port is the binding port for server
  16. Port int `json:"-"`
  17. // Data is the data directory
  18. Data string `json:"-"`
  19. // DSN points to where Memos stores its own data
  20. DSN string `json:"-"`
  21. // Version is the current version of server
  22. Version string `json:"version"`
  23. }
  24. func (p *Profile) IsDev() bool {
  25. return p.Mode != "prod"
  26. }
  27. func checkDSN(dataDir string) (string, error) {
  28. // Convert to absolute path if relative path is supplied.
  29. if !filepath.IsAbs(dataDir) {
  30. relativeDir := filepath.Join(filepath.Dir(os.Args[0]), dataDir)
  31. absDir, err := filepath.Abs(relativeDir)
  32. if err != nil {
  33. return "", err
  34. }
  35. dataDir = absDir
  36. }
  37. // Trim trailing \ or / in case user supplies
  38. dataDir = strings.TrimRight(dataDir, "\\/")
  39. if _, err := os.Stat(dataDir); err != nil {
  40. return "", fmt.Errorf("unable to access data folder %s, err %w", dataDir, err)
  41. }
  42. return dataDir, nil
  43. }
  44. // GetProfile will return a profile for dev or prod.
  45. func GetProfile() (*Profile, error) {
  46. profile := Profile{}
  47. err := viper.Unmarshal(&profile)
  48. if err != nil {
  49. return nil, err
  50. }
  51. if profile.Mode != "demo" && profile.Mode != "dev" && profile.Mode != "prod" {
  52. profile.Mode = "demo"
  53. }
  54. if profile.Mode == "prod" && profile.Data == "" {
  55. if runtime.GOOS == "windows" {
  56. profile.Data = filepath.Join(os.Getenv("ProgramData"), "memos")
  57. if _, err := os.Stat(profile.Data); os.IsNotExist(err) {
  58. if err := os.MkdirAll(profile.Data, 0770); err != nil {
  59. fmt.Printf("Failed to create data directory: %s, err: %+v\n", profile.Data, err)
  60. return nil, err
  61. }
  62. }
  63. } else {
  64. profile.Data = "/var/opt/memos"
  65. }
  66. }
  67. dataDir, err := checkDSN(profile.Data)
  68. if err != nil {
  69. fmt.Printf("Failed to check dsn: %s, err: %+v\n", dataDir, err)
  70. return nil, err
  71. }
  72. profile.Data = dataDir
  73. dbFile := fmt.Sprintf("memos_%s.db", profile.Mode)
  74. profile.DSN = filepath.Join(dataDir, dbFile)
  75. profile.Version = version.GetCurrentVersion(profile.Mode)
  76. return &profile, nil
  77. }