Repository navigation
Expand file tree
/
Copy pathrbcp.go
More file actions
421 lines (374 loc) · 11.7 KB
/
Copy pathrbcp.go
File metadata and controls
421 lines (374 loc) · 11.7 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
package main
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"runtime/pprof"
"slices"
"strconv"
"strings"
"time"
"github.com/alexflint/go-arg"
"github.com/charmbracelet/bubbles/progress"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
"github.com/charmbracelet/log"
"mvdan.cc/sh/v3/expand"
"mvdan.cc/sh/v3/syntax"
)
// # Version information
const (
ProgramName = "rbcp"
Author = "plutonium-239"
)
// : this will be injected by goreleaser at buildtime through ldflags
var (
Version = ""
Commit = ""
BuildDate = ""
)
var (
p *tea.Program
config Config
logger *log.Logger
args Args
root string
dest string
files []string
)
type Args struct {
Paths []string `arg:"positional, required" placeholder:"SRC DEST"`
Mir bool `arg:"-m" help:"Convenience argument to specify /MIR to robocopy"`
List bool `arg:"-l" help:"Only list files that would be copied. Similar to a 'dry-run' "`
PreserveExitCode bool `arg:"-p,--preserve-exitcode" help:"Always return the error code given by robocopy. By default, exit with code 0 on success and passthrough on copy failures."`
Insane bool `help:"Don't set sane defaults (currently sets #retries to 2 and timeout between them to 1 sec)."`
OtherArgs []string `arg:"-[,--passthrough" help:"All other arguments to be passed directly to robocopy."`
// !!! DISABLE IN PROD
Profile bool
}
func (Args) Description() string {
return "rbcp is a compact wrapper around robocopy, aiming to modernize the input and output while preserving the robustness of this time tested tool.\n"
}
func (Args) Version() string {
// impStyle will never be defined as GetConfig is never called in help/version text
impStyle = lipgloss.NewStyle().Foreground(lipgloss.Color(defaultConfig().Theme.ColorPrimary)).Bold(true)
return impStyle.Render(ProgramName+" version "+Version) + "\n" +
"Commit: " + Commit + "\n" +
"Built: " + BuildDate
}
// # Setup logging, config
func setup() int {
lvl := "warn"
if envLoglvl := os.Getenv("LOGLEVEL"); envLoglvl != "" {
lvl = envLoglvl
}
if loglvl, err := log.ParseLevel(lvl); err == nil {
log.SetLevel(loglvl)
logger.SetLevel(loglvl)
}
initWidth := 80
if envColumns := os.Getenv("COLUMNS"); envColumns != "" {
if i, err := strconv.Atoi(envColumns); err == nil {
initWidth = i
}
}
config = GetConfig()
styles := log.DefaultStyles()
styles.Levels[log.ErrorLevel] = lipgloss.NewStyle().
Background(lipgloss.Color(config.Theme.ColorError)).Foreground(lipgloss.Color("#fff")).
SetString("ERROR").Padding(0, 1).Bold(true)
styles.Levels[log.FatalLevel] = lipgloss.NewStyle().
Foreground(styles.Levels[log.FatalLevel].GetForeground()).
SetString("FATAL (EXIT)").Padding(0, 1).Bold(true)
logger.SetStyles(styles)
return initWidth
}
// # Parse arguments (break Paths into Src and Dest, perform expansions, build arguments for robocopy)
func parseArgs() {
if args.Profile {
os.MkdirAll("prof/", os.ModeDir)
runtime.SetBlockProfileRate(1)
t_now := time.Now().Format("2006-01-02 15.04.05")
f, err := os.Create("prof/" + t_now + ".pprof")
f2, err2 := os.Create("prof/block_" + t_now + ".pprof")
if err != nil || err2 != nil {
logger.Fatalf("could not create CPU profile: %v", err)
}
defer f.Close()
defer f2.Close()
if err := pprof.StartCPUProfile(f); err != nil {
logger.Fatalf("could not start CPU profile: %v", err)
}
pprof.Lookup("block").WriteTo(f2, 0)
defer pprof.StopCPUProfile()
}
// stores the positions of files in args.Paths
files = make([]string, 0)
if len(args.Paths) < 2 {
logger.Fatal("No destination specified")
}
dest = args.Paths[len(args.Paths)-1]
// TODO: ensure args.mir does not proceed if files are given
// : bash ./{a,b} brace expansion syntax
cfg := &expand.Config{
// do not expand env vars or do cmd/proc substitution
Env: nil,
CmdSubst: nil,
ProcSubst: nil,
ReadDir2: os.ReadDir,
}
parser := syntax.NewParser()
// : multiple files
for _, srcf := range args.Paths[:len(args.Paths)-1] {
if strings.ContainsRune(srcf, '{') {
_,err := os.Stat(srcf)
if err == nil {
logger.Warnf("The path passed %v is an existing file and also a valid brace expansion.\n" +
"Do you want to continue with "+ errorStyle.Render("expanding") +" it? (y/n)", srcf)
choice := getUserInputYN()
switch choice {
case "n":
// do not expand
files = append(files, srcf)
continue
case "y":
}
}
}
word, err := parser.Document(strings.NewReader(srcf))
if err != nil {
logger.Fatalf("Cannot parse syntax: %v", srcf)
}
fields, err := expand.Fields(cfg, word)
if err != nil {
logger.Fatalf("Invalid path syntax: %v", srcf)
}
logger.Infof("Expanded %v to %v", srcf, fields)
// ! check if a file exists with {} in its name and brace expansion would make it incorrect
files = append(files, fields...)
}
for i, srcf := range files {
// normalize paths; mvdan/sh has some weird behaviour i.e.
// paths in globs are /-separated whereas paths in braces are \-separated
srcf = filepath.ToSlash(srcf)
_, err := os.Stat(srcf)
if err == nil {
p, f := filepath.Split(srcf)
if p == "" {
logger.Debugf("Empty path, setting to ./")
p = "./"
}
if root == "" {
root = p
}
if root != p {
logger.Warnf("File passed not in root dir(%v): %v", root, srcf)
}
logger.Infof("Detected file %v and broke into %v and %v", srcf, p, f)
// args.Src[i] = p
// slices.Insert(args.OtherArgs, 0, f)
files[i] = f
} else {
logger.Errorf(errorStyle.Render("The file trying to be copied does not exist.\n%v"), err.Error())
os.Exit(1)
}
}
}
// # builds arguments for robocopy based on args. no side effects.
func buildRobocopyArgs() []string {
out := []string{root, dest}
out = slices.Concat(out, files, args.OtherArgs)
// out = append(out, args.OtherArgs...)
if args.Mir {
out = append(out, "/MIR")
}
logger.Infof("Starting robocopy with arguments: %v", out)
if !args.List {
// Add our output formatting flags
notAllowed := []string{"/bytes", "/np", "/njh", "/njs", "/ndl", "/nfl", "/ns"}
slices.DeleteFunc(out, func(e string) bool {
return slices.Contains(notAllowed, strings.ToLower(e))
})
// let user log if wanted, but we need output to function so tee it
for _, e := range out {
e = strings.ToLower(e)
if strings.HasPrefix(e, "/log") || strings.HasPrefix(e, "/unilog") {
out = append(out, "/tee")
}
}
out = append(out, "/NJH", "/NDL", "/BYTES")
if !args.Insane {
out = append(out, "/R:2", "/W:1")
}
} else {
fmt.Println()
}
return out
}
func main() {
logger = log.New(os.Stderr)
// : Argument parsing and applying effects
arg.MustParse(&args)
initWidth := setup()
startTime := time.Now()
parseArgs()
arrow := pathStyle.Italic(false).Render(" --> ")
if config.UseNerdFontArrow {
arrow = pathStyle.Italic(false).Render(" ─── ")
}
fmt.Println(lipgloss.PlaceHorizontal(initWidth, lipgloss.Center,
pathStyle.Render(root+"["+strings.Join(files, ",")+"]")+arrow+pathStyle.Render(args.Paths[len(args.Paths)-1])))
rbarglist := buildRobocopyArgs()
// : Dummy list-only run to get an overview of total
// if args.List is passed the program terminates inside this
totalFiles, totalBytes, err := getTotalCounts()
if err != nil {
logger.Fatalf("Error getting total counts: %v", err)
}
logger.Infof("Total to copy: %d files, %s\n", totalFiles, formatByteValue(totalBytes))
// : Init TUI and start robocopy
m := model{
progress: progress.New(
progress.WithGradient(config.Theme.ColorProgress[0], config.Theme.ColorProgress[1]),
// progress.WithSpringOptions(40, 1),
),
totalFiles: totalFiles,
totalBytes: totalBytes,
totalWidth: initWidth,
}
p = tea.NewProgram(m)
var stats RobocopyStats
// this apparently makes a 0-memory channel
ended := make(chan struct{})
forceQuit := make(chan struct{})
go func() {
if totalBytes > 0 {
// returns after TUI exit
t, err := p.Run()
if err != nil {
logger.Fatal("error running program:", err)
os.Exit(1)
}
m = t.(model)
if m.ForceQuit {
forceQuit <- struct{}{}
}
} else {
logger.Info("Nothing to copy, skipping progress bar")
}
ended <- struct{}{}
// logger.Warnf("program is over, waiting for summary")
}()
robocopyStart := time.Now()
var robocopyEnd time.Time
if totalBytes > 0 {
stats, err = runRobocopy(rbarglist, forceQuit)
if err != nil {
logger.Fatalf("Error: %v", err)
}
// logger.Debugf("Killed")
robocopyEnd = time.Now()
// p.Send(tea.Quit())
p.Wait()
} else {
// :/
robocopyEnd = time.Now()
}
<-ended
// : Display summary
logger.Infof("Robocopy took %v", robocopyEnd.Sub(robocopyStart))
logger.Infof("Waited for %v", time.Since(robocopyEnd))
displaySummary(stats)
timeTaken := time.Since(startTime)
logger.Infof("Whole program took %v", timeTaken)
if args.PreserveExitCode || stats.ExitCode >= 8 {
// Exit with the same code as robocopy
os.Exit(stats.ExitCode)
}
}
func runRobocopy(args []string, forceQuit chan struct{}) (RobocopyStats, error) {
var stats RobocopyStats
// Start timing
startTime := time.Now()
// Run robocopy and capture output
ctx := context.Background()
cmd := exec.CommandContext(ctx, "robocopy", args...)
logger.Debugf("Starting command %v", cmd)
stdout, err := cmd.StdoutPipe()
if err != nil {
return stats, fmt.Errorf("failed to get stdout pipe: %v", err)
}
// stderr, err := cmd.StderrPipe()
// if err != nil {
// return stats, fmt.Errorf("failed to get stderr pipe: %v", err)
// }
if err := cmd.Start(); err != nil {
return stats, fmt.Errorf("failed to start robocopy: %v", err)
}
ended := make(chan struct{})
var parsingTime time.Duration
go func() {
parsingStart := time.Now()
err = parseStreaming(stdout, &stats)
parsingTime = time.Since(parsingStart)
ended <- struct{}{}
}()
// no need to wait for both here - only one path can be true.
// also, don't return if forceQuit - can still display stats (if any)
select {
case <-forceQuit:
cmd.Cancel()
case <-ended:
}
cmd.Wait()
// TODO: add OSC 9;4 (progress) support through https://github.com/charmbracelet/x/blob/main/ansi/progress.go (or bubbletea)
// Calculate duration
endTime := time.Now()
stats.Duration = endTime.Sub(startTime)
stats.ExitCode = cmd.ProcessState.ExitCode()
logger.Infof("parsing took %v", parsingTime)
logger.Infof("Waited after cmd exit for parsing for %v", time.Since(endTime))
logger.Debugf("%+v", stats)
// Non-fatal error handling (robocopy uses exit codes for normal operations)
if err != nil && stats.ExitCode > 16 {
return stats, fmt.Errorf("robocopy failed with exit code %d: %v", stats.ExitCode, err)
}
return stats, nil
}
// getTotalCounts runs robocopy in list-only mode to get total files and bytes
func getTotalCounts() (int, int64, error) {
// Clone args and add /L to make it "list only" mode
rbargs := buildRobocopyArgs()
listArgs := make([]string, len(rbargs))
copy(listArgs, rbargs)
if !args.List {
listArgs = append(listArgs, "/L", "/NFL", "/NDL", "/NP", "/NC", "/BYTES")
}
cmd := exec.Command("robocopy", listArgs...)
output, err := cmd.CombinedOutput()
if args.List {
fmt.Print(string(output))
os.Exit(0)
}
var stats RobocopyStats
if err != nil && cmd.ProcessState.ExitCode() > 16 {
return 0, 0, fmt.Errorf("robocopy failed with exit code %d: %v", cmd.ProcessState.ExitCode(), err)
}
// stderr, err := cmd.StderrPipe()
// if err != nil {
// return stats, fmt.Errorf("failed to get stderr pipe: %v", err)
// }
// if err := cmd.Start(); err != nil {
// return stats, fmt.Errorf("failed to start robocopy: %v", err)
// }
err = parseStreaming(bytes.NewReader(output), &stats)
if err != nil {
return 0, 0, err
}
logger.Debugf("%+v", stats)
return stats.Copied.Files, stats.Copied.Bytes, nil
}