chore: import official kitty sources from upstream
Bring the kovidgoyal/kitty codebase in as the base of FWS-Kitty, vendored at upstream commit 91fb38a without its git history.
This commit is contained in:
commit
7e7d249099
1134 files changed
+433629
No files matched your search
Whitespace-only changes.
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,339 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package transfer
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/emmansun/base64"
|
||||
|
||||
"github.com/kovidgoyal/kitty"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
type Serializable interface {
|
||||
String() string
|
||||
MarshalJSON() ([]byte, error)
|
||||
}
|
||||
|
||||
type Unserializable interface {
|
||||
SetString(string) error
|
||||
}
|
||||
|
||||
type Action int // enum
|
||||
|
||||
var _ Serializable = Action_cancel
|
||||
var _ Unserializable = (*Action)(nil)
|
||||
|
||||
const (
|
||||
Action_invalid Action = iota
|
||||
Action_file
|
||||
Action_data
|
||||
Action_end_data
|
||||
Action_receive
|
||||
Action_send
|
||||
Action_cancel
|
||||
Action_status
|
||||
Action_finish
|
||||
)
|
||||
|
||||
type Compression int // enum
|
||||
|
||||
var _ Serializable = Compression_none
|
||||
var _ Unserializable = (*Compression)(nil)
|
||||
|
||||
const (
|
||||
Compression_none Compression = iota
|
||||
Compression_zlib
|
||||
)
|
||||
|
||||
type FileType int // enum
|
||||
|
||||
var _ Serializable = FileType_regular
|
||||
var _ Unserializable = (*FileType)(nil)
|
||||
|
||||
const (
|
||||
FileType_regular FileType = iota
|
||||
FileType_symlink
|
||||
FileType_directory
|
||||
FileType_link
|
||||
)
|
||||
|
||||
func (self FileType) ShortText() string {
|
||||
switch self {
|
||||
case FileType_regular:
|
||||
return "fil"
|
||||
case FileType_directory:
|
||||
return "dir"
|
||||
case FileType_symlink:
|
||||
return "sym"
|
||||
case FileType_link:
|
||||
return "lnk"
|
||||
}
|
||||
return "und"
|
||||
}
|
||||
|
||||
func (self FileType) Color() string {
|
||||
switch self {
|
||||
case FileType_regular:
|
||||
return "yellow"
|
||||
case FileType_directory:
|
||||
return "magenta"
|
||||
case FileType_symlink:
|
||||
return "blue"
|
||||
case FileType_link:
|
||||
return "green"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type TransmissionType int // enum
|
||||
|
||||
var _ Serializable = TransmissionType_simple
|
||||
var _ Unserializable = (*TransmissionType)(nil)
|
||||
|
||||
const (
|
||||
TransmissionType_simple TransmissionType = iota
|
||||
TransmissionType_rsync
|
||||
)
|
||||
|
||||
type QuietLevel int // enum
|
||||
|
||||
var _ Serializable = Quiet_none
|
||||
var _ Unserializable = (*QuietLevel)(nil)
|
||||
|
||||
const (
|
||||
Quiet_none QuietLevel = iota // 0
|
||||
Quiet_acknowledgements // 1
|
||||
Quiet_errors // 2
|
||||
)
|
||||
|
||||
type FileTransmissionCommand struct {
|
||||
Action Action `json:"ac,omitempty"`
|
||||
Compression Compression `json:"zip,omitempty"`
|
||||
Ftype FileType `json:"ft,omitempty"`
|
||||
Ttype TransmissionType `json:"tt,omitempty"`
|
||||
Quiet QuietLevel `json:"q,omitempty"`
|
||||
|
||||
Id string `json:"id,omitempty"`
|
||||
File_id string `json:"fid,omitempty"`
|
||||
Bypass string `json:"pw,omitempty" encoding:"base64"`
|
||||
Name string `json:"n,omitempty" encoding:"base64"`
|
||||
Status string `json:"st,omitempty" encoding:"base64"`
|
||||
Parent string `json:"pr,omitempty"`
|
||||
Mtime time.Duration `json:"mod,omitempty"`
|
||||
Permissions fs.FileMode `json:"prm,omitempty"`
|
||||
Size int64 `json:"sz,omitempty" default:"-1"`
|
||||
|
||||
Data []byte `json:"d,omitempty"`
|
||||
}
|
||||
|
||||
var ftc_field_map = sync.OnceValue(func() map[string]reflect.StructField {
|
||||
ans := make(map[string]reflect.StructField)
|
||||
self := FileTransmissionCommand{}
|
||||
v := reflect.ValueOf(self)
|
||||
typ := v.Type()
|
||||
fields := reflect.VisibleFields(typ)
|
||||
for _, field := range fields {
|
||||
if name := field.Tag.Get("json"); name != "" && field.IsExported() {
|
||||
name, _, _ = strings.Cut(name, ",")
|
||||
ans[name] = field
|
||||
}
|
||||
}
|
||||
return ans
|
||||
})
|
||||
|
||||
var safe_string_pat = sync.OnceValue(func() *regexp.Regexp {
|
||||
return regexp.MustCompile(`[^0-9a-zA-Z_:./@-]`)
|
||||
})
|
||||
|
||||
func safe_string(x string) string {
|
||||
return safe_string_pat().ReplaceAllLiteralString(x, ``)
|
||||
}
|
||||
|
||||
func (self FileTransmissionCommand) Serialize(prefix_with_osc_code ...bool) string {
|
||||
ans := strings.Builder{}
|
||||
v := reflect.ValueOf(self)
|
||||
found := false
|
||||
if len(prefix_with_osc_code) > 0 && prefix_with_osc_code[0] {
|
||||
ans.WriteString(strconv.Itoa(kitty.FileTransferCode))
|
||||
found = true
|
||||
}
|
||||
for name, field := range ftc_field_map() {
|
||||
val := v.FieldByIndex(field.Index)
|
||||
encoded_val := ""
|
||||
switch val.Kind() {
|
||||
case reflect.String:
|
||||
if sval := val.String(); sval != "" {
|
||||
enc := field.Tag.Get("encoding")
|
||||
switch enc {
|
||||
case "base64":
|
||||
encoded_val = base64.RawStdEncoding.EncodeToString(utils.UnsafeStringToBytes(sval))
|
||||
default:
|
||||
encoded_val = safe_string(sval)
|
||||
}
|
||||
}
|
||||
case reflect.Slice:
|
||||
switch val.Type().Elem().Kind() {
|
||||
case reflect.Uint8:
|
||||
if bval := val.Bytes(); len(bval) > 0 {
|
||||
encoded_val = base64.RawStdEncoding.EncodeToString(bval)
|
||||
}
|
||||
}
|
||||
case reflect.Int64:
|
||||
if ival := val.Int(); ival != 0 && (ival > 0 || name != "sz") {
|
||||
encoded_val = strconv.FormatInt(ival, 10)
|
||||
}
|
||||
default:
|
||||
if val.CanInterface() {
|
||||
switch field := val.Interface().(type) {
|
||||
case fs.FileMode:
|
||||
if field = field.Perm(); field != 0 {
|
||||
encoded_val = strconv.FormatInt(int64(field), 10)
|
||||
}
|
||||
case Serializable:
|
||||
if !val.Equal(reflect.Zero(val.Type())) {
|
||||
encoded_val = field.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if encoded_val != "" {
|
||||
if found {
|
||||
ans.WriteString(";")
|
||||
} else {
|
||||
found = true
|
||||
}
|
||||
ans.WriteString(name)
|
||||
ans.WriteString("=")
|
||||
ans.WriteString(encoded_val)
|
||||
}
|
||||
}
|
||||
return ans.String()
|
||||
}
|
||||
|
||||
func (self FileTransmissionCommand) String() string {
|
||||
s := self
|
||||
s.Data = nil
|
||||
ans, _ := json.Marshal(s)
|
||||
return utils.UnsafeBytesToString(ans)
|
||||
}
|
||||
|
||||
func NewFileTransmissionCommand(serialized string) (ans *FileTransmissionCommand, err error) {
|
||||
ans = &FileTransmissionCommand{}
|
||||
v := reflect.Indirect(reflect.ValueOf(ans))
|
||||
if err = utils.SetStructDefaults(v); err != nil {
|
||||
return
|
||||
}
|
||||
field_map := ftc_field_map()
|
||||
key_length, key_start, val_start := 0, 0, 0
|
||||
|
||||
handle_value := func(key, serialized_val string) error {
|
||||
key = strings.TrimLeft(key, `;`)
|
||||
if field, ok := field_map[key]; ok {
|
||||
val := v.FieldByIndex(field.Index)
|
||||
switch val.Kind() {
|
||||
case reflect.String:
|
||||
switch field.Tag.Get("encoding") {
|
||||
case "base64":
|
||||
b, err := base64.RawStdEncoding.DecodeString(serialized_val)
|
||||
if err != nil {
|
||||
return fmt.Errorf("The field %#v has invalid base64 encoded value with error: %w", key, err)
|
||||
}
|
||||
val.SetString(utils.UnsafeBytesToString(b))
|
||||
default:
|
||||
val.SetString(safe_string(serialized_val))
|
||||
}
|
||||
case reflect.Slice:
|
||||
switch val.Type().Elem().Kind() {
|
||||
case reflect.Uint8:
|
||||
b, err := base64.RawStdEncoding.DecodeString(serialized_val)
|
||||
if err != nil {
|
||||
return fmt.Errorf("The field %#v has invalid base64 encoded value with error: %w", key, err)
|
||||
}
|
||||
val.SetBytes(b)
|
||||
}
|
||||
case reflect.Int64:
|
||||
b, err := strconv.ParseInt(serialized_val, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("The field %#v has invalid integer value with error: %w", key, err)
|
||||
}
|
||||
val.SetInt(b)
|
||||
default:
|
||||
if val.CanAddr() {
|
||||
switch field := val.Addr().Interface().(type) {
|
||||
case Unserializable:
|
||||
err = field.SetString(serialized_val)
|
||||
if err != nil {
|
||||
return fmt.Errorf("The field %#v has invalid enum value with error: %w", key, err)
|
||||
}
|
||||
case *fs.FileMode:
|
||||
b, err := strconv.ParseUint(serialized_val, 10, 32)
|
||||
if err != nil {
|
||||
return fmt.Errorf("The field %#v has invalid file mode value with error: %w", key, err)
|
||||
}
|
||||
*field = fs.FileMode(b).Perm()
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return nil
|
||||
} else {
|
||||
return fmt.Errorf("The field name %#v is not known", key)
|
||||
}
|
||||
}
|
||||
|
||||
for i := 0; i < len(serialized); i++ {
|
||||
ch := serialized[i]
|
||||
if key_length == 0 {
|
||||
if ch == '=' {
|
||||
key_length = i - key_start
|
||||
val_start = i + 1
|
||||
}
|
||||
} else {
|
||||
if ch == ';' {
|
||||
val_length := i - val_start
|
||||
if key_length > 0 && val_start > 0 {
|
||||
err = handle_value(serialized[key_start:key_start+key_length], serialized[val_start:val_start+val_length])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
key_length = 0
|
||||
key_start = i + 1
|
||||
val_start = 0
|
||||
}
|
||||
}
|
||||
}
|
||||
if key_length > 0 && val_start > 0 {
|
||||
err = handle_value(serialized[key_start:key_start+key_length], serialized[val_start:])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func split_for_transfer(data []byte, file_id string, mark_last bool, callback func(*FileTransmissionCommand)) {
|
||||
const chunk_size = 4096
|
||||
for len(data) > 0 {
|
||||
chunk := data
|
||||
if len(chunk) > chunk_size {
|
||||
chunk = data[:chunk_size]
|
||||
}
|
||||
data = data[len(chunk):]
|
||||
callback(&FileTransmissionCommand{
|
||||
Action: utils.IfElse(mark_last && len(data) == 0, Action_end_data, Action_data),
|
||||
File_id: file_id, Data: chunk})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package transfer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestFTCSerialization(t *testing.T) {
|
||||
ftc := FileTransmissionCommand{}
|
||||
q := func(expected string) {
|
||||
actual := ftc.Serialize()
|
||||
ad := make(map[string]bool)
|
||||
for x := range strings.SplitSeq(actual, ";") {
|
||||
ad[x] = true
|
||||
}
|
||||
ed := make(map[string]bool)
|
||||
for x := range strings.SplitSeq(expected, ";") {
|
||||
ed[x] = true
|
||||
}
|
||||
if diff := cmp.Diff(ed, ad); diff != "" {
|
||||
t.Fatalf("Failed to Serialize:\n%s", diff)
|
||||
}
|
||||
}
|
||||
q("")
|
||||
ftc.Action = Action_send
|
||||
q("ac=send")
|
||||
ftc.File_id = "fid"
|
||||
ftc.Name = "moose"
|
||||
ftc.Mtime = time.Second
|
||||
ftc.Permissions = 0o600
|
||||
ftc.Data = []byte("moose")
|
||||
q("ac=send;fid=fid;n=bW9vc2U;mod=1000000000;prm=384;d=bW9vc2U")
|
||||
n, err := NewFileTransmissionCommand(ftc.Serialize())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
q(n.Serialize())
|
||||
|
||||
unsafe := "moo\x1b;;[?*.-se1"
|
||||
if safe_string(unsafe) != "moo.-se1" {
|
||||
t.Fatalf("safe_string() failed for %#v yielding: %#v", unsafe, safe_string(unsafe))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package transfer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/cli"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func read_bypass(loc string) (string, error) {
|
||||
if loc == "" {
|
||||
return "", nil
|
||||
}
|
||||
fdnum, err := strconv.Atoi(loc)
|
||||
if err == nil && fdnum >= 0 && fdnum < 256 && loc[0] >= '0' && loc[0] <= '9' {
|
||||
file := os.NewFile(uintptr(fdnum), loc)
|
||||
defer file.Close()
|
||||
raw, err := io.ReadAll(file)
|
||||
return utils.UnsafeBytesToString(raw), err
|
||||
}
|
||||
if loc == "-" {
|
||||
raw, err := io.ReadAll(os.Stdin)
|
||||
defer os.Stdin.Close()
|
||||
return utils.UnsafeBytesToString(raw), err
|
||||
}
|
||||
switch loc[0] {
|
||||
case '.', '~', '/':
|
||||
if loc[0] == '~' {
|
||||
loc = utils.Expanduser(loc)
|
||||
}
|
||||
raw, err := os.ReadFile(loc)
|
||||
return utils.UnsafeBytesToString(raw), err
|
||||
default:
|
||||
return loc, nil
|
||||
}
|
||||
}
|
||||
|
||||
func main(cmd *cli.Command, opts *Options, args []string) (rc int, err error) {
|
||||
if opts.PermissionsBypass != "" {
|
||||
val, err := read_bypass(opts.PermissionsBypass)
|
||||
if err != nil {
|
||||
return 1, err
|
||||
}
|
||||
opts.PermissionsBypass = strings.TrimSpace(val)
|
||||
}
|
||||
if len(args) == 0 {
|
||||
return 1, fmt.Errorf("Must specify at least one file to transfer")
|
||||
}
|
||||
switch opts.Direction {
|
||||
case "send", "download":
|
||||
err, rc = send_main(opts, args)
|
||||
default:
|
||||
err, rc = receive_main(opts, args)
|
||||
}
|
||||
if err != nil {
|
||||
rc = 1
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func EntryPoint(parent *cli.Command) {
|
||||
create_cmd(parent, main)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
|
||||
import sys
|
||||
|
||||
usage = 'source_files_or_directories destination_path'
|
||||
help_text = """\
|
||||
Transfer files over the TTY device. Can be used to send files between any two
|
||||
computers provided there is a TTY connection between them, such as over SSH.
|
||||
Supports copying files, directories (recursively), symlinks and hardlinks. Can
|
||||
even use an rsync like protocol to copy only changes between files. When
|
||||
copying multiple files, use the --confirm-paths option to see what exactly will
|
||||
be copied. The easiest way to use this kitten is to first ssh into the remote
|
||||
computer with the ssh kitten:
|
||||
|
||||
.. code::
|
||||
|
||||
$ kitten ssh my-remote-computer
|
||||
|
||||
Then, on the remote computer run the transfer kitten to do your copying.
|
||||
To copy a file from the remote computer to the local computer, run:
|
||||
|
||||
.. code::
|
||||
|
||||
$ kitten transfer remote-file /path/to/local-file
|
||||
|
||||
This will copy :file:`remote-file` from the remote computer to :file:`/path/to/local-file`
|
||||
on the local computer.
|
||||
|
||||
Similarly, to copy a file from the local computer to the remote one, run:
|
||||
|
||||
.. code::
|
||||
|
||||
$ kitten transfer --direction=upload /path/to/local-file remote-file
|
||||
|
||||
This will copy :file:`/path/to/local-file` from the local computer
|
||||
to :file:`remote-file` on the remote computer.
|
||||
|
||||
Multiple files can be copied:
|
||||
|
||||
.. code::
|
||||
|
||||
$ kitten transfer file1 file2 /path/to/dir/
|
||||
|
||||
This will put :code:`file1` and :code:`file2` into the directory
|
||||
:file:`/path/to/dir/` on the local computer.
|
||||
|
||||
Directories can also be copied, recursively:
|
||||
|
||||
.. code::
|
||||
|
||||
$ kitten transfer dir1 /path/to/dir/
|
||||
|
||||
This will put :file:`dir1` and all its contents into
|
||||
:file:`/path/to/dir/` on the local computer.
|
||||
|
||||
Note that when copying multiple files or directories, the destination
|
||||
must be an existing directory on the receiving computer. Relative file
|
||||
paths are resolved with respect to the current directory on the computer
|
||||
running the kitten and the home directory on the other computer. It is
|
||||
a good idea to use the :option:`--confirm-paths` command line flag to verify
|
||||
the kitten will copy the files you expect it to.
|
||||
"""
|
||||
|
||||
|
||||
def option_text() -> str:
|
||||
return """\
|
||||
--direction -d
|
||||
default=download
|
||||
choices=upload,download,send,receive
|
||||
Whether to send or receive files. :code:`send` or :code:`download` copy files from the computer
|
||||
on which the kitten is running (usually the remote computer) to the local computer. :code:`receive`
|
||||
or :code:`upload` copy files from the local computer to the remote computer.
|
||||
|
||||
|
||||
--mode -m
|
||||
default=normal
|
||||
choices=normal,mirror
|
||||
How to interpret command line arguments. In :code:`mirror` mode all arguments
|
||||
are assumed to be files/dirs on the sending computer and they are mirrored onto the
|
||||
receiving computer. Files under the HOME directory are copied to the HOME directory
|
||||
on the receiving computer even if the HOME directory is different.
|
||||
In :code:`normal` mode the last argument is assumed to be a destination path on the
|
||||
receiving computer. The last argument must be an existing directory unless copying a
|
||||
single file. When it is a directory it should end with a trailing slash.
|
||||
|
||||
|
||||
--compress
|
||||
default=auto
|
||||
choices=auto,never,always
|
||||
Whether to compress data being sent. By default compression is enabled based on the
|
||||
type of file being sent. For files recognized as being already compressed, compression
|
||||
is turned off as it just wastes CPU cycles.
|
||||
|
||||
|
||||
--permissions-bypass -p
|
||||
The password to use to skip the transfer confirmation popup in kitty. Must match
|
||||
the password set for the :opt:`file_transfer_confirmation_bypass` option in
|
||||
:file:`kitty.conf`. Note that leading and trailing whitespace is removed from
|
||||
the password. A password starting with :code:`.`, :code:`/` or :code:`~`
|
||||
characters is assumed to be a file name to read the password from. A value of
|
||||
:code:`-` means read the password from STDIN. A password that is purely a number
|
||||
less than 256 is assumed to be the number of a file descriptor from which to
|
||||
read the actual password.
|
||||
|
||||
|
||||
--confirm-paths -c
|
||||
type=bool-set
|
||||
Before actually transferring files, show a mapping of local file names to remote
|
||||
file names and ask for confirmation.
|
||||
|
||||
|
||||
--transmit-deltas -x
|
||||
type=bool-set
|
||||
If a file on the receiving side already exists, use the rsync algorithm to
|
||||
update it to match the file on the sending side, potentially saving lots of
|
||||
bandwidth and also automatically resuming partial transfers. Note that this will
|
||||
actually degrade performance on fast links or with small files, so use with care.
|
||||
"""
|
||||
|
||||
|
||||
def main(args: list[str]) -> None:
|
||||
raise SystemExit('This should be run as kitten transfer')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main(sys.argv)
|
||||
elif __name__ == '__doc__':
|
||||
from kitty.simple_cli_definitions import CompletionSpec
|
||||
|
||||
cd = sys.cli_docs # type: ignore
|
||||
cd['usage'] = usage
|
||||
cd['options'] = option_text
|
||||
cd['help_text'] = help_text
|
||||
cd['short_desc'] = 'Transfer files easily over the TTY device'
|
||||
cd['args_completion'] = CompletionSpec.from_string('type:file group:"Files"')
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,320 @@
|
||||
// License: GPLv3 Copyright: 2026, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package transfer
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestReceiveEmptyFile(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
|
||||
zlib_compress := func(data []byte) []byte {
|
||||
var b bytes.Buffer
|
||||
w := zlib.NewWriter(&b)
|
||||
if _, err := w.Write(data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return b.Bytes()
|
||||
}
|
||||
|
||||
receive := func(name, compress string, size int64, expected_compression Compression, chunks ...[]byte) string {
|
||||
t.Helper()
|
||||
ftc := &FileTransmissionCommand{Action: Action_file, File_id: "0", Name: name, Ftype: FileType_regular, Size: size}
|
||||
f, err := new_remote_file(&Options{Compress: compress}, ftc, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if f.compression_type != expected_compression {
|
||||
t.Fatalf("Unexpected compression type for %s: %s != %s", name, f.compression_type, expected_compression)
|
||||
}
|
||||
f.expanded_local_path = filepath.Join(tdir, name)
|
||||
for i, chunk := range chunks {
|
||||
is_last := i == len(chunks)-1
|
||||
if _, err = f.write_data(chunk, is_last); err != nil {
|
||||
t.Fatalf("Writing chunk %d of %s failed with error: %s", i, name, err)
|
||||
}
|
||||
}
|
||||
if f.actual_file != nil {
|
||||
t.Fatalf("Output file for %s not closed after last chunk", name)
|
||||
}
|
||||
return f.expanded_local_path
|
||||
}
|
||||
|
||||
assert_contents := func(path string, expected []byte) {
|
||||
t.Helper()
|
||||
actual, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to read %s with error: %s", path, err)
|
||||
}
|
||||
if !bytes.Equal(actual, expected) {
|
||||
t.Fatalf("Contents of %s incorrect: %q != %q", path, actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
// A single end_data with no payload, as sent for empty files
|
||||
assert_contents(receive("empty", "never", 0, Compression_none, nil), nil)
|
||||
// Parent directories must be created for empty files too
|
||||
assert_contents(receive(filepath.Join("sub", "dir", "empty"), "never", 0, Compression_none, nil), nil)
|
||||
|
||||
// An existing file must be truncated when the source is empty
|
||||
existing := filepath.Join(tdir, "existing")
|
||||
if err := os.WriteFile(existing, []byte("stale contents"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assert_contents(receive("existing", "never", 0, Compression_none, nil), nil)
|
||||
|
||||
// A zlib stream that decompresses to nothing, which happens when the
|
||||
// file shrinks to empty after its metadata was sent
|
||||
assert_contents(receive("zempty", "always", 8192, Compression_zlib, zlib_compress(nil)), nil)
|
||||
zstream := zlib_compress(nil)
|
||||
assert_contents(receive("zempty-split", "always", 8192, Compression_zlib, zstream[:1], zstream[1:]), nil)
|
||||
|
||||
// Non-empty files continue to work, including when the last chunk is empty
|
||||
assert_contents(receive("nonempty", "never", 3, Compression_none, []byte("abc"), nil), []byte("abc"))
|
||||
assert_contents(receive("znonempty", "always", 8192, Compression_zlib, zlib_compress([]byte("abc"))), []byte("abc"))
|
||||
}
|
||||
|
||||
func TestReceiveEmptyFileError(t *testing.T) {
|
||||
tdir := t.TempDir()
|
||||
// Make the destination impossible to create by having its parent be a regular file
|
||||
blocker := filepath.Join(tdir, "blocker")
|
||||
if err := os.WriteFile(blocker, []byte("x"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ftc := &FileTransmissionCommand{Action: Action_file, File_id: "0", Name: "empty", Ftype: FileType_regular}
|
||||
f, err := new_remote_file(&Options{Compress: "never"}, ftc, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.expanded_local_path = filepath.Join(blocker, "empty")
|
||||
_, err = f.write_data(nil, true)
|
||||
if err == nil {
|
||||
t.Fatalf("Receiving an empty file into an uncreatable path did not fail")
|
||||
}
|
||||
if !strings.Contains(err.Error(), f.expanded_local_path) {
|
||||
t.Fatalf("Error does not mention the destination path: %s", err)
|
||||
}
|
||||
}
|
||||
|
||||
func receive_regular_file(t *testing.T, dest string, chunks ...[]byte) (*remote_file, error) {
|
||||
t.Helper()
|
||||
size := 0
|
||||
for _, c := range chunks {
|
||||
size += len(c)
|
||||
}
|
||||
f, err := new_remote_file(&Options{Compress: "never"}, &FileTransmissionCommand{
|
||||
File_id: "0", Ftype: FileType_regular, Size: int64(size), Permissions: 0o644,
|
||||
}, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.expanded_local_path = dest
|
||||
t.Cleanup(func() { _ = f.close() })
|
||||
for i, chunk := range chunks {
|
||||
if _, err = f.write_data(chunk, i == len(chunks)-1); err != nil {
|
||||
return f, err
|
||||
}
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func assert_no_temp_files(t *testing.T, dir string, expected ...string) {
|
||||
t.Helper()
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var names []string
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
slices.Sort(expected)
|
||||
if !slices.Equal(names, expected) {
|
||||
t.Fatalf("Unexpected directory contents: %v != %v", names, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiveReplacesExistingLinks(t *testing.T) {
|
||||
for _, link := range []struct {
|
||||
name string
|
||||
create func(string, string) error
|
||||
target_exists bool
|
||||
}{
|
||||
{"symlink", os.Symlink, true},
|
||||
{"hardlink", os.Link, true},
|
||||
{"dangling_symlink", os.Symlink, false},
|
||||
} {
|
||||
for _, data := range []string{"", "incoming contents"} {
|
||||
t.Run(fmt.Sprintf("%s/size=%d", link.name, len(data)), func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "unrelated")
|
||||
const original = "keep these contents"
|
||||
if link.target_exists {
|
||||
if err := os.WriteFile(target, []byte(original), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
dest := filepath.Join(dir, "received")
|
||||
if err := link.create(target, dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := receive_regular_file(t, dest, []byte(data))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
m := manager{files: []*remote_file{f}}
|
||||
if err := m.finalize_transfer(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
st, err := os.Lstat(dest)
|
||||
if err != nil || !st.Mode().IsRegular() || st.Mode().Perm() != 0o644 {
|
||||
t.Fatalf("Destination is not a regular file with correct permissions: %v, %v", st, err)
|
||||
}
|
||||
if actual, err := os.ReadFile(dest); err != nil || string(actual) != data {
|
||||
t.Fatalf("Incorrect received contents: %q, %v", actual, err)
|
||||
}
|
||||
if link.target_exists {
|
||||
if actual, err := os.ReadFile(target); err != nil || string(actual) != original {
|
||||
t.Fatalf("Link target was modified: %q, %v", actual, err)
|
||||
}
|
||||
if st, err := os.Stat(target); err != nil || st.Mode().Perm() != 0o600 {
|
||||
t.Fatalf("Link target permissions changed: %v, %v", st, err)
|
||||
}
|
||||
assert_no_temp_files(t, dir, "received", "unrelated")
|
||||
} else {
|
||||
assert_no_temp_files(t, dir, "received")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiveInterruptedLeavesDestinationIntact(t *testing.T) {
|
||||
for _, symlink := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("symlink=%t", symlink), func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "existing")
|
||||
const original = "keep these contents"
|
||||
if err := os.WriteFile(target, []byte(original), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dest, expected := target, []string{"existing"}
|
||||
if symlink {
|
||||
dest, expected = filepath.Join(dir, "link"), []string{"existing", "link"}
|
||||
if err := os.Symlink(target, dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
before, err := os.Lstat(dest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f, err := new_remote_file(&Options{Compress: "never"}, &FileTransmissionCommand{
|
||||
File_id: "0", Ftype: FileType_regular, Size: 100,
|
||||
}, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.expanded_local_path = dest
|
||||
if _, err := f.write_data([]byte("partial"), false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := os.Lstat(dest)
|
||||
if err != nil || !os.SameFile(before, after) {
|
||||
t.Fatalf("Destination was replaced by an incomplete transfer: %v", err)
|
||||
}
|
||||
if actual, err := os.ReadFile(target); err != nil || string(actual) != original {
|
||||
t.Fatalf("Destination was modified by an incomplete transfer: %q, %v", actual, err)
|
||||
}
|
||||
assert_no_temp_files(t, dir, expected...)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiveIntoUnwritableDirectory(t *testing.T) {
|
||||
if os.Geteuid() == 0 {
|
||||
t.Skip("Directory permissions are not enforced for root")
|
||||
}
|
||||
dir := t.TempDir()
|
||||
dest := filepath.Join(dir, "existing")
|
||||
if err := os.WriteFile(dest, []byte("stale contents"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := filepath.Join(dir, "hardlink")
|
||||
if err := os.Link(dest, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(dir, 0o500); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chmod(dir, 0o700) })
|
||||
// A hard linked file cannot be safely written in place
|
||||
if _, err := receive_regular_file(t, dest, []byte("new")); err == nil {
|
||||
t.Fatal("Receiving into a hard linked file in an unwritable directory should fail")
|
||||
}
|
||||
if actual, err := os.ReadFile(link); err != nil || string(actual) != "stale contents" {
|
||||
t.Fatalf("Hard linked file was modified: %q, %v", actual, err)
|
||||
}
|
||||
// A file with a single link is written in place
|
||||
if err := os.Chmod(dir, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Remove(link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Chmod(dir, 0o500); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := receive_regular_file(t, dest, []byte("new")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if actual, err := os.ReadFile(dest); err != nil || string(actual) != "new" {
|
||||
t.Fatalf("Incorrect received contents: %q, %v", actual, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceivePreservesExistingDirectory(t *testing.T) {
|
||||
for _, symlink := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("symlink=%t", symlink), func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
target := filepath.Join(dir, "directory")
|
||||
if err := os.Mkdir(target, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
dest := target
|
||||
if symlink {
|
||||
dest = filepath.Join(dir, "link")
|
||||
if err := os.Symlink(target, dest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
before, err := os.Lstat(dest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := receive_regular_file(t, dest, nil); err == nil {
|
||||
t.Fatal("Receiving a regular file over a directory should fail")
|
||||
}
|
||||
after, err := os.Lstat(dest)
|
||||
if err != nil || !os.SameFile(before, after) {
|
||||
t.Fatalf("Directory or its symlink was replaced: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
from typing import Callable, Union
|
||||
|
||||
from kitty.typing_compat import ReadableBuffer, WriteableBuffer
|
||||
|
||||
class RsyncError(Exception):
|
||||
pass
|
||||
|
||||
class Hasher:
|
||||
def __init__(self, which: str, data: ReadableBuffer = b''): ...
|
||||
def update(self, data: ReadableBuffer) -> None: ...
|
||||
def reset(self) -> None: ...
|
||||
def digest(self) -> bytes: ...
|
||||
def hexdigest(self) -> str: ...
|
||||
@property
|
||||
def digest_size(self) -> int: ...
|
||||
@property
|
||||
def block_size(self) -> int: ...
|
||||
@property
|
||||
def name(self) -> str: ...
|
||||
|
||||
def xxh128_hash(data: ReadableBuffer) -> bytes: ...
|
||||
def xxh128_hash_with_seed(data: ReadableBuffer, seed: int) -> bytes: ...
|
||||
|
||||
class Patcher:
|
||||
def __init__(self, expected_input_size: int = 0): ...
|
||||
def signature_header(self, output: WriteableBuffer) -> int: ...
|
||||
def sign_block(self, block: ReadableBuffer, output: WriteableBuffer) -> int: ...
|
||||
def apply_delta_data(self, data: ReadableBuffer, read: Callable[[int, WriteableBuffer], int], write: Callable[[ReadableBuffer], None]) -> None: ...
|
||||
def finish_delta_data(self) -> None: ...
|
||||
@property
|
||||
def block_size(self) -> int: ...
|
||||
@property
|
||||
def total_data_in_delta(self) -> int: ...
|
||||
|
||||
class Differ:
|
||||
def add_signature_data(self, data: ReadableBuffer) -> None: ...
|
||||
def finish_signature_data(self) -> None: ...
|
||||
def next_op(self, read: Callable[[WriteableBuffer], int], write: Callable[[ReadableBuffer], None]) -> bool: ...
|
||||
|
||||
def parse_ftc(x: Union[str, ReadableBuffer], callback: Callable[[memoryview, memoryview], None]) -> None: ...
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,130 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package transfer
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-cmp/cmp"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
func TestPathMappingSend(t *testing.T) {
|
||||
opts := &Options{}
|
||||
tdir := t.TempDir()
|
||||
b := filepath.Join(tdir, "b")
|
||||
os.Mkdir(b, 0o700)
|
||||
os.WriteFile(filepath.Join(b, "r"), nil, 0600)
|
||||
os.Mkdir(filepath.Join(b, "d"), 0o700)
|
||||
os.WriteFile(filepath.Join(b, "d", "r"), nil, 0600)
|
||||
|
||||
gm := func(args ...string) ([]*File, error) {
|
||||
return files_for_send(opts, args)
|
||||
}
|
||||
|
||||
mp := func(path string, is_remote bool) string {
|
||||
path = strings.TrimSpace(path)
|
||||
if strings.HasPrefix(path, "~") || filepath.IsAbs(path) {
|
||||
return path
|
||||
}
|
||||
return filepath.Join(tdir, path)
|
||||
}
|
||||
|
||||
tf := func(expected string, args ...string) {
|
||||
files, err := gm(args...)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed with mode: %s cwd: %s home: %s and args: %#v\n%s", opts.Mode, cwd_path(), home_path(), args, err)
|
||||
}
|
||||
actual := make(map[string]string)
|
||||
for _, f := range files {
|
||||
actual[f.expanded_local_path] = f.remote_path
|
||||
}
|
||||
e := make(map[string]string, len(actual))
|
||||
for rec := range strings.SplitSeq(expected, " ") {
|
||||
k, v, _ := strings.Cut(rec, ":")
|
||||
e[mp(k, false)] = mp(v, true)
|
||||
}
|
||||
if diff := cmp.Diff(e, actual); diff != "" {
|
||||
t.Fatalf("Failed with mode: %s cwd: %s home: %s and args: %#v\n%s", opts.Mode, cwd_path(), home_path(), args, diff)
|
||||
}
|
||||
}
|
||||
|
||||
opts.Mode = "mirror"
|
||||
run_with_paths(b, "/foo/bar", func() {
|
||||
tf("b/r:b/r b/d:b/d b/d/r:b/d/r", "r", "d")
|
||||
tf("b/r:b/r b/d/r:b/d/r", "r", "d/r")
|
||||
})
|
||||
run_with_paths(b, tdir, func() {
|
||||
tf("b/r:~/b/r b/d:~/b/d b/d/r:~/b/d/r", "r", "d")
|
||||
})
|
||||
opts.Mode = "normal"
|
||||
run_with_paths("/some/else", "/foo/bar", func() {
|
||||
tf("b/r:/dest/r b/d:/dest/d b/d/r:/dest/d/r", filepath.Join(b, "r"), filepath.Join(b, "d"), "/dest")
|
||||
tf("b/r:~/dest/r b/d:~/dest/d b/d/r:~/dest/d/r", filepath.Join(b, "r"), filepath.Join(b, "d"), "~/dest")
|
||||
})
|
||||
run_with_paths(b, "/foo/bar", func() {
|
||||
tf("b/r:/dest/r b/d:/dest/d b/d/r:/dest/d/r", "r", "d", "/dest")
|
||||
})
|
||||
os.Symlink("/foo/b", filepath.Join(b, "e"))
|
||||
os.Symlink("r", filepath.Join(b, "s"))
|
||||
os.Link(filepath.Join(b, "r"), filepath.Join(b, "h"))
|
||||
|
||||
file_idx := 0
|
||||
first_file := func(args ...string) *File {
|
||||
files, err := gm(args...)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return files[file_idx]
|
||||
}
|
||||
ae := func(a any, b any) {
|
||||
if diff := cmp.Diff(a, b); diff != "" {
|
||||
t.Fatalf("%s", diff)
|
||||
}
|
||||
}
|
||||
run_with_paths("/some/else", "/foo/bar", func() {
|
||||
f := first_file(filepath.Join(b, "e"), "dest")
|
||||
ae(f.symbolic_link_target, "path:/foo/b")
|
||||
f = first_file(filepath.Join(b, "s"), filepath.Join(b, "r"), "dest")
|
||||
ae(f.symbolic_link_target, "fid:2")
|
||||
f = first_file(filepath.Join(b, "h"), "dest")
|
||||
ae(f.file_type, FileType_regular)
|
||||
file_idx = 1
|
||||
f = first_file(filepath.Join(b, "h"), filepath.Join(b, "r"), "dest")
|
||||
ae(f.hard_link_target, "fid:1")
|
||||
ae(f.file_type, FileType_link)
|
||||
})
|
||||
}
|
||||
|
||||
func TestSendFailureHints(t *testing.T) {
|
||||
opts := &Options{}
|
||||
home := filepath.ToSlash(home_path())
|
||||
eisdir := func(remote_path string) *File {
|
||||
return &File{remote_path: remote_path, err_msg: "EISDIR:Cannot replace the existing directory x with a file"}
|
||||
}
|
||||
th := func(args []string, failed []*File, expected ...string) {
|
||||
t.Helper()
|
||||
actual := failure_hints(opts, args, failed)
|
||||
if len(actual) != len(expected) {
|
||||
t.Fatalf("Unexpected hints for %#v: %#v", args, actual)
|
||||
}
|
||||
for i, e := range expected {
|
||||
if !strings.Contains(actual[i], e) {
|
||||
t.Fatalf("Hint %#v does not contain %#v", actual[i], e)
|
||||
}
|
||||
}
|
||||
}
|
||||
th([]string{"a", "/x/d"}, nil)
|
||||
th([]string{"a", "/x/d"}, []*File{eisdir("/x/d")}, "trailing slash, for example: /x/d/")
|
||||
th([]string{"a", "/x/d/"}, []*File{eisdir("/x/d/a")})
|
||||
th([]string{"a", "b", "/x/d"}, []*File{eisdir("/x/d/a")})
|
||||
th([]string{"a", home + "/Downloads"}, []*File{{remote_path: home + "/Downloads", err_msg: "ENOTSUP:x"}}, `\~/Downloads`)
|
||||
th([]string{"a", home + "/Downloads"}, []*File{eisdir(home + "/Downloads")}, "trailing slash", `\~/Downloads`)
|
||||
opts.Mode = "mirror"
|
||||
th([]string{"a", "/x/d"}, []*File{eisdir("/x/d")})
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
// License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
|
||||
|
||||
package transfer
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/kovidgoyal/kitty/tools/crypto"
|
||||
"github.com/kovidgoyal/kitty/tools/utils"
|
||||
"github.com/kovidgoyal/kitty/tools/utils/humanize"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
var global_cwd, global_home string
|
||||
|
||||
func cwd_path() string {
|
||||
if global_cwd == "" {
|
||||
ans, _ := os.Getwd()
|
||||
return ans
|
||||
}
|
||||
return global_cwd
|
||||
}
|
||||
|
||||
func home_path() string {
|
||||
if global_home == "" {
|
||||
return utils.Expanduser("~")
|
||||
}
|
||||
return global_home
|
||||
}
|
||||
|
||||
func encode_bypass(request_id string, bypass string) (string, error) {
|
||||
q := request_id + ";" + bypass
|
||||
if pkey_encoded := os.Getenv("KITTY_PUBLIC_KEY"); pkey_encoded != "" {
|
||||
encryption_protocol, pubkey, err := crypto.DecodePublicKey(pkey_encoded)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
encrypted, err := crypto.Encrypt_data(utils.UnsafeStringToBytes(q), pubkey, encryption_protocol)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return fmt.Sprintf("kitty-1:%s", utils.UnsafeBytesToString(encrypted)), nil
|
||||
}
|
||||
return "", fmt.Errorf("KITTY_PUBLIC_KEY env var not set, cannot transmit password securely")
|
||||
}
|
||||
|
||||
func abspath(path string, use_home ...bool) string {
|
||||
if filepath.IsAbs(path) {
|
||||
return path
|
||||
}
|
||||
var base string
|
||||
if len(use_home) > 0 && use_home[0] {
|
||||
base = home_path()
|
||||
} else {
|
||||
base = cwd_path()
|
||||
}
|
||||
return filepath.Join(base, path)
|
||||
}
|
||||
|
||||
func expand_home(path string) string {
|
||||
if strings.HasPrefix(path, "~"+string(os.PathSeparator)) {
|
||||
path = strings.TrimLeft(path[2:], string(os.PathSeparator))
|
||||
path = filepath.Join(home_path(), path)
|
||||
} else if path == "~" {
|
||||
path = home_path()
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func random_id() string {
|
||||
bytes := []byte{0, 0}
|
||||
rand.Read(bytes)
|
||||
return fmt.Sprintf("%x%s", os.Getpid(), hex.EncodeToString(bytes))
|
||||
}
|
||||
|
||||
func run_with_paths(cwd, home string, f func()) {
|
||||
global_cwd, global_home = cwd, home
|
||||
defer func() { global_cwd, global_home = "", "" }()
|
||||
f()
|
||||
}
|
||||
|
||||
func should_be_compressed(path, strategy string) bool {
|
||||
if strategy == "always" {
|
||||
return true
|
||||
}
|
||||
if strategy == "never" {
|
||||
return false
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(path))
|
||||
if ext != "" {
|
||||
switch ext[1:] {
|
||||
case "zip", "odt", "odp", "pptx", "docx", "gz", "bz2", "xz", "svgz":
|
||||
return false
|
||||
}
|
||||
}
|
||||
mt := utils.GuessMimeType(path)
|
||||
if strings.HasSuffix(mt, "+zip") || (strings.HasPrefix(mt, "image/") && mt != "image/svg+xml") || strings.HasPrefix(mt, "video/") {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func print_rsync_stats(total_bytes, delta_bytes, signature_bytes int64) {
|
||||
fmt.Println("Rsync stats:")
|
||||
fmt.Printf(" Delta size: %s Signature size: %s\n", humanize.Size(delta_bytes), humanize.Size(signature_bytes))
|
||||
frac := float64(delta_bytes+signature_bytes) / float64(utils.Max(1, total_bytes))
|
||||
fmt.Printf(" Transmitted: %s of a total of %s (%.1f%%)\n", humanize.Size(delta_bytes+signature_bytes), humanize.Size(total_bytes), frac*100)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python
|
||||
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
|
||||
|
||||
import os
|
||||
from collections.abc import Generator
|
||||
from contextlib import contextmanager
|
||||
|
||||
_cwd = _home = ''
|
||||
|
||||
|
||||
def abspath(path: str, use_home: bool = False) -> str:
|
||||
base = home_path() if use_home else (_cwd or os.getcwd())
|
||||
return os.path.normpath(os.path.join(base, path))
|
||||
|
||||
|
||||
def home_path() -> str:
|
||||
return _home or os.path.expanduser('~')
|
||||
|
||||
|
||||
def cwd_path() -> str:
|
||||
return _cwd or os.getcwd()
|
||||
|
||||
|
||||
def expand_home(path: str) -> str:
|
||||
if path.startswith('~' + os.sep) or (os.altsep and path.startswith('~' + os.altsep)):
|
||||
return os.path.join(home_path(), path[2:].lstrip(os.sep + (os.altsep or '')))
|
||||
return path
|
||||
|
||||
|
||||
@contextmanager
|
||||
def set_paths(cwd: str = '', home: str = '') -> Generator[None, None, None]:
|
||||
global _cwd, _home
|
||||
orig = _cwd, _home
|
||||
try:
|
||||
_cwd, _home = cwd, home
|
||||
yield
|
||||
finally:
|
||||
_cwd, _home = orig
|
||||
|
||||
|
||||
class IdentityCompressor:
|
||||
def compress(self, data: bytes | memoryview) -> bytes:
|
||||
return bytes(data)
|
||||
|
||||
def flush(self) -> bytes:
|
||||
return b''
|
||||
|
||||
|
||||
class ZlibCompressor:
|
||||
def __init__(self) -> None:
|
||||
import zlib
|
||||
|
||||
self.c = zlib.compressobj()
|
||||
|
||||
def compress(self, data: bytes | memoryview) -> bytes:
|
||||
return self.c.compress(data)
|
||||
|
||||
def flush(self) -> bytes:
|
||||
return self.c.flush()
|
||||
Reference in new issue
Block a user