-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.go
More file actions
307 lines (270 loc) · 7.6 KB
/
Copy pathcli.go
File metadata and controls
307 lines (270 loc) · 7.6 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
package cli
import (
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
)
// ScanStr scans the given input
func ScanStr(input *string, label string) {
fmt.Print(fmt.Sprintf("Enter the %s name: ", label))
_, err := fmt.Scanln(input)
if err != nil {
log.Fatal(fmt.Sprintf("Error reading %s name:", label), err)
}
}
// CopyFile is a helper function to copy a file
func CopyFile(src, dst string) error {
sourceFile, err := os.Open(src)
if err != nil {
return err
}
defer sourceFile.Close()
destinationFile, err := os.Create(dst)
if err != nil {
return err
}
defer destinationFile.Close()
_, err = io.Copy(destinationFile, sourceFile)
if err != nil {
return err
}
//err = os.Chmod(dst, 0644) // Set the file permissions
//if err != nil {
// return err
//}
//
// Copy file info (like modification times)
info, err := os.Stat(src)
if err != nil {
return err
}
return os.Chtimes(dst, info.ModTime(), info.ModTime())
}
// CopyDir copies the src dir to dst
func CopyDir(src string, dst string) error {
entries, err := ioutil.ReadDir(src)
if err != nil {
return err
}
if err := os.MkdirAll(dst, 0755); err != nil {
return err
}
for _, entry := range entries {
sourcePath := filepath.Join(src, entry.Name())
destPath := filepath.Join(dst, entry.Name())
if entry.IsDir() {
err = CopyDir(sourcePath, destPath)
if err != nil {
return err
}
} else {
// Check if the destination file exists
if _, err := os.Stat(destPath); err == nil {
// If the file exists, remove it before copying
if err := os.Remove(destPath); err != nil {
return fmt.Errorf("failed to remove existing destination file: %v", err)
}
}
err = CopyFile(sourcePath, destPath)
if err != nil {
return err
}
}
}
return nil
}
// RemoveDirs removes the list of given directories
func RemoveDirs(dirPath string, dirNames []string) {
fmt.Println("> Cleaning up...")
for _, dirName := range dirNames {
if err := os.RemoveAll(filepath.Join(dirPath, dirName)); err != nil {
fmt.Println("Warning: Unable to remove .git directory:", err)
}
}
}
// EnsureBinary ensures the git binary is present in the system
func EnsureBinary(binary string) {
// Check if the given binary is installed
if _, err := exec.LookPath(binary); err != nil {
log.Fatal(fmt.Sprintf("Error: %s must be installed to use this command.", binary))
}
}
// HasBinary returns if the given binary is installed in the system
func HasBinary(binary string) bool {
if _, err := exec.LookPath(binary); err != nil {
return false
}
return true
}
// DirPath returns the full directory path for a directory name
func DirPath(dirname string) string {
currentDir, _ := os.Getwd()
return filepath.Join(currentDir, dirname)
}
// EnsureEmptyDir ensures the directory in which the project should be created is empty
func EnsureEmptyDir(dirname string) {
dirPath := DirPath(dirname)
// Check if directory exists
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
// If directory doesn't exist, create it
fmt.Printf("> Creating new directory: %s\n", dirname)
if err := os.MkdirAll(dirPath, 0755); err != nil {
log.Fatal("Error creating directory:", err)
}
} else {
// Directory exists, check if it's empty
files, _ := filepath.Glob(filepath.Join(dirPath, "*"))
if len(files) > 0 {
log.Fatal("Error: The directory must be empty to create a new project.")
}
}
}
// HasDirectory returns true if a directory exists and false otherwise
func HasDirectory(dirPath string) bool {
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
return false
}
return true
}
// CreateDirIfNotExists creates a directory if it does not exist
func CreateDirIfNotExists(dirPath string) {
if _, err := os.Stat(dirPath); os.IsNotExist(err) {
err := os.MkdirAll(dirPath, 0755)
if err != nil {
log.Fatal("Error creating directory:", err)
}
}
}
// RunCommand runs a command in a specific directory
func RunCommand(dirPath string, command string, args ...string) {
cmd := exec.Command(command, args...)
cmd.Dir = dirPath
output, err := cmd.CombinedOutput()
if len(output) > 0 {
fmt.Printf("%s\n", output)
}
if err != nil {
log.Fatalf("command %s %v failed: %v\n%s", command, args, err, output)
}
}
const scaffoldCacheDir = ".cache/lemmego/scaffold"
const scaffoldRepoOwner = "lemmego"
const scaffoldRepoName = "cli"
const scaffoldRepoBranch = "main"
// scaffoldCache returns the path to the local scaffold cache directory.
func scaffoldCache() string {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, scaffoldCacheDir)
}
// scaffoldCacheVersion returns the cached scaffold version string, or "".
func scaffoldCacheVersion() string {
cacheDir := scaffoldCache()
if cacheDir == "" {
return ""
}
data, err := os.ReadFile(filepath.Join(cacheDir, "VERSION"))
if err != nil {
return ""
}
return strings.TrimSpace(string(data))
}
// fetchLatestScaffold attempts to download the latest scaffold from GitHub main
// into the local cache. Returns true if a newer version was fetched, false if
// the cache is already current or if the fetch fails (non-fatal).
func fetchLatestScaffold() bool {
cacheDir := scaffoldCache()
if cacheDir == "" {
return false
}
// Fetch remote VERSION
versionURL := fmt.Sprintf("https://raw.githubusercontent.com/%s/%s/%s/_scaffold/VERSION",
scaffoldRepoOwner, scaffoldRepoName, scaffoldRepoBranch)
resp, err := http.Get(versionURL)
if err != nil {
return false
}
defer resp.Body.Close()
remoteVersionBytes, err := io.ReadAll(resp.Body)
if err != nil {
return false
}
remoteVersion := strings.TrimSpace(string(remoteVersionBytes))
if remoteVersion == "" {
return false
}
// Compare with cached version
if scaffoldCacheVersion() == remoteVersion && dirExists(filepath.Join(cacheDir, "_scaffold")) {
return false
}
// Download tarball from GitHub
tarballURL := fmt.Sprintf("https://api.github.com/repos/%s/%s/tarball/%s",
scaffoldRepoOwner, scaffoldRepoName, scaffoldRepoBranch)
req, err := http.NewRequest("GET", tarballURL, nil)
if err != nil {
return false
}
req.Header.Set("Accept", "application/vnd.github.v3.raw")
resp2, err := http.DefaultClient.Do(req)
if err != nil {
return false
}
defer resp2.Body.Close()
// Extract to temp dir, then move _scaffold/ to cache
tmpDir, err := os.MkdirTemp("", "lemmego-scaffold-*")
if err != nil {
return false
}
defer os.RemoveAll(tmpDir)
// Download and extract using system tar
tarPath, err := os.CreateTemp("", "scaffold-*.tar.gz")
if err != nil {
return false
}
defer os.Remove(tarPath.Name())
if _, err := io.Copy(tarPath, resp2.Body); err != nil {
return false
}
tarPath.Close()
// Extract
cmd := exec.Command("tar", "-xzf", tarPath.Name(), "-C", tmpDir, "--strip-components=1")
if err := cmd.Run(); err != nil {
return false
}
// Move _scaffold/ into cache
os.RemoveAll(filepath.Join(cacheDir, "_scaffold"))
if err := os.MkdirAll(cacheDir, 0755); err != nil {
return false
}
if err := CopyDir(filepath.Join(tmpDir, "_scaffold"), filepath.Join(cacheDir, "_scaffold")); err != nil {
return false
}
// Write VERSION
os.WriteFile(filepath.Join(cacheDir, "VERSION"), []byte(remoteVersion), 0644)
return true
}
func dirExists(path string) bool {
info, err := os.Stat(path)
return err == nil && info.IsDir()
}
// scaffoldDir returns the path to the scaffold to use (cached or embedded).
// Returns the embedded "_scaffold" marker if no cache is available.
func scaffoldDir() string {
cacheDir := scaffoldCache()
if cacheDir == "" {
return ""
}
candidate := filepath.Join(cacheDir, "_scaffold")
if dirExists(candidate) {
return candidate
}
return ""
}