-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathall_code.txt
More file actions
4278 lines (3563 loc) · 104 KB
/
Copy pathall_code.txt
File metadata and controls
4278 lines (3563 loc) · 104 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
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/// --- ./cmd/info.go --- ///
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var infoCmd = &cobra.Command{
Use: "info [file_id]",
Short: "Show detailed information about a file or folder",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
fileID := args[0]
driver, err := getDriver()
if err != nil {
return err
}
defer driver.Close()
obj, err := driver.Info(cmd.Context(), fileID)
if err != nil {
return err
}
return outputTableOrJSON(obj, func() {
typeStr := "File"
if obj.IsDir {
typeStr = "Folder"
}
fmt.Printf("📂 Name: %s\n", obj.Name)
fmt.Printf("🆔 ID: %s\n", obj.ID)
fmt.Printf("📦 Type: %s\n", typeStr)
if !obj.IsDir {
fmt.Printf("💾 Size: %s\n", formatSize(obj.Size))
if obj.Hash != "" {
fmt.Printf("#️⃣ SHA1: %s\n", obj.Hash)
}
}
fmt.Printf("🕒 Modified: %s\n", obj.ModTime.Format("2006-01-02 15:04:05"))
})
},
}
func init() {
rootCmd.AddCommand(infoCmd)
}
/// --- ./cmd/ls.go --- ///
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var lsCmd = &cobra.Command{
Use: "ls [path]",
Short: "List directory",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
driver, err := getDriver()
if err != nil {
return err
}
path := "/"
if len(args) > 0 {
path = args[0]
}
objects, err := driver.List(cmd.Context(), path)
if err != nil {
return err
}
return outputTableOrJSON(objects, func() {
fmt.Printf("%-30s %-10s %s\n", "NAME", "SIZE", "TIME")
for _, obj := range objects {
size := "-"
if !obj.IsDir {
size = formatSize(obj.Size)
} else {
size = "DIR"
}
name := obj.Name
if obj.IsDir {
name += "/"
}
fmt.Printf("%-30s %-10s %s\n", name, size, obj.ModTime.Format("2006-01-02 15:04"))
}
})
},
}
func init() {
rootCmd.AddCommand(lsCmd)
}
/// --- ./cmd/share.go --- ///
package cmd
import (
"fmt"
"time"
"github.com/Ab-code520/cloud-cli/core"
"github.com/spf13/cobra"
)
var shareCmd = &cobra.Command{
Use: "share [subcommand]",
Short: "Manage file shares (create, list, delete)",
Long: `Manage file shares for cloud drive.
Examples:
cloud-cli share create file_id1 file_id2 # Create a share for files
cloud-cli share list # List all shares
cloud-cli share delete share_id1 share_id2 # Delete shares`,
}
var shareCreateCmd = &cobra.Command{
Use: "create [file_id...]",
Short: "Create a share for files/folders",
Long: `Create a share for one or more files or folders.
Examples:
cloud-cli share create abc123 # Permanent share
cloud-cli share create abc123 --days 7 # 7-day share`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
driver, err := getDriver()
if err != nil {
return err
}
defer driver.Close()
sh, ok := driver.(core.Sharable)
if !ok {
return fmt.Errorf("share is not supported by this driver")
}
days, _ := cmd.Flags().GetInt("days")
url, err := sh.CreateShare(cmd.Context(), args, days)
if err != nil {
return err
}
fmt.Printf("✅ Share created successfully!\n")
fmt.Printf("🔗 URL: %s\n", url)
return nil
},
}
var shareListCmd = &cobra.Command{
Use: "list",
Short: "List all shares",
RunE: func(cmd *cobra.Command, args []string) error {
driver, err := getDriver()
if err != nil {
return err
}
defer driver.Close()
sh, ok := driver.(core.Sharable)
if !ok {
return fmt.Errorf("share is not supported by this driver")
}
shares, err := sh.ListShares(cmd.Context(), 1, 50)
if err != nil {
return err
}
if len(shares) == 0 {
fmt.Println("No shares found.")
return nil
}
fmt.Printf("📦 Found %d shares:\n\n", len(shares))
for _, s := range shares {
status := "🟢 Active"
if s.IsExpired {
status = "🔴 Expired"
}
fmt.Printf("%s %s\n", status, s.Title)
fmt.Printf(" ID: %s\n", s.ShareID)
fmt.Printf(" 🔗 %s\n", s.URL)
fmt.Printf(" 📄 Files: %d | 📅 Created: %s\n\n", s.FileCount, time.Unix(s.CreatedAt, 0).Format("2006-01-02"))
}
return nil
},
}
var shareDeleteCmd = &cobra.Command{
Use: "delete [share_id...]",
Short: "Delete one or more shares",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
driver, err := getDriver()
if err != nil {
return err
}
defer driver.Close()
sh, ok := driver.(core.Sharable)
if !ok {
return fmt.Errorf("share is not supported by this driver")
}
err = sh.DeleteShare(cmd.Context(), args)
if err != nil {
return err
}
fmt.Printf("✅ Deleted %d share(s) successfully.\n", len(args))
return nil
},
}
func init() {
shareCreateCmd.Flags().IntP("days", "d", -1, "Expiration days (-1 for permanent)")
shareCmd.AddCommand(shareCreateCmd)
shareCmd.AddCommand(shareListCmd)
shareCmd.AddCommand(shareDeleteCmd)
rootCmd.AddCommand(shareCmd)
}
/// --- ./cmd/delete.go --- ///
package cmd
import (
"context"
"fmt"
"github.com/spf13/cobra"
)
var deleteCmd = &cobra.Command{
Use: "delete [id_or_path...]",
Short: "Delete file(s) or folder(s)",
Long: `Delete one or more files or folders.
Examples:
cloud-cli delete file_id # Delete single file
cloud-cli delete id1 id2 id3 # Batch delete
cloud-cli delete /path/to/file.txt # Delete by path`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
driver, err := getDriver()
if err != nil {
return err
}
defer driver.Close()
deleted := 0
failed := 0
for _, arg := range args {
obj, err := findObjectByPath(driver, arg)
if err != nil {
fmt.Printf("❌ Cannot find '%s': %v\n", arg, err)
failed++
continue
}
if err := driver.Delete(context.Background(), obj); err != nil {
fmt.Printf("❌ Failed to delete '%s': %v\n", obj.Name, err)
failed++
} else {
fmt.Printf("🗑️ Deleted: %s\n", obj.Name)
deleted++
}
}
fmt.Printf("\n📊 Summary: %d deleted, %d failed\n", deleted, failed)
return nil
},
}
func init() {
rootCmd.AddCommand(deleteCmd)
}
/// --- ./cmd/output.go --- ///
package cmd
import (
"encoding/json"
"fmt"
"os"
"strings"
)
// outputFormat controls the global output format (table, json).
var outputFormat string
// outputJSON encodes v as JSON to stdout.
func outputJSON(v interface{}) error {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
return enc.Encode(v)
}
// outputTableOrJSON calls tableFn if outputFormat is "table" (default),
// otherwise encodes v as JSON.
func outputTableOrJSON(v interface{}, tableFn func()) error {
switch strings.ToLower(outputFormat) {
case "json":
return outputJSON(v)
default:
tableFn()
return nil
}
}
func formatSize(b int64) string {
const unit = 1024
if b < unit {
return fmt.Sprintf("%d B", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %ciB", float64(b)/float64(div), "KMGTPE"[exp])
}
/// --- ./cmd/download.go --- ///
package cmd
import (
"fmt"
"io"
"os"
"path/filepath"
"github.com/spf13/cobra"
)
var downloadCmd = &cobra.Command{
Use: "download [remote_path] [local_path]",
Short: "Download file",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
driver, err := getDriver()
if err != nil {
return err
}
remotePath := args[0]
localPath := args[1]
// Fix #8: Support recursive path finding
obj, err := findObjectByPathOrID(driver, remotePath)
if err != nil {
return err
}
if obj.IsDir {
return fmt.Errorf("download does not support directories yet")
}
// Fix #7: Use cmd.Context() for cancellation
reader, err := driver.Open(cmd.Context(), obj, 0)
if err != nil {
return err
}
defer reader.Close()
if err := os.MkdirAll(filepath.Dir(localPath), 0755); err != nil {
return err
}
out, err := os.Create(localPath)
if err != nil {
return err
}
defer out.Close()
fmt.Printf("Downloading %s (%s)...\n", obj.Name, formatSize(obj.Size))
// Simple copy, progress bar could be added here via io.TeeReader
_, err = io.Copy(out, reader)
if err != nil {
return err
}
fmt.Printf("Downloaded to %s\n", localPath)
return nil
},
}
func init() {
rootCmd.AddCommand(downloadCmd)
}
/// --- ./cmd/rename.go --- ///
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var renameCmd = &cobra.Command{
Use: "rename [file_id] [new_name]",
Short: "Rename a file or folder",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
fileID := args[0]
newName := args[1]
driver, err := getDriver()
if err != nil {
return err
}
defer driver.Close()
obj, err := driver.Info(cmd.Context(), fileID)
if err != nil {
return fmt.Errorf("get file info: %w", err)
}
err = driver.Rename(cmd.Context(), obj, newName)
if err != nil {
return fmt.Errorf("rename failed: %w", err)
}
fmt.Printf("✅ Successfully renamed '%s' to '%s'\n", obj.Name, newName)
return nil
},
}
func init() {
rootCmd.AddCommand(renameCmd)
}
/// --- ./cmd/recycle.go --- ///
package cmd
import (
"fmt"
"time"
"github.com/Ab-code520/cloud-cli/core"
"github.com/spf13/cobra"
)
var recycleCmd = &cobra.Command{
Use: "recycle [subcommand]",
Short: "Manage recycle bin (list, restore, delete)",
Long: `Manage recycle bin items.
Examples:
cloud-cli recycle list # List deleted files
cloud-cli recycle restore fid1 fid2 # Restore files
cloud-cli recycle delete fid1 fid2 # Permanently delete`,
}
var recycleListCmd = &cobra.Command{
Use: "list",
Short: "List items in recycle bin",
RunE: func(cmd *cobra.Command, args []string) error {
driver, err := getDriver()
if err != nil {
return err
}
defer driver.Close()
rb, ok := driver.(core.RecycleBin)
if !ok {
return fmt.Errorf("recycle bin is not supported by this driver")
}
page, _ := cmd.Flags().GetInt("page")
size, _ := cmd.Flags().GetInt("size")
items, err := rb.ListRecycle(cmd.Context(), page, size)
if err != nil {
return err
}
if len(items) == 0 {
fmt.Println("♻️ Recycle bin is empty.")
return nil
}
fmt.Printf("♻️ Found %d items in recycle bin:\n\n", len(items))
for _, item := range items {
typeIcon := "📄"
if item.IsDir {
typeIcon = "📁"
}
sizeStr := ""
if !item.IsDir {
sizeStr = fmt.Sprintf(" (%s)", formatSize(item.Size))
}
fmt.Printf("%s %s%s\n", typeIcon, item.FileName, sizeStr)
fmt.Printf(" 🆔 %s | 🗑️ Deleted: %s\n\n", item.FID, time.Unix(item.DeletedAt, 0).Format("2006-01-02 15:04:05"))
}
return nil
},
}
var recycleRestoreCmd = &cobra.Command{
Use: "restore [file_id...]",
Short: "Restore items from recycle bin",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
driver, err := getDriver()
if err != nil {
return err
}
defer driver.Close()
rb, ok := driver.(core.RecycleBin)
if !ok {
return fmt.Errorf("recycle bin is not supported by this driver")
}
err = rb.RecoverRecycle(cmd.Context(), args)
if err != nil {
return err
}
fmt.Printf("✅ Successfully restored %d item(s).\n", len(args))
return nil
},
}
var recycleDeleteCmd = &cobra.Command{
Use: "delete [file_id...]",
Short: "Permanently delete items from recycle bin",
Long: "Permanently delete items from recycle bin. This action cannot be undone!",
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
driver, err := getDriver()
if err != nil {
return err
}
defer driver.Close()
rb, ok := driver.(core.RecycleBin)
if !ok {
return fmt.Errorf("recycle bin is not supported by this driver")
}
err = rb.DeleteRecycle(cmd.Context(), args)
if err != nil {
return err
}
fmt.Printf("✅ Permanently deleted %d item(s).\n", len(args))
return nil
},
}
func init() {
recycleListCmd.Flags().IntP("page", "p", 1, "Page number")
recycleListCmd.Flags().IntP("size", "s", 50, "Items per page")
recycleCmd.AddCommand(recycleListCmd)
recycleCmd.AddCommand(recycleRestoreCmd)
recycleCmd.AddCommand(recycleDeleteCmd)
rootCmd.AddCommand(recycleCmd)
}
/// --- ./cmd/helpers.go --- ///
package cmd
import (
"context"
"fmt"
"strings"
"github.com/Ab-code520/cloud-cli/core"
)
// findObjectByPath resolves a path like "/folder/subfolder/file.txt" to an Object.
// It recursively traverses the directory structure from root ("0").
func findObjectByPath(driver core.Storage, path string) (*core.Object, error) {
if path == "" || path == "/" || path == "0" {
return &core.Object{ID: "0", Name: "/", IsDir: true}, nil
}
// Remove leading slash
path = strings.TrimPrefix(path, "/")
parts := strings.Split(path, "/")
// Find the file/dir
return resolvePathParts(driver, context.Background(), "0", parts)
}
func resolvePathParts(driver core.Storage, ctx context.Context, currentID string, parts []string) (*core.Object, error) {
if len(parts) == 0 {
return driver.Info(ctx, currentID)
}
part := parts[0]
// Optimization: If currentID is "0" and part is just a name, we can try Info if supported?
// No, Info usually takes ID. We must List.
objs, err := driver.List(ctx, currentID)
if err != nil {
return nil, fmt.Errorf("list %s: %w", currentID, err)
}
for _, obj := range objs {
if obj.Name == part {
if len(parts) == 1 {
// Found it
return obj, nil
}
// It's a directory (intermediate part), recurse
if obj.IsDir {
return resolvePathParts(driver, ctx, obj.ID, parts[1:])
} else {
return nil, fmt.Errorf("%s is a file, not a directory", part)
}
}
}
return nil, fmt.Errorf("path '%s' not found", strings.Join(parts, "/"))
}
// findObjectByPathOrID tries to parse as ID first, then path.
func findObjectByPathOrID(driver core.Storage, path string) (*core.Object, error) {
// If it looks like an ID (alphanumeric, length ~32), try Info first
if isValidDirID(path) {
obj, err := driver.Info(context.Background(), path)
if err == nil {
return obj, nil
}
// Fallback to path resolution
}
return findObjectByPath(driver, path)
}
/// --- ./cmd/mkdir.go --- ///
package cmd
import (
"context"
"fmt"
"github.com/spf13/cobra"
)
var mkdirCmd = &cobra.Command{
Use: "mkdir [path]",
Short: "Create directory",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
driver, err := getDriver()
if err != nil {
return err
}
_, err = driver.Mkdir(context.Background(), args[0])
if err != nil {
return err
}
fmt.Printf("Created directory %s\n", args[0])
return nil
},
}
func init() {
rootCmd.AddCommand(mkdirCmd)
}
/// --- ./cmd/search.go --- ///
package cmd
import (
"fmt"
"github.com/Ab-code520/cloud-cli/core"
"github.com/spf13/cobra"
)
var searchCmd = &cobra.Command{
Use: "search [query]",
Short: "Search for files and folders in cloud drive",
Long: `Search for files and folders in your cloud drive.
Examples:
cloud-cli search "report.pdf" # Search by filename
cloud-cli search "photos" --dir abc # Search in specific directory
cloud-cli search "*.mp4" # Use wildcard pattern`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
query := args[0]
driver, err := getDriver()
if err != nil {
return err
}
defer driver.Close()
s, ok := driver.(core.Searchable)
if !ok {
return fmt.Errorf("search is not supported by this driver")
}
dirID, _ := cmd.Flags().GetString("dir")
page, _ := cmd.Flags().GetInt("page")
size, _ := cmd.Flags().GetInt("size")
results, err := s.Search(cmd.Context(), query, dirID, page, size)
if err != nil {
return err
}
if len(results) == 0 {
if outputFormat == "json" {
return outputTableOrJSON([]interface{}{}, func() {})
}
fmt.Printf("🔍 No results found for '%s'\n", query)
return nil
}
return outputTableOrJSON(results, func() {
fmt.Printf("🔍 Found %d results for '%s':\n\n", len(results), query)
for _, obj := range results {
typeIcon := "📄"
if obj.IsDir {
typeIcon = "📁"
}
sizeStr := ""
if !obj.IsDir {
sizeStr = fmt.Sprintf(" (%s)", formatSize(obj.Size))
}
fmt.Printf("%s %s%s\n", typeIcon, obj.Name, sizeStr)
fmt.Printf(" 🆔 %s | 📅 %s\n\n", obj.ID, obj.ModTime.Format("2006-01-02"))
}
})
},
}
func init() {
searchCmd.Flags().StringP("dir", "d", "", "Search in specific directory ID")
searchCmd.Flags().IntP("page", "p", 1, "Page number")
searchCmd.Flags().IntP("size", "s", 50, "Results per page")
rootCmd.AddCommand(searchCmd)
}
/// --- ./cmd/copy.go --- ///
package cmd
import (
"fmt"
"github.com/Ab-code520/cloud-cli/core"
"github.com/spf13/cobra"
)
var copyCmd = &cobra.Command{
Use: "copy [source_id] [dest_dir_id]",
Short: "Copy a file or folder to another directory",
Long: `Copy a file or folder to another directory.
Examples:
cloud-cli copy file123 folder456 # Copy file123 into folder456
cloud-cli copy file123 0 # Copy file123 to root directory`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
srcID := args[0]
destID := args[1]
driver, err := getDriver()
if err != nil {
return err
}
defer driver.Close()
// Get source object
srcObj, err := driver.Info(cmd.Context(), srcID)
if err != nil {
return fmt.Errorf("get source info: %w", err)
}
// Construct destination directory object
destDirObj := &core.Object{ID: destID}
// Call Copy
err = driver.Copy(cmd.Context(), srcObj, destDirObj)
if err != nil {
return fmt.Errorf("copy failed: %w", err)
}
fmt.Printf("✅ Successfully copied '%s' to directory '%s'\n", srcObj.Name, destID)
return nil
},
}
func init() {
rootCmd.AddCommand(copyCmd)
}
/// --- ./cmd/sync.go --- ///
package cmd
import (
"fmt"
"path/filepath"
"github.com/Ab-code520/cloud-cli/core"
"github.com/spf13/cobra"
)
var syncCmd = &cobra.Command{
Use: "sync <source> <destination>",
Short: "Synchronize directories (Local <-> Cloud)",
Long: `Synchronize files between local directory and cloud drive.
Supports one-way sync (up/down) and deletion of extra files.
Examples:
# Upload local folder to quark (only new/changed files)
cloud-cli sync ./photos quark:/backup/photos
# Preview sync (Dry Run)
cloud-cli sync ./data quark:/backup --dry-run
# Sync and delete extra files in destination
cloud-cli sync ./important quark:/important --delete`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
srcInput := args[0]
destInput := args[1]
// Parse paths
srcDriverName, srcPath, err := parseResourcePath(srcInput)
if err != nil {
return err
}
destDriverName, destPath, err := parseResourcePath(destInput)
if err != nil {
return err
}
// Initialize drivers
// For local driver, if path is absolute, we set root to "/" so we can traverse fully.
// If relative, we keep default (cwd) and pass relative path.
srcRoot := ""
if srcDriverName == "local" && filepath.IsAbs(srcPath) {
srcRoot = "/"
}
srcDriver, err := initDriver(srcDriverName, srcRoot)
if err != nil {
return fmt.Errorf("init source driver: %w", err)
}
defer srcDriver.Close()
destRoot := ""
if destDriverName == "local" && filepath.IsAbs(destPath) {
destRoot = "/"
}
destDriver, err := initDriver(destDriverName, destRoot)
if err != nil {
return fmt.Errorf("init dest driver: %w", err)
}
defer destDriver.Close()
// Config
dryRun, _ := cmd.Flags().GetBool("dry-run")
deleteExtra, _ := cmd.Flags().GetBool("delete")
syncer := &core.Syncer{
Source: srcDriver,
Dest: destDriver,
Config: core.SyncConfig{
DryRun: dryRun,
DeleteExtra: deleteExtra,
},
OnAction: func(action *core.SyncAction) {
icon := " "
switch action.Type {
case "upload":
icon = "⬆️"
case "update":
icon = "🔄"
case "delete":
icon = "🗑️"
case "mkdir":
icon = "📁"
case "skip":
icon = "⏭️"
}
msg := fmt.Sprintf("%s %s %s", icon, action.Type, action.Object.Name)
if dryRun {
msg += " [DRY RUN]"
}
fmt.Println(msg)
},
}
fmt.Printf("🔄 Syncing %s -> %s ...\n", srcInput, destInput)
if dryRun {
fmt.Println("👀 This is a dry run, no files will be modified.")
}
if err := syncer.Sync(cmd.Context(), srcPath, destPath); err != nil {
return fmt.Errorf("sync failed: %w", err)
}
fmt.Println("✅ Sync completed.")
return nil
},
}
func init() {
syncCmd.Flags().Bool("dry-run", false, "Preview changes without executing")
syncCmd.Flags().Bool("delete", false, "Delete extra files in destination")
rootCmd.AddCommand(syncCmd)
}
/// --- ./cmd/user.go --- ///
package cmd
import (
"fmt"
"github.com/spf13/cobra"
)
var userCmd = &cobra.Command{
Use: "user",
Short: "Show user info",
RunE: func(cmd *cobra.Command, args []string) error {
driver, err := getDriver()
if err != nil {
return err
}
info, err := driver.User(cmd.Context())
if err != nil {
return err
}
return outputTableOrJSON(info, func() {
if name, ok := info["name"]; ok {
fmt.Printf("👤 Name: %v\n", name)
}
if used, ok := info["space_used"]; ok {
fmt.Printf("💾 Used: %s\n", formatSize(int64(used.(float64))))
}
if total, ok := info["space_total"]; ok {
fmt.Printf("📊 Total: %s\n", formatSize(int64(total.(float64))))
}
})
},
}
func init() {
rootCmd.AddCommand(userCmd)
}