| 1 | // Package rsynccmd provides a command-like interface to gokrazy/rsync, which |
| 2 | // contains a native Go rsync implementation that supports sending and receiving |
| 3 | // files as client or server, compatible with the original tridge rsync (from |
| 4 | // the samba project) or openrsync (used on OpenBSD and macOS 15+). |
| 5 | // |
| 6 | // This interface allows you to replace calls to an external rsync program, like: |
| 7 | // |
| 8 | // rsync -a rsync://share01/dataset /tmp/dataset |
| 9 | // |
| 10 | // …with calls into Go code running in the same process (no dependency on an |
| 11 | // external rsync program!): |
| 12 | // |
| 13 | // cmd := rsynccmd.Command("rsync", "-a", "rsync://share01/dataset", "/tmp/dataset") |
| 14 | // cmd.Stdout = os.Stdout |
| 15 | // cmd.Stderr = os.Stderr |
| 16 | // if _, err := cmd.Run(context.Background()); err != nil { |
| 17 | // return fmt.Errorf("%v: %v", cmd.Args, err) |
| 18 | // } |
| 19 | package rsynccmd |
| 20 | |
| 21 | import ( |
| 22 | "context" |
| 23 | "io" |
| 24 | "net" |
| 25 | |
| 26 | "github.com/gokrazy/rsync/internal/maincmd" |
| 27 | "github.com/gokrazy/rsync/internal/rsyncos" |
| 28 | "github.com/gokrazy/rsync/internal/rsyncstats" |
| 29 | ) |
| 30 | |
| 31 | // Cmd represents an rsync invocation being prepared or run. |
| 32 | type Cmd struct { |
| 33 | Args []string |
| 34 | Stdin io.ReadCloser |
| 35 | Stdout io.WriteCloser |
| 36 | Stderr io.WriteCloser |
| 37 | DontRestrict bool |
| 38 | |
| 39 | DialContext func(ctx context.Context, network, addr string) (net.Conn, error) |
| 40 | } |
| 41 | |
| 42 | // Command returns the [Cmd] struct to execute rsync with the given arguments. |
| 43 | // |
| 44 | // The name parameter is ignored and only specified for symmetry with |
| 45 | // os/exec.Command. |
| 46 | func Command(name string, arg ...string) *Cmd { |
| 47 | return &Cmd{ |
| 48 | Args: append([]string{name}, arg...), |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | // Result contains information about the transfer. |
| 53 | type Result struct { |
| 54 | Stats *rsyncstats.TransferStats |
| 55 | } |
| 56 | |
| 57 | // Run starts the specified rsync invocation. |
| 58 | func (c *Cmd) Run(ctx context.Context) (*Result, error) { |
| 59 | osenv := &rsyncos.Env{ |
| 60 | Stdin: c.Stdin, |
| 61 | Stdout: c.Stdout, |
| 62 | Stderr: c.Stderr, |
| 63 | DontRestrict: c.DontRestrict, |
| 64 | DialContext: c.DialContext, |
| 65 | } |
| 66 | stats, err := maincmd.Main(ctx, osenv, c.Args, nil) |
| 67 | if err != nil { |
| 68 | return nil, err |
| 69 | } |
| 70 | return &Result{Stats: stats}, nil |
| 71 | } |