-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathactions.go
More file actions
447 lines (372 loc) · 9.59 KB
/
actions.go
File metadata and controls
447 lines (372 loc) · 9.59 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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
package main
import (
"archive/zip"
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
type ActionService struct {
ctx *App
storage *Storage
}
func NewActionService(app *App, storage *Storage) *ActionService {
return &ActionService{
ctx: app,
storage: storage,
}
}
// File Operations
func (as *ActionService) ReadFile(path string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("failed to read file: %w", err)
}
return string(data), nil
}
func (as *ActionService) WriteFile(path, content string) error {
dir := filepath.Dir(path)
if err := os.MkdirAll(dir, 0755); err != nil {
return fmt.Errorf("failed to create directory: %w", err)
}
if err := os.WriteFile(path, []byte(content), 0644); err != nil {
return fmt.Errorf("failed to write file: %w", err)
}
return nil
}
func (as *ActionService) AppendFile(path, content string) error {
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("failed to open file: %w", err)
}
defer f.Close()
if _, err := f.WriteString(content); err != nil {
return fmt.Errorf("failed to append to file: %w", err)
}
return nil
}
func (as *ActionService) CopyFile(source, destination string) error {
sourceData, err := os.ReadFile(source)
if err != nil {
return fmt.Errorf("failed to read source: %w", err)
}
destDir := filepath.Dir(destination)
if err := os.MkdirAll(destDir, 0755); err != nil {
return fmt.Errorf("failed to create destination directory: %w", err)
}
if err := os.WriteFile(destination, sourceData, 0644); err != nil {
return fmt.Errorf("failed to write destination: %w", err)
}
return nil
}
func (as *ActionService) MoveFile(source, destination string) error {
if err := as.CopyFile(source, destination); err != nil {
return err
}
return os.Remove(source)
}
func (as *ActionService) DeleteFile(path string) error {
if err := os.Remove(path); err != nil {
return fmt.Errorf("failed to delete file: %w", err)
}
return nil
}
func (as *ActionService) FileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}
func (as *ActionService) FileInfo(path string) (map[string]interface{}, error) {
info, err := os.Stat(path)
if err != nil {
return nil, err
}
return map[string]interface{}{
"name": info.Name(),
"size": info.Size(),
"mode": info.Mode().String(),
"mod": info.ModTime().Format(time.RFC3339),
"isDir": info.IsDir(),
}, nil
}
func (as *ActionService) ListDirectory(path string, pattern string, recursive bool) ([]map[string]interface{}, error) {
var result []map[string]interface{}
if pattern == "" {
pattern = "*"
}
walker := func(p string, info os.FileInfo, err error) error {
if err != nil {
return nil // Skip errors
}
if p == path {
return nil // Skip root dir
}
// Match pattern
match, _ := filepath.Match(pattern, info.Name())
if !match && pattern != "*" {
return nil
}
result = append(result, map[string]interface{}{
"name": info.Name(),
"path": p,
"isDir": info.IsDir(),
"size": info.Size(),
"mod": info.ModTime().Format(time.RFC3339),
})
if !recursive && info.IsDir() && p != path {
return filepath.SkipDir
}
return nil
}
if recursive {
err := filepath.Walk(path, walker)
return result, err
} else {
entries, err := os.ReadDir(path)
if err != nil {
return nil, err
}
for _, entry := range entries {
info, err := entry.Info()
if err != nil {
continue
}
// Match pattern
match, _ := filepath.Match(pattern, info.Name())
if !match && pattern != "*" {
continue
}
result = append(result, map[string]interface{}{
"name": info.Name(),
"path": filepath.Join(path, info.Name()),
"isDir": info.IsDir(),
"size": info.Size(),
"mod": info.ModTime().Format(time.RFC3339),
})
}
return result, nil
}
}
func (as *ActionService) Compress(sourcePaths []string, zipPath string) error {
zipFile, err := os.Create(zipPath)
if err != nil {
return err
}
defer zipFile.Close()
archive := zip.NewWriter(zipFile)
defer archive.Close()
for _, src := range sourcePaths {
filepath.Walk(src, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
header, err := zip.FileInfoHeader(info)
if err != nil {
return err
}
header.Name, _ = filepath.Rel(filepath.Dir(src), path)
if info.IsDir() {
header.Name += "/"
} else {
header.Method = zip.Deflate
}
writer, err := archive.CreateHeader(header)
if err != nil {
return err
}
if info.IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(writer, file)
return err
})
}
return nil
}
func (as *ActionService) Extract(src, dest string) error {
r, err := zip.OpenReader(src)
if err != nil {
return err
}
defer r.Close()
os.MkdirAll(dest, 0755)
for _, f := range r.File {
// Prevent Zip Slip: ensure resolved path stays within dest
path := filepath.Join(dest, f.Name)
if !strings.HasPrefix(filepath.Clean(path), filepath.Clean(dest)+string(os.PathSeparator)) {
return fmt.Errorf("illegal file path in archive: %s", f.Name)
}
if f.FileInfo().IsDir() {
os.MkdirAll(path, f.Mode())
continue
}
os.MkdirAll(filepath.Dir(path), 0755)
fOr, err := f.Open()
if err != nil {
return err
}
defer fOr.Close()
fDest, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, f.Mode())
if err != nil {
return err
}
defer fDest.Close()
_, err = io.Copy(fDest, fOr)
if err != nil {
return err
}
}
return nil
}
// HTTP Operations
func (as *ActionService) HTTPRequest(method, url string, headers map[string]string, body string) (map[string]interface{}, error) {
var reqBody io.Reader
if body != "" && method != "GET" {
reqBody = bytes.NewBufferString(body)
}
req, err := http.NewRequest(method, url, reqBody)
if err != nil {
return nil, fmt.Errorf("failed to create request: %w", err)
}
for key, value := range headers {
req.Header.Set(key, value)
}
client := &http.Client{Timeout: 30 * time.Second}
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}
result := map[string]interface{}{
"status": resp.StatusCode,
"statusText": resp.Status,
"headers": resp.Header,
"body": string(respBody),
}
// Try to parse as JSON
var jsonBody interface{}
if err := json.Unmarshal(respBody, &jsonBody); err == nil {
result["json"] = jsonBody
}
return result, nil
}
// Shell Operations
func (as *ActionService) RunCommand(command string, args []string, workDir string) (map[string]interface{}, error) {
cmd := exec.Command(command, args...)
if workDir != "" {
cmd.Dir = workDir
}
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
exitCode := 0
if err != nil {
if exitErr, ok := err.(*exec.ExitError); ok {
exitCode = exitErr.ExitCode()
} else {
return nil, fmt.Errorf("failed to run command: %w", err)
}
}
return map[string]interface{}{
"stdout": stdout.String(),
"stderr": stderr.String(),
"exitCode": exitCode,
"success": exitCode == 0,
}, nil
}
// System Operations
// Platform-specific implementations are in actions_windows.go, actions_darwin.go, actions_linux.go
// Date/Time Operations
func (as *ActionService) GetCurrentTime(format string) string {
now := time.Now()
if format == "" {
return now.Format(time.RFC3339)
}
// Simple format mapping
format = replaceFormat(format)
return now.Format(format)
}
func replaceFormat(format string) string {
// Convert common format strings to Go format
replacements := map[string]string{
"YYYY": "2006",
"MM": "01",
"DD": "02",
"HH": "15",
"mm": "04",
"ss": "05",
}
for old, new := range replacements {
format = replaceAll(format, old, new)
}
return format
}
func replaceAll(s, old, new string) string {
result := ""
for i := 0; i < len(s); {
if i+len(old) <= len(s) && s[i:i+len(old)] == old {
result += new
i += len(old)
} else {
result += string(s[i])
i++
}
}
return result
}
// Utility Operations
func (as *ActionService) GenerateUUID() string {
return fmt.Sprintf("%d-%d", time.Now().UnixNano(), time.Now().Unix())
}
func (as *ActionService) Sleep(milliseconds int) {
time.Sleep(time.Duration(milliseconds) * time.Millisecond)
}
// Secrets & Settings
func (as *ActionService) GetSecret(key string) (string, error) {
return as.storage.GetSecret(key)
}
func (as *ActionService) SaveSecret(key, value string) error {
return as.storage.SaveSecret(key, value)
}
func (as *ActionService) GetSetting(key string) (string, error) {
// For app settings, we might want to parse the settings.json
settingsJSON, err := as.storage.LoadSettings()
if err != nil {
return "", err
}
var settings map[string]interface{}
if err := json.Unmarshal([]byte(settingsJSON), &settings); err != nil {
return "", err
}
val, ok := settings[key]
if !ok {
return "", fmt.Errorf("setting %s not found", key)
}
return fmt.Sprintf("%v", val), nil
}
func (as *ActionService) SaveSetting(key, value string) error {
settingsJSON, _ := as.storage.LoadSettings()
var settings map[string]interface{}
json.Unmarshal([]byte(settingsJSON), &settings)
if settings == nil {
settings = make(map[string]interface{})
}
settings[key] = value
newData, _ := json.MarshalIndent(settings, "", " ")
return as.storage.SaveSettings(string(newData))
}