/
ssh.go
52 lines (42 loc) · 1.01 KB
/
ssh.go
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
package fs
import (
gocontext "context"
"fmt"
"io"
"os"
"path/filepath"
sftpClient "github.com/flanksource/artifacts/clients/sftp"
"github.com/pkg/sftp"
)
type sshFS struct {
*sftp.Client
}
func NewSSHFS(host, user, password string) (*sshFS, error) {
sftpClient, err := sftpClient.SSHConnect(host, user, password)
if err != nil {
return nil, err
}
return &sshFS{
Client: sftpClient,
}, nil
}
func (s *sshFS) Read(ctx gocontext.Context, path string) (io.ReadCloser, error) {
return s.Client.Open(path)
}
func (s *sshFS) Write(ctx gocontext.Context, path string, data io.Reader) (os.FileInfo, error) {
// Ensure the directory exists
dir := filepath.Dir(path)
err := s.Client.MkdirAll(dir)
if err != nil {
return nil, fmt.Errorf("error creating directory: %w", err)
}
f, err := s.Client.Create(path)
if err != nil {
return nil, fmt.Errorf("error creating file: %w", err)
}
_, err = io.Copy(f, data)
if err != nil {
return nil, fmt.Errorf("error writing to file: %w", err)
}
return f.Stat()
}