Skip to content

Commit 5ebf39f

Browse files
authored
Add WriteFile and use it for Scp (#64)
- WriteFile takes io.Reader as input so we have a more generic copy mechanism - Let Scp method use WriteFile - Possible fix for #61 as Scp did not close the source
1 parent 7fc0760 commit 5ebf39f

File tree

1 file changed

+29
-17
lines changed

1 file changed

+29
-17
lines changed

easyssh.go

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -377,8 +377,8 @@ loop:
377377
return outStr, errStr, isTimeout, err
378378
}
379379

380-
// Scp uploads sourceFile to remote machine like native scp console app.
381-
func (ssh_conf *MakeConfig) Scp(sourceFile string, etargetFile string) error {
380+
// WriteFile reads size bytes from the reader and writes them to a file on the remote machine
381+
func (ssh_conf *MakeConfig) WriteFile(reader io.Reader, size int64, etargetFile string) error {
382382
session, client, err := ssh_conf.Connect()
383383
if err != nil {
384384
return err
@@ -388,31 +388,19 @@ func (ssh_conf *MakeConfig) Scp(sourceFile string, etargetFile string) error {
388388

389389
targetFile := filepath.Base(etargetFile)
390390

391-
src, srcErr := os.Open(sourceFile)
392-
393-
if srcErr != nil {
394-
return srcErr
395-
}
396-
397-
srcStat, statErr := src.Stat()
398-
399-
if statErr != nil {
400-
return statErr
401-
}
402-
403391
w, err := session.StdinPipe()
404392
if err != nil {
405393
return err
406394
}
407395

408396
copyF := func() error {
409-
_, err := fmt.Fprintln(w, "C0644", srcStat.Size(), targetFile)
397+
_, err := fmt.Fprintln(w, "C0644", size, targetFile)
410398
if err != nil {
411399
return err
412400
}
413401

414-
if srcStat.Size() > 0 {
415-
_, err = io.Copy(w, src)
402+
if size > 0 {
403+
_, err = io.Copy(w, reader)
416404
if err != nil {
417405
return err
418406
}
@@ -440,3 +428,27 @@ func (ssh_conf *MakeConfig) Scp(sourceFile string, etargetFile string) error {
440428
err = <-copyErrC
441429
return err
442430
}
431+
432+
// Scp uploads sourceFile to remote machine like native scp console app.
433+
func (ssh_conf *MakeConfig) Scp(sourceFile string, etargetFile string) error {
434+
session, client, err := ssh_conf.Connect()
435+
if err != nil {
436+
return err
437+
}
438+
defer client.Close()
439+
defer session.Close()
440+
441+
src, srcErr := os.Open(sourceFile)
442+
443+
if srcErr != nil {
444+
return srcErr
445+
}
446+
defer src.Close()
447+
448+
srcStat, statErr := src.Stat()
449+
450+
if statErr != nil {
451+
return statErr
452+
}
453+
return ssh_conf.WriteFile(src, srcStat.Size(), etargetFile)
454+
}

0 commit comments

Comments
 (0)