-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
104 lines (83 loc) · 2.48 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"fmt"
"os"
"path/filepath"
"gopkg.in/yaml.v2"
)
type Config struct {
TemplatesDir string `yaml:"templates_dir"`
NotesDir string `yaml:"notes_dir,omitempty"`
}
var AppConfig Config
func LoadConfig() error {
// Set default values
AppConfig = Config{
TemplatesDir: "templates",
}
configPath := getConfigPath()
if configPath == "" {
// Config file doesn't exist, create a default one
err := createDefaultConfig()
if err != nil {
return fmt.Errorf("failed to create default config: %w", err)
}
configPath = ".md_config.yaml"
}
// Read from config file
data, err := os.ReadFile(configPath)
if err != nil {
return fmt.Errorf("failed to read config file: %w", err)
}
err = yaml.Unmarshal(data, &AppConfig)
if err != nil {
return fmt.Errorf("failed to parse config file: %w", err)
}
// Override with environment variables
if envTemplatesDir := os.Getenv("MD_TEMPLATES_DIR"); envTemplatesDir != "" {
AppConfig.TemplatesDir = envTemplatesDir
}
if envNotesDir := os.Getenv("MD_NOTES_DIR"); envNotesDir != "" {
AppConfig.NotesDir = envNotesDir
}
return nil
}
func getConfigPath() string {
configFileName := ".md_config.yaml"
// Check for config file in the current directory
if _, err := os.Stat(configFileName); err == nil {
return configFileName
}
// Check for config file in the user's home directory
homeDir, err := os.UserHomeDir()
if err == nil {
configPath := filepath.Join(homeDir, configFileName)
if _, err := os.Stat(configPath); err == nil {
return configPath
}
}
return ""
}
func createDefaultConfig() error {
configContent := `# Markdown File Creator Configuration
# templates_dir: Directory where template files are stored
# Default is 'templates' in the current working directory
# Examples for custom paths:
# Windows: C:\Users\YourUsername\Documents\templates
# macOS: /Users/YourUsername/Documents/templates
# Linux: /home/YourUsername/Documents/templates
templates_dir: templates
# notes_dir: Optional directory where notes will be stored
# If not set, notes will be created in the current directory
# Example:
# notes_dir: /path/to/your/notes
# Note: You can use the environment variables MD_TEMPLATES_DIR and MD_NOTES_DIR
# to override these settings at runtime.
`
err := os.WriteFile(".md_config.yaml", []byte(configContent), 0644)
if err != nil {
return fmt.Errorf("failed to write default config file: %w", err)
}
fmt.Println("Created default configuration file: .md_config.yaml")
return nil
}