diff --git a/pkg/utils/filepath/path.go b/pkg/utils/filepath/path.go new file mode 100644 index 000000000..48d1e1320 --- /dev/null +++ b/pkg/utils/filepath/path.go @@ -0,0 +1,33 @@ +package filepath + +import ( + stdfilepath "path/filepath" + "strings" +) + +// 与标准库中的 [filepath.Dir] 类似,但会尝试保留原有的路径分隔符。 +// +// 入参: +// - path: 文件路径。 +// +// 出参: +// - 目录路径。 +func Dir(path string) string { + const SEP_WIN = "\\" + const SEP_UNIX = "/" + + sep := SEP_UNIX + if strings.Contains(path, SEP_WIN) && !strings.Contains(path, SEP_UNIX) { + sep = SEP_WIN + } + + dir := stdfilepath.Dir(path) + + if sep != SEP_UNIX && strings.Contains(dir, SEP_UNIX) { + dir = strings.ReplaceAll(dir, SEP_UNIX, sep) + } else if sep != SEP_WIN && strings.Contains(dir, SEP_WIN) { + dir = strings.ReplaceAll(dir, SEP_WIN, sep) + } + + return dir +} diff --git a/pkg/utils/ssh/io.go b/pkg/utils/ssh/io.go index 7261e58fa..ff1d77536 100644 --- a/pkg/utils/ssh/io.go +++ b/pkg/utils/ssh/io.go @@ -5,11 +5,12 @@ import ( "errors" "fmt" "os" - "path/filepath" "github.com/pkg/sftp" "github.com/povsister/scp" "golang.org/x/crypto/ssh" + + xfilepath "github.com/certimate-go/certimate/pkg/utils/filepath" ) // 与 [WriteRemote] 类似,但写入的是字符串内容。 @@ -97,7 +98,7 @@ func writeRemoteWithSFTP(sshCli *ssh.Client, path string, data []byte) error { } defer sftpCli.Close() - if err := sftpCli.MkdirAll(filepath.ToSlash(filepath.Dir(path))); err != nil { + if err := sftpCli.MkdirAll(xfilepath.Dir(path)); err != nil { return fmt.Errorf("failed to create remote directory: %w", err) } @@ -122,7 +123,7 @@ func removeRemoteWithSFTP(sshCli *ssh.Client, path string) error { } defer sftpCli.Close() - if err := sftpCli.MkdirAll(filepath.ToSlash(filepath.Dir(path))); err != nil { + if err := sftpCli.MkdirAll(xfilepath.Dir(path)); err != nil { return fmt.Errorf("failed to create remote directory: %w", err) }