sftp: refactor so we only have one way of running remote commands

This also returns errors from running ssh Hash commands which we
didn't do before.
This commit is contained in:
Nick Craig-Wood 2021-11-15 12:21:43 +00:00
parent c4cb167d4a
commit 099eff8891

View File

@ -1110,10 +1110,12 @@ func (f *Fs) run(ctx context.Context, cmd string) ([]byte, error) {
session.Stdout = &stdout session.Stdout = &stdout
session.Stderr = &stderr session.Stderr = &stderr
fs.Debugf(f, "Running remote command: %s", cmd)
err = session.Run(cmd) err = session.Run(cmd)
if err != nil { if err != nil {
return nil, fmt.Errorf("failed to run %q: %s: %w", cmd, stderr.Bytes(), err) return nil, fmt.Errorf("failed to run %q: %s: %w", cmd, bytes.TrimSpace(stderr.Bytes()), err)
} }
fs.Debugf(f, "Remote command result: %s", bytes.TrimSpace(stdout.Bytes()))
return stdout.Bytes(), nil return stdout.Bytes(), nil
} }
@ -1230,8 +1232,6 @@ func (o *Object) Remote() string {
// Hash returns the selected checksum of the file // Hash returns the selected checksum of the file
// If no checksum is available it returns "" // If no checksum is available it returns ""
func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) { func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) {
o.fs.addSession() // Show session in use
defer o.fs.removeSession()
if o.fs.opt.DisableHashCheck { if o.fs.opt.DisableHashCheck {
return "", nil return "", nil
} }
@ -1255,36 +1255,16 @@ func (o *Object) Hash(ctx context.Context, r hash.Type) (string, error) {
return "", hash.ErrUnsupported return "", hash.ErrUnsupported
} }
c, err := o.fs.getSftpConnection(ctx)
if err != nil {
return "", fmt.Errorf("Hash get SFTP connection: %w", err)
}
session, err := c.sshClient.NewSession()
o.fs.putSftpConnection(&c, err)
if err != nil {
return "", fmt.Errorf("Hash put SFTP connection: %w", err)
}
var stdout, stderr bytes.Buffer
session.Stdout = &stdout
session.Stderr = &stderr
escapedPath := shellEscape(o.path()) escapedPath := shellEscape(o.path())
if o.fs.opt.PathOverride != "" { if o.fs.opt.PathOverride != "" {
escapedPath = shellEscape(path.Join(o.fs.opt.PathOverride, o.remote)) escapedPath = shellEscape(path.Join(o.fs.opt.PathOverride, o.remote))
} }
err = session.Run(hashCmd + " " + escapedPath) b, err := o.fs.run(ctx, hashCmd+" "+escapedPath)
fs.Debugf(nil, "sftp cmd = %s", escapedPath)
if err != nil { if err != nil {
_ = session.Close() return "", fmt.Errorf("failed to calculate %v hash: %w", r, err)
fs.Debugf(o, "Failed to calculate %v hash: %v (%s)", r, err, bytes.TrimSpace(stderr.Bytes()))
return "", nil
} }
_ = session.Close()
b := stdout.Bytes()
fs.Debugf(nil, "sftp output = %q", b)
str := parseHash(b) str := parseHash(b)
fs.Debugf(nil, "sftp hash = %q", str)
if r == hash.MD5 { if r == hash.MD5 {
o.md5sum = &str o.md5sum = &str
} else if r == hash.SHA1 { } else if r == hash.SHA1 {