-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutility.go
More file actions
345 lines (308 loc) · 9.14 KB
/
Copy pathutility.go
File metadata and controls
345 lines (308 loc) · 9.14 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
package main
import (
"archive/zip"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"
"github.com/cavaliergopher/grab/v3"
"github.com/joho/godotenv"
)
const ConfigFile = ".env"
var Reset = "\033[0m"
var Red = "\033[31m"
var Green = "\033[32m"
var Yellow = "\033[33m"
var Blue = "\033[34m"
var Magenta = "\033[35m"
var Cyan = "\033[36m"
var Gray = "\033[37m"
var White = "\033[97m"
// Function to print colored output
func print_status(message string) {
fmt.Println(Blue + "[INFO]" + Reset + " " + message)
}
func print_success(message string) {
fmt.Println(Green + "[SUCCESS]" + Reset + " " + message)
}
func print_warning(message string) {
fmt.Println(Yellow + "[WARNING]" + Reset + " " + message)
}
func print_error(message string) {
fmt.Println(Red + "[ERROR]" + Reset + " " + message)
}
func print_step(message string) {
fmt.Println(Magenta + "[STEP]" + Reset + " " + message)
}
// print_check prints a green check confirmation (same visual as promptui Select).
func print_check(message string) {
fmt.Println(Green + "✔" + Reset + " " + message)
}
func ArrayContains(arr []string, str string) bool {
for _, k := range arr {
if k == str {
return true
}
}
return false
}
func getLatestReleaseTag() (string, error) {
resp, err := http.Get("https://api.github.com/repos/apito-io/engine/releases/latest")
if err != nil {
return "", fmt.Errorf("error fetching latest release: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to fetch latest release: status code %d", resp.StatusCode)
}
var result struct {
TagName string `json:"tag_name"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", fmt.Errorf("error decoding response: %w", err)
}
return result.TagName, nil
}
func downloadAndExtractEngine(projectName, releaseTag string, destDir string) error {
// This function is kept for backward compatibility with update command
// In the new architecture, projects are created via API calls
print_warning("Engine download is deprecated. Projects are now created via API.")
return nil
}
// getConfig reads configuration from a project directory (deprecated, use ReadEnv instead)
func getConfig(projectDir string) (map[string]string, error) {
// For backward compatibility, if the path contains "bin", use ReadEnv
if strings.Contains(projectDir, "bin") {
return ReadEnv()
}
// Otherwise, use the old method for project-specific configs
configFile := filepath.Join(projectDir, ConfigFile)
envMap, err := godotenv.Read(configFile)
if err != nil {
return nil, fmt.Errorf("error reading config file: %w", err)
}
return envMap, nil
}
// saveConfig saves configuration to a project directory (deprecated, use WriteEnv instead)
func saveEnvConfig(projectDir string, config map[string]string) error {
// For backward compatibility, if the path contains "bin", use WriteEnv
if strings.Contains(projectDir, "bin") {
return WriteEnv(config)
}
// Otherwise, use the old method for project-specific configs
configFile := filepath.Join(projectDir, ConfigFile)
// Ensure the directory exists
if err := os.MkdirAll(projectDir, 0755); err != nil {
return fmt.Errorf("error creating directory: %w", err)
}
// Read existing config to preserve other variables
existingConfig, err := godotenv.Read(configFile)
if err != nil {
// If file doesn't exist, start with empty config
existingConfig = make(map[string]string)
}
// Merge new config with existing config
for k, v := range config {
existingConfig[k] = v
}
// Write the merged config to the file
if err := godotenv.Write(existingConfig, configFile); err != nil {
return fmt.Errorf("error writing config file: %w", err)
}
return nil
}
// updateConfig updates a single configuration value in a project directory
func updateEnvConfig(projectDir, key, value string) error {
envMap, err := getConfig(projectDir)
if err != nil {
return fmt.Errorf("error reading config file: %w", err)
}
envMap[key] = value
// write back to config file
if err := saveEnvConfig(projectDir, envMap); err != nil {
return fmt.Errorf("error saving config file: %w", err)
}
return nil
}
// ensureBaseDirs creates core directories under ~/.apito used by both modes
func ensureBaseDirs() error {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("error finding home directory: %w", err)
}
apitoDir := filepath.Join(homeDir, ".apito")
binDir := filepath.Join(apitoDir, "bin")
dbDir := filepath.Join(apitoDir, "db")
logsDir := filepath.Join(apitoDir, "logs")
runDir := filepath.Join(apitoDir, "run")
for _, d := range []string{apitoDir, binDir, dbDir, logsDir, runDir} {
if err := os.MkdirAll(d, 0755); err != nil {
return fmt.Errorf("error creating directory %s: %w", d, err)
}
}
return nil
}
// downloadFileWithProgress downloads a URL into destDir with progress output and returns the downloaded file path.
func downloadFileWithProgress(url, destDir string) (string, error) {
resp, err := grab.Get(destDir, url)
if err != nil {
return "", fmt.Errorf("error downloading: %w", err)
}
ticker := time.NewTicker(500 * time.Millisecond)
defer ticker.Stop()
Loop:
for {
select {
case <-ticker.C:
fmt.Printf(" transferred %v / %v bytes (%.2f%%)\n", resp.BytesComplete(), resp.Size(), 100*resp.Progress())
case <-resp.Done:
break Loop
}
}
if err := resp.Err(); err != nil {
return "", fmt.Errorf("download failed: %w", err)
}
return resp.Filename, nil
}
// extractArchiveToTemp extracts an archive file into a unique temp directory and returns the directory path.
func extractArchiveToTemp(archivePath string) (string, error) {
tmpDir, err := os.MkdirTemp("", "apito-extract-*")
if err != nil {
return "", fmt.Errorf("error creating temp dir: %w", err)
}
// Detect extension
if strings.HasSuffix(strings.ToLower(archivePath), ".zip") {
zr, err := zip.OpenReader(archivePath)
if err != nil {
os.RemoveAll(tmpDir)
return "", fmt.Errorf("open zip: %w", err)
}
defer zr.Close()
for _, f := range zr.File {
fp := filepath.Join(tmpDir, f.Name)
if f.FileInfo().IsDir() {
if err := os.MkdirAll(fp, 0755); err != nil {
os.RemoveAll(tmpDir)
return "", err
}
continue
}
if err := os.MkdirAll(filepath.Dir(fp), 0755); err != nil {
os.RemoveAll(tmpDir)
return "", err
}
rc, err := f.Open()
if err != nil {
os.RemoveAll(tmpDir)
return "", err
}
out, err := os.Create(fp)
if err != nil {
rc.Close()
os.RemoveAll(tmpDir)
return "", err
}
if _, err := io.Copy(out, rc); err != nil {
out.Close()
rc.Close()
os.RemoveAll(tmpDir)
return "", err
}
out.Close()
rc.Close()
}
} else if strings.HasSuffix(strings.ToLower(archivePath), ".tar.gz") || strings.HasSuffix(strings.ToLower(archivePath), ".tgz") {
f, err := os.Open(archivePath)
if err != nil {
os.RemoveAll(tmpDir)
return "", err
}
defer f.Close()
gz, err := gzip.NewReader(f)
if err != nil {
os.RemoveAll(tmpDir)
return "", err
}
defer gz.Close()
// Use tar utility if available to keep implementation small
// Write to tmp file then use system tar
tmpTar := filepath.Join(tmpDir, "archive.tar")
tf, err := os.Create(tmpTar)
if err != nil {
os.RemoveAll(tmpDir)
return "", err
}
if _, err := io.Copy(tf, gz); err != nil {
tf.Close()
os.RemoveAll(tmpDir)
return "", err
}
tf.Close()
// Extract with tar -xf
if err := execCommand("tar", "-xf", tmpTar, "-C", tmpDir); err != nil {
os.RemoveAll(tmpDir)
return "", err
}
_ = os.Remove(tmpTar)
} else {
os.RemoveAll(tmpDir)
return "", fmt.Errorf("unsupported archive format: %s", archivePath)
}
return tmpDir, nil
}
func execCommand(name string, args ...string) error {
cmd := exec.Command(name, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
// findBinaryInDir recursively finds a binary by name within root and returns full path.
func findBinaryInDir(root, name string) (string, error) {
binName := name
if runtime.GOOS == "windows" && !strings.HasSuffix(strings.ToLower(name), ".exe") {
binName = name + ".exe"
}
var found string
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !info.IsDir() && info.Name() == binName {
found = path
}
return nil
})
if err != nil {
return "", err
}
if found == "" {
return "", fmt.Errorf("%s not found in %s", binName, root)
}
return found, nil
}
// moveAndChmod moves a file to destDir/name and makes it executable. Returns the final path.
func moveAndChmod(srcPath, destDir, name string) (string, error) {
if err := os.MkdirAll(destDir, 0755); err != nil {
return "", fmt.Errorf("error creating dir: %w", err)
}
destPath := filepath.Join(destDir, name)
if runtime.GOOS == "windows" && !strings.HasSuffix(strings.ToLower(destPath), ".exe") {
destPath += ".exe"
}
if err := os.Rename(srcPath, destPath); err != nil {
return "", fmt.Errorf("error moving file: %w", err)
}
if runtime.GOOS != "windows" {
if err := os.Chmod(destPath, 0755); err != nil {
return "", fmt.Errorf("error chmod: %w", err)
}
}
return destPath, nil
}