go-sshclient icon indicating copy to clipboard operation
go-sshclient copied to clipboard

When uploading/downloading, make sure to truncate the remote/local file when opened.

Open jlesage opened this issue 2 years ago • 1 comments

This fixes issue when replacing an existing remote/local file. If the file is not first truncated, the resulting file will be incorrect when new file is smaller than the existing one.

jlesage avatar Oct 19 '23 16:10 jlesage

Sorry for the late reply.

Implicitly truncating files is usually not safe, and this decision is usually left to the developer. There are two options to fix this problem:

  1. Explicitly truncate the file using the Truncate API
// upload
sftp.Truncate(remotePath, 0 /*size*/) or sftp.Remove(remotePath)
sftp.Upload(localPath, remotePath)

// download
os.Truncate(localPath, 0 /*size*/) or os.Remove(localPath)
sftp.Download(remotePath, localPath)
  1. Add a truncated version of the upload/download API in go-sshclient (explicitly indicating that it will overwrite existing files)
// force upload and overwrite existing remote files
sftp.ForceUpload(localPath, remotePath)

// force download and overwrite existing local files
sftp.ForceDownload(remotePath, localPath)

If you are interested, please add ForceUpload and ForceDownload APIs. looking forward to your work!

helloyi avatar Nov 30 '23 14:11 helloyi