repo stringlengths 6 47 | file_url stringlengths 77 269 | file_path stringlengths 5 186 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-07 08:35:43 2026-01-07 08:55:24 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/configstruct/configstruct_test.go | fs/config/configstruct/configstruct_test.go | package configstruct_test
import (
"fmt"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config/configstruct"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type Conf struct {
A string
B string
}
type Conf2 struct {
PotatoPie string `config:"spud_pie"`
BeanStew bool
RaisinRoll int
SausageOnStick int64
ForbiddenFruit uint
CookingTime fs.Duration
TotalWeight fs.SizeSuffix
}
type ConfNested struct {
Conf // embedded struct with no tag
Sub1 Conf `config:"sub"` // member struct with tag
Sub2 Conf2 // member struct without tag
C string // normal item
D fs.Tristate // an embedded struct which we don't want to recurse
}
func TestItemsError(t *testing.T) {
_, err := configstruct.Items(nil)
assert.EqualError(t, err, "argument must be a pointer")
_, err = configstruct.Items(new(int))
assert.EqualError(t, err, "argument must be a pointer to a struct")
}
// Check each item has a Set function pointer then clear it for the assert.Equal
func cleanItems(t *testing.T, items []configstruct.Item) []configstruct.Item {
for i := range items {
item := &items[i]
assert.NotNil(t, item.Set)
item.Set = nil
}
return items
}
func TestItems(t *testing.T) {
in := &Conf2{
PotatoPie: "yum",
BeanStew: true,
RaisinRoll: 42,
SausageOnStick: 101,
ForbiddenFruit: 6,
CookingTime: fs.Duration(42 * time.Second),
TotalWeight: fs.SizeSuffix(17 << 20),
}
got, err := configstruct.Items(in)
require.NoError(t, err)
want := []configstruct.Item{
{Name: "spud_pie", Field: "PotatoPie", Value: string("yum")},
{Name: "bean_stew", Field: "BeanStew", Value: true},
{Name: "raisin_roll", Field: "RaisinRoll", Value: int(42)},
{Name: "sausage_on_stick", Field: "SausageOnStick", Value: int64(101)},
{Name: "forbidden_fruit", Field: "ForbiddenFruit", Value: uint(6)},
{Name: "cooking_time", Field: "CookingTime", Value: fs.Duration(42 * time.Second)},
{Name: "total_weight", Field: "TotalWeight", Value: fs.SizeSuffix(17 << 20)},
}
assert.Equal(t, want, cleanItems(t, got))
}
func TestItemsNested(t *testing.T) {
in := ConfNested{
Conf: Conf{
A: "1",
B: "2",
},
Sub1: Conf{
A: "3",
B: "4",
},
Sub2: Conf2{
PotatoPie: "yum",
BeanStew: true,
RaisinRoll: 42,
SausageOnStick: 101,
ForbiddenFruit: 6,
CookingTime: fs.Duration(42 * time.Second),
TotalWeight: fs.SizeSuffix(17 << 20),
},
C: "normal",
D: fs.Tristate{Value: true, Valid: true},
}
got, err := configstruct.Items(&in)
require.NoError(t, err)
want := []configstruct.Item{
{Name: "a", Field: "Conf.A", Value: string("1")},
{Name: "b", Field: "Conf.B", Value: string("2")},
{Name: "sub_a", Field: "Sub1.A", Value: string("3")},
{Name: "sub_b", Field: "Sub1.B", Value: string("4")},
{Name: "spud_pie", Field: "Sub2.PotatoPie", Value: string("yum")},
{Name: "bean_stew", Field: "Sub2.BeanStew", Value: true},
{Name: "raisin_roll", Field: "Sub2.RaisinRoll", Value: int(42)},
{Name: "sausage_on_stick", Field: "Sub2.SausageOnStick", Value: int64(101)},
{Name: "forbidden_fruit", Field: "Sub2.ForbiddenFruit", Value: uint(6)},
{Name: "cooking_time", Field: "Sub2.CookingTime", Value: fs.Duration(42 * time.Second)},
{Name: "total_weight", Field: "Sub2.TotalWeight", Value: fs.SizeSuffix(17 << 20)},
{Name: "c", Field: "C", Value: string("normal")},
{Name: "d", Field: "D", Value: fs.Tristate{Value: true, Valid: true}},
}
assert.Equal(t, want, cleanItems(t, got))
}
func TestSetBasics(t *testing.T) {
c := &Conf{A: "one", B: "two"}
err := configstruct.Set(configMap{}, c)
require.NoError(t, err)
assert.Equal(t, &Conf{A: "one", B: "two"}, c)
}
// a simple configmap.Getter for testing
type configMap map[string]string
// Get the value
func (c configMap) Get(key string) (value string, ok bool) {
value, ok = c[key]
return value, ok
}
func TestSetMore(t *testing.T) {
c := &Conf{A: "one", B: "two"}
m := configMap{
"a": "ONE",
}
err := configstruct.Set(m, c)
require.NoError(t, err)
assert.Equal(t, &Conf{A: "ONE", B: "two"}, c)
}
func TestSetFull(t *testing.T) {
in := &Conf2{
PotatoPie: "yum",
BeanStew: true,
RaisinRoll: 42,
SausageOnStick: 101,
ForbiddenFruit: 6,
CookingTime: fs.Duration(42 * time.Second),
TotalWeight: fs.SizeSuffix(17 << 20),
}
m := configMap{
"spud_pie": "YUM",
"bean_stew": "FALSE",
"raisin_roll": "43 ",
"sausage_on_stick": " 102 ",
"forbidden_fruit": "0x7",
"cooking_time": "43s",
"total_weight": "18M",
}
want := &Conf2{
PotatoPie: "YUM",
BeanStew: false,
RaisinRoll: 43,
SausageOnStick: 102,
ForbiddenFruit: 7,
CookingTime: fs.Duration(43 * time.Second),
TotalWeight: fs.SizeSuffix(18 << 20),
}
err := configstruct.Set(m, in)
require.NoError(t, err)
assert.Equal(t, want, in)
}
func TestSetAnyFull(t *testing.T) {
in := &Conf2{
PotatoPie: "yum",
BeanStew: true,
RaisinRoll: 42,
SausageOnStick: 101,
ForbiddenFruit: 6,
CookingTime: fs.Duration(42 * time.Second),
TotalWeight: fs.SizeSuffix(17 << 20),
}
m := map[string]any{
"spud_pie": "YUM",
"bean_stew": false,
"raisin_roll": "43 ",
"sausage_on_stick": " 102 ",
"forbidden_fruit": "0x7",
"cooking_time": 43 * time.Second,
"total_weight": "18M",
}
want := &Conf2{
PotatoPie: "YUM",
BeanStew: false,
RaisinRoll: 43,
SausageOnStick: 102,
ForbiddenFruit: 7,
CookingTime: fs.Duration(43 * time.Second),
TotalWeight: fs.SizeSuffix(18 << 20),
}
err := configstruct.SetAny(m, in)
require.NoError(t, err)
assert.Equal(t, want, in)
}
func TestStringToInterface(t *testing.T) {
item := struct{ A int }{2}
for _, test := range []struct {
in string
def any
want any
err string
}{
{"", string(""), "", ""},
{" string ", string(""), " string ", ""},
{"123", int(0), int(123), ""},
{"0x123", int(0), int(0x123), ""},
{" 0x123 ", int(0), int(0x123), ""},
{"-123", int(0), int(-123), ""},
{"0", false, false, ""},
{"1", false, true, ""},
{"7", false, true, `parsing "7" as bool failed: strconv.ParseBool: parsing "7": invalid syntax`},
{"FALSE", false, false, ""},
{"true", false, true, ""},
{"123", uint(0), uint(123), ""},
{"123", int64(0), int64(123), ""},
{"123x", int64(0), nil, "parsing \"123x\" as int64 failed: expected newline"},
{"truth", false, nil, "parsing \"truth\" as bool failed: strconv.ParseBool: parsing \"truth\": invalid syntax"},
{"struct", item, nil, "parsing \"struct\" as struct { A int } failed: don't know how to parse this type"},
{"1s", fs.Duration(0), fs.Duration(time.Second), ""},
{"1m1s", fs.Duration(0), fs.Duration(61 * time.Second), ""},
{"1potato", fs.Duration(0), nil, `parsing "1potato" as fs.Duration failed: parsing time "1potato" as "2006-01-02": cannot parse "1potato" as "2006"`},
{``, []string{}, []string{}, ""},
{`""`, []string(nil), []string{""}, ""},
{`hello`, []string{}, []string{"hello"}, ""},
{`"hello"`, []string{}, []string{"hello"}, ""},
{`hello,world!`, []string(nil), []string{"hello", "world!"}, ""},
{`"hello","world!"`, []string(nil), []string{"hello", "world!"}, ""},
{"1s", time.Duration(0), time.Second, ""},
{"1m1s", time.Duration(0), 61 * time.Second, ""},
{"1potato", time.Duration(0), nil, `parsing "1potato" as time.Duration failed: time: unknown unit "potato" in duration "1potato"`},
{"1M", fs.SizeSuffix(0), fs.Mebi, ""},
{"1G", fs.SizeSuffix(0), fs.Gibi, ""},
{"1potato", fs.SizeSuffix(0), nil, `parsing "1potato" as fs.SizeSuffix failed: bad suffix 'o'`},
} {
what := fmt.Sprintf("parse %q as %T", test.in, test.def)
got, err := configstruct.StringToInterface(test.def, test.in)
if test.err == "" {
require.NoError(t, err, what)
assert.Equal(t, test.want, got, what)
} else {
assert.Nil(t, got, what)
assert.EqualError(t, err, test.err, what)
}
}
}
func TestInterfaceToString(t *testing.T) {
item := struct{ A int }{2}
for _, test := range []struct {
in any
want string
err string
}{
{nil, "", "interpreting <nil> as string failed: don't know how to convert this"},
{"", "", ""},
{" string ", " string ", ""},
{int(123), "123", ""},
{int(0x123), "291", ""},
{int(-123), "-123", ""},
{false, "false", ""},
{true, "true", ""},
{uint(123), "123", ""},
{int64(123), "123", ""},
{item, "", "interpreting struct { A int } as string failed: don't know how to convert this"},
{fs.Duration(time.Second), "1s", ""},
{fs.Duration(61 * time.Second), "1m1s", ""},
{[]string{}, ``, ""},
{[]string{""}, `""`, ""},
{[]string{"", ""}, `,`, ""},
{[]string{"hello"}, `hello`, ""},
{[]string{"hello", "world"}, `hello,world`, ""},
{[]string{"hello", "", "world"}, `hello,,world`, ""},
{[]string{`hello, world`, `goodbye, world!`}, `"hello, world","goodbye, world!"`, ""},
{time.Second, "1s", ""},
{61 * time.Second, "1m1s", ""},
{fs.Mebi, "1Mi", ""},
{fs.Gibi, "1Gi", ""},
} {
what := fmt.Sprintf("interpret %#v as string", test.in)
got, err := configstruct.InterfaceToString(test.in)
if test.err == "" {
require.NoError(t, err, what)
assert.Equal(t, test.want, got, what)
} else {
assert.Equal(t, "", got)
assert.EqualError(t, err, test.err, what)
}
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/configstruct/internal_test.go | fs/config/configstruct/internal_test.go | package configstruct
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestCamelToSnake(t *testing.T) {
for _, test := range []struct {
in string
want string
}{
{"", ""},
{"Type", "type"},
{"AuthVersion", "auth_version"},
{"AccessKeyID", "access_key_id"},
} {
got := camelToSnake(test.in)
assert.Equal(t, test.want, got, test.in)
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/flags/flags.go | fs/config/flags/flags.go | // Package flags contains enhanced versions of spf13/pflag flag
// routines which will read from the environment also.
package flags
import (
"os"
"regexp"
"strings"
"time"
"github.com/rclone/rclone/fs"
"github.com/spf13/pflag"
)
// Groups of Flags
type Groups struct {
// Groups of flags
Groups []*Group
// GroupsMaps maps a group name to a Group
ByName map[string]*Group
}
// Group related flags together for documentation purposes
type Group struct {
Groups *Groups
Name string
Help string
Flags *pflag.FlagSet
}
// NewGroups constructs a collection of Groups
func NewGroups() *Groups {
return &Groups{
ByName: make(map[string]*Group),
}
}
// NewGroup to create Group
func (gs *Groups) NewGroup(name, help string) *Group {
group := &Group{
Name: name,
Help: help,
Flags: pflag.NewFlagSet(name, pflag.ExitOnError),
}
gs.ByName[group.Name] = group
gs.Groups = append(gs.Groups, group)
return group
}
// Filter makes a copy of groups filtered by flagsRe
func (gs *Groups) Filter(group string, filterRe *regexp.Regexp, filterNamesOnly bool) *Groups {
newGs := NewGroups()
for _, g := range gs.Groups {
if group == "" || strings.EqualFold(g.Name, group) {
newG := newGs.NewGroup(g.Name, g.Help)
g.Flags.VisitAll(func(f *pflag.Flag) {
if filterRe == nil || filterRe.MatchString(f.Name) || (!filterNamesOnly && filterRe.MatchString(f.Usage)) {
newG.Flags.AddFlag(f)
}
})
}
}
return newGs
}
// Include makes a copy of groups only including the ones in the filter string
func (gs *Groups) Include(groupsString string) *Groups {
if groupsString == "" {
return gs
}
want := map[string]bool{}
for groupName := range strings.SplitSeq(groupsString, ",") {
_, ok := All.ByName[groupName]
if !ok {
fs.Fatalf(nil, "Couldn't find group %q in command annotation", groupName)
}
want[groupName] = true
}
newGs := NewGroups()
for _, g := range gs.Groups {
if !want[g.Name] {
continue
}
newG := newGs.NewGroup(g.Name, g.Help)
newG.Flags = g.Flags
}
return newGs
}
// Add a new flag to the Group
func (g *Group) Add(flag *pflag.Flag) {
g.Flags.AddFlag(flag)
}
// AllRegistered returns all flags in a group
func (gs *Groups) AllRegistered() map[*pflag.Flag]struct{} {
out := make(map[*pflag.Flag]struct{})
for _, g := range gs.Groups {
g.Flags.VisitAll(func(f *pflag.Flag) {
out[f] = struct{}{}
})
}
return out
}
// All is the global stats Groups
var All *Groups
// Groups of flags for documentation purposes
func init() {
All = NewGroups()
All.NewGroup("Copy", "Flags for anything which can copy a file")
All.NewGroup("Sync", "Flags used for sync commands")
All.NewGroup("Important", "Important flags useful for most commands")
All.NewGroup("Check", "Flags used for check commands")
All.NewGroup("Networking", "Flags for general networking and HTTP stuff")
All.NewGroup("Performance", "Flags helpful for increasing performance")
All.NewGroup("Config", "Flags for general configuration of rclone")
All.NewGroup("Debugging", "Flags for developers")
All.NewGroup("Filter", "Flags for filtering directory listings")
All.NewGroup("Listing", "Flags for listing directories")
All.NewGroup("Logging", "Flags for logging and statistics")
All.NewGroup("Metadata", "Flags to control metadata")
All.NewGroup("RC", "Flags to control the Remote Control API")
All.NewGroup("Metrics", "Flags to control the Metrics HTTP endpoint.")
}
// installFlag constructs a name from the flag passed in and
// sets the value and default from the environment if possible
// the value may be overridden when the command line is parsed
//
// Used to create non-backend flags like --stats.
//
// It also adds the flag to the groups passed in.
func installFlag(flags *pflag.FlagSet, name string, groupsString string) {
// Find flag
flag := flags.Lookup(name)
if flag == nil {
fs.Fatalf(nil, "Couldn't find flag --%q", name)
}
// Read default from environment if possible
envKey := fs.OptionToEnv(name)
if envValue, envFound := os.LookupEnv(envKey); envFound {
isStringArray := false
opt, isOption := flag.Value.(*fs.Option)
if isOption {
_, isStringArray = opt.Default.([]string)
}
if isStringArray {
// Treat stringArray differently, treating the environment variable as a CSV array
var list fs.CommaSepList
err := list.Set(envValue)
if err != nil {
fs.Fatalf(nil, "Invalid value when setting stringArray --%s from environment variable %s=%q: %v", name, envKey, envValue, err)
}
// Set both the Value (so items on the command line get added) and DefValue so the help is correct
opt.Value = ([]string)(list)
flag.DefValue = list.String()
for _, v := range list {
fs.Debugf(nil, "Setting --%s %q from environment variable %s=%q", name, v, envKey, envValue)
}
} else {
err := flags.Set(name, envValue)
if err != nil {
fs.Fatalf(nil, "Invalid value when setting --%s from environment variable %s=%q: %v", name, envKey, envValue, err)
}
fs.Debugf(nil, "Setting --%s %q from environment variable %s=%q", name, flag.Value, envKey, envValue)
flag.DefValue = envValue
}
}
// Add flag to Group if it is a global flag
if groupsString != "" && flags == pflag.CommandLine {
for groupName := range strings.SplitSeq(groupsString, ",") {
if groupName == "rc-" {
groupName = "RC"
}
group, ok := All.ByName[groupName]
if !ok {
fs.Fatalf(nil, "Couldn't find group %q for flag --%s", groupName, name)
}
group.Add(flag)
}
}
}
// StringP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.StringP
func StringP(name, shorthand string, value string, usage string, groups string) (out *string) {
out = pflag.StringP(name, shorthand, value, usage)
installFlag(pflag.CommandLine, name, groups)
return out
}
// StringVarP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.StringVarP
func StringVarP(flags *pflag.FlagSet, p *string, name, shorthand string, value string, usage string, groups string) {
flags.StringVarP(p, name, shorthand, value, usage)
installFlag(flags, name, groups)
}
// BoolP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.BoolP
func BoolP(name, shorthand string, value bool, usage string, groups string) (out *bool) {
out = pflag.BoolP(name, shorthand, value, usage)
installFlag(pflag.CommandLine, name, groups)
return out
}
// BoolVarP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.BoolVarP
func BoolVarP(flags *pflag.FlagSet, p *bool, name, shorthand string, value bool, usage string, groups string) {
flags.BoolVarP(p, name, shorthand, value, usage)
installFlag(flags, name, groups)
}
// IntP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.IntP
func IntP(name, shorthand string, value int, usage string, groups string) (out *int) {
out = pflag.IntP(name, shorthand, value, usage)
installFlag(pflag.CommandLine, name, groups)
return out
}
// Int64P defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.IntP
func Int64P(name, shorthand string, value int64, usage string, groups string) (out *int64) {
out = pflag.Int64P(name, shorthand, value, usage)
installFlag(pflag.CommandLine, name, groups)
return out
}
// Int64VarP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.Int64VarP
func Int64VarP(flags *pflag.FlagSet, p *int64, name, shorthand string, value int64, usage string, groups string) {
flags.Int64VarP(p, name, shorthand, value, usage)
installFlag(flags, name, groups)
}
// IntVarP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.IntVarP
func IntVarP(flags *pflag.FlagSet, p *int, name, shorthand string, value int, usage string, groups string) {
flags.IntVarP(p, name, shorthand, value, usage)
installFlag(flags, name, groups)
}
// Uint32VarP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.Uint32VarP
func Uint32VarP(flags *pflag.FlagSet, p *uint32, name, shorthand string, value uint32, usage string, groups string) {
flags.Uint32VarP(p, name, shorthand, value, usage)
installFlag(flags, name, groups)
}
// Float64P defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.Float64P
func Float64P(name, shorthand string, value float64, usage string, groups string) (out *float64) {
out = pflag.Float64P(name, shorthand, value, usage)
installFlag(pflag.CommandLine, name, groups)
return out
}
// Float64VarP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.Float64VarP
func Float64VarP(flags *pflag.FlagSet, p *float64, name, shorthand string, value float64, usage string, groups string) {
flags.Float64VarP(p, name, shorthand, value, usage)
installFlag(flags, name, groups)
}
// DurationP defines a flag which can be set by an environment variable
//
// It wraps the duration in an fs.Duration for extra suffixes and
// passes it to pflag.VarP
func DurationP(name, shorthand string, value time.Duration, usage string, groups string) (out *time.Duration) {
out = new(time.Duration)
*out = value
pflag.VarP((*fs.Duration)(out), name, shorthand, usage)
installFlag(pflag.CommandLine, name, groups)
return out
}
// DurationVarP defines a flag which can be set by an environment variable
//
// It wraps the duration in an fs.Duration for extra suffixes and
// passes it to pflag.VarP
func DurationVarP(flags *pflag.FlagSet, p *time.Duration, name, shorthand string, value time.Duration, usage string, groups string) {
flags.VarP((*fs.Duration)(p), name, shorthand, usage)
installFlag(flags, name, groups)
}
// VarP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.VarP
func VarP(value pflag.Value, name, shorthand, usage string, groups string) {
pflag.VarP(value, name, shorthand, usage)
installFlag(pflag.CommandLine, name, groups)
}
// FVarP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.VarP
func FVarP(flags *pflag.FlagSet, value pflag.Value, name, shorthand, usage string, groups string) {
flags.VarP(value, name, shorthand, usage)
installFlag(flags, name, groups)
}
// StringArrayP defines a flag which can be set by an environment variable
//
// It sets one value only - command line flags can be used to set more.
//
// It is a thin wrapper around pflag.StringArrayP
func StringArrayP(name, shorthand string, value []string, usage string, groups string) (out *[]string) {
out = pflag.StringArrayP(name, shorthand, value, usage)
installFlag(pflag.CommandLine, name, groups)
return out
}
// StringArrayVarP defines a flag which can be set by an environment variable
//
// It sets one value only - command line flags can be used to set more.
//
// It is a thin wrapper around pflag.StringArrayVarP
func StringArrayVarP(flags *pflag.FlagSet, p *[]string, name, shorthand string, value []string, usage string, groups string) {
flags.StringArrayVarP(p, name, shorthand, value, usage)
installFlag(flags, name, groups)
}
// CountP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.CountP
func CountP(name, shorthand string, usage string, groups string) (out *int) {
out = pflag.CountP(name, shorthand, usage)
installFlag(pflag.CommandLine, name, groups)
return out
}
// CountVarP defines a flag which can be set by an environment variable
//
// It is a thin wrapper around pflag.CountVarP
func CountVarP(flags *pflag.FlagSet, p *int, name, shorthand string, usage string, groups string) {
flags.CountVarP(p, name, shorthand, usage)
installFlag(flags, name, groups)
}
// AddFlagsFromOptions takes a slice of fs.Option and adds flags for all of them
func AddFlagsFromOptions(flags *pflag.FlagSet, prefix string, options fs.Options) {
done := map[string]struct{}{}
for i := range options {
opt := &options[i]
// Skip if done already (e.g. with Provider options)
if _, doneAlready := done[opt.Name]; doneAlready {
continue
}
done[opt.Name] = struct{}{}
// Make a flag from each option
if prefix == "" {
opt.NoPrefix = true
}
name := opt.FlagName(prefix)
found := flags.Lookup(name) != nil
if !found {
// Take first line of help only
help := strings.TrimSpace(opt.Help)
if nl := strings.IndexRune(help, '\n'); nl >= 0 {
help = help[:nl]
}
help = strings.TrimRight(strings.TrimSpace(help), ".!?")
if opt.IsPassword {
help += " (obscured)"
}
flag := flags.VarPF(opt, name, opt.ShortOpt, help)
installFlag(flags, name, opt.Groups)
if _, isBool := opt.Default.(bool); isBool {
flag.NoOptDefVal = "true"
}
// Hide on the command line if requested
if opt.Hide&fs.OptionHideCommandLine != 0 {
flag.Hidden = true
}
} else {
fs.Errorf(nil, "Not adding duplicate flag --%s", name)
}
// flag.Hidden = true
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/configflags/configflags.go | fs/config/configflags/configflags.go | // Package configflags defines the flags used by rclone. It is
// decoupled into a separate package so it can be replaced.
package configflags
// Options set by command line flags
import (
"context"
"net"
"os"
"strconv"
"strings"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fs/config/flags"
"github.com/spf13/pflag"
)
var (
// these will get interpreted into fs.Config via SetFlags() below
verbose int
quiet bool
configPath string
cacheDir string
tempDir string
dumpHeaders bool
dumpBodies bool
deleteBefore bool
deleteDuring bool
deleteAfter bool
bindAddr string
disableFeatures string
dscp string
uploadHeaders []string
downloadHeaders []string
headers []string
metadataSet []string
)
// AddFlags adds the non filing system specific flags to the command
func AddFlags(ci *fs.ConfigInfo, flagSet *pflag.FlagSet) {
flags.AddFlagsFromOptions(flagSet, "", fs.ConfigOptionsInfo)
// Add flags we haven't converted into options yet
flags.CountVarP(flagSet, &verbose, "verbose", "v", "Print lots more stuff (repeat for more)", "Logging,Important")
flags.BoolVarP(flagSet, &quiet, "quiet", "q", false, "Print as little stuff as possible", "Logging")
flags.StringVarP(flagSet, &configPath, "config", "", config.GetConfigPath(), "Config file", "Config")
flags.StringVarP(flagSet, &cacheDir, "cache-dir", "", config.GetCacheDir(), "Directory rclone will use for caching", "Config")
flags.StringVarP(flagSet, &tempDir, "temp-dir", "", os.TempDir(), "Directory rclone will use for temporary files", "Config")
flags.BoolVarP(flagSet, &dumpHeaders, "dump-headers", "", false, "Dump HTTP headers - may contain sensitive info", "Debugging")
flags.BoolVarP(flagSet, &dumpBodies, "dump-bodies", "", false, "Dump HTTP headers and bodies - may contain sensitive info", "Debugging")
flags.BoolVarP(flagSet, &deleteBefore, "delete-before", "", false, "When synchronizing, delete files on destination before transferring", "Sync")
flags.BoolVarP(flagSet, &deleteDuring, "delete-during", "", false, "When synchronizing, delete files during transfer", "Sync")
flags.BoolVarP(flagSet, &deleteAfter, "delete-after", "", false, "When synchronizing, delete files on destination after transferring (default)", "Sync")
flags.StringVarP(flagSet, &bindAddr, "bind", "", "", "Local address to bind to for outgoing connections, IPv4, IPv6 or name", "Networking")
flags.StringVarP(flagSet, &disableFeatures, "disable", "", "", "Disable a comma separated list of features (use --disable help to see a list)", "Config")
flags.StringArrayVarP(flagSet, &uploadHeaders, "header-upload", "", nil, "Set HTTP header for upload transactions", "Networking")
flags.StringArrayVarP(flagSet, &downloadHeaders, "header-download", "", nil, "Set HTTP header for download transactions", "Networking")
flags.StringArrayVarP(flagSet, &headers, "header", "", nil, "Set HTTP header for all transactions", "Networking")
flags.StringArrayVarP(flagSet, &metadataSet, "metadata-set", "", nil, "Add metadata key=value when uploading", "Metadata")
flags.StringVarP(flagSet, &dscp, "dscp", "", "", "Set DSCP value to connections, value or name, e.g. CS1, LE, DF, AF21", "Networking")
}
// ParseHeaders converts the strings passed in via the header flags into HTTPOptions
func ParseHeaders(headers []string) []*fs.HTTPOption {
opts := []*fs.HTTPOption{}
for _, header := range headers {
parts := strings.SplitN(header, ":", 2)
if len(parts) == 1 {
fs.Fatalf(nil, "Failed to parse '%s' as an HTTP header. Expecting a string like: 'Content-Encoding: gzip'", header)
}
option := &fs.HTTPOption{
Key: strings.TrimSpace(parts[0]),
Value: strings.TrimSpace(parts[1]),
}
opts = append(opts, option)
}
return opts
}
// SetFlags sets flags which aren't part of the config system
func SetFlags(ci *fs.ConfigInfo) {
// Process obsolete --dump-headers and --dump-bodies flags
if dumpHeaders {
ci.Dump |= fs.DumpHeaders
fs.Logf(nil, "--dump-headers is obsolete - please use --dump headers instead")
}
if dumpBodies {
ci.Dump |= fs.DumpBodies
fs.Logf(nil, "--dump-bodies is obsolete - please use --dump bodies instead")
}
// Process -v flag
if verbose >= 2 {
ci.LogLevel = fs.LogLevelDebug
} else if verbose >= 1 {
ci.LogLevel = fs.LogLevelInfo
}
// Process -q flag
if quiet {
if verbose > 0 {
fs.Fatalf(nil, "Can't set -v and -q")
}
ci.LogLevel = fs.LogLevelError
}
// Can't set log level, -v, -q
logLevelFlag := pflag.Lookup("log-level")
if logLevelFlag != nil && logLevelFlag.Changed {
if verbose > 0 {
fs.Fatalf(nil, "Can't set -v and --log-level")
}
if quiet {
fs.Fatalf(nil, "Can't set -q and --log-level")
}
}
// Process --delete-before, --delete-during and --delete-after
switch {
case deleteBefore && (deleteDuring || deleteAfter),
deleteDuring && deleteAfter:
fs.Fatalf(nil, `Only one of --delete-before, --delete-during or --delete-after can be used.`)
case deleteBefore:
ci.DeleteMode = fs.DeleteModeBefore
case deleteDuring:
ci.DeleteMode = fs.DeleteModeDuring
case deleteAfter:
ci.DeleteMode = fs.DeleteModeAfter
default:
ci.DeleteMode = fs.DeleteModeDefault
}
// Process --bind into IP address
if bindAddr != "" {
addrs, err := net.LookupIP(bindAddr)
if err != nil {
fs.Fatalf(nil, "--bind: Failed to parse %q as IP address: %v", bindAddr, err)
}
if len(addrs) != 1 {
fs.Fatalf(nil, "--bind: Expecting 1 IP address for %q but got %d", bindAddr, len(addrs))
}
ci.BindAddr = addrs[0]
}
// Process --disable
if disableFeatures != "" {
if disableFeatures == "help" {
fs.Fatalf(nil, "Possible backend features are: %s\n", strings.Join(new(fs.Features).List(), ", "))
}
ci.DisableFeatures = strings.Split(disableFeatures, ",")
}
// Process --headers-upload, --headers-download, --headers
if len(uploadHeaders) != 0 {
ci.UploadHeaders = ParseHeaders(uploadHeaders)
}
if len(downloadHeaders) != 0 {
ci.DownloadHeaders = ParseHeaders(downloadHeaders)
}
if len(headers) != 0 {
ci.Headers = ParseHeaders(headers)
}
// Process --metadata-set
if len(metadataSet) != 0 {
ci.MetadataSet = make(fs.Metadata, len(metadataSet))
for _, kv := range metadataSet {
equal := strings.IndexRune(kv, '=')
if equal < 0 {
fs.Fatalf(nil, "Failed to parse '%s' as metadata key=value.", kv)
}
ci.MetadataSet[strings.ToLower(kv[:equal])] = kv[equal+1:]
}
fs.Debugf(nil, "MetadataUpload %v", ci.MetadataSet)
}
// Process --dscp
if len(dscp) != 0 {
if value, ok := parseDSCP(dscp); ok {
ci.TrafficClass = value << 2
} else {
fs.Fatalf(nil, "--dscp: Invalid DSCP name: %v", dscp)
}
}
// Process --config path
if err := config.SetConfigPath(configPath); err != nil {
fs.Fatalf(nil, "--config: Failed to set %q as config path: %v", configPath, err)
}
// Process --cache-dir path
if err := config.SetCacheDir(cacheDir); err != nil {
fs.Fatalf(nil, "--cache-dir: Failed to set %q as cache dir: %v", cacheDir, err)
}
// Process --temp-dir path
if err := config.SetTempDir(tempDir); err != nil {
fs.Fatalf(nil, "--temp-dir: Failed to set %q as temp dir: %v", tempDir, err)
}
// Process --multi-thread-streams - set whether multi-thread-streams was set
multiThreadStreamsFlag := pflag.Lookup("multi-thread-streams")
ci.MultiThreadSet = multiThreadStreamsFlag != nil && multiThreadStreamsFlag.Changed
// Reload any changes
if err := ci.Reload(context.Background()); err != nil {
fs.Fatalf(nil, "Failed to reload config changes: %v", err)
}
}
// parseDSCP converts DSCP names to value
func parseDSCP(dscp string) (uint8, bool) {
if s, err := strconv.ParseUint(dscp, 10, 6); err == nil {
return uint8(s), true
}
dscp = strings.ToUpper(dscp)
switch dscp {
case "BE":
fallthrough
case "DF":
fallthrough
case "CS0":
return 0x00, true
case "CS1":
return 0x08, true
case "AF11":
return 0x0A, true
case "AF12":
return 0x0C, true
case "AF13":
return 0x0E, true
case "CS2":
return 0x10, true
case "AF21":
return 0x12, true
case "AF22":
return 0x14, true
case "AF23":
return 0x16, true
case "CS3":
return 0x18, true
case "AF31":
return 0x1A, true
case "AF32":
return 0x1C, true
case "AF33":
return 0x1E, true
case "CS4":
return 0x20, true
case "AF41":
return 0x22, true
case "AF42":
return 0x24, true
case "AF43":
return 0x26, true
case "CS5":
return 0x28, true
case "EF":
return 0x2E, true
case "CS6":
return 0x30, true
case "LE":
return 0x01, true
default:
return 0, false
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/configfile/configfile.go | fs/config/configfile/configfile.go | // Package configfile implements a config file loader and saver
package configfile
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/lib/file"
"github.com/unknwon/goconfig" //nolint:misspell // Don't include misspell when running golangci-lint
)
// Install installs the config file handler
func Install() {
config.SetData(&Storage{})
}
// Storage implements config.Storage for saving and loading config
// data in a simple INI based file.
type Storage struct {
mu sync.Mutex // to protect the following variables
gc *goconfig.ConfigFile // config file loaded - not thread safe
fi os.FileInfo // stat of the file when last loaded
}
// Check to see if we need to reload the config
//
// mu must be held when calling this
func (s *Storage) _check() {
if configPath := config.GetConfigPath(); configPath != "" {
// Check to see if config file has changed since it was last loaded
fi, err := os.Stat(configPath)
if err == nil {
// check to see if config file has changed and if it has, reload it
if s.fi == nil || !fi.ModTime().Equal(s.fi.ModTime()) || fi.Size() != s.fi.Size() {
fs.Debugf(nil, "Config file has changed externally - reloading")
err := s._load()
if err != nil {
fs.Errorf(nil, "Failed to read config file - using previous config: %v", err)
}
}
}
}
}
// _load the config from permanent storage, decrypting if necessary
//
// mu must be held when calling this
func (s *Storage) _load() (err error) {
// Make sure we have a sensible default even when we error
defer func() {
if s.gc == nil {
s.gc, _ = goconfig.LoadFromReader(bytes.NewReader([]byte{}))
}
}()
configPath := config.GetConfigPath()
if configPath == "" {
return config.ErrorConfigFileNotFound
}
fd, err := os.Open(configPath)
if err != nil {
if os.IsNotExist(err) {
return config.ErrorConfigFileNotFound
}
return err
}
defer fs.CheckClose(fd, &err)
// Update s.fi with the current file info
s.fi, _ = os.Stat(configPath)
cryptReader, err := config.Decrypt(fd)
if err != nil {
return err
}
gc, err := goconfig.LoadFromReader(cryptReader)
if err != nil {
return err
}
s.gc = gc
return nil
}
// Load the config from permanent storage, decrypting if necessary
func (s *Storage) Load() (err error) {
s.mu.Lock()
defer s.mu.Unlock()
return s._load()
}
// Save the config to permanent storage, encrypting if necessary
func (s *Storage) Save() error {
s.mu.Lock()
defer s.mu.Unlock()
configPath := config.GetConfigPath()
if configPath == "" {
return fmt.Errorf("failed to save config file, path is empty")
}
configDir, configName := filepath.Split(configPath)
info, err := os.Lstat(configPath)
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("failed to resolve config file path: %w", err)
}
} else {
if info.Mode()&os.ModeSymlink != 0 {
configPath, err = os.Readlink(configPath)
if err != nil {
return fmt.Errorf("failed to resolve config file symbolic link: %w", err)
}
if !filepath.IsAbs(configPath) {
configPath = filepath.Join(configDir, configPath)
}
configDir = filepath.Dir(configPath)
}
}
err = file.MkdirAll(configDir, os.ModePerm)
if err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
f, err := os.CreateTemp(configDir, configName)
if err != nil {
return fmt.Errorf("failed to create temp file for new config: %w", err)
}
defer func() {
_ = f.Close()
if err := os.Remove(f.Name()); err != nil && !os.IsNotExist(err) {
fs.Errorf(nil, "Failed to remove temp file for new config: %v", err)
}
}()
var buf bytes.Buffer
if err := goconfig.SaveConfigData(s.gc, &buf); err != nil {
return fmt.Errorf("failed to save config file: %w", err)
}
if err := config.Encrypt(&buf, f); err != nil {
return err
}
_ = f.Sync()
err = f.Close()
if err != nil {
return fmt.Errorf("failed to close config file: %w", err)
}
var fileMode os.FileMode = 0600
info, err = os.Stat(configPath)
if err != nil {
fs.Debugf(nil, "Using default permissions for config file: %v", fileMode)
} else if info.Mode() != fileMode {
fs.Debugf(nil, "Keeping previous permissions for config file: %v", info.Mode())
fileMode = info.Mode()
}
attemptCopyGroup(configPath, f.Name())
err = os.Chmod(f.Name(), fileMode)
if err != nil {
fs.Errorf(nil, "Failed to set permissions on config file: %v", err)
}
fbackup, err := os.CreateTemp(configDir, configName+".old")
if err != nil {
return fmt.Errorf("failed to create temp file for old config backup: %w", err)
}
err = fbackup.Close()
if err != nil {
return fmt.Errorf("failed to close temp file for old config backup: %w", err)
}
keepBackup := true
defer func() {
if !keepBackup {
if err := os.Remove(fbackup.Name()); err != nil && !os.IsNotExist(err) {
fs.Errorf(nil, "Failed to remove temp file for old config backup: %v", err)
}
}
}()
if err = os.Rename(configPath, fbackup.Name()); err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("failed to move previous config to backup location: %w", err)
}
keepBackup = false // no existing file, no need to keep backup even if writing of new file fails
}
if err = os.Rename(f.Name(), configPath); err != nil {
return fmt.Errorf("failed to move newly written config from %s to final location: %v", f.Name(), err)
}
keepBackup = false // new file was written, no need to keep backup
// Update s.fi with the newly written file
s.fi, _ = os.Stat(configPath)
return nil
}
// Serialize the config into a string
func (s *Storage) Serialize() (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
s._check()
var buf bytes.Buffer
if err := goconfig.SaveConfigData(s.gc, &buf); err != nil {
return "", fmt.Errorf("failed to save config file: %w", err)
}
return buf.String(), nil
}
// HasSection returns true if section exists in the config file
func (s *Storage) HasSection(section string) bool {
s.mu.Lock()
defer s.mu.Unlock()
s._check()
_, err := s.gc.GetSection(section)
return err == nil
}
// DeleteSection removes the named section and all config from the
// config file
func (s *Storage) DeleteSection(section string) {
s.mu.Lock()
defer s.mu.Unlock()
s._check()
s.gc.DeleteSection(section)
}
// GetSectionList returns a slice of strings with names for all the
// sections
func (s *Storage) GetSectionList() []string {
s.mu.Lock()
defer s.mu.Unlock()
s._check()
return s.gc.GetSectionList()
}
// GetKeyList returns the keys in this section
func (s *Storage) GetKeyList(section string) []string {
s.mu.Lock()
defer s.mu.Unlock()
s._check()
return s.gc.GetKeyList(section)
}
// GetValue returns the key in section with a found flag
func (s *Storage) GetValue(section string, key string) (value string, found bool) {
s.mu.Lock()
defer s.mu.Unlock()
s._check()
value, err := s.gc.GetValue(section, key)
if err != nil {
return "", false
}
return value, true
}
// SetValue sets the value under key in section
func (s *Storage) SetValue(section string, key string, value string) {
s.mu.Lock()
defer s.mu.Unlock()
s._check()
if strings.HasPrefix(section, ":") {
fs.Logf(nil, "Can't save config %q for on the fly backend %q", key, section)
return
}
s.gc.SetValue(section, key, value)
}
// DeleteKey removes the key under section
func (s *Storage) DeleteKey(section string, key string) bool {
s.mu.Lock()
defer s.mu.Unlock()
s._check()
return s.gc.DeleteKey(section, key)
}
// Check the interface is satisfied
var _ config.Storage = (*Storage)(nil)
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/configfile/configfile_other.go | fs/config/configfile/configfile_other.go | // Read, write and edit the config file
// Non-unix specific functions.
//go:build !darwin && !dragonfly && !freebsd && !linux && !netbsd && !openbsd && !solaris
package configfile
// attemptCopyGroup tries to keep the group the same, which only makes sense
// for system with user-group-world permission model.
func attemptCopyGroup(fromPath, toPath string) {}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/configfile/configfile_unix.go | fs/config/configfile/configfile_unix.go | // Read, write and edit the config file
// Unix specific functions.
//go:build darwin || dragonfly || freebsd || linux || netbsd || openbsd || solaris
package configfile
import (
"os"
"os/user"
"strconv"
"syscall"
"github.com/rclone/rclone/fs"
)
// attemptCopyGroup tries to keep the group the same. User will be the one
// who is currently running this process.
func attemptCopyGroup(fromPath, toPath string) {
info, err := os.Stat(fromPath)
if err != nil || info.Sys() == nil {
return
}
if stat, ok := info.Sys().(*syscall.Stat_t); ok {
uid := int(stat.Uid)
// prefer self over previous owner of file, because it has a higher chance
// of success
if user, err := user.Current(); err == nil {
if tmpUID, err := strconv.Atoi(user.Uid); err == nil {
uid = tmpUID
}
}
if err = os.Chown(toPath, uid, int(stat.Gid)); err != nil {
fs.Debugf(nil, "Failed to keep previous owner of config file: %v", err)
}
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/configfile/configfile_test.go | fs/config/configfile/configfile_test.go | package configfile
import (
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"testing"
"github.com/rclone/rclone/fs/config"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var configData = `[one]
type = number1
fruit = potato
[two]
type = number2
fruit = apple
topping = nuts
[three]
type = number3
fruit = banana
`
// Fill up a temporary config file with the testdata filename passed in
func setConfigFile(t *testing.T, data string) func() {
out, err := os.CreateTemp("", "rclone-configfile-test")
require.NoError(t, err)
filePath := out.Name()
_, err = out.Write([]byte(data))
require.NoError(t, err)
require.NoError(t, out.Close())
old := config.GetConfigPath()
assert.NoError(t, config.SetConfigPath(filePath))
return func() {
assert.NoError(t, config.SetConfigPath(old))
_ = os.Remove(filePath)
}
}
// toUnix converts \r\n to \n in buf
func toUnix(buf string) string {
if runtime.GOOS == "windows" {
return strings.ReplaceAll(buf, "\r\n", "\n")
}
return buf
}
func TestConfigFile(t *testing.T) {
defer setConfigFile(t, configData)()
data := &Storage{}
require.NoError(t, data.Load())
t.Run("Read", func(t *testing.T) {
t.Run("Serialize", func(t *testing.T) {
buf, err := data.Serialize()
require.NoError(t, err)
assert.Equal(t, configData, toUnix(buf))
})
t.Run("HasSection", func(t *testing.T) {
assert.True(t, data.HasSection("one"))
assert.False(t, data.HasSection("missing"))
})
t.Run("GetSectionList", func(t *testing.T) {
assert.Equal(t, []string{
"one",
"two",
"three",
}, data.GetSectionList())
})
t.Run("GetKeyList", func(t *testing.T) {
assert.Equal(t, []string{
"type",
"fruit",
"topping",
}, data.GetKeyList("two"))
assert.Equal(t, []string(nil), data.GetKeyList("unicorn"))
})
t.Run("GetValue", func(t *testing.T) {
value, ok := data.GetValue("one", "type")
assert.True(t, ok)
assert.Equal(t, "number1", value)
value, ok = data.GetValue("three", "fruit")
assert.True(t, ok)
assert.Equal(t, "banana", value)
value, ok = data.GetValue("one", "typeX")
assert.False(t, ok)
assert.Equal(t, "", value)
value, ok = data.GetValue("threeX", "fruit")
assert.False(t, ok)
assert.Equal(t, "", value)
})
})
//defer setConfigFile(configData)()
t.Run("Write", func(t *testing.T) {
t.Run("SetValue", func(t *testing.T) {
data.SetValue("one", "extra", "42")
data.SetValue("two", "fruit", "acorn")
buf, err := data.Serialize()
require.NoError(t, err)
assert.Equal(t, `[one]
type = number1
fruit = potato
extra = 42
[two]
type = number2
fruit = acorn
topping = nuts
[three]
type = number3
fruit = banana
`, toUnix(buf))
t.Run("DeleteKey", func(t *testing.T) {
data.DeleteKey("one", "type")
data.DeleteKey("two", "missing")
data.DeleteKey("three", "fruit")
buf, err := data.Serialize()
require.NoError(t, err)
assert.Equal(t, `[one]
fruit = potato
extra = 42
[two]
type = number2
fruit = acorn
topping = nuts
[three]
type = number3
`, toUnix(buf))
t.Run("DeleteSection", func(t *testing.T) {
data.DeleteSection("two")
data.DeleteSection("missing")
buf, err := data.Serialize()
require.NoError(t, err)
assert.Equal(t, `[one]
fruit = potato
extra = 42
[three]
type = number3
`, toUnix(buf))
t.Run("Save", func(t *testing.T) {
require.NoError(t, data.Save())
buf, err := os.ReadFile(config.GetConfigPath())
require.NoError(t, err)
assert.Equal(t, `[one]
fruit = potato
extra = 42
[three]
type = number3
`, toUnix(string(buf)))
})
})
})
})
})
}
func TestConfigFileReload(t *testing.T) {
defer setConfigFile(t, configData)()
data := &Storage{}
require.NoError(t, data.Load())
value, ok := data.GetValue("three", "appended")
assert.False(t, ok)
assert.Equal(t, "", value)
// Now write a new value on the end
out, err := os.OpenFile(config.GetConfigPath(), os.O_APPEND|os.O_WRONLY, 0777)
require.NoError(t, err)
_, err = fmt.Fprintln(out, "appended = what magic")
require.NoError(t, err)
require.NoError(t, out.Close())
// And check we magically reloaded it
value, ok = data.GetValue("three", "appended")
assert.True(t, ok)
assert.Equal(t, "what magic", value)
}
func TestConfigFileDoesNotExist(t *testing.T) {
defer setConfigFile(t, configData)()
data := &Storage{}
require.NoError(t, os.Remove(config.GetConfigPath()))
err := data.Load()
require.Equal(t, config.ErrorConfigFileNotFound, err)
// check that using data doesn't crash
value, ok := data.GetValue("three", "appended")
assert.False(t, ok)
assert.Equal(t, "", value)
}
func testConfigFileNoConfig(t *testing.T, configPath string) {
assert.NoError(t, config.SetConfigPath(configPath))
data := &Storage{}
err := data.Load()
require.Equal(t, config.ErrorConfigFileNotFound, err)
data.SetValue("one", "extra", "42")
value, ok := data.GetValue("one", "extra")
assert.True(t, ok)
assert.Equal(t, "42", value)
err = data.Save()
require.Error(t, err)
}
func TestConfigFileNoConfig(t *testing.T) {
old := config.GetConfigPath()
defer func() {
assert.NoError(t, config.SetConfigPath(old))
}()
t.Run("Empty", func(t *testing.T) {
testConfigFileNoConfig(t, "")
})
t.Run("NotFound", func(t *testing.T) {
testConfigFileNoConfig(t, "/notfound")
})
}
func TestConfigFileSave(t *testing.T) {
testDir := t.TempDir()
configPath := filepath.Join(testDir, "a", "b", "c", "configfile")
assert.NoError(t, config.SetConfigPath(configPath))
data := &Storage{}
require.Error(t, data.Load(), config.ErrorConfigFileNotFound)
t.Run("CreatesDirsAndFile", func(t *testing.T) {
err := data.Save()
require.NoError(t, err)
info, err := os.Stat(configPath)
require.NoError(t, err)
assert.False(t, info.IsDir())
})
t.Run("KeepsFileMode", func(t *testing.T) {
if runtime.GOOS != "linux" {
t.Skip("this is a Linux only test")
}
assert.NoError(t, os.Chmod(configPath, 0400)) // -r--------
defer func() {
_ = os.Chmod(configPath, 0644) // -rw-r--r--
}()
err := data.Save()
require.NoError(t, err)
info, err := os.Stat(configPath)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0400), info.Mode().Perm())
})
t.Run("SucceedsEvenIfReadOnlyFile", func(t *testing.T) {
// Save succeeds even if file is read-only since it does not write directly to the file.
assert.NoError(t, os.Chmod(configPath, 0400)) // -r--------
defer func() {
_ = os.Chmod(configPath, 0644) // -rw-r--r--
}()
err := data.Save()
assert.NoError(t, err)
})
t.Run("FailsIfNotAccessToDir", func(t *testing.T) {
// Save fails if no access to the directory.
if runtime.GOOS != "linux" {
// On Windows the os.Chmod only affects the read-only attribute of files)
t.Skip("this is a Linux only test")
}
configDir := filepath.Dir(configPath)
assert.NoError(t, os.Chmod(configDir, 0400)) // -r--------
defer func() {
_ = os.Chmod(configDir, 0755) // -rwxr-xr-x
}()
err := data.Save()
require.Error(t, err)
assert.True(t, strings.HasPrefix(err.Error(), "failed to resolve config file path"))
})
t.Run("FailsIfNotAllowedToCreateNewFiles", func(t *testing.T) {
// Save fails if read-only access to the directory, since it needs to create temporary files in there.
if runtime.GOOS != "linux" {
// On Windows the os.Chmod only affects the read-only attribute of files)
t.Skip("this is a Linux only test")
}
configDir := filepath.Dir(configPath)
assert.NoError(t, os.Chmod(configDir, 0544)) // -r-xr--r--
defer func() {
_ = os.Chmod(configDir, 0755) // -rwxr-xr-x
}()
err := data.Save()
require.Error(t, err)
assert.True(t, strings.HasPrefix(err.Error(), "failed to create temp file for new config"))
})
}
func TestConfigFileSaveSymlinkAbsolute(t *testing.T) {
if runtime.GOOS != "linux" {
// Symlinks may require admin privileges on Windows and os.Symlink will then
// fail with "A required privilege is not held by the client."
t.Skip("this is a Linux only test")
}
testDir := t.TempDir()
linkDir := filepath.Join(testDir, "a")
err := os.Mkdir(linkDir, os.ModePerm)
require.NoError(t, err)
testSymlink := func(t *testing.T, link string, target string, resolvedTarget string) {
err = os.Symlink(target, link)
require.NoError(t, err)
defer func() {
_ = os.Remove(link)
}()
assert.NoError(t, config.SetConfigPath(link))
data := &Storage{}
require.Error(t, data.Load(), config.ErrorConfigFileNotFound)
err = data.Save()
require.NoError(t, err)
info, err := os.Lstat(link)
require.NoError(t, err)
assert.True(t, info.Mode()&os.ModeSymlink != 0)
assert.False(t, info.IsDir())
info, err = os.Lstat(resolvedTarget)
require.NoError(t, err)
assert.False(t, info.IsDir())
}
t.Run("Absolute", func(t *testing.T) {
link := filepath.Join(linkDir, "configfilelink")
target := filepath.Join(testDir, "b", "configfiletarget")
testSymlink(t, link, target, target)
})
t.Run("Relative", func(t *testing.T) {
link := filepath.Join(linkDir, "configfilelink")
target := filepath.Join("b", "c", "configfiletarget")
resolvedTarget := filepath.Join(filepath.Dir(link), target)
testSymlink(t, link, target, resolvedTarget)
})
}
type pipedInput struct {
io.Reader
}
func (p *pipedInput) Read(b []byte) (int, error) {
return p.Reader.Read(b)
}
func (*pipedInput) Seek(int64, int) (int64, error) {
return 0, fmt.Errorf("Seek not supported")
}
func TestPipedConfig(t *testing.T) {
t.Run("DoesNotSupportSeeking", func(t *testing.T) {
r := &pipedInput{strings.NewReader("")}
_, err := r.Seek(0, io.SeekStart)
require.Error(t, err)
})
t.Run("IsSupported", func(t *testing.T) {
r := &pipedInput{strings.NewReader(configData)}
_, err := config.Decrypt(r)
require.NoError(t, err)
})
t.Run("PlainTextConfigIsNotConsumedByCryptCheck", func(t *testing.T) {
in := &pipedInput{strings.NewReader(configData)}
r, _ := config.Decrypt(in)
got, err := io.ReadAll(r)
require.NoError(t, err)
assert.Equal(t, configData, string(got))
})
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/configmap/configmap_test.go | fs/config/configmap/configmap_test.go | package configmap
import (
"encoding/base64"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
_ Mapper = Simple(nil)
_ Getter = Simple(nil)
_ Setter = Simple(nil)
)
func TestConfigMapGet(t *testing.T) {
m := New()
value, found := m.Get("config1")
assert.Equal(t, "", value)
assert.Equal(t, false, found)
value, found = m.Get("config2")
assert.Equal(t, "", value)
assert.Equal(t, false, found)
m1 := Simple{
"config1": "one",
}
m.AddGetter(m1, PriorityNormal)
value, found = m.Get("config1")
assert.Equal(t, "one", value)
assert.Equal(t, true, found)
value, found = m.Get("config2")
assert.Equal(t, "", value)
assert.Equal(t, false, found)
m2 := Simple{
"config1": "one2",
"config2": "two2",
}
m.AddGetter(m2, PriorityNormal)
value, found = m.Get("config1")
assert.Equal(t, "one", value)
assert.Equal(t, true, found)
value, found = m.Get("config2")
assert.Equal(t, "two2", value)
assert.Equal(t, true, found)
}
func TestConfigMapSet(t *testing.T) {
m := New()
m1 := Simple{
"config1": "one",
}
m2 := Simple{
"config1": "one2",
"config2": "two2",
}
m.AddSetter(m1).AddSetter(m2)
m.Set("config2", "potato")
assert.Equal(t, Simple{
"config1": "one",
"config2": "potato",
}, m1)
assert.Equal(t, Simple{
"config1": "one2",
"config2": "potato",
}, m2)
m.Set("config1", "beetroot")
assert.Equal(t, Simple{
"config1": "beetroot",
"config2": "potato",
}, m1)
assert.Equal(t, Simple{
"config1": "beetroot",
"config2": "potato",
}, m2)
m.ClearSetters()
// Check that nothing gets set
m.Set("config1", "BEETROOT")
assert.Equal(t, Simple{
"config1": "beetroot",
"config2": "potato",
}, m1)
assert.Equal(t, Simple{
"config1": "beetroot",
"config2": "potato",
}, m2)
}
func TestConfigMapGetPriority(t *testing.T) {
m := New()
value, found := m.GetPriority("config1", PriorityMax)
assert.Equal(t, "", value)
assert.Equal(t, false, found)
value, found = m.GetPriority("config2", PriorityMax)
assert.Equal(t, "", value)
assert.Equal(t, false, found)
m1 := Simple{
"config1": "one",
"config3": "three",
}
m.AddGetter(m1, PriorityConfig)
value, found = m.GetPriority("config1", PriorityNormal)
assert.Equal(t, "", value)
assert.Equal(t, false, found)
value, found = m.GetPriority("config2", PriorityNormal)
assert.Equal(t, "", value)
assert.Equal(t, false, found)
value, found = m.GetPriority("config3", PriorityNormal)
assert.Equal(t, "", value)
assert.Equal(t, false, found)
value, found = m.GetPriority("config1", PriorityConfig)
assert.Equal(t, "one", value)
assert.Equal(t, true, found)
value, found = m.GetPriority("config2", PriorityConfig)
assert.Equal(t, "", value)
assert.Equal(t, false, found)
value, found = m.GetPriority("config3", PriorityConfig)
assert.Equal(t, "three", value)
assert.Equal(t, true, found)
value, found = m.GetPriority("config1", PriorityMax)
assert.Equal(t, "one", value)
assert.Equal(t, true, found)
value, found = m.GetPriority("config2", PriorityMax)
assert.Equal(t, "", value)
assert.Equal(t, false, found)
value, found = m.GetPriority("config3", PriorityMax)
assert.Equal(t, "three", value)
assert.Equal(t, true, found)
m2 := Simple{
"config1": "one2",
"config2": "two2",
}
m.AddGetter(m2, PriorityNormal)
value, found = m.GetPriority("config1", PriorityNormal)
assert.Equal(t, "one2", value)
assert.Equal(t, true, found)
value, found = m.GetPriority("config2", PriorityNormal)
assert.Equal(t, "two2", value)
assert.Equal(t, true, found)
value, found = m.GetPriority("config3", PriorityNormal)
assert.Equal(t, "", value)
assert.Equal(t, false, found)
value, found = m.GetPriority("config1", PriorityConfig)
assert.Equal(t, "one2", value)
assert.Equal(t, true, found)
value, found = m.GetPriority("config2", PriorityConfig)
assert.Equal(t, "two2", value)
assert.Equal(t, true, found)
value, found = m.GetPriority("config3", PriorityConfig)
assert.Equal(t, "three", value)
assert.Equal(t, true, found)
value, found = m.GetPriority("config1", PriorityMax)
assert.Equal(t, "one2", value)
assert.Equal(t, true, found)
value, found = m.GetPriority("config2", PriorityMax)
assert.Equal(t, "two2", value)
assert.Equal(t, true, found)
value, found = m.GetPriority("config3", PriorityMax)
assert.Equal(t, "three", value)
assert.Equal(t, true, found)
}
func TestConfigMapClearGetters(t *testing.T) {
m := New()
m1 := Simple{}
m2 := Simple{}
m3 := Simple{}
m.AddGetter(m1, PriorityNormal)
m.AddGetter(m2, PriorityDefault)
m.AddGetter(m3, PriorityConfig)
assert.Equal(t, []getprio{
{m1, PriorityNormal},
{m3, PriorityConfig},
{m2, PriorityDefault},
}, m.getters)
m.ClearGetters(PriorityConfig)
assert.Equal(t, []getprio{
{m1, PriorityNormal},
{m2, PriorityDefault},
}, m.getters)
m.ClearGetters(PriorityNormal)
assert.Equal(t, []getprio{
{m2, PriorityDefault},
}, m.getters)
m.ClearGetters(PriorityDefault)
assert.Equal(t, []getprio{}, m.getters)
m.ClearGetters(PriorityDefault)
assert.Equal(t, []getprio{}, m.getters)
}
func TestConfigMapClearSetters(t *testing.T) {
m := New()
m1 := Simple{}
m2 := Simple{}
m3 := Simple{}
m.AddSetter(m1)
m.AddSetter(m2)
m.AddSetter(m3)
assert.Equal(t, []Setter{m1, m2, m3}, m.setters)
m.ClearSetters()
assert.Equal(t, []Setter(nil), m.setters)
}
func TestSimpleEncode(t *testing.T) {
for _, test := range []struct {
in Simple
want string
}{
{
in: Simple{},
want: "",
},
{
in: Simple{
"one": "potato",
},
want: "eyJvbmUiOiJwb3RhdG8ifQ",
},
{
in: Simple{
"one": "potato",
"two": "",
},
want: "eyJvbmUiOiJwb3RhdG8iLCJ0d28iOiIifQ",
},
} {
got, err := test.in.Encode()
require.NoError(t, err)
assert.Equal(t, test.want, got)
gotM := Simple{}
err = gotM.Decode(got)
require.NoError(t, err)
assert.Equal(t, test.in, gotM)
}
}
func TestSimpleDecode(t *testing.T) {
for _, test := range []struct {
in string
want Simple
wantErr string
}{
{
in: "",
want: Simple{},
},
{
in: "eyJvbmUiOiJwb3RhdG8ifQ",
want: Simple{
"one": "potato",
},
},
{
in: " e yJvbm UiOiJwb\r\n 3Rhd\tG8ifQ\n\n ",
want: Simple{
"one": "potato",
},
},
{
in: "eyJvbmUiOiJwb3RhdG8iLCJ0d28iOiIifQ",
want: Simple{
"one": "potato",
"two": "",
},
},
{
in: "!!!!!",
want: Simple{},
wantErr: "decode simple map",
},
{
in: base64.RawStdEncoding.EncodeToString([]byte(`null`)),
want: Simple{},
},
{
in: base64.RawStdEncoding.EncodeToString([]byte(`rubbish`)),
want: Simple{},
wantErr: "parse simple map",
},
} {
got := Simple{}
err := got.Decode(test.in)
assert.Equal(t, test.want, got, test.in)
if test.wantErr == "" {
require.NoError(t, err, test.in)
} else {
assert.Contains(t, err.Error(), test.wantErr, test.in)
}
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/configmap/configmap_external_test.go | fs/config/configmap/configmap_external_test.go | package configmap_test
import (
"fmt"
"testing"
"github.com/rclone/rclone/fs/config/configmap"
"github.com/rclone/rclone/fs/fspath"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSimpleString(t *testing.T) {
for _, tt := range []struct {
name string
want string
in configmap.Simple
}{
{name: "Nil", want: "", in: configmap.Simple(nil)},
{name: "Empty", want: "", in: configmap.Simple{}},
{name: "Basic", want: "config1='one'", in: configmap.Simple{
"config1": "one",
}},
{name: "Truthy", want: "config1='true',config2='true'", in: configmap.Simple{
"config1": "true",
"config2": "true",
}},
{name: "Quotable", want: `config1='"one"',config2=':two:',config3='''three''',config4='=four=',config5=',five,'`, in: configmap.Simple{
"config1": `"one"`,
"config2": `:two:`,
"config3": `'three'`,
"config4": `=four=`,
"config5": `,five,`,
}},
{name: "Order", want: "config1='one',config2='two',config3='three',config4='four',config5='five'", in: configmap.Simple{
"config5": "five",
"config4": "four",
"config3": "three",
"config2": "two",
"config1": "one",
}},
{name: "Escaping", want: "apple='',config1='o''n''e'", in: configmap.Simple{
"config1": "o'n'e",
"apple": "",
}},
} {
t.Run(tt.name, func(t *testing.T) {
// Check forwards
params := tt.in.String()
assert.Equal(t, tt.want, params)
// Check config round trips through config parser
remote := ":local," + params + ":"
if params == "" {
remote = ":local:"
}
what := fmt.Sprintf("remote = %q", remote)
parsed, err := fspath.Parse(remote)
require.NoError(t, err, what)
if len(parsed.Config) != 0 || len(tt.in) != 0 {
assert.Equal(t, tt.in, parsed.Config, what)
}
})
}
}
func TestSimpleHuman(t *testing.T) {
for _, tt := range []struct {
name string
want string
in configmap.Simple
}{
{name: "Nil", want: "", in: configmap.Simple(nil)},
{name: "Empty", want: "", in: configmap.Simple{}},
{name: "Basic", want: "config1=one", in: configmap.Simple{
"config1": "one",
}},
{name: "Truthy", want: "config1,config2", in: configmap.Simple{
"config1": "true",
"config2": "true",
}},
{name: "Quotable", want: `config1='"one"',config2=':two:',config3='''three''',config4='=four=',config5=',five,'`, in: configmap.Simple{
"config1": `"one"`,
"config2": `:two:`,
"config3": `'three'`,
"config4": `=four=`,
"config5": `,five,`,
}},
{name: "Order", want: "config1=one,config2=two,config3=three,config4=four,config5=five", in: configmap.Simple{
"config5": "five",
"config4": "four",
"config3": "three",
"config2": "two",
"config1": "one",
}},
{name: "Escaping", want: "apple=,config1='o''n''e'", in: configmap.Simple{
"config1": "o'n'e",
"apple": "",
}},
} {
t.Run(tt.name, func(t *testing.T) {
// Check forwards
params := tt.in.Human()
assert.Equal(t, tt.want, params)
// Check config round trips through config parser
remote := ":local," + params + ":"
if params == "" {
remote = ":local:"
}
what := fmt.Sprintf("remote = %q", remote)
parsed, err := fspath.Parse(remote)
require.NoError(t, err, what)
if len(parsed.Config) != 0 || len(tt.in) != 0 {
assert.Equal(t, tt.in, parsed.Config, what)
}
})
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/configmap/configmap.go | fs/config/configmap/configmap.go | // Package configmap provides an abstraction for reading and writing config
package configmap
import (
"encoding/base64"
"encoding/json"
"fmt"
"sort"
"strings"
"unicode"
)
// Priority of getters
type Priority int8
// Priority levels for AddGetter
const (
PriorityNormal Priority = iota
PriorityConfig // use for reading from the config
PriorityDefault // use for default values
PriorityMax
)
// Getter provides an interface to get config items
type Getter interface {
// Get should get an item with the key passed in and return
// the value. If the item is found then it should return true,
// otherwise false.
Get(key string) (value string, ok bool)
}
// Setter provides an interface to set config items
type Setter interface {
// Set should set an item into persistent config store.
Set(key, value string)
}
// Mapper provides an interface to read and write config
type Mapper interface {
Getter
Setter
}
// Map provides a wrapper around multiple Setter and
// Getter interfaces.
type Map struct {
setters []Setter
getters []getprio
}
type getprio struct {
getter Getter
priority Priority
}
// New returns an empty Map
func New() *Map {
return &Map{}
}
// AddGetter appends a getter onto the end of the getters in priority order
func (c *Map) AddGetter(getter Getter, priority Priority) *Map {
c.getters = append(c.getters, getprio{getter, priority})
sort.SliceStable(c.getters, func(i, j int) bool {
return c.getters[i].priority < c.getters[j].priority
})
return c
}
// AddSetter appends a setter onto the end of the setters
func (c *Map) AddSetter(setter Setter) *Map {
c.setters = append(c.setters, setter)
return c
}
// ClearSetters removes all the setters set so far
func (c *Map) ClearSetters() *Map {
c.setters = nil
return c
}
// ClearGetters removes all the getters with the priority given
func (c *Map) ClearGetters(priority Priority) *Map {
getters := c.getters[:0]
for _, item := range c.getters {
if item.priority != priority {
getters = append(getters, item)
}
}
c.getters = getters
return c
}
// GetPriority gets an item with the key passed in and return the
// value from the first getter to return a result with priority <=
// maxPriority. If the item is found then it returns true, otherwise
// false.
func (c *Map) GetPriority(key string, maxPriority Priority) (value string, ok bool) {
for _, item := range c.getters {
if item.priority > maxPriority {
break
}
value, ok = item.getter.Get(key)
if ok {
return value, ok
}
}
return "", false
}
// Get gets an item with the key passed in and return the value from
// the first getter. If the item is found then it returns true,
// otherwise false.
func (c *Map) Get(key string) (value string, ok bool) {
return c.GetPriority(key, PriorityMax)
}
// Set sets an item into all the stored setters.
func (c *Map) Set(key, value string) {
for _, do := range c.setters {
do.Set(key, value)
}
}
// Simple is a simple Mapper for testing
type Simple map[string]string
// Get the value
func (c Simple) Get(key string) (value string, ok bool) {
value, ok = c[key]
return value, ok
}
// Set the value
func (c Simple) Set(key, value string) {
c[key] = value
}
// string the map value the same way the config parser does, but with
// sorted keys for reproducibility.
//
// If human is set then use fewer quotes.
func (c Simple) string(human bool) string {
var ks = make([]string, 0, len(c))
for k := range c {
ks = append(ks, k)
}
sort.Strings(ks)
var out strings.Builder
for _, k := range ks {
if out.Len() > 0 {
out.WriteRune(',')
}
out.WriteString(k)
v := c[k]
if human && v == "true" {
continue
}
out.WriteRune('=')
if !human || strings.ContainsAny(v, `'":=,`) {
out.WriteRune('\'')
for _, ch := range v {
out.WriteRune(ch)
// Escape ' as ''
if ch == '\'' {
out.WriteRune(ch)
}
}
out.WriteRune('\'')
} else {
out.WriteString(v)
}
}
return out.String()
}
// Human converts the map value the same way the config parser does,
// but with sorted keys for reproducibility. This does it in human
// readable form with fewer quotes.
func (c Simple) Human() string {
return c.string(true)
}
// String the map value the same way the config parser does, but with
// sorted keys for reproducibility.
func (c Simple) String() string {
return c.string(false)
}
// Encode from c into a string suitable for putting on the command line
func (c Simple) Encode() (string, error) {
if len(c) == 0 {
return "", nil
}
buf, err := json.Marshal(c)
if err != nil {
return "", fmt.Errorf("encode simple map: %w", err)
}
return base64.RawStdEncoding.EncodeToString(buf), nil
}
// Decode an Encode~d string in into c
func (c Simple) Decode(in string) error {
// Remove all whitespace from the input string
in = strings.Map(func(r rune) rune {
if unicode.IsSpace(r) {
return -1
}
return r
}, in)
if len(in) == 0 {
return nil
}
decodedM, err := base64.RawStdEncoding.DecodeString(in)
if err != nil {
return fmt.Errorf("decode simple map: %w", err)
}
err = json.Unmarshal(decodedM, &c)
if err != nil {
return fmt.Errorf("parse simple map: %w", err)
}
return nil
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/obscure/obscure_test.go | fs/config/obscure/obscure_test.go | package obscure
import (
"bytes"
"crypto/rand"
"testing"
"github.com/stretchr/testify/assert"
)
func TestObscure(t *testing.T) {
for _, test := range []struct {
in string
want string
iv string
}{
{"", "YWFhYWFhYWFhYWFhYWFhYQ", "aaaaaaaaaaaaaaaa"},
{"potato", "YWFhYWFhYWFhYWFhYWFhYXMaGgIlEQ", "aaaaaaaaaaaaaaaa"},
{"potato", "YmJiYmJiYmJiYmJiYmJiYp3gcEWbAw", "bbbbbbbbbbbbbbbb"},
} {
cryptRand = bytes.NewBufferString(test.iv)
got, err := Obscure(test.in)
cryptRand = rand.Reader
assert.NoError(t, err)
assert.Equal(t, test.want, got)
recoveredIn, err := Reveal(got)
assert.NoError(t, err)
assert.Equal(t, test.in, recoveredIn, "not bidirectional")
// Now the Must variants
cryptRand = bytes.NewBufferString(test.iv)
got = MustObscure(test.in)
cryptRand = rand.Reader
assert.Equal(t, test.want, got)
recoveredIn = MustReveal(got)
assert.Equal(t, test.in, recoveredIn, "not bidirectional")
}
}
func TestReveal(t *testing.T) {
for _, test := range []struct {
in string
want string
iv string
}{
{"YWFhYWFhYWFhYWFhYWFhYQ", "", "aaaaaaaaaaaaaaaa"},
{"YWFhYWFhYWFhYWFhYWFhYXMaGgIlEQ", "potato", "aaaaaaaaaaaaaaaa"},
{"YmJiYmJiYmJiYmJiYmJiYp3gcEWbAw", "potato", "bbbbbbbbbbbbbbbb"},
} {
cryptRand = bytes.NewBufferString(test.iv)
got, err := Reveal(test.in)
assert.NoError(t, err)
assert.Equal(t, test.want, got)
// Now the Must variants
cryptRand = bytes.NewBufferString(test.iv)
got = MustReveal(test.in)
assert.Equal(t, test.want, got)
}
}
// Test some error cases
func TestRevealErrors(t *testing.T) {
for _, test := range []struct {
in string
wantErr string
}{
{"YmJiYmJiYmJiYmJiYmJiYp*gcEWbAw", "base64 decode failed when revealing password - is it obscured?: illegal base64 data at input byte 22"},
{"aGVsbG8", "input too short when revealing password - is it obscured?"},
{"", "input too short when revealing password - is it obscured?"},
} {
gotString, gotErr := Reveal(test.in)
assert.Equal(t, "", gotString)
assert.Equal(t, test.wantErr, gotErr.Error())
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/config/obscure/obscure.go | fs/config/obscure/obscure.go | // Package obscure contains the Obscure and Reveal commands
package obscure
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"errors"
"fmt"
"io"
"math"
"github.com/rclone/rclone/fs"
)
// crypt internals
var (
cryptKey = []byte{
0x9c, 0x93, 0x5b, 0x48, 0x73, 0x0a, 0x55, 0x4d,
0x6b, 0xfd, 0x7c, 0x63, 0xc8, 0x86, 0xa9, 0x2b,
0xd3, 0x90, 0x19, 0x8e, 0xb8, 0x12, 0x8a, 0xfb,
0xf4, 0xde, 0x16, 0x2b, 0x8b, 0x95, 0xf6, 0x38,
}
cryptBlock cipher.Block
cryptRand = rand.Reader
)
// crypt transforms in to out using iv under AES-CTR.
//
// in and out may be the same buffer.
//
// Note encryption and decryption are the same operation
func crypt(out, in, iv []byte) error {
if cryptBlock == nil {
var err error
cryptBlock, err = aes.NewCipher(cryptKey)
if err != nil {
return err
}
}
stream := cipher.NewCTR(cryptBlock, iv)
stream.XORKeyStream(out, in)
return nil
}
// Obscure a value
//
// This is done by encrypting with AES-CTR
func Obscure(x string) (string, error) {
plaintext := []byte(x)
if math.MaxInt32-aes.BlockSize < len(plaintext) {
return "", fmt.Errorf("value too large")
}
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(cryptRand, iv); err != nil {
return "", fmt.Errorf("failed to read iv: %w", err)
}
if err := crypt(ciphertext[aes.BlockSize:], plaintext, iv); err != nil {
return "", fmt.Errorf("encrypt failed: %w", err)
}
return base64.RawURLEncoding.EncodeToString(ciphertext), nil
}
// MustObscure obscures a value, exiting with a fatal error if it failed
func MustObscure(x string) string {
out, err := Obscure(x)
if err != nil {
fs.Fatalf(nil, "Obscure failed: %v", err)
}
return out
}
// Reveal an obscured value
func Reveal(x string) (string, error) {
ciphertext, err := base64.RawURLEncoding.DecodeString(x)
if err != nil {
return "", fmt.Errorf("base64 decode failed when revealing password - is it obscured?: %w", err)
}
if len(ciphertext) < aes.BlockSize {
return "", errors.New("input too short when revealing password - is it obscured?")
}
buf := ciphertext[aes.BlockSize:]
iv := ciphertext[:aes.BlockSize]
if err := crypt(buf, buf, iv); err != nil {
return "", fmt.Errorf("decrypt failed when revealing password - is it obscured?: %w", err)
}
return string(buf), nil
}
// MustReveal reveals an obscured value, exiting with a fatal error if it failed
func MustReveal(x string) string {
out, err := Reveal(x)
if err != nil {
fs.Fatalf(nil, "Reveal failed: %v", err)
}
return out
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/systemd.go | fs/log/systemd.go | // Systemd interface for non-Unix variants only
//go:build !unix
package log
import (
"runtime"
"github.com/rclone/rclone/fs"
)
// Enables systemd logs if configured or if auto-detected
func startSystemdLog(handler *OutputHandler) bool {
fs.Fatalf(nil, "--log-systemd not supported on %s platform", runtime.GOOS)
return false
}
func isJournalStream() bool {
return false
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/syslog.go | fs/log/syslog.go | // Syslog interface for non-Unix variants only
//go:build windows || nacl || plan9
package log
import (
"runtime"
"github.com/rclone/rclone/fs"
)
// Starts syslog if configured, returns true if it was started
func startSysLog(handler *OutputHandler) bool {
fs.Fatalf(nil, "--syslog not supported on %s platform", runtime.GOOS)
return false
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/log.go | fs/log/log.go | // Package log provides logging for rclone
package log
import (
"context"
"fmt"
"io"
"os"
"reflect"
"runtime"
"strings"
"time"
"github.com/rclone/rclone/fs"
"gopkg.in/natefinch/lumberjack.v2"
)
// OptionsInfo descripts the Options in use
var OptionsInfo = fs.Options{{
Name: "log_file",
Default: "",
Help: "Log everything to this file",
Groups: "Logging",
}, {
Name: "log_file_max_size",
Default: fs.SizeSuffix(-1),
Help: `Maximum size of the log file before it's rotated (eg "10M")`,
Groups: "Logging",
}, {
Name: "log_file_max_backups",
Default: 0,
Help: "Maximum number of old log files to retain.",
Groups: "Logging",
}, {
Name: "log_file_max_age",
Default: fs.Duration(0),
Help: `Maximum duration to retain old log files (eg "7d")`,
Groups: "Logging",
}, {
Name: "log_file_compress",
Default: false,
Help: "If set, compress rotated log files using gzip.",
Groups: "Logging",
}, {
Name: "log_format",
Default: logFormatDate | logFormatTime,
Help: "Comma separated list of log format options",
Groups: "Logging",
}, {
Name: "syslog",
Default: false,
Help: "Use Syslog for logging",
Groups: "Logging",
}, {
Name: "syslog_facility",
Default: "DAEMON",
Help: "Facility for syslog, e.g. KERN,USER",
Groups: "Logging",
}, {
Name: "log_systemd",
Default: false,
Help: "Activate systemd integration for the logger",
Groups: "Logging",
}, {
Name: "windows_event_log_level",
Default: fs.LogLevelOff,
Help: "Windows Event Log level DEBUG|INFO|NOTICE|ERROR|OFF",
Groups: "Logging",
Hide: func() fs.OptionVisibility {
if runtime.GOOS == "windows" {
return 0
}
return fs.OptionHideBoth
}(),
}}
// Options contains options for controlling the logging
type Options struct {
File string `config:"log_file"` // Log everything to this file
MaxSize fs.SizeSuffix `config:"log_file_max_size"` // Max size of log file
MaxBackups int `config:"log_file_max_backups"` // Max backups of log file
MaxAge fs.Duration `config:"log_file_max_age"` // Max age of of log file
Compress bool `config:"log_file_compress"` // Set to compress log file
Format logFormat `config:"log_format"` // Comma separated list of log format options
UseSyslog bool `config:"syslog"` // Use Syslog for logging
SyslogFacility string `config:"syslog_facility"` // Facility for syslog, e.g. KERN,USER,...
LogSystemdSupport bool `config:"log_systemd"` // set if using systemd logging
WindowsEventLogLevel fs.LogLevel `config:"windows_event_log_level"`
}
func init() {
fs.RegisterGlobalOptions(fs.OptionsInfo{Name: "log", Opt: &Opt, Options: OptionsInfo})
}
// Opt is the options for the logger
var Opt Options
// enum for the log format
type logFormat = fs.Bits[logFormatChoices]
const (
logFormatDate logFormat = 1 << iota
logFormatTime
logFormatMicroseconds
logFormatUTC
logFormatLongFile
logFormatShortFile
logFormatPid
logFormatNoLevel
logFormatJSON
)
type logFormatChoices struct{}
func (logFormatChoices) Choices() []fs.BitsChoicesInfo {
return []fs.BitsChoicesInfo{
{Bit: uint64(logFormatDate), Name: "date"},
{Bit: uint64(logFormatTime), Name: "time"},
{Bit: uint64(logFormatMicroseconds), Name: "microseconds"},
{Bit: uint64(logFormatUTC), Name: "UTC"},
{Bit: uint64(logFormatLongFile), Name: "longfile"},
{Bit: uint64(logFormatShortFile), Name: "shortfile"},
{Bit: uint64(logFormatPid), Name: "pid"},
{Bit: uint64(logFormatNoLevel), Name: "nolevel"},
{Bit: uint64(logFormatJSON), Name: "json"},
}
}
// fnName returns the name of the calling +2 function
func fnName() string {
pc, _, _, ok := runtime.Caller(2)
name := "*Unknown*"
if ok {
name = runtime.FuncForPC(pc).Name()
dot := strings.LastIndex(name, ".")
if dot >= 0 {
name = name[dot+1:]
}
}
return name
}
// Trace debugs the entry and exit of the calling function
//
// It is designed to be used in a defer statement, so it returns a
// function that logs the exit parameters.
//
// Any pointers in the exit function will be dereferenced
func Trace(o any, format string, a ...any) func(string, ...any) {
if fs.GetConfig(context.Background()).LogLevel < fs.LogLevelDebug {
return func(format string, a ...any) {}
}
name := fnName()
fs.LogPrintf(fs.LogLevelDebug, o, name+": "+format, a...)
return func(format string, a ...any) {
for i := range a {
// read the values of the pointed to items
typ := reflect.TypeOf(a[i])
if typ.Kind() == reflect.Ptr {
value := reflect.ValueOf(a[i])
if value.IsNil() {
a[i] = nil
} else {
pointedToValue := reflect.Indirect(value)
a[i] = pointedToValue.Interface()
}
}
}
fs.LogPrintf(fs.LogLevelDebug, o, ">"+name+": "+format, a...)
}
}
// Stack logs a stack trace of callers with the o and info passed in
func Stack(o any, info string) {
if fs.GetConfig(context.Background()).LogLevel < fs.LogLevelDebug {
return
}
arr := [16 * 1024]byte{}
buf := arr[:]
n := runtime.Stack(buf, false)
buf = buf[:n]
fs.LogPrintf(fs.LogLevelDebug, o, "%s\nStack trace:\n%s", info, buf)
}
// This is called from fs when the config is reloaded
//
// The config should really be here but we can't move it as it is
// externally visible in the rc.
func logReload(ci *fs.ConfigInfo) error {
Handler.SetLevel(fs.LogLevelToSlog(ci.LogLevel))
if Opt.WindowsEventLogLevel != fs.LogLevelOff && Opt.WindowsEventLogLevel > ci.LogLevel {
return fmt.Errorf("--windows-event-log-level %q must be >= --log-level %q", Opt.WindowsEventLogLevel, ci.LogLevel)
}
return nil
}
func init() {
fs.LogReload = logReload
}
// InitLogging start the logging as per the command line flags
func InitLogging() {
// Note that ci only has the defaults in at this point
// We set real values in logReload
ci := fs.GetConfig(context.Background())
// Log file output
if Opt.File != "" {
var w io.Writer
if Opt.MaxSize < 0 {
// No log rotation - just open the file as normal
// We'll capture tracebacks like this too.
f, err := os.OpenFile(Opt.File, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0640)
if err != nil {
fs.Fatalf(nil, "Failed to open log file: %v", err)
}
redirectStderr(f)
w = f
} else {
// Round with a minimum of 1 if set
round := func(x float64) int {
if x <= 0 {
return 0
} else if x <= 1 {
return 1
}
return int(x + 0.5)
}
// Log rotation active
f := &lumberjack.Logger{
Filename: Opt.File,
MaxSize: round(float64(Opt.MaxSize) / float64(fs.Mebi)), // MiB
MaxBackups: Opt.MaxBackups,
MaxAge: round(time.Duration(Opt.MaxAge).Hours() / 24), // Days
Compress: Opt.Compress,
LocalTime: true, // format log file names in localtime
}
w = f
}
Handler.setWriter(w)
}
// --use-json-log implies JSON formatting
if ci.UseJSONLog {
Opt.Format |= logFormatJSON
}
// Set slog level to initial log level
Handler.SetLevel(fs.LogLevelToSlog(fs.InitialLogLevel()))
// Set the format to the configured format
Handler.setFormat(Opt.Format)
// Syslog output
if Opt.UseSyslog {
if Opt.File != "" {
fs.Fatalf(nil, "Can't use --syslog and --log-file together")
}
startSysLog(Handler)
}
// Activate systemd logger support if systemd invocation ID is
// detected and output is going to stderr (not logging to a file or syslog)
if !Redirected() {
if isJournalStream() {
Opt.LogSystemdSupport = true
}
}
// Systemd logging output
if Opt.LogSystemdSupport {
startSystemdLog(Handler)
}
// Windows event logging
if Opt.WindowsEventLogLevel != fs.LogLevelOff {
err := startWindowsEventLog(Handler)
if err != nil {
fs.Fatalf(nil, "Failed to start windows event log: %v", err)
}
}
}
// Redirected returns true if the log has been redirected from stdout
func Redirected() bool {
return Opt.UseSyslog || Opt.File != ""
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/syslog_unix.go | fs/log/syslog_unix.go | // Syslog interface for Unix variants only
//go:build !windows && !nacl && !plan9
package log
import (
"log/slog"
"log/syslog"
"os"
"path"
"github.com/rclone/rclone/fs"
)
var (
syslogFacilityMap = map[string]syslog.Priority{
"KERN": syslog.LOG_KERN,
"USER": syslog.LOG_USER,
"MAIL": syslog.LOG_MAIL,
"DAEMON": syslog.LOG_DAEMON,
"AUTH": syslog.LOG_AUTH,
"SYSLOG": syslog.LOG_SYSLOG,
"LPR": syslog.LOG_LPR,
"NEWS": syslog.LOG_NEWS,
"UUCP": syslog.LOG_UUCP,
"CRON": syslog.LOG_CRON,
"AUTHPRIV": syslog.LOG_AUTHPRIV,
"FTP": syslog.LOG_FTP,
"LOCAL0": syslog.LOG_LOCAL0,
"LOCAL1": syslog.LOG_LOCAL1,
"LOCAL2": syslog.LOG_LOCAL2,
"LOCAL3": syslog.LOG_LOCAL3,
"LOCAL4": syslog.LOG_LOCAL4,
"LOCAL5": syslog.LOG_LOCAL5,
"LOCAL6": syslog.LOG_LOCAL6,
"LOCAL7": syslog.LOG_LOCAL7,
}
)
// Starts syslog
func startSysLog(handler *OutputHandler) bool {
facility, ok := syslogFacilityMap[Opt.SyslogFacility]
if !ok {
fs.Fatalf(nil, "Unknown syslog facility %q - man syslog for list", Opt.SyslogFacility)
}
Me := path.Base(os.Args[0])
w, err := syslog.New(syslog.LOG_NOTICE|facility, Me)
if err != nil {
fs.Fatalf(nil, "Failed to start syslog: %v", err)
}
handler.clearFormatFlags(logFormatDate | logFormatTime | logFormatMicroseconds | logFormatUTC | logFormatLongFile | logFormatShortFile | logFormatPid)
handler.setFormatFlags(logFormatNoLevel)
handler.SetOutput(func(level slog.Level, text string) {
switch level {
case fs.SlogLevelEmergency:
_ = w.Emerg(text)
case fs.SlogLevelAlert:
_ = w.Alert(text)
case fs.SlogLevelCritical:
_ = w.Crit(text)
case slog.LevelError:
_ = w.Err(text)
case slog.LevelWarn:
_ = w.Warning(text)
case fs.SlogLevelNotice:
_ = w.Notice(text)
case slog.LevelInfo:
_ = w.Info(text)
case slog.LevelDebug:
_ = w.Debug(text)
}
})
return true
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/event_log_windows.go | fs/log/event_log_windows.go | // Windows event logging
//go:build windows
package log
import (
"fmt"
"log/slog"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/atexit"
"golang.org/x/sys/windows"
"golang.org/x/sys/windows/svc/eventlog"
)
const (
errorID = uint32(windows.ERROR_INTERNAL_ERROR)
infoID = uint32(windows.ERROR_SUCCESS)
sourceName = "rclone"
)
var (
windowsEventLog *eventlog.Log
)
func startWindowsEventLog(handler *OutputHandler) error {
// Don't install Windows event log if it is disabled.
if Opt.WindowsEventLogLevel == fs.LogLevelOff {
return nil
}
// Install the event source - we don't care if this fails as Windows has sensible fallbacks.
_ = eventlog.InstallAsEventCreate(sourceName, eventlog.Info|eventlog.Warning|eventlog.Error)
// Open the event log
// If sourceName didn't get registered then Windows will use "Application" instead which is fine.
// Though in my tests it seemsed to use sourceName regardless.
elog, err := eventlog.Open(sourceName)
if err != nil {
return fmt.Errorf("open event log: %w", err)
}
// Set the global for the handler
windowsEventLog = elog
// Close it on exit
atexit.Register(func() {
err := elog.Close()
if err != nil {
fs.Errorf(nil, "Failed to close Windows event log: %v", err)
}
})
// Add additional JSON logging to the eventLog handler.
handler.AddOutput(true, eventLog)
fs.Infof(nil, "Logging to Windows event log at level %v", Opt.WindowsEventLogLevel)
return nil
}
// We use levels ERROR, NOTICE, INFO, DEBUG
// Need to map to ERROR, WARNING, INFO
func eventLog(level slog.Level, text string) {
// Check to see if this level is required
if level < fs.LogLevelToSlog(Opt.WindowsEventLogLevel) {
return
}
// Now log to windows eventLog
switch level {
case fs.SlogLevelEmergency, fs.SlogLevelAlert, fs.SlogLevelCritical, slog.LevelError:
_ = windowsEventLog.Error(errorID, text)
case slog.LevelWarn:
_ = windowsEventLog.Warning(infoID, text)
case fs.SlogLevelNotice, slog.LevelInfo, slog.LevelDebug:
_ = windowsEventLog.Info(infoID, text)
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/slog_test.go | fs/log/slog_test.go | package log
import (
"bytes"
"context"
"fmt"
"os"
"regexp"
"strings"
"testing"
"time"
"log/slog"
"github.com/rclone/rclone/fs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var (
utcPlusOne = time.FixedZone("UTC+1", 1*60*60)
t0 = time.Date(2020, 1, 2, 3, 4, 5, 123456000, utcPlusOne)
)
// Test slogLevelToString covers all mapped levels and an unknown level.
func TestSlogLevelToString(t *testing.T) {
tests := []struct {
level slog.Level
want string
}{
{slog.LevelDebug, "DEBUG"},
{slog.LevelInfo, "INFO"},
{fs.SlogLevelNotice, "NOTICE"},
{slog.LevelWarn, "WARNING"},
{slog.LevelError, "ERROR"},
{fs.SlogLevelCritical, "CRITICAL"},
{fs.SlogLevelAlert, "ALERT"},
{fs.SlogLevelEmergency, "EMERGENCY"},
// Unknown level should fall back to .String()
{slog.Level(1234), slog.Level(1234).String()},
}
for _, tc := range tests {
got := slogLevelToString(tc.level)
assert.Equal(t, tc.want, got)
}
}
// Test mapLogLevelNames replaces only the LevelKey attr and lowercases it.
func TestMapLogLevelNames(t *testing.T) {
a := slog.Any(slog.LevelKey, slog.LevelWarn)
mapped := mapLogLevelNames(nil, a)
val, ok := mapped.Value.Any().(string)
if !ok || val != "warning" {
t.Errorf("mapLogLevelNames did not lowercase level: got %v", mapped.Value.Any())
}
// non-level attr should remain unchanged
other := slog.String("foo", "bar")
out := mapLogLevelNames(nil, other)
assert.Equal(t, out.Value, other.Value, "mapLogLevelNames changed a non-level attr")
}
// Test getCaller returns a file:line string of the correct form.
func TestGetCaller(t *testing.T) {
out := getCaller(0)
assert.NotEqual(t, "", out)
match := regexp.MustCompile(`^([^:]+):(\d+)$`).FindStringSubmatch(out)
assert.NotNil(t, match)
// Can't test this as it skips the /log/ directory!
// assert.Equal(t, "slog_test.go", match[1])
}
// Test formatStdLogHeader for various flag combinations.
func TestFormatStdLogHeader(t *testing.T) {
cases := []struct {
name string
format logFormat
lineInfo string
object string
wantPrefix string
}{
{"dateTime", logFormatDate | logFormatTime, "", "", "2020/01/02 03:04:05 "},
{"time", logFormatTime, "", "", "03:04:05 "},
{"date", logFormatDate, "", "", "2020/01/02 "},
{"dateTimeUTC", logFormatDate | logFormatTime | logFormatUTC, "", "", "2020/01/02 02:04:05 "},
{"dateTimeMicro", logFormatDate | logFormatTime | logFormatMicroseconds, "", "", "2020/01/02 03:04:05.123456 "},
{"micro", logFormatMicroseconds, "", "", "03:04:05.123456 "},
{"shortFile", logFormatShortFile, "foo.go:10", "03:04:05 ", "foo.go:10: "},
{"longFile", logFormatLongFile, "foo.go:10", "03:04:05 ", "foo.go:10: "},
{"timePID", logFormatPid, "", "", fmt.Sprintf("[%d] ", os.Getpid())},
{"levelObject", 0, "", "myobj", "INFO : myobj: "},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
h := &OutputHandler{format: tc.format}
buf := &bytes.Buffer{}
h.formatStdLogHeader(buf, slog.LevelInfo, t0, tc.object, tc.lineInfo)
if !strings.HasPrefix(buf.String(), tc.wantPrefix) {
t.Errorf("%s: got %q; want prefix %q", tc.name, buf.String(), tc.wantPrefix)
}
})
}
}
// Test Enabled honors the HandlerOptions.Level.
func TestEnabled(t *testing.T) {
h := NewOutputHandler(&bytes.Buffer{}, nil, 0)
assert.True(t, h.Enabled(context.Background(), slog.LevelInfo))
assert.False(t, h.Enabled(context.Background(), slog.LevelDebug))
opts := &slog.HandlerOptions{Level: slog.LevelDebug}
h2 := NewOutputHandler(&bytes.Buffer{}, opts, 0)
assert.True(t, h2.Enabled(context.Background(), slog.LevelDebug))
}
// Test clearFormatFlags and setFormatFlags bitwise ops.
func TestClearSetFormatFlags(t *testing.T) {
h := &OutputHandler{format: logFormatDate | logFormatTime}
h.clearFormatFlags(logFormatTime)
assert.True(t, h.format&logFormatTime == 0)
h.setFormatFlags(logFormatMicroseconds)
assert.True(t, h.format&logFormatMicroseconds != 0)
}
// Test SetOutput and ResetOutput override the default writer.
func TestSetResetOutput(t *testing.T) {
buf := &bytes.Buffer{}
h := NewOutputHandler(buf, nil, 0)
var gotOverride string
out := func(_ slog.Level, txt string) {
gotOverride = txt
}
h.SetOutput(out)
r := slog.NewRecord(t0, slog.LevelInfo, "hello", 0)
require.NoError(t, h.Handle(context.Background(), r))
assert.NotEqual(t, "", gotOverride)
require.Equal(t, "", buf.String())
h.ResetOutput()
require.NoError(t, h.Handle(context.Background(), r))
require.NotEqual(t, "", buf.String())
}
// Test AddOutput sends to extra destinations.
func TestAddOutput(t *testing.T) {
buf := &bytes.Buffer{}
h := NewOutputHandler(buf, nil, logFormatDate|logFormatTime)
var extraText string
out := func(_ slog.Level, txt string) {
extraText = txt
}
h.AddOutput(false, out)
r := slog.NewRecord(t0, slog.LevelInfo, "world", 0)
require.NoError(t, h.Handle(context.Background(), r))
assert.Equal(t, "2020/01/02 03:04:05 INFO : world\n", buf.String())
assert.Equal(t, "2020/01/02 03:04:05 INFO : world\n", extraText)
}
// Test AddOutputJSON sends JSON to extra destinations.
func TestAddOutputJSON(t *testing.T) {
buf := &bytes.Buffer{}
h := NewOutputHandler(buf, nil, logFormatDate|logFormatTime)
var extraText string
out := func(_ slog.Level, txt string) {
extraText = txt
}
h.AddOutput(true, out)
r := slog.NewRecord(t0, slog.LevelInfo, "world", 0)
require.NoError(t, h.Handle(context.Background(), r))
assert.NotEqual(t, "", extraText)
assert.Equal(t, "2020/01/02 03:04:05 INFO : world\n", buf.String())
assert.True(t, strings.HasPrefix(extraText, `{"time":"2020-01-02T03:04:05.123456+01:00","level":"info","msg":"world","source":"`))
assert.True(t, strings.HasSuffix(extraText, "\"}\n"))
}
// Test AddOutputUseJSONLog sends text to extra destinations.
func TestAddOutputUseJSONLog(t *testing.T) {
buf := &bytes.Buffer{}
h := NewOutputHandler(buf, nil, logFormatDate|logFormatTime|logFormatJSON)
var extraText string
out := func(_ slog.Level, txt string) {
extraText = txt
}
h.AddOutput(false, out)
r := slog.NewRecord(t0, slog.LevelInfo, "world", 0)
require.NoError(t, h.Handle(context.Background(), r))
assert.NotEqual(t, "", extraText)
assert.True(t, strings.HasPrefix(buf.String(), `{"time":"2020-01-02T03:04:05.123456+01:00","level":"info","msg":"world","source":"`))
assert.True(t, strings.HasSuffix(buf.String(), "\"}\n"))
assert.Equal(t, "2020/01/02 03:04:05 INFO : world\n", extraText)
}
// Test JSON log includes PID when logFormatPid is set.
func TestJSONLogWithPid(t *testing.T) {
buf := &bytes.Buffer{}
h := NewOutputHandler(buf, nil, logFormatJSON|logFormatPid)
r := slog.NewRecord(t0, slog.LevelInfo, "hello", 0)
require.NoError(t, h.Handle(context.Background(), r))
output := buf.String()
assert.Contains(t, output, fmt.Sprintf(`"pid":%d`, os.Getpid()))
}
// Test WithAttrs and WithGroup return new handlers with same settings.
func TestWithAttrsAndGroup(t *testing.T) {
buf := &bytes.Buffer{}
h := NewOutputHandler(buf, nil, logFormatDate)
h2 := h.WithAttrs([]slog.Attr{slog.String("k", "v")})
if _, ok := h2.(*OutputHandler); !ok {
t.Error("WithAttrs returned wrong type")
}
h3 := h.WithGroup("grp")
if _, ok := h3.(*OutputHandler); !ok {
t.Error("WithGroup returned wrong type")
}
}
// Test textLog and jsonLog directly for basic correctness.
func TestTextLogAndJsonLog(t *testing.T) {
h := NewOutputHandler(&bytes.Buffer{}, nil, logFormatDate|logFormatTime)
r := slog.NewRecord(t0, slog.LevelWarn, "msg!", 0)
r.AddAttrs(slog.String("object", "obj"))
// textLog
bufText := &bytes.Buffer{}
require.NoError(t, h.textLog(context.Background(), bufText, r))
out := bufText.String()
if !strings.Contains(out, "WARNING") || !strings.Contains(out, "obj:") || !strings.HasSuffix(out, "\n") {
t.Errorf("textLog output = %q", out)
}
// jsonLog
bufJSON := &bytes.Buffer{}
require.NoError(t, h.jsonLog(context.Background(), bufJSON, r))
j := bufJSON.String()
if !strings.Contains(j, `"level":"warning"`) || !strings.Contains(j, `"msg":"msg!"`) {
t.Errorf("jsonLog output = %q", j)
}
}
// Table-driven test for JSON vs text Handle behavior.
func TestHandleFormatFlags(t *testing.T) {
r := slog.NewRecord(t0, slog.LevelInfo, "hi", 0)
cases := []struct {
name string
format logFormat
wantJSON bool
}{
{"textMode", 0, false},
{"jsonMode", logFormatJSON, true},
}
for _, tc := range cases {
buf := &bytes.Buffer{}
h := NewOutputHandler(buf, nil, tc.format)
require.NoError(t, h.Handle(context.Background(), r))
out := buf.String()
if tc.wantJSON {
if !strings.HasPrefix(out, "{") || !strings.Contains(out, `"level":"info"`) {
t.Errorf("%s: got %q; want JSON", tc.name, out)
}
} else {
if !strings.Contains(out, "INFO") {
t.Errorf("%s: got %q; want text INFO", tc.name, out)
}
}
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/systemd_unix.go | fs/log/systemd_unix.go | // Systemd interface for Unix variants only
//go:build unix
package log
import (
"log/slog"
"github.com/coreos/go-systemd/v22/journal"
"github.com/rclone/rclone/fs"
)
// Enables systemd logs if configured or if auto-detected
func startSystemdLog(handler *OutputHandler) bool {
handler.clearFormatFlags(logFormatDate | logFormatTime | logFormatMicroseconds | logFormatUTC | logFormatLongFile | logFormatShortFile | logFormatPid)
handler.setFormatFlags(logFormatNoLevel)
handler.SetOutput(func(level slog.Level, text string) {
_ = journal.Print(slogLevelToSystemdPriority(level), "%-6s: %s\n", level, text)
})
return true
}
var slogLevelToSystemdPrefix = map[slog.Level]journal.Priority{
fs.SlogLevelEmergency: journal.PriEmerg,
fs.SlogLevelAlert: journal.PriAlert,
fs.SlogLevelCritical: journal.PriCrit,
slog.LevelError: journal.PriErr,
slog.LevelWarn: journal.PriWarning,
fs.SlogLevelNotice: journal.PriNotice,
slog.LevelInfo: journal.PriInfo,
slog.LevelDebug: journal.PriDebug,
}
func slogLevelToSystemdPriority(l slog.Level) journal.Priority {
prio, ok := slogLevelToSystemdPrefix[l]
if !ok {
return journal.PriInfo
}
return prio
}
func isJournalStream() bool {
if usingJournald, _ := journal.StderrIsJournalStream(); usingJournald {
return true
}
return false
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/redirect_stderr_windows.go | fs/log/redirect_stderr_windows.go | // Log the panic under windows to the log file
//
// Code from minix, via
//
// https://play.golang.org/p/kLtct7lSUg
//go:build windows
package log
import (
"os"
"syscall"
"github.com/rclone/rclone/fs"
)
var (
kernel32 = syscall.MustLoadDLL("kernel32.dll")
procSetStdHandle = kernel32.MustFindProc("SetStdHandle")
)
func setStdHandle(stdhandle int32, handle syscall.Handle) error {
r0, _, e1 := syscall.SyscallN(procSetStdHandle.Addr(), uintptr(stdhandle), uintptr(handle))
if r0 == 0 {
if e1 != 0 {
return error(e1)
}
return syscall.EINVAL
}
return nil
}
// redirectStderr to the file passed in
func redirectStderr(f *os.File) {
err := setStdHandle(syscall.STD_ERROR_HANDLE, syscall.Handle(f.Fd()))
if err != nil {
fs.Fatalf(nil, "Failed to redirect stderr to file: %v", err)
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/slog.go | fs/log/slog.go | // Interfaces for the slog package
package log
import (
"bytes"
"context"
"fmt"
"io"
"log/slog"
"os"
"runtime"
"strings"
"sync"
"time"
"github.com/rclone/rclone/fs"
)
// Handler is the standard handler for the logging.
var Handler = defaultHandler()
// Create the default OutputHandler
//
// This logs to stderr with standard go logger format at level INFO.
//
// This will be adjusted by InitLogging to be the configured levels
// but it is important we have a logger running regardless of whether
// InitLogging has been called yet or not.
func defaultHandler() *OutputHandler {
// Default options for default handler
opts := &slog.HandlerOptions{
Level: fs.LogLevelToSlog(fs.InitialLogLevel()),
}
// Create our handler
h := NewOutputHandler(os.Stderr, opts, logFormatDate|logFormatTime)
// Set the slog default handler
slog.SetDefault(slog.New(h))
// Make log.Printf logs at level Notice
slog.SetLogLoggerLevel(fs.SlogLevelNotice)
return h
}
// Map slog level names to string
var slogNames = map[slog.Level]string{
slog.LevelDebug: "DEBUG",
slog.LevelInfo: "INFO",
fs.SlogLevelNotice: "NOTICE",
slog.LevelWarn: "WARNING",
slog.LevelError: "ERROR",
fs.SlogLevelCritical: "CRITICAL",
fs.SlogLevelAlert: "ALERT",
fs.SlogLevelEmergency: "EMERGENCY",
}
// Convert a slog level to string using rclone's extra levels
func slogLevelToString(level slog.Level) string {
levelStr := slogNames[level]
if levelStr == "" {
levelStr = level.String()
}
return levelStr
}
// ReplaceAttr function to customize the level key's string value in logs
func mapLogLevelNames(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.LevelKey {
level, ok := a.Value.Any().(slog.Level)
if !ok {
return a
}
levelStr := strings.ToLower(slogLevelToString(level))
a.Value = slog.StringValue(levelStr)
}
return a
}
// get the file and line number of the caller skipping skip levels
func getCaller(skip int) string {
var pc [64]uintptr
n := runtime.Callers(skip, pc[:])
if n == 0 {
return ""
}
frames := runtime.CallersFrames(pc[:n])
more := true
var frame runtime.Frame
for more {
frame, more = frames.Next()
file := frame.File
if strings.Contains(file, "/log/") || strings.HasSuffix(file, "log.go") {
continue
}
line := frame.Line
// shorten file name
n := 0
for i := len(file) - 1; i > 0; i-- {
if file[i] == '/' {
n++
if n >= 2 {
file = file[i+1:]
break
}
}
}
return fmt.Sprintf("%s:%d", file, line)
}
return ""
}
// OutputHandler is a slog.Handler that writes log records in a format
// identical to the standard library's `log` package (e.g., "YYYY/MM/DD HH:MM:SS message").
//
// It can also write logs in JSON format identical to logrus.
type OutputHandler struct {
opts slog.HandlerOptions
levelVar slog.LevelVar
writer io.Writer
mu sync.Mutex
output []outputFn // log to writer if empty or the last item
outputExtra []outputExtra // log to all these additional places
format logFormat
jsonBuf bytes.Buffer
jsonHandler *slog.JSONHandler
}
// Records the type and function pointer for extra logging output.
type outputExtra struct {
json bool
output outputFn
}
// Define the type of the override logger
type outputFn func(level slog.Level, text string)
// NewOutputHandler creates a new OutputHandler with the specified flags.
//
// This is designed to use log/slog but produce output which is
// backwards compatible with previous rclone versions.
//
// If opts is nil, default options are used, with Level set to
// slog.LevelInfo.
func NewOutputHandler(out io.Writer, opts *slog.HandlerOptions, format logFormat) *OutputHandler {
h := &OutputHandler{
writer: out,
format: format,
}
if opts != nil {
h.opts = *opts
}
if h.opts.Level == nil {
h.opts.Level = slog.LevelInfo
}
// Set the level var with the configured level
h.levelVar.Set(h.opts.Level.Level())
// And use it from now on
h.opts.Level = &h.levelVar
// Create the JSON logger in case we need it
jsonOpts := slog.HandlerOptions{
Level: h.opts.Level,
ReplaceAttr: mapLogLevelNames,
}
h.jsonHandler = slog.NewJSONHandler(&h.jsonBuf, &jsonOpts)
return h
}
// SetOutput sets a new output handler for the log output.
//
// This is for temporarily overriding the output.
func (h *OutputHandler) SetOutput(fn outputFn) {
h.mu.Lock()
defer h.mu.Unlock()
h.output = append(h.output, fn)
}
// ResetOutput resets the log output to what is was.
func (h *OutputHandler) ResetOutput() {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.output) > 0 {
h.output = h.output[:len(h.output)-1]
}
}
// AddOutput adds an additional logging destination of the type specified.
func (h *OutputHandler) AddOutput(json bool, fn outputFn) {
h.mu.Lock()
defer h.mu.Unlock()
h.outputExtra = append(h.outputExtra, outputExtra{
json: json,
output: fn,
})
}
// SetLevel sets a new log level, returning the old one.
func (h *OutputHandler) SetLevel(level slog.Level) slog.Level {
h.mu.Lock()
defer h.mu.Unlock()
oldLevel := h.levelVar.Level()
h.levelVar.Set(level)
return oldLevel
}
// Set the writer for the log to that passed.
func (h *OutputHandler) setWriter(writer io.Writer) {
h.writer = writer
}
// Set the format flags to that passed in.
func (h *OutputHandler) setFormat(format logFormat) {
h.format = format
}
// clear format flags that this output type doesn't want
func (h *OutputHandler) clearFormatFlags(bitMask logFormat) {
h.format &^= bitMask
}
// set format flags that this output type requires
func (h *OutputHandler) setFormatFlags(bitMask logFormat) {
h.format |= bitMask
}
// Enabled returns whether this logger is enabled for this level.
func (h *OutputHandler) Enabled(_ context.Context, level slog.Level) bool {
minLevel := slog.LevelInfo
if h.opts.Level != nil {
minLevel = h.opts.Level.Level()
}
return level >= minLevel
}
// Create a log header in Go standard log format.
func (h *OutputHandler) formatStdLogHeader(buf *bytes.Buffer, level slog.Level, t time.Time, object string, lineInfo string) {
// Add time in Go standard format if requested
if h.format&(logFormatDate|logFormatTime|logFormatMicroseconds) != 0 {
if h.format&logFormatUTC != 0 {
t = t.UTC()
}
if h.format&logFormatDate != 0 {
year, month, day := t.Date()
fmt.Fprintf(buf, "%04d/%02d/%02d ", year, month, day)
}
if h.format&(logFormatTime|logFormatMicroseconds) != 0 {
hour, min, sec := t.Clock()
fmt.Fprintf(buf, "%02d:%02d:%02d", hour, min, sec)
if h.format&logFormatMicroseconds != 0 {
fmt.Fprintf(buf, ".%06d", t.Nanosecond()/1e3)
}
buf.WriteByte(' ')
}
}
// Add source code filename:line if requested
if h.format&(logFormatShortFile|logFormatLongFile) != 0 && lineInfo != "" {
buf.WriteString(lineInfo)
buf.WriteByte(':')
buf.WriteByte(' ')
}
// Add PID if requested
if h.format&logFormatPid != 0 {
fmt.Fprintf(buf, "[%d] ", os.Getpid())
}
// Add log level if required
if h.format&logFormatNoLevel == 0 {
levelStr := slogLevelToString(level)
fmt.Fprintf(buf, "%-6s: ", levelStr)
}
// Add object if passed
if object != "" {
buf.WriteString(object)
buf.WriteByte(':')
buf.WriteByte(' ')
}
}
// Create a log in standard Go log format into buf.
func (h *OutputHandler) textLog(ctx context.Context, buf *bytes.Buffer, r slog.Record) error {
var lineInfo string
if h.format&(logFormatShortFile|logFormatLongFile) != 0 {
lineInfo = getCaller(2)
}
var object string
r.Attrs(func(attr slog.Attr) bool {
if attr.Key == "object" {
object = attr.Value.String()
return false
}
return true
})
h.formatStdLogHeader(buf, r.Level, r.Time, object, lineInfo)
buf.WriteString(r.Message)
if buf.Len() == 0 || buf.Bytes()[buf.Len()-1] != '\n' { // Ensure newline
buf.WriteByte('\n')
}
return nil
}
// Create a log in JSON format into buf.
func (h *OutputHandler) jsonLog(ctx context.Context, buf *bytes.Buffer, r slog.Record) (err error) {
// Call the JSON handler to create the JSON in buf
r.AddAttrs(
slog.String("source", getCaller(2)),
)
// Add PID if requested
if h.format&logFormatPid != 0 {
r.AddAttrs(slog.Int("pid", os.Getpid()))
}
h.mu.Lock()
err = h.jsonHandler.Handle(ctx, r)
if err == nil {
_, err = h.jsonBuf.WriteTo(buf)
}
h.mu.Unlock()
return err
}
// Handle outputs a log in the current format
func (h *OutputHandler) Handle(ctx context.Context, r slog.Record) (err error) {
var (
bufJSON *bytes.Buffer
bufText *bytes.Buffer
buf *bytes.Buffer
)
// Check whether we need to build Text or JSON logs or both
needJSON := h.format&logFormatJSON != 0
needText := !needJSON
for _, out := range h.outputExtra {
if out.json {
needJSON = true
} else {
needText = true
}
}
if needJSON {
var bufJSONBack [256]byte
bufJSON = bytes.NewBuffer(bufJSONBack[:0])
err = h.jsonLog(ctx, bufJSON, r)
if err != nil {
return err
}
}
if needText {
var bufTextBack [256]byte
bufText = bytes.NewBuffer(bufTextBack[:0])
err = h.textLog(ctx, bufText, r)
if err != nil {
return err
}
}
h.mu.Lock()
defer h.mu.Unlock()
// Do the log, either to the default destination or to the alternate logging system
if h.format&logFormatJSON != 0 {
buf = bufJSON
} else {
buf = bufText
}
if len(h.output) > 0 {
h.output[len(h.output)-1](r.Level, buf.String())
err = nil
} else {
_, err = h.writer.Write(buf.Bytes())
}
// Log to any additional destinations required
for _, out := range h.outputExtra {
if out.json {
out.output(r.Level, bufJSON.String())
} else {
out.output(r.Level, bufText.String())
}
}
return err
}
// WithAttrs creates a new handler with the same writer, options, and flags.
// Attributes are ignored for the output format of this specific handler.
func (h *OutputHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
return NewOutputHandler(h.writer, &h.opts, h.format)
}
// WithGroup creates a new handler with the same writer, options, and flags.
// Groups are ignored for the output format of this specific handler.
func (h *OutputHandler) WithGroup(name string) slog.Handler {
return NewOutputHandler(h.writer, &h.opts, h.format)
}
// Check interface
var _ slog.Handler = (*OutputHandler)(nil)
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/redirect_stderr_unix.go | fs/log/redirect_stderr_unix.go | // Log the panic under unix to the log file
//go:build !windows && !solaris && !plan9 && !js
package log
import (
"os"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config"
"golang.org/x/sys/unix"
)
// redirectStderr to the file passed in
func redirectStderr(f *os.File) {
passPromptFd, err := unix.Dup(int(os.Stderr.Fd()))
if err != nil {
fs.Fatalf(nil, "Failed to duplicate stderr: %v", err)
}
config.PasswordPromptOutput = os.NewFile(uintptr(passPromptFd), "passPrompt")
err = unix.Dup2(int(f.Fd()), int(os.Stderr.Fd()))
if err != nil {
fs.Fatalf(nil, "Failed to redirect stderr to file: %v", err)
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/event_log.go | fs/log/event_log.go | // Windows event logging stubs for non windows machines
//go:build !windows
package log
import (
"fmt"
"runtime"
)
// Starts windows event log if configured.
func startWindowsEventLog(*OutputHandler) error {
return fmt.Errorf("windows event log not supported on %s platform", runtime.GOOS)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/redirect_stderr.go | fs/log/redirect_stderr.go | // Log the panic to the log file - for oses which can't do this
//go:build !windows && !darwin && !dragonfly && !freebsd && !linux && !nacl && !netbsd && !openbsd && !aix
package log
import (
"os"
"github.com/rclone/rclone/fs"
)
// redirectStderr to the file passed in
func redirectStderr(f *os.File) {
fs.Errorf(nil, "Can't redirect stderr to file")
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/log/logflags/logflags.go | fs/log/logflags/logflags.go | // Package logflags implements command line flags to set up the log
package logflags
import (
"github.com/rclone/rclone/fs/config/flags"
"github.com/rclone/rclone/fs/log"
"github.com/spf13/pflag"
)
// AddFlags adds the log flags to the flagSet
func AddFlags(flagSet *pflag.FlagSet) {
flags.AddFlagsFromOptions(flagSet, "", log.OptionsInfo)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/driveletter/driveletter.go | fs/driveletter/driveletter.go | //go:build !windows
// Package driveletter returns whether a name is a valid drive letter
package driveletter
// IsDriveLetter returns a bool indicating whether name is a valid
// Windows drive letter
//
// On non windows platforms we don't have drive letters so we always
// return false
func IsDriveLetter(name string) bool {
return false
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/driveletter/driveletter_windows.go | fs/driveletter/driveletter_windows.go | //go:build windows
// Package driveletter returns whether a name is a valid drive letter
package driveletter
// IsDriveLetter returns a bool indicating whether name is a valid
// Windows drive letter
func IsDriveLetter(name string) bool {
if len(name) != 1 {
return false
}
c := name[0]
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/sync/sync_test.go | fs/sync/sync_test.go | // Test sync/copy/move
package sync
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"sort"
"strings"
"testing"
"time"
mutex "sync" // renamed as "sync" already in use
_ "github.com/rclone/rclone/backend/all" // import all backends
"github.com/rclone/rclone/cmd/bisync/bilib"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/filter"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/transform"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/text/unicode/norm"
)
// Some times used in the tests
var (
t1 = fstest.Time("2001-02-03T04:05:06.499999999Z")
t2 = fstest.Time("2011-12-25T12:59:59.123456789Z")
t3 = fstest.Time("2011-12-30T12:59:59.000000000Z")
)
// TestMain drives the tests
func TestMain(m *testing.M) {
fstest.TestMain(m)
}
// Check dry run is working
func TestCopyWithDryRun(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
r.Mkdir(ctx, r.Fremote)
ci.DryRun = true
ctx = predictDstFromLogger(ctx)
err := CopyDir(ctx, r.Fremote, r.Flocal, false)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t) // error expected here because dry-run
require.NoError(t, err)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t)
}
// Now without dry run
func TestCopy(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
_, err := operations.SetDirModTime(ctx, r.Flocal, nil, "sub dir", t2)
if err != nil && !errors.Is(err, fs.ErrorNotImplemented) {
require.NoError(t, err)
}
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = CopyDir(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file1)
// Check that the modtimes of the directories are as expected
r.CheckDirectoryModTimes(t, "sub dir")
}
func testCopyMetadata(t *testing.T, createEmptySrcDirs bool) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
ci.Metadata = true
r := fstest.NewRun(t)
features := r.Fremote.Features()
if !features.ReadMetadata && !features.WriteMetadata && !features.UserMetadata &&
!features.ReadDirMetadata && !features.WriteDirMetadata && !features.UserDirMetadata {
t.Skip("Skipping as metadata not supported")
}
if createEmptySrcDirs && !features.CanHaveEmptyDirectories {
t.Skip("Skipping as can't have empty directories")
}
const content = "hello metadata world!"
const dirPath = "metadata sub dir"
const emptyDirPath = "empty metadata sub dir"
const filePath = dirPath + "/hello metadata world"
fileMetadata := fs.Metadata{
// System metadata supported by all backends
"mtime": t1.Format(time.RFC3339Nano),
// User metadata
"potato": "jersey",
}
dirMetadata := fs.Metadata{
// System metadata supported by all backends
"mtime": t2.Format(time.RFC3339Nano),
// User metadata
"potato": "king edward",
}
// Make the directory with metadata - may fall back to Mkdir
_, err := operations.MkdirMetadata(ctx, r.Flocal, dirPath, dirMetadata)
require.NoError(t, err)
// Make the empty directory with metadata - may fall back to Mkdir
_, err = operations.MkdirMetadata(ctx, r.Flocal, emptyDirPath, dirMetadata)
require.NoError(t, err)
// Upload the file with metadata
in := io.NopCloser(bytes.NewBufferString(content))
_, err = operations.Rcat(ctx, r.Flocal, filePath, in, t1, fileMetadata)
require.NoError(t, err)
file1 := fstest.NewItem(filePath, content, t1)
// Reset the time of the directory
_, err = operations.SetDirModTime(ctx, r.Flocal, nil, dirPath, t2)
if err != nil && !errors.Is(err, fs.ErrorNotImplemented) {
require.NoError(t, err)
}
ctx = predictDstFromLogger(ctx)
err = CopyDir(ctx, r.Fremote, r.Flocal, createEmptySrcDirs)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file1)
// Check that the modtimes of the directories are as expected
r.CheckDirectoryModTimes(t, dirPath)
// Check that the metadata on the directory and file is correct
if features.WriteMetadata && features.ReadMetadata {
fstest.CheckEntryMetadata(ctx, t, r.Fremote, fstest.NewObject(ctx, t, r.Fremote, filePath), fileMetadata)
}
if features.WriteDirMetadata && features.ReadDirMetadata {
fstest.CheckEntryMetadata(ctx, t, r.Fremote, fstest.NewDirectory(ctx, t, r.Fremote, dirPath), dirMetadata)
}
if !createEmptySrcDirs {
// dir must not exist
_, err := fstest.NewDirectoryRetries(ctx, t, r.Fremote, emptyDirPath, 1)
assert.Error(t, err, "Not expecting to find empty directory")
assert.True(t, errors.Is(err, fs.ErrorDirNotFound), fmt.Sprintf("expecting wrapped %#v not: %#v", fs.ErrorDirNotFound, err))
} else {
// dir must exist
dir := fstest.NewDirectory(ctx, t, r.Fremote, emptyDirPath)
if features.ReadDirMetadata {
fstest.CheckEntryMetadata(ctx, t, r.Fremote, dir, dirMetadata)
}
}
}
func TestCopyMetadata(t *testing.T) {
testCopyMetadata(t, true)
}
func TestCopyMetadataNoEmptyDirs(t *testing.T) {
testCopyMetadata(t, false)
}
func TestCopyMissingDirectory(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
r.Mkdir(ctx, r.Fremote)
nonExistingFs, err := fs.NewFs(ctx, "/non-existing")
if err != nil {
t.Fatal(err)
}
ctx = predictDstFromLogger(ctx)
err = CopyDir(ctx, r.Fremote, nonExistingFs, false)
require.Error(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
}
// Now with --no-traverse
func TestCopyNoTraverse(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
ci.NoTraverse = true
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
ctx = predictDstFromLogger(ctx)
err := CopyDir(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file1)
}
func TestCopyNoTraverseDeadlock(t *testing.T) {
r := fstest.NewRun(t)
if !r.Fremote.Features().IsLocal {
t.Skip("Only runs on local")
}
const nFiles = 200
t1 := fstest.Time("2001-02-03T04:05:06.499999999Z")
// Create lots of source files.
items := make([]fstest.Item, nFiles)
for i := range items {
name := fmt.Sprintf("file%d.txt", i)
items[i] = r.WriteFile(name, fmt.Sprintf("content%d", i), t1)
}
r.CheckLocalItems(t, items...)
// Set --no-traverse
ctx, ci := fs.AddConfig(context.Background())
ci.NoTraverse = true
// Initial copy to establish destination.
require.NoError(t, CopyDir(ctx, r.Fremote, r.Flocal, false))
r.CheckRemoteItems(t, items...)
// Second copy which shouldn't deadlock
require.NoError(t, CopyDir(ctx, r.Flocal, r.Fremote, false))
r.CheckRemoteItems(t, items...)
}
// Now with --check-first
func TestCopyCheckFirst(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
ci.CheckFirst = true
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
ctx = predictDstFromLogger(ctx)
err := CopyDir(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file1)
}
// Now with --no-traverse
func TestSyncNoTraverse(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
ci.NoTraverse = true
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err := Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file1)
}
// Test copy with depth
func TestCopyWithDepth(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
file2 := r.WriteFile("hello world2", "hello world2", t2)
// Check the MaxDepth too
ci.MaxDepth = 1
ctx = predictDstFromLogger(ctx)
err := CopyDir(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t, file1, file2)
r.CheckRemoteItems(t, file2)
}
// Test copy with files from
func testCopyWithFilesFrom(t *testing.T, noTraverse bool) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
file1 := r.WriteFile("potato2", "hello world", t1)
file2 := r.WriteFile("hello world2", "hello world2", t2)
// Set the --files-from equivalent
f, err := filter.NewFilter(nil)
require.NoError(t, err)
require.NoError(t, f.AddFile("potato2"))
require.NoError(t, f.AddFile("notfound"))
// Change the active filter
ctx = filter.ReplaceConfig(ctx, f)
ci.NoTraverse = noTraverse
ctx = predictDstFromLogger(ctx)
err = CopyDir(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t, file1, file2)
r.CheckRemoteItems(t, file1)
}
func TestCopyWithFilesFrom(t *testing.T) { testCopyWithFilesFrom(t, false) }
func TestCopyWithFilesFromAndNoTraverse(t *testing.T) { testCopyWithFilesFrom(t, true) }
// Test copy empty directories
func TestCopyEmptyDirectories(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
_, err := operations.MkdirModTime(ctx, r.Flocal, "sub dir2/sub sub dir2", t2)
require.NoError(t, err)
_, err = operations.SetDirModTime(ctx, r.Flocal, nil, "sub dir2", t2)
require.NoError(t, err)
r.Mkdir(ctx, r.Fremote)
// Set the modtime on "sub dir" to something specific
// Without this it fails on the CI and in VirtualBox with variances of up to 10mS
_, err = operations.SetDirModTime(ctx, r.Flocal, nil, "sub dir", t1)
require.NoError(t, err)
ctx = predictDstFromLogger(ctx)
err = CopyDir(ctx, r.Fremote, r.Flocal, true)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckRemoteListing(
t,
[]fstest.Item{
file1,
},
[]string{
"sub dir",
"sub dir2",
"sub dir2/sub sub dir2",
},
)
// Check that the modtimes of the directories are as expected
r.CheckDirectoryModTimes(t, "sub dir", "sub dir2", "sub dir2/sub sub dir2")
}
// Test copy empty directories when we are configured not to create them
func TestCopyNoEmptyDirectories(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
err := operations.Mkdir(ctx, r.Flocal, "sub dir2")
require.NoError(t, err)
_, err = operations.MkdirModTime(ctx, r.Flocal, "sub dir2/sub sub dir2", t2)
require.NoError(t, err)
r.Mkdir(ctx, r.Fremote)
err = CopyDir(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
r.CheckRemoteListing(
t,
[]fstest.Item{
file1,
},
[]string{
"sub dir",
},
)
}
// Test move empty directories
func TestMoveEmptyDirectories(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
_, err := operations.MkdirModTime(ctx, r.Flocal, "sub dir2", t2)
require.NoError(t, err)
subDir := fstest.NewDirectory(ctx, t, r.Flocal, "sub dir")
subDirT := subDir.ModTime(ctx)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = MoveDir(ctx, r.Fremote, r.Flocal, false, true)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckRemoteListing(
t,
[]fstest.Item{
file1,
},
[]string{
"sub dir",
"sub dir2",
},
)
// Check that the modtimes of the directories are as expected
r.CheckDirectoryModTimes(t, "sub dir2")
// Note that "sub dir" mod time is updated when file1 is deleted from it
// So check it more manually
got := fstest.NewDirectory(ctx, t, r.Fremote, "sub dir")
fstest.CheckDirModTime(ctx, t, r.Fremote, got, subDirT)
}
// Test that --no-update-dir-modtime is working
func TestSyncNoUpdateDirModtime(t *testing.T) {
r := fstest.NewRun(t)
if r.Fremote.Features().DirSetModTime == nil {
t.Skip("Skipping test as backend does not support DirSetModTime")
}
ctx, ci := fs.AddConfig(context.Background())
ci.NoUpdateDirModTime = true
const name = "sub dir no update dir modtime"
// Set the modtime on name to something specific
_, err := operations.MkdirModTime(ctx, r.Flocal, name, t1)
require.NoError(t, err)
// Create the remote directory with the current time
require.NoError(t, r.Fremote.Mkdir(ctx, name))
// Read its modification time
wantT := fstest.NewDirectory(ctx, t, r.Fremote, name).ModTime(ctx)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckRemoteListing(
t,
[]fstest.Item{},
[]string{
name,
},
)
// Read the new directory modification time - it should not have changed
gotT := fstest.NewDirectory(ctx, t, r.Fremote, name).ModTime(ctx)
fstest.AssertTimeEqualWithPrecision(t, name, wantT, gotT, r.Fremote.Precision())
}
// Test move empty directories when we are not configured to create them
func TestMoveNoEmptyDirectories(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
err := operations.Mkdir(ctx, r.Flocal, "sub dir2")
require.NoError(t, err)
r.Mkdir(ctx, r.Fremote)
err = MoveDir(ctx, r.Fremote, r.Flocal, false, false)
require.NoError(t, err)
r.CheckRemoteListing(
t,
[]fstest.Item{
file1,
},
[]string{
"sub dir",
},
)
}
// Test sync empty directories
func TestSyncEmptyDirectories(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
_, err := operations.MkdirModTime(ctx, r.Flocal, "sub dir2", t2)
require.NoError(t, err)
// Set the modtime on "sub dir" to something specific
// Without this it fails on the CI and in VirtualBox with variances of up to 10mS
_, err = operations.SetDirModTime(ctx, r.Flocal, nil, "sub dir", t1)
require.NoError(t, err)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckRemoteListing(
t,
[]fstest.Item{
file1,
},
[]string{
"sub dir",
"sub dir2",
},
)
// Check that the modtimes of the directories are as expected
r.CheckDirectoryModTimes(t, "sub dir", "sub dir2")
}
// Test delayed mod time setting
func TestSyncSetDelayedModTimes(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
if !r.Fremote.Features().DirModTimeUpdatesOnWrite {
t.Skip("Backend doesn't have DirModTimeUpdatesOnWrite set")
}
// Create directories without timestamps
require.NoError(t, r.Flocal.Mkdir(ctx, "a1/b1/c1/d1/e1/f1"))
require.NoError(t, r.Flocal.Mkdir(ctx, "a1/b2/c1/d1/e1/f1"))
require.NoError(t, r.Flocal.Mkdir(ctx, "a1/b1/c1/d2/e1/f1"))
require.NoError(t, r.Flocal.Mkdir(ctx, "a1/b1/c1/d2/e1/f2"))
dirs := []string{
"a1",
"a1/b1",
"a1/b1/c1",
"a1/b1/c1/d1",
"a1/b1/c1/d1/e1",
"a1/b1/c1/d1/e1/f1",
"a1/b1/c1/d2",
"a1/b1/c1/d2/e1",
"a1/b1/c1/d2/e1/f1",
"a1/b1/c1/d2/e1/f2",
"a1/b2",
"a1/b2/c1",
"a1/b2/c1/d1",
"a1/b2/c1/d1/e1",
"a1/b2/c1/d1/e1/f1",
}
r.CheckLocalListing(t, []fstest.Item{}, dirs)
// Timestamp the directories in reverse order
ts := t1
for i := len(dirs) - 1; i >= 0; i-- {
dir := dirs[i]
_, err := operations.SetDirModTime(ctx, r.Flocal, nil, dir, ts)
require.NoError(t, err)
ts = ts.Add(time.Minute)
}
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err := Sync(ctx, r.Fremote, r.Flocal, true)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckRemoteListing(t, []fstest.Item{}, dirs)
// Check that the modtimes of the directories are as expected
r.CheckDirectoryModTimes(t, dirs...)
}
// Test sync empty directories when we are not configured to create them
func TestSyncNoEmptyDirectories(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteFile("sub dir/hello world", "hello world", t1)
err := operations.Mkdir(ctx, r.Flocal, "sub dir2")
require.NoError(t, err)
r.Mkdir(ctx, r.Fremote)
err = Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
r.CheckRemoteListing(
t,
[]fstest.Item{
file1,
},
[]string{
"sub dir",
},
)
}
// Test a server-side copy if possible, or the backup path if not
func TestServerSideCopy(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteObject(ctx, "sub dir/hello world", "hello world", t1)
r.CheckRemoteItems(t, file1)
FremoteCopy, _, finaliseCopy, err := fstest.RandomRemote()
require.NoError(t, err)
defer finaliseCopy()
t.Logf("Server side copy (if possible) %v -> %v", r.Fremote, FremoteCopy)
ctx = predictDstFromLogger(ctx)
err = CopyDir(ctx, FremoteCopy, r.Fremote, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
fstest.CheckItems(t, FremoteCopy, file1)
}
// Test copying a file over itself
func TestCopyOverSelf(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteObject(ctx, "sub dir/hello world", "hello world", t1)
r.CheckRemoteItems(t, file1)
file2 := r.WriteFile("sub dir/hello world", "hello world again", t2)
r.CheckLocalItems(t, file2)
ctx = predictDstFromLogger(ctx)
err := CopyDir(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckRemoteItems(t, file2)
}
// Test server-side copying a file over itself
func TestServerSideCopyOverSelf(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteObject(ctx, "sub dir/hello world", "hello world", t1)
r.CheckRemoteItems(t, file1)
FremoteCopy, _, finaliseCopy, err := fstest.RandomRemote()
require.NoError(t, err)
defer finaliseCopy()
t.Logf("Server side copy (if possible) %v -> %v", r.Fremote, FremoteCopy)
ctx = predictDstFromLogger(ctx)
err = CopyDir(ctx, FremoteCopy, r.Fremote, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, FremoteCopy, r.Fremote, operations.GetLoggerOpt(ctx).JSON, t)
fstest.CheckItems(t, FremoteCopy, file1)
file2 := r.WriteObject(ctx, "sub dir/hello world", "hello world again", t2)
r.CheckRemoteItems(t, file2)
ctx = predictDstFromLogger(ctx)
err = CopyDir(ctx, FremoteCopy, r.Fremote, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, FremoteCopy, r.Fremote, operations.GetLoggerOpt(ctx).JSON, t)
fstest.CheckItems(t, FremoteCopy, file2)
}
// Test moving a file over itself
func TestMoveOverSelf(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteObject(ctx, "sub dir/hello world", "hello world", t1)
r.CheckRemoteItems(t, file1)
file2 := r.WriteFile("sub dir/hello world", "hello world again", t2)
r.CheckLocalItems(t, file2)
ctx = predictDstFromLogger(ctx)
err := MoveDir(ctx, r.Fremote, r.Flocal, false, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t)
r.CheckRemoteItems(t, file2)
}
// Test server-side moving a file over itself
func TestServerSideMoveOverSelf(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteObject(ctx, "sub dir/hello world", "hello world", t1)
r.CheckRemoteItems(t, file1)
FremoteCopy, _, finaliseCopy, err := fstest.RandomRemote()
require.NoError(t, err)
defer finaliseCopy()
t.Logf("Server side copy (if possible) %v -> %v", r.Fremote, FremoteCopy)
ctx = predictDstFromLogger(ctx)
err = CopyDir(ctx, FremoteCopy, r.Fremote, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, FremoteCopy, r.Fremote, operations.GetLoggerOpt(ctx).JSON, t)
fstest.CheckItems(t, FremoteCopy, file1)
file2 := r.WriteObject(ctx, "sub dir/hello world", "hello world again", t2)
r.CheckRemoteItems(t, file2)
// ctx = predictDstFromLogger(ctx)
err = MoveDir(ctx, FremoteCopy, r.Fremote, false, false)
require.NoError(t, err)
// testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t) // not currently supported
r.CheckRemoteItems(t)
fstest.CheckItems(t, FremoteCopy, file2)
// check that individual file moves also work without MoveDir
file3 := r.WriteObject(ctx, "sub dir/hello world", "hello world a third time", t3)
r.CheckRemoteItems(t, file3)
ctx = predictDstFromLogger(ctx)
fs.Debugf(nil, "testing file moves")
err = moveDir(ctx, FremoteCopy, r.Fremote, false, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, FremoteCopy, r.Fremote, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckRemoteItems(t)
fstest.CheckItems(t, FremoteCopy, file3)
}
// Check that if the local file doesn't exist when we copy it up,
// nothing happens to the remote file
func TestCopyAfterDelete(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteObject(ctx, "sub dir/hello world", "hello world", t1)
r.CheckLocalItems(t)
r.CheckRemoteItems(t, file1)
err := operations.Mkdir(ctx, r.Flocal, "")
require.NoError(t, err)
ctx = predictDstFromLogger(ctx)
err = CopyDir(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t)
r.CheckRemoteItems(t, file1)
}
// Check the copy downloading a file
func TestCopyRedownload(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteObject(ctx, "sub dir/hello world", "hello world", t1)
r.CheckRemoteItems(t, file1)
ctx = predictDstFromLogger(ctx)
err := CopyDir(ctx, r.Flocal, r.Fremote, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
// Test with combined precision of local and remote as we copied it there and back
r.CheckLocalListing(t, []fstest.Item{file1}, nil)
}
// Create a file and sync it. Change the last modified date and resync.
// If we're only doing sync by size and checksum, we expect nothing to
// to be transferred on the second sync.
func TestSyncBasedOnCheckSum(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
ci.CheckSum = true
file1 := r.WriteFile("check sum", "-", t1)
r.CheckLocalItems(t, file1)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err := Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
// We should have transferred exactly one file.
assert.Equal(t, toyFileTransfers(r), accounting.GlobalStats().GetTransfers())
r.CheckRemoteItems(t, file1)
// Change last modified date only
file2 := r.WriteFile("check sum", "-", t2)
r.CheckLocalItems(t, file2)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
// We should have transferred no files
assert.Equal(t, int64(0), accounting.GlobalStats().GetTransfers())
r.CheckLocalItems(t, file2)
r.CheckRemoteItems(t, file1)
}
// Create a file and sync it. Change the last modified date and the
// file contents but not the size. If we're only doing sync by size
// only, we expect nothing to to be transferred on the second sync.
func TestSyncSizeOnly(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
ci.SizeOnly = true
file1 := r.WriteFile("sizeonly", "potato", t1)
r.CheckLocalItems(t, file1)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err := Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
// We should have transferred exactly one file.
assert.Equal(t, toyFileTransfers(r), accounting.GlobalStats().GetTransfers())
r.CheckRemoteItems(t, file1)
// Update mtime, md5sum but not length of file
file2 := r.WriteFile("sizeonly", "POTATO", t2)
r.CheckLocalItems(t, file2)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
// We should have transferred no files
assert.Equal(t, int64(0), accounting.GlobalStats().GetTransfers())
r.CheckLocalItems(t, file2)
r.CheckRemoteItems(t, file1)
}
// Create a file and sync it. Keep the last modified date but change
// the size. With --ignore-size we expect nothing to to be
// transferred on the second sync.
func TestSyncIgnoreSize(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
ci.IgnoreSize = true
file1 := r.WriteFile("ignore-size", "contents", t1)
r.CheckLocalItems(t, file1)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err := Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
// We should have transferred exactly one file.
assert.Equal(t, toyFileTransfers(r), accounting.GlobalStats().GetTransfers())
r.CheckRemoteItems(t, file1)
// Update size but not date of file
file2 := r.WriteFile("ignore-size", "longer contents but same date", t1)
r.CheckLocalItems(t, file2)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
// We should have transferred no files
assert.Equal(t, int64(0), accounting.GlobalStats().GetTransfers())
r.CheckLocalItems(t, file2)
r.CheckRemoteItems(t, file1)
}
func TestSyncIgnoreTimes(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
file1 := r.WriteBoth(ctx, "existing", "potato", t1)
r.CheckRemoteItems(t, file1)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err := Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
// We should have transferred exactly 0 files because the
// files were identical.
assert.Equal(t, int64(0), accounting.GlobalStats().GetTransfers())
ci.IgnoreTimes = true
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
// We should have transferred exactly one file even though the
// files were identical.
assert.Equal(t, toyFileTransfers(r), accounting.GlobalStats().GetTransfers())
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file1)
}
func TestSyncIgnoreExisting(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
file1 := r.WriteFile("existing", "potato", t1)
ci.IgnoreExisting = true
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err := Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file1)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
// Change everything
r.WriteFile("existing", "newpotatoes", t2)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
// Items should not change
r.CheckRemoteItems(t, file1)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
}
func TestSyncIgnoreErrors(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
ci.IgnoreErrors = true
file1 := r.WriteFile("a/potato2", "------------------------------------------------------------", t1)
file2 := r.WriteObject(ctx, "b/potato", "SMALLER BUT SAME DATE", t2)
file3 := r.WriteBoth(ctx, "c/non empty space", "AhHa!", t2)
require.NoError(t, operations.Mkdir(ctx, r.Fremote, "d"))
r.CheckLocalListing(
t,
[]fstest.Item{
file1,
file3,
},
[]string{
"a",
"c",
},
)
r.CheckRemoteListing(
t,
[]fstest.Item{
file2,
file3,
},
[]string{
"b",
"c",
"d",
},
)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
_ = fs.CountError(ctx, errors.New("boom"))
assert.NoError(t, Sync(ctx, r.Fremote, r.Flocal, false))
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalListing(
t,
[]fstest.Item{
file1,
file3,
},
[]string{
"a",
"c",
},
)
r.CheckRemoteListing(
t,
[]fstest.Item{
file1,
file3,
},
[]string{
"a",
"c",
},
)
}
func TestSyncAfterChangingModtimeOnly(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
file1 := r.WriteFile("empty space", "-", t2)
file2 := r.WriteObject(ctx, "empty space", "-", t1)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file2)
ci.DryRun = true
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err := Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file2)
ci.DryRun = false
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file1)
}
func TestSyncAfterChangingModtimeOnlyWithNoUpdateModTime(t *testing.T) {
ctx := context.Background()
ctx, ci := fs.AddConfig(ctx)
r := fstest.NewRun(t)
if r.Fremote.Hashes().Count() == 0 {
t.Logf("Can't check this if no hashes supported")
return
}
ci.NoUpdateModTime = true
file1 := r.WriteFile("empty space", "-", t2)
file2 := r.WriteObject(ctx, "empty space", "-", t1)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file2)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err := Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file2)
}
func TestSyncDoesntUpdateModtime(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
if fs.GetModifyWindow(ctx, r.Fremote) == fs.ModTimeNotSupported {
t.Skip("Can't run this test on fs which doesn't support mod time")
}
file1 := r.WriteFile("foo", "foo", t2)
file2 := r.WriteObject(ctx, "foo", "bar", t1)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file2)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err := Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, file1)
// We should have transferred exactly one file, not set the mod time
assert.Equal(t, toyFileTransfers(r), accounting.GlobalStats().GetTransfers())
}
func TestSyncAfterAddingAFile(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
file1 := r.WriteBoth(ctx, "empty space", "-", t2)
file2 := r.WriteFile("potato", "------------------------------------------------------------", t3)
r.CheckLocalItems(t, file1, file2)
r.CheckRemoteItems(t, file1)
accounting.GlobalStats().ResetCounters()
ctx = predictDstFromLogger(ctx)
err := Sync(ctx, r.Fremote, r.Flocal, false)
require.NoError(t, err)
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | true |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/sync/rc.go | fs/sync/rc.go | package sync
import (
"context"
"github.com/rclone/rclone/fs/rc"
)
func init() {
for _, name := range []string{"sync", "copy", "move"} {
moveHelp := ""
if name == "move" {
moveHelp = "- deleteEmptySrcDirs - delete empty src directories if set\n"
}
rc.Add(rc.Call{
Path: "sync/" + name,
AuthRequired: true,
Fn: func(ctx context.Context, in rc.Params) (rc.Params, error) {
return rcSyncCopyMove(ctx, in, name)
},
Title: name + " a directory from source remote to destination remote",
Help: `This takes the following parameters:
- srcFs - a remote name string e.g. "drive:src" for the source
- dstFs - a remote name string e.g. "drive:dst" for the destination
- createEmptySrcDirs - create empty src directories on destination if set
` + moveHelp + `
See the [` + name + `](/commands/rclone_` + name + `/) command for more information on the above.`,
})
}
}
// Sync/Copy/Move a file
func rcSyncCopyMove(ctx context.Context, in rc.Params, name string) (out rc.Params, err error) {
srcFs, err := rc.GetFsNamed(ctx, in, "srcFs")
if err != nil {
return nil, err
}
dstFs, err := rc.GetFsNamed(ctx, in, "dstFs")
if err != nil {
return nil, err
}
createEmptySrcDirs, err := in.GetBool("createEmptySrcDirs")
if rc.NotErrParamNotFound(err) {
return nil, err
}
switch name {
case "sync":
return nil, Sync(ctx, dstFs, srcFs, createEmptySrcDirs)
case "copy":
return nil, CopyDir(ctx, dstFs, srcFs, createEmptySrcDirs)
case "move":
deleteEmptySrcDirs, err := in.GetBool("deleteEmptySrcDirs")
if rc.NotErrParamNotFound(err) {
return nil, err
}
return nil, MoveDir(ctx, dstFs, srcFs, deleteEmptySrcDirs, createEmptySrcDirs)
}
panic("unknown rcSyncCopyMove type")
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/sync/sync_transform_test.go | fs/sync/sync_transform_test.go | // Test transform
package sync
import (
"cmp"
"context"
"fmt"
"path"
"slices"
"strings"
"testing"
_ "github.com/rclone/rclone/backend/all"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/filter"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fs/walk"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/transform"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/text/unicode/norm"
)
var debug = ``
func TestTransform(t *testing.T) {
type args struct {
TransformOpt []string
TransformBackOpt []string
Lossless bool // whether the TransformBackAlgo is always losslessly invertible
}
tests := []struct {
name string
args args
}{
{name: "NFC", args: args{
TransformOpt: []string{"nfc"},
TransformBackOpt: []string{"nfd"},
Lossless: false,
}},
{name: "NFD", args: args{
TransformOpt: []string{"nfd"},
TransformBackOpt: []string{"nfc"},
Lossless: false,
}},
{name: "base64", args: args{
TransformOpt: []string{"base64encode"},
TransformBackOpt: []string{"base64encode"},
Lossless: false,
}},
{name: "prefix", args: args{
TransformOpt: []string{"prefix=PREFIX"},
TransformBackOpt: []string{"trimprefix=PREFIX"},
Lossless: true,
}},
{name: "suffix", args: args{
TransformOpt: []string{"suffix=SUFFIX"},
TransformBackOpt: []string{"trimsuffix=SUFFIX"},
Lossless: true,
}},
{name: "truncate", args: args{
TransformOpt: []string{"truncate=10"},
TransformBackOpt: []string{"truncate=10"},
Lossless: false,
}},
{name: "encoder", args: args{
TransformOpt: []string{"encoder=Colon,SquareBracket"},
TransformBackOpt: []string{"decoder=Colon,SquareBracket"},
Lossless: true,
}},
{name: "ISO-8859-1", args: args{
TransformOpt: []string{"ISO-8859-1"},
TransformBackOpt: []string{"ISO-8859-1"},
Lossless: false,
}},
{name: "charmap", args: args{
TransformOpt: []string{"all,charmap=ISO-8859-7"},
TransformBackOpt: []string{"all,charmap=ISO-8859-7"},
Lossless: false,
}},
{name: "lowercase", args: args{
TransformOpt: []string{"all,lowercase"},
TransformBackOpt: []string{"all,lowercase"},
Lossless: false,
}},
{name: "ascii", args: args{
TransformOpt: []string{"all,ascii"},
TransformBackOpt: []string{"all,ascii"},
Lossless: false,
}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := fstest.NewRun(t)
defer r.Finalise()
ctx := context.Background()
r.Mkdir(ctx, r.Flocal)
r.Mkdir(ctx, r.Fremote)
items := makeTestFiles(t, r, "dir1")
deleteDSStore(t, r)
r.CheckRemoteListing(t, items, nil)
r.CheckLocalListing(t, items, nil)
err := transform.SetOptions(ctx, tt.args.TransformOpt...)
require.NoError(t, err)
err = Sync(ctx, r.Fremote, r.Flocal, true)
assert.NoError(t, err)
compareNames(ctx, t, r, items)
err = transform.SetOptions(ctx, tt.args.TransformBackOpt...)
require.NoError(t, err)
err = Sync(ctx, r.Fremote, r.Flocal, true)
assert.NoError(t, err)
compareNames(ctx, t, r, items)
if tt.args.Lossless {
deleteDSStore(t, r)
r.CheckRemoteItems(t, items...)
}
})
}
}
const alphabet = "abcdefg123456789"
var extras = []string{"apple", "banana", "appleappleapplebanana", "splitbananasplit"}
func makeTestFiles(t *testing.T, r *fstest.Run, dir string) []fstest.Item {
t.Helper()
n := 0
// Create test files
items := []fstest.Item{}
for _, c := range alphabet {
var out strings.Builder
for i := range rune(7) {
out.WriteRune(c + i)
}
fileName := path.Join(dir, fmt.Sprintf("%04d-%s.txt", n, out.String()))
fileName = strings.ToValidUTF8(fileName, "")
fileName = strings.NewReplacer(":", "", "<", "", ">", "", "?", "").Replace(fileName) // remove characters illegal on windows
if debug != "" {
fileName = debug
}
item := r.WriteObject(context.Background(), fileName, fileName, t1)
r.WriteFile(fileName, fileName, t1)
items = append(items, item)
n++
if debug != "" {
break
}
}
for _, extra := range extras {
item := r.WriteObject(context.Background(), extra, extra, t1)
r.WriteFile(extra, extra, t1)
items = append(items, item)
}
return items
}
func deleteDSStore(t *testing.T, r *fstest.Run) {
ctxDSStore, fi := filter.AddConfig(context.Background())
err := fi.AddRule(`+ *.DS_Store`)
assert.NoError(t, err)
err = fi.AddRule(`- **`)
assert.NoError(t, err)
err = operations.Delete(ctxDSStore, r.Fremote)
assert.NoError(t, err)
}
func compareNames(ctx context.Context, t *testing.T, r *fstest.Run, items []fstest.Item) {
var entries fs.DirEntries
deleteDSStore(t, r)
err := walk.ListR(context.Background(), r.Fremote, "", true, -1, walk.ListObjects, func(e fs.DirEntries) error {
entries = append(entries, e...)
return nil
})
assert.NoError(t, err)
entries = slices.DeleteFunc(entries, func(E fs.DirEntry) bool { // remove those pesky .DS_Store files
if strings.Contains(E.Remote(), ".DS_Store") {
err := operations.DeleteFile(context.Background(), E.(fs.Object))
assert.NoError(t, err)
return true
}
return false
})
require.Equal(t, len(items), entries.Len())
// sort by CONVERTED name
slices.SortStableFunc(items, func(a, b fstest.Item) int {
aConv := transform.Path(ctx, a.Path, false)
bConv := transform.Path(ctx, b.Path, false)
return cmp.Compare(aConv, bConv)
})
slices.SortStableFunc(entries, func(a, b fs.DirEntry) int {
return cmp.Compare(a.Remote(), b.Remote())
})
for i, e := range entries {
expect := transform.Path(ctx, items[i].Path, false)
msg := fmt.Sprintf("expected %v, got %v", detectEncoding(expect), detectEncoding(e.Remote()))
assert.Equal(t, expect, e.Remote(), msg)
}
}
func detectEncoding(s string) string {
if norm.NFC.IsNormalString(s) && norm.NFD.IsNormalString(s) {
return "BOTH"
}
if !norm.NFC.IsNormalString(s) && norm.NFD.IsNormalString(s) {
return "NFD"
}
if norm.NFC.IsNormalString(s) && !norm.NFD.IsNormalString(s) {
return "NFC"
}
return "OTHER"
}
func TestTransformCopy(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "all,suffix_keep_extension=_somesuffix")
require.NoError(t, err)
file1 := r.WriteFile("sub dir/hello world.txt", "hello world", t1)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, fstest.NewItem("sub dir_somesuffix/hello world_somesuffix.txt", "hello world", t1))
}
func TestDoubleTransform(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "all,prefix=tac", "all,prefix=tic")
require.NoError(t, err)
file1 := r.WriteFile("toe/toe", "hello world", t1)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, fstest.NewItem("tictactoe/tictactoe", "hello world", t1))
}
func TestFileTag(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "file,prefix=tac", "file,prefix=tic")
require.NoError(t, err)
file1 := r.WriteFile("toe/toe/toe", "hello world", t1)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, fstest.NewItem("toe/toe/tictactoe", "hello world", t1))
}
func TestNoTag(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "prefix=tac", "prefix=tic")
require.NoError(t, err)
file1 := r.WriteFile("toe/toe/toe", "hello world", t1)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, fstest.NewItem("toe/toe/tictactoe", "hello world", t1))
}
func TestDirTag(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "dir,prefix=tac", "dir,prefix=tic")
require.NoError(t, err)
r.WriteFile("toe/toe/toe.txt", "hello world", t1)
_, err = operations.MkdirModTime(ctx, r.Flocal, "empty_dir", t1)
require.NoError(t, err)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalListing(t, []fstest.Item{fstest.NewItem("toe/toe/toe.txt", "hello world", t1)}, []string{"empty_dir", "toe", "toe/toe"})
r.CheckRemoteListing(t, []fstest.Item{fstest.NewItem("tictactoe/tictactoe/toe.txt", "hello world", t1)}, []string{"tictacempty_dir", "tictactoe", "tictactoe/tictactoe"})
}
func TestAllTag(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "all,prefix=tac", "all,prefix=tic")
require.NoError(t, err)
r.WriteFile("toe/toe/toe.txt", "hello world", t1)
_, err = operations.MkdirModTime(ctx, r.Flocal, "empty_dir", t1)
require.NoError(t, err)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalListing(t, []fstest.Item{fstest.NewItem("toe/toe/toe.txt", "hello world", t1)}, []string{"empty_dir", "toe", "toe/toe"})
r.CheckRemoteListing(t, []fstest.Item{fstest.NewItem("tictactoe/tictactoe/tictactoe.txt", "hello world", t1)}, []string{"tictacempty_dir", "tictactoe", "tictactoe/tictactoe"})
err = operations.Check(ctx, &operations.CheckOpt{Fsrc: r.Flocal, Fdst: r.Fremote}) // should not error even though dst has transformed names
assert.NoError(t, err)
}
func TestRunTwice(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "dir,prefix=tac", "dir,prefix=tic")
require.NoError(t, err)
file1 := r.WriteFile("toe/toe/toe.txt", "hello world", t1)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, fstest.NewItem("tictactoe/tictactoe/toe.txt", "hello world", t1))
// result should not change second time, since src is unchanged
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, fstest.NewItem("tictactoe/tictactoe/toe.txt", "hello world", t1))
}
func TestSyntax(t *testing.T) {
ctx := context.Background()
err := transform.SetOptions(ctx, "prefix")
assert.Error(t, err) // should error as required value is missing
err = transform.SetOptions(ctx, "banana")
assert.Error(t, err) // should error as unrecognized option
err = transform.SetOptions(ctx, "=123")
assert.Error(t, err) // should error as required key is missing
err = transform.SetOptions(ctx, "prefix=123")
assert.NoError(t, err) // should not error
}
func TestConflicting(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "prefix=tac", "trimprefix=tac")
require.NoError(t, err)
file1 := r.WriteFile("toe/toe/toe", "hello world", t1)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
// should result in no change as prefix and trimprefix cancel out
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, fstest.NewItem("toe/toe/toe", "hello world", t1))
}
func TestMove(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "all,prefix=tac", "all,prefix=tic")
require.NoError(t, err)
r.WriteFile("toe/toe/toe.txt", "hello world", t1)
_, err = operations.MkdirModTime(ctx, r.Flocal, "empty_dir", t1)
require.NoError(t, err)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = MoveDir(ctx, r.Fremote, r.Flocal, true, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalListing(t, []fstest.Item{}, []string{})
r.CheckRemoteListing(t, []fstest.Item{fstest.NewItem("tictactoe/tictactoe/tictactoe.txt", "hello world", t1)}, []string{"tictacempty_dir", "tictactoe", "tictactoe/tictactoe"})
}
func TestTransformFile(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "all,prefix=tac", "all,prefix=tic")
require.NoError(t, err)
r.WriteFile("toe/toe/toe.txt", "hello world", t1)
_, err = operations.MkdirModTime(ctx, r.Flocal, "empty_dir", t1)
require.NoError(t, err)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = MoveDir(ctx, r.Fremote, r.Flocal, true, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalListing(t, []fstest.Item{}, []string{})
r.CheckRemoteListing(t, []fstest.Item{fstest.NewItem("tictactoe/tictactoe/tictactoe.txt", "hello world", t1)}, []string{"tictacempty_dir", "tictactoe", "tictactoe/tictactoe"})
err = transform.SetOptions(ctx, "all,trimprefix=tic", "all,trimprefix=tac")
require.NoError(t, err)
err = operations.TransformFile(ctx, r.Fremote, "tictactoe/tictactoe/tictactoe.txt")
require.NoError(t, err)
r.CheckLocalListing(t, []fstest.Item{}, []string{})
r.CheckRemoteListing(t, []fstest.Item{fstest.NewItem("toe/toe/toe.txt", "hello world", t1)}, []string{"tictacempty_dir", "tictactoe", "tictactoe/tictactoe", "toe", "toe/toe"})
}
func TestManualTransformFile(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
r.Flocal.Features().DisableList([]string{"Copy", "Move"})
r.Fremote.Features().DisableList([]string{"Copy", "Move"})
err := transform.SetOptions(ctx, "all,prefix=tac", "all,prefix=tic")
require.NoError(t, err)
r.WriteFile("toe/toe/toe.txt", "hello world", t1)
_, err = operations.MkdirModTime(ctx, r.Flocal, "empty_dir", t1)
require.NoError(t, err)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = MoveDir(ctx, r.Fremote, r.Flocal, true, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalListing(t, []fstest.Item{}, []string{})
r.CheckRemoteListing(t, []fstest.Item{fstest.NewItem("tictactoe/tictactoe/tictactoe.txt", "hello world", t1)}, []string{"tictacempty_dir", "tictactoe", "tictactoe/tictactoe"})
err = transform.SetOptions(ctx, "all,trimprefix=tic", "all,trimprefix=tac")
require.NoError(t, err)
err = operations.TransformFile(ctx, r.Fremote, "tictactoe/tictactoe/tictactoe.txt")
require.NoError(t, err)
r.CheckLocalListing(t, []fstest.Item{}, []string{})
r.CheckRemoteListing(t, []fstest.Item{fstest.NewItem("toe/toe/toe.txt", "hello world", t1)}, []string{"tictacempty_dir", "tictactoe", "tictactoe/tictactoe", "toe", "toe/toe"})
}
func TestBase64(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "all,base64encode")
require.NoError(t, err)
file1 := r.WriteFile("toe/toe/toe.txt", "hello world", t1)
r.Mkdir(ctx, r.Fremote)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, fstest.NewItem("dG9l/dG9l/dG9lLnR4dA==", "hello world", t1))
// round trip
err = transform.SetOptions(ctx, "all,base64decode")
require.NoError(t, err)
ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Flocal, r.Fremote, true)
testLoggerVsLsf(ctx, r.Flocal, r.Fremote, operations.GetLoggerOpt(ctx).JSON, t)
require.NoError(t, err)
r.CheckLocalItems(t, file1)
r.CheckRemoteItems(t, fstest.NewItem("dG9l/dG9l/dG9lLnR4dA==", "hello world", t1))
}
func TestError(t *testing.T) {
ctx := context.Background()
r := fstest.NewRun(t)
err := transform.SetOptions(ctx, "all,prefix=ta/c") // has illegal character
require.NoError(t, err)
file1 := r.WriteFile("toe/toe/toe", "hello world", t1)
r.Mkdir(ctx, r.Fremote)
// ctx = predictDstFromLogger(ctx)
err = Sync(ctx, r.Fremote, r.Flocal, true)
// testLoggerVsLsf(ctx, r.Fremote, r.Flocal, operations.GetLoggerOpt(ctx).JSON, t)
assert.Error(t, err)
accounting.GlobalStats().ResetCounters()
r.CheckLocalListing(t, []fstest.Item{file1}, []string{"toe", "toe/toe"})
r.CheckRemoteListing(t, []fstest.Item{file1}, []string{"toe", "toe/toe"})
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/sync/sync.go | fs/sync/sync.go | // Package sync is the implementation of sync/copy/move
package sync
import (
"context"
"errors"
"fmt"
"path"
"slices"
"sort"
"strings"
"sync"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/filter"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/march"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/lib/errcount"
"github.com/rclone/rclone/lib/transform"
"golang.org/x/sync/errgroup"
)
// ErrorMaxDurationReached defines error when transfer duration is reached
// Used for checking on exit and matching to correct exit code.
var ErrorMaxDurationReached = errors.New("max transfer duration reached as set by --max-duration")
// ErrorMaxDurationReachedFatal is returned from when the max
// duration limit is reached.
var ErrorMaxDurationReachedFatal = fserrors.FatalError(ErrorMaxDurationReached)
type syncCopyMove struct {
// parameters
fdst fs.Fs
fsrc fs.Fs
deleteMode fs.DeleteMode // how we are doing deletions
DoMove bool
copyEmptySrcDirs bool
deleteEmptySrcDirs bool
dir string
// internal state
ci *fs.ConfigInfo // global config
fi *filter.Filter // filter config
ctx context.Context // internal context for controlling go-routines
cancel func() // cancel the context
inCtx context.Context // internal context for controlling march
inCancel func() // cancel the march context
noTraverse bool // if set don't traverse the dst
noCheckDest bool // if set transfer all objects regardless without checking dst
noUnicodeNormalization bool // don't normalize unicode characters in filenames
deletersWg sync.WaitGroup // for delete before go routine
deleteFilesCh chan fs.Object // channel to receive deletes if delete before
trackRenames bool // set if we should do server-side renames
trackRenamesStrategy trackRenamesStrategy // strategies used for tracking renames
dstFilesMu sync.Mutex // protect dstFiles
dstFiles map[string]fs.Object // dst files, always filled
srcFiles map[string]fs.Object // src files, only used if deleteBefore
srcFilesChan chan fs.Object // passes src objects
srcFilesResult chan error // error result of src listing
dstFilesResult chan error // error result of dst listing
dstEmptyDirsMu sync.Mutex // protect dstEmptyDirs
dstEmptyDirs map[string]fs.DirEntry // potentially empty directories
srcEmptyDirsMu sync.Mutex // protect srcEmptyDirs
srcEmptyDirs map[string]fs.DirEntry // potentially empty directories
srcMoveEmptyDirs map[string]fs.DirEntry // potentially empty directories when moving files out of them
checkerWg sync.WaitGroup // wait for checkers
toBeChecked *pipe // checkers channel
transfersWg sync.WaitGroup // wait for transfers
toBeUploaded *pipe // copiers channel
errorMu sync.Mutex // Mutex covering the errors variables
err error // normal error from copy process
noRetryErr error // error with NoRetry set
fatalErr error // fatal error
commonHash hash.Type // common hash type between src and dst
modifyWindow time.Duration // modify window between fsrc, fdst
renameMapMu sync.Mutex // mutex to protect the below
renameMap map[string][]fs.Object // dst files by hash - only used by trackRenames
renamerWg sync.WaitGroup // wait for renamers
toBeRenamed *pipe // renamers channel
trackRenamesWg sync.WaitGroup // wg for background track renames
trackRenamesCh chan fs.Object // objects are pumped in here
renameCheck []fs.Object // accumulate files to check for rename here
compareCopyDest []fs.Fs // place to check for files to server side copy
backupDir fs.Fs // place to store overwrites/deletes
checkFirst bool // if set run all the checkers before starting transfers
maxDurationEndTime time.Time // end time if --max-duration is set
logger operations.LoggerFn // LoggerFn used to report the results of a sync (or bisync) to an io.Writer
usingLogger bool // whether we are using logger
setDirMetadata bool // if set we set the directory metadata
setDirModTime bool // if set we set the directory modtimes
setDirModTimeAfter bool // if set we set the directory modtimes at the end of the sync
setDirModTimeMu sync.Mutex // protect setDirModTimes and modifiedDirs
setDirModTimes []setDirModTime // directories that need their modtime set
setDirModTimesMaxLevel int // max level of the directories to set
modifiedDirs map[string]struct{} // dirs with changed contents (if s.setDirModTimeAfter)
allowOverlap bool // whether we allow src and dst to overlap (i.e. for convmv)
}
// For keeping track of delayed modtime sets
type setDirModTime struct {
src fs.Directory
dst fs.Directory
dir string
modTime time.Time
level int // the level of the directory, 0 is root
}
type trackRenamesStrategy byte
const (
trackRenamesStrategyHash trackRenamesStrategy = 1 << iota
trackRenamesStrategyModtime
trackRenamesStrategyLeaf
)
func (strategy trackRenamesStrategy) hash() bool {
return (strategy & trackRenamesStrategyHash) != 0
}
func (strategy trackRenamesStrategy) modTime() bool {
return (strategy & trackRenamesStrategyModtime) != 0
}
func (strategy trackRenamesStrategy) leaf() bool {
return (strategy & trackRenamesStrategyLeaf) != 0
}
func newSyncCopyMove(ctx context.Context, fdst, fsrc fs.Fs, deleteMode fs.DeleteMode, DoMove bool, deleteEmptySrcDirs bool, copyEmptySrcDirs bool, allowOverlap bool) (*syncCopyMove, error) {
if (deleteMode != fs.DeleteModeOff || DoMove) && operations.OverlappingFilterCheck(ctx, fdst, fsrc) && !allowOverlap {
return nil, fserrors.FatalError(fs.ErrorOverlapping)
}
ci := fs.GetConfig(ctx)
fi := filter.GetConfig(ctx)
s := &syncCopyMove{
ci: ci,
fi: fi,
fdst: fdst,
fsrc: fsrc,
deleteMode: deleteMode,
DoMove: DoMove,
copyEmptySrcDirs: copyEmptySrcDirs,
deleteEmptySrcDirs: deleteEmptySrcDirs,
dir: "",
srcFilesChan: make(chan fs.Object, ci.Checkers+ci.Transfers),
srcFilesResult: make(chan error, 1),
dstFilesResult: make(chan error, 1),
dstEmptyDirs: make(map[string]fs.DirEntry),
srcEmptyDirs: make(map[string]fs.DirEntry),
srcMoveEmptyDirs: make(map[string]fs.DirEntry),
noTraverse: ci.NoTraverse,
noCheckDest: ci.NoCheckDest,
noUnicodeNormalization: ci.NoUnicodeNormalization,
deleteFilesCh: make(chan fs.Object, ci.Checkers),
trackRenames: ci.TrackRenames,
commonHash: fsrc.Hashes().Overlap(fdst.Hashes()).GetOne(),
modifyWindow: fs.GetModifyWindow(ctx, fsrc, fdst),
trackRenamesCh: make(chan fs.Object, ci.Checkers),
checkFirst: ci.CheckFirst,
setDirMetadata: ci.Metadata && fsrc.Features().ReadDirMetadata && fdst.Features().WriteDirMetadata,
setDirModTime: (!ci.NoUpdateDirModTime && fsrc.Features().CanHaveEmptyDirectories) && (fdst.Features().WriteDirSetModTime || fdst.Features().MkdirMetadata != nil || fdst.Features().DirSetModTime != nil),
setDirModTimeAfter: !ci.NoUpdateDirModTime && (!copyEmptySrcDirs || fsrc.Features().CanHaveEmptyDirectories && fdst.Features().DirModTimeUpdatesOnWrite),
modifiedDirs: make(map[string]struct{}),
allowOverlap: allowOverlap,
}
s.logger, s.usingLogger = operations.GetLogger(ctx)
if deleteMode == fs.DeleteModeOff {
loggerOpt := operations.GetLoggerOpt(ctx)
loggerOpt.DeleteModeOff = true
loggerOpt.LoggerFn = s.logger
ctx = operations.WithLoggerOpt(ctx, loggerOpt)
}
backlog := ci.MaxBacklog
if s.checkFirst {
fs.Infof(s.fdst, "Running all checks before starting transfers")
backlog = -1
}
var err error
s.toBeChecked, err = newPipe(ci.OrderBy, accounting.Stats(ctx).SetCheckQueue, backlog)
if err != nil {
return nil, err
}
s.toBeUploaded, err = newPipe(ci.OrderBy, accounting.Stats(ctx).SetTransferQueue, backlog)
if err != nil {
return nil, err
}
s.toBeRenamed, err = newPipe(ci.OrderBy, accounting.Stats(ctx).SetRenameQueue, backlog)
if err != nil {
return nil, err
}
if ci.MaxDuration > 0 {
s.maxDurationEndTime = time.Now().Add(time.Duration(ci.MaxDuration))
fs.Infof(s.fdst, "Transfer session %v deadline: %s", ci.CutoffMode, s.maxDurationEndTime.Format("2006/01/02 15:04:05"))
}
// If a max session duration has been defined add a deadline
// to the main context if cutoff mode is hard. This will cut
// the transfers off.
if !s.maxDurationEndTime.IsZero() && ci.CutoffMode == fs.CutoffModeHard {
s.ctx, s.cancel = context.WithDeadline(ctx, s.maxDurationEndTime)
} else {
s.ctx, s.cancel = context.WithCancel(ctx)
}
// Input context - cancel this for graceful stop.
//
// If a max session duration has been defined add a deadline
// to the input context if cutoff mode is graceful or soft.
// This won't stop the transfers but will cut the
// list/check/transfer pipelines.
if !s.maxDurationEndTime.IsZero() && ci.CutoffMode != fs.CutoffModeHard {
s.inCtx, s.inCancel = context.WithDeadline(s.ctx, s.maxDurationEndTime)
} else {
s.inCtx, s.inCancel = context.WithCancel(s.ctx)
}
if s.noTraverse && s.deleteMode != fs.DeleteModeOff {
if !fi.HaveFilesFrom() {
fs.Errorf(nil, "Ignoring --no-traverse with sync")
}
s.noTraverse = false
}
s.trackRenamesStrategy, err = parseTrackRenamesStrategy(ci.TrackRenamesStrategy)
if err != nil {
return nil, err
}
if s.noCheckDest {
if s.deleteMode != fs.DeleteModeOff {
return nil, errors.New("can't use --no-check-dest with sync: use copy instead")
}
if ci.Immutable {
return nil, errors.New("can't use --no-check-dest with --immutable")
}
if s.backupDir != nil {
return nil, errors.New("can't use --no-check-dest with --backup-dir")
}
}
if s.trackRenames {
// Don't track renames for remotes without server-side move support.
if !operations.CanServerSideMove(fdst) {
fs.Errorf(fdst, "Ignoring --track-renames as the destination does not support server-side move or copy")
s.trackRenames = false
}
if s.trackRenamesStrategy.hash() && s.commonHash == hash.None {
fs.Errorf(fdst, "Ignoring --track-renames as the source and destination do not have a common hash")
s.trackRenames = false
}
if s.trackRenamesStrategy.modTime() && s.modifyWindow == fs.ModTimeNotSupported {
fs.Errorf(fdst, "Ignoring --track-renames as either the source or destination do not support modtime")
s.trackRenames = false
}
if s.deleteMode == fs.DeleteModeOff {
fs.Errorf(fdst, "Ignoring --track-renames as it doesn't work with copy or move, only sync")
s.trackRenames = false
}
}
if s.trackRenames {
// track renames needs delete after
if s.deleteMode != fs.DeleteModeOff {
s.deleteMode = fs.DeleteModeAfter
}
if s.noTraverse {
fs.Errorf(nil, "Ignoring --no-traverse with --track-renames")
s.noTraverse = false
}
}
// Make Fs for --backup-dir if required
if ci.BackupDir != "" || ci.Suffix != "" {
var err error
s.backupDir, err = operations.BackupDir(ctx, fdst, fsrc, "")
if err != nil {
return nil, err
}
}
if len(ci.CompareDest) > 0 {
var err error
s.compareCopyDest, err = operations.GetCompareDest(ctx)
if err != nil {
return nil, err
}
} else if len(ci.CopyDest) > 0 {
var err error
s.compareCopyDest, err = operations.GetCopyDest(ctx, fdst)
if err != nil {
return nil, err
}
}
return s, nil
}
// Check to see if the context has been cancelled
func (s *syncCopyMove) aborting() bool {
return s.ctx.Err() != nil
}
// This reads the map and pumps it into the channel passed in, closing
// the channel at the end
func (s *syncCopyMove) pumpMapToChan(files map[string]fs.Object, out chan<- fs.Object) {
outer:
for _, o := range files {
if s.aborting() {
break outer
}
select {
case out <- o:
case <-s.ctx.Done():
break outer
}
}
close(out)
s.srcFilesResult <- nil
}
// This checks the types of errors returned while copying files
func (s *syncCopyMove) processError(err error) {
if err == nil {
return
}
if err == context.DeadlineExceeded {
err = fserrors.NoRetryError(err)
} else if err == accounting.ErrorMaxTransferLimitReachedGraceful {
if s.inCtx.Err() == nil {
fs.Logf(nil, "%v - stopping transfers", err)
// Cancel the march and stop the pipes
s.inCancel()
}
} else if err == context.Canceled && s.inCtx.Err() != nil {
// Ignore context Canceled if we have called s.inCancel()
return
}
s.errorMu.Lock()
defer s.errorMu.Unlock()
switch {
case fserrors.IsFatalError(err):
if !s.aborting() {
fs.Errorf(nil, "Cancelling sync due to fatal error: %v", err)
s.cancel()
}
s.fatalErr = err
case fserrors.IsNoRetryError(err):
s.noRetryErr = err
default:
s.err = err
}
}
// Returns the current error (if any) in the order of precedence
//
// fatalErr
// normal error
// noRetryErr
func (s *syncCopyMove) currentError() error {
s.errorMu.Lock()
defer s.errorMu.Unlock()
if s.fatalErr != nil {
return s.fatalErr
}
if s.err != nil {
return s.err
}
return s.noRetryErr
}
// pairChecker reads Objects~s on in send to out if they need transferring.
//
// FIXME potentially doing lots of hashes at once
func (s *syncCopyMove) pairChecker(in *pipe, out *pipe, fraction int, wg *sync.WaitGroup) {
defer wg.Done()
for {
pair, ok := in.GetMax(s.inCtx, fraction)
if !ok {
return
}
src := pair.Src
var err error
tr := accounting.Stats(s.ctx).NewCheckingTransfer(src, "checking")
// Check to see if can store this
if src.Storable() {
needTransfer := operations.NeedTransfer(s.ctx, pair.Dst, pair.Src)
if needTransfer {
NoNeedTransfer, err := operations.CompareOrCopyDest(s.ctx, s.fdst, pair.Dst, pair.Src, s.compareCopyDest, s.backupDir)
if err != nil {
s.processError(err)
s.logger(s.ctx, operations.TransferError, pair.Src, pair.Dst, err)
}
if NoNeedTransfer {
needTransfer = false
}
}
// Fix case for case insensitive filesystems
if s.ci.FixCase && !s.ci.Immutable && src.Remote() != pair.Dst.Remote() {
if newDst, err := operations.Move(s.ctx, s.fdst, nil, src.Remote(), pair.Dst); err != nil {
fs.Errorf(pair.Dst, "Error while attempting to rename to %s: %v", src.Remote(), err)
s.processError(err)
} else {
fs.Infof(pair.Dst, "Fixed case by renaming to: %s", src.Remote())
pair.Dst = newDst
}
}
if needTransfer {
// If files are treated as immutable, fail if destination exists and does not match
if s.ci.Immutable && pair.Dst != nil {
err := fs.CountError(s.ctx, fserrors.NoRetryError(fs.ErrorImmutableModified))
fs.Errorf(pair.Dst, "Source and destination exist but do not match: %v", err)
s.processError(err)
} else {
if pair.Dst != nil {
s.markDirModifiedObject(pair.Dst)
} else {
s.markDirModifiedObject(src)
}
// If destination already exists, then we must move it into --backup-dir if required
if pair.Dst != nil && s.backupDir != nil {
err := operations.MoveBackupDir(s.ctx, s.backupDir, pair.Dst)
if err != nil {
s.processError(err)
s.logger(s.ctx, operations.TransferError, pair.Src, pair.Dst, err)
} else {
// If successful zero out the dst as it is no longer there and copy the file
pair.Dst = nil
ok = out.Put(s.inCtx, pair)
if !ok {
return
}
}
} else {
ok = out.Put(s.inCtx, pair)
if !ok {
return
}
}
}
} else {
// If moving need to delete the files we don't need to copy
if s.DoMove {
// Delete src if no error on copy
if operations.SameObject(src, pair.Dst) {
fs.Logf(src, "Not removing source file as it is the same file as the destination")
} else if s.ci.IgnoreExisting {
fs.Debugf(src, "Not removing source file as destination file exists and --ignore-existing is set")
} else if s.checkFirst && s.ci.OrderBy != "" {
// If we want perfect ordering then use the transfers to delete the file
//
// We send src == dst, to say we want the src deleted
ok = out.Put(s.inCtx, fs.ObjectPair{Src: src, Dst: src})
if !ok {
return
}
} else {
deleteFileErr := operations.DeleteFile(s.ctx, src)
s.processError(deleteFileErr)
s.logger(s.ctx, operations.TransferError, pair.Src, pair.Dst, deleteFileErr)
}
}
}
}
tr.Done(s.ctx, err)
}
}
// pairRenamer reads Objects~s on in and attempts to rename them,
// otherwise it sends them out if they need transferring.
func (s *syncCopyMove) pairRenamer(in *pipe, out *pipe, fraction int, wg *sync.WaitGroup) {
defer wg.Done()
for {
pair, ok := in.GetMax(s.inCtx, fraction)
if !ok {
return
}
src := pair.Src
if !s.tryRename(src) {
// pass on if not renamed
fs.Debugf(src, "Need to transfer - No matching file found at Destination")
ok = out.Put(s.inCtx, pair)
if !ok {
return
}
}
}
}
// pairCopyOrMove reads Objects on in and moves or copies them.
func (s *syncCopyMove) pairCopyOrMove(ctx context.Context, in *pipe, fdst fs.Fs, fraction int, wg *sync.WaitGroup) {
defer wg.Done()
var err error
for {
pair, ok := in.GetMax(s.inCtx, fraction)
if !ok {
return
}
src := pair.Src
dst := pair.Dst
if s.DoMove {
if src != dst {
_, err = operations.MoveTransfer(ctx, fdst, dst, src.Remote(), src)
} else {
// src == dst signals delete the src
err = operations.DeleteFile(ctx, src)
}
} else {
_, err = operations.Copy(ctx, fdst, dst, src.Remote(), src)
}
s.processError(err)
if err != nil {
s.logger(ctx, operations.TransferError, src, dst, err)
}
}
}
// This starts the background checkers.
func (s *syncCopyMove) startCheckers() {
s.checkerWg.Add(s.ci.Checkers)
for i := range s.ci.Checkers {
fraction := (100 * i) / s.ci.Checkers
go s.pairChecker(s.toBeChecked, s.toBeUploaded, fraction, &s.checkerWg)
}
}
// This stops the background checkers
func (s *syncCopyMove) stopCheckers() {
s.toBeChecked.Close()
fs.Debugf(s.fdst, "Waiting for checks to finish")
s.checkerWg.Wait()
}
// This starts the background transfers
func (s *syncCopyMove) startTransfers() {
s.transfersWg.Add(s.ci.Transfers)
for i := range s.ci.Transfers {
fraction := (100 * i) / s.ci.Transfers
go s.pairCopyOrMove(s.ctx, s.toBeUploaded, s.fdst, fraction, &s.transfersWg)
}
}
// This stops the background transfers
func (s *syncCopyMove) stopTransfers() {
s.toBeUploaded.Close()
fs.Debugf(s.fdst, "Waiting for transfers to finish")
s.transfersWg.Wait()
}
// This starts the background renamers.
func (s *syncCopyMove) startRenamers() {
if !s.trackRenames {
return
}
s.renamerWg.Add(s.ci.Checkers)
for i := range s.ci.Checkers {
fraction := (100 * i) / s.ci.Checkers
go s.pairRenamer(s.toBeRenamed, s.toBeUploaded, fraction, &s.renamerWg)
}
}
// This stops the background renamers
func (s *syncCopyMove) stopRenamers() {
if !s.trackRenames {
return
}
s.toBeRenamed.Close()
fs.Debugf(s.fdst, "Waiting for renames to finish")
s.renamerWg.Wait()
}
// This starts the collection of possible renames
func (s *syncCopyMove) startTrackRenames() {
if !s.trackRenames {
return
}
s.trackRenamesWg.Add(1)
go func() {
defer s.trackRenamesWg.Done()
for o := range s.trackRenamesCh {
s.renameCheck = append(s.renameCheck, o)
}
}()
}
// This stops the background rename collection
func (s *syncCopyMove) stopTrackRenames() {
if !s.trackRenames {
return
}
close(s.trackRenamesCh)
s.trackRenamesWg.Wait()
}
// This starts the background deletion of files for --delete-during
func (s *syncCopyMove) startDeleters() {
if s.deleteMode != fs.DeleteModeDuring && s.deleteMode != fs.DeleteModeOnly {
return
}
s.deletersWg.Add(1)
go func() {
defer s.deletersWg.Done()
err := operations.DeleteFilesWithBackupDir(s.ctx, s.deleteFilesCh, s.backupDir)
s.processError(err)
}()
}
// This stops the background deleters
func (s *syncCopyMove) stopDeleters() {
if s.deleteMode != fs.DeleteModeDuring && s.deleteMode != fs.DeleteModeOnly {
return
}
close(s.deleteFilesCh)
s.deletersWg.Wait()
}
// This deletes the files in the dstFiles map. If checkSrcMap is set
// then it checks to see if they exist first in srcFiles the source
// file map, otherwise it unconditionally deletes them. If
// checkSrcMap is clear then it assumes that the any source files that
// have been found have been removed from dstFiles already.
func (s *syncCopyMove) deleteFiles(checkSrcMap bool) error {
if accounting.Stats(s.ctx).Errored() && !s.ci.IgnoreErrors {
fs.Errorf(s.fdst, "%v", fs.ErrorNotDeleting)
// log all deletes as errors
for remote, o := range s.dstFiles {
if checkSrcMap {
_, exists := s.srcFiles[remote]
if exists {
continue
}
}
s.logger(s.ctx, operations.TransferError, nil, o, fs.ErrorNotDeleting)
}
return fs.ErrorNotDeleting
}
// Delete the spare files
toDelete := make(fs.ObjectsChan, s.ci.Checkers)
go func() {
outer:
for remote, o := range s.dstFiles {
if checkSrcMap {
_, exists := s.srcFiles[remote]
if exists {
continue
}
}
if s.aborting() {
break
}
select {
case <-s.ctx.Done():
break outer
case toDelete <- o:
}
}
close(toDelete)
}()
return operations.DeleteFilesWithBackupDir(s.ctx, toDelete, s.backupDir)
}
// This deletes the empty directories in the slice passed in. It
// ignores any errors deleting directories
func (s *syncCopyMove) deleteEmptyDirectories(ctx context.Context, f fs.Fs, entriesMap map[string]fs.DirEntry) error {
if len(entriesMap) == 0 {
return nil
}
if accounting.Stats(ctx).Errored() && !s.ci.IgnoreErrors {
fs.Errorf(f, "%v", fs.ErrorNotDeletingDirs)
return fs.ErrorNotDeletingDirs
}
var entries fs.DirEntries
for _, entry := range entriesMap {
entries = append(entries, entry)
}
// Now delete the empty directories starting from the longest path
sort.Sort(entries)
var errorCount int
var okCount int
for i := len(entries) - 1; i >= 0; i-- {
entry := entries[i]
dir, ok := entry.(fs.Directory)
if ok {
// TryRmdir only deletes empty directories
err := operations.TryRmdir(ctx, f, dir.Remote())
if err != nil {
fs.Debugf(fs.LogDirName(f, dir.Remote()), "Failed to Rmdir: %v", err)
errorCount++
} else {
okCount++
}
} else {
fs.Errorf(f, "Not a directory: %v", entry)
}
}
if errorCount > 0 {
fs.Debugf(f, "failed to delete %d directories", errorCount)
}
if okCount > 0 {
fs.Debugf(f, "deleted %d directories", okCount)
}
return nil
}
// mark the parent of entry as not empty and if entry is a directory mark it as potentially empty.
func (s *syncCopyMove) markParentNotEmpty(entry fs.DirEntry) {
s.srcEmptyDirsMu.Lock()
defer s.srcEmptyDirsMu.Unlock()
// Mark entry as potentially empty if it is a directory
_, isDir := entry.(fs.Directory)
if isDir {
s.srcEmptyDirs[entry.Remote()] = entry
// if DoMove and --delete-empty-src-dirs flag is set then record the parent but
// don't remove any as we are about to move files out of them them making the
// directory empty.
if s.DoMove && s.deleteEmptySrcDirs {
s.srcMoveEmptyDirs[entry.Remote()] = entry
}
}
parentDir := path.Dir(entry.Remote())
if isDir && s.copyEmptySrcDirs {
// Mark its parent as not empty
if parentDir == "." {
parentDir = ""
}
delete(s.srcEmptyDirs, parentDir)
}
if !isDir {
// Mark ALL its parents as not empty
for {
if parentDir == "." {
parentDir = ""
}
delete(s.srcEmptyDirs, parentDir)
if parentDir == "" || parentDir == "/" {
break
}
parentDir = path.Dir(parentDir)
}
}
}
// parseTrackRenamesStrategy turns a config string into a trackRenamesStrategy
func parseTrackRenamesStrategy(strategies string) (strategy trackRenamesStrategy, err error) {
if len(strategies) == 0 {
return strategy, nil
}
for s := range strings.SplitSeq(strategies, ",") {
switch s {
case "hash":
strategy |= trackRenamesStrategyHash
case "modtime":
strategy |= trackRenamesStrategyModtime
case "leaf":
strategy |= trackRenamesStrategyLeaf
case "size":
// ignore
default:
return strategy, fmt.Errorf("unknown track renames strategy %q", s)
}
}
return strategy, nil
}
// renameID makes a string with the size and the other identifiers of the requested rename strategies
//
// it may return an empty string in which case no hash could be made
func (s *syncCopyMove) renameID(obj fs.Object, renamesStrategy trackRenamesStrategy, precision time.Duration) string {
var builder strings.Builder
fmt.Fprintf(&builder, "%d", obj.Size())
if renamesStrategy.hash() {
var err error
hash, err := obj.Hash(s.ctx, s.commonHash)
if err != nil {
fs.Debugf(obj, "Hash failed: %v", err)
return ""
}
if hash == "" {
return ""
}
builder.WriteRune(',')
builder.WriteString(hash)
}
// for renamesStrategy.modTime() we don't add to the hash but we check the times in
// popRenameMap
if renamesStrategy.leaf() {
builder.WriteRune(',')
builder.WriteString(path.Base(obj.Remote()))
}
return builder.String()
}
// pushRenameMap adds the object with hash to the rename map
func (s *syncCopyMove) pushRenameMap(hash string, obj fs.Object) {
s.renameMapMu.Lock()
s.renameMap[hash] = append(s.renameMap[hash], obj)
s.renameMapMu.Unlock()
}
// popRenameMap finds the object with hash and pop the first match from
// renameMap or returns nil if not found.
func (s *syncCopyMove) popRenameMap(hash string, src fs.Object) (dst fs.Object) {
s.renameMapMu.Lock()
defer s.renameMapMu.Unlock()
dsts, ok := s.renameMap[hash]
if ok && len(dsts) > 0 {
// Element to remove
i := 0
// If using track renames strategy modtime then we need to check the modtimes here
if s.trackRenamesStrategy.modTime() {
i = -1
srcModTime := src.ModTime(s.ctx)
for j, dst := range dsts {
dstModTime := dst.ModTime(s.ctx)
dt := dstModTime.Sub(srcModTime)
if dt < s.modifyWindow && dt > -s.modifyWindow {
i = j
break
}
}
// If nothing matched then return nil
if i < 0 {
return nil
}
}
// Remove the entry and return it
dst = dsts[i]
dsts = slices.Delete(dsts, i, i+1)
if len(dsts) > 0 {
s.renameMap[hash] = dsts
} else {
delete(s.renameMap, hash)
}
}
return dst
}
// makeRenameMap builds a map of the destination files by hash that
// match sizes in the slice of objects in s.renameCheck
func (s *syncCopyMove) makeRenameMap() {
fs.Infof(s.fdst, "Making map for --track-renames")
// first make a map of possible sizes we need to check
possibleSizes := map[int64]struct{}{}
for _, obj := range s.renameCheck {
possibleSizes[obj.Size()] = struct{}{}
}
// pump all the dstFiles into in
in := make(chan fs.Object, s.ci.Checkers)
go s.pumpMapToChan(s.dstFiles, in)
// now make a map of size,hash for all dstFiles
s.renameMap = make(map[string][]fs.Object)
var wg sync.WaitGroup
wg.Add(s.ci.Checkers)
for range s.ci.Checkers {
go func() {
defer wg.Done()
for obj := range in {
// only create hash for dst fs.Object if its size could match
if _, found := possibleSizes[obj.Size()]; found {
tr := accounting.Stats(s.ctx).NewCheckingTransfer(obj, "renaming")
hash := s.renameID(obj, s.trackRenamesStrategy, s.modifyWindow)
if hash != "" {
s.pushRenameMap(hash, obj)
}
tr.Done(s.ctx, nil)
}
}
}()
}
wg.Wait()
fs.Infof(s.fdst, "Finished making map for --track-renames")
}
// tryRename renames an src object when doing track renames if
// possible, it returns true if the object was renamed.
func (s *syncCopyMove) tryRename(src fs.Object) bool {
// Calculate the hash of the src object
hash := s.renameID(src, s.trackRenamesStrategy, fs.GetModifyWindow(s.ctx, s.fsrc, s.fdst))
if hash == "" {
return false
}
// Get a match on fdst
dst := s.popRenameMap(hash, src)
if dst == nil {
return false
}
// Find dst object we are about to overwrite if it exists
dstOverwritten, _ := s.fdst.NewObject(s.ctx, src.Remote())
// Rename dst to have name src.Remote()
_, err := operations.Move(s.ctx, s.fdst, dstOverwritten, src.Remote(), dst)
if err != nil {
fs.Debugf(src, "Failed to rename to %q: %v", dst.Remote(), err)
return false
}
// remove file from dstFiles if present
s.dstFilesMu.Lock()
delete(s.dstFiles, dst.Remote())
s.dstFilesMu.Unlock()
fs.Infof(src, "Renamed from %q", dst.Remote())
return true
}
// Syncs fsrc into fdst
//
// If Delete is true then it deletes any files in fdst that aren't in fsrc
//
// If DoMove is true then files will be moved instead of copied.
//
// dir is the start directory, "" for root
func (s *syncCopyMove) run() error {
if operations.Same(s.fdst, s.fsrc) && !s.allowOverlap {
fs.Errorf(s.fdst, "Nothing to do as source and destination are the same")
return nil
}
// Start background checking and transferring pipeline
s.startCheckers()
s.startRenamers()
if !s.checkFirst {
s.startTransfers()
}
s.startDeleters()
s.dstFiles = make(map[string]fs.Object)
s.startTrackRenames()
// set up a march over fdst and fsrc
m := &march.March{
Ctx: s.inCtx,
Fdst: s.fdst,
Fsrc: s.fsrc,
Dir: s.dir,
NoTraverse: s.noTraverse,
Callback: s,
DstIncludeAll: s.fi.Opt.DeleteExcluded,
NoCheckDest: s.noCheckDest,
NoUnicodeNormalization: s.noUnicodeNormalization,
}
s.processError(m.Run(s.ctx))
s.stopTrackRenames()
if s.trackRenames {
// Build the map of the remaining dstFiles by hash
s.makeRenameMap()
// Attempt renames for all the files which don't have a matching dst
for _, src := range s.renameCheck {
ok := s.toBeRenamed.Put(s.inCtx, fs.ObjectPair{Src: src, Dst: nil})
if !ok {
break
}
}
}
// Stop background checking and transferring pipeline
s.stopCheckers()
if s.checkFirst {
fs.Infof(s.fdst, "Checks finished, now starting transfers")
s.startTransfers()
}
s.stopRenamers()
s.stopTransfers()
s.stopDeleters()
// Delete files after
if s.deleteMode == fs.DeleteModeAfter {
if s.currentError() != nil && !s.ci.IgnoreErrors {
fs.Errorf(s.fdst, "%v", fs.ErrorNotDeleting)
} else {
s.processError(s.deleteFiles(false))
}
}
// Update modtimes for directories if necessary
if s.setDirModTime && s.setDirModTimeAfter {
s.processError(s.setDelayedDirModTimes(s.ctx))
}
// Prune empty directories
if s.deleteMode != fs.DeleteModeOff {
if s.currentError() != nil && !s.ci.IgnoreErrors {
fs.Errorf(s.fdst, "%v", fs.ErrorNotDeletingDirs)
} else {
s.processError(s.deleteEmptyDirectories(s.ctx, s.fdst, s.dstEmptyDirs))
}
}
// Delete empty fsrc subdirectories
// if DoMove and --delete-empty-src-dirs flag is set
if s.DoMove && s.deleteEmptySrcDirs {
// delete potentially empty subdirectories that were part of the move
s.processError(s.deleteEmptyDirectories(s.ctx, s.fsrc, s.srcMoveEmptyDirs))
}
// Read the error out of the contexts if there is one
s.processError(s.ctx.Err())
s.processError(s.inCtx.Err())
// If the duration was exceeded then add a Fatal Error so we don't retry
if !s.maxDurationEndTime.IsZero() && time.Since(s.maxDurationEndTime) > 0 {
fs.Errorf(s.fdst, "%v", ErrorMaxDurationReachedFatal)
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | true |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/sync/pipe_test.go | fs/sync/pipe_test.go | package sync
import (
"container/heap"
"context"
"sync"
"sync/atomic"
"testing"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest/mockobject"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Check interface satisfied
var _ heap.Interface = (*pipe)(nil)
func TestPipe(t *testing.T) {
var queueLength int
var queueSize int64
stats := func(n int, size int64) {
queueLength, queueSize = n, size
}
// Make a new pipe
p, err := newPipe("", stats, 10)
require.NoError(t, err)
checkStats := func(expectedN int, expectedSize int64) {
n, size := p.Stats()
assert.Equal(t, expectedN, n)
assert.Equal(t, expectedSize, size)
assert.Equal(t, expectedN, queueLength)
assert.Equal(t, expectedSize, queueSize)
}
checkStats(0, 0)
ctx := context.Background()
obj1 := mockobject.New("potato").WithContent([]byte("hello"), mockobject.SeekModeNone)
pair1 := fs.ObjectPair{Src: obj1, Dst: nil}
pairD := fs.ObjectPair{Src: obj1, Dst: obj1} // this object should not count to the stats
// Put an object
ok := p.Put(ctx, pair1)
assert.Equal(t, true, ok)
checkStats(1, 5)
// Put an object to be deleted
ok = p.Put(ctx, pairD)
assert.Equal(t, true, ok)
checkStats(2, 5)
// Close the pipe showing reading on closed pipe is OK
p.Close()
// Read from pipe
pair2, ok := p.Get(ctx)
assert.Equal(t, pair1, pair2)
assert.Equal(t, true, ok)
checkStats(1, 0)
// Read from pipe
pair2, ok = p.Get(ctx)
assert.Equal(t, pairD, pair2)
assert.Equal(t, true, ok)
checkStats(0, 0)
// Check read on closed pipe
pair2, ok = p.Get(ctx)
assert.Equal(t, fs.ObjectPair{}, pair2)
assert.Equal(t, false, ok)
// Check panic on write to closed pipe
assert.Panics(t, func() { p.Put(ctx, pair1) })
// Make a new pipe
p, err = newPipe("", stats, 10)
require.NoError(t, err)
ctx2, cancel := context.WithCancel(ctx)
// cancel it in the background - check read ceases
go cancel()
pair2, ok = p.Get(ctx2)
assert.Equal(t, fs.ObjectPair{}, pair2)
assert.Equal(t, false, ok)
// check we can't write
ok = p.Put(ctx2, pair1)
assert.Equal(t, false, ok)
}
// TestPipeConcurrent runs concurrent Get and Put to flush out any
// race conditions and concurrency problems.
func TestPipeConcurrent(t *testing.T) {
const (
N = 1000
readWriters = 10
)
stats := func(n int, size int64) {}
// Make a new pipe
p, err := newPipe("", stats, 10)
require.NoError(t, err)
var wg sync.WaitGroup
obj1 := mockobject.New("potato").WithContent([]byte("hello"), mockobject.SeekModeNone)
pair1 := fs.ObjectPair{Src: obj1, Dst: nil}
ctx := context.Background()
var count atomic.Int64
for range readWriters {
wg.Add(2)
go func() {
defer wg.Done()
for range N {
// Read from pipe
pair2, ok := p.Get(ctx)
assert.Equal(t, pair1, pair2)
assert.Equal(t, true, ok)
count.Add(-1)
}
}()
go func() {
defer wg.Done()
for range N {
// Put an object
ok := p.Put(ctx, pair1)
assert.Equal(t, true, ok)
count.Add(1)
}
}()
}
wg.Wait()
assert.Equal(t, int64(0), count.Load())
}
func TestPipeOrderBy(t *testing.T) {
var (
stats = func(n int, size int64) {}
ctx = context.Background()
obj1 = mockobject.New("b").WithContent([]byte("1"), mockobject.SeekModeNone)
obj2 = mockobject.New("a").WithContent([]byte("22"), mockobject.SeekModeNone)
pair1 = fs.ObjectPair{Src: obj1}
pair2 = fs.ObjectPair{Src: obj2}
)
for _, test := range []struct {
orderBy string
swapped1 bool
swapped2 bool
fraction int
}{
{"", false, true, -1},
{"size", false, false, -1},
{"name", true, true, -1},
{"modtime", false, true, -1},
{"size,ascending", false, false, -1},
{"name,asc", true, true, -1},
{"modtime,ascending", false, true, -1},
{"size,descending", true, true, -1},
{"name,desc", false, false, -1},
{"modtime,descending", true, false, -1},
{"size,mixed,50", false, false, 25},
{"size,mixed,51", true, true, 75},
} {
t.Run(test.orderBy, func(t *testing.T) {
p, err := newPipe(test.orderBy, stats, 10)
require.NoError(t, err)
readAndCheck := func(swapped bool) {
var readFirst, readSecond fs.ObjectPair
var ok1, ok2 bool
if test.fraction < 0 {
readFirst, ok1 = p.Get(ctx)
readSecond, ok2 = p.Get(ctx)
} else {
readFirst, ok1 = p.GetMax(ctx, test.fraction)
readSecond, ok2 = p.GetMax(ctx, test.fraction)
}
assert.True(t, ok1)
assert.True(t, ok2)
if swapped {
assert.True(t, readFirst == pair2 && readSecond == pair1)
} else {
assert.True(t, readFirst == pair1 && readSecond == pair2)
}
}
ok := p.Put(ctx, pair1)
assert.True(t, ok)
ok = p.Put(ctx, pair2)
assert.True(t, ok)
readAndCheck(test.swapped1)
// insert other way round
ok = p.Put(ctx, pair2)
assert.True(t, ok)
ok = p.Put(ctx, pair1)
assert.True(t, ok)
readAndCheck(test.swapped2)
})
}
}
func TestNewLess(t *testing.T) {
t.Run("blankOK", func(t *testing.T) {
less, _, err := newLess("")
require.NoError(t, err)
assert.Nil(t, less)
})
t.Run("tooManyParts", func(t *testing.T) {
_, _, err := newLess("size,asc,toomanyparts")
require.Error(t, err)
assert.Contains(t, err.Error(), "bad --order-by string")
})
t.Run("tooManyParts2", func(t *testing.T) {
_, _, err := newLess("size,mixed,50,toomanyparts")
require.Error(t, err)
assert.Contains(t, err.Error(), "bad --order-by string")
})
t.Run("badMixed", func(t *testing.T) {
_, _, err := newLess("size,mixed,32.7")
require.Error(t, err)
assert.Contains(t, err.Error(), "bad mixed fraction")
})
t.Run("unknownComparison", func(t *testing.T) {
_, _, err := newLess("potato")
require.Error(t, err)
assert.Contains(t, err.Error(), "unknown --order-by comparison")
})
t.Run("unknownSortDirection", func(t *testing.T) {
_, _, err := newLess("name,sideways")
require.Error(t, err)
assert.Contains(t, err.Error(), "unknown --order-by sort direction")
})
var (
obj1 = mockobject.New("b").WithContent([]byte("1"), mockobject.SeekModeNone)
obj2 = mockobject.New("a").WithContent([]byte("22"), mockobject.SeekModeNone)
pair1 = fs.ObjectPair{Src: obj1}
pair2 = fs.ObjectPair{Src: obj2}
)
for _, test := range []struct {
orderBy string
pair1LessPair2 bool
pair2LessPair1 bool
wantFraction int
}{
{"size", true, false, -1},
{"name", false, true, -1},
{"modtime", false, false, -1},
{"size,ascending", true, false, -1},
{"name,asc", false, true, -1},
{"modtime,ascending", false, false, -1},
{"size,descending", false, true, -1},
{"name,desc", true, false, -1},
{"modtime,descending", true, true, -1},
{"modtime,mixed", false, false, 50},
{"modtime,mixed,30", false, false, 30},
} {
t.Run(test.orderBy, func(t *testing.T) {
less, gotFraction, err := newLess(test.orderBy)
assert.Equal(t, test.wantFraction, gotFraction)
require.NoError(t, err)
require.NotNil(t, less)
pair1LessPair2 := less(pair1, pair2)
assert.Equal(t, test.pair1LessPair2, pair1LessPair2)
pair2LessPair1 := less(pair2, pair1)
assert.Equal(t, test.pair2LessPair1, pair2LessPair1)
})
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/sync/rc_test.go | fs/sync/rc_test.go | package sync
import (
"context"
"testing"
"github.com/rclone/rclone/fs/cache"
"github.com/rclone/rclone/fs/rc"
"github.com/rclone/rclone/fstest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func rcNewRun(t *testing.T, method string) (*fstest.Run, *rc.Call) {
if *fstest.RemoteName != "" {
t.Skip("Skipping test on non local remote")
}
r := fstest.NewRun(t)
call := rc.Calls.Get(method)
assert.NotNil(t, call)
cache.Put(r.LocalName, r.Flocal)
cache.Put(r.FremoteName, r.Fremote)
return r, call
}
// sync/copy: copy a directory from source remote to destination remote
func TestRcCopy(t *testing.T) {
r, call := rcNewRun(t, "sync/copy")
r.Mkdir(context.Background(), r.Fremote)
file1 := r.WriteBoth(context.Background(), "file1", "file1 contents", t1)
file2 := r.WriteFile("subdir/file2", "file2 contents", t2)
file3 := r.WriteObject(context.Background(), "subdir/subsubdir/file3", "file3 contents", t3)
r.CheckLocalItems(t, file1, file2)
r.CheckRemoteItems(t, file1, file3)
in := rc.Params{
"srcFs": r.LocalName,
"dstFs": r.FremoteName,
}
out, err := call.Fn(context.Background(), in)
require.NoError(t, err)
assert.Equal(t, rc.Params(nil), out)
r.CheckLocalItems(t, file1, file2)
r.CheckRemoteItems(t, file1, file2, file3)
}
// sync/move: move a directory from source remote to destination remote
func TestRcMove(t *testing.T) {
r, call := rcNewRun(t, "sync/move")
r.Mkdir(context.Background(), r.Fremote)
file1 := r.WriteBoth(context.Background(), "file1", "file1 contents", t1)
file2 := r.WriteFile("subdir/file2", "file2 contents", t2)
file3 := r.WriteObject(context.Background(), "subdir/subsubdir/file3", "file3 contents", t3)
r.CheckLocalItems(t, file1, file2)
r.CheckRemoteItems(t, file1, file3)
in := rc.Params{
"srcFs": r.LocalName,
"dstFs": r.FremoteName,
}
out, err := call.Fn(context.Background(), in)
require.NoError(t, err)
assert.Equal(t, rc.Params(nil), out)
r.CheckLocalItems(t)
r.CheckRemoteItems(t, file1, file2, file3)
}
// sync/sync: sync a directory from source remote to destination remote
func TestRcSync(t *testing.T) {
r, call := rcNewRun(t, "sync/sync")
r.Mkdir(context.Background(), r.Fremote)
file1 := r.WriteBoth(context.Background(), "file1", "file1 contents", t1)
file2 := r.WriteFile("subdir/file2", "file2 contents", t2)
file3 := r.WriteObject(context.Background(), "subdir/subsubdir/file3", "file3 contents", t3)
r.CheckLocalItems(t, file1, file2)
r.CheckRemoteItems(t, file1, file3)
in := rc.Params{
"srcFs": r.LocalName,
"dstFs": r.FremoteName,
}
out, err := call.Fn(context.Background(), in)
require.NoError(t, err)
assert.Equal(t, rc.Params(nil), out)
r.CheckLocalItems(t, file1, file2)
r.CheckRemoteItems(t, file1, file2)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/fs/sync/pipe.go | fs/sync/pipe.go | package sync
import (
"context"
"fmt"
"math/bits"
"strconv"
"strings"
"sync"
"github.com/aalpar/deheap"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/fserrors"
)
// compare two items for order by
type lessFn func(a, b fs.ObjectPair) bool
// pipe provides an unbounded channel like experience
//
// Note unlike channels these aren't strictly ordered.
type pipe struct {
mu sync.Mutex
c chan struct{}
queue []fs.ObjectPair
closed bool
totalSize int64
stats func(items int, totalSize int64)
less lessFn
fraction int
}
func newPipe(orderBy string, stats func(items int, totalSize int64), maxBacklog int) (*pipe, error) {
if maxBacklog < 0 {
maxBacklog = (1 << (bits.UintSize - 1)) - 1 // largest positive int
}
less, fraction, err := newLess(orderBy)
if err != nil {
return nil, fserrors.FatalError(err)
}
p := &pipe{
c: make(chan struct{}, maxBacklog),
stats: stats,
less: less,
fraction: fraction,
}
if p.less != nil {
deheap.Init(p)
}
return p, nil
}
// Len satisfy heap.Interface - must be called with lock held
func (p *pipe) Len() int {
return len(p.queue)
}
// Len satisfy heap.Interface - must be called with lock held
func (p *pipe) Less(i, j int) bool {
return p.less(p.queue[i], p.queue[j])
}
// Swap satisfy heap.Interface - must be called with lock held
func (p *pipe) Swap(i, j int) {
p.queue[i], p.queue[j] = p.queue[j], p.queue[i]
}
// Push satisfy heap.Interface - must be called with lock held
func (p *pipe) Push(item any) {
p.queue = append(p.queue, item.(fs.ObjectPair))
}
// Pop satisfy heap.Interface - must be called with lock held
func (p *pipe) Pop() any {
old := p.queue
n := len(old)
item := old[n-1]
old[n-1] = fs.ObjectPair{} // avoid memory leak
p.queue = old[0 : n-1]
return item
}
// Put a pair into the pipe
//
// It returns ok = false if the context was cancelled
//
// It will panic if you call it after Close()
//
// Note that pairs where src==dst aren't counted for stats
func (p *pipe) Put(ctx context.Context, pair fs.ObjectPair) (ok bool) {
if ctx.Err() != nil {
return false
}
p.mu.Lock()
if p.less == nil {
// no order-by
p.queue = append(p.queue, pair)
} else {
deheap.Push(p, pair)
}
size := pair.Src.Size()
if size > 0 && pair.Src != pair.Dst {
p.totalSize += size
}
p.stats(len(p.queue), p.totalSize)
p.mu.Unlock()
select {
case <-ctx.Done():
return false
case p.c <- struct{}{}:
}
return true
}
// Get a pair from the pipe
//
// If fraction is > the mixed fraction set in the pipe then it gets it
// from the other end of the heap if order-by is in effect
//
// It returns ok = false if the context was cancelled or Close() has
// been called.
func (p *pipe) GetMax(ctx context.Context, fraction int) (pair fs.ObjectPair, ok bool) {
if ctx.Err() != nil {
return
}
select {
case <-ctx.Done():
return
case _, ok = <-p.c:
if !ok {
return
}
}
p.mu.Lock()
if p.less == nil {
// no order-by
pair = p.queue[0]
p.queue[0] = fs.ObjectPair{} // avoid memory leak
p.queue = p.queue[1:]
} else if p.fraction < 0 || fraction < p.fraction {
pair = deheap.Pop(p).(fs.ObjectPair)
} else {
pair = deheap.PopMax(p).(fs.ObjectPair)
}
size := pair.Src.Size()
if size > 0 && pair.Src != pair.Dst {
p.totalSize -= size
}
if p.totalSize < 0 {
p.totalSize = 0
}
p.stats(len(p.queue), p.totalSize)
p.mu.Unlock()
return pair, true
}
// Get a pair from the pipe
//
// It returns ok = false if the context was cancelled or Close() has
// been called.
func (p *pipe) Get(ctx context.Context) (pair fs.ObjectPair, ok bool) {
return p.GetMax(ctx, -1)
}
// Stats reads the number of items in the queue and the totalSize
func (p *pipe) Stats() (items int, totalSize int64) {
p.mu.Lock()
items, totalSize = len(p.queue), p.totalSize
p.mu.Unlock()
return items, totalSize
}
// Close the pipe
//
// Writes to a closed pipe will panic as will double closing a pipe
func (p *pipe) Close() {
p.mu.Lock()
close(p.c)
p.closed = true
p.mu.Unlock()
}
// newLess returns a less function for the heap comparison or nil if
// one is not required
func newLess(orderBy string) (less lessFn, fraction int, err error) {
fraction = -1
if orderBy == "" {
return nil, fraction, nil
}
parts := strings.Split(strings.ToLower(orderBy), ",")
switch parts[0] {
case "name":
less = func(a, b fs.ObjectPair) bool {
return a.Src.Remote() < b.Src.Remote()
}
case "size":
less = func(a, b fs.ObjectPair) bool {
return a.Src.Size() < b.Src.Size()
}
case "modtime":
less = func(a, b fs.ObjectPair) bool {
ctx := context.Background()
return a.Src.ModTime(ctx).Before(b.Src.ModTime(ctx))
}
default:
return nil, fraction, fmt.Errorf("unknown --order-by comparison %q", parts[0])
}
descending := false
if len(parts) > 1 {
switch parts[1] {
case "ascending", "asc":
case "descending", "desc":
descending = true
case "mixed":
fraction = 50
if len(parts) > 2 {
fraction, err = strconv.Atoi(parts[2])
if err != nil {
return nil, fraction, fmt.Errorf("bad mixed fraction --order-by %q", parts[2])
}
}
default:
return nil, fraction, fmt.Errorf("unknown --order-by sort direction %q", parts[1])
}
}
if (fraction >= 0 && len(parts) > 3) || (fraction < 0 && len(parts) > 2) {
return nil, fraction, fmt.Errorf("bad --order-by string %q", orderBy)
}
if descending {
oldLess := less
less = func(a, b fs.ObjectPair) bool {
return !oldLess(a, b)
}
}
return less, fraction, nil
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/open_test.go | vfs/open_test.go | // Code generated by make_open_tests.go - use go generate to rebuild - DO NOT EDIT
package vfs
import (
"io"
"os"
)
// openTest describes a test of OpenFile
type openTest struct {
flags int
what string
openNonExistentErr error
readNonExistentErr error
writeNonExistentErr error
openExistingErr error
readExistingErr error
writeExistingErr error
contents string
}
// openTests is a suite of tests for OpenFile with all possible
// combination of flags. This obeys Unix semantics even on Windows.
var openTests = []openTest{
{
flags: os.O_RDONLY,
what: "os.O_RDONLY",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_TRUNC,
what: "os.O_RDONLY|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_SYNC,
what: "os.O_RDONLY|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDONLY|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_EXCL,
what: "os.O_RDONLY|os.O_EXCL",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_EXCL | os.O_TRUNC,
what: "os.O_RDONLY|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_EXCL | os.O_SYNC,
what: "os.O_RDONLY|os.O_EXCL|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_EXCL | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDONLY|os.O_EXCL|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_CREATE,
what: "os.O_RDONLY|os.O_CREATE",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: EBADF,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_CREATE | os.O_TRUNC,
what: "os.O_RDONLY|os.O_CREATE|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_CREATE | os.O_SYNC,
what: "os.O_RDONLY|os.O_CREATE|os.O_SYNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: EBADF,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_CREATE | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDONLY|os.O_CREATE|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_CREATE | os.O_EXCL,
what: "os.O_RDONLY|os.O_CREATE|os.O_EXCL",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: EBADF,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_CREATE | os.O_EXCL | os.O_TRUNC,
what: "os.O_RDONLY|os.O_CREATE|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_CREATE | os.O_EXCL | os.O_SYNC,
what: "os.O_RDONLY|os.O_CREATE|os.O_EXCL|os.O_SYNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: EBADF,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_CREATE | os.O_EXCL | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDONLY|os.O_CREATE|os.O_EXCL|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND,
what: "os.O_RDONLY|os.O_APPEND",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_TRUNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_SYNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_EXCL,
what: "os.O_RDONLY|os.O_APPEND|os.O_EXCL",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_EXCL | os.O_TRUNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_EXCL | os.O_SYNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_EXCL|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_EXCL | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_EXCL|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_CREATE,
what: "os.O_RDONLY|os.O_APPEND|os.O_CREATE",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: EBADF,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_CREATE | os.O_TRUNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_CREATE|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_CREATE | os.O_SYNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_CREATE|os.O_SYNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: EBADF,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: EBADF,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_CREATE | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_CREATE|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_CREATE | os.O_EXCL,
what: "os.O_RDONLY|os.O_APPEND|os.O_CREATE|os.O_EXCL",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: EBADF,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_CREATE | os.O_EXCL | os.O_TRUNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_CREATE|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_CREATE | os.O_EXCL | os.O_SYNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_CREATE|os.O_EXCL|os.O_SYNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: EBADF,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDONLY | os.O_APPEND | os.O_CREATE | os.O_EXCL | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDONLY|os.O_APPEND|os.O_CREATE|os.O_EXCL|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: EINVAL,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: EINVAL,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_WRONLY,
what: "os.O_WRONLY",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HELlo",
}, {
flags: os.O_WRONLY | os.O_TRUNC,
what: "os.O_WRONLY|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_SYNC,
what: "os.O_WRONLY|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HELlo",
}, {
flags: os.O_WRONLY | os.O_SYNC | os.O_TRUNC,
what: "os.O_WRONLY|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_EXCL,
what: "os.O_WRONLY|os.O_EXCL",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HELlo",
}, {
flags: os.O_WRONLY | os.O_EXCL | os.O_TRUNC,
what: "os.O_WRONLY|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_EXCL | os.O_SYNC,
what: "os.O_WRONLY|os.O_EXCL|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HELlo",
}, {
flags: os.O_WRONLY | os.O_EXCL | os.O_SYNC | os.O_TRUNC,
what: "os.O_WRONLY|os.O_EXCL|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_CREATE,
what: "os.O_WRONLY|os.O_CREATE",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HELlo",
}, {
flags: os.O_WRONLY | os.O_CREATE | os.O_TRUNC,
what: "os.O_WRONLY|os.O_CREATE|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_CREATE | os.O_SYNC,
what: "os.O_WRONLY|os.O_CREATE|os.O_SYNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HELlo",
}, {
flags: os.O_WRONLY | os.O_CREATE | os.O_SYNC | os.O_TRUNC,
what: "os.O_WRONLY|os.O_CREATE|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_CREATE | os.O_EXCL,
what: "os.O_WRONLY|os.O_CREATE|os.O_EXCL",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_WRONLY | os.O_CREATE | os.O_EXCL | os.O_TRUNC,
what: "os.O_WRONLY|os.O_CREATE|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_WRONLY | os.O_CREATE | os.O_EXCL | os.O_SYNC,
what: "os.O_WRONLY|os.O_CREATE|os.O_EXCL|os.O_SYNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_WRONLY | os.O_CREATE | os.O_EXCL | os.O_SYNC | os.O_TRUNC,
what: "os.O_WRONLY|os.O_CREATE|os.O_EXCL|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_WRONLY | os.O_APPEND,
what: "os.O_WRONLY|os.O_APPEND",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_TRUNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_SYNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_SYNC | os.O_TRUNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_EXCL,
what: "os.O_WRONLY|os.O_APPEND|os.O_EXCL",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_EXCL | os.O_TRUNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_EXCL | os.O_SYNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_EXCL|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_EXCL | os.O_SYNC | os.O_TRUNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_EXCL|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_CREATE,
what: "os.O_WRONLY|os.O_APPEND|os.O_CREATE",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_CREATE | os.O_TRUNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_CREATE | os.O_SYNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_SYNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_CREATE | os.O_SYNC | os.O_TRUNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: EBADF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_CREATE | os.O_EXCL,
what: "os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_EXCL",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_CREATE | os.O_EXCL | os.O_TRUNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_CREATE | os.O_EXCL | os.O_SYNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_EXCL|os.O_SYNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_WRONLY | os.O_APPEND | os.O_CREATE | os.O_EXCL | os.O_SYNC | os.O_TRUNC,
what: "os.O_WRONLY|os.O_APPEND|os.O_CREATE|os.O_EXCL|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: EBADF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDWR,
what: "os.O_RDWR",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "heHEL",
}, {
flags: os.O_RDWR | os.O_TRUNC,
what: "os.O_RDWR|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_SYNC,
what: "os.O_RDWR|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "heHEL",
}, {
flags: os.O_RDWR | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDWR|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_EXCL,
what: "os.O_RDWR|os.O_EXCL",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "heHEL",
}, {
flags: os.O_RDWR | os.O_EXCL | os.O_TRUNC,
what: "os.O_RDWR|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_EXCL | os.O_SYNC,
what: "os.O_RDWR|os.O_EXCL|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "heHEL",
}, {
flags: os.O_RDWR | os.O_EXCL | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDWR|os.O_EXCL|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_CREATE,
what: "os.O_RDWR|os.O_CREATE",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "heHEL",
}, {
flags: os.O_RDWR | os.O_CREATE | os.O_TRUNC,
what: "os.O_RDWR|os.O_CREATE|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_CREATE | os.O_SYNC,
what: "os.O_RDWR|os.O_CREATE|os.O_SYNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "heHEL",
}, {
flags: os.O_RDWR | os.O_CREATE | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDWR|os.O_CREATE|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_CREATE | os.O_EXCL,
what: "os.O_RDWR|os.O_CREATE|os.O_EXCL",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDWR | os.O_CREATE | os.O_EXCL | os.O_TRUNC,
what: "os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDWR | os.O_CREATE | os.O_EXCL | os.O_SYNC,
what: "os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDWR | os.O_CREATE | os.O_EXCL | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDWR|os.O_CREATE|os.O_EXCL|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDWR | os.O_APPEND,
what: "os.O_RDWR|os.O_APPEND",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_TRUNC,
what: "os.O_RDWR|os.O_APPEND|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_SYNC,
what: "os.O_RDWR|os.O_APPEND|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDWR|os.O_APPEND|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_EXCL,
what: "os.O_RDWR|os.O_APPEND|os.O_EXCL",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_EXCL | os.O_TRUNC,
what: "os.O_RDWR|os.O_APPEND|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_EXCL | os.O_SYNC,
what: "os.O_RDWR|os.O_APPEND|os.O_EXCL|os.O_SYNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_EXCL | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDWR|os.O_APPEND|os.O_EXCL|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: ENOENT,
readNonExistentErr: nil,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_CREATE,
what: "os.O_RDWR|os.O_APPEND|os.O_CREATE",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_CREATE | os.O_TRUNC,
what: "os.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_CREATE | os.O_SYNC,
what: "os.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_SYNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: nil,
writeExistingErr: nil,
contents: "helloHEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_CREATE | os.O_SYNC | os.O_TRUNC,
what: "os.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_SYNC|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: nil,
readExistingErr: io.EOF,
writeExistingErr: nil,
contents: "HEL",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_CREATE | os.O_EXCL,
what: "os.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_EXCL",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
writeExistingErr: nil,
contents: "hello",
}, {
flags: os.O_RDWR | os.O_APPEND | os.O_CREATE | os.O_EXCL | os.O_TRUNC,
what: "os.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_EXCL|os.O_TRUNC",
openNonExistentErr: nil,
readNonExistentErr: io.EOF,
writeNonExistentErr: nil,
openExistingErr: EEXIST,
readExistingErr: nil,
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | true |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/rc.go | vfs/rc.go | package vfs
import (
"context"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/cache"
"github.com/rclone/rclone/fs/rc"
"github.com/rclone/rclone/vfs/vfscache/writeback"
)
const getVFSHelp = `
This command takes an "fs" parameter. If this parameter is not
supplied and if there is only one VFS in use then that VFS will be
used. If there is more than one VFS in use then the "fs" parameter
must be supplied.`
// GetVFS gets a VFS with config name "fs" from the cache or returns an error.
//
// If "fs" is not set and there is one and only one VFS in the active
// cache then it returns it. This is for backwards compatibility.
//
// This deletes the "fs" parameter from in if it is valid
func getVFS(in rc.Params) (vfs *VFS, err error) {
fsString, err := in.GetString("fs")
if rc.IsErrParamNotFound(err) {
var count int
vfs, count = activeCacheEntries()
if count == 1 {
return vfs, nil
} else if count == 0 {
return nil, errors.New(`no VFS active and "fs" parameter not supplied`)
}
return nil, errors.New(`more than one VFS active - need "fs" parameter`)
} else if err != nil {
return nil, err
}
activeMu.Lock()
defer activeMu.Unlock()
fsString = cache.Canonicalize(fsString)
activeVFS := active[fsString]
if len(activeVFS) == 0 {
return nil, fmt.Errorf("no VFS found with name %q", fsString)
} else if len(activeVFS) > 1 {
return nil, fmt.Errorf("more than one VFS active with name %q", fsString)
}
delete(in, "fs") // delete the fs parameter
return activeVFS[0], nil
}
func init() {
rc.Add(rc.Call{
Path: "vfs/refresh",
Fn: rcRefresh,
Title: "Refresh the directory cache.",
Help: `
This reads the directories for the specified paths and freshens the
directory cache.
If no paths are passed in then it will refresh the root directory.
rclone rc vfs/refresh
Otherwise pass directories in as dir=path. Any parameter key
starting with dir will refresh that directory, e.g.
rclone rc vfs/refresh dir=home/junk dir2=data/misc
If the parameter recursive=true is given the whole directory tree
will get refreshed. This refresh will use --fast-list if enabled.
` + getVFSHelp,
})
}
func rcRefresh(ctx context.Context, in rc.Params) (out rc.Params, err error) {
vfs, err := getVFS(in)
if err != nil {
return nil, err
}
root, err := vfs.Root()
if err != nil {
return nil, err
}
getDir := func(path string) (*Dir, error) {
path = strings.Trim(path, "/")
segments := strings.Split(path, "/")
var node Node = root
for _, s := range segments {
if dir, ok := node.(*Dir); ok {
node, err = dir.stat(s)
if err != nil {
return nil, err
}
}
}
if dir, ok := node.(*Dir); ok {
return dir, nil
}
return nil, EINVAL
}
recursive := false
{
const k = "recursive"
if v, ok := in[k]; ok {
s, ok := v.(string)
if !ok {
return out, fmt.Errorf("value must be string %q=%v", k, v)
}
recursive, err = strconv.ParseBool(s)
if err != nil {
return out, fmt.Errorf("invalid value %q=%v", k, v)
}
delete(in, k)
}
}
result := map[string]string{}
if len(in) == 0 {
if recursive {
err = root.readDirTree()
} else {
err = root.readDir()
}
if err != nil {
result[""] = err.Error()
} else {
result[""] = "OK"
}
} else {
for k, v := range in {
path, ok := v.(string)
if !ok {
return out, fmt.Errorf("value must be string %q=%v", k, v)
}
if strings.HasPrefix(k, "dir") {
dir, err := getDir(path)
if err != nil {
result[path] = err.Error()
} else {
if recursive {
err = dir.readDirTree()
} else {
err = dir.readDir()
}
if err != nil {
result[path] = err.Error()
} else {
result[path] = "OK"
}
}
} else {
return out, fmt.Errorf("unknown key %q", k)
}
}
}
out = rc.Params{
"result": result,
}
return out, nil
}
// Add remote control for the VFS
func init() {
rc.Add(rc.Call{
Path: "vfs/forget",
Fn: rcForget,
Title: "Forget files or directories in the directory cache.",
Help: `
This forgets the paths in the directory cache causing them to be
re-read from the remote when needed.
If no paths are passed in then it will forget all the paths in the
directory cache.
rclone rc vfs/forget
Otherwise pass files or dirs in as file=path or dir=path. Any
parameter key starting with file will forget that file and any
starting with dir will forget that dir, e.g.
rclone rc vfs/forget file=hello file2=goodbye dir=home/junk
` + getVFSHelp,
})
}
func rcForget(ctx context.Context, in rc.Params) (out rc.Params, err error) {
vfs, err := getVFS(in)
if err != nil {
return nil, err
}
root, err := vfs.Root()
if err != nil {
return nil, err
}
forgotten := []string{}
if len(in) == 0 {
root.ForgetAll()
} else {
for k, v := range in {
path, ok := v.(string)
if !ok {
return out, fmt.Errorf("value must be string %q=%v", k, v)
}
path = strings.Trim(path, "/")
if strings.HasPrefix(k, "file") {
root.ForgetPath(path, fs.EntryObject)
} else if strings.HasPrefix(k, "dir") {
root.ForgetPath(path, fs.EntryDirectory)
} else {
return out, fmt.Errorf("unknown key %q", k)
}
forgotten = append(forgotten, path)
}
}
out = rc.Params{
"forgotten": forgotten,
}
return out, nil
}
func getDuration(k string, v any) (time.Duration, error) {
s, ok := v.(string)
if !ok {
return 0, fmt.Errorf("value must be string %q=%v", k, v)
}
interval, err := fs.ParseDuration(s)
if err != nil {
return 0, fmt.Errorf("parse duration: %w", err)
}
return interval, nil
}
func getInterval(in rc.Params) (time.Duration, bool, error) {
k := "interval"
v, ok := in[k]
if !ok {
return 0, false, nil
}
interval, err := getDuration(k, v)
if err != nil {
return 0, true, err
}
if interval < 0 {
return 0, true, errors.New("interval must be >= 0")
}
delete(in, k)
return interval, true, nil
}
func getTimeout(in rc.Params) (time.Duration, error) {
k := "timeout"
v, ok := in[k]
if !ok {
return 10 * time.Second, nil
}
timeout, err := getDuration(k, v)
if err != nil {
return 0, err
}
delete(in, k)
return timeout, nil
}
func getStatus(vfs *VFS, in rc.Params) (out rc.Params, err error) {
for k, v := range in {
return nil, fmt.Errorf("invalid parameter: %s=%s", k, v)
}
return rc.Params{
"enabled": vfs.Opt.PollInterval != 0,
"supported": vfs.pollChan != nil,
"interval": map[string]any{
"raw": vfs.Opt.PollInterval,
"seconds": time.Duration(vfs.Opt.PollInterval) / time.Second,
"string": vfs.Opt.PollInterval.String(),
},
}, nil
}
func init() {
rc.Add(rc.Call{
Path: "vfs/poll-interval",
Fn: rcPollInterval,
Title: "Get the status or update the value of the poll-interval option.",
Help: `
Without any parameter given this returns the current status of the
poll-interval setting.
When the interval=duration parameter is set, the poll-interval value
is updated and the polling function is notified.
Setting interval=0 disables poll-interval.
rclone rc vfs/poll-interval interval=5m
The timeout=duration parameter can be used to specify a time to wait
for the current poll function to apply the new value.
If timeout is less or equal 0, which is the default, wait indefinitely.
The new poll-interval value will only be active when the timeout is
not reached.
If poll-interval is updated or disabled temporarily, some changes
might not get picked up by the polling function, depending on the
used remote.
` + getVFSHelp,
})
}
func rcPollInterval(ctx context.Context, in rc.Params) (out rc.Params, err error) {
vfs, err := getVFS(in)
if err != nil {
return nil, err
}
interval, intervalPresent, err := getInterval(in)
if err != nil {
return nil, err
}
timeout, err := getTimeout(in)
if err != nil {
return nil, err
}
for k, v := range in {
return nil, fmt.Errorf("invalid parameter: %s=%s", k, v)
}
if vfs.pollChan == nil {
return nil, errors.New("poll-interval is not supported by this remote")
}
if !intervalPresent {
return getStatus(vfs, in)
}
var timeoutHit bool
var timeoutChan <-chan time.Time
if timeout > 0 {
timer := time.NewTimer(timeout)
defer timer.Stop()
timeoutChan = timer.C
}
select {
case vfs.pollChan <- interval:
vfs.Opt.PollInterval = fs.Duration(interval)
case <-timeoutChan:
timeoutHit = true
}
out, err = getStatus(vfs, in)
if out != nil {
out["timeout"] = timeoutHit
}
return
}
func init() {
rc.Add(rc.Call{
Path: "vfs/list",
Title: "List active VFSes.",
Help: `
This lists the active VFSes.
It returns a list under the key "vfses" where the values are the VFS
names that could be passed to the other VFS commands in the "fs"
parameter.`,
Fn: rcList,
})
}
func rcList(ctx context.Context, in rc.Params) (out rc.Params, err error) {
activeMu.Lock()
defer activeMu.Unlock()
var names = []string{}
for name, vfses := range active {
if len(vfses) == 1 {
names = append(names, name)
} else {
for i := range vfses {
names = append(names, fmt.Sprintf("%s[%d]", name, i))
}
}
}
out = rc.Params{}
out["vfses"] = names
return out, nil
}
func init() {
rc.Add(rc.Call{
Path: "vfs/stats",
Title: "Stats for a VFS.",
Help: `
This returns stats for the selected VFS.
{
// Status of the disk cache - only present if --vfs-cache-mode > off
"diskCache": {
"bytesUsed": 0,
"erroredFiles": 0,
"files": 0,
"hashType": 1,
"outOfSpace": false,
"path": "/home/user/.cache/rclone/vfs/local/mnt/a",
"pathMeta": "/home/user/.cache/rclone/vfsMeta/local/mnt/a",
"uploadsInProgress": 0,
"uploadsQueued": 0
},
"fs": "/mnt/a",
"inUse": 1,
// Status of the in memory metadata cache
"metadataCache": {
"dirs": 1,
"files": 0
},
// Options as returned by options/get
"opt": {
"CacheMaxAge": 3600000000000,
// ...
"WriteWait": 1000000000
}
}
` + getVFSHelp,
Fn: rcStats,
})
}
func rcStats(ctx context.Context, in rc.Params) (out rc.Params, err error) {
vfs, err := getVFS(in)
if err != nil {
return nil, err
}
return vfs.Stats(), nil
}
func init() {
rc.Add(rc.Call{
Path: "vfs/queue",
Title: "Queue info for a VFS.",
Help: strings.ReplaceAll(`
This returns info about the upload queue for the selected VFS.
This is only useful if |--vfs-cache-mode| > off. If you call it when
the |--vfs-cache-mode| is off, it will return an empty result.
{
"queue": // an array of files queued for upload
[
{
"name": "file", // string: name (full path) of the file,
"id": 123, // integer: id of this item in the queue,
"size": 79, // integer: size of the file in bytes
"expiry": 1.5 // float: time until file is eligible for transfer, lowest goes first
"tries": 1, // integer: number of times we have tried to upload
"delay": 5.0, // float: seconds between upload attempts
"uploading": false, // boolean: true if item is being uploaded
},
],
}
The |expiry| time is the time until the file is eligible for being
uploaded in floating point seconds. This may go negative. As rclone
only transfers |--transfers| files at once, only the lowest
|--transfers| expiry times will have |uploading| as |true|. So there
may be files with negative expiry times for which |uploading| is
|false|.
`, "|", "`") + getVFSHelp,
Fn: rcQueue,
})
}
func rcQueue(ctx context.Context, in rc.Params) (out rc.Params, err error) {
vfs, err := getVFS(in)
if err != nil {
return nil, err
}
if vfs.cache == nil {
return nil, nil
}
return vfs.cache.Queue(), nil
}
func init() {
rc.Add(rc.Call{
Path: "vfs/queue-set-expiry",
Title: "Set the expiry time for an item queued for upload.",
Help: strings.ReplaceAll(`
Use this to adjust the |expiry| time for an item in the upload queue.
You will need to read the |id| of the item using |vfs/queue| before
using this call.
You can then set |expiry| to a floating point number of seconds from
now when the item is eligible for upload. If you want the item to be
uploaded as soon as possible then set it to a large negative number (eg
-1000000000). If you want the upload of the item to be delayed
for a long time then set it to a large positive number.
Setting the |expiry| of an item which has already has started uploading
will have no effect - the item will carry on being uploaded.
This will return an error if called with |--vfs-cache-mode| off or if
the |id| passed is not found.
This takes the following parameters
- |fs| - select the VFS in use (optional)
- |id| - a numeric ID as returned from |vfs/queue|
- |expiry| - a new expiry time as floating point seconds
- |relative| - if set, expiry is to be treated as relative to the current expiry (optional, boolean)
This returns an empty result on success, or an error.
`, "|", "`") + getVFSHelp,
Fn: rcQueueSetExpiry,
})
}
func rcQueueSetExpiry(ctx context.Context, in rc.Params) (out rc.Params, err error) {
vfs, err := getVFS(in)
if err != nil {
return nil, err
}
if vfs.cache == nil {
return nil, rc.NewErrParamInvalid(errors.New("can't call this unless using the VFS cache"))
}
// Read input values
id, err := in.GetInt64("id")
if err != nil {
return nil, err
}
expiry, err := in.GetFloat64("expiry")
if err != nil {
return nil, err
}
relative, err := in.GetBool("relative")
if err != nil && !rc.IsErrParamNotFound(err) {
return nil, err
}
// Set expiry
var refTime time.Time
if !relative {
refTime = time.Now()
}
err = vfs.cache.QueueSetExpiry(writeback.Handle(id), refTime, time.Duration(float64(time.Second)*expiry))
return nil, err
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/read_test.go | vfs/read_test.go | package vfs
import (
"context"
"io"
"os"
"testing"
"github.com/rclone/rclone/fstest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Open a file for write
func readHandleCreate(t *testing.T) (r *fstest.Run, vfs *VFS, fh *ReadFileHandle) {
r, vfs = newTestVFS(t)
file1 := r.WriteObject(context.Background(), "dir/file1", "0123456789abcdef", t1)
r.CheckRemoteItems(t, file1)
h, err := vfs.OpenFile("dir/file1", os.O_RDONLY, 0777)
require.NoError(t, err)
fh, ok := h.(*ReadFileHandle)
require.True(t, ok)
return r, vfs, fh
}
// read data from the string
func readString(t *testing.T, fh *ReadFileHandle, n int) string {
buf := make([]byte, n)
n, err := fh.Read(buf)
if err != io.EOF {
assert.NoError(t, err)
}
return string(buf[:n])
}
func TestReadFileHandleMethods(t *testing.T) {
_, _, fh := readHandleCreate(t)
// String
assert.Equal(t, "dir/file1 (r)", fh.String())
assert.Equal(t, "<nil *ReadFileHandle>", (*ReadFileHandle)(nil).String())
assert.Equal(t, "<nil *ReadFileHandle.file>", new(ReadFileHandle).String())
// Name
assert.Equal(t, "dir/file1", fh.Name())
// Node
node := fh.Node()
assert.Equal(t, "file1", node.Name())
// Size
assert.Equal(t, int64(16), fh.Size())
// Read 1
assert.Equal(t, "0", readString(t, fh, 1))
// Read remainder
assert.Equal(t, "123456789abcdef", readString(t, fh, 256))
// Read EOF
buf := make([]byte, 16)
_, err := fh.Read(buf)
assert.Equal(t, io.EOF, err)
// Stat
var fi os.FileInfo
fi, err = fh.Stat()
assert.NoError(t, err)
assert.Equal(t, int64(16), fi.Size())
assert.Equal(t, "file1", fi.Name())
// Close
assert.False(t, fh.closed)
assert.Equal(t, nil, fh.Close())
assert.True(t, fh.closed)
// Close again
assert.Equal(t, ECLOSED, fh.Close())
}
func TestReadFileHandleSeek(t *testing.T) {
_, _, fh := readHandleCreate(t)
assert.Equal(t, "0", readString(t, fh, 1))
// 0 means relative to the origin of the file,
n, err := fh.Seek(5, io.SeekStart)
assert.NoError(t, err)
assert.Equal(t, int64(5), n)
assert.Equal(t, "5", readString(t, fh, 1))
// 1 means relative to the current offset
n, err = fh.Seek(-3, io.SeekCurrent)
assert.NoError(t, err)
assert.Equal(t, int64(3), n)
assert.Equal(t, "3", readString(t, fh, 1))
// 2 means relative to the end.
n, err = fh.Seek(-3, io.SeekEnd)
assert.NoError(t, err)
assert.Equal(t, int64(13), n)
assert.Equal(t, "d", readString(t, fh, 1))
// Seek off the end
_, err = fh.Seek(100, io.SeekStart)
assert.NoError(t, err)
// Get the error on read
buf := make([]byte, 16)
l, err := fh.Read(buf)
assert.Equal(t, io.EOF, err)
assert.Equal(t, 0, l)
// Check if noSeek is set we get an error
fh.noSeek = true
_, err = fh.Seek(0, io.SeekStart)
assert.Equal(t, ESPIPE, err)
// Close
assert.Equal(t, nil, fh.Close())
}
func TestReadFileHandleReadAt(t *testing.T) {
_, _, fh := readHandleCreate(t)
// read from start
buf := make([]byte, 1)
n, err := fh.ReadAt(buf, 0)
require.NoError(t, err)
assert.Equal(t, 1, n)
assert.Equal(t, "0", string(buf[:n]))
// seek forwards
n, err = fh.ReadAt(buf, 5)
require.NoError(t, err)
assert.Equal(t, 1, n)
assert.Equal(t, "5", string(buf[:n]))
// seek backwards
n, err = fh.ReadAt(buf, 1)
require.NoError(t, err)
assert.Equal(t, 1, n)
assert.Equal(t, "1", string(buf[:n]))
// read exactly to the end
buf = make([]byte, 6)
n, err = fh.ReadAt(buf, 10)
require.NoError(t, err)
assert.Equal(t, 6, n)
assert.Equal(t, "abcdef", string(buf[:n]))
// read off the end
buf = make([]byte, 256)
n, err = fh.ReadAt(buf, 10)
assert.Equal(t, io.EOF, err)
assert.Equal(t, 6, n)
assert.Equal(t, "abcdef", string(buf[:n]))
// read starting off the end
n, err = fh.ReadAt(buf, 100)
assert.Equal(t, io.EOF, err)
assert.Equal(t, 0, n)
// check noSeek gives an error
fh.noSeek = true
_, err = fh.ReadAt(buf, 100)
assert.Equal(t, ESPIPE, err)
// Properly close the file
assert.NoError(t, fh.Close())
// check reading on closed file
fh.noSeek = true
_, err = fh.ReadAt(buf, 100)
assert.Equal(t, ECLOSED, err)
}
func TestReadFileHandleFlush(t *testing.T) {
_, _, fh := readHandleCreate(t)
// Check Flush does nothing if read not called
err := fh.Flush()
assert.NoError(t, err)
assert.False(t, fh.closed)
// Read data
buf := make([]byte, 256)
n, err := fh.Read(buf)
assert.Equal(t, io.EOF, err)
assert.Equal(t, 16, n)
// Check Flush does nothing if read called
err = fh.Flush()
assert.NoError(t, err)
assert.False(t, fh.closed)
// Check flush does nothing if called again
err = fh.Flush()
assert.NoError(t, err)
assert.False(t, fh.closed)
// Properly close the file
assert.NoError(t, fh.Close())
}
func TestReadFileHandleRelease(t *testing.T) {
_, _, fh := readHandleCreate(t)
// Check Release does nothing if file not read from
err := fh.Release()
assert.NoError(t, err)
assert.False(t, fh.closed)
// Read data
buf := make([]byte, 256)
n, err := fh.Read(buf)
assert.Equal(t, io.EOF, err)
assert.Equal(t, 16, n)
// Check Release closes file
err = fh.Release()
assert.NoError(t, err)
assert.True(t, fh.closed)
// Check Release does nothing if called again
err = fh.Release()
assert.NoError(t, err)
assert.True(t, fh.closed)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/file.go | vfs/file.go | package vfs
import (
"context"
"errors"
"fmt"
"io"
"os"
"path"
"strings"
"sync"
"sync/atomic"
"time"
"slices"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/log"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/vfs/vfscommon"
)
// The File object is tightly coupled to the Dir object. Since they
// both have locks there is plenty of potential for deadlocks. In
// order to mitigate this, we use the following conventions
//
// File may **only** call these methods from Dir with the File lock
// held.
//
// Dir.Fs
// Dir.VFS
//
// (As these are read only and do not need to take the Dir mutex.)
//
// File may **not** call any other Dir methods with the File lock
// held. This preserves total lock ordering and makes File subordinate
// to Dir as far as locking is concerned, preventing deadlocks.
//
// File may **not** read any members of Dir directly.
// File represents a file or a symlink
type File struct {
inode uint64 // inode number - read only
size atomic.Int64 // size of file
muRW sync.Mutex // synchronize RWFileHandle.openPending(), RWFileHandle.close() and File.Remove
mu sync.RWMutex // protects the following
d *Dir // parent directory
dPath string // path of parent directory. NB dir rename means all Files are flushed
o fs.Object // NB o may be nil if file is being written
leaf string // leaf name of the object
writers []Handle // writers for this file
virtualModTime *time.Time // modtime for backends with Precision == fs.ModTimeNotSupported
pendingModTime time.Time // will be applied once o becomes available, i.e. after file was written
pendingRenameFun func(ctx context.Context) error // will be run/renamed after all writers close
sys atomic.Value // user defined info to be attached here
nwriters atomic.Int32 // len(writers)
appendMode bool // file was opened with O_APPEND
isLink bool // file represents a symlink
}
// newFile creates a new File
//
// o may be nil
func newFile(d *Dir, dPath string, o fs.Object, leaf string) *File {
f := &File{
d: d,
dPath: dPath,
o: o,
leaf: leaf,
inode: newInode(),
}
if o != nil {
f.size.Store(o.Size())
}
f._setIsLink()
return f
}
// Set whether this is a link or not based on f.o
func (f *File) _setIsLink() {
if f.o == nil {
return
}
f.isLink = f.d.vfs.Opt.Links && strings.HasSuffix(f.o.Remote(), fs.LinkSuffix)
}
// String converts it to printable
func (f *File) String() string {
if f == nil {
return "<nil *File>"
}
return f.Path()
}
// IsFile returns true for File - satisfies Node interface
func (f *File) IsFile() bool {
return true
}
// IsDir returns false for File - satisfies Node interface
func (f *File) IsDir() bool {
return false
}
// IsSymlink returns true for symlinks when --links is enabled
func (f *File) IsSymlink() bool {
f.mu.RLock()
defer f.mu.RUnlock()
return f.isLink
}
// setSymlink marks this File as being a symlink
func (f *File) setSymlink() {
f.mu.RLock()
f.isLink = true
f.mu.RUnlock()
}
// Mode bits of the file or directory - satisfies Node interface
func (f *File) Mode() (mode os.FileMode) {
f.mu.RLock()
defer f.mu.RUnlock()
if f.isLink {
mode = os.FileMode(f.d.vfs.Opt.LinkPerms)
} else {
mode = os.FileMode(f.d.vfs.Opt.FilePerms)
if f.appendMode {
mode |= os.ModeAppend
}
}
return mode
}
// Name (base) of the directory - satisfies Node interface
func (f *File) Name() (name string) {
f.mu.RLock()
defer f.mu.RUnlock()
return f.leaf
}
// _path returns the full path of the file
// use when lock is held
func (f *File) _path() string {
return path.Join(f.dPath, f.leaf)
}
// Path returns the full path of the file
func (f *File) Path() string {
f.mu.RLock()
dPath, leaf := f.dPath, f.leaf
f.mu.RUnlock()
return path.Join(dPath, leaf)
}
// _fixCachePath returns fullPath with the fs.LinkSuffix added if appropriate
// use when lock is held
func (f *File) _fixCachePath(fullPath string) string {
if !f.isLink {
return fullPath
}
return fullPath + fs.LinkSuffix
}
// _cachePath returns the full path of the file with the fs.LinkSuffix if appropriate
// use when lock is held
func (f *File) _cachePath() string {
dPath, leaf := f.dPath, f.leaf
if f.isLink {
leaf += fs.LinkSuffix
}
return path.Join(dPath, leaf)
}
// CachePath returns the full path of the file with the fs.LinkSuffix if appropriate
//
// We use this path when storing files in the cache.
func (f *File) CachePath() string {
f.mu.RLock()
defer f.mu.RUnlock()
return f._cachePath()
}
// Sys returns underlying data source (can be nil) - satisfies Node interface
func (f *File) Sys() any {
return f.sys.Load()
}
// SetSys sets the underlying data source (can be nil) - satisfies Node interface
func (f *File) SetSys(x any) {
f.sys.Store(x)
}
// Inode returns the inode number - satisfies Node interface
func (f *File) Inode() uint64 {
return f.inode
}
// Node returns the Node associated with this - satisfies Noder interface
func (f *File) Node() Node {
return f
}
// renameDir - call when parent directory has been renamed
func (f *File) renameDir(dPath string) {
f.mu.RLock()
f.dPath = dPath
f.mu.RUnlock()
}
// applyPendingRename runs a previously set rename operation if there are no
// more remaining writers. Call without lock held.
func (f *File) applyPendingRename() {
f.mu.RLock()
fun := f.pendingRenameFun
writing := f._writingInProgress()
f.mu.RUnlock()
if fun == nil || writing {
return
}
fs.Debugf(f.Path(), "Running delayed rename now")
if err := fun(context.TODO()); err != nil {
fs.Errorf(f.Path(), "delayed File.Rename error: %v", err)
}
}
// rename attempts to immediately rename a file if there are no open writers.
// Otherwise it will queue the rename operation on the remote until no writers
// remain.
func (f *File) rename(ctx context.Context, destDir *Dir, newName string) error {
f.mu.RLock()
d := f.d
oldPendingRenameFun := f.pendingRenameFun
oldPath := f._cachePath()
newCacheName := f._fixCachePath(newName)
f.mu.RUnlock()
if features := d.Fs().Features(); features.Move == nil && features.Copy == nil {
err := fmt.Errorf("Fs %q can't rename files (no server-side Move or Copy)", d.Fs())
fs.Errorf(f.Path(), "Dir.Rename error: %v", err)
return err
}
// File.mu is unlocked here to call Dir.Path()
newPath := path.Join(destDir.Path(), newCacheName)
renameCall := func(ctx context.Context) (err error) {
// chain rename calls if any
if oldPendingRenameFun != nil {
err := oldPendingRenameFun(ctx)
if err != nil {
return err
}
}
f.mu.RLock()
o := f.o
d := f.d
f.mu.RUnlock()
var newObject fs.Object
// if o is nil then are writing the file so no need to rename the object
if o != nil {
if o.Remote() == newPath {
return nil // no need to rename
}
// do the move of the remote object
dstOverwritten, _ := d.Fs().NewObject(ctx, newPath)
newObject, err = operations.Move(ctx, d.Fs(), dstOverwritten, newPath, o)
if err != nil {
fs.Errorf(f.Path(), "File.Rename error: %v", err)
return err
}
// newObject can be nil here for example if --dry-run
if newObject == nil {
err = errors.New("rename failed: nil object returned")
fs.Errorf(f.Path(), "File.Rename %v", err)
return err
}
}
// Rename in the cache
if d.vfs.cache != nil && d.vfs.cache.Exists(oldPath) {
if err := d.vfs.cache.Rename(oldPath, newPath, newObject); err != nil {
fs.Infof(f.Path(), "File.Rename failed in Cache: %v", err)
}
}
// Update the node with the new details
fs.Debugf(f.Path(), "Updating file with %v %p", newObject, f)
// f.rename(destDir, newObject)
f.mu.Lock()
if newObject != nil {
f.o = newObject
f._setIsLink()
}
f.pendingRenameFun = nil
f.mu.Unlock()
return nil
}
// rename the file object
dPath := destDir.Path()
f.mu.Lock()
f.d = destDir
f.dPath = dPath
f.leaf = newName
writing := f._writingInProgress()
f.mu.Unlock()
// Delay the rename if not using RW caching. For the minimal case we
// need to look in the cache to see if caching is in use.
CacheMode := d.vfs.Opt.CacheMode
if writing &&
(CacheMode < vfscommon.CacheModeMinimal ||
(CacheMode == vfscommon.CacheModeMinimal && !destDir.vfs.cache.Exists(oldPath))) {
fs.Debugf(oldPath, "File is currently open, delaying rename %p", f)
f.mu.Lock()
f.pendingRenameFun = renameCall
f.mu.Unlock()
return nil
}
return renameCall(ctx)
}
// addWriter adds a write handle to the file
func (f *File) addWriter(h Handle) {
f.mu.Lock()
f.writers = append(f.writers, h)
f.nwriters.Add(1)
f.mu.Unlock()
}
// delWriter removes a write handle from the file
func (f *File) delWriter(h Handle) {
f.mu.Lock()
defer f.applyPendingRename()
defer f.mu.Unlock()
var found = -1
for i := range f.writers {
if f.writers[i] == h {
found = i
break
}
}
if found >= 0 {
f.writers = slices.Delete(f.writers, found, found+1)
f.nwriters.Add(-1)
} else {
fs.Debugf(f._path(), "File.delWriter couldn't find handle")
}
}
// activeWriters returns the number of writers on the file
//
// Note that we don't take the mutex here. If we do then we can get a
// deadlock.
func (f *File) activeWriters() int {
return int(f.nwriters.Load())
}
// _roundModTime rounds the time passed in to the Precision of the
// underlying Fs
//
// It should be called with the lock held
func (f *File) _roundModTime(modTime time.Time) time.Time {
precision := f.d.f.Precision()
if precision == fs.ModTimeNotSupported {
return modTime
}
return modTime.Truncate(precision)
}
// ModTime returns the modified time of the file
//
// if NoModTime is set then it returns the mod time of the directory
func (f *File) ModTime() (modTime time.Time) {
f.mu.RLock()
d, o, pendingModTime, virtualModTime := f.d, f.o, f.pendingModTime, f.virtualModTime
f.mu.RUnlock()
// Set the virtual modtime up for backends which don't support setting modtime
//
// Note that we only cache modtime values that we have returned to the OS
// if we haven't returned a value to the OS then we can change it
defer func() {
if f.d.f.Precision() == fs.ModTimeNotSupported && (virtualModTime == nil || !virtualModTime.Equal(modTime)) {
f.virtualModTime = &modTime
fs.Debugf(f._path(), "Set virtual modtime to %v", f.virtualModTime)
}
}()
if d.vfs.Opt.NoModTime {
return d.ModTime()
}
// Read the modtime from a dirty item if it exists
if f.d.vfs.Opt.CacheMode >= vfscommon.CacheModeMinimal {
if item := f.d.vfs.cache.DirtyItem(f._cachePath()); item != nil {
modTime, err := item.GetModTime()
if err != nil {
fs.Errorf(f._path(), "ModTime: Item GetModTime failed: %v", err)
} else {
return f._roundModTime(modTime)
}
}
}
if !pendingModTime.IsZero() {
return f._roundModTime(pendingModTime)
}
if virtualModTime != nil && !virtualModTime.IsZero() {
fs.Debugf(f._path(), "Returning virtual modtime %v", f.virtualModTime)
return f._roundModTime(*virtualModTime)
}
if o == nil {
return time.Now()
}
return o.ModTime(context.TODO())
}
// nonNegative returns 0 if i is -ve, i otherwise
func nonNegative(i int64) int64 {
if i >= 0 {
return i
}
return 0
}
// Size of the file
func (f *File) Size() int64 {
f.mu.RLock()
defer f.mu.RUnlock()
// Read the size from a dirty item if it exists
if f.d.vfs.Opt.CacheMode >= vfscommon.CacheModeMinimal {
if item := f.d.vfs.cache.DirtyItem(f._cachePath()); item != nil {
size, err := item.GetSize()
if err != nil {
fs.Errorf(f._path(), "Size: Item GetSize failed: %v", err)
} else {
return size
}
}
}
// if o is nil it isn't valid yet or there are writers, so return the size so far
if f._writingInProgress() {
return f.size.Load()
}
return nonNegative(f.o.Size())
}
// SetModTime sets the modtime for the file
//
// if NoModTime is set then it does nothing
func (f *File) SetModTime(modTime time.Time) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.d.vfs.Opt.NoModTime {
return nil
}
if f.d.vfs.Opt.ReadOnly {
return EROFS
}
f.pendingModTime = modTime
// set the time of the file in the cache
if f.d.vfs.cache != nil && f.d.vfs.cache.Exists(f._cachePath()) {
f.d.vfs.cache.SetModTime(f._cachePath(), f.pendingModTime)
}
// Only update the ModTime when there are no writers, setObject will do it
if !f._writingInProgress() {
return f._applyPendingModTime()
}
// queue up for later, hoping f.o becomes available
return nil
}
// Apply a pending mod time
// Call with the mutex held
func (f *File) _applyPendingModTime() error {
if f.pendingModTime.IsZero() {
return nil
}
defer func() { f.pendingModTime = time.Time{} }()
if f.o == nil {
return errors.New("cannot apply ModTime, file object is not available")
}
dt := f.pendingModTime.Sub(f.o.ModTime(context.Background()))
modifyWindow := f.o.Fs().Precision()
if dt < modifyWindow && dt > -modifyWindow {
fs.Debugf(f.o, "Not setting pending mod time %v as it is already set", f.pendingModTime)
return nil
}
// set the time of the object
err := f.o.SetModTime(context.TODO(), f.pendingModTime)
switch err {
case nil:
fs.Debugf(f.o, "Applied pending mod time %v OK", f.pendingModTime)
case fs.ErrorCantSetModTime, fs.ErrorCantSetModTimeWithoutDelete:
// do nothing, in order to not break "touch somefile" if it exists already
default:
fs.Errorf(f.o, "Failed to apply pending mod time %v: %v", f.pendingModTime, err)
return err
}
return nil
}
// Apply a pending mod time
func (f *File) applyPendingModTime() error {
f.mu.Lock()
defer f.mu.Unlock()
return f._applyPendingModTime()
}
// _writingInProgress returns true of there are any open writers
// Call with read lock held
func (f *File) _writingInProgress() bool {
return f.o == nil || len(f.writers) != 0
}
// writingInProgress returns true of there are any open writers
func (f *File) writingInProgress() bool {
f.mu.RLock()
defer f.mu.RUnlock()
return f.o == nil || len(f.writers) != 0
}
// Update the size while writing
func (f *File) setSize(n int64) {
f.size.Store(n)
}
// Update the object when written and add it to the directory
func (f *File) setObject(o fs.Object) {
f.mu.Lock()
f.o = o
f._setIsLink()
_ = f._applyPendingModTime()
d := f.d
f.mu.Unlock()
// Release File.mu before calling Dir method
d.addObject(f)
}
// Update the object but don't update the directory cache - for use by
// the directory cache
func (f *File) setObjectNoUpdate(o fs.Object) {
f.mu.Lock()
f.o = o
f._setIsLink()
f.virtualModTime = nil
fs.Debugf(f._path(), "Reset virtual modtime")
f.mu.Unlock()
}
// Get the current fs.Object - may be nil
func (f *File) getObject() fs.Object {
f.mu.RLock()
defer f.mu.RUnlock()
return f.o
}
// exists returns whether the file exists already
func (f *File) exists() bool {
f.mu.RLock()
defer f.mu.RUnlock()
return f.o != nil
}
// Wait for f.o to become non nil for a short time returning it or an
// error. Use when opening a read handle.
//
// Call without the mutex held
func (f *File) waitForValidObject() (o fs.Object, err error) {
for range 50 {
f.mu.RLock()
o = f.o
nwriters := len(f.writers)
f.mu.RUnlock()
if o != nil {
return o, nil
}
if nwriters == 0 {
return nil, errors.New("can't open file - writer failed")
}
time.Sleep(100 * time.Millisecond)
}
return nil, ENOENT
}
// openRead open the file for read
func (f *File) openRead() (fh *ReadFileHandle, err error) {
// if o is nil it isn't valid yet
_, err = f.waitForValidObject()
if err != nil {
return nil, err
}
// fs.Debugf(f.Path(), "File.openRead")
fh, err = newReadFileHandle(f)
if err != nil {
fs.Debugf(f.Path(), "File.openRead failed: %v", err)
return nil, err
}
return fh, nil
}
// openWrite open the file for write
func (f *File) openWrite(flags int) (fh *WriteFileHandle, err error) {
f.mu.RLock()
d := f.d
f.mu.RUnlock()
if d.vfs.Opt.ReadOnly {
return nil, EROFS
}
// fs.Debugf(f.Path(), "File.openWrite")
fh, err = newWriteFileHandle(d, f, f.Path(), flags)
if err != nil {
fs.Debugf(f.Path(), "File.openWrite failed: %v", err)
return nil, err
}
return fh, nil
}
// openRW open the file for read and write using a temporary file
//
// It uses the open flags passed in.
func (f *File) openRW(flags int) (fh *RWFileHandle, err error) {
f.mu.RLock()
d := f.d
f.mu.RUnlock()
// FIXME chunked
if flags&accessModeMask != os.O_RDONLY && d.vfs.Opt.ReadOnly {
return nil, EROFS
}
// fs.Debugf(f.Path(), "File.openRW")
fh, err = newRWFileHandle(d, f, flags)
if err != nil {
fs.Debugf(f.Path(), "File.openRW failed: %v", err)
return nil, err
}
return fh, nil
}
// Sync the file
//
// Note that we don't do anything except return OK
func (f *File) Sync() error {
return nil
}
// Remove the file
func (f *File) Remove() (err error) {
defer log.Trace(f.Path(), "")("err=%v", &err)
f.mu.RLock()
d := f.d
f.mu.RUnlock()
if d.vfs.Opt.ReadOnly {
return EROFS
}
// Remove the object from the cache
wasWriting := false
if d.vfs.cache != nil && d.vfs.cache.Exists(f.CachePath()) {
wasWriting = d.vfs.cache.Remove(f.CachePath())
}
f.muRW.Lock() // muRW must be locked before mu to avoid
f.mu.Lock() // deadlock in RWFileHandle.openPending and .close
if f.o != nil {
err = f.o.Remove(context.TODO())
}
f.mu.Unlock()
f.muRW.Unlock()
if err != nil {
if wasWriting {
// Ignore error deleting file if was writing it as it may not be uploaded yet
err = nil
fs.Debugf(f._path(), "Ignoring File.Remove file error as uploading: %v", err)
} else {
fs.Debugf(f._path(), "File.Remove file error: %v", err)
}
}
// Remove the item from the directory listing
// called with File.mu released when there is no error removing the underlying file
if err == nil {
d.delObject(f.Name())
}
return err
}
// RemoveAll the file - same as remove for files
func (f *File) RemoveAll() error {
return f.Remove()
}
// DirEntry returns the underlying fs.DirEntry - may be nil
func (f *File) DirEntry() (entry fs.DirEntry) {
f.mu.RLock()
defer f.mu.RUnlock()
return f.o
}
// Dir returns the directory this file is in
func (f *File) Dir() *Dir {
f.mu.RLock()
defer f.mu.RUnlock()
return f.d
}
// VFS returns the instance of the VFS
func (f *File) VFS() *VFS {
f.mu.RLock()
defer f.mu.RUnlock()
return f.d.vfs
}
// Fs returns the underlying Fs for the file
func (f *File) Fs() fs.Fs {
f.mu.RLock()
defer f.mu.RUnlock()
return f.d.Fs()
}
// MaxSymlinkIterations is the largest number of symlink evaluations EvalSymlinks will do.
const MaxSymlinkIterations = 32
// If f is a symlink then it resolves it to a new Node.
//
// This is a simplistic symlink resolver - it only resolves direct
// symlinks, it will **not** resolve paths that point into a directory
// via a symlink.
//
// It returns the target node after the evaluation of all symbolic
// links.
//
// It returns an error if too many symlinks need to be resolved
// (ELOOP) or there is a loop.
func (f *File) resolveNode() (target Node, err error) {
defer log.Trace(f.Path(), "")("target=%v, err=%v", &target, &err)
seen := make(map[string]struct{})
for range MaxSymlinkIterations {
// If f isn't a symlink, we've arrived at the target
if !f.IsSymlink() {
return f, nil
}
// Read the symlink
fd, err := f.Open(os.O_RDONLY | o_SYMLINK)
if err != nil {
return nil, err
}
b, err := io.ReadAll(fd)
closeErr := fd.Close()
if err != nil {
return nil, err
}
if closeErr != nil {
return nil, closeErr
}
targetPath := string(b)
// Convert to a path relative to the root
// Symlinks are relative to their file node
if !path.IsAbs(targetPath) {
basePath := path.Dir(f.Path())
targetPath = path.Join(basePath, targetPath)
}
// Clean the path, rclone style
targetPath = path.Clean(targetPath)
if targetPath == "." {
targetPath = ""
}
// Check if we've already seen this path
if _, ok := seen[targetPath]; ok {
return nil, ELOOP
}
seen[targetPath] = struct{}{}
// Resolve the targetPath into a node
target, err = f.d.vfs.Stat(targetPath)
if err != nil {
return nil, err
}
// Return node as it must be the destination if not a file
var ok bool
f, ok = target.(*File)
if !ok {
return target, nil
}
}
return nil, ELOOP
}
// Open also also implements the internal flag o_SYMLINK which instead
// of opening the file a symlink points to, opens the symlink itself.
// This is used for reading and writing the symlink and shouldn't be
// used externally.
const o_SYMLINK = 0x4000_0000 //nolint:revive
// Open a file according to the flags provided
//
// O_RDONLY open the file read-only.
// O_WRONLY open the file write-only.
// O_RDWR open the file read-write.
//
// O_APPEND append data to the file when writing.
// O_CREATE create a new file if none exists.
// O_EXCL used with O_CREATE, file must not exist
// O_SYNC open for synchronous I/O.
// O_TRUNC if possible, truncate file when opened
//
// We ignore O_SYNC and O_EXCL
func (f *File) Open(flags int) (fd Handle, err error) {
defer log.Trace(f.Path(), "flags=%s", decodeOpenFlags(flags))("fd=%v, err=%v", &fd, &err)
var (
write bool // if set need write support
read bool // if set need read support
rdwrMode = flags & accessModeMask
)
// If this is a symlink, then resolve it
if f.IsSymlink() && flags&o_SYMLINK == 0 {
target, err := f.resolveNode()
if err != nil {
return nil, err
}
return target.Open(flags)
}
flags &^= o_SYMLINK
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/open.html
// The result of using O_TRUNC with O_RDONLY is undefined.
// Linux seems to truncate the file, but we prefer to return EINVAL
if rdwrMode == os.O_RDONLY && flags&os.O_TRUNC != 0 {
return nil, EINVAL
}
// Figure out the read/write intents
switch {
case rdwrMode == os.O_RDONLY:
read = true
case rdwrMode == os.O_WRONLY:
write = true
case rdwrMode == os.O_RDWR:
read = true
write = true
default:
fs.Debugf(f.Path(), "Can't figure out how to open with flags: 0x%X", flags)
return nil, EPERM
}
// If append is set then set read to force openRW
if flags&os.O_APPEND != 0 {
read = true
f.mu.Lock()
f.appendMode = true
f.mu.Unlock()
}
// If truncate is set then set write to force openRW
if flags&os.O_TRUNC != 0 {
write = true
}
// If create is set then set write to force openRW
if flags&os.O_CREATE != 0 {
write = true
}
// Open the correct sort of handle
f.mu.RLock()
d := f.d
f.mu.RUnlock()
CacheMode := d.vfs.Opt.CacheMode
if CacheMode >= vfscommon.CacheModeMinimal && (d.vfs.cache.InUse(f.CachePath()) || d.vfs.cache.Exists(f.CachePath())) {
fd, err = f.openRW(flags)
} else if read && write {
if CacheMode >= vfscommon.CacheModeMinimal {
fd, err = f.openRW(flags)
} else {
// Open write only and hope the user doesn't
// want to read. If they do they will get an
// EPERM plus an Error log.
fd, err = f.openWrite(flags)
}
} else if write {
if CacheMode >= vfscommon.CacheModeWrites {
fd, err = f.openRW(flags)
} else {
fd, err = f.openWrite(flags)
}
} else if read {
if CacheMode >= vfscommon.CacheModeFull {
fd, err = f.openRW(flags)
} else {
fd, err = f.openRead()
}
} else {
fs.Debugf(f.Path(), "Can't figure out how to open with flags: 0x%X", flags)
return nil, EPERM
}
// if creating a file, add the file to the directory
if err == nil && flags&os.O_CREATE != 0 {
// called without File.mu held
d.addObject(f)
}
return fd, err
}
// Truncate changes the size of the named file.
func (f *File) Truncate(size int64) (err error) {
// make a copy of fh.writers with the lock held then unlock so
// we can call other file methods.
f.mu.Lock()
writers := make([]Handle, len(f.writers))
copy(writers, f.writers)
f.mu.Unlock()
// If have writers then call truncate for each writer
if len(writers) != 0 {
var openWriters = len(writers)
fs.Debugf(f.Path(), "Truncating %d file handles", len(writers))
for _, h := range writers {
truncateErr := h.Truncate(size)
if truncateErr == ECLOSED {
// Ignore ECLOSED since file handle can get closed while this is running
openWriters--
} else if truncateErr != nil {
err = truncateErr
}
}
// If at least one open writer return here
if openWriters > 0 {
return err
}
}
// if o is nil it isn't valid yet
o, err := f.waitForValidObject()
if err != nil {
return err
}
// If no writers, and size is already correct then all done
if o.Size() == size {
return nil
}
fs.Debugf(f.Path(), "Truncating file")
// Otherwise if no writers then truncate the file by opening
// the file and truncating it.
flags := os.O_WRONLY
if size == 0 {
flags |= os.O_TRUNC
}
fh, err := f.Open(flags)
if err != nil {
return err
}
defer fs.CheckClose(fh, &err)
if size != 0 {
return fh.Truncate(size)
}
return nil
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/errors_test.go | vfs/errors_test.go | package vfs
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestErrorError(t *testing.T) {
assert.Equal(t, "Success", OK.Error())
assert.Equal(t, "Function not implemented", ENOSYS.Error())
assert.Equal(t, "Low level error 99", Error(99).Error())
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/dir_handle.go | vfs/dir_handle.go | package vfs
import (
"io"
"os"
)
// DirHandle represents an open directory
type DirHandle struct {
baseHandle
d *Dir
fis []os.FileInfo // where Readdir got to
}
// newDirHandle opens a directory for read
func newDirHandle(d *Dir) *DirHandle {
return &DirHandle{
d: d,
}
}
// String converts it to printable
func (fh *DirHandle) String() string {
if fh == nil {
return "<nil *DirHandle>"
}
if fh.d == nil {
return "<nil *DirHandle.d>"
}
return fh.d.String() + " (r)"
}
// Stat returns info about the current directory
func (fh *DirHandle) Stat() (fi os.FileInfo, err error) {
return fh.d, nil
}
// Node returns the Node associated with this - satisfies Noder interface
func (fh *DirHandle) Node() Node {
return fh.d
}
// Readdir reads the contents of the directory associated with file and returns
// a slice of up to n FileInfo values, as would be returned by Lstat, in
// directory order. Subsequent calls on the same file will yield further
// FileInfos.
//
// If n > 0, Readdir returns at most n FileInfo structures. In this case, if
// Readdir returns an empty slice, it will return a non-nil error explaining
// why. At the end of a directory, the error is io.EOF.
//
// If n <= 0, Readdir returns all the FileInfo from the directory in a single
// slice. In this case, if Readdir succeeds (reads all the way to the end of
// the directory), it returns the slice and a nil error. If it encounters an
// error before the end of the directory, Readdir returns the FileInfo read
// until that point and a non-nil error.
func (fh *DirHandle) Readdir(n int) (fis []os.FileInfo, err error) {
if fh.fis == nil {
nodes, err := fh.d.ReadDirAll()
if err != nil {
return nil, err
}
fh.fis = []os.FileInfo{}
for _, node := range nodes {
fh.fis = append(fh.fis, node)
}
}
nn := len(fh.fis)
if n > 0 {
if nn == 0 {
return nil, io.EOF
}
if nn > n {
nn = n
}
}
fis, fh.fis = fh.fis[:nn], fh.fis[nn:]
return fis, nil
}
// Readdirnames reads and returns a slice of names from the directory f.
//
// If n > 0, Readdirnames returns at most n names. In this case, if
// Readdirnames returns an empty slice, it will return a non-nil error
// explaining why. At the end of a directory, the error is io.EOF.
//
// If n <= 0, Readdirnames returns all the names from the directory in a single
// slice. In this case, if Readdirnames succeeds (reads all the way to the end
// of the directory), it returns the slice and a nil error. If it encounters an
// error before the end of the directory, Readdirnames returns the names read
// until that point and a non-nil error.
func (fh *DirHandle) Readdirnames(n int) (names []string, err error) {
nodes, err := fh.Readdir(n)
if err != nil {
return nil, err
}
for _, node := range nodes {
names = append(names, node.Name())
}
return names, nil
}
// Close closes the handle
func (fh *DirHandle) Close() (err error) {
fh.fis = nil
return nil
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/dir_test.go | vfs/dir_test.go | package vfs
import (
"context"
"encoding/json"
"fmt"
"os"
"runtime"
"slices"
"sort"
"testing"
"time"
"unsafe"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fstest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func dirCreate(t *testing.T) (r *fstest.Run, vfs *VFS, dir *Dir, item fstest.Item) {
r, vfs = newTestVFS(t)
file1 := r.WriteObject(context.Background(), "dir/file1", "file1 contents", t1)
r.CheckRemoteItems(t, file1)
node, err := vfs.Stat("dir")
require.NoError(t, err)
require.True(t, node.IsDir())
return r, vfs, node.(*Dir), file1
}
func TestDirMethods(t *testing.T) {
_, vfs, dir, _ := dirCreate(t)
// String
assert.Equal(t, "dir/", dir.String())
assert.Equal(t, "<nil *Dir>", (*Dir)(nil).String())
// IsDir
assert.Equal(t, true, dir.IsDir())
// IsFile
assert.Equal(t, false, dir.IsFile())
// Mode
assert.Equal(t, os.FileMode(vfs.Opt.DirPerms), dir.Mode())
// Name
assert.Equal(t, "dir", dir.Name())
// Path
assert.Equal(t, "dir", dir.Path())
// Sys
assert.Equal(t, nil, dir.Sys())
// SetSys
dir.SetSys(42)
assert.Equal(t, 42, dir.Sys())
// Inode
assert.NotEqual(t, uint64(0), dir.Inode())
// Node
assert.Equal(t, dir, dir.Node())
// ModTime
assert.WithinDuration(t, t1, dir.ModTime(), 100*365*24*60*60*time.Second)
// Size
assert.Equal(t, int64(0), dir.Size())
// Sync
assert.NoError(t, dir.Sync())
// DirEntry
assert.Equal(t, dir.entry, dir.DirEntry())
// VFS
assert.Equal(t, vfs, dir.VFS())
}
func TestDirForgetAll(t *testing.T) {
_, vfs, dir, file1 := dirCreate(t)
// Make sure / and dir are in cache
_, err := vfs.Stat(file1.Path)
require.NoError(t, err)
root, err := vfs.Root()
require.NoError(t, err)
assert.Equal(t, 1, len(root.items))
assert.Equal(t, 1, len(dir.items))
assert.False(t, root.read.IsZero())
assert.False(t, dir.read.IsZero())
dir.ForgetAll()
assert.Equal(t, 1, len(root.items))
assert.Equal(t, 0, len(dir.items))
assert.False(t, root.read.IsZero())
assert.True(t, dir.read.IsZero())
root.ForgetAll()
assert.Equal(t, 0, len(root.items))
assert.Equal(t, 0, len(dir.items))
assert.True(t, root.read.IsZero())
}
func TestDirForgetPath(t *testing.T) {
_, vfs, dir, file1 := dirCreate(t)
// Make sure / and dir are in cache
_, err := vfs.Stat(file1.Path)
require.NoError(t, err)
root, err := vfs.Root()
require.NoError(t, err)
assert.Equal(t, 1, len(root.items))
assert.Equal(t, 1, len(dir.items))
assert.False(t, root.read.IsZero())
assert.False(t, dir.read.IsZero())
root.ForgetPath("dir/notfound", fs.EntryObject)
assert.Equal(t, 1, len(root.items))
assert.Equal(t, 1, len(dir.items))
assert.False(t, root.read.IsZero())
assert.True(t, dir.read.IsZero())
root.ForgetPath("dir", fs.EntryDirectory)
assert.Equal(t, 1, len(root.items))
assert.Equal(t, 0, len(dir.items))
assert.True(t, root.read.IsZero())
root.ForgetPath("not/in/cache", fs.EntryDirectory)
assert.Equal(t, 1, len(root.items))
assert.Equal(t, 0, len(dir.items))
}
func TestDirWalk(t *testing.T) {
r, vfs, _, file1 := dirCreate(t)
file2 := r.WriteObject(context.Background(), "fil/a/b/c", "super long file", t1)
r.CheckRemoteItems(t, file1, file2)
root, err := vfs.Root()
require.NoError(t, err)
// Forget the cache since we put another object in
root.ForgetAll()
// Read the directories in
_, err = vfs.Stat("dir")
require.NoError(t, err)
_, err = vfs.Stat("fil/a/b")
require.NoError(t, err)
fil, err := vfs.Stat("fil")
require.NoError(t, err)
var result []string
fn := func(d *Dir) {
result = append(result, d.path)
}
result = nil
root.walk(fn)
sort.Strings(result) // sort as there is a map traversal involved
assert.Equal(t, []string{"", "dir", "fil", "fil/a", "fil/a/b"}, result)
assert.Nil(t, root.cachedDir("not found"))
if dir := root.cachedDir("dir"); assert.NotNil(t, dir) {
result = nil
dir.walk(fn)
assert.Equal(t, []string{"dir"}, result)
}
if dir := root.cachedDir("fil"); assert.NotNil(t, dir) {
result = nil
dir.walk(fn)
assert.Equal(t, []string{"fil/a/b", "fil/a", "fil"}, result)
}
if dir := fil.(*Dir); assert.NotNil(t, dir) {
result = nil
dir.walk(fn)
assert.Equal(t, []string{"fil/a/b", "fil/a", "fil"}, result)
}
if dir := root.cachedDir("fil/a"); assert.NotNil(t, dir) {
result = nil
dir.walk(fn)
assert.Equal(t, []string{"fil/a/b", "fil/a"}, result)
}
if dir := fil.(*Dir).cachedDir("a"); assert.NotNil(t, dir) {
result = nil
dir.walk(fn)
assert.Equal(t, []string{"fil/a/b", "fil/a"}, result)
}
if dir := root.cachedDir("fil/a"); assert.NotNil(t, dir) {
result = nil
dir.walk(fn)
assert.Equal(t, []string{"fil/a/b", "fil/a"}, result)
}
if dir := root.cachedDir("fil/a/b"); assert.NotNil(t, dir) {
result = nil
dir.walk(fn)
assert.Equal(t, []string{"fil/a/b"}, result)
}
}
func TestDirSetModTime(t *testing.T) {
_, vfs, dir, _ := dirCreate(t)
err := dir.SetModTime(t1)
require.NoError(t, err)
assert.WithinDuration(t, t1, dir.ModTime(), time.Second)
err = dir.SetModTime(t2)
require.NoError(t, err)
assert.WithinDuration(t, t2, dir.ModTime(), time.Second)
vfs.Opt.ReadOnly = true
err = dir.SetModTime(t2)
assert.Equal(t, EROFS, err)
}
func TestDirStat(t *testing.T) {
_, _, dir, _ := dirCreate(t)
node, err := dir.Stat("file1")
require.NoError(t, err)
_, ok := node.(*File)
assert.True(t, ok)
assert.Equal(t, int64(14), node.Size())
assert.Equal(t, "file1", node.Name())
_, err = dir.Stat("not found")
assert.Equal(t, ENOENT, err)
}
// This lists dir and checks the listing is as expected
func checkListing(t *testing.T, dir *Dir, want []string) {
var got []string
nodes, err := dir.ReadDirAll()
require.NoError(t, err)
for _, node := range nodes {
got = append(got, fmt.Sprintf("%s,%d,%v", node.Name(), node.Size(), node.IsDir()))
}
assert.Equal(t, want, got)
}
func TestDirReadDirAll(t *testing.T) {
r, vfs := newTestVFS(t)
file1 := r.WriteObject(context.Background(), "dir/file1", "file1 contents", t1)
file2 := r.WriteObject(context.Background(), "dir/file2", "file2- contents", t2)
file3 := r.WriteObject(context.Background(), "dir/subdir/file3", "file3-- contents", t3)
r.CheckRemoteItems(t, file1, file2, file3)
node, err := vfs.Stat("dir")
require.NoError(t, err)
dir := node.(*Dir)
checkListing(t, dir, []string{"file1,14,false", "file2,15,false", "subdir,0,true"})
node, err = vfs.Stat("")
require.NoError(t, err)
root := node.(*Dir)
checkListing(t, root, []string{"dir,0,true"})
node, err = vfs.Stat("dir/subdir")
require.NoError(t, err)
subdir := node.(*Dir)
checkListing(t, subdir, []string{"file3,16,false"})
t.Run("Virtual", func(t *testing.T) {
// Add some virtual entries and check what happens
dir.AddVirtual("virtualFile", 17, false)
dir.AddVirtual("virtualDir", 0, true)
// Remove some existing entries
dir.DelVirtual("file2")
dir.DelVirtual("subdir")
checkListing(t, dir, []string{"file1,14,false", "virtualDir,0,true", "virtualFile,17,false"})
// Now action the deletes and uploads
_ = r.WriteObject(context.Background(), "dir/virtualFile", "virtualFile contents", t1)
_ = r.WriteObject(context.Background(), "dir/virtualDir/testFile", "testFile contents", t1)
o, err := r.Fremote.NewObject(context.Background(), "dir/file2")
require.NoError(t, err)
require.NoError(t, o.Remove(context.Background()))
require.NoError(t, operations.Purge(context.Background(), r.Fremote, "dir/subdir"))
// Force a directory reload...
dir.invalidateDir("dir")
checkListing(t, dir, []string{"file1,14,false", "virtualDir,0,true", "virtualFile,20,false"})
// check no virtuals left
dir.mu.Lock()
assert.Nil(t, dir.virtual)
dir.mu.Unlock()
// Add some virtual entries and check what happens
dir.AddVirtual("virtualFile2", 100, false)
dir.AddVirtual("virtualDir2", 0, true)
// Remove some existing entries
dir.DelVirtual("file1")
checkListing(t, dir, []string{"virtualDir,0,true", "virtualDir2,0,true", "virtualFile,20,false", "virtualFile2,100,false"})
// Force a directory reload...
dir.invalidateDir("dir")
want := []string{"file1,14,false", "virtualDir,0,true", "virtualDir2,0,true", "virtualFile,20,false", "virtualFile2,100,false"}
features := r.Fremote.Features()
if features.CanHaveEmptyDirectories {
// snip out virtualDir2 which will only be present if can't have empty dirs
want = slices.Delete(want, 2, 3)
}
checkListing(t, dir, want)
// Check that forgetting the root doesn't invalidate the virtual entries
root.ForgetAll()
checkListing(t, dir, want)
})
}
func TestDirOpen(t *testing.T) {
_, _, dir, _ := dirCreate(t)
fd, err := dir.Open(os.O_RDONLY)
require.NoError(t, err)
_, ok := fd.(*DirHandle)
assert.True(t, ok)
require.NoError(t, fd.Close())
_, err = dir.Open(os.O_WRONLY)
assert.Equal(t, EPERM, err)
}
func TestDirCreate(t *testing.T) {
_, vfs, dir, _ := dirCreate(t)
origModTime := dir.ModTime()
time.Sleep(100 * time.Millisecond) // for low rez Windows timers
file, err := dir.Create("potato", os.O_WRONLY|os.O_CREATE)
require.NoError(t, err)
assert.Equal(t, int64(0), file.Size())
assert.True(t, dir.ModTime().After(origModTime))
fd, err := file.Open(os.O_WRONLY | os.O_CREATE)
require.NoError(t, err)
// FIXME Note that this fails with the current implementation
// until the file has been opened.
// file2, err := vfs.Stat("dir/potato")
// require.NoError(t, err)
// assert.Equal(t, file, file2)
n, err := fd.Write([]byte("hello"))
require.NoError(t, err)
assert.Equal(t, 5, n)
require.NoError(t, fd.Close())
file2, err := vfs.Stat("dir/potato")
require.NoError(t, err)
assert.Equal(t, int64(5), file2.Size())
// Try creating the file again - make sure we get the same file node
file3, err := dir.Create("potato", os.O_RDWR|os.O_CREATE)
require.NoError(t, err)
assert.Equal(t, int64(5), file3.Size())
assert.Equal(t, fmt.Sprintf("%p", file), fmt.Sprintf("%p", file3), "didn't return same node")
// Test read only fs creating new
vfs.Opt.ReadOnly = true
_, err = dir.Create("sausage", os.O_WRONLY|os.O_CREATE)
assert.Equal(t, EROFS, err)
}
func TestDirMkdir(t *testing.T) {
r, vfs, dir, file1 := dirCreate(t)
_, err := dir.Mkdir("file1")
assert.Error(t, err)
origModTime := dir.ModTime()
time.Sleep(100 * time.Millisecond) // for low rez Windows timers
sub, err := dir.Mkdir("sub")
assert.NoError(t, err)
assert.True(t, dir.ModTime().After(origModTime))
// check the vfs
checkListing(t, dir, []string{"file1,14,false", "sub,0,true"})
checkListing(t, sub, []string(nil))
// check the underlying r.Fremote
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1}, []string{"dir", "dir/sub"}, r.Fremote.Precision())
vfs.Opt.ReadOnly = true
_, err = dir.Mkdir("sausage")
assert.Equal(t, EROFS, err)
}
func TestDirMkdirSub(t *testing.T) {
r, vfs, dir, file1 := dirCreate(t)
_, err := dir.Mkdir("file1")
assert.Error(t, err)
sub, err := dir.Mkdir("sub")
assert.NoError(t, err)
subsub, err := sub.Mkdir("subsub")
assert.NoError(t, err)
// check the vfs
checkListing(t, dir, []string{"file1,14,false", "sub,0,true"})
checkListing(t, sub, []string{"subsub,0,true"})
checkListing(t, subsub, []string(nil))
// check the underlying r.Fremote
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1}, []string{"dir", "dir/sub", "dir/sub/subsub"}, r.Fremote.Precision())
vfs.Opt.ReadOnly = true
_, err = dir.Mkdir("sausage")
assert.Equal(t, EROFS, err)
}
func TestDirRemove(t *testing.T) {
r, vfs, dir, _ := dirCreate(t)
// check directory is there
node, err := vfs.Stat("dir")
require.NoError(t, err)
assert.True(t, node.IsDir())
err = dir.Remove()
assert.Equal(t, ENOTEMPTY, err)
// Delete the sub file
node, err = vfs.Stat("dir/file1")
require.NoError(t, err)
err = node.Remove()
require.NoError(t, err)
// Remove the now empty directory
err = dir.Remove()
require.NoError(t, err)
// check directory is not there
_, err = vfs.Stat("dir")
assert.Equal(t, ENOENT, err)
// check the vfs
root, err := vfs.Root()
require.NoError(t, err)
checkListing(t, root, []string(nil))
// check the underlying r.Fremote
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{}, []string{}, r.Fremote.Precision())
// read only check
vfs.Opt.ReadOnly = true
err = dir.Remove()
assert.Equal(t, EROFS, err)
}
func TestDirRemoveAll(t *testing.T) {
r, vfs, dir, _ := dirCreate(t)
// Remove the directory and contents
err := dir.RemoveAll()
require.NoError(t, err)
// check the vfs
root, err := vfs.Root()
require.NoError(t, err)
checkListing(t, root, []string(nil))
// check the underlying r.Fremote
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{}, []string{}, r.Fremote.Precision())
// read only check
vfs.Opt.ReadOnly = true
err = dir.RemoveAll()
assert.Equal(t, EROFS, err)
}
func TestDirRemoveName(t *testing.T) {
r, vfs, dir, _ := dirCreate(t)
origModTime := dir.ModTime()
time.Sleep(100 * time.Millisecond) // for low rez Windows timers
err := dir.RemoveName("file1")
require.NoError(t, err)
assert.True(t, dir.ModTime().After(origModTime))
checkListing(t, dir, []string(nil))
root, err := vfs.Root()
require.NoError(t, err)
checkListing(t, root, []string{"dir,0,true"})
// check the underlying r.Fremote
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{}, []string{"dir"}, r.Fremote.Precision())
// read only check
vfs.Opt.ReadOnly = true
err = dir.RemoveName("potato")
assert.Equal(t, EROFS, err)
}
func TestDirRename(t *testing.T) {
r, vfs, dir, file1 := dirCreate(t)
features := r.Fremote.Features()
if features.DirMove == nil && features.Move == nil && features.Copy == nil {
t.Skip("can't rename directories")
}
file3 := r.WriteObject(context.Background(), "dir/file3", "file3 contents!", t1)
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1, file3}, []string{"dir"}, r.Fremote.Precision())
root, err := vfs.Root()
require.NoError(t, err)
err = dir.Rename("not found", "tuba", dir)
assert.Equal(t, ENOENT, err)
// Rename a directory
err = root.Rename("dir", "dir2", root)
assert.NoError(t, err)
checkListing(t, root, []string{"dir2,0,true"})
checkListing(t, dir, []string{"file1,14,false", "file3,15,false"})
// check the underlying r.Fremote
file1.Path = "dir2/file1"
file3.Path = "dir2/file3"
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1, file3}, []string{"dir2"}, r.Fremote.Precision())
// refetch dir
node, err := vfs.Stat("dir2")
assert.NoError(t, err)
dir = node.(*Dir)
// Rename a file
origModTime := dir.ModTime()
time.Sleep(100 * time.Millisecond) // for low rez Windows timers
err = dir.Rename("file1", "file2", root)
assert.NoError(t, err)
assert.True(t, dir.ModTime().After(origModTime))
checkListing(t, root, []string{"dir2,0,true", "file2,14,false"})
checkListing(t, dir, []string{"file3,15,false"})
// check the underlying r.Fremote
file1.Path = "file2"
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1, file3}, []string{"dir2"}, r.Fremote.Precision())
// Rename a file on top of another file
err = root.Rename("file2", "file3", dir)
assert.NoError(t, err)
checkListing(t, root, []string{"dir2,0,true"})
checkListing(t, dir, []string{"file3,14,false"})
// check the underlying r.Fremote
file1.Path = "dir2/file3"
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1}, []string{"dir2"}, r.Fremote.Precision())
// rename an empty directory
_, err = root.Mkdir("empty directory")
assert.NoError(t, err)
checkListing(t, root, []string{
"dir2,0,true",
"empty directory,0,true",
})
err = root.Rename("empty directory", "renamed empty directory", root)
assert.NoError(t, err)
checkListing(t, root, []string{
"dir2,0,true",
"renamed empty directory,0,true",
})
// ...we don't check the underlying f.Fremote because on
// bucket-based remotes the directory won't be there
// read only check
vfs.Opt.ReadOnly = true
err = dir.Rename("potato", "tuba", dir)
assert.Equal(t, EROFS, err)
// Rename a dir, check that key was correctly renamed in dir.parent.items
vfs.Opt.ReadOnly = false
_, ok := dir.parent.items["dir2"]
assert.True(t, ok, "dir.parent.items should have 'dir2' key before rename")
_, ok = dir.parent.items["dir3"]
assert.False(t, ok, "dir.parent.items should not have 'dir3' key before rename")
dir.renameTree("dir3") // rename dir2 to dir3
_, ok = dir.parent.items["dir2"]
assert.False(t, ok, "dir.parent.items should not have 'dir2' key after rename")
d, ok := dir.parent.items["dir3"]
assert.True(t, ok, fmt.Sprintf("expected to find 'dir3' key in dir.parent.items after rename, got %v", dir.parent.items))
assert.Equal(t, dir, d, `expected renamed dir to match value of dir.parent.items["dir3"]`)
}
func TestDirStructSize(t *testing.T) {
t.Logf("Dir struct has size %d bytes", unsafe.Sizeof(Dir{}))
}
// Check that open files appear in the directory listing properly after a forget
func TestDirFileOpen(t *testing.T) {
_, vfs, dir, _ := dirCreate(t)
assert.False(t, dir.hasVirtual())
assert.False(t, dir.parent.hasVirtual())
_, err := dir.Mkdir("sub")
require.NoError(t, err)
assert.True(t, dir.hasVirtual())
assert.True(t, dir.parent.hasVirtual())
fd0, err := vfs.Create("dir/sub/file0")
require.NoError(t, err)
_, err = fd0.Write([]byte("hello"))
require.NoError(t, err)
defer func() {
require.NoError(t, fd0.Close())
}()
fd2, err := vfs.Create("dir/sub/file2")
require.NoError(t, err)
_, err = fd2.Write([]byte("hello world!"))
require.NoError(t, err)
require.NoError(t, fd2.Close())
assert.True(t, dir.hasVirtual())
assert.True(t, dir.hasVirtual())
assert.True(t, dir.parent.hasVirtual())
// Now forget the directory
hasVirtual := dir.parent.ForgetAll()
assert.True(t, hasVirtual)
assert.True(t, dir.hasVirtual())
assert.True(t, dir.parent.hasVirtual())
// Check the files can still be found
fi, err := vfs.Stat("dir/sub/file0")
require.NoError(t, err)
assert.Equal(t, int64(5), fi.Size())
fi, err = vfs.Stat("dir/sub/file2")
require.NoError(t, err)
assert.Equal(t, int64(12), fi.Size())
}
func TestDirEntryModTimeInvalidation(t *testing.T) {
r, vfs := newTestVFS(t)
features := r.Fremote.Features()
if !features.DirModTimeUpdatesOnWrite {
t.Skip("Need DirModTimeUpdatesOnWrite")
}
if features.IsLocal && runtime.GOOS == "windows" {
t.Skip("dirent modtime is unreliable on Windows filesystems")
}
r.WriteObject(context.Background(), "dir/file1", "file1 contents", t1)
// Read the modtime of the directory fresh
vfs.FlushDirCache()
node, err := vfs.Stat("dir")
require.NoError(t, err)
modTime1 := node.(*Dir).DirEntry().ModTime(context.Background())
// Wait some time (we wait for Precision+10%), then write another file
// which should update the ModTime of the directory.
prec := (11 * vfs.f.Precision()) / 10
time.Sleep(max(100*time.Millisecond, prec))
r.WriteObject(context.Background(), "dir/file2", "file2 contents", t2)
// Read the modtime of the directory fresh again - it should have changed
vfs.FlushDirCache()
node2, err := vfs.Stat("dir")
require.NoError(t, err)
modTime2 := node2.(*Dir).DirEntry().ModTime(context.Background())
// ModTime of directory must be different after second file was written.
if modTime1.Equal(modTime2) {
t.Error("ModTime not invalidated")
}
}
func TestDirMetadataExtension(t *testing.T) {
r, vfs, dir, _ := dirCreate(t)
root, err := vfs.Root()
require.NoError(t, err)
features := r.Fremote.Features()
checkListing(t, dir, []string{"file1,14,false"})
checkListing(t, root, []string{"dir,0,true"})
node, err := vfs.Stat("dir/file1")
require.NoError(t, err)
require.True(t, node.IsFile())
node, err = vfs.Stat("dir")
require.NoError(t, err)
require.True(t, node.IsDir())
// Check metadata files do not exist
_, err = vfs.Stat("dir/file1.metadata")
require.Error(t, err, ENOENT)
_, err = vfs.Stat("dir.metadata")
require.Error(t, err, ENOENT)
// Configure metadata extension
vfs.Opt.MetadataExtension = ".metadata"
// Check metadata for file does exist
node, err = vfs.Stat("dir/file1.metadata")
require.NoError(t, err)
require.True(t, node.IsFile())
size := node.Size()
assert.Greater(t, size, int64(1))
modTime := node.ModTime()
// ...and is now in the listing
checkListing(t, dir, []string{"file1,14,false", fmt.Sprintf("file1.metadata,%d,false", size)})
// ...and is a JSON blob with correct "mtime" key
blob, err := vfs.ReadFile("dir/file1.metadata")
require.NoError(t, err)
var metadata map[string]string
err = json.Unmarshal(blob, &metadata)
require.NoError(t, err)
if features.ReadMetadata {
assert.Equal(t, modTime.Format(time.RFC3339Nano), metadata["mtime"])
}
// Check metadata for dir does exist
node, err = vfs.Stat("dir.metadata")
require.NoError(t, err)
require.True(t, node.IsFile())
size = node.Size()
assert.Greater(t, size, int64(1))
modTime = node.ModTime()
// ...and is now in the listing
checkListing(t, root, []string{"dir,0,true", fmt.Sprintf("dir.metadata,%d,false", size)})
// ...and is a JSON blob with correct "mtime" key
blob, err = vfs.ReadFile("dir.metadata")
require.NoError(t, err)
clear(metadata)
err = json.Unmarshal(blob, &metadata)
require.NoError(t, err)
if features.ReadDirMetadata {
assert.Equal(t, modTime.Format(time.RFC3339Nano), metadata["mtime"])
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/zip_test.go | vfs/zip_test.go | package vfs
import (
"archive/zip"
"bytes"
"context"
"crypto/sha256"
"fmt"
"io"
"strings"
"testing"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/random"
"github.com/stretchr/testify/require"
)
func readZip(t *testing.T, buf *bytes.Buffer) *zip.Reader {
t.Helper()
r, err := zip.NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
require.NoError(t, err)
return r
}
func mustCreateZip(t *testing.T, d *Dir) *bytes.Buffer {
t.Helper()
var buf bytes.Buffer
require.NoError(t, CreateZip(context.Background(), d, &buf))
return &buf
}
func zipReadFile(t *testing.T, zr *zip.Reader, match func(name string) bool) ([]byte, string) {
t.Helper()
for _, f := range zr.File {
if strings.HasSuffix(f.Name, "/") {
continue
}
if match(f.Name) {
rc, err := f.Open()
require.NoError(t, err)
defer func() { require.NoError(t, rc.Close()) }()
b, err := io.ReadAll(rc)
require.NoError(t, err)
return b, f.Name
}
}
t.Fatalf("zip entry matching predicate not found")
return nil, ""
}
func TestZipManyFiles(t *testing.T) {
r, vfs := newTestVFS(t)
const N = 5
want := make(map[string]string, N)
items := make([]fstest.Item, 0, N)
for i := range N {
name := fmt.Sprintf("flat/f%03d.txt", i)
data := strings.Repeat(fmt.Sprintf("line-%d\n", i), (i%5)+1)
it := r.WriteObject(context.Background(), name, data, t1)
items = append(items, it)
want[name[strings.LastIndex(name, "/")+1:]] = data
}
r.CheckRemoteItems(t, items...)
node, err := vfs.Stat("flat")
require.NoError(t, err)
dir := node.(*Dir)
buf := mustCreateZip(t, dir)
zr := readZip(t, buf)
// count only file entries (skip dir entries with trailing "/")
files := 0
for _, f := range zr.File {
if !strings.HasSuffix(f.Name, "/") {
files++
}
}
require.Equal(t, N, files)
// validate contents by base name
for base, data := range want {
got, _ := zipReadFile(t, zr, func(name string) bool { return name == base })
require.Equal(t, data, string(got), "mismatch for %s", base)
}
}
func TestZipManySubDirs(t *testing.T) {
r, vfs := newTestVFS(t)
r.WriteObject(context.Background(), "a/top.txt", "top", t1)
r.WriteObject(context.Background(), "a/b/mid.txt", "mid", t1)
r.WriteObject(context.Background(), "a/b/c/deep.txt", "deep", t1)
node, err := vfs.Stat("a")
require.NoError(t, err)
dir := node.(*Dir)
buf := mustCreateZip(t, dir)
zr := readZip(t, buf)
// paths may include directory prefixes; assert by suffix
got, name := zipReadFile(t, zr, func(n string) bool { return strings.HasSuffix(n, "/top.txt") || n == "top.txt" })
require.Equal(t, "top", string(got), "bad content for %s", name)
got, name = zipReadFile(t, zr, func(n string) bool { return strings.HasSuffix(n, "/mid.txt") || n == "mid.txt" })
require.Equal(t, "mid", string(got), "bad content for %s", name)
got, name = zipReadFile(t, zr, func(n string) bool { return strings.HasSuffix(n, "/deep.txt") || n == "deep.txt" })
require.Equal(t, "deep", string(got), "bad content for %s", name)
}
func TestZipLargeFiles(t *testing.T) {
r, vfs := newTestVFS(t)
if strings.HasPrefix(r.Fremote.Name(), "TestChunker") {
t.Skip("skipping test as chunker too slow")
}
data := random.String(5 * 1024 * 1024)
sum := sha256.Sum256([]byte(data))
r.WriteObject(context.Background(), "bigdir/big.bin", data, t1)
node, err := vfs.Stat("bigdir")
require.NoError(t, err)
dir := node.(*Dir)
buf := mustCreateZip(t, dir)
zr := readZip(t, buf)
got, _ := zipReadFile(t, zr, func(n string) bool { return n == "big.bin" || strings.HasSuffix(n, "/big.bin") })
require.Equal(t, sum, sha256.Sum256(got))
}
func TestZipDirsInRoot(t *testing.T) {
r, vfs := newTestVFS(t)
r.WriteObject(context.Background(), "dir1/a.txt", "x", t1)
r.WriteObject(context.Background(), "dir2/b.txt", "y", t1)
r.WriteObject(context.Background(), "dir3/c.txt", "z", t1)
root, err := vfs.Root()
require.NoError(t, err)
buf := mustCreateZip(t, root)
zr := readZip(t, buf)
// Check each file exists (ignore exact directory-entry names)
gx, _ := zipReadFile(t, zr, func(n string) bool { return strings.HasSuffix(n, "/a.txt") })
require.Equal(t, "x", string(gx))
gy, _ := zipReadFile(t, zr, func(n string) bool { return strings.HasSuffix(n, "/b.txt") })
require.Equal(t, "y", string(gy))
gz, _ := zipReadFile(t, zr, func(n string) bool { return strings.HasSuffix(n, "/c.txt") })
require.Equal(t, "z", string(gz))
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfs_test.go | vfs/vfs_test.go | // Test suite for vfs
package vfs
import (
"context"
"errors"
"fmt"
"io"
"os"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Some times used in the tests
var (
t1 = fstest.Time("2001-02-03T04:05:06.499999999Z")
t2 = fstest.Time("2011-12-25T12:59:59.123456789Z")
t3 = fstest.Time("2011-12-30T12:59:59.000000000Z")
)
// Constants uses in the tests
const (
writeBackDelay = fs.Duration(100 * time.Millisecond) // A short writeback delay for testing
waitForWritersDelay = 30 * time.Second // time to wait for existing writers
)
// TestMain drives the tests
func TestMain(m *testing.M) {
fstest.TestMain(m)
}
// Clean up a test VFS
func cleanupVFS(t *testing.T, vfs *VFS) {
vfs.WaitForWriters(waitForWritersDelay)
err := vfs.CleanUp()
require.NoError(t, err)
vfs.Shutdown()
}
// Create a new VFS
func newTestVFSOpt(t *testing.T, opt *vfscommon.Options) (r *fstest.Run, vfs *VFS) {
r = fstest.NewRun(t)
vfs = New(r.Fremote, opt)
t.Cleanup(func() {
cleanupVFS(t, vfs)
})
return r, vfs
}
// Create a new VFS with default options
func newTestVFS(t *testing.T) (r *fstest.Run, vfs *VFS) {
return newTestVFSOpt(t, nil)
}
// Check baseHandle performs as advertised
func TestVFSbaseHandle(t *testing.T) {
fh := baseHandle{}
err := fh.Chdir()
assert.Equal(t, ENOSYS, err)
err = fh.Chmod(0)
assert.Equal(t, ENOSYS, err)
err = fh.Chown(0, 0)
assert.Equal(t, ENOSYS, err)
err = fh.Close()
assert.Equal(t, ENOSYS, err)
fd := fh.Fd()
assert.Equal(t, uintptr(0), fd)
name := fh.Name()
assert.Equal(t, "", name)
_, err = fh.Read(nil)
assert.Equal(t, ENOSYS, err)
_, err = fh.ReadAt(nil, 0)
assert.Equal(t, ENOSYS, err)
_, err = fh.Readdir(0)
assert.Equal(t, ENOSYS, err)
_, err = fh.Readdirnames(0)
assert.Equal(t, ENOSYS, err)
_, err = fh.Seek(0, io.SeekStart)
assert.Equal(t, ENOSYS, err)
_, err = fh.Stat()
assert.Equal(t, ENOSYS, err)
err = fh.Sync()
assert.Equal(t, nil, err)
err = fh.Truncate(0)
assert.Equal(t, ENOSYS, err)
_, err = fh.Write(nil)
assert.Equal(t, ENOSYS, err)
_, err = fh.WriteAt(nil, 0)
assert.Equal(t, ENOSYS, err)
_, err = fh.WriteString("")
assert.Equal(t, ENOSYS, err)
err = fh.Flush()
assert.Equal(t, ENOSYS, err)
err = fh.Release()
assert.Equal(t, ENOSYS, err)
node := fh.Node()
assert.Nil(t, node)
}
// TestVFSNew sees if the New command works properly
func TestVFSNew(t *testing.T) {
// Check active cache has this many entries
checkActiveCacheEntries := func(i int) {
_, count := activeCacheEntries()
assert.Equal(t, i, count)
}
checkActiveCacheEntries(0)
r, vfs := newTestVFS(t)
// Check making a VFS with nil options
var defaultOpt = vfscommon.Opt
defaultOpt.Init()
checkActiveCacheEntries(1)
// Check that we get the same VFS if we ask for it again with
// the same options
vfs2 := New(r.Fremote, nil)
assert.Equal(t, fmt.Sprintf("%p", vfs), fmt.Sprintf("%p", vfs2))
checkActiveCacheEntries(1)
// Shut the new VFS down and check the cache still has stuff in
vfs2.Shutdown()
checkActiveCacheEntries(1)
cleanupVFS(t, vfs)
checkActiveCacheEntries(0)
}
// TestVFSNewWithOpts sees if the New command works properly
func TestVFSNewWithOpts(t *testing.T) {
var opt = vfscommon.Opt
opt.DirPerms = 0777
opt.FilePerms = 0666
opt.Umask = 0002
_, vfs := newTestVFSOpt(t, &opt)
assert.Equal(t, vfscommon.FileMode(0775)|vfscommon.FileMode(os.ModeDir), vfs.Opt.DirPerms)
assert.Equal(t, vfscommon.FileMode(0664), vfs.Opt.FilePerms)
}
// TestVFSRoot checks root directory is present and correct
func TestVFSRoot(t *testing.T) {
_, vfs := newTestVFS(t)
root, err := vfs.Root()
require.NoError(t, err)
assert.Equal(t, vfs.root, root)
assert.True(t, root.IsDir())
assert.Equal(t, os.FileMode(vfs.Opt.DirPerms).Perm(), root.Mode().Perm())
}
func TestVFSStat(t *testing.T) {
r, vfs := newTestVFS(t)
file1 := r.WriteObject(context.Background(), "file1", "file1 contents", t1)
file2 := r.WriteObject(context.Background(), "dir/file2", "file2 contents", t2)
r.CheckRemoteItems(t, file1, file2)
node, err := vfs.Stat("file1")
require.NoError(t, err)
assert.True(t, node.IsFile())
assert.Equal(t, "file1", node.Name())
node, err = vfs.Stat("dir")
require.NoError(t, err)
assert.True(t, node.IsDir())
assert.Equal(t, "dir", node.Name())
node, err = vfs.Stat("dir/file2")
require.NoError(t, err)
assert.True(t, node.IsFile())
assert.Equal(t, "file2", node.Name())
_, err = vfs.Stat("not found")
assert.Equal(t, os.ErrNotExist, err)
_, err = vfs.Stat("dir/not found")
assert.Equal(t, os.ErrNotExist, err)
_, err = vfs.Stat("not found/not found")
assert.Equal(t, os.ErrNotExist, err)
_, err = vfs.Stat("file1/under a file")
assert.Equal(t, os.ErrNotExist, err)
}
func TestVFSStatParent(t *testing.T) {
r, vfs := newTestVFS(t)
file1 := r.WriteObject(context.Background(), "file1", "file1 contents", t1)
file2 := r.WriteObject(context.Background(), "dir/file2", "file2 contents", t2)
r.CheckRemoteItems(t, file1, file2)
node, leaf, err := vfs.StatParent("file1")
require.NoError(t, err)
assert.True(t, node.IsDir())
assert.Equal(t, "/", node.Name())
assert.Equal(t, "file1", leaf)
node, leaf, err = vfs.StatParent("dir/file2")
require.NoError(t, err)
assert.True(t, node.IsDir())
assert.Equal(t, "dir", node.Name())
assert.Equal(t, "file2", leaf)
node, leaf, err = vfs.StatParent("not found")
require.NoError(t, err)
assert.True(t, node.IsDir())
assert.Equal(t, "/", node.Name())
assert.Equal(t, "not found", leaf)
_, _, err = vfs.StatParent("not found dir/not found")
assert.Equal(t, os.ErrNotExist, err)
_, _, err = vfs.StatParent("file1/under a file")
assert.Equal(t, os.ErrExist, err)
}
func TestVFSOpenFile(t *testing.T) {
r, vfs := newTestVFS(t)
file1 := r.WriteObject(context.Background(), "file1", "file1 contents", t1)
file2 := r.WriteObject(context.Background(), "dir/file2", "file2 contents", t2)
r.CheckRemoteItems(t, file1, file2)
fd, err := vfs.OpenFile("file1", os.O_RDONLY, 0777)
require.NoError(t, err)
assert.NotNil(t, fd)
require.NoError(t, fd.Close())
fd, err = vfs.OpenFile("dir", os.O_RDONLY, 0777)
require.NoError(t, err)
assert.NotNil(t, fd)
require.NoError(t, fd.Close())
fd, err = vfs.OpenFile("dir/new_file.txt", os.O_RDONLY, 0777)
assert.Equal(t, os.ErrNotExist, err)
assert.Nil(t, fd)
fd, err = vfs.OpenFile("dir/new_file.txt", os.O_WRONLY|os.O_CREATE, 0777)
require.NoError(t, err)
assert.NotNil(t, fd)
err = fd.Close()
if !errors.Is(err, fs.ErrorCantUploadEmptyFiles) {
require.NoError(t, err)
}
fd, err = vfs.OpenFile("not found/new_file.txt", os.O_WRONLY|os.O_CREATE, 0777)
assert.Equal(t, os.ErrNotExist, err)
assert.Nil(t, fd)
}
func TestVFSRename(t *testing.T) {
r, vfs := newTestVFS(t)
features := r.Fremote.Features()
if features.Move == nil && features.Copy == nil {
t.Skip("skip as can't rename files")
}
file1 := r.WriteObject(context.Background(), "dir/file2", "file2 contents", t2)
r.CheckRemoteItems(t, file1)
err := vfs.Rename("dir/file2", "dir/file1")
require.NoError(t, err)
file1.Path = "dir/file1"
r.CheckRemoteItems(t, file1)
err = vfs.Rename("dir/file1", "file0")
require.NoError(t, err)
file1.Path = "file0"
r.CheckRemoteItems(t, file1)
err = vfs.Rename("not found/file0", "file0")
assert.Equal(t, os.ErrNotExist, err)
err = vfs.Rename("file0", "not found/file0")
assert.Equal(t, os.ErrNotExist, err)
}
func TestVFSStatfs(t *testing.T) {
r, vfs := newTestVFS(t)
// pre-conditions
assert.Nil(t, vfs.usage)
assert.True(t, vfs.usageTime.IsZero())
aboutSupported := r.Fremote.Features().About != nil
// read
total, used, free := vfs.Statfs()
if !aboutSupported {
assert.Equal(t, int64(unknownFreeBytes), total)
assert.Equal(t, int64(unknownFreeBytes), free)
assert.Equal(t, int64(0), used)
return // can't test anything else if About not supported
}
require.NotNil(t, vfs.usage)
assert.False(t, vfs.usageTime.IsZero())
if vfs.usage.Total != nil {
assert.Equal(t, *vfs.usage.Total, total)
} else {
assert.True(t, total >= int64(unknownFreeBytes))
}
if vfs.usage.Free != nil {
assert.Equal(t, *vfs.usage.Free, free)
} else {
if vfs.usage.Total != nil && vfs.usage.Used != nil {
assert.Equal(t, free, total-used)
} else {
assert.True(t, free >= int64(unknownFreeBytes))
}
}
if vfs.usage.Used != nil {
assert.Equal(t, *vfs.usage.Used, used)
} else {
assert.Equal(t, int64(0), used)
}
// read cached
oldUsage := vfs.usage
oldTime := vfs.usageTime
total2, used2, free2 := vfs.Statfs()
assert.Equal(t, oldUsage, vfs.usage)
assert.Equal(t, total, total2)
assert.Equal(t, used, used2)
assert.Equal(t, free, free2)
assert.Equal(t, oldTime, vfs.usageTime)
}
func TestVFSMkdir(t *testing.T) {
r, vfs := newTestVFS(t)
if !r.Fremote.Features().CanHaveEmptyDirectories {
return // can't test if can't have empty directories
}
r.CheckRemoteListing(t, nil, []string{})
// Try making the root
err := vfs.Mkdir("", 0777)
require.NoError(t, err)
r.CheckRemoteListing(t, nil, []string{})
// Try making a sub directory
err = vfs.Mkdir("a", 0777)
require.NoError(t, err)
r.CheckRemoteListing(t, nil, []string{"a"})
// Try making an existing directory
err = vfs.Mkdir("a", 0777)
require.NoError(t, err)
r.CheckRemoteListing(t, nil, []string{"a"})
// Try making a new directory
err = vfs.Mkdir("b/", 0777)
require.NoError(t, err)
r.CheckRemoteListing(t, nil, []string{"a", "b"})
// Try making a new directory
err = vfs.Mkdir("/c", 0777)
require.NoError(t, err)
r.CheckRemoteListing(t, nil, []string{"a", "b", "c"})
// Try making a new directory
err = vfs.Mkdir("/d/", 0777)
require.NoError(t, err)
r.CheckRemoteListing(t, nil, []string{"a", "b", "c", "d"})
}
func TestVFSMkdirAll(t *testing.T) {
r, vfs := newTestVFS(t)
if !r.Fremote.Features().CanHaveEmptyDirectories {
return // can't test if can't have empty directories
}
r.CheckRemoteListing(t, nil, []string{})
// Try making the root
err := vfs.MkdirAll("", 0777)
require.NoError(t, err)
r.CheckRemoteListing(t, nil, []string{})
// Try making a sub directory
err = vfs.MkdirAll("a/b/c/d", 0777)
require.NoError(t, err)
r.CheckRemoteListing(t, nil, []string{"a", "a/b", "a/b/c", "a/b/c/d"})
// Try making an existing directory
err = vfs.MkdirAll("a/b/c", 0777)
require.NoError(t, err)
r.CheckRemoteListing(t, nil, []string{"a", "a/b", "a/b/c", "a/b/c/d"})
// Try making an existing directory
err = vfs.MkdirAll("/a/b/c/", 0777)
require.NoError(t, err)
r.CheckRemoteListing(t, nil, []string{"a", "a/b", "a/b/c", "a/b/c/d"})
}
func TestFillInMissingSizes(t *testing.T) {
const unknownFree = 10
for _, test := range []struct {
total, free, used int64
wantTotal, wantUsed, wantFree int64
}{
{
total: 20, free: 5, used: 15,
wantTotal: 20, wantFree: 5, wantUsed: 15,
},
{
total: 20, free: 5, used: -1,
wantTotal: 20, wantFree: 5, wantUsed: 15,
},
{
total: 20, free: -1, used: 15,
wantTotal: 20, wantFree: 5, wantUsed: 15,
},
{
total: 20, free: -1, used: -1,
wantTotal: 20, wantFree: 20, wantUsed: 0,
},
{
total: -1, free: 5, used: 15,
wantTotal: 20, wantFree: 5, wantUsed: 15,
},
{
total: -1, free: 15, used: -1,
wantTotal: 15, wantFree: 15, wantUsed: 0,
},
{
total: -1, free: -1, used: 15,
wantTotal: 25, wantFree: 10, wantUsed: 15,
},
{
total: -1, free: -1, used: -1,
wantTotal: 10, wantFree: 10, wantUsed: 0,
},
} {
t.Run(fmt.Sprintf("total=%d,free=%d,used=%d", test.total, test.free, test.used), func(t *testing.T) {
gotTotal, gotUsed, gotFree := fillInMissingSizes(test.total, test.used, test.free, unknownFree)
assert.Equal(t, test.wantTotal, gotTotal, "total")
assert.Equal(t, test.wantUsed, gotUsed, "used")
assert.Equal(t, test.wantFree, gotFree, "free")
})
}
}
func TestVFSIsMetadataFile(t *testing.T) {
_, vfs := newTestVFS(t)
rawName, found := vfs.isMetadataFile("leaf.metadata")
assert.Equal(t, "leaf.metadata", rawName)
assert.Equal(t, false, found)
vfs.Opt.MetadataExtension = ".metadata"
rawName, found = vfs.isMetadataFile("leaf.metadata")
assert.Equal(t, "leaf", rawName)
assert.Equal(t, true, found)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/errors.go | vfs/errors.go | // Cross platform errors
package vfs
import (
"fmt"
"os"
)
// Error describes low level errors in a cross platform way.
type Error byte
// NB if changing errors, update translateError in cmd/mount/fs.go, cmd/cmount/fs.go, cmd/mount2/fs.go
// Low level errors
const (
OK Error = iota
ENOTEMPTY
ESPIPE
EBADF
EROFS
ENOSYS
ELOOP
)
// Errors which have exact counterparts in os
var (
ENOENT = os.ErrNotExist
EEXIST = os.ErrExist
EPERM = os.ErrPermission
EINVAL = os.ErrInvalid
ECLOSED = os.ErrClosed
)
var errorNames = []string{
OK: "Success",
ENOTEMPTY: "Directory not empty",
ESPIPE: "Illegal seek",
EBADF: "Bad file descriptor",
EROFS: "Read only file system",
ENOSYS: "Function not implemented",
ELOOP: "Too many symbolic links",
}
// Error renders the error as a string
func (e Error) Error() string {
if int(e) >= len(errorNames) {
return fmt.Sprintf("Low level error %d", e)
}
return errorNames[e]
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/write_test.go | vfs/write_test.go | package vfs
import (
"context"
"errors"
"io"
"os"
"runtime"
"sync"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/random"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Open a file for write
func writeHandleCreate(t *testing.T) (r *fstest.Run, vfs *VFS, fh *WriteFileHandle) {
r, vfs = newTestVFS(t)
h, err := vfs.OpenFile("file1", os.O_WRONLY|os.O_CREATE, 0777)
require.NoError(t, err)
fh, ok := h.(*WriteFileHandle)
require.True(t, ok)
return r, vfs, fh
}
// Test write when underlying storage is readonly, must be run as non-root
func TestWriteFileHandleReadonly(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skipf("Skipping test on %s", runtime.GOOS)
}
if *fstest.RemoteName != "" {
t.Skip("Skipping test on non local remote")
}
r, vfs, fh := writeHandleCreate(t)
// Name
assert.Equal(t, "file1", fh.Name())
// Write a file, so underlying remote will be created
_, err := fh.Write([]byte("hello"))
assert.NoError(t, err)
err = fh.Close()
assert.NoError(t, err)
var info os.FileInfo
info, err = os.Stat(r.FremoteName)
assert.NoError(t, err)
// Remove write permission
oldMode := info.Mode()
err = os.Chmod(r.FremoteName, oldMode^(oldMode&0222))
assert.NoError(t, err)
var h Handle
h, err = vfs.OpenFile("file2", os.O_WRONLY|os.O_CREATE, 0777)
require.NoError(t, err)
var ok bool
fh, ok = h.(*WriteFileHandle)
require.True(t, ok)
// error is propagated to Close()
_, err = fh.Write([]byte("hello"))
assert.NoError(t, err)
err = fh.Close()
assert.NotNil(t, err)
// Remove should fail
err = vfs.Remove("file1")
assert.NotNil(t, err)
// Only file1 should exist
_, err = vfs.Stat("file1")
assert.NoError(t, err)
_, err = vfs.Stat("file2")
assert.Equal(t, true, errors.Is(err, os.ErrNotExist))
// Restore old permission
err = os.Chmod(r.FremoteName, oldMode)
assert.NoError(t, err)
}
func TestWriteFileHandleMethods(t *testing.T) {
r, vfs, fh := writeHandleCreate(t)
// String
assert.Equal(t, "file1 (w)", fh.String())
assert.Equal(t, "<nil *WriteFileHandle>", (*WriteFileHandle)(nil).String())
assert.Equal(t, "<nil *WriteFileHandle.file>", new(WriteFileHandle).String())
// Node
node := fh.Node()
assert.Equal(t, "file1", node.Name())
// Offset #1
assert.Equal(t, int64(0), fh.Offset())
assert.Equal(t, int64(0), node.Size())
// Write (smoke test only since heavy lifting done in WriteAt)
n, err := fh.Write([]byte("hello"))
assert.NoError(t, err)
assert.Equal(t, 5, n)
// Offset #2
assert.Equal(t, int64(5), fh.Offset())
assert.Equal(t, int64(5), node.Size())
// Stat
var fi os.FileInfo
fi, err = fh.Stat()
assert.NoError(t, err)
assert.Equal(t, int64(5), fi.Size())
assert.Equal(t, "file1", fi.Name())
// Read
var buf = make([]byte, 16)
_, err = fh.Read(buf)
assert.Equal(t, EPERM, err)
// ReadAt
_, err = fh.ReadAt(buf, 0)
assert.Equal(t, EPERM, err)
// Sync
err = fh.Sync()
assert.NoError(t, err)
// Truncate - can only truncate where the file pointer is
err = fh.Truncate(5)
assert.NoError(t, err)
err = fh.Truncate(6)
assert.Equal(t, EPERM, err)
// Close
assert.NoError(t, fh.Close())
// Check double close
err = fh.Close()
assert.Equal(t, ECLOSED, err)
// check vfs
root, err := vfs.Root()
require.NoError(t, err)
checkListing(t, root, []string{"file1,5,false"})
// check the underlying r.Fremote but not the modtime
file1 := fstest.NewItem("file1", "hello", t1)
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1}, []string{}, fs.ModTimeNotSupported)
// Check trying to open the file now it exists then closing it
// immediately is OK
h, err := vfs.OpenFile("file1", os.O_WRONLY|os.O_CREATE, 0777)
require.NoError(t, err)
assert.NoError(t, h.Close())
checkListing(t, root, []string{"file1,5,false"})
// Check trying to open the file and writing it now it exists
// returns an error
h, err = vfs.OpenFile("file1", os.O_WRONLY|os.O_CREATE, 0777)
require.NoError(t, err)
_, err = h.Write([]byte("hello1"))
require.Equal(t, EPERM, err)
assert.NoError(t, h.Close())
checkListing(t, root, []string{"file1,5,false"})
// Check opening the file with O_TRUNC does actually truncate
// it even if we don't write to it
h, err = vfs.OpenFile("file1", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0777)
require.NoError(t, err)
err = h.Close()
if !errors.Is(err, fs.ErrorCantUploadEmptyFiles) {
assert.NoError(t, err)
checkListing(t, root, []string{"file1,0,false"})
}
// Check opening the file with O_TRUNC and writing does work
h, err = vfs.OpenFile("file1", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0777)
require.NoError(t, err)
_, err = h.WriteString("hello12")
require.NoError(t, err)
assert.NoError(t, h.Close())
checkListing(t, root, []string{"file1,7,false"})
}
func TestWriteFileHandleWriteAt(t *testing.T) {
r, vfs, fh := writeHandleCreate(t)
// Preconditions
assert.Equal(t, int64(0), fh.offset)
assert.False(t, fh.writeCalled)
// Write the data
n, err := fh.WriteAt([]byte("hello"), 0)
assert.NoError(t, err)
assert.Equal(t, 5, n)
// After write
assert.Equal(t, int64(5), fh.offset)
assert.True(t, fh.writeCalled)
// Check can't seek
n, err = fh.WriteAt([]byte("hello"), 100)
assert.Equal(t, ESPIPE, err)
assert.Equal(t, 0, n)
// Write more data
n, err = fh.WriteAt([]byte(" world"), 5)
assert.NoError(t, err)
assert.Equal(t, 6, n)
// Close
assert.NoError(t, fh.Close())
// Check can't write on closed handle
n, err = fh.WriteAt([]byte("hello"), 0)
assert.Equal(t, ECLOSED, err)
assert.Equal(t, 0, n)
// check vfs
root, err := vfs.Root()
require.NoError(t, err)
checkListing(t, root, []string{"file1,11,false"})
// check the underlying r.Fremote but not the modtime
file1 := fstest.NewItem("file1", "hello world", t1)
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1}, []string{}, fs.ModTimeNotSupported)
}
func TestWriteFileHandleFlush(t *testing.T) {
_, vfs, fh := writeHandleCreate(t)
// Check Flush already creates file for unwritten handles, without closing it
err := fh.Flush()
assert.NoError(t, err)
assert.False(t, fh.closed)
root, err := vfs.Root()
assert.NoError(t, err)
checkListing(t, root, []string{"file1,0,false"})
// Write some data
n, err := fh.Write([]byte("hello"))
assert.NoError(t, err)
assert.Equal(t, 5, n)
// Check Flush closes file if write called
err = fh.Flush()
assert.NoError(t, err)
assert.True(t, fh.closed)
// Check flush does nothing if called again
err = fh.Flush()
assert.NoError(t, err)
assert.True(t, fh.closed)
// Check file was written properly
root, err = vfs.Root()
assert.NoError(t, err)
checkListing(t, root, []string{"file1,5,false"})
}
func TestWriteFileHandleRelease(t *testing.T) {
_, _, fh := writeHandleCreate(t)
// Check Release closes file
err := fh.Release()
if errors.Is(err, fs.ErrorCantUploadEmptyFiles) {
t.Logf("skipping test: %v", err)
return
}
assert.NoError(t, err)
assert.True(t, fh.closed)
// Check Release does nothing if called again
err = fh.Release()
assert.NoError(t, err)
assert.True(t, fh.closed)
}
var (
canSetModTimeOnce sync.Once
canSetModTimeValue = true
)
// returns whether the remote can set modtime
func canSetModTime(t *testing.T, r *fstest.Run) bool {
canSetModTimeOnce.Do(func() {
mtime1 := time.Date(2008, time.November, 18, 17, 32, 31, 0, time.UTC)
_ = r.WriteObject(context.Background(), "time_test", "stuff", mtime1)
obj, err := r.Fremote.NewObject(context.Background(), "time_test")
require.NoError(t, err)
mtime2 := time.Date(2009, time.November, 18, 17, 32, 31, 0, time.UTC)
err = obj.SetModTime(context.Background(), mtime2)
switch err {
case nil:
canSetModTimeValue = true
case fs.ErrorCantSetModTime, fs.ErrorCantSetModTimeWithoutDelete:
canSetModTimeValue = false
default:
require.NoError(t, err)
}
require.NoError(t, obj.Remove(context.Background()))
fs.Debugf(nil, "Can set mod time: %v", canSetModTimeValue)
})
return canSetModTimeValue
}
// tests mod time on open files
func TestWriteFileModTimeWithOpenWriters(t *testing.T) {
r, vfs, fh := writeHandleCreate(t)
if !canSetModTime(t, r) {
t.Skip("can't set mod time")
}
mtime := time.Date(2012, time.November, 18, 17, 32, 31, 0, time.UTC)
_, err := fh.Write([]byte{104, 105})
require.NoError(t, err)
err = fh.Node().SetModTime(mtime)
require.NoError(t, err)
err = fh.Close()
require.NoError(t, err)
info, err := vfs.Stat("file1")
require.NoError(t, err)
if r.Fremote.Precision() != fs.ModTimeNotSupported {
// avoid errors because of timezone differences
assert.Equal(t, info.ModTime().Unix(), mtime.Unix())
}
}
func testFileReadAt(t *testing.T, n int) {
_, vfs, fh := writeHandleCreate(t)
contents := []byte(random.String(n))
if n != 0 {
written, err := fh.Write(contents)
require.NoError(t, err)
assert.Equal(t, n, written)
}
// Close the file without writing to it if n==0
err := fh.Close()
if errors.Is(err, fs.ErrorCantUploadEmptyFiles) {
t.Logf("skipping test: %v", err)
return
}
assert.NoError(t, err)
// read the file back in using ReadAt into a buffer
// this simulates what mount does
rd, err := vfs.OpenFile("file1", os.O_RDONLY, 0)
require.NoError(t, err)
buf := make([]byte, 1024)
read, err := rd.ReadAt(buf, 0)
if err != io.EOF {
assert.NoError(t, err)
}
assert.Equal(t, read, n)
assert.Equal(t, contents, buf[:read])
err = rd.Close()
assert.NoError(t, err)
}
func TestFileReadAtZeroLength(t *testing.T) {
testFileReadAt(t, 0)
}
func TestFileReadAtNonZeroLength(t *testing.T) {
testFileReadAt(t, 100)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/read_write_test.go | vfs/read_write_test.go | package vfs
import (
"context"
"errors"
"fmt"
"io"
"os"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Check interfaces
var (
_ io.Reader = (*RWFileHandle)(nil)
_ io.ReaderAt = (*RWFileHandle)(nil)
_ io.Writer = (*RWFileHandle)(nil)
_ io.WriterAt = (*RWFileHandle)(nil)
_ io.Seeker = (*RWFileHandle)(nil)
_ io.Closer = (*RWFileHandle)(nil)
_ Handle = (*RWFileHandle)(nil)
)
// Create a file and open it with the flags passed in
func rwHandleCreateFlags(t *testing.T, create bool, filename string, flags int) (r *fstest.Run, vfs *VFS, fh *RWFileHandle) {
opt := vfscommon.Opt
opt.CacheMode = vfscommon.CacheModeFull
opt.WriteBack = writeBackDelay
r, vfs = newTestVFSOpt(t, &opt)
if create {
file1 := r.WriteObject(context.Background(), filename, "0123456789abcdef", t1)
r.CheckRemoteItems(t, file1)
}
h, err := vfs.OpenFile(filename, flags, 0777)
require.NoError(t, err)
fh, ok := h.(*RWFileHandle)
require.True(t, ok)
return r, vfs, fh
}
// Open a file for read
func rwHandleCreateReadOnly(t *testing.T) (r *fstest.Run, vfs *VFS, fh *RWFileHandle) {
return rwHandleCreateFlags(t, true, "dir/file1", os.O_RDONLY)
}
// Open a file for write
func rwHandleCreateWriteOnly(t *testing.T) (r *fstest.Run, vfs *VFS, fh *RWFileHandle) {
return rwHandleCreateFlags(t, false, "file1", os.O_WRONLY|os.O_CREATE)
}
// read data from the string
func rwReadString(t *testing.T, fh *RWFileHandle, n int) string {
buf := make([]byte, n)
n, err := fh.Read(buf)
if err != io.EOF {
assert.NoError(t, err)
}
return string(buf[:n])
}
func TestRWFileHandleMethodsRead(t *testing.T) {
_, _, fh := rwHandleCreateReadOnly(t)
// String
assert.Equal(t, "dir/file1 (rw)", fh.String())
assert.Equal(t, "<nil *RWFileHandle>", (*RWFileHandle)(nil).String())
assert.Equal(t, "<nil *RWFileHandle.file>", new(RWFileHandle).String())
// Node
node := fh.Node()
assert.Equal(t, "file1", node.Name())
// Size
assert.Equal(t, int64(16), fh.Size())
// Read 1
assert.Equal(t, "0", rwReadString(t, fh, 1))
// Read remainder
assert.Equal(t, "123456789abcdef", rwReadString(t, fh, 256))
// Read EOF
buf := make([]byte, 16)
_, err := fh.Read(buf)
assert.Equal(t, io.EOF, err)
// Sync
err = fh.Sync()
assert.NoError(t, err)
// Stat
var fi os.FileInfo
fi, err = fh.Stat()
assert.NoError(t, err)
assert.Equal(t, int64(16), fi.Size())
assert.Equal(t, "file1", fi.Name())
// Close
assert.False(t, fh.closed)
assert.Equal(t, nil, fh.Close())
assert.True(t, fh.closed)
// Close again
assert.Equal(t, ECLOSED, fh.Close())
}
func TestRWFileHandleSeek(t *testing.T) {
_, _, fh := rwHandleCreateReadOnly(t)
assert.Equal(t, fh.opened, false)
// Check null seeks don't open the file
n, err := fh.Seek(0, io.SeekStart)
assert.NoError(t, err)
assert.Equal(t, int64(0), n)
assert.Equal(t, fh.opened, false)
n, err = fh.Seek(0, io.SeekCurrent)
assert.NoError(t, err)
assert.Equal(t, int64(0), n)
assert.Equal(t, fh.opened, false)
assert.Equal(t, "0", rwReadString(t, fh, 1))
// 0 means relative to the origin of the file,
n, err = fh.Seek(5, io.SeekStart)
assert.NoError(t, err)
assert.Equal(t, int64(5), n)
assert.Equal(t, "5", rwReadString(t, fh, 1))
// 1 means relative to the current offset
n, err = fh.Seek(-3, io.SeekCurrent)
assert.NoError(t, err)
assert.Equal(t, int64(3), n)
assert.Equal(t, "3", rwReadString(t, fh, 1))
// 2 means relative to the end.
n, err = fh.Seek(-3, io.SeekEnd)
assert.NoError(t, err)
assert.Equal(t, int64(13), n)
assert.Equal(t, "d", rwReadString(t, fh, 1))
// Seek off the end
_, err = fh.Seek(100, io.SeekStart)
assert.NoError(t, err)
// Get the error on read
buf := make([]byte, 16)
l, err := fh.Read(buf)
assert.Equal(t, io.EOF, err)
assert.Equal(t, 0, l)
// Close
assert.Equal(t, nil, fh.Close())
}
func TestRWFileHandleReadAt(t *testing.T) {
_, _, fh := rwHandleCreateReadOnly(t)
// read from start
buf := make([]byte, 1)
n, err := fh.ReadAt(buf, 0)
require.NoError(t, err)
assert.Equal(t, 1, n)
assert.Equal(t, "0", string(buf[:n]))
// seek forwards
n, err = fh.ReadAt(buf, 5)
require.NoError(t, err)
assert.Equal(t, 1, n)
assert.Equal(t, "5", string(buf[:n]))
// seek backwards
n, err = fh.ReadAt(buf, 1)
require.NoError(t, err)
assert.Equal(t, 1, n)
assert.Equal(t, "1", string(buf[:n]))
// read exactly to the end
buf = make([]byte, 6)
n, err = fh.ReadAt(buf, 10)
require.NoError(t, err)
assert.Equal(t, 6, n)
assert.Equal(t, "abcdef", string(buf[:n]))
// read off the end
buf = make([]byte, 256)
n, err = fh.ReadAt(buf, 10)
assert.Equal(t, io.EOF, err)
assert.Equal(t, 6, n)
assert.Equal(t, "abcdef", string(buf[:n]))
// read starting off the end
n, err = fh.ReadAt(buf, 100)
assert.Equal(t, io.EOF, err)
assert.Equal(t, 0, n)
// Properly close the file
assert.NoError(t, fh.Close())
// check reading on closed file
_, err = fh.ReadAt(buf, 100)
assert.Equal(t, ECLOSED, err)
}
func TestRWFileHandleFlushRead(t *testing.T) {
_, _, fh := rwHandleCreateReadOnly(t)
// Check Flush does nothing if read not called
err := fh.Flush()
assert.NoError(t, err)
assert.False(t, fh.closed)
// Read data
buf := make([]byte, 256)
n, err := fh.Read(buf)
assert.True(t, err == io.EOF || err == nil)
assert.Equal(t, 16, n)
// Check Flush does nothing if read called
err = fh.Flush()
assert.NoError(t, err)
assert.False(t, fh.closed)
// Check flush does nothing if called again
err = fh.Flush()
assert.NoError(t, err)
assert.False(t, fh.closed)
// Properly close the file
assert.NoError(t, fh.Close())
}
func TestRWFileHandleReleaseRead(t *testing.T) {
_, _, fh := rwHandleCreateReadOnly(t)
// Read data
buf := make([]byte, 256)
n, err := fh.Read(buf)
assert.True(t, err == io.EOF || err == nil)
assert.Equal(t, 16, n)
// Check Release closes file
err = fh.Release()
assert.NoError(t, err)
assert.True(t, fh.closed)
// Check Release does nothing if called again
err = fh.Release()
assert.NoError(t, err)
assert.True(t, fh.closed)
}
/// ------------------------------------------------------------
func TestRWFileHandleMethodsWrite(t *testing.T) {
r, vfs, fh := rwHandleCreateWriteOnly(t)
// String
assert.Equal(t, "file1 (rw)", fh.String())
assert.Equal(t, "<nil *RWFileHandle>", (*RWFileHandle)(nil).String())
assert.Equal(t, "<nil *RWFileHandle.file>", new(RWFileHandle).String())
// Node
node := fh.Node()
assert.Equal(t, "file1", node.Name())
offset := func() int64 {
n, err := fh.Seek(0, io.SeekCurrent)
require.NoError(t, err)
return n
}
// Offset #1
assert.Equal(t, int64(0), offset())
assert.Equal(t, int64(0), node.Size())
// Size #1
assert.Equal(t, int64(0), fh.Size())
// Write
n, err := fh.Write([]byte("hello"))
assert.NoError(t, err)
assert.Equal(t, 5, n)
// Offset #2
assert.Equal(t, int64(5), offset())
assert.Equal(t, int64(5), node.Size())
// Size #2
assert.Equal(t, int64(5), fh.Size())
// WriteString
n, err = fh.WriteString(" world!")
assert.NoError(t, err)
assert.Equal(t, 7, n)
// Sync
err = fh.Sync()
assert.NoError(t, err)
// Stat
var fi os.FileInfo
fi, err = fh.Stat()
assert.NoError(t, err)
assert.Equal(t, int64(12), fi.Size())
assert.Equal(t, "file1", fi.Name())
// Truncate
err = fh.Truncate(11)
assert.NoError(t, err)
// Close
assert.NoError(t, fh.Close())
// Check double close
err = fh.Close()
assert.Equal(t, ECLOSED, err)
// check vfs
root, err := vfs.Root()
require.NoError(t, err)
checkListing(t, root, []string{"file1,11,false"})
// check the underlying r.Fremote but not the modtime
file1 := fstest.NewItem("file1", "hello world", t1)
vfs.WaitForWriters(waitForWritersDelay)
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1}, []string{}, fs.ModTimeNotSupported)
}
func TestRWFileHandleWriteAt(t *testing.T) {
r, vfs, fh := rwHandleCreateWriteOnly(t)
offset := func() int64 {
n, err := fh.Seek(0, io.SeekCurrent)
require.NoError(t, err)
return n
}
// Name
assert.Equal(t, "file1", fh.Name())
// Preconditions
assert.Equal(t, int64(0), offset())
assert.True(t, fh.opened)
assert.False(t, fh.writeCalled)
// Write the data
n, err := fh.WriteAt([]byte("hello**"), 0)
assert.NoError(t, err)
assert.Equal(t, 7, n)
// After write
assert.Equal(t, int64(0), offset())
assert.True(t, fh.writeCalled)
// Write more data
n, err = fh.WriteAt([]byte(" world"), 5)
assert.NoError(t, err)
assert.Equal(t, 6, n)
// Close
assert.NoError(t, fh.Close())
// Check can't write on closed handle
n, err = fh.WriteAt([]byte("hello"), 0)
assert.Equal(t, ECLOSED, err)
assert.Equal(t, 0, n)
// check vfs
root, err := vfs.Root()
require.NoError(t, err)
checkListing(t, root, []string{"file1,11,false"})
// check the underlying r.Fremote but not the modtime
file1 := fstest.NewItem("file1", "hello world", t1)
vfs.WaitForWriters(waitForWritersDelay)
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1}, []string{}, fs.ModTimeNotSupported)
}
func TestRWFileHandleWriteNoWrite(t *testing.T) {
r, vfs, fh := rwHandleCreateWriteOnly(t)
// Close the file without writing to it
err := fh.Close()
if errors.Is(err, fs.ErrorCantUploadEmptyFiles) {
t.Logf("skipping test: %v", err)
return
}
assert.NoError(t, err)
// Create a different file (not in the cache)
h, err := vfs.OpenFile("file2", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0777)
require.NoError(t, err)
// Close it with Flush and Release
err = h.Flush()
assert.NoError(t, err)
err = h.Release()
assert.NoError(t, err)
// check vfs
root, err := vfs.Root()
require.NoError(t, err)
checkListing(t, root, []string{"file1,0,false", "file2,0,false"})
// check the underlying r.Fremote but not the modtime
file1 := fstest.NewItem("file1", "", t1)
file2 := fstest.NewItem("file2", "", t1)
vfs.WaitForWriters(waitForWritersDelay)
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{file1, file2}, []string{}, fs.ModTimeNotSupported)
}
func TestRWFileHandleFlushWrite(t *testing.T) {
_, _, fh := rwHandleCreateWriteOnly(t)
// Check that the file has been create and is open
assert.True(t, fh.opened)
// Write some data
n, err := fh.Write([]byte("hello"))
assert.NoError(t, err)
assert.Equal(t, 5, n)
assert.True(t, fh.opened)
// Check Flush does not close file if write called
err = fh.Flush()
assert.NoError(t, err)
assert.False(t, fh.closed)
// Check flush does nothing if called again
err = fh.Flush()
assert.NoError(t, err)
assert.False(t, fh.closed)
// Check that Close closes the file
err = fh.Close()
assert.NoError(t, err)
assert.True(t, fh.closed)
}
func TestRWFileHandleReleaseWrite(t *testing.T) {
_, _, fh := rwHandleCreateWriteOnly(t)
// Write some data
n, err := fh.Write([]byte("hello"))
assert.NoError(t, err)
assert.Equal(t, 5, n)
// Check Release closes file
err = fh.Release()
assert.NoError(t, err)
assert.True(t, fh.closed)
// Check Release does nothing if called again
err = fh.Release()
assert.NoError(t, err)
assert.True(t, fh.closed)
}
// check the size of the file through the open file (if not nil) and via stat
func assertSize(t *testing.T, vfs *VFS, fh *RWFileHandle, filepath string, size int64) {
if fh != nil {
assert.Equal(t, size, fh.Size())
}
fi, err := vfs.Stat(filepath)
require.NoError(t, err)
assert.Equal(t, size, fi.Size())
}
func TestRWFileHandleSizeTruncateExisting(t *testing.T) {
_, vfs, fh := rwHandleCreateFlags(t, true, "dir/file1", os.O_WRONLY|os.O_TRUNC)
// check initial size after opening
assertSize(t, vfs, fh, "dir/file1", 0)
// write some bytes
n, err := fh.Write([]byte("hello"))
assert.NoError(t, err)
assert.Equal(t, 5, n)
// check size after writing
assertSize(t, vfs, fh, "dir/file1", 5)
// close
assert.NoError(t, fh.Close())
// check size after close
assertSize(t, vfs, nil, "dir/file1", 5)
}
func TestRWFileHandleSizeCreateExisting(t *testing.T) {
_, vfs, fh := rwHandleCreateFlags(t, true, "dir/file1", os.O_WRONLY|os.O_CREATE)
// check initial size after opening
assertSize(t, vfs, fh, "dir/file1", 16)
// write some bytes
n, err := fh.Write([]byte("hello"))
assert.NoError(t, err)
assert.Equal(t, 5, n)
// check size after writing
assertSize(t, vfs, fh, "dir/file1", 16)
// write some more bytes
n, err = fh.Write([]byte("helloHELLOhello"))
assert.NoError(t, err)
assert.Equal(t, 15, n)
// check size after writing
assertSize(t, vfs, fh, "dir/file1", 20)
// close
assert.NoError(t, fh.Close())
// check size after close
assertSize(t, vfs, nil, "dir/file1", 20)
}
func TestRWFileHandleSizeCreateNew(t *testing.T) {
_, vfs, fh := rwHandleCreateFlags(t, false, "file1", os.O_WRONLY|os.O_CREATE)
// check initial size after opening
assertSize(t, vfs, fh, "file1", 0)
// write some bytes
n, err := fh.Write([]byte("hello"))
assert.NoError(t, err)
assert.Equal(t, 5, n)
// check size after writing
assertSize(t, vfs, fh, "file1", 5)
// check size after writing
assertSize(t, vfs, fh, "file1", 5)
// close
assert.NoError(t, fh.Close())
// check size after close
assertSize(t, vfs, nil, "file1", 5)
}
func testRWFileHandleOpenTest(t *testing.T, vfs *VFS, test *openTest) {
fileName := "open-test-file"
// Make sure we delete the file on failure too
defer func() {
_ = vfs.Remove(fileName)
}()
// first try with file not existing
_, err := vfs.Stat(fileName)
require.True(t, os.IsNotExist(err))
f, openNonExistentErr := vfs.OpenFile(fileName, test.flags, 0666)
var readNonExistentErr error
var writeNonExistentErr error
if openNonExistentErr == nil {
// read some bytes
buf := []byte{0, 0}
_, readNonExistentErr = f.Read(buf)
// write some bytes
_, writeNonExistentErr = f.Write([]byte("hello"))
// close
err = f.Close()
require.NoError(t, err)
}
// write the file
f, err = vfs.OpenFile(fileName, os.O_WRONLY|os.O_CREATE, 0777)
require.NoError(t, err)
_, err = f.Write([]byte("hello"))
require.NoError(t, err)
err = f.Close()
require.NoError(t, err)
// then open file and try with file existing
f, openExistingErr := vfs.OpenFile(fileName, test.flags, 0666)
var readExistingErr error
var writeExistingErr error
if openExistingErr == nil {
// read some bytes
buf := []byte{0, 0}
_, readExistingErr = f.Read(buf)
// write some bytes
_, writeExistingErr = f.Write([]byte("HEL"))
// close
err = f.Close()
require.NoError(t, err)
}
// read the file
f, err = vfs.OpenFile(fileName, os.O_RDONLY, 0)
require.NoError(t, err)
buf, err := io.ReadAll(f)
require.NoError(t, err)
err = f.Close()
require.NoError(t, err)
contents := string(buf)
// remove file
node, err := vfs.Stat(fileName)
require.NoError(t, err)
err = node.Remove()
require.NoError(t, err)
// check
assert.Equal(t, test.openNonExistentErr, openNonExistentErr, "openNonExistentErr: want=%v, got=%v", test.openNonExistentErr, openNonExistentErr)
assert.Equal(t, test.readNonExistentErr, readNonExistentErr, "readNonExistentErr: want=%v, got=%v", test.readNonExistentErr, readNonExistentErr)
assert.Equal(t, test.writeNonExistentErr, writeNonExistentErr, "writeNonExistentErr: want=%v, got=%v", test.writeNonExistentErr, writeNonExistentErr)
assert.Equal(t, test.openExistingErr, openExistingErr, "openExistingErr: want=%v, got=%v", test.openExistingErr, openExistingErr)
assert.Equal(t, test.readExistingErr, readExistingErr, "readExistingErr: want=%v, got=%v", test.readExistingErr, readExistingErr)
assert.Equal(t, test.writeExistingErr, writeExistingErr, "writeExistingErr: want=%v, got=%v", test.writeExistingErr, writeExistingErr)
assert.Equal(t, test.contents, contents)
}
func TestRWFileHandleOpenTests(t *testing.T) {
for _, cacheMode := range []vfscommon.CacheMode{vfscommon.CacheModeWrites, vfscommon.CacheModeFull} {
t.Run(cacheMode.String(), func(t *testing.T) {
opt := vfscommon.Opt
opt.CacheMode = cacheMode
opt.WriteBack = writeBackDelay
_, vfs := newTestVFSOpt(t, &opt)
for _, test := range openTests {
t.Run(test.what, func(t *testing.T) {
testRWFileHandleOpenTest(t, vfs, &test)
})
}
})
}
}
// tests mod time on open files
func TestRWFileModTimeWithOpenWriters(t *testing.T) {
r, vfs, fh := rwHandleCreateWriteOnly(t)
if !canSetModTime(t, r) {
t.Skip("can't set mod time")
}
mtime := time.Date(2012, time.November, 18, 17, 32, 31, 0, time.UTC)
_, err := fh.Write([]byte{104, 105})
require.NoError(t, err)
err = fh.Node().SetModTime(mtime)
require.NoError(t, err)
// Using Flush/Release to mimic mount instead of Close
err = fh.Flush()
require.NoError(t, err)
err = fh.Release()
require.NoError(t, err)
info, err := vfs.Stat("file1")
require.NoError(t, err)
if r.Fremote.Precision() != fs.ModTimeNotSupported {
// avoid errors because of timezone differences
assert.Equal(t, info.ModTime().Unix(), mtime.Unix(), fmt.Sprintf("Time mismatch: %v != %v", info.ModTime(), mtime))
}
file1 := fstest.NewItem("file1", "hi", mtime)
vfs.WaitForWriters(waitForWritersDelay)
r.CheckRemoteItems(t, file1)
}
func TestRWCacheRename(t *testing.T) {
opt := vfscommon.Opt
opt.CacheMode = vfscommon.CacheModeFull
opt.WriteBack = writeBackDelay
r, vfs := newTestVFSOpt(t, &opt)
if !operations.CanServerSideMove(r.Fremote) {
t.Skip("skip as can't rename files")
}
h, err := vfs.OpenFile("rename_me", os.O_WRONLY|os.O_CREATE, 0777)
require.NoError(t, err)
_, err = h.WriteString("hello")
require.NoError(t, err)
fh, ok := h.(*RWFileHandle)
require.True(t, ok)
err = fh.Sync()
require.NoError(t, err)
err = fh.Close()
require.NoError(t, err)
assert.True(t, vfs.cache.Exists("rename_me"))
err = vfs.Rename("rename_me", "i_was_renamed")
require.NoError(t, err)
assert.False(t, vfs.cache.Exists("rename_me"))
assert.True(t, vfs.cache.Exists("i_was_renamed"))
}
// Test the cache reading a file that is updated externally
//
// See: https://github.com/rclone/rclone/issues/6053
func TestRWCacheUpdate(t *testing.T) {
opt := vfscommon.Opt
opt.CacheMode = vfscommon.CacheModeFull
opt.WriteBack = writeBackDelay
opt.DirCacheTime = fs.Duration(100 * time.Millisecond)
r, vfs := newTestVFSOpt(t, &opt)
if r.Fremote.Precision() == fs.ModTimeNotSupported {
t.Skip("skip as modtime not supported")
}
const filename = "TestRWCacheUpdate"
modTime := time.Now().Add(-time.Hour)
for i := range 10 {
modTime = modTime.Add(time.Minute)
// Refresh test file
contents := fmt.Sprintf("TestRWCacheUpdate%03d", i)
// Increase the size for second half of test
for j := 5; j < i; j++ {
contents += "*"
}
file1 := r.WriteObject(context.Background(), filename, contents, modTime)
r.CheckRemoteItems(t, file1)
// Wait for directory cache to expire
time.Sleep(time.Duration(2 * opt.DirCacheTime))
// Check the file is OK via the VFS
data, err := vfs.ReadFile(filename)
require.NoError(t, err)
require.Equal(t, contents, string(data))
// Check Stat
fi, err := vfs.Stat(filename)
require.NoError(t, err)
assert.Equal(t, int64(len(contents)), fi.Size())
fstest.AssertTimeEqualWithPrecision(t, filename, modTime, fi.ModTime(), r.Fremote.Precision())
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/zip.go | vfs/zip.go | package vfs
import (
"archive/zip"
"context"
"fmt"
"io"
"os"
"github.com/rclone/rclone/fs"
)
// CreateZip creates a zip file from a vfs.Dir writing it to w
func CreateZip(ctx context.Context, dir *Dir, w io.Writer) (err error) {
zipWriter := zip.NewWriter(w)
defer fs.CheckClose(zipWriter, &err)
var walk func(dir *Dir, root string) error
walk = func(dir *Dir, root string) error {
nodes, err := dir.ReadDirAll()
if err != nil {
return fmt.Errorf("create zip directory read: %w", err)
}
for _, node := range nodes {
switch e := node.(type) {
case *File:
in, err := e.Open(os.O_RDONLY)
if err != nil {
return fmt.Errorf("create zip open file: %w", err)
}
header := &zip.FileHeader{
Name: root + e.Name(),
Method: zip.Deflate,
Modified: e.ModTime(),
}
fileWriter, err := zipWriter.CreateHeader(header)
if err != nil {
fs.CheckClose(in, &err)
return fmt.Errorf("create zip file header: %w", err)
}
_, err = io.Copy(fileWriter, in)
if err != nil {
fs.CheckClose(in, &err)
return fmt.Errorf("create zip copy: %w", err)
}
fs.CheckClose(in, &err)
case *Dir:
name := root + e.Path()
if name != "" && name[len(name)-1] != '/' {
name += "/"
}
header := &zip.FileHeader{
Name: name,
Method: zip.Store,
Modified: e.ModTime(),
}
_, err := zipWriter.CreateHeader(header)
if err != nil {
return fmt.Errorf("create zip directory header: %w", err)
}
err = walk(e, name)
if err != nil {
return err
}
}
}
return nil
}
err = walk(dir, "")
if err != nil {
return err
}
return nil
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/file_test.go | vfs/file_test.go | package vfs
import (
"context"
"fmt"
"io"
"os"
"testing"
"unsafe"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/fstest/mockfs"
"github.com/rclone/rclone/fstest/mockobject"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func fileCreate(t *testing.T, mode vfscommon.CacheMode) (r *fstest.Run, vfs *VFS, fh *File, item fstest.Item) {
opt := vfscommon.Opt
opt.CacheMode = mode
opt.WriteBack = writeBackDelay
r, vfs = newTestVFSOpt(t, &opt)
file1 := r.WriteObject(context.Background(), "dir/file1", "file1 contents", t1)
r.CheckRemoteItems(t, file1)
node, err := vfs.Stat("dir/file1")
require.NoError(t, err)
require.True(t, node.Mode().IsRegular())
return r, vfs, node.(*File), file1
}
func TestFileMethods(t *testing.T) {
r, vfs, file, _ := fileCreate(t, vfscommon.CacheModeOff)
// String
assert.Equal(t, "dir/file1", file.String())
assert.Equal(t, "<nil *File>", (*File)(nil).String())
// IsDir
assert.Equal(t, false, file.IsDir())
// IsFile
assert.Equal(t, true, file.IsFile())
// Mode
assert.Equal(t, os.FileMode(vfs.Opt.FilePerms), file.Mode())
// Name
assert.Equal(t, "file1", file.Name())
// Path
assert.Equal(t, "dir/file1", file.Path())
// Sys
assert.Equal(t, nil, file.Sys())
// SetSys
file.SetSys(42)
assert.Equal(t, 42, file.Sys())
// Inode
assert.NotEqual(t, uint64(0), file.Inode())
// Node
assert.Equal(t, file, file.Node())
// ModTime
assert.WithinDuration(t, t1, file.ModTime(), r.Fremote.Precision())
// Size
assert.Equal(t, int64(14), file.Size())
// Sync
assert.NoError(t, file.Sync())
// DirEntry
assert.Equal(t, file.o, file.DirEntry())
// Dir
assert.Equal(t, file.d, file.Dir())
// VFS
assert.Equal(t, vfs, file.VFS())
}
func testFileSetModTime(t *testing.T, cacheMode vfscommon.CacheMode, open bool, write bool) {
if !canSetModTimeValue {
t.Skip("can't set mod time")
}
r, vfs, file, file1 := fileCreate(t, cacheMode)
if !canSetModTime(t, r) {
t.Skip("can't set mod time")
}
var (
err error
fd Handle
contents = "file1 contents"
)
if open {
// Open with write intent
if cacheMode != vfscommon.CacheModeOff {
fd, err = file.Open(os.O_WRONLY)
if write {
contents = "hello contents"
}
} else {
// Can't write without O_TRUNC with CacheMode Off
fd, err = file.Open(os.O_WRONLY | os.O_TRUNC)
if write {
contents = "hello"
} else {
contents = ""
}
}
require.NoError(t, err)
// Write some data
if write {
_, err = fd.WriteString("hello")
require.NoError(t, err)
}
}
err = file.SetModTime(t2)
require.NoError(t, err)
if open {
require.NoError(t, fd.Close())
vfs.WaitForWriters(waitForWritersDelay)
}
file1 = fstest.NewItem(file1.Path, contents, t2)
r.CheckRemoteItems(t, file1)
vfs.Opt.ReadOnly = true
err = file.SetModTime(t2)
assert.Equal(t, EROFS, err)
}
// Test various combinations of setting mod times with and
// without the cache and with and without opening or writing
// to the file.
//
// Each of these tests a different path through the VFS code.
func TestFileSetModTime(t *testing.T) {
for _, cacheMode := range []vfscommon.CacheMode{vfscommon.CacheModeOff, vfscommon.CacheModeFull} {
for _, open := range []bool{false, true} {
for _, write := range []bool{false, true} {
if write && !open {
continue
}
t.Run(fmt.Sprintf("cache=%v,open=%v,write=%v", cacheMode, open, write), func(t *testing.T) {
testFileSetModTime(t, cacheMode, open, write)
})
}
}
}
}
func fileCheckContents(t *testing.T, file *File) {
fd, err := file.Open(os.O_RDONLY)
require.NoError(t, err)
contents, err := io.ReadAll(fd)
require.NoError(t, err)
assert.Equal(t, "file1 contents", string(contents))
require.NoError(t, fd.Close())
}
func TestFileOpenRead(t *testing.T) {
_, _, file, _ := fileCreate(t, vfscommon.CacheModeOff)
fileCheckContents(t, file)
}
func TestFileOpenReadUnknownSize(t *testing.T) {
var (
contents = []byte("file contents")
remote = "file.txt"
ctx = context.Background()
)
// create a mock object which returns size -1
o := mockobject.New(remote).WithContent(contents, mockobject.SeekModeNone)
o.SetUnknownSize(true)
assert.Equal(t, int64(-1), o.Size())
// add it to a mock fs
fMock, err := mockfs.NewFs(context.Background(), "test", "root", nil)
require.NoError(t, err)
f := fMock.(*mockfs.Fs)
f.AddObject(o)
testObj, err := f.NewObject(ctx, remote)
require.NoError(t, err)
assert.Equal(t, int64(-1), testObj.Size())
// create a VFS from that mockfs
vfs := New(f, nil)
defer cleanupVFS(t, vfs)
// find the file
node, err := vfs.Stat(remote)
require.NoError(t, err)
require.True(t, node.IsFile())
file := node.(*File)
// open it
fd, err := file.openRead()
require.NoError(t, err)
assert.Equal(t, int64(0), fd.Size())
// check the contents are not empty even though size is empty
gotContents, err := io.ReadAll(fd)
require.NoError(t, err)
assert.Equal(t, contents, gotContents)
t.Logf("gotContents = %q", gotContents)
// check that file size has been updated
assert.Equal(t, int64(len(contents)), fd.Size())
require.NoError(t, fd.Close())
}
func TestFileOpenWrite(t *testing.T) {
_, vfs, file, _ := fileCreate(t, vfscommon.CacheModeOff)
fd, err := file.openWrite(os.O_WRONLY | os.O_TRUNC)
require.NoError(t, err)
newContents := []byte("this is some new contents")
n, err := fd.Write(newContents)
require.NoError(t, err)
assert.Equal(t, len(newContents), n)
require.NoError(t, fd.Close())
assert.Equal(t, int64(25), file.Size())
vfs.Opt.ReadOnly = true
_, err = file.openWrite(os.O_WRONLY | os.O_TRUNC)
assert.Equal(t, EROFS, err)
}
func TestFileRemove(t *testing.T) {
r, vfs, file, _ := fileCreate(t, vfscommon.CacheModeOff)
err := file.Remove()
require.NoError(t, err)
r.CheckRemoteItems(t)
vfs.Opt.ReadOnly = true
err = file.Remove()
assert.Equal(t, EROFS, err)
}
func TestFileRemoveAll(t *testing.T) {
r, vfs, file, _ := fileCreate(t, vfscommon.CacheModeOff)
err := file.RemoveAll()
require.NoError(t, err)
r.CheckRemoteItems(t)
vfs.Opt.ReadOnly = true
err = file.RemoveAll()
assert.Equal(t, EROFS, err)
}
func TestFileOpen(t *testing.T) {
_, _, file, _ := fileCreate(t, vfscommon.CacheModeOff)
fd, err := file.Open(os.O_RDONLY)
require.NoError(t, err)
_, ok := fd.(*ReadFileHandle)
assert.True(t, ok)
require.NoError(t, fd.Close())
fd, err = file.Open(os.O_WRONLY)
assert.NoError(t, err)
_, ok = fd.(*WriteFileHandle)
assert.True(t, ok)
require.NoError(t, fd.Close())
fd, err = file.Open(os.O_RDWR)
assert.NoError(t, err)
_, ok = fd.(*WriteFileHandle)
assert.True(t, ok)
require.NoError(t, fd.Close())
_, err = file.Open(3)
assert.Equal(t, EPERM, err)
}
func testFileRename(t *testing.T, mode vfscommon.CacheMode, inCache bool, forceCache bool) {
r, vfs, file, item := fileCreate(t, mode)
if !operations.CanServerSideMove(r.Fremote) {
t.Skip("skip as can't rename files")
}
rootDir, err := vfs.Root()
require.NoError(t, err)
// force the file into the cache if required
if forceCache {
// write the file with read and write
fd, err := file.Open(os.O_RDWR | os.O_CREATE | os.O_TRUNC)
require.NoError(t, err)
n, err := fd.Write([]byte("file1 contents"))
require.NoError(t, err)
require.Equal(t, 14, n)
require.NoError(t, file.SetModTime(item.ModTime))
err = fd.Close()
require.NoError(t, err)
}
vfs.WaitForWriters(waitForWritersDelay)
// check file in cache
if inCache {
// read contents to get file in cache
fileCheckContents(t, file)
assert.True(t, vfs.cache.Exists(item.Path))
}
dir := file.Dir()
// start with "dir/file1"
r.CheckRemoteItems(t, item)
// rename file to "newLeaf"
err = dir.Rename("file1", "newLeaf", rootDir)
require.NoError(t, err)
item.Path = "newLeaf"
r.CheckRemoteItems(t, item)
// check file in cache
if inCache {
assert.True(t, vfs.cache.Exists(item.Path))
}
// check file exists in the vfs layer at its new name
_, err = vfs.Stat("newLeaf")
require.NoError(t, err)
// rename it back to "dir/file1"
err = rootDir.Rename("newLeaf", "file1", dir)
require.NoError(t, err)
item.Path = "dir/file1"
r.CheckRemoteItems(t, item)
// check file in cache
if inCache {
assert.True(t, vfs.cache.Exists(item.Path))
}
// now try renaming it with the file open
// first open it and write to it but don't close it
fd, err := file.Open(os.O_WRONLY | os.O_TRUNC)
require.NoError(t, err)
newContents := []byte("this is some new contents")
_, err = fd.Write(newContents)
require.NoError(t, err)
// rename file to "newLeaf"
err = dir.Rename("file1", "newLeaf", rootDir)
require.NoError(t, err)
newItem := fstest.NewItem("newLeaf", string(newContents), item.ModTime)
// check file has been renamed immediately in the cache
if inCache {
assert.True(t, vfs.cache.Exists("newLeaf"))
}
// check file exists in the vfs layer at its new name
_, err = vfs.Stat("newLeaf")
require.NoError(t, err)
// Close the file
require.NoError(t, fd.Close())
// Check file has now been renamed on the remote
item.Path = "newLeaf"
vfs.WaitForWriters(waitForWritersDelay)
fstest.CheckListingWithPrecision(t, r.Fremote, []fstest.Item{newItem}, nil, fs.ModTimeNotSupported)
}
func TestFileRename(t *testing.T) {
for _, test := range []struct {
mode vfscommon.CacheMode
inCache bool
forceCache bool
}{
{mode: vfscommon.CacheModeOff, inCache: false},
{mode: vfscommon.CacheModeMinimal, inCache: false},
{mode: vfscommon.CacheModeMinimal, inCache: true, forceCache: true},
{mode: vfscommon.CacheModeWrites, inCache: false},
{mode: vfscommon.CacheModeWrites, inCache: true, forceCache: true},
{mode: vfscommon.CacheModeFull, inCache: true},
} {
t.Run(fmt.Sprintf("%v,forceCache=%v", test.mode, test.forceCache), func(t *testing.T) {
testFileRename(t, test.mode, test.inCache, test.forceCache)
})
}
}
func TestFileStructSize(t *testing.T) {
t.Logf("File struct has size %d bytes", unsafe.Sizeof(File{}))
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfs.go | vfs/vfs.go | // Package vfs provides a virtual filing system layer over rclone's
// native objects.
//
// It attempts to behave in a similar way to Go's filing system
// manipulation code in the os package. The same named function
// should behave in an identical fashion. The objects also obey Go's
// standard interfaces.
//
// Note that paths don't start or end with /, so the root directory
// may be referred to as "". However Stat strips slashes so you can
// use paths with slashes in.
//
// # It also includes directory caching
//
// The vfs package returns Error values to signal precisely which
// error conditions have occurred. It may also return general errors
// it receives. It tries to use os Error values (e.g. os.ErrExist)
// where possible.
//
//go:generate sh -c "go run make_open_tests.go | gofmt > open_test.go"
package vfs
import (
"context"
_ "embed"
"fmt"
"io"
"os"
"path"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"slices"
"github.com/go-git/go-billy/v5"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/cache"
"github.com/rclone/rclone/fs/log"
"github.com/rclone/rclone/fs/rc"
"github.com/rclone/rclone/fs/walk"
"github.com/rclone/rclone/vfs/vfscache"
"github.com/rclone/rclone/vfs/vfscommon"
)
//go:embed vfs.md
var help string
// Help returns the help string cleaned up to simplify appending
func Help() string {
return strings.TrimSpace(help) + "\n\n"
}
// Node represents either a directory (*Dir) or a file (*File)
type Node interface {
os.FileInfo
IsFile() bool
Inode() uint64
SetModTime(modTime time.Time) error
Sync() error
Remove() error
RemoveAll() error
DirEntry() fs.DirEntry
VFS() *VFS
Open(flags int) (Handle, error)
Truncate(size int64) error
Path() string
SetSys(any)
}
// Check interfaces
var (
_ Node = (*File)(nil)
_ Node = (*Dir)(nil)
)
// Nodes is a slice of Node
type Nodes []Node
// Sort functions
func (ns Nodes) Len() int { return len(ns) }
func (ns Nodes) Swap(i, j int) { ns[i], ns[j] = ns[j], ns[i] }
func (ns Nodes) Less(i, j int) bool { return ns[i].Path() < ns[j].Path() }
// Noder represents something which can return a node
type Noder interface {
fmt.Stringer
Node() Node
}
// Check interfaces
var (
_ Noder = (*File)(nil)
_ Noder = (*Dir)(nil)
_ Noder = (*ReadFileHandle)(nil)
_ Noder = (*WriteFileHandle)(nil)
_ Noder = (*RWFileHandle)(nil)
_ Noder = (*DirHandle)(nil)
)
// OsFiler is the methods on *os.File
type OsFiler interface {
Chdir() error
Chmod(mode os.FileMode) error
Chown(uid, gid int) error
Close() error
Fd() uintptr
Name() string
Read(b []byte) (n int, err error)
ReadAt(b []byte, off int64) (n int, err error)
Readdir(n int) ([]os.FileInfo, error)
Readdirnames(n int) (names []string, err error)
Seek(offset int64, whence int) (ret int64, err error)
Stat() (os.FileInfo, error)
Sync() error
Truncate(size int64) error
Write(b []byte) (n int, err error)
WriteAt(b []byte, off int64) (n int, err error)
WriteString(s string) (n int, err error)
}
// Handle is the interface satisfied by open files or directories.
// It is the methods on *os.File, plus a few more useful for FUSE
// filingsystems. Not all of them are supported.
type Handle interface {
OsFiler
// Additional methods useful for FUSE filesystems
Flush() error
Release() error
Node() Node
// Size() int64
Lock() error
Unlock() error
}
// baseHandle implements all the missing methods
type baseHandle struct{}
func (h baseHandle) Chdir() error { return ENOSYS }
func (h baseHandle) Chmod(mode os.FileMode) error { return ENOSYS }
func (h baseHandle) Chown(uid, gid int) error { return ENOSYS }
func (h baseHandle) Close() error { return ENOSYS }
func (h baseHandle) Fd() uintptr { return 0 }
func (h baseHandle) Name() string { return "" }
func (h baseHandle) Read(b []byte) (n int, err error) { return 0, ENOSYS }
func (h baseHandle) ReadAt(b []byte, off int64) (n int, err error) { return 0, ENOSYS }
func (h baseHandle) Readdir(n int) ([]os.FileInfo, error) { return nil, ENOSYS }
func (h baseHandle) Readdirnames(n int) (names []string, err error) { return nil, ENOSYS }
func (h baseHandle) Seek(offset int64, whence int) (ret int64, err error) { return 0, ENOSYS }
func (h baseHandle) Stat() (os.FileInfo, error) { return nil, ENOSYS }
func (h baseHandle) Sync() error { return nil }
func (h baseHandle) Truncate(size int64) error { return ENOSYS }
func (h baseHandle) Write(b []byte) (n int, err error) { return 0, ENOSYS }
func (h baseHandle) WriteAt(b []byte, off int64) (n int, err error) { return 0, ENOSYS }
func (h baseHandle) WriteString(s string) (n int, err error) { return 0, ENOSYS }
func (h baseHandle) Flush() (err error) { return ENOSYS }
func (h baseHandle) Release() (err error) { return ENOSYS }
func (h baseHandle) Node() Node { return nil }
func (h baseHandle) Unlock() error { return os.ErrInvalid }
func (h baseHandle) Lock() error { return os.ErrInvalid }
//func (h baseHandle) Size() int64 { return 0 }
// Check interfaces
var (
_ OsFiler = (*os.File)(nil)
_ Handle = (*baseHandle)(nil)
_ Handle = (*ReadFileHandle)(nil)
_ Handle = (*WriteFileHandle)(nil)
_ Handle = (*DirHandle)(nil)
_ billy.File = (Handle)(nil)
)
// VFS represents the top level filing system
type VFS struct {
f fs.Fs
root *Dir
Opt vfscommon.Options
cache *vfscache.Cache
cancel context.CancelFunc
cancelCache context.CancelFunc
usageMu sync.Mutex
usageTime time.Time
usage *fs.Usage
pollChan chan time.Duration
inUse atomic.Int32 // count of number of opens
}
// Keep track of active VFS keyed on fs.ConfigString(f)
var (
activeMu sync.Mutex
active = map[string][]*VFS{}
)
// New creates a new VFS and root directory. If opt is nil, then
// DefaultOpt will be used
func New(f fs.Fs, opt *vfscommon.Options) *VFS {
fsDir := fs.NewDir("", time.Now())
ctx, cancel := context.WithCancel(context.Background())
vfs := &VFS{
f: f,
cancel: cancel,
}
vfs.inUse.Store(1)
// Make a copy of the options
if opt != nil {
vfs.Opt = *opt
} else {
vfs.Opt = vfscommon.Opt
}
// Fill out anything else
vfs.Opt.Init()
// Find a VFS with the same name and options and return it if possible
activeMu.Lock()
defer activeMu.Unlock()
configName := fs.ConfigString(f)
for _, activeVFS := range active[configName] {
if vfs.Opt == activeVFS.Opt {
fs.Debugf(f, "Reusing VFS from active cache")
activeVFS.inUse.Add(1)
return activeVFS
}
}
// Put the VFS into the active cache
active[configName] = append(active[configName], vfs)
// Create root directory
vfs.root = newDir(vfs, f, nil, fsDir)
// Start polling function
features := vfs.f.Features()
if do := features.ChangeNotify; do != nil {
vfs.pollChan = make(chan time.Duration)
do(context.TODO(), vfs.root.changeNotify, vfs.pollChan)
vfs.pollChan <- time.Duration(vfs.Opt.PollInterval)
} else if vfs.Opt.PollInterval > 0 {
fs.Infof(f, "poll-interval is not supported by this remote")
}
// Warn if can't stream
if !vfs.Opt.ReadOnly && vfs.Opt.CacheMode < vfscommon.CacheModeWrites && features.PutStream == nil {
fs.Logf(f, "--vfs-cache-mode writes or full is recommended for this remote as it can't stream")
}
// Warn if we handle symlinks
if vfs.Opt.Links {
fs.Logf(f, "Symlinks support enabled")
}
// Pin the Fs into the cache so that when we use cache.NewFs
// with the same remote string we get this one. The Pin is
// removed when the vfs is finalized
cache.PinUntilFinalized(f, vfs)
// Refresh the dircache if required
if vfs.Opt.Refresh {
go vfs.refresh()
}
// Handle supported signals
go vfs.signalHandler(ctx)
// This can take some time so do it after the Pin
vfs.SetCacheMode(vfs.Opt.CacheMode)
return vfs
}
// refresh the directory cache for all directories
func (vfs *VFS) refresh() {
fs.Debugf(vfs.f, "Refreshing VFS directory cache")
err := vfs.root.readDirTree()
if err != nil {
fs.Errorf(vfs.f, "Error refreshing VFS directory cache: %v", err)
}
}
// Reload VFS cache on SIGHUP
func (vfs *VFS) signalHandler(ctx context.Context) {
sigHup := make(chan os.Signal, 1)
NotifyOnSigHup(sigHup)
waiting := true
for waiting {
select {
case <-ctx.Done():
waiting = false
case <-sigHup:
root, err := vfs.Root()
if err != nil {
fs.Errorf(vfs.Fs(), "Error reading root: %v", err)
} else {
root.ForgetAll()
}
}
}
}
// Stats returns info about the VFS
func (vfs *VFS) Stats() (out rc.Params) {
out = make(rc.Params)
out["fs"] = fs.ConfigString(vfs.f)
out["opt"] = vfs.Opt
out["inUse"] = vfs.inUse.Load()
var (
dirs int
files int
)
vfs.root.walk(func(d *Dir) {
dirs++
files += len(d.items)
})
inf := make(rc.Params)
out["metadataCache"] = inf
inf["dirs"] = dirs
inf["files"] = files
if vfs.cache != nil {
out["diskCache"] = vfs.cache.Stats()
}
return out
}
// Return the number of active cache entries and a VFS if any are in
// the cache.
func activeCacheEntries() (vfs *VFS, count int) {
activeMu.Lock()
for _, vfses := range active {
count += len(vfses)
if len(vfses) > 0 {
vfs = vfses[0]
}
}
activeMu.Unlock()
return vfs, count
}
// Fs returns the Fs passed into the New call
func (vfs *VFS) Fs() fs.Fs {
return vfs.f
}
// SetCacheMode change the cache mode
func (vfs *VFS) SetCacheMode(cacheMode vfscommon.CacheMode) {
vfs.shutdownCache()
vfs.cache = nil
if cacheMode > vfscommon.CacheModeOff {
ctx, cancel := context.WithCancel(context.Background())
cache, err := vfscache.New(ctx, vfs.f, &vfs.Opt, vfs.AddVirtual) // FIXME pass on context or get from Opt?
if err != nil {
fs.Errorf(nil, "Failed to create vfs cache - disabling: %v", err)
vfs.Opt.CacheMode = vfscommon.CacheModeOff
cancel()
return
}
vfs.Opt.CacheMode = cacheMode
vfs.cancelCache = cancel
vfs.cache = cache
}
}
// shutdown the cache if it was running
func (vfs *VFS) shutdownCache() {
if vfs.cancelCache != nil {
vfs.cancelCache()
vfs.cancelCache = nil
}
}
// Shutdown stops any background go-routines and removes the VFS from
// the active ache.
func (vfs *VFS) Shutdown() {
if vfs.inUse.Add(-1) > 0 {
return
}
// Remove from active cache
activeMu.Lock()
configName := fs.ConfigString(vfs.f)
activeVFSes := active[configName]
for i, activeVFS := range activeVFSes {
if activeVFS == vfs {
activeVFSes[i] = nil
active[configName] = slices.Delete(activeVFSes, i, i+1)
break
}
}
activeMu.Unlock()
vfs.shutdownCache()
if vfs.pollChan != nil {
close(vfs.pollChan)
vfs.pollChan = nil
}
// Cancel any background go routines
vfs.cancel()
}
// CleanUp deletes the contents of the on disk cache
func (vfs *VFS) CleanUp() error {
if vfs.Opt.CacheMode == vfscommon.CacheModeOff {
return nil
}
return vfs.cache.CleanUp()
}
// FlushDirCache empties the directory cache
func (vfs *VFS) FlushDirCache() {
vfs.root.ForgetAll()
}
// WaitForWriters sleeps until all writers have finished or
// time.Duration has elapsed
func (vfs *VFS) WaitForWriters(timeout time.Duration) {
defer log.Trace(nil, "timeout=%v", timeout)("")
tickTime := 10 * time.Millisecond
deadline := time.NewTimer(timeout)
defer deadline.Stop()
tick := time.NewTimer(tickTime)
defer tick.Stop()
tick.Stop()
for {
writers := vfs.root.countActiveWriters()
cacheInUse := 0
if vfs.cache != nil {
cacheInUse = vfs.cache.TotalInUse()
}
if writers == 0 && cacheInUse == 0 {
return
}
fs.Debugf(nil, "Still %d writers active and %d cache items in use, waiting %v", writers, cacheInUse, tickTime)
tick.Reset(tickTime)
select {
case <-tick.C:
case <-deadline.C:
fs.Errorf(nil, "Exiting even though %d writers active and %d cache items in use after %v\n%s", writers, cacheInUse, timeout, vfs.cache.Dump())
return
}
tickTime *= 2
if tickTime > time.Second {
tickTime = time.Second
}
}
}
// Root returns the root node
func (vfs *VFS) Root() (*Dir, error) {
// fs.Debugf(vfs.f, "Root()")
return vfs.root, nil
}
var inodeCount atomic.Uint64
// newInode creates a new unique inode number
func newInode() (inode uint64) {
return inodeCount.Add(1)
}
// Stat finds the Node by path starting from the root
//
// It is the equivalent of os.Stat - Node contains the os.FileInfo
// interface.
func (vfs *VFS) Stat(path string) (node Node, err error) {
path = strings.Trim(path, "/")
node = vfs.root
for path != "" {
i := strings.IndexRune(path, '/')
var name string
if i < 0 {
name, path = path, ""
} else {
name, path = path[:i], path[i+1:]
}
if name == "" {
continue
}
dir, ok := node.(*Dir)
if !ok {
// We need to look in a directory, but found a file
return nil, ENOENT
}
node, err = dir.Stat(name)
if err != nil {
return nil, err
}
}
return
}
// StatParent finds the parent directory and the leaf name of a path
func (vfs *VFS) StatParent(name string) (dir *Dir, leaf string, err error) {
name = strings.Trim(name, "/")
parent, leaf := path.Split(name)
node, err := vfs.Stat(parent)
if err != nil {
return nil, "", err
}
if node.IsFile() {
return nil, "", os.ErrExist
}
dir = node.(*Dir)
return dir, leaf, nil
}
// decodeOpenFlags returns a string representing the open flags
func decodeOpenFlags(flags int) string {
var out []string
rdwrMode := flags & accessModeMask
switch rdwrMode {
case os.O_RDONLY:
out = append(out, "O_RDONLY")
case os.O_WRONLY:
out = append(out, "O_WRONLY")
case os.O_RDWR:
out = append(out, "O_RDWR")
default:
out = append(out, fmt.Sprintf("0x%X", rdwrMode))
}
if flags&os.O_APPEND != 0 {
out = append(out, "O_APPEND")
}
if flags&os.O_CREATE != 0 {
out = append(out, "O_CREATE")
}
if flags&os.O_EXCL != 0 {
out = append(out, "O_EXCL")
}
if flags&os.O_SYNC != 0 {
out = append(out, "O_SYNC")
}
if flags&os.O_TRUNC != 0 {
out = append(out, "O_TRUNC")
}
flags &^= accessModeMask | os.O_APPEND | os.O_CREATE | os.O_EXCL | os.O_SYNC | os.O_TRUNC
if flags != 0 {
out = append(out, fmt.Sprintf("0x%X", flags))
}
return strings.Join(out, "|")
}
// OpenFile a file according to the flags and perm provided
func (vfs *VFS) OpenFile(name string, flags int, perm os.FileMode) (fd Handle, err error) {
defer log.Trace(name, "flags=%s, perm=%v", decodeOpenFlags(flags), perm)("fd=%v, err=%v", &fd, &err)
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/open.html
// The result of using O_TRUNC with O_RDONLY is undefined.
// Linux seems to truncate the file, but we prefer to return EINVAL
if flags&accessModeMask == os.O_RDONLY && flags&os.O_TRUNC != 0 {
return nil, EINVAL
}
node, err := vfs.Stat(name)
if err != nil {
if err != ENOENT || flags&os.O_CREATE == 0 {
return nil, err
}
// If not found and O_CREATE then create the file
dir, leaf, err := vfs.StatParent(name)
if err != nil {
return nil, err
}
node, err = dir.Create(leaf, flags)
if err != nil {
return nil, err
}
}
return node.Open(flags)
}
// Open opens the named file for reading. If successful, methods on
// the returned file can be used for reading; the associated file
// descriptor has mode O_RDONLY.
func (vfs *VFS) Open(name string) (Handle, error) {
return vfs.OpenFile(name, os.O_RDONLY, 0)
}
// Create creates the named file with mode 0666 (before umask), truncating
// it if it already exists. If successful, methods on the returned
// File can be used for I/O; the associated file descriptor has mode
// O_RDWR.
func (vfs *VFS) Create(name string) (Handle, error) {
return vfs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
}
// Rename oldName to newName
func (vfs *VFS) Rename(oldName, newName string) error {
// find the parent directories
oldDir, oldLeaf, err := vfs.StatParent(oldName)
if err != nil {
return err
}
newDir, newLeaf, err := vfs.StatParent(newName)
if err != nil {
return err
}
err = oldDir.Rename(oldLeaf, newLeaf, newDir)
if err != nil {
return err
}
return nil
}
// This works out the missing values from (total, used, free) using
// unknownFree as the intended free space
func fillInMissingSizes(total, used, free, unknownFree int64) (newTotal, newUsed, newFree int64) {
if total < 0 {
if free >= 0 {
total = free
} else {
total = unknownFree
}
if used >= 0 {
total += used
}
}
// total is now defined
if used < 0 {
if free >= 0 {
used = total - free
} else {
used = 0
}
}
// used is now defined
if free < 0 {
free = total - used
}
return total, used, free
}
// If the total size isn't known then we will aim for this many bytes free (1 PiB)
const unknownFreeBytes = 1 << 50
// Statfs returns into about the filing system if known
//
// The values will be -1 if they aren't known
//
// This information is cached for the DirCacheTime interval
func (vfs *VFS) Statfs() (total, used, free int64) {
// defer log.Trace("/", "")("total=%d, used=%d, free=%d", &total, &used, &free)
vfs.usageMu.Lock()
defer vfs.usageMu.Unlock()
total, used, free = -1, -1, -1
doAbout := vfs.f.Features().About
if (doAbout != nil || vfs.Opt.UsedIsSize) && (vfs.usageTime.IsZero() || time.Since(vfs.usageTime) >= time.Duration(vfs.Opt.DirCacheTime)) {
var err error
ctx := context.TODO()
if doAbout == nil {
vfs.usage = &fs.Usage{}
} else {
vfs.usage, err = doAbout(ctx)
}
if vfs.Opt.UsedIsSize {
var usedBySizeAlgorithm int64
// Algorithm from `rclone size`
err = walk.ListR(ctx, vfs.f, "", true, -1, walk.ListObjects, func(entries fs.DirEntries) error {
entries.ForObject(func(o fs.Object) {
usedBySizeAlgorithm += o.Size()
})
return nil
})
vfs.usage.Used = &usedBySizeAlgorithm
// if we read a Total size then we should calculate Free from it
if vfs.usage.Total != nil {
vfs.usage.Free = nil
}
}
vfs.usageTime = time.Now()
if err != nil {
fs.Errorf(vfs.f, "Statfs failed: %v", err)
return
}
}
if u := vfs.usage; u != nil {
if u.Total != nil {
total = *u.Total
}
if u.Free != nil {
free = *u.Free
}
if u.Used != nil {
used = *u.Used
}
}
if int64(vfs.Opt.DiskSpaceTotalSize) >= 0 {
total = int64(vfs.Opt.DiskSpaceTotalSize)
}
total, used, free = fillInMissingSizes(total, used, free, unknownFreeBytes)
return
}
// Remove removes the named file or (empty) directory.
func (vfs *VFS) Remove(name string) error {
node, err := vfs.Stat(name)
if err != nil {
return err
}
err = node.Remove()
if err != nil {
return err
}
return nil
}
// Chtimes changes the access and modification times of the named file, similar
// to the Unix utime() or utimes() functions.
//
// The underlying filesystem may truncate or round the values to a less precise
// time unit.
func (vfs *VFS) Chtimes(name string, atime time.Time, mtime time.Time) error {
node, err := vfs.Stat(name)
if err != nil {
return err
}
err = node.SetModTime(mtime)
if err != nil {
return err
}
return nil
}
// mkdir creates a new directory with the specified name and permission bits
// (before umask) returning the new directory node.
func (vfs *VFS) mkdir(name string, perm os.FileMode) (*Dir, error) {
dir, leaf, err := vfs.StatParent(name)
if err != nil {
return nil, err
}
return dir.Mkdir(leaf)
}
// Mkdir creates a new directory with the specified name and permission bits
// (before umask).
func (vfs *VFS) Mkdir(name string, perm os.FileMode) error {
_, err := vfs.mkdir(name, perm)
return err
}
// mkdirAll creates a new directory with the specified name and
// permission bits (before umask) and all of its parent directories up
// to the root.
func (vfs *VFS) mkdirAll(name string, perm os.FileMode) (dir *Dir, err error) {
name = strings.Trim(name, "/")
// the root directory node already exists even if the directory isn't created yet
if name == "" {
return vfs.root, nil
}
var parent, leaf string
dir, leaf, err = vfs.StatParent(name)
if err == ENOENT {
parent, leaf = path.Split(name)
dir, err = vfs.mkdirAll(parent, perm)
}
if err != nil {
return nil, err
}
dir, err = dir.Mkdir(leaf)
if err != nil {
return nil, err
}
return dir, nil
}
// MkdirAll creates a new directory with the specified name and
// permission bits (before umask) and all of its parent directories up
// to the root.
func (vfs *VFS) MkdirAll(name string, perm os.FileMode) error {
_, err := vfs.mkdirAll(name, perm)
return err
}
// ReadDir reads the directory named by dirname and returns
// a list of directory entries sorted by filename.
func (vfs *VFS) ReadDir(dirname string) ([]os.FileInfo, error) {
f, err := vfs.Open(dirname)
if err != nil {
return nil, err
}
list, err := f.Readdir(-1)
closeErr := f.Close()
if err != nil {
return nil, err
}
if closeErr != nil {
return nil, closeErr
}
sort.Slice(list, func(i, j int) bool { return list[i].Name() < list[j].Name() })
return list, nil
}
// ReadFile reads the file named by filename and returns the contents.
// A successful call returns err == nil, not err == EOF. Because ReadFile
// reads the whole file, it does not treat an EOF from Read as an error
// to be reported.
func (vfs *VFS) ReadFile(filename string) (b []byte, err error) {
f, err := vfs.Open(filename)
if err != nil {
return nil, err
}
defer fs.CheckClose(f, &err)
return io.ReadAll(f)
}
// WriteFile writes data to the named file, creating it if necessary. If the
// file does not exist, WriteFile creates it with permissions perm (before
// umask); otherwise WriteFile truncates it before writing, without changing
// permissions. Since WriteFile requires multiple system calls to complete,
// a failure mid-operation can leave the file in a partially written state.
func (vfs *VFS) WriteFile(name string, data []byte, perm os.FileMode) (err error) {
fh, err := vfs.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
return err
}
defer fs.CheckClose(fh, &err)
_, err = fh.Write(data)
return err
}
// AddVirtual adds the object (file or dir) to the directory cache
//
// This is used by the vfs cache to insert objects that are uploading
// into the directory tree.
func (vfs *VFS) AddVirtual(remote string, size int64, isDir bool) (err error) {
remote = strings.TrimRight(remote, "/")
var dir *Dir
var parent, leaf string
if vfs.f.Features().CanHaveEmptyDirectories {
dir, leaf, err = vfs.StatParent(remote)
} else {
// Create parent of virtual directory since backend can't have empty directories
parent, leaf = path.Split(remote)
dir, err = vfs.mkdirAll(parent, os.FileMode(vfs.Opt.DirPerms))
}
if err != nil {
return err
}
dir.AddVirtual(leaf, size, false)
return nil
}
// Readlink returns the destination of the named symbolic link.
// If there is an error, it will be of type *PathError.
func (vfs *VFS) Readlink(name string) (s string, err error) {
if !vfs.Opt.Links {
fs.Errorf(nil, "symlinks not supported without the --links flag: %v", name)
return "", ENOSYS
}
node, err := vfs.Stat(name)
if err != nil {
return "", err
}
file, ok := node.(*File)
if !ok || !file.IsSymlink() {
return "", EINVAL // not a symlink
}
fd, err := file.Open(os.O_RDONLY | o_SYMLINK)
if err != nil {
return "", err
}
defer fs.CheckClose(fd, &err)
b, err := io.ReadAll(fd)
if err != nil {
return "", err
}
return string(b), nil
}
// CreateSymlink creates newname as a symbolic link to oldname.
// On Windows, a symlink to a non-existent oldname creates a file symlink;
// if oldname is later created as a directory the symlink will not work.
// It returns the node created
func (vfs *VFS) CreateSymlink(oldname, newname string) (Node, error) {
if !vfs.Opt.Links {
fs.Errorf(newname, "symlinks not supported without the --links flag")
return nil, ENOSYS
}
// Destination can't exist
_, err := vfs.Stat(newname)
if err == nil {
return nil, EEXIST
} else if err != ENOENT {
return nil, err
}
// Find the parent
dir, leaf, err := vfs.StatParent(newname)
if err != nil {
return nil, err
}
// Create the file node
flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC | o_SYMLINK
file, err := dir.Create(leaf, flags)
if err != nil {
return nil, err
}
// Force the file to be a link
file.setSymlink()
// Open the file
fh, err := file.Open(flags)
if err != nil {
return nil, err
}
defer fs.CheckClose(fh, &err)
// Write the symlink data
_, err = fh.Write([]byte(strings.ReplaceAll(oldname, "\\", "/")))
return file, nil
}
// Symlink creates newname as a symbolic link to oldname.
// On Windows, a symlink to a non-existent oldname creates a file symlink;
// if oldname is later created as a directory the symlink will not work.
func (vfs *VFS) Symlink(oldname, newname string) error {
_, err := vfs.CreateSymlink(oldname, newname)
return err
}
// Return true if name represents a metadata file
//
// It returns the underlying path
func (vfs *VFS) isMetadataFile(name string) (rawName string, found bool) {
ext := vfs.Opt.MetadataExtension
if ext == "" {
return name, false
}
rawName, found = strings.CutSuffix(name, ext)
return rawName, found
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/read_write.go | vfs/read_write.go | package vfs
import (
"fmt"
"io"
"os"
"sync"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/log"
"github.com/rclone/rclone/vfs/vfscache"
)
// RWFileHandle is a handle that can be open for read and write.
//
// It will be open to a temporary file which, when closed, will be
// transferred to the remote.
type RWFileHandle struct {
// read only variables
file *File
d *Dir
flags int // open flags
item *vfscache.Item // cached file item
// read write variables protected by mutex
mu sync.Mutex
offset int64 // file pointer offset
closed bool // set if handle has been closed
opened bool
writeCalled bool // if any Write() methods have been called
}
// Lock performs Unix locking, not supported
func (fh *RWFileHandle) Lock() error {
return os.ErrInvalid
}
// Unlock performs Unix unlocking, not supported
func (fh *RWFileHandle) Unlock() error {
return os.ErrInvalid
}
func newRWFileHandle(d *Dir, f *File, flags int) (fh *RWFileHandle, err error) {
defer log.Trace(f.Path(), "")("err=%v", &err)
// get an item to represent this from the cache
item := d.vfs.cache.Item(f.CachePath())
exists := f.exists() || (item.Exists() && !item.WrittenBack())
// if O_CREATE and O_EXCL are set and if path already exists, then return EEXIST
if flags&(os.O_CREATE|os.O_EXCL) == os.O_CREATE|os.O_EXCL && exists {
return nil, EEXIST
}
fh = &RWFileHandle{
file: f,
d: d,
flags: flags,
item: item,
}
// truncate immediately if O_TRUNC is set or O_CREATE is set and file doesn't exist
if !fh.readOnly() && (fh.flags&os.O_TRUNC != 0 || (fh.flags&os.O_CREATE != 0 && !exists)) {
err = fh.Truncate(0)
if err != nil {
return nil, fmt.Errorf("cache open with O_TRUNC: failed to truncate: %w", err)
}
// we definitely need to write back the item even if we don't write to it
item.Dirty()
}
if !fh.readOnly() {
fh.file.addWriter(fh)
}
return fh, nil
}
// readOnly returns whether flags say fh is read only
func (fh *RWFileHandle) readOnly() bool {
return (fh.flags & accessModeMask) == os.O_RDONLY
}
// writeOnly returns whether flags say fh is write only
func (fh *RWFileHandle) writeOnly() bool {
return (fh.flags & accessModeMask) == os.O_WRONLY
}
// openPending opens the file if there is a pending open
//
// call with the lock held
func (fh *RWFileHandle) openPending() (err error) {
if fh.opened {
return nil
}
defer log.Trace(fh.logPrefix(), "")("err=%v", &err)
fh.file.muRW.Lock()
defer fh.file.muRW.Unlock()
o := fh.file.getObject()
err = fh.item.Open(o)
if err != nil {
return fmt.Errorf("open RW handle failed to open cache file: %w", err)
}
size := fh._size() // update size in file and read size
if fh.flags&os.O_APPEND != 0 {
fh.offset = size
fs.Debugf(fh.logPrefix(), "open at offset %d", fh.offset)
} else {
fh.offset = 0
}
fh.opened = true
fh.d.addObject(fh.file) // make sure the directory has this object in it now
return nil
}
// String converts it to printable
func (fh *RWFileHandle) String() string {
if fh == nil {
return "<nil *RWFileHandle>"
}
if fh.file == nil {
return "<nil *RWFileHandle.file>"
}
return fh.file.String() + " (rw)"
}
// Node returns the Node associated with this - satisfies Noder interface
func (fh *RWFileHandle) Node() Node {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.file
}
// updateSize updates the size of the file if necessary
//
// Must be called with fh.mu held
func (fh *RWFileHandle) updateSize() {
// If read only or not opened then ignore
if fh.readOnly() || !fh.opened {
return
}
size := fh._size()
fh.file.setSize(size)
}
// close the file handle returning EBADF if it has been
// closed already.
//
// Must be called with fh.mu held.
//
// Note that we leave the file around in the cache on error conditions
// to give the user a chance to recover it.
func (fh *RWFileHandle) close() (err error) {
defer log.Trace(fh.logPrefix(), "")("err=%v", &err)
fh.file.muRW.Lock()
defer fh.file.muRW.Unlock()
if fh.closed {
return ECLOSED
}
fh.closed = true
fh.updateSize()
if fh.opened {
err = fh.item.Close(fh.file.setObject)
fh.opened = false
} else {
// apply any pending mod times if any
_ = fh.file.applyPendingModTime()
}
if !fh.readOnly() {
fh.file.delWriter(fh)
}
return err
}
// Close closes the file
func (fh *RWFileHandle) Close() error {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.close()
}
// Flush is called each time the file or directory is closed.
// Because there can be multiple file descriptors referring to a
// single opened file, Flush can be called multiple times.
func (fh *RWFileHandle) Flush() error {
fh.mu.Lock()
fs.Debugf(fh.logPrefix(), "RWFileHandle.Flush")
fh.updateSize()
fh.mu.Unlock()
return nil
}
// Release is called when we are finished with the file handle
//
// It isn't called directly from userspace so the error is ignored by
// the kernel
func (fh *RWFileHandle) Release() error {
fh.mu.Lock()
defer fh.mu.Unlock()
fs.Debugf(fh.logPrefix(), "RWFileHandle.Release")
if fh.closed {
// Don't return an error if called twice
return nil
}
err := fh.close()
if err != nil {
fs.Errorf(fh.logPrefix(), "RWFileHandle.Release error: %v", err)
}
return err
}
// _size returns the size of the underlying file and also sets it in
// the owning file
//
// call with the lock held
func (fh *RWFileHandle) _size() int64 {
size, err := fh.item.GetSize()
if err != nil {
o := fh.file.getObject()
if o != nil {
size = o.Size()
} else {
fs.Errorf(fh.logPrefix(), "Couldn't read size of file")
size = 0
}
}
fh.file.setSize(size)
return size
}
// Size returns the size of the underlying file
func (fh *RWFileHandle) Size() int64 {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh._size()
}
// Stat returns info about the file
func (fh *RWFileHandle) Stat() (os.FileInfo, error) {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.file, nil
}
// _readAt bytes from the file at off
//
// if release is set then it releases the mutex just before doing the IO
//
// call with lock held
func (fh *RWFileHandle) _readAt(b []byte, off int64, release bool) (n int, err error) {
defer log.Trace(fh.logPrefix(), "size=%d, off=%d", len(b), off)("n=%d, err=%v", &n, &err)
if fh.closed {
return n, ECLOSED
}
if fh.writeOnly() {
return n, EBADF
}
if off >= fh._size() {
return n, io.EOF
}
if err = fh.openPending(); err != nil {
return n, err
}
if release {
// Do the writing with fh.mu unlocked
fh.mu.Unlock()
}
n, err = fh.item.ReadAt(b, off)
if release {
fh.mu.Lock()
}
return n, err
}
// ReadAt bytes from the file at off
func (fh *RWFileHandle) ReadAt(b []byte, off int64) (n int, err error) {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh._readAt(b, off, true)
}
// Read bytes from the file
func (fh *RWFileHandle) Read(b []byte) (n int, err error) {
fh.mu.Lock()
defer fh.mu.Unlock()
n, err = fh._readAt(b, fh.offset, false)
fh.offset += int64(n)
return n, err
}
// Seek to new file position
func (fh *RWFileHandle) Seek(offset int64, whence int) (ret int64, err error) {
fh.mu.Lock()
defer fh.mu.Unlock()
if fh.closed {
return 0, ECLOSED
}
if !fh.opened && offset == 0 && whence != 2 {
return 0, nil
}
if err = fh.openPending(); err != nil {
return ret, err
}
switch whence {
case io.SeekStart:
fh.offset = 0
case io.SeekEnd:
fh.offset = fh._size()
}
fh.offset += offset
// we don't check the offset - the next Read will
return fh.offset, nil
}
// _writeAt bytes to the file at off
//
// if release is set then it releases the mutex just before doing the IO
//
// call with lock held
func (fh *RWFileHandle) _writeAt(b []byte, off int64, release bool) (n int, err error) {
defer log.Trace(fh.logPrefix(), "size=%d, off=%d", len(b), off)("n=%d, err=%v", &n, &err)
if fh.closed {
return n, ECLOSED
}
if fh.readOnly() {
return n, EBADF
}
if err = fh.openPending(); err != nil {
return n, err
}
if fh.flags&os.O_APPEND != 0 {
// From open(2): Before each write(2), the file offset is
// positioned at the end of the file, as if with lseek(2).
size := fh._size()
fh.offset = size
off = fh.offset
}
fh.writeCalled = true
if release {
// Do the writing with fh.mu unlocked
fh.mu.Unlock()
}
n, err = fh.item.WriteAt(b, off)
if release {
fh.mu.Lock()
}
if err != nil {
return n, err
}
_ = fh._size()
return n, err
}
// WriteAt bytes to the file at off
func (fh *RWFileHandle) WriteAt(b []byte, off int64) (n int, err error) {
fh.mu.Lock()
n, err = fh._writeAt(b, off, true)
if fh.flags&os.O_APPEND != 0 {
fh.offset += int64(n)
}
fh.mu.Unlock()
return n, err
}
// Write bytes to the file
func (fh *RWFileHandle) Write(b []byte) (n int, err error) {
fh.mu.Lock()
defer fh.mu.Unlock()
n, err = fh._writeAt(b, fh.offset, false)
fh.offset += int64(n)
return n, err
}
// WriteString a string to the file
func (fh *RWFileHandle) WriteString(s string) (n int, err error) {
return fh.Write([]byte(s))
}
// Truncate file to given size
//
// Call with mutex held
func (fh *RWFileHandle) _truncate(size int64) (err error) {
if size == fh._size() {
return nil
}
fh.file.setSize(size)
return fh.item.Truncate(size)
}
// Truncate file to given size
func (fh *RWFileHandle) Truncate(size int64) (err error) {
fh.mu.Lock()
defer fh.mu.Unlock()
if fh.closed {
return ECLOSED
}
if err = fh.openPending(); err != nil {
return err
}
return fh._truncate(size)
}
// Sync commits the current contents of the file to stable storage. Typically,
// this means flushing the file system's in-memory copy of recently written
// data to disk.
func (fh *RWFileHandle) Sync() error {
fh.mu.Lock()
defer fh.mu.Unlock()
if fh.closed {
return ECLOSED
}
if !fh.opened {
return nil
}
if fh.readOnly() {
return nil
}
return fh.item.Sync()
}
func (fh *RWFileHandle) logPrefix() string {
return fmt.Sprintf("%s(%p)", fh.file.Path(), fh)
}
// Chdir changes the current working directory to the file, which must
// be a directory.
func (fh *RWFileHandle) Chdir() error {
return ENOSYS
}
// Chmod changes the mode of the file to mode.
func (fh *RWFileHandle) Chmod(mode os.FileMode) error {
return ENOSYS
}
// Chown changes the numeric uid and gid of the named file.
func (fh *RWFileHandle) Chown(uid, gid int) error {
return ENOSYS
}
// Fd returns the integer Unix file descriptor referencing the open file.
func (fh *RWFileHandle) Fd() uintptr {
return 0xdeadbeef // FIXME
}
// Name returns the name of the file from the underlying Object.
func (fh *RWFileHandle) Name() string {
return fh.file.String()
}
// Readdir reads the contents of the directory associated with file.
func (fh *RWFileHandle) Readdir(n int) ([]os.FileInfo, error) {
return nil, ENOSYS
}
// Readdirnames reads the contents of the directory associated with file.
func (fh *RWFileHandle) Readdirnames(n int) (names []string, err error) {
return nil, ENOSYS
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/sighup.go | vfs/sighup.go | //go:build !plan9 && !js
package vfs
import (
"os"
"os/signal"
"syscall"
)
// NotifyOnSigHup makes SIGHUP notify given channel on supported systems
func NotifyOnSigHup(sighupChan chan os.Signal) {
signal.Notify(sighupChan, syscall.SIGHUP)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vstate_string.go | vfs/vstate_string.go | // Code generated by "stringer -type=vState"; DO NOT EDIT.
package vfs
import "strconv"
func _() {
// An "invalid array index" compiler error signifies that the constant values have changed.
// Re-run the stringer command to generate them again.
var x [1]struct{}
_ = x[vOK-0]
_ = x[vAddFile-1]
_ = x[vAddDir-2]
_ = x[vDel-3]
}
const _vState_name = "vOKvAddFilevAddDirvDel"
var _vState_index = [...]uint8{0, 3, 11, 18, 22}
func (i vState) String() string {
if i >= vState(len(_vState_index)-1) {
return "vState(" + strconv.FormatInt(int64(i), 10) + ")"
}
return _vState_name[_vState_index[i]:_vState_index[i+1]]
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/make_open_tests.go | vfs/make_open_tests.go | // This makes the open test suite. It tries to open a file (existing
// or not existing) with all possible file modes and writes a test
// matrix.
//
// The behaviour is as run on Linux, with the small modification that
// O_TRUNC with O_RDONLY does **not** truncate the file.
//
// Run with go generate (defined in vfs.go)
//
//go:build none
// FIXME include read too?
package main
import (
"fmt"
"io"
"log"
"os"
"strings"
"github.com/rclone/rclone/lib/file"
)
// Interprets err into a vfs error
func whichError(err error) string {
switch err {
case nil:
return "nil"
case io.EOF:
return "io.EOF"
case os.ErrInvalid:
return "EINVAL"
}
s := err.Error()
switch {
case strings.Contains(s, "no such file or directory"):
return "ENOENT"
case strings.Contains(s, "bad file descriptor"):
return "EBADF"
case strings.Contains(s, "file exists"):
return "EEXIST"
}
log.Fatalf("Unknown error: %v", err)
return ""
}
const accessModeMask = (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)
// test Opening, reading and writing the file handle with the flags given
func test(fileName string, flags int, mode string) {
// first try with file not existing
_, err := os.Stat(fileName)
if !os.IsNotExist(err) {
log.Fatalf("File must not exist")
}
f, openNonExistentErr := file.OpenFile(fileName, flags, 0666)
var readNonExistentErr error
var writeNonExistentErr error
if openNonExistentErr == nil {
// read some bytes
buf := []byte{0, 0}
_, readNonExistentErr = f.Read(buf)
// write some bytes
_, writeNonExistentErr = f.Write([]byte("hello"))
// close
err = f.Close()
if err != nil {
log.Fatalf("failed to close: %v", err)
}
}
// write the file
f, err = file.Create(fileName)
if err != nil {
log.Fatalf("failed to create: %v", err)
}
n, err := f.Write([]byte("hello"))
if n != 5 || err != nil {
log.Fatalf("failed to write n=%d: %v", n, err)
}
// close
err = f.Close()
if err != nil {
log.Fatalf("failed to close: %v", err)
}
// then open file and try with file existing
f, openExistingErr := file.OpenFile(fileName, flags, 0666)
var readExistingErr error
var writeExistingErr error
if openExistingErr == nil {
// read some bytes
buf := []byte{0, 0}
_, readExistingErr = f.Read(buf)
// write some bytes
_, writeExistingErr = f.Write([]byte("HEL"))
// close
err = f.Close()
if err != nil {
log.Fatalf("failed to close: %v", err)
}
}
// read the file
f, err = file.Open(fileName)
if err != nil {
log.Fatalf("failed to open: %v", err)
}
var buf = make([]byte, 64)
n, err = f.Read(buf)
if err != nil && err != io.EOF {
log.Fatalf("failed to read n=%d: %v", n, err)
}
err = f.Close()
if err != nil {
log.Fatalf("failed to close: %v", err)
}
contents := string(buf[:n])
// remove file
err = os.Remove(fileName)
if err != nil {
log.Fatalf("failed to remove: %v", err)
}
// http://pubs.opengroup.org/onlinepubs/7908799/xsh/open.html
// The result of using O_TRUNC with O_RDONLY is undefined.
// Linux seems to truncate the file, but we prefer to return EINVAL
if (flags&accessModeMask) == os.O_RDONLY && flags&os.O_TRUNC != 0 {
openNonExistentErr = os.ErrInvalid // EINVAL
readNonExistentErr = nil
writeNonExistentErr = nil
openExistingErr = os.ErrInvalid // EINVAL
readExistingErr = nil
writeExistingErr = nil
contents = "hello"
}
// output the struct
fmt.Printf(`{
flags: %s,
what: %q,
openNonExistentErr: %s,
readNonExistentErr: %s,
writeNonExistentErr: %s,
openExistingErr: %s,
readExistingErr: %s,
writeExistingErr: %s,
contents: %q,
},`,
mode,
mode,
whichError(openNonExistentErr),
whichError(readNonExistentErr),
whichError(writeNonExistentErr),
whichError(openExistingErr),
whichError(readExistingErr),
whichError(writeExistingErr),
contents)
}
func main() {
fmt.Printf(`// Code generated by make_open_tests.go - use go generate to rebuild - DO NOT EDIT
package vfs
import (
"os"
"io"
)
// openTest describes a test of OpenFile
type openTest struct{
flags int
what string
openNonExistentErr error
readNonExistentErr error
writeNonExistentErr error
openExistingErr error
readExistingErr error
writeExistingErr error
contents string
}
// openTests is a suite of tests for OpenFile with all possible
// combination of flags. This obeys Unix semantics even on Windows.
var openTests = []openTest{
`)
f, err := os.CreateTemp("", "open-test")
if err != nil {
log.Fatal(err)
}
fileName := f.Name()
_ = f.Close()
err = os.Remove(fileName)
if err != nil {
log.Fatalf("failed to remove: %v", err)
}
for _, rwMode := range []int{os.O_RDONLY, os.O_WRONLY, os.O_RDWR} {
flags0 := rwMode
parts0 := []string{"os.O_RDONLY", "os.O_WRONLY", "os.O_RDWR"}[rwMode : rwMode+1]
for _, appendMode := range []int{0, os.O_APPEND} {
flags1 := flags0 | appendMode
parts1 := parts0
if appendMode != 0 {
parts1 = append(parts1, "os.O_APPEND")
}
for _, createMode := range []int{0, os.O_CREATE} {
flags2 := flags1 | createMode
parts2 := parts1
if createMode != 0 {
parts2 = append(parts2, "os.O_CREATE")
}
for _, exclMode := range []int{0, os.O_EXCL} {
flags3 := flags2 | exclMode
parts3 := parts2
if exclMode != 0 {
parts3 = append(parts2, "os.O_EXCL")
}
for _, syncMode := range []int{0, os.O_SYNC} {
flags4 := flags3 | syncMode
parts4 := parts3
if syncMode != 0 {
parts4 = append(parts4, "os.O_SYNC")
}
for _, truncMode := range []int{0, os.O_TRUNC} {
flags5 := flags4 | truncMode
parts5 := parts4
if truncMode != 0 {
parts5 = append(parts5, "os.O_TRUNC")
}
textMode := strings.Join(parts5, "|")
flags := flags5
test(fileName, flags, textMode)
}
}
}
}
}
}
fmt.Printf("\n}\n")
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfs_case_test.go | vfs/vfs_case_test.go | package vfs
import (
"context"
"os"
"testing"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/text/unicode/norm"
)
func TestCaseSensitivity(t *testing.T) {
r := fstest.NewRun(t)
if r.Fremote.Features().CaseInsensitive {
t.Skip("Can't test case sensitivity - this remote is officially not case-sensitive")
}
// Create test files
ctx := context.Background()
file1 := r.WriteObject(ctx, "FiLeA", "data1", t1)
file2 := r.WriteObject(ctx, "FiLeB", "data2", t2)
r.CheckRemoteItems(t, file1, file2)
// Create file3 with name differing from file2 name only by case.
// On a case-Sensitive remote this will be a separate file.
// On a case-INsensitive remote this file will either not exist
// or overwrite file2 depending on how file system diverges.
// On a box.com remote this step will even fail.
file3 := r.WriteObject(ctx, "FilEb", "data3", t3)
// Create a case-Sensitive and case-INsensitive VFS
optCS := vfscommon.Opt
optCS.CaseInsensitive = false
vfsCS := New(r.Fremote, &optCS)
defer cleanupVFS(t, vfsCS)
optCI := vfscommon.Opt
optCI.CaseInsensitive = true
vfsCI := New(r.Fremote, &optCI)
defer cleanupVFS(t, vfsCI)
// Run basic checks that must pass on VFS of any type.
assertFileDataVFS(t, vfsCI, "FiLeA", "data1")
assertFileDataVFS(t, vfsCS, "FiLeA", "data1")
// Detect case sensitivity of the underlying remote.
remoteIsOK := true
if !checkFileDataVFS(t, vfsCS, "FiLeA", "data1") {
remoteIsOK = false
}
if !checkFileDataVFS(t, vfsCS, "FiLeB", "data2") {
remoteIsOK = false
}
if !checkFileDataVFS(t, vfsCS, "FilEb", "data3") {
remoteIsOK = false
}
// The remaining test is only meaningful on a case-Sensitive file system.
if !remoteIsOK {
t.Skip("Can't test case sensitivity - this remote doesn't comply as case-sensitive")
}
// Continue with test as the underlying remote is fully case-Sensitive.
r.CheckRemoteItems(t, file1, file2, file3)
// See how VFS handles case-INsensitive flag
assertFileDataVFS(t, vfsCI, "FiLeA", "data1")
assertFileDataVFS(t, vfsCI, "fileA", "data1")
assertFileDataVFS(t, vfsCI, "filea", "data1")
assertFileDataVFS(t, vfsCI, "FILEA", "data1")
assertFileDataVFS(t, vfsCI, "FiLeB", "data2")
assertFileDataVFS(t, vfsCI, "FilEb", "data3")
fd, err := vfsCI.OpenFile("fileb", os.O_RDONLY, 0777)
assert.Nil(t, fd)
assert.Error(t, err)
assert.NotEqual(t, err, ENOENT)
fd, err = vfsCI.OpenFile("FILEB", os.O_RDONLY, 0777)
assert.Nil(t, fd)
assert.Error(t, err)
assert.NotEqual(t, err, ENOENT)
// Run the same set of checks with case-Sensitive VFS, for comparison.
assertFileDataVFS(t, vfsCS, "FiLeA", "data1")
assertFileAbsentVFS(t, vfsCS, "fileA")
assertFileAbsentVFS(t, vfsCS, "filea")
assertFileAbsentVFS(t, vfsCS, "FILEA")
assertFileDataVFS(t, vfsCS, "FiLeB", "data2")
assertFileDataVFS(t, vfsCS, "FilEb", "data3")
assertFileAbsentVFS(t, vfsCS, "fileb")
assertFileAbsentVFS(t, vfsCS, "FILEB")
}
func checkFileDataVFS(t *testing.T, vfs *VFS, name string, expect string) bool {
fd, err := vfs.OpenFile(name, os.O_RDONLY, 0777)
if fd == nil || err != nil {
return false
}
defer func() {
// File must be closed - otherwise Run.cleanUp() will fail on Windows.
_ = fd.Close()
}()
fh, ok := fd.(*ReadFileHandle)
if !ok {
return false
}
size := len(expect)
buf := make([]byte, size)
num, err := fh.Read(buf)
if err != nil || num != size {
return false
}
return string(buf) == expect
}
func assertFileDataVFS(t *testing.T, vfs *VFS, name string, expect string) {
fd, errOpen := vfs.OpenFile(name, os.O_RDONLY, 0777)
assert.NotNil(t, fd)
assert.NoError(t, errOpen)
defer func() {
// File must be closed - otherwise Run.cleanUp() will fail on Windows.
if errOpen == nil && fd != nil {
_ = fd.Close()
}
}()
fh, ok := fd.(*ReadFileHandle)
require.True(t, ok)
size := len(expect)
buf := make([]byte, size)
numRead, errRead := fh.Read(buf)
assert.NoError(t, errRead)
assert.Equal(t, numRead, size)
assert.Equal(t, string(buf), expect)
}
func assertFileAbsentVFS(t *testing.T, vfs *VFS, name string) {
fd, err := vfs.OpenFile(name, os.O_RDONLY, 0777)
defer func() {
// File must be closed - otherwise Run.cleanUp() will fail on Windows.
if err == nil && fd != nil {
_ = fd.Close()
}
}()
assert.Nil(t, fd)
assert.Error(t, err)
assert.Equal(t, err, ENOENT)
}
func TestUnicodeNormalization(t *testing.T) {
r := fstest.NewRun(t)
var (
nfc = norm.NFC.String(norm.NFD.String("測試_Русский___ě_áñ"))
nfd = norm.NFD.String(nfc)
both = "normal name with no special characters.txt"
)
// Create test files
ctx := context.Background()
file1 := r.WriteObject(ctx, both, "data1", t1)
file2 := r.WriteObject(ctx, nfc, "data2", t2)
r.CheckRemoteItems(t, file1, file2)
// Create VFS
opt := vfscommon.Opt
vfs := New(r.Fremote, &opt)
defer cleanupVFS(t, vfs)
// assert that both files are found under NFD-normalized names
assertFileDataVFS(t, vfs, norm.NFD.String(both), "data1")
assertFileDataVFS(t, vfs, nfd, "data2")
// change ci.NoUnicodeNormalization to true and verify that only file1 is found
ci := fs.GetConfig(ctx) // need to set the global config here as the *Dir methods don't take a ctx param
oldVal := ci.NoUnicodeNormalization
defer func() { fs.GetConfig(ctx).NoUnicodeNormalization = oldVal }() // restore the prior value after the test
ci.NoUnicodeNormalization = true
assertFileDataVFS(t, vfs, norm.NFD.String(both), "data1")
assertFileAbsentVFS(t, vfs, nfd)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/write.go | vfs/write.go | package vfs
import (
"context"
"io"
"os"
"sync"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/operations"
)
// WriteFileHandle is an open for write handle on a File
type WriteFileHandle struct {
baseHandle
mu sync.Mutex
cond sync.Cond // cond lock for out of sequence writes
remote string
pipeWriter *io.PipeWriter
o fs.Object
result chan error
file *File
offset int64
flags int
closed bool // set if handle has been closed
writeCalled bool // set the first time Write() is called
opened bool
truncated bool
}
// Check interfaces
var (
_ io.Writer = (*WriteFileHandle)(nil)
_ io.WriterAt = (*WriteFileHandle)(nil)
_ io.Closer = (*WriteFileHandle)(nil)
)
func newWriteFileHandle(d *Dir, f *File, remote string, flags int) (*WriteFileHandle, error) {
if f.IsSymlink() {
remote += fs.LinkSuffix
}
fh := &WriteFileHandle{
remote: remote,
flags: flags,
result: make(chan error, 1),
file: f,
}
fh.cond = sync.Cond{L: &fh.mu}
fh.file.addWriter(fh)
return fh, nil
}
// returns whether it is OK to truncate the file
func (fh *WriteFileHandle) safeToTruncate() bool {
return fh.truncated || fh.flags&os.O_TRUNC != 0 || !fh.file.exists()
}
// openPending opens the file if there is a pending open
//
// call with the lock held
func (fh *WriteFileHandle) openPending() (err error) {
if fh.opened {
return nil
}
if !fh.safeToTruncate() {
fs.Errorf(fh.remote, "WriteFileHandle: Can't open for write without O_TRUNC on existing file without --vfs-cache-mode >= writes")
return EPERM
}
var pipeReader *io.PipeReader
pipeReader, fh.pipeWriter = io.Pipe()
go func() {
// NB Rcat deals with Stats.Transferring, etc.
o, err := operations.Rcat(context.TODO(), fh.file.Fs(), fh.remote, pipeReader, time.Now(), nil)
if err != nil {
fs.Errorf(fh.remote, "WriteFileHandle.New Rcat failed: %v", err)
}
// Close the pipeReader so the pipeWriter fails with ErrClosedPipe
_ = pipeReader.Close()
fh.o = o
fh.result <- err
}()
fh.file.setSize(0)
fh.truncated = true
fh.file.Dir().addObject(fh.file) // make sure the directory has this object in it now
fh.opened = true
return nil
}
// String converts it to printable
func (fh *WriteFileHandle) String() string {
if fh == nil {
return "<nil *WriteFileHandle>"
}
fh.mu.Lock()
defer fh.mu.Unlock()
if fh.file == nil {
return "<nil *WriteFileHandle.file>"
}
return fh.file.String() + " (w)"
}
// Node returns the Node associated with this - satisfies Noder interface
func (fh *WriteFileHandle) Node() Node {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.file
}
// WriteAt writes len(p) bytes from p to the underlying data stream at offset
// off. It returns the number of bytes written from p (0 <= n <= len(p)) and
// any error encountered that caused the write to stop early. WriteAt must
// return a non-nil error if it returns n < len(p).
//
// If WriteAt is writing to a destination with a seek offset, WriteAt should
// not affect nor be affected by the underlying seek offset.
//
// Clients of WriteAt can execute parallel WriteAt calls on the same
// destination if the ranges do not overlap.
//
// Implementations must not retain p.
func (fh *WriteFileHandle) WriteAt(p []byte, off int64) (n int, err error) {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.writeAt(p, off)
}
// Implementation of WriteAt - call with lock held
func (fh *WriteFileHandle) writeAt(p []byte, off int64) (n int, err error) {
// defer log.Trace(fh.remote, "len=%d off=%d", len(p), off)("n=%d, fh.off=%d, err=%v", &n, &fh.offset, &err)
if fh.closed {
fs.Errorf(fh.remote, "WriteFileHandle.Write: error: %v", EBADF)
return 0, ECLOSED
}
if fh.offset != off {
waitSequential("write", fh.remote, &fh.cond, time.Duration(fh.file.VFS().Opt.WriteWait), &fh.offset, off)
}
if fh.offset != off {
fs.Errorf(fh.remote, "WriteFileHandle.Write: can't seek in file without --vfs-cache-mode >= writes")
return 0, ESPIPE
}
if err = fh.openPending(); err != nil {
return 0, err
}
fh.writeCalled = true
n, err = fh.pipeWriter.Write(p)
fh.offset += int64(n)
fh.file.setSize(fh.offset)
if err != nil {
fs.Errorf(fh.remote, "WriteFileHandle.Write error: %v", err)
return 0, err
}
// fs.Debugf(fh.remote, "WriteFileHandle.Write OK (%d bytes written)", n)
fh.cond.Broadcast() // wake everyone up waiting for an in-sequence read
return n, nil
}
// Write writes len(p) bytes from p to the underlying data stream. It returns
// the number of bytes written from p (0 <= n <= len(p)) and any error
// encountered that caused the write to stop early. Write must return a non-nil
// error if it returns n < len(p). Write must not modify the slice data, even
// temporarily.
//
// Implementations must not retain p.
func (fh *WriteFileHandle) Write(p []byte) (n int, err error) {
fh.mu.Lock()
defer fh.mu.Unlock()
// Since we can't seek, just call WriteAt with the current offset
return fh.writeAt(p, fh.offset)
}
// WriteString a string to the file
func (fh *WriteFileHandle) WriteString(s string) (n int, err error) {
return fh.Write([]byte(s))
}
// Offset returns the offset of the file pointer
func (fh *WriteFileHandle) Offset() (offset int64) {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.offset
}
// close the file handle returning EBADF if it has been
// closed already.
//
// Must be called with fh.mu held
func (fh *WriteFileHandle) close() (err error) {
if fh.closed {
return ECLOSED
}
fh.closed = true
// leave writer open until file is transferred
defer func() {
fh.file.delWriter(fh)
}()
// If file not opened and not safe to truncate then leave file intact
if !fh.opened && !fh.safeToTruncate() {
return nil
}
if err = fh.openPending(); err != nil {
return err
}
writeCloseErr := fh.pipeWriter.Close()
err = <-fh.result
if err == nil {
fh.file.setObject(fh.o)
err = writeCloseErr
} else if fh.file.getObject() == nil {
// Remove vfs file entry when no object is present
_ = fh.file.Remove()
}
return err
}
// Close closes the file
func (fh *WriteFileHandle) Close() error {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.close()
}
// Flush is called on each close() of a file descriptor. So if a
// filesystem wants to return write errors in close() and the file has
// cached dirty data, this is a good place to write back data and
// return any errors. Since many applications ignore close() errors
// this is not always useful.
//
// NOTE: The flush() method may be called more than once for each
// open(). This happens if more than one file descriptor refers to an
// opened file due to dup(), dup2() or fork() calls. It is not
// possible to determine if a flush is final, so each flush should be
// treated equally. Multiple write-flush sequences are relatively
// rare, so this shouldn't be a problem.
//
// Filesystems shouldn't assume that flush will always be called after
// some writes, or that if will be called at all.
func (fh *WriteFileHandle) Flush() error {
fh.mu.Lock()
defer fh.mu.Unlock()
if fh.closed {
fs.Debugf(fh.remote, "WriteFileHandle.Flush nothing to do")
return nil
}
// fs.Debugf(fh.remote, "WriteFileHandle.Flush")
// If Write hasn't been called then ignore the Flush - Release
// will pick it up
if !fh.writeCalled {
fs.Debugf(fh.remote, "WriteFileHandle.Flush unwritten handle, writing 0 bytes to avoid race conditions")
_, err := fh.writeAt([]byte{}, fh.offset)
return err
}
err := fh.close()
if err != nil {
fs.Errorf(fh.remote, "WriteFileHandle.Flush error: %v", err)
//} else {
// fs.Debugf(fh.remote, "WriteFileHandle.Flush OK")
}
return err
}
// Release is called when we are finished with the file handle
//
// It isn't called directly from userspace so the error is ignored by
// the kernel
func (fh *WriteFileHandle) Release() error {
fh.mu.Lock()
defer fh.mu.Unlock()
if fh.closed {
fs.Debugf(fh.remote, "WriteFileHandle.Release nothing to do")
return nil
}
fs.Debugf(fh.remote, "WriteFileHandle.Release closing")
err := fh.close()
if err != nil {
fs.Errorf(fh.remote, "WriteFileHandle.Release error: %v", err)
//} else {
// fs.Debugf(fh.remote, "WriteFileHandle.Release OK")
}
return err
}
// Stat returns info about the file
func (fh *WriteFileHandle) Stat() (os.FileInfo, error) {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.file, nil
}
// Truncate file to given size
func (fh *WriteFileHandle) Truncate(size int64) (err error) {
// defer log.Trace(fh.remote, "size=%d", size)("err=%v", &err)
fh.mu.Lock()
defer fh.mu.Unlock()
if size != fh.offset {
fs.Errorf(fh.remote, "WriteFileHandle: Truncate: Can't change size without --vfs-cache-mode >= writes")
return EPERM
}
// File is correct size
if size == 0 {
fh.truncated = true
}
return nil
}
// Read reads up to len(p) bytes into p.
func (fh *WriteFileHandle) Read(p []byte) (n int, err error) {
fs.Errorf(fh.remote, "WriteFileHandle: Read: Can't read and write to file without --vfs-cache-mode >= minimal")
return 0, EPERM
}
// ReadAt reads len(p) bytes into p starting at offset off in the
// underlying input source. It returns the number of bytes read (0 <=
// n <= len(p)) and any error encountered.
func (fh *WriteFileHandle) ReadAt(p []byte, off int64) (n int, err error) {
fs.Errorf(fh.remote, "WriteFileHandle: ReadAt: Can't read and write to file without --vfs-cache-mode >= minimal")
return 0, EPERM
}
// Sync commits the current contents of the file to stable storage. Typically,
// this means flushing the file system's in-memory copy of recently written
// data to disk.
func (fh *WriteFileHandle) Sync() error {
return nil
}
// Name returns the name of the file from the underlying Object.
func (fh *WriteFileHandle) Name() string {
return fh.file.String()
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/read.go | vfs/read.go | package vfs
import (
"context"
"errors"
"fmt"
"io"
"os"
"sync"
"sync/atomic"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/chunkedreader"
"github.com/rclone/rclone/fs/hash"
)
// ReadFileHandle is an open for read file handle on a File
type ReadFileHandle struct {
baseHandle
done func(ctx context.Context, err error)
mu sync.Mutex
cond sync.Cond // cond lock for out of sequence reads
r *accounting.Account
size int64 // size of the object (0 for unknown length)
offset int64 // offset of read of o
roffset int64 // offset of Read() calls
file *File
hash *hash.MultiHasher
remote string
closed bool // set if handle has been closed
readCalled bool // set if read has been called
noSeek bool
sizeUnknown bool // set if size of source is not known
opened bool
}
// Check interfaces
var (
_ io.Reader = (*ReadFileHandle)(nil)
_ io.ReaderAt = (*ReadFileHandle)(nil)
_ io.Seeker = (*ReadFileHandle)(nil)
_ io.Closer = (*ReadFileHandle)(nil)
)
func newReadFileHandle(f *File) (*ReadFileHandle, error) {
var mhash *hash.MultiHasher
var err error
o := f.getObject()
if !f.VFS().Opt.NoChecksum {
hashes := hash.NewHashSet(o.Fs().Hashes().GetOne()) // just pick one hash
mhash, err = hash.NewMultiHasherTypes(hashes)
if err != nil {
fs.Errorf(o.Fs(), "newReadFileHandle hash error: %v", err)
}
}
fh := &ReadFileHandle{
remote: o.Remote(),
noSeek: f.VFS().Opt.NoSeek,
file: f,
hash: mhash,
size: nonNegative(o.Size()),
sizeUnknown: o.Size() < 0,
}
fh.cond = sync.Cond{L: &fh.mu}
return fh, nil
}
// openPending opens the file if there is a pending open
// call with the lock held
func (fh *ReadFileHandle) openPending() (err error) {
if fh.opened {
return nil
}
o := fh.file.getObject()
opt := &fh.file.VFS().Opt
r, err := chunkedreader.New(context.TODO(), o, int64(opt.ChunkSize), int64(opt.ChunkSizeLimit), opt.ChunkStreams).Open()
if err != nil {
return err
}
tr := accounting.GlobalStats().NewTransfer(o, nil)
fh.done = tr.Done
fh.r = tr.Account(context.TODO(), r).WithBuffer() // account the transfer
fh.opened = true
return nil
}
// String converts it to printable
func (fh *ReadFileHandle) String() string {
if fh == nil {
return "<nil *ReadFileHandle>"
}
fh.mu.Lock()
defer fh.mu.Unlock()
if fh.file == nil {
return "<nil *ReadFileHandle.file>"
}
return fh.file.String() + " (r)"
}
// Node returns the Node associated with this - satisfies Noder interface
func (fh *ReadFileHandle) Node() Node {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.file
}
// seek to a new offset
//
// if reopen is true, then we won't attempt to use an io.Seeker interface
//
// Must be called with fh.mu held
func (fh *ReadFileHandle) seek(offset int64, reopen bool) (err error) {
if fh.noSeek {
return ESPIPE
}
fh.hash = nil
if !reopen {
ar := fh.r.GetAsyncReader()
// try to fulfill the seek with buffer discard
if ar != nil && ar.SkipBytes(int(offset-fh.offset)) {
fh.offset = offset
return nil
}
}
fh.r.StopBuffering() // stop the background reading first
oldReader := fh.r.GetReader()
r, ok := oldReader.(chunkedreader.ChunkedReader)
if !ok {
fs.Logf(fh.remote, "ReadFileHandle.Read expected reader to be a ChunkedReader, got %T", oldReader)
reopen = true
}
if !reopen {
fs.Debugf(fh.remote, "ReadFileHandle.seek from %d to %d (fs.RangeSeeker)", fh.offset, offset)
_, err = r.RangeSeek(context.TODO(), offset, io.SeekStart, -1)
if err != nil {
fs.Debugf(fh.remote, "ReadFileHandle.Read fs.RangeSeeker failed: %v", err)
return err
}
} else {
fs.Debugf(fh.remote, "ReadFileHandle.seek from %d to %d", fh.offset, offset)
// close old one
err = oldReader.Close()
if err != nil {
fs.Debugf(fh.remote, "ReadFileHandle.Read seek close old failed: %v", err)
}
// re-open with a seek
o := fh.file.getObject()
opt := &fh.file.VFS().Opt
r = chunkedreader.New(context.TODO(), o, int64(opt.ChunkSize), int64(opt.ChunkSizeLimit), opt.ChunkStreams)
_, err := r.Seek(offset, 0)
if err != nil {
fs.Debugf(fh.remote, "ReadFileHandle.Read seek failed: %v", err)
return err
}
r, err = r.Open()
if err != nil {
fs.Debugf(fh.remote, "ReadFileHandle.Read seek failed: %v", err)
return err
}
}
fh.r.UpdateReader(context.TODO(), r)
fh.offset = offset
return nil
}
// Seek the file - returns ESPIPE if seeking isn't possible
func (fh *ReadFileHandle) Seek(offset int64, whence int) (n int64, err error) {
fh.mu.Lock()
defer fh.mu.Unlock()
if fh.noSeek {
return 0, ESPIPE
}
size := fh.size
switch whence {
case io.SeekStart:
fh.roffset = 0
case io.SeekEnd:
fh.roffset = size
}
fh.roffset += offset
// we don't check the offset - the next Read will
return fh.roffset, nil
}
// ReadAt reads len(p) bytes into p starting at offset off in the
// underlying input source. It returns the number of bytes read (0 <=
// n <= len(p)) and any error encountered.
//
// When ReadAt returns n < len(p), it returns a non-nil error
// explaining why more bytes were not returned. In this respect,
// ReadAt is stricter than Read.
//
// Even if ReadAt returns n < len(p), it may use all of p as scratch
// space during the call. If some data is available but not len(p)
// bytes, ReadAt blocks until either all the data is available or an
// error occurs. In this respect ReadAt is different from Read.
//
// If the n = len(p) bytes returned by ReadAt are at the end of the
// input source, ReadAt may return either err == EOF or err == nil.
//
// If ReadAt is reading from an input source with a seek offset,
// ReadAt should not affect nor be affected by the underlying seek
// offset.
//
// Clients of ReadAt can execute parallel ReadAt calls on the same
// input source.
//
// Implementations must not retain p.
func (fh *ReadFileHandle) ReadAt(p []byte, off int64) (n int, err error) {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.readAt(p, off)
}
// This waits for *poff to equal off or aborts after the timeout.
//
// Waits here potentially affect all seeks so need to keep them short.
//
// Call with fh.mu Locked
func waitSequential(what string, remote string, cond *sync.Cond, maxWait time.Duration, poff *int64, off int64) {
var (
timeout = time.NewTimer(maxWait)
done = make(chan struct{})
abort atomic.Int32
)
go func() {
select {
case <-timeout.C:
// take the lock to make sure that cond.Wait() is called before
// cond.Broadcast. NB cond.L == mu
cond.L.Lock()
// set abort flag and give all the waiting goroutines a kick on timeout
abort.Store(1)
fs.Debugf(remote, "aborting in-sequence %s wait, off=%d", what, off)
cond.Broadcast()
cond.L.Unlock()
case <-done:
}
}()
for *poff != off && abort.Load() == 0 {
fs.Debugf(remote, "waiting for in-sequence %s to %d for %v", what, off, maxWait)
cond.Wait()
}
// tidy up end timer
close(done)
timeout.Stop()
if *poff != off {
fs.Debugf(remote, "failed to wait for in-sequence %s to %d", what, off)
}
}
// Implementation of ReadAt - call with lock held
func (fh *ReadFileHandle) readAt(p []byte, off int64) (n int, err error) {
// defer log.Trace(fh.remote, "p[%d], off=%d", len(p), off)("n=%d, err=%v", &n, &err)
err = fh.openPending() // FIXME pending open could be more efficient in the presence of seek (and retries)
if err != nil {
return 0, err
}
// fs.Debugf(fh.remote, "ReadFileHandle.Read size %d offset %d", reqSize, off)
if fh.closed {
fs.Errorf(fh.remote, "ReadFileHandle.Read error: %v", EBADF)
return 0, ECLOSED
}
maxBuf := min(len(p), 1024*1024)
if gap := off - fh.offset; gap > 0 && gap < int64(8*maxBuf) {
waitSequential("read", fh.remote, &fh.cond, time.Duration(fh.file.VFS().Opt.ReadWait), &fh.offset, off)
}
doSeek := off != fh.offset
if doSeek && fh.noSeek {
return 0, ESPIPE
}
var newOffset int64
retries := 0
reqSize := len(p)
doReopen := false
lowLevelRetries := fs.GetConfig(context.TODO()).LowLevelRetries
for {
if doSeek {
// Are we attempting to seek beyond the end of the
// file - if so just return EOF leaving the underlying
// file in an unchanged state.
if off >= fh.size {
fs.Debugf(fh.remote, "ReadFileHandle.Read attempt to read beyond end of file: %d > %d", off, fh.size)
return 0, io.EOF
}
// Otherwise do the seek
err = fh.seek(off, doReopen)
} else {
err = nil
}
if err == nil {
if reqSize > 0 {
fh.readCalled = true
}
n, err = io.ReadFull(fh.r, p)
newOffset = fh.offset + int64(n)
// if err == nil && rand.Intn(10) == 0 {
// err = errors.New("random error")
// }
if err == nil {
break
} else if (err == io.ErrUnexpectedEOF || err == io.EOF) && (newOffset == fh.size || fh.sizeUnknown) {
if fh.sizeUnknown {
// size is now known since we have read to the end
fh.sizeUnknown = false
fh.size = newOffset
}
// Have read to end of file - reset error
err = nil
break
}
}
if retries >= lowLevelRetries {
break
}
retries++
fs.Errorf(fh.remote, "ReadFileHandle.Read error: low level retry %d/%d: %v", retries, lowLevelRetries, err)
doSeek = true
doReopen = true
}
if err != nil {
fs.Errorf(fh.remote, "ReadFileHandle.Read error: %v", err)
} else {
fh.offset = newOffset
// fs.Debugf(fh.remote, "ReadFileHandle.Read OK")
if fh.hash != nil {
_, err = fh.hash.Write(p[:n])
if err != nil {
fs.Errorf(fh.remote, "ReadFileHandle.Read HashError: %v", err)
return 0, err
}
}
// If we have no error and we didn't fill the buffer, must be EOF
if n != len(p) {
err = io.EOF
}
}
fh.cond.Broadcast() // wake everyone up waiting for an in-sequence read
return n, err
}
func (fh *ReadFileHandle) checkHash() error {
if fh.hash == nil || !fh.readCalled || fh.offset < fh.size {
return nil
}
o := fh.file.getObject()
for hashType, dstSum := range fh.hash.Sums() {
srcSum, err := o.Hash(context.TODO(), hashType)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
// if it was file not found then at
// this point we don't care any more
continue
}
return err
}
if !hash.Equals(dstSum, srcSum) {
return fmt.Errorf("corrupted on transfer: %v hashes differ src %q vs dst %q", hashType, srcSum, dstSum)
}
}
return nil
}
// Read reads up to len(p) bytes into p. It returns the number of bytes read (0
// <= n <= len(p)) and any error encountered. Even if Read returns n < len(p),
// it may use all of p as scratch space during the call. If some data is
// available but not len(p) bytes, Read conventionally returns what is
// available instead of waiting for more.
//
// When Read encounters an error or end-of-file condition after successfully
// reading n > 0 bytes, it returns the number of bytes read. It may return the
// (non-nil) error from the same call or return the error (and n == 0) from a
// subsequent call. An instance of this general case is that a Reader returning
// a non-zero number of bytes at the end of the input stream may return either
// err == EOF or err == nil. The next Read should return 0, EOF.
//
// Callers should always process the n > 0 bytes returned before considering
// the error err. Doing so correctly handles I/O errors that happen after
// reading some bytes and also both of the allowed EOF behaviors.
//
// Implementations of Read are discouraged from returning a zero byte count
// with a nil error, except when len(p) == 0. Callers should treat a return of
// 0 and nil as indicating that nothing happened; in particular it does not
// indicate EOF.
//
// Implementations must not retain p.
func (fh *ReadFileHandle) Read(p []byte) (n int, err error) {
fh.mu.Lock()
defer fh.mu.Unlock()
if fh.roffset >= fh.size && !fh.sizeUnknown {
return 0, io.EOF
}
n, err = fh.readAt(p, fh.roffset)
fh.roffset += int64(n)
return n, err
}
// close the file handle returning EBADF if it has been
// closed already.
//
// Must be called with fh.mu held
func (fh *ReadFileHandle) close() error {
if fh.closed {
return ECLOSED
}
fh.closed = true
if fh.opened {
var err error
defer func() {
fh.done(context.TODO(), err)
}()
// Close first so that we have hashes
err = fh.r.Close()
if err != nil {
return err
}
// Now check the hash
err = fh.checkHash()
if err != nil {
return err
}
}
return nil
}
// Close closes the file
func (fh *ReadFileHandle) Close() error {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.close()
}
// Flush is called each time the file or directory is closed.
// Because there can be multiple file descriptors referring to a
// single opened file, Flush can be called multiple times.
func (fh *ReadFileHandle) Flush() error {
fh.mu.Lock()
defer fh.mu.Unlock()
if !fh.opened {
return nil
}
// fs.Debugf(fh.remote, "ReadFileHandle.Flush")
if err := fh.checkHash(); err != nil {
fs.Errorf(fh.remote, "ReadFileHandle.Flush error: %v", err)
return err
}
// fs.Debugf(fh.remote, "ReadFileHandle.Flush OK")
return nil
}
// Release is called when we are finished with the file handle
//
// It isn't called directly from userspace so the error is ignored by
// the kernel
func (fh *ReadFileHandle) Release() error {
fh.mu.Lock()
defer fh.mu.Unlock()
if !fh.opened {
return nil
}
if fh.closed {
fs.Debugf(fh.remote, "ReadFileHandle.Release nothing to do")
return nil
}
fs.Debugf(fh.remote, "ReadFileHandle.Release closing")
err := fh.close()
if err != nil {
fs.Errorf(fh.remote, "ReadFileHandle.Release error: %v", err)
//} else {
// fs.Debugf(fh.remote, "ReadFileHandle.Release OK")
}
return err
}
// Name returns the name of the file from the underlying Object.
func (fh *ReadFileHandle) Name() string {
return fh.file.String()
}
// Size returns the size of the underlying file
func (fh *ReadFileHandle) Size() int64 {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.size
}
// Stat returns info about the file
func (fh *ReadFileHandle) Stat() (os.FileInfo, error) {
fh.mu.Lock()
defer fh.mu.Unlock()
return fh.file, nil
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/dir_handle_test.go | vfs/dir_handle_test.go | package vfs
import (
"context"
"io"
"os"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestDirHandleMethods(t *testing.T) {
_, _, dir, _ := dirCreate(t)
h, err := dir.Open(os.O_RDONLY)
require.NoError(t, err)
fh, ok := h.(*DirHandle)
assert.True(t, ok)
// String
assert.Equal(t, "dir/ (r)", fh.String())
assert.Equal(t, "<nil *DirHandle>", (*DirHandle)(nil).String())
assert.Equal(t, "<nil *DirHandle.d>", newDirHandle(nil).String())
// Stat
fi, err := fh.Stat()
require.NoError(t, err)
assert.Equal(t, dir, fi)
// Node
assert.Equal(t, dir, fh.Node())
// Close
require.NoError(t, h.Close())
assert.Equal(t, []os.FileInfo(nil), fh.fis)
}
func TestDirHandleReaddir(t *testing.T) {
r, vfs := newTestVFS(t)
file1 := r.WriteObject(context.Background(), "dir/file1", "file1 contents", t1)
file2 := r.WriteObject(context.Background(), "dir/file2", "file2- contents", t2)
file3 := r.WriteObject(context.Background(), "dir/subdir/file3", "file3-- contents", t3)
r.CheckRemoteItems(t, file1, file2, file3)
node, err := vfs.Stat("dir")
require.NoError(t, err)
dir := node.(*Dir)
// Read in one chunk
fh, err := dir.Open(os.O_RDONLY)
require.NoError(t, err)
fis, err := fh.Readdir(-1)
require.NoError(t, err)
require.Equal(t, 3, len(fis))
assert.Equal(t, "file1", fis[0].Name())
assert.Equal(t, "file2", fis[1].Name())
assert.Equal(t, "subdir", fis[2].Name())
assert.False(t, fis[0].IsDir())
assert.False(t, fis[1].IsDir())
assert.True(t, fis[2].IsDir())
require.NoError(t, fh.Close())
// Read in multiple chunks
fh, err = dir.Open(os.O_RDONLY)
require.NoError(t, err)
fis, err = fh.Readdir(2)
require.NoError(t, err)
require.Equal(t, 2, len(fis))
assert.Equal(t, "file1", fis[0].Name())
assert.Equal(t, "file2", fis[1].Name())
assert.False(t, fis[0].IsDir())
assert.False(t, fis[1].IsDir())
fis, err = fh.Readdir(2)
require.NoError(t, err)
require.Equal(t, 1, len(fis))
assert.Equal(t, "subdir", fis[0].Name())
assert.True(t, fis[0].IsDir())
fis, err = fh.Readdir(2)
assert.Equal(t, io.EOF, err)
require.Equal(t, 0, len(fis))
require.NoError(t, fh.Close())
}
func TestDirHandleReaddirnames(t *testing.T) {
_, _, dir, _ := dirCreate(t)
fh, err := dir.Open(os.O_RDONLY)
require.NoError(t, err)
// Smoke test only since heavy lifting done in Readdir
fis, err := fh.Readdirnames(-1)
require.NoError(t, err)
require.Equal(t, 1, len(fis))
assert.Equal(t, "file1", fis[0])
require.NoError(t, fh.Close())
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/sighup_unsupported.go | vfs/sighup_unsupported.go | //go:build plan9 || js
package vfs
import (
"os"
)
// NotifyOnSigHup makes SIGHUP notify given channel on supported systems
func NotifyOnSigHup(sighupChan chan os.Signal) {}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest_test.go | vfs/vfstest_test.go | // Run the more functional vfstest package on the vfs
package vfs_test
import (
"testing"
_ "github.com/rclone/rclone/backend/all" // import all the backends
"github.com/rclone/rclone/cmd/mountlib"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/vfs"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/rclone/rclone/vfs/vfstest"
)
// TestFunctional runs more functional tests all the tests against all the
// VFS cache modes
func TestFunctional(t *testing.T) {
if *fstest.RemoteName != "" {
t.Skip("Skip on non local")
}
vfstest.RunTests(t, true, vfscommon.CacheModeOff, true, func(VFS *vfs.VFS, mountpoint string, opt *mountlib.Options) (unmountResult <-chan error, unmount func() error, err error) {
unmountResultChan := make(chan (error), 1)
unmount = func() error {
unmountResultChan <- nil
return nil
}
return unmountResultChan, unmount, nil
})
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/rc_test.go | vfs/rc_test.go | package vfs
import (
"context"
"testing"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/rc"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func rcNewRun(t *testing.T, method string) (r *fstest.Run, vfs *VFS, call *rc.Call) {
if *fstest.RemoteName != "" {
t.Skip("Skipping test on non local remote")
}
r, vfs = newTestVFS(t)
call = rc.Calls.Get(method)
assert.NotNil(t, call)
return r, vfs, call
}
func TestRcGetVFS(t *testing.T) {
in := rc.Params{}
vfs, err := getVFS(in)
require.Error(t, err)
assert.Contains(t, err.Error(), "no VFS active")
assert.Nil(t, vfs)
r, vfs2 := newTestVFS(t)
vfs, err = getVFS(in)
require.NoError(t, err)
assert.True(t, vfs == vfs2)
inPresent := rc.Params{"fs": fs.ConfigString(r.Fremote)}
vfs, err = getVFS(inPresent)
require.NoError(t, err)
assert.True(t, vfs == vfs2)
inWrong := rc.Params{"fs": fs.ConfigString(r.Fremote) + "notfound"}
vfs, err = getVFS(inWrong)
require.Error(t, err)
assert.Contains(t, err.Error(), "no VFS found with name")
assert.Nil(t, vfs)
opt := vfscommon.Opt
opt.NoModTime = true
vfs3 := New(r.Fremote, &opt)
defer vfs3.Shutdown()
vfs, err = getVFS(in)
require.Error(t, err)
assert.Contains(t, err.Error(), "more than one VFS active - need")
assert.Nil(t, vfs)
inPresent = rc.Params{"fs": fs.ConfigString(r.Fremote)}
vfs, err = getVFS(inPresent)
require.Error(t, err)
assert.Contains(t, err.Error(), "more than one VFS active with name")
assert.Nil(t, vfs)
}
func TestRcForget(t *testing.T) {
r, vfs, call := rcNewRun(t, "vfs/forget")
_, _ = r, vfs
in := rc.Params{"fs": fs.ConfigString(r.Fremote)}
out, err := call.Fn(context.Background(), in)
require.NoError(t, err)
assert.Equal(t, rc.Params{
"forgotten": []string{},
}, out)
// FIXME needs more tests
}
func TestRcRefresh(t *testing.T) {
r, vfs, call := rcNewRun(t, "vfs/refresh")
_, _ = r, vfs
in := rc.Params{"fs": fs.ConfigString(r.Fremote)}
out, err := call.Fn(context.Background(), in)
require.NoError(t, err)
assert.Equal(t, rc.Params{
"result": map[string]string{
"": "OK",
},
}, out)
// FIXME needs more tests
}
func TestRcPollInterval(t *testing.T) {
r, vfs, call := rcNewRun(t, "vfs/poll-interval")
_ = vfs
if r.Fremote.Features().ChangeNotify == nil {
t.Skip("ChangeNotify not supported")
}
out, err := call.Fn(context.Background(), nil)
require.NoError(t, err)
assert.Equal(t, rc.Params{}, out)
// FIXME needs more tests
}
func TestRcList(t *testing.T) {
r, vfs, call := rcNewRun(t, "vfs/list")
_ = vfs
out, err := call.Fn(context.Background(), nil)
require.NoError(t, err)
assert.Equal(t, rc.Params{
"vfses": []string{
fs.ConfigString(r.Fremote),
},
}, out)
}
func TestRcStats(t *testing.T) {
r, vfs, call := rcNewRun(t, "vfs/stats")
out, err := call.Fn(context.Background(), nil)
require.NoError(t, err)
assert.Equal(t, fs.ConfigString(r.Fremote), out["fs"])
assert.Equal(t, int32(1), out["inUse"])
assert.Equal(t, 0, out["metadataCache"].(rc.Params)["files"])
assert.Equal(t, 1, out["metadataCache"].(rc.Params)["dirs"])
assert.Equal(t, vfs.Opt, out["opt"].(vfscommon.Options))
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/dir.go | vfs/dir.go | package vfs
import (
"context"
"encoding/json"
"fmt"
"os"
"path"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/dirtree"
"github.com/rclone/rclone/fs/list"
"github.com/rclone/rclone/fs/log"
"github.com/rclone/rclone/fs/object"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fs/walk"
"github.com/rclone/rclone/vfs/vfscommon"
"golang.org/x/text/unicode/norm"
)
// Dir represents a directory entry
type Dir struct {
vfs *VFS // read only
inode uint64 // read only: inode number
f fs.Fs // read only
cleanupTimer *time.Timer // read only: timer to call cacheCleanup
mu sync.RWMutex // protects the following
parent *Dir // parent, nil for root
path string
entry fs.Directory
read time.Time // time directory entry last read
items map[string]Node // directory entries - can be empty but not nil
virtual map[string]vState // virtual directory entries - may be nil
sys atomic.Value // user defined info to be attached here
modTimeMu sync.Mutex // protects the following
modTime time.Time
_virtuals atomic.Int32 // number of virtual directory entries in this directory and children
}
//go:generate stringer -type=vState
// vState describes the state of the virtual directory entries
type vState byte
const (
vOK vState = iota // Not virtual
vAddFile // added file
vAddDir // added directory
vDel // removed file or directory
)
func newDir(vfs *VFS, f fs.Fs, parent *Dir, fsDir fs.Directory) *Dir {
d := &Dir{
vfs: vfs,
f: f,
parent: parent,
entry: fsDir,
path: fsDir.Remote(),
modTime: fsDir.ModTime(context.TODO()),
inode: newInode(),
items: make(map[string]Node),
}
// Set timer up like this to avoid race of d.cacheCleanup being called
// before d.cleanupTimer is assigned to
d.cleanupTimer = time.AfterFunc(time.Hour, d.cacheCleanup)
d.cleanupTimer.Reset(time.Duration(vfs.Opt.DirCacheTime * 2))
return d
}
func (d *Dir) cacheCleanup() {
defer func() {
// We should never panic here
_ = recover()
}()
when := time.Now()
d.mu.Lock()
_, stale := d._age(when)
d.mu.Unlock()
if stale {
d.ForgetAll()
}
}
// String converts it to printable
func (d *Dir) String() string {
if d == nil {
return "<nil *Dir>"
}
d.mu.RLock()
defer d.mu.RUnlock()
return d.path + "/"
}
// Dumps the directory tree to the string builder with the given indent
//
//lint:ignore U1000 false positive when running staticcheck,
//nolint:unused // Don't include unused when running golangci-lint
func (d *Dir) dumpIndent(out *strings.Builder, indent string) {
if d == nil {
fmt.Fprintf(out, "%s<nil *Dir>\n", indent)
return
}
d.mu.RLock()
defer d.mu.RUnlock()
fmt.Fprintf(out, "%sPath: %s\n", indent, d.path)
fmt.Fprintf(out, "%sEntry: %v\n", indent, d.entry)
fmt.Fprintf(out, "%sRead: %v\n", indent, d.read)
fmt.Fprintf(out, "%s- items %d\n", indent, len(d.items))
// Sort?
for leaf, node := range d.items {
switch x := node.(type) {
case *Dir:
fmt.Fprintf(out, "%s %s/ - %v\n", indent, leaf, x)
// check the parent is correct
if x.parent != d {
fmt.Fprintf(out, "%s PARENT POINTER WRONG\n", indent)
}
x.dumpIndent(out, indent+"\t")
case *File:
fmt.Fprintf(out, "%s %s - %v\n", indent, leaf, x)
default:
panic("bad dir entry")
}
}
fmt.Fprintf(out, "%s- virtual %d\n", indent, len(d.virtual))
for leaf, state := range d.virtual {
fmt.Fprintf(out, "%s %s - %v\n", indent, leaf, state)
}
}
// Dumps a nicely formatted directory tree to a string
//
//lint:ignore U1000 false positive when running staticcheck,
//nolint:unused // Don't include unused when running golangci-lint
func (d *Dir) dump() string {
var out strings.Builder
d.dumpIndent(&out, "")
return out.String()
}
// IsFile returns false for Dir - satisfies Node interface
func (d *Dir) IsFile() bool {
return false
}
// IsDir returns true for Dir - satisfies Node interface
func (d *Dir) IsDir() bool {
return true
}
// Mode bits of the directory - satisfies Node interface
func (d *Dir) Mode() (mode os.FileMode) {
return os.FileMode(d.vfs.Opt.DirPerms)
}
// Name (base) of the directory - satisfies Node interface
func (d *Dir) Name() (name string) {
d.mu.RLock()
name = path.Base(d.path)
d.mu.RUnlock()
if name == "." {
name = "/"
}
return name
}
// Path of the directory - satisfies Node interface
func (d *Dir) Path() (name string) {
d.mu.RLock()
defer d.mu.RUnlock()
return d.path
}
// Sys returns underlying data source (can be nil) - satisfies Node interface
func (d *Dir) Sys() any {
return d.sys.Load()
}
// SetSys sets the underlying data source (can be nil) - satisfies Node interface
func (d *Dir) SetSys(x any) {
d.sys.Store(x)
}
// Inode returns the inode number - satisfies Node interface
func (d *Dir) Inode() uint64 {
return d.inode
}
// Node returns the Node associated with this - satisfies Noder interface
func (d *Dir) Node() Node {
return d
}
// hasVirtual returns whether the directory or children has virtual entries
func (d *Dir) hasVirtual() bool {
return d._virtuals.Load() != 0
}
// addVirtual adds n virtual items to this directory and all of its parents
func (d *Dir) addVirtual(n int32) {
for d != nil {
d._virtuals.Add(n)
d = d.parent
}
}
// ForgetAll forgets directory entries for this directory and any children.
//
// It does not invalidate or clear the cache of the parent directory.
//
// It returns true if the directory or any of its children had virtual
// entries so could not be forgotten. Children which didn't have
// virtual entries will be forgotten even if true is returned.
func (d *Dir) ForgetAll() (hasVirtual bool) {
// We run this part with RLock only to avoid deadlocks in the recursion
d.mu.RLock()
fs.Debugf(d.path, "forgetting directory cache")
for _, node := range d.items {
if dir, ok := node.(*Dir); ok {
dir.ForgetAll()
}
}
d.mu.RUnlock()
// We run this part with Lock so we can modify the Dir
d.mu.Lock()
defer d.mu.Unlock()
// Purge any unnecessary virtual entries
d._purgeVirtual()
// Don't clear directory entries if there are virtual entries in this
// directory or any children
hasVirtual = d.hasVirtual()
if !hasVirtual {
d.read = time.Time{}
d.items = make(map[string]Node)
d.cleanupTimer.Stop()
} else {
d.cleanupTimer.Reset(time.Duration(d.vfs.Opt.DirCacheTime * 2))
}
return hasVirtual
}
// forgetDirPath clears the cache for itself and all subdirectories if
// they match the given path. The path is specified relative from the
// directory it is called from.
//
// It does not invalidate or clear the cache of the parent directory.
func (d *Dir) forgetDirPath(relativePath string) {
dir := d.cachedDir(relativePath)
if dir == nil {
return
}
dir.ForgetAll()
}
// invalidateDir invalidates the directory cache for absPath relative to the root
func (d *Dir) invalidateDir(absPath string) {
node := d.vfs.root.cachedNode(absPath)
if dir, ok := node.(*Dir); ok {
dir.mu.Lock()
if !dir.read.IsZero() {
fs.Debugf(dir.path, "invalidating directory cache")
dir.read = time.Time{}
}
dir.mu.Unlock()
}
}
// changeNotify invalidates the directory cache for the relativePath
// passed in.
//
// if entryType is a directory it invalidates the parent of the directory too.
func (d *Dir) changeNotify(relativePath string, entryType fs.EntryType) {
defer log.Trace(d.path, "relativePath=%q, type=%v", relativePath, entryType)("")
d.mu.RLock()
absPath := path.Join(d.path, relativePath)
d.mu.RUnlock()
d.invalidateDir(vfscommon.FindParent(absPath))
if entryType == fs.EntryDirectory {
d.invalidateDir(absPath)
}
}
// ForgetPath clears the cache for itself and all subdirectories if
// they match the given path. The path is specified relative from the
// directory it is called from. The cache of the parent directory is
// marked as stale, but not cleared otherwise.
// It is not possible to traverse the directory tree upwards, i.e.
// you cannot clear the cache for the Dir's ancestors or siblings.
func (d *Dir) ForgetPath(relativePath string, entryType fs.EntryType) {
defer log.Trace(d.path, "relativePath=%q, type=%v", relativePath, entryType)("")
d.mu.RLock()
absPath := path.Join(d.path, relativePath)
d.mu.RUnlock()
if absPath != "" {
d.invalidateDir(vfscommon.FindParent(absPath))
}
if entryType == fs.EntryDirectory {
d.forgetDirPath(relativePath)
}
}
// walk runs a function on all cached directories. It will be called
// on a directory's children first.
//
// The mutex will be held for the directory when fun is called
func (d *Dir) walk(fun func(*Dir)) {
d.mu.Lock()
defer d.mu.Unlock()
for _, node := range d.items {
if dir, ok := node.(*Dir); ok {
dir.walk(fun)
}
}
fun(d)
}
// countActiveWriters returns the number of writers active in this
// directory and any subdirectories.
func (d *Dir) countActiveWriters() (writers int) {
d.walk(func(d *Dir) {
// NB d.mu is held by walk() here
fs.Debugf(d.path, "Looking for writers")
for leaf, item := range d.items {
fs.Debugf(leaf, "reading active writers")
if file, ok := item.(*File); ok {
n := file.activeWriters()
if n != 0 {
fs.Debugf(file, "active writers %d", n)
}
writers += n
}
}
})
return writers
}
// age returns the duration since the last time the directory contents
// was read and the content is considered stale. age will be 0 and
// stale true if the last read time is empty.
// age must be called with d.mu held.
func (d *Dir) _age(when time.Time) (age time.Duration, stale bool) {
if d.read.IsZero() {
return age, true
}
age = when.Sub(d.read)
stale = age > time.Duration(d.vfs.Opt.DirCacheTime)
return
}
// renameTree renames the directories under this directory
//
// path should be the desired path
func (d *Dir) renameTree(dirPath string) {
d.mu.Lock()
defer d.mu.Unlock()
// Make sure the path is correct for each node
if d.path != dirPath {
fs.Debugf(d.path, "Renaming to %q", dirPath)
delete(d.parent.items, name(d.path))
d.path = dirPath
d.parent.items[name(d.path)] = d
d.entry = fs.NewDirCopy(context.TODO(), d.entry).SetRemote(dirPath)
}
// Do the same to any child directories and files
for leaf, node := range d.items {
switch x := node.(type) {
case *Dir:
x.renameTree(path.Join(dirPath, leaf))
case *File:
x.renameDir(dirPath)
default:
panic("bad dir entry")
}
}
}
// rename should be called after the directory is renamed
//
// Reset the directory to new state, discarding all the objects and
// reading everything again
func (d *Dir) rename(newParent *Dir, fsDir fs.Directory) {
d.ForgetAll()
d.modTimeMu.Lock()
d.modTime = fsDir.ModTime(context.TODO())
d.modTimeMu.Unlock()
d.mu.Lock()
oldPath := d.path
d.parent = newParent
d.entry = fsDir
d.path = fsDir.Remote()
newPath := d.path
delete(d.parent.items, name(oldPath))
d.parent.items[name(d.path)] = d
d.read = time.Time{}
d.mu.Unlock()
// Rename any remaining items in the tree that we couldn't forget
d.renameTree(d.path)
// Rename in the cache
if d.vfs.cache != nil && d.vfs.cache.DirExists(oldPath) {
if err := d.vfs.cache.DirRename(oldPath, newPath); err != nil {
fs.Infof(d, "Dir.Rename failed in Cache: %v", err)
}
}
}
// convert path to name
func name(p string) string {
p = path.Base(p)
if p == "." {
p = "/"
}
return p
}
// addObject adds a new object or directory to the directory
//
// The name passed in is marked as virtual as it hasn't been read from a remote
// directory listing.
//
// note that we add new objects rather than updating old ones
func (d *Dir) addObject(node Node) {
d.mu.Lock()
leaf := node.Name()
d.items[leaf] = node
if d.virtual == nil {
d.virtual = make(map[string]vState)
}
vAdd := vAddFile
if node.IsDir() {
vAdd = vAddDir
}
if _, found := d.virtual[leaf]; !found {
d.addVirtual(1)
}
d.virtual[leaf] = vAdd
fs.Debugf(d.path, "Added virtual directory entry %v: %q", vAdd, leaf)
d.mu.Unlock()
}
// AddVirtual adds a virtual object of name and size to the directory
//
// This will be replaced with a real object when it is read back from the
// remote.
//
// This is used by the vfs cache to insert objects that are uploading
// into the directory tree.
func (d *Dir) AddVirtual(leaf string, size int64, isDir bool) {
var node Node
d.mu.RLock()
dPath := d.path
_, found := d.items[leaf]
d.mu.RUnlock()
if found {
// Don't overwrite existing objects
return
}
if isDir {
remote := path.Join(dPath, leaf)
entry := fs.NewDir(remote, time.Now())
node = newDir(d.vfs, d.f, d, entry)
} else {
isLink := false
if d.vfs.Opt.Links {
// since the path came from the cache it may have fs.LinkSuffix,
// so remove it and mark the *File accordingly
leaf, isLink = strings.CutSuffix(leaf, fs.LinkSuffix)
}
f := newFile(d, dPath, nil, leaf)
if isLink {
f.setSymlink()
}
f.setSize(size)
node = f
}
d.addObject(node)
}
// delObject removes an object from the directory
//
// The name passed in is marked as virtual as the delete it hasn't been read
// from a remote directory listing.
func (d *Dir) delObject(leaf string) {
d.mu.Lock()
delete(d.items, leaf)
if d.virtual == nil {
d.virtual = make(map[string]vState)
}
if _, found := d.virtual[leaf]; !found {
d.addVirtual(1)
}
d.virtual[leaf] = vDel
fs.Debugf(d.path, "Added virtual directory entry %v: %q", vDel, leaf)
d.mu.Unlock()
}
// DelVirtual removes an object from the directory listing
//
// It marks it as removed until it has confirmed the object is missing when the
// directory entries are re-read in.
//
// This is used to remove directory entries after things have been deleted or
// renamed but before we've had confirmation from the backend.
func (d *Dir) DelVirtual(leaf string) {
d.delObject(leaf)
}
// read the directory and sets d.items - must be called with the lock held
func (d *Dir) _readDir() error {
when := time.Now()
if age, stale := d._age(when); stale {
if age != 0 {
fs.Debugf(d.path, "Re-reading directory (%v old)", age)
}
} else {
return nil
}
entries, err := list.DirSorted(context.TODO(), d.f, false, d.path)
if err == fs.ErrorDirNotFound {
// We treat directory not found as empty because we
// create directories on the fly
} else if err != nil {
return err
}
if d.vfs.Opt.BlockNormDupes { // do this only if requested, as it will have a performance hit
ci := fs.GetConfig(context.TODO())
// sort entries such that NFD comes before NFC of same name
sort.Slice(entries, func(i, j int) bool {
if entries[i] != entries[j] && fs.DirEntryType(entries[i]) == fs.DirEntryType(entries[j]) && norm.NFC.String(entries[i].Remote()) == norm.NFC.String(entries[j].Remote()) {
if norm.NFD.IsNormalString(entries[i].Remote()) && !norm.NFD.IsNormalString(entries[j].Remote()) {
return true
}
}
return entries.Less(i, j)
})
// detect dupes, remove them from the list and log an error
normalizedNames := make(map[string]struct{}, entries.Len())
filteredEntries := make(fs.DirEntries, 0)
for _, e := range entries {
normName := fmt.Sprintf("%s-%T", operations.ToNormal(e.Remote(), !ci.NoUnicodeNormalization, (ci.IgnoreCaseSync || d.vfs.Opt.CaseInsensitive)), e) // include type to track objects and dirs separately
_, found := normalizedNames[normName]
if found {
fs.Errorf(e.Remote(), "duplicate normalized names detected - skipping")
continue
}
normalizedNames[normName] = struct{}{}
filteredEntries = append(filteredEntries, e)
}
entries = filteredEntries
}
err = d._readDirFromEntries(entries, nil, time.Time{})
if err != nil {
return err
}
d.read = time.Now()
d.cleanupTimer.Reset(time.Duration(d.vfs.Opt.DirCacheTime * 2))
return nil
}
// update d.items for each dir in the DirTree below this one and
// set the last read time - must be called with the lock held
func (d *Dir) _readDirFromDirTree(dirTree dirtree.DirTree, when time.Time) error {
return d._readDirFromEntries(dirTree[d.path], dirTree, when)
}
// Remove the virtual directory entry leaf
func (d *Dir) _deleteVirtual(name string) {
virtualState, ok := d.virtual[name]
if !ok {
return
}
delete(d.virtual, name)
d.addVirtual(-1)
if len(d.virtual) == 0 {
d.virtual = nil
}
fs.Debugf(d.path, "Removed virtual directory entry %v: %q", virtualState, name)
}
// Purge virtual entries assuming the directory has just been re-read
//
// Remove all the entries except:
//
// 1) vDirAdd on remotes which can't have empty directories. These will remain
// virtual as long as the directory is empty. When the directory becomes real
// (ie files are added) the virtual directory will be removed. This means that
// directories will disappear when the last file is deleted which is probably
// OK.
//
// 2) vFileAdd that are being written or uploaded
func (d *Dir) _purgeVirtual() {
canHaveEmptyDirectories := d.f.Features().CanHaveEmptyDirectories
for name, virtualState := range d.virtual {
switch virtualState {
case vAddDir:
if canHaveEmptyDirectories {
// if remote can have empty directories then a
// new dir will be read in the listing
d._deleteVirtual(name)
//} else {
// leave the empty directory marker
}
case vAddFile:
// Delete all virtual file adds that have finished uploading
node, ok := d.items[name]
if !ok {
// if the object has disappeared somehow then remove the virtual
d._deleteVirtual(name)
continue
}
f, ok := node.(*File)
if !ok {
// if the object isn't a file then remove the virtual as it is wrong
d._deleteVirtual(name)
continue
}
if f.writingInProgress() {
// if writing in progress then leave virtual
continue
}
if d.vfs.Opt.CacheMode >= vfscommon.CacheModeMinimal && d.vfs.cache.InUse(f.CachePath()) {
// if object in use or dirty then leave virtual
continue
}
d._deleteVirtual(name)
default:
d._deleteVirtual(name)
}
}
}
// Manage the virtuals in a listing
//
// This keeps a record of the names listed in this directory so far
type manageVirtuals map[string]struct{}
// Create a new manageVirtuals and purge the d.virtuals of any entries which can
// be removed.
//
// must be called with the Dir lock held
func (d *Dir) _newManageVirtuals() manageVirtuals {
tv := make(manageVirtuals)
d._purgeVirtual()
return tv
}
// This should be called for every entry added to the directory
//
// It returns true if this entry should be skipped.
//
// must be called with the Dir lock held
func (mv manageVirtuals) add(d *Dir, name string) bool {
// Keep a record of all names listed
mv[name] = struct{}{}
// Remove virtuals if possible
switch d.virtual[name] {
case vAddFile, vAddDir:
// item was added to the dir but since it is found in a
// listing is no longer virtual
d._deleteVirtual(name)
case vDel:
// item is deleted from the dir so skip it
return true
case vOK:
}
return false
}
// This should be called after the directory entry is read to update d.items
// with virtual entries
//
// must be called with the Dir lock held
func (mv manageVirtuals) end(d *Dir) {
// delete unused d.items
for name := range d.items {
if _, ok := mv[name]; !ok {
// name was previously in the directory but wasn't found
// in the current listing
switch d.virtual[name] {
case vAddFile, vAddDir:
// virtually added so leave virtual item
default:
// otherwise delete it
delete(d.items, name)
}
}
}
// delete unused d.virtual~s
for name, virtualState := range d.virtual {
if _, ok := mv[name]; !ok {
// name exists as a virtual but isn't in the current
// listing so if it is a virtual delete we can remove it
// as it is no longer needed.
if virtualState == vDel {
d._deleteVirtual(name)
}
}
}
}
// update d.items and if dirTree is not nil update each dir in the DirTree below this one and
// set the last read time - must be called with the lock held
func (d *Dir) _readDirFromEntries(entries fs.DirEntries, dirTree dirtree.DirTree, when time.Time) error {
var err error
mv := d._newManageVirtuals()
for _, entry := range entries {
name := path.Base(entry.Remote())
if name == "." || name == ".." {
continue
}
if d.vfs.Opt.Links {
name, _ = strings.CutSuffix(name, fs.LinkSuffix)
}
node := d.items[name]
if mv.add(d, name) {
continue
}
switch item := entry.(type) {
case fs.Object:
obj := item
// Reuse old file value if it exists
if file, ok := node.(*File); node != nil && ok {
file.setObjectNoUpdate(obj)
} else {
node = newFile(d, d.path, obj, name)
}
case fs.Directory:
// Reuse old dir value if it exists
if node == nil || !node.IsDir() {
node = newDir(d.vfs, d.f, d, item)
}
dir := node.(*Dir)
dir.mu.Lock()
dir.modTime = item.ModTime(context.TODO())
dir.entry = item
if dirTree != nil {
err = dir._readDirFromDirTree(dirTree, when)
if err != nil {
dir.read = time.Time{}
} else {
dir.read = when
dir.cleanupTimer.Reset(time.Duration(d.vfs.Opt.DirCacheTime * 2))
}
}
dir.mu.Unlock()
if err != nil {
return err
}
default:
err = fmt.Errorf("unknown type %T", item)
fs.Errorf(d, "readDir error: %v", err)
return err
}
d.items[name] = node
}
mv.end(d)
return nil
}
// readDirTree forces a refresh of the complete directory tree
func (d *Dir) readDirTree() error {
d.mu.RLock()
f, path := d.f, d.path
d.mu.RUnlock()
when := time.Now()
fs.Debugf(path, "Reading directory tree")
dt, err := walk.NewDirTree(context.TODO(), f, path, false, -1)
if err != nil {
return err
}
d.mu.Lock()
defer d.mu.Unlock()
d.read = time.Time{}
err = d._readDirFromDirTree(dt, when)
if err != nil {
return err
}
fs.Debugf(d.path, "Reading directory tree done in %s", time.Since(when))
d.read = when
d.cleanupTimer.Reset(time.Duration(d.vfs.Opt.DirCacheTime * 2))
return nil
}
// readDir forces a refresh of the directory
func (d *Dir) readDir() error {
d.mu.Lock()
defer d.mu.Unlock()
d.read = time.Time{}
return d._readDir()
}
// jsonErrorf formats the string according to a format specifier and
// returns the resulting string as a JSON blob with key "error"
func jsonErrorf(format string, a ...any) []byte {
errMsg := fmt.Sprintf(format, a...)
jsonBlob, _ := json.MarshalIndent(map[string]string{"error": errMsg}, "", "\t")
return jsonBlob
}
// stat a single metadata item in the directory
//
// Returns true if it is a metadata name
func (d *Dir) statMetadata(leaf, baseLeaf string) (metaNode Node, err error) {
// Find original file - note that this is recursing into stat()
node, err := d.stat(baseLeaf)
if err != nil {
return node, err
}
// Read the metadata from the original entry into a JSON dump
entry := node.DirEntry()
var metadataDump []byte
if entry != nil {
metadata, err := fs.GetMetadata(context.TODO(), entry)
if err != nil {
metadataDump = jsonErrorf("failed to read metadata: %v", err)
} else if metadata == nil {
metadataDump = []byte("{}") // no metadata to read
} else {
metadataDump, err = json.MarshalIndent(metadata, "", "\t")
if err != nil {
metadataDump = jsonErrorf("failed to write metadata: %v", err)
}
}
} else {
metadataDump = []byte("{}") // no metadata yet when an object is being written
}
// Make a memory based file with metadataDump in
remote := path.Join(d.path, leaf)
o := object.NewMemoryObject(remote, entry.ModTime(context.TODO()), metadataDump)
f := newFile(d, d.path, o, leaf)
// Base the metadata inode number off the real file inode number
// to keep it constant
f.inode = node.Inode() ^ (1 << 63)
return f, nil
}
// stat a single item in the directory
//
// returns ENOENT if not found.
// returns a custom error if directory on a case-insensitive file system
// contains files with names that differ only by case.
func (d *Dir) stat(leaf string) (Node, error) {
d.mu.Lock()
err := d._readDir()
if err != nil {
d.mu.Unlock()
return nil, err
}
item, ok := d.items[leaf]
d.mu.Unlock()
// Look for a metadata file
if !ok {
if baseLeaf, found := d.vfs.isMetadataFile(leaf); found {
node, err := d.statMetadata(leaf, baseLeaf)
if err != nil {
return nil, err
}
// Add metadata file to directory as virtual object
d.addObject(node)
return node, nil
}
}
ci := fs.GetConfig(context.TODO())
normUnicode := !ci.NoUnicodeNormalization
normCase := ci.IgnoreCaseSync || d.vfs.Opt.CaseInsensitive
if !ok && (normUnicode || normCase) {
leafNormalized := operations.ToNormal(leaf, normUnicode, normCase) // this handles both case and unicode normalization
d.mu.Lock()
for name, node := range d.items {
if operations.ToNormal(name, normUnicode, normCase) == leafNormalized {
if ok {
// duplicate normalized match is an error
d.mu.Unlock()
return nil, fmt.Errorf("duplicate filename %q detected with case/unicode normalization settings", leaf)
}
// found a normalized match
ok = true
item = node
}
}
d.mu.Unlock()
}
if !ok {
return nil, ENOENT
}
return item, nil
}
// Check to see if a directory is empty
func (d *Dir) isEmpty() (bool, error) {
d.mu.Lock()
defer d.mu.Unlock()
err := d._readDir()
if err != nil {
return false, err
}
return len(d.items) == 0, nil
}
// ModTime returns the modification time of the directory
func (d *Dir) ModTime() time.Time {
d.modTimeMu.Lock()
defer d.modTimeMu.Unlock()
// fs.Debugf(d.path, "Dir.ModTime %v", d.modTime)
return d.modTime
}
// Size of the directory
func (d *Dir) Size() int64 {
return 0
}
// SetModTime sets the modTime for this dir
func (d *Dir) SetModTime(modTime time.Time) error {
if d.vfs.Opt.ReadOnly {
return EROFS
}
d.modTimeMu.Lock()
d.modTime = modTime
d.modTimeMu.Unlock()
return nil
}
func (d *Dir) cachedDir(relativePath string) (dir *Dir) {
dir, _ = d.cachedNode(relativePath).(*Dir)
return
}
func (d *Dir) cachedNode(relativePath string) Node {
segments := strings.Split(strings.Trim(relativePath, "/"), "/")
var node Node = d
for _, s := range segments {
if s == "" {
continue
}
if dir, ok := node.(*Dir); ok {
dir.mu.Lock()
node = dir.items[s]
dir.mu.Unlock()
if node != nil {
continue
}
}
return nil
}
return node
}
// Stat looks up a specific entry in the receiver.
//
// Stat should return a Node corresponding to the entry. If the
// name does not exist in the directory, Stat should return ENOENT.
//
// Stat need not to handle the names "." and "..".
func (d *Dir) Stat(name string) (node Node, err error) {
// fs.Debugf(path, "Dir.Stat")
node, err = d.stat(name)
if err != nil {
if err != ENOENT {
fs.Errorf(d, "Dir.Stat error: %v", err)
}
return nil, err
}
// fs.Debugf(path, "Dir.Stat OK")
return node, nil
}
// ReadDirAll reads the contents of the directory sorted
func (d *Dir) ReadDirAll() (items Nodes, err error) {
// fs.Debugf(d.path, "Dir.ReadDirAll")
d.mu.Lock()
err = d._readDir()
if err != nil {
fs.Debugf(d.path, "Dir.ReadDirAll error: %v", err)
d.mu.Unlock()
return nil, err
}
for _, item := range d.items {
items = append(items, item)
}
d.mu.Unlock()
sort.Sort(items)
// fs.Debugf(d.path, "Dir.ReadDirAll OK with %d entries", len(items))
return items, nil
}
// accessModeMask masks off the read modes from the flags
const accessModeMask = (os.O_RDONLY | os.O_WRONLY | os.O_RDWR)
// Open the directory according to the flags provided
func (d *Dir) Open(flags int) (fd Handle, err error) {
rdwrMode := flags & accessModeMask
if rdwrMode != os.O_RDONLY {
fs.Errorf(d, "Can only open directories read only")
return nil, EPERM
}
return newDirHandle(d), nil
}
// Create makes a new file node
func (d *Dir) Create(name string, flags int) (*File, error) {
// fs.Debugf(path, "Dir.Create")
// Return existing node if one exists
node, err := d.stat(name)
switch err {
case ENOENT:
// not found, carry on
case nil:
// found so check what it is
if node.IsFile() {
return node.(*File), err
}
return nil, EEXIST // EISDIR would be better but we don't have that
default:
// a different error - report
fs.Errorf(d, "Dir.Create stat failed: %v", err)
return nil, err
}
// node doesn't exist so create it
if d.vfs.Opt.ReadOnly {
return nil, EROFS
}
if err = d.SetModTime(time.Now()); err != nil {
fs.Errorf(d, "Dir.Create failed to set modtime on parent dir: %v", err)
return nil, err
}
// This gets added to the directory when the file is opened for write
return newFile(d, d.Path(), nil, name), nil
}
// Mkdir creates a new directory
func (d *Dir) Mkdir(name string) (*Dir, error) {
if d.vfs.Opt.ReadOnly {
return nil, EROFS
}
path := path.Join(d.path, name)
node, err := d.stat(name)
switch err {
case ENOENT:
// not found, carry on
case nil:
// found so check what it is
if node.IsDir() {
return node.(*Dir), err
}
return nil, EEXIST
default:
// a different error - report
fs.Errorf(d, "Dir.Mkdir failed to read directory: %v", err)
return nil, err
}
// fs.Debugf(path, "Dir.Mkdir")
err = d.f.Mkdir(context.TODO(), path)
if err != nil {
fs.Errorf(d, "Dir.Mkdir failed to create directory: %v", err)
return nil, err
}
fsDir := fs.NewDir(path, time.Now())
dir := newDir(d.vfs, d.f, d, fsDir)
d.addObject(dir)
if err = d.SetModTime(time.Now()); err != nil {
fs.Errorf(d, "Dir.Mkdir failed to set modtime on parent dir: %v", err)
return nil, err
}
// fs.Debugf(path, "Dir.Mkdir OK")
return dir, nil
}
// Remove the directory
func (d *Dir) Remove() error {
if d.vfs.Opt.ReadOnly {
return EROFS
}
// Check directory is empty first
empty, err := d.isEmpty()
if err != nil {
fs.Errorf(d, "Dir.Remove dir error: %v", err)
return err
}
if !empty {
fs.Errorf(d, "Dir.Remove not empty")
return ENOTEMPTY
}
// remove directory
err = d.f.Rmdir(context.TODO(), d.path)
if err != nil {
fs.Errorf(d, "Dir.Remove failed to remove directory: %v", err)
return err
}
// Remove the item from the parent directory listing
if d.parent != nil {
d.parent.delObject(d.Name())
}
return nil
}
// RemoveAll removes the directory and any contents recursively
func (d *Dir) RemoveAll() error {
if d.vfs.Opt.ReadOnly {
return EROFS
}
// Remove contents of the directory
nodes, err := d.ReadDirAll()
if err != nil {
fs.Errorf(d, "Dir.RemoveAll failed to read directory: %v", err)
return err
}
for _, node := range nodes {
err = node.RemoveAll()
if err != nil {
fs.Errorf(node.Path(), "Dir.RemoveAll failed to remove: %v", err)
return err
}
}
return d.Remove()
}
// DirEntry returns the underlying fs.DirEntry
func (d *Dir) DirEntry() (entry fs.DirEntry) {
return d.entry
}
// RemoveName removes the entry with the given name from the receiver,
// which must be a directory. The entry to be removed may correspond
// to a file (unlink) or to a directory (rmdir).
func (d *Dir) RemoveName(name string) error {
if d.vfs.Opt.ReadOnly {
return EROFS
}
// fs.Debugf(path, "Dir.Remove")
node, err := d.stat(name)
if err != nil {
fs.Errorf(d, "Dir.Remove error: %v", err)
return err
}
if err = d.SetModTime(time.Now()); err != nil {
fs.Errorf(d, "Dir.Remove failed to set modtime on parent dir: %v", err)
return err
}
return node.Remove()
}
// Rename the file
func (d *Dir) Rename(oldName, newName string, destDir *Dir) error {
// fs.Debugf(d, "BEFORE\n%s", d.dump())
if d.vfs.Opt.ReadOnly {
return EROFS
}
oldPath := path.Join(d.path, oldName)
newPath := path.Join(destDir.path, newName)
// fs.Debugf(oldPath, "Dir.Rename to %q", newPath)
oldNode, err := d.stat(oldName)
if err != nil {
fs.Errorf(oldPath, "Dir.Rename error: %v", err)
return err
}
switch x := oldNode.DirEntry().(type) {
case nil:
if oldFile, ok := oldNode.(*File); ok {
if err = oldFile.rename(context.TODO(), destDir, newName); err != nil {
fs.Errorf(oldPath, "Dir.Rename error: %v", err)
return err
}
} else {
fs.Errorf(oldPath, "Dir.Rename can't rename open file that is not a vfs.File")
return EPERM
}
case fs.Object:
if oldFile, ok := oldNode.(*File); ok {
if err = oldFile.rename(context.TODO(), destDir, newName); err != nil {
fs.Errorf(oldPath, "Dir.Rename error: %v", err)
return err
}
} else {
err := fmt.Errorf("Fs %q can't rename file that is not a vfs.File", d.f)
fs.Errorf(oldPath, "Dir.Rename error: %v", err)
return err
}
case fs.Directory:
features := d.f.Features()
if features.DirMove == nil && features.Move == nil && features.Copy == nil {
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | true |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfsflags/vfsflags.go | vfs/vfsflags/vfsflags.go | // Package vfsflags implements command line flags to set up a vfs
package vfsflags
import (
"github.com/rclone/rclone/fs/config/flags"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/spf13/pflag"
)
// AddFlags adds the non filing system specific flags to the command
func AddFlags(flagSet *pflag.FlagSet) {
flags.AddFlagsFromOptions(flagSet, "", vfscommon.OptionsInfo)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/test_vfs/test_vfs.go | vfs/test_vfs/test_vfs.go | // Test the VFS to exhaustion, specifically looking for deadlocks
//
// Run on a mounted filesystem
package main
import (
"flag"
"fmt"
"io"
"math"
"math/rand"
"os"
"path"
"sync"
"sync/atomic"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/lib/file"
"github.com/rclone/rclone/lib/random"
)
var (
nameLength = flag.Int("name-length", 10, "Length of names to create")
verbose = flag.Bool("v", false, "Set to show more info")
number = flag.Int("n", 4, "Number of tests to run simultaneously")
iterations = flag.Int("i", 100, "Iterations of the test")
timeout = flag.Duration("timeout", 10*time.Second, "Inactivity time to detect a deadlock")
testNumber atomic.Int32
)
// Test contains stats about the running test which work for files or
// directories
type Test struct {
dir string
name string
created bool
handle *os.File
tests []func()
isDir bool
number int32
prefix string
timer *time.Timer
}
// NewTest creates a new test and fills in the Tests
func NewTest(Dir string) *Test {
t := &Test{
dir: Dir,
name: random.String(*nameLength),
isDir: rand.Intn(2) == 0,
number: testNumber.Add(1),
timer: time.NewTimer(*timeout),
}
width := int(math.Floor(math.Log10(float64(*number)))) + 1
t.prefix = fmt.Sprintf("%*d: %s: ", width, t.number, t.path())
if t.isDir {
t.tests = []func(){
t.list,
t.rename,
t.mkdir,
t.rmdir,
}
} else {
t.tests = []func(){
t.list,
t.rename,
t.open,
t.close,
t.remove,
t.read,
t.write,
}
}
return t
}
// kick the deadlock timeout
func (t *Test) kick() {
if !t.timer.Stop() {
<-t.timer.C
}
t.timer.Reset(*timeout)
}
// randomTest runs a random test
func (t *Test) randomTest() {
t.kick()
i := rand.Intn(len(t.tests))
t.tests[i]()
}
// logf logs things - not shown unless -v
func (t *Test) logf(format string, a ...any) {
if *verbose {
fs.Logf(nil, t.prefix+format, a)
}
}
// errorf logs errors
func (t *Test) errorf(format string, a ...any) {
fs.Logf(nil, t.prefix+"ERROR: "+format, a)
}
// list test
func (t *Test) list() {
t.logf("list")
fis, err := os.ReadDir(t.dir)
if err != nil {
t.errorf("%s: failed to read directory: %v", t.dir, err)
return
}
if t.created && len(fis) == 0 {
t.errorf("%s: expecting entries in directory, got none", t.dir)
return
}
found := false
for _, fi := range fis {
if fi.Name() == t.name {
found = true
}
}
if t.created {
if !found {
t.errorf("%s: expecting to find %q in directory, got none", t.dir, t.name)
return
}
} else {
if found {
t.errorf("%s: not expecting to find %q in directory, got none", t.dir, t.name)
return
}
}
}
// path returns the current path to the item
func (t *Test) path() string {
return path.Join(t.dir, t.name)
}
// rename test
func (t *Test) rename() {
if !t.created {
return
}
t.logf("rename")
NewName := random.String(*nameLength)
newPath := path.Join(t.dir, NewName)
err := os.Rename(t.path(), newPath)
if err != nil {
t.errorf("failed to rename to %q: %v", newPath, err)
return
}
t.name = NewName
}
// close test
func (t *Test) close() {
if t.handle == nil {
return
}
t.logf("close")
err := t.handle.Close()
t.handle = nil
if err != nil {
t.errorf("failed to close: %v", err)
return
}
}
// open test
func (t *Test) open() {
t.close()
t.logf("open")
handle, err := file.OpenFile(t.path(), os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
t.errorf("failed to open: %v", err)
return
}
t.handle = handle
t.created = true
}
// read test
func (t *Test) read() {
if t.handle == nil {
return
}
t.logf("read")
bytes := make([]byte, 10)
_, err := t.handle.Read(bytes)
if err != nil && err != io.EOF {
t.errorf("failed to read: %v", err)
return
}
}
// write test
func (t *Test) write() {
if t.handle == nil {
return
}
t.logf("write")
bytes := make([]byte, 10)
_, err := t.handle.Write(bytes)
if err != nil {
t.errorf("failed to write: %v", err)
return
}
}
// remove test
func (t *Test) remove() {
if !t.created {
return
}
t.logf("remove")
err := os.Remove(t.path())
if err != nil {
t.errorf("failed to remove: %v", err)
return
}
t.created = false
}
// mkdir test
func (t *Test) mkdir() {
if t.created {
return
}
t.logf("mkdir")
err := os.Mkdir(t.path(), 0777)
if err != nil {
t.errorf("failed to mkdir %q", t.path())
return
}
t.created = true
}
// rmdir test
func (t *Test) rmdir() {
if !t.created {
return
}
t.logf("rmdir")
err := os.Remove(t.path())
if err != nil {
t.errorf("failed to rmdir %q", t.path())
return
}
t.created = false
}
// Tidy removes any stray files and stops the deadlock timer
func (t *Test) Tidy() {
t.timer.Stop()
if !t.isDir {
t.close()
t.remove()
} else {
t.rmdir()
}
t.logf("finished")
}
// RandomTests runs random tests with deadlock detection
func (t *Test) RandomTests(iterations int, quit chan struct{}) {
var finished = make(chan struct{})
go func() {
for range iterations {
t.randomTest()
}
close(finished)
}()
select {
case <-finished:
case <-quit:
quit <- struct{}{}
case <-t.timer.C:
t.errorf("deadlock detected")
quit <- struct{}{}
}
}
func main() {
flag.Parse()
args := flag.Args()
if len(args) != 1 {
fs.Fatalf(nil, "%s: Syntax [opts] <directory>", os.Args[0])
}
dir := args[0]
_ = file.MkdirAll(dir, 0777)
var (
wg sync.WaitGroup
quit = make(chan struct{}, *iterations)
)
for range *number {
wg.Add(1)
go func() {
defer wg.Done()
t := NewTest(dir)
defer t.Tidy()
t.RandomTests(*iterations, quit)
}()
}
wg.Wait()
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscache/item_test.go | vfs/vfscache/item_test.go | package vfscache
// FIXME need to test async writeback here
import (
"context"
"fmt"
"io"
"math/rand"
"os"
"sync"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/random"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var zeroes = string(make([]byte, 100))
func newItemTestCache(t *testing.T) (r *fstest.Run, c *Cache) {
opt := vfscommon.Opt
// Disable the cache cleaner as it interferes with these tests
opt.CachePollInterval = 0
// Disable synchronous write
opt.WriteBack = 0
return newTestCacheOpt(t, opt)
}
// Check the object has contents
func checkObject(t *testing.T, r *fstest.Run, remote string, contents string) {
obj, err := r.Fremote.NewObject(context.Background(), remote)
require.NoError(t, err)
in, err := obj.Open(context.Background())
require.NoError(t, err)
buf, err := io.ReadAll(in)
require.NoError(t, err)
require.NoError(t, in.Close())
assert.Equal(t, contents, string(buf))
}
func newFileLength(t *testing.T, r *fstest.Run, c *Cache, remote string, length int) (contents string, obj fs.Object, item *Item) {
contents = random.String(length)
r.WriteObject(context.Background(), remote, contents, time.Now())
item, _ = c.get(remote)
obj, err := r.Fremote.NewObject(context.Background(), remote)
require.NoError(t, err)
return
}
func newFile(t *testing.T, r *fstest.Run, c *Cache, remote string) (contents string, obj fs.Object, item *Item) {
return newFileLength(t, r, c, remote, 100)
}
func TestItemExists(t *testing.T) {
_, c := newItemTestCache(t)
item, _ := c.get("potato")
assert.False(t, item.Exists())
require.NoError(t, item.Open(nil))
assert.True(t, item.Exists())
require.NoError(t, item.Close(nil))
assert.True(t, item.Exists())
item.remove("test")
assert.False(t, item.Exists())
}
func TestItemGetSize(t *testing.T) {
r, c := newItemTestCache(t)
item, _ := c.get("potato")
require.NoError(t, item.Open(nil))
size, err := item.GetSize()
require.NoError(t, err)
assert.Equal(t, int64(0), size)
n, err := item.WriteAt([]byte("hello"), 0)
require.NoError(t, err)
assert.Equal(t, 5, n)
size, err = item.GetSize()
require.NoError(t, err)
assert.Equal(t, int64(5), size)
require.NoError(t, item.Close(nil))
checkObject(t, r, "potato", "hello")
}
func TestItemDirty(t *testing.T) {
r, c := newItemTestCache(t)
item, _ := c.get("potato")
require.NoError(t, item.Open(nil))
assert.Equal(t, false, item.IsDirty())
n, err := item.WriteAt([]byte("hello"), 0)
require.NoError(t, err)
assert.Equal(t, 5, n)
assert.Equal(t, true, item.IsDirty())
require.NoError(t, item.Close(nil))
// Sync writeback so expect clean here
assert.Equal(t, false, item.IsDirty())
item.Dirty()
assert.Equal(t, true, item.IsDirty())
checkObject(t, r, "potato", "hello")
}
func TestItemSync(t *testing.T) {
_, c := newItemTestCache(t)
item, _ := c.get("potato")
require.Error(t, item.Sync())
require.NoError(t, item.Open(nil))
require.NoError(t, item.Sync())
require.NoError(t, item.Close(nil))
}
func TestItemTruncateNew(t *testing.T) {
r, c := newItemTestCache(t)
item, _ := c.get("potato")
require.Error(t, item.Truncate(0))
require.NoError(t, item.Open(nil))
require.NoError(t, item.Truncate(100))
size, err := item.GetSize()
require.NoError(t, err)
assert.Equal(t, int64(100), size)
// Check the Close callback works
callbackCalled := false
callback := func(o fs.Object) {
callbackCalled = true
assert.Equal(t, "potato", o.Remote())
assert.Equal(t, int64(100), o.Size())
}
require.NoError(t, item.Close(callback))
assert.True(t, callbackCalled)
checkObject(t, r, "potato", zeroes)
}
func TestItemTruncateExisting(t *testing.T) {
r, c := newItemTestCache(t)
contents, obj, item := newFile(t, r, c, "existing")
require.Error(t, item.Truncate(40))
checkObject(t, r, "existing", contents)
require.NoError(t, item.Open(obj))
require.NoError(t, item.Truncate(40))
require.NoError(t, item.Truncate(60))
require.NoError(t, item.Close(nil))
checkObject(t, r, "existing", contents[:40]+zeroes[:20])
}
func TestItemReadAt(t *testing.T) {
r, c := newItemTestCache(t)
contents, obj, item := newFile(t, r, c, "existing")
buf := make([]byte, 10)
_, err := item.ReadAt(buf, 10)
require.Error(t, err)
require.NoError(t, item.Open(obj))
n, err := item.ReadAt(buf, 10)
assert.Equal(t, 10, n)
require.NoError(t, err)
assert.Equal(t, contents[10:20], string(buf[:n]))
n, err = item.ReadAt(buf, 95)
assert.Equal(t, 5, n)
assert.Equal(t, io.EOF, err)
assert.Equal(t, contents[95:], string(buf[:n]))
n, err = item.ReadAt(buf, 1000)
assert.Equal(t, 0, n)
assert.Equal(t, io.EOF, err)
assert.Equal(t, contents[:0], string(buf[:n]))
n, err = item.ReadAt(buf, -1)
assert.Equal(t, 0, n)
assert.Equal(t, io.EOF, err)
assert.Equal(t, contents[:0], string(buf[:n]))
require.NoError(t, item.Close(nil))
}
func TestItemWriteAtNew(t *testing.T) {
r, c := newItemTestCache(t)
item, _ := c.get("potato")
buf := make([]byte, 10)
_, err := item.WriteAt(buf, 10)
require.Error(t, err)
require.NoError(t, item.Open(nil))
assert.Equal(t, int64(0), item.getDiskSize())
n, err := item.WriteAt([]byte("HELLO"), 10)
require.NoError(t, err)
assert.Equal(t, 5, n)
// FIXME we account for the sparse data we've "written" to
// disk here so this is actually 5 bytes higher than expected
assert.Equal(t, int64(15), item.getDiskSize())
n, err = item.WriteAt([]byte("THEND"), 20)
require.NoError(t, err)
assert.Equal(t, 5, n)
assert.Equal(t, int64(25), item.getDiskSize())
require.NoError(t, item.Close(nil))
checkObject(t, r, "potato", zeroes[:10]+"HELLO"+zeroes[:5]+"THEND")
}
func TestItemWriteAtExisting(t *testing.T) {
r, c := newItemTestCache(t)
contents, obj, item := newFile(t, r, c, "existing")
require.NoError(t, item.Open(obj))
n, err := item.WriteAt([]byte("HELLO"), 10)
require.NoError(t, err)
assert.Equal(t, 5, n)
n, err = item.WriteAt([]byte("THEND"), 95)
require.NoError(t, err)
assert.Equal(t, 5, n)
n, err = item.WriteAt([]byte("THEVERYEND"), 120)
require.NoError(t, err)
assert.Equal(t, 10, n)
require.NoError(t, item.Close(nil))
checkObject(t, r, "existing", contents[:10]+"HELLO"+contents[15:95]+"THEND"+zeroes[:20]+"THEVERYEND")
}
func TestItemLoadMeta(t *testing.T) {
r, c := newItemTestCache(t)
contents, obj, item := newFile(t, r, c, "existing")
_ = contents
// Open the object to create metadata for it
require.NoError(t, item.Open(obj))
require.NoError(t, item.Close(nil))
info := item.info
// Remove the item from the cache
c.mu.Lock()
delete(c.item, item.name)
c.mu.Unlock()
// Reload the item so we have to load the metadata
item2, _ := c._get("existing")
require.NoError(t, item2.Open(obj))
info2 := item.info
require.NoError(t, item2.Close(nil))
// Check that the item is different
assert.NotEqual(t, item, item2)
// ... but the info is the same
assert.Equal(t, info, info2)
}
func TestItemReload(t *testing.T) {
r, c := newItemTestCache(t)
contents, obj, item := newFile(t, r, c, "existing")
_ = contents
// Open the object to create metadata for it
require.NoError(t, item.Open(obj))
// Make it dirty
n, err := item.WriteAt([]byte("THEENDMYFRIEND"), 95)
require.NoError(t, err)
assert.Equal(t, 14, n)
assert.True(t, item.IsDirty())
// Close the file to pacify Windows, but don't call item.Close()
item.mu.Lock()
require.NoError(t, item.fd.Close())
item.fd = nil
item.mu.Unlock()
// Remove the item from the cache
c.mu.Lock()
delete(c.item, item.name)
c.mu.Unlock()
// Reload the item so we have to load the metadata and restart
// the transfer
item2, _ := c._get("existing")
require.NoError(t, item2.reload(context.Background()))
assert.False(t, item2.IsDirty())
// Check that the item is different
assert.NotEqual(t, item, item2)
// And check the contents got written back to the remote
checkObject(t, r, "existing", contents[:95]+"THEENDMYFRIEND")
// And check that AddVirtual was called
assert.Equal(t, []avInfo{
{Remote: "existing", Size: 109, IsDir: false},
}, avInfos)
}
func TestItemReloadRemoteGone(t *testing.T) {
r, c := newItemTestCache(t)
contents, obj, item := newFile(t, r, c, "existing")
_ = contents
// Open the object to create metadata for it
require.NoError(t, item.Open(obj))
size, err := item.GetSize()
require.NoError(t, err)
assert.Equal(t, int64(100), size)
// Read something to instantiate the cache file
buf := make([]byte, 10)
_, err = item.ReadAt(buf, 10)
require.NoError(t, err)
// Test cache file present
_, err = os.Stat(item.c.toOSPath(item.name))
require.NoError(t, err)
require.NoError(t, item.Close(nil))
// Remove the remote object
require.NoError(t, obj.Remove(context.Background()))
// Re-open with no object
require.NoError(t, item.Open(nil))
// Check size is now 0
size, err = item.GetSize()
require.NoError(t, err)
assert.Equal(t, int64(0), size)
// Test cache file is now empty
fi, err := os.Stat(item.c.toOSPath(item.name))
require.NoError(t, err)
assert.Equal(t, int64(0), fi.Size())
require.NoError(t, item.Close(nil))
}
func TestItemReloadCacheStale(t *testing.T) {
r, c := newItemTestCache(t)
contents, obj, item := newFile(t, r, c, "existing")
// Open the object to create metadata for it
require.NoError(t, item.Open(obj))
size, err := item.GetSize()
require.NoError(t, err)
assert.Equal(t, int64(100), size)
// Read something to instantiate the cache file
buf := make([]byte, 10)
_, err = item.ReadAt(buf, 10)
require.NoError(t, err)
// Test cache file present
_, err = os.Stat(item.c.toOSPath(item.name))
require.NoError(t, err)
require.NoError(t, item.Close(nil))
// Update the remote to something different
contents2, obj, item := newFileLength(t, r, c, "existing", 110)
assert.NotEqual(t, contents, contents2)
// Re-open with updated object
oldFingerprint := item.info.Fingerprint
assert.NotEqual(t, "", oldFingerprint)
require.NoError(t, item.Open(obj))
// Make sure fingerprint was updated
assert.NotEqual(t, oldFingerprint, item.info.Fingerprint)
assert.NotEqual(t, "", item.info.Fingerprint)
// Check size is now 110
size, err = item.GetSize()
require.NoError(t, err)
assert.Equal(t, int64(110), size)
// Test cache file is now correct size
fi, err := os.Stat(item.c.toOSPath(item.name))
require.NoError(t, err)
assert.Equal(t, int64(110), fi.Size())
// Write to the file to make it dirty
// This checks we aren't reusing stale data
n, err := item.WriteAt([]byte("HELLO"), 0)
require.NoError(t, err)
assert.Equal(t, 5, n)
assert.Equal(t, true, item.IsDirty())
require.NoError(t, item.Close(nil))
// Now check with all that swizzling stuff around that the
// object is correct
checkObject(t, r, "existing", "HELLO"+contents2[5:])
}
func TestItemReadWrite(t *testing.T) {
r, c := newItemTestCache(t)
const (
size = 50*1024*1024 + 123
fileName = "large"
)
item, _ := c.get(fileName)
require.NoError(t, item.Open(nil))
// Create the test file
in := readers.NewPatternReader(size)
buf := make([]byte, 1024*1024)
buf2 := make([]byte, 1024*1024)
offset := int64(0)
for {
n, err := in.Read(buf)
n2, err2 := item.WriteAt(buf[:n], offset)
offset += int64(n2)
require.NoError(t, err2)
require.Equal(t, n, n2)
if err == io.EOF {
break
}
require.NoError(t, err)
}
// Check it is the right size
readSize, err := item.GetSize()
require.NoError(t, err)
assert.Equal(t, int64(size), readSize)
require.NoError(t, item.Close(nil))
assert.False(t, item.remove(fileName))
obj, err := r.Fremote.NewObject(context.Background(), fileName)
require.NoError(t, err)
assert.Equal(t, int64(size), obj.Size())
// read and check a block of size N at offset
// It returns eof true if the end of file has been reached
readCheckBuf := func(t *testing.T, in io.ReadSeeker, buf, buf2 []byte, item *Item, offset int64, N int) (n int, eof bool) {
what := fmt.Sprintf("buf=%p, buf2=%p, item=%p, offset=%d, N=%d", buf, buf2, item, offset, N)
n, err := item.ReadAt(buf, offset)
_, err2 := in.Seek(offset, io.SeekStart)
require.NoError(t, err2, what)
n2, err2 := in.Read(buf2[:n])
require.Equal(t, n, n2, what)
assert.Equal(t, buf[:n], buf2[:n2], what)
assert.Equal(t, buf[:n], buf2[:n2], what)
if err == io.EOF {
return n, true
}
require.NoError(t, err, what)
require.NoError(t, err2, what)
return n, false
}
readCheck := func(t *testing.T, item *Item, offset int64, N int) (n int, eof bool) {
return readCheckBuf(t, in, buf, buf2, item, offset, N)
}
// Read it back sequentially
t.Run("Sequential", func(t *testing.T) {
require.NoError(t, item.Open(obj))
assert.False(t, item.present())
offset := int64(0)
for {
n, eof := readCheck(t, item, offset, len(buf))
offset += int64(n)
if eof {
break
}
}
assert.Equal(t, int64(size), offset)
require.NoError(t, item.Close(nil))
assert.False(t, item.remove(fileName))
})
// Read it back randomly
t.Run("Random", func(t *testing.T) {
require.NoError(t, item.Open(obj))
assert.False(t, item.present())
for !item.present() {
blockSize := rand.Intn(len(buf))
offset := max(rand.Int63n(size+2*int64(blockSize))-int64(blockSize), 0)
_, _ = readCheck(t, item, offset, blockSize)
}
require.NoError(t, item.Close(nil))
assert.False(t, item.remove(fileName))
})
// Read it back randomly concurrently
t.Run("RandomConcurrent", func(t *testing.T) {
require.NoError(t, item.Open(obj))
assert.False(t, item.present())
var wg sync.WaitGroup
for range 8 {
wg.Add(1)
go func() {
defer wg.Done()
in := readers.NewPatternReader(size)
buf := make([]byte, 1024*1024)
buf2 := make([]byte, 1024*1024)
for !item.present() {
blockSize := rand.Intn(len(buf))
offset := max(rand.Int63n(size+2*int64(blockSize))-int64(blockSize), 0)
_, _ = readCheckBuf(t, in, buf, buf2, item, offset, blockSize)
}
}()
}
wg.Wait()
require.NoError(t, item.Close(nil))
assert.False(t, item.remove(fileName))
})
// Read it back in reverse which creates the maximum number of
// downloaders
t.Run("Reverse", func(t *testing.T) {
require.NoError(t, item.Open(obj))
assert.False(t, item.present())
offset := int64(size)
for {
blockSize := len(buf)
offset -= int64(blockSize)
if offset < 0 {
offset = 0
blockSize += int(offset)
}
_, _ = readCheck(t, item, offset, blockSize)
if offset == 0 {
break
}
}
require.NoError(t, item.Close(nil))
assert.False(t, item.remove(fileName))
})
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscache/cache.go | vfs/vfscache/cache.go | // Package vfscache deals with caching of files locally for the VFS layer
package vfscache
import (
"context"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"runtime"
"sort"
"strings"
"sync"
"time"
"github.com/rclone/rclone/fs"
fscache "github.com/rclone/rclone/fs/cache"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/hash"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fs/rc"
"github.com/rclone/rclone/lib/diskusage"
"github.com/rclone/rclone/lib/encoder"
"github.com/rclone/rclone/lib/file"
"github.com/rclone/rclone/lib/systemd"
"github.com/rclone/rclone/vfs/vfscache/writeback"
"github.com/rclone/rclone/vfs/vfscommon"
)
// NB as Cache and Item are tightly linked it is necessary to have a
// total lock ordering between them. So Cache.mu must always be
// taken before Item.mu to avoid deadlocks.
//
// Cache may call into Item but care is needed if Item calls Cache
// FIXME need to purge cache nodes which don't have backing files and aren't dirty
// these may get created by the VFS layer or may be orphans from reload()
// Cache opened files
type Cache struct {
// read only - no locking needed to read these
fremote fs.Fs // fs for the remote we are caching
fcache fs.Fs // fs for the cache directory
fcacheMeta fs.Fs // fs for the cache metadata directory
opt *vfscommon.Options // vfs Options
root string // root of the cache directory
metaRoot string // root of the cache metadata directory
hashType hash.Type // hash to use locally and remotely
hashOption *fs.HashesOption // corresponding OpenOption
writeback *writeback.WriteBack // holds Items for writeback
avFn AddVirtualFn // if set, can be called to add dir entries
mu sync.Mutex // protects the following variables
cond sync.Cond // cond lock for synchronous cache cleaning
item map[string]*Item // files/directories in the cache
errItems map[string]error // items in error state
used int64 // total size of files in the cache
outOfSpace bool // out of space
cleanerKicked bool // some thread kicked the cleaner upon out of space
kickerMu sync.Mutex // mutex for cleanerKicked
kick chan struct{} // channel for kicking clear to start
}
// AddVirtualFn if registered by the WithAddVirtual method, can be
// called to register the object or directory at remote as a virtual
// entry in directory listings.
//
// This is used when reloading the Cache and uploading items need to
// go into the directory tree.
type AddVirtualFn func(remote string, size int64, isDir bool) error
// New creates a new cache hierarchy for fremote
//
// This starts background goroutines which can be cancelled with the
// context passed in.
func New(ctx context.Context, fremote fs.Fs, opt *vfscommon.Options, avFn AddVirtualFn) (*Cache, error) {
// Get cache root path.
// We need it in two variants: OS path as an absolute path with UNC prefix,
// OS-specific path separators, and encoded with OS-specific encoder. Standard path
// without UNC prefix, with slash path separators, and standard (internal) encoding.
// Care must be taken when creating OS paths so that the ':' separator following a
// drive letter is not encoded (e.g. into unicode fullwidth colon).
var err error
parentOSPath := config.GetCacheDir() // Assuming string contains a local absolute path in OS encoding
fs.Debugf(fremote, "vfs cache: root is %q", parentOSPath)
parentPath := fromOSPath(parentOSPath)
// Get a relative cache path representing the remote.
relativeDirPath := fremote.Root() // This is a remote path in standard encoding
if runtime.GOOS == "windows" {
if strings.HasPrefix(relativeDirPath, `//?/`) {
relativeDirPath = relativeDirPath[2:] // Trim off the "//" for the result to be a valid when appending to another path
}
}
relativeDirPath = fremote.Name() + "/" + relativeDirPath
relativeDirOSPath := toOSPath(relativeDirPath)
// Create cache root dirs
var dataOSPath, metaOSPath string
if dataOSPath, metaOSPath, err = createRootDirs(parentOSPath, relativeDirOSPath); err != nil {
return nil, err
}
fs.Debugf(fremote, "vfs cache: data root is %q", dataOSPath)
fs.Debugf(fremote, "vfs cache: metadata root is %q", metaOSPath)
// Get (create) cache backends
var fdata, fmeta fs.Fs
if fdata, fmeta, err = getBackends(ctx, parentPath, relativeDirPath); err != nil {
return nil, err
}
hashType, hashOption := operations.CommonHash(ctx, fdata, fremote)
// Create the cache object
c := &Cache{
fremote: fremote,
fcache: fdata,
fcacheMeta: fmeta,
opt: opt,
root: dataOSPath,
metaRoot: metaOSPath,
item: make(map[string]*Item),
errItems: make(map[string]error),
hashType: hashType,
hashOption: hashOption,
writeback: writeback.New(ctx, opt),
avFn: avFn,
}
// load in the cache and metadata off disk
err = c.reload(ctx)
if err != nil {
return nil, fmt.Errorf("failed to load cache: %w", err)
}
// Remove any empty directories
c.purgeEmptyDirs("", true)
// Create a channel for cleaner to be kicked upon out of space con
c.kick = make(chan struct{}, 1)
c.cond = sync.Cond{L: &c.mu}
go c.cleaner(ctx)
return c, nil
}
// Stats returns info about the Cache
func (c *Cache) Stats() (out rc.Params) {
out = make(rc.Params)
// read only - no locking needed to read these
out["path"] = c.root
out["pathMeta"] = c.metaRoot
out["hashType"] = c.hashType
uploadsInProgress, uploadsQueued := c.writeback.Stats()
out["uploadsInProgress"] = uploadsInProgress
out["uploadsQueued"] = uploadsQueued
c.mu.Lock()
defer c.mu.Unlock()
out["files"] = len(c.item)
out["erroredFiles"] = len(c.errItems)
out["bytesUsed"] = c.used
out["outOfSpace"] = c.outOfSpace
return out
}
// Queue returns info about the Cache
func (c *Cache) Queue() (out rc.Params) {
out = make(rc.Params)
out["queue"] = c.writeback.Queue()
return out
}
// QueueSetExpiry updates the expiry of a single item in the upload queue
//
// The expiry time is set to expiry + relative if expiry is passed in,
// otherwise the expiry of the item is used.
func (c *Cache) QueueSetExpiry(id writeback.Handle, expiry time.Time, relative time.Duration) error {
return c.writeback.SetExpiry(id, expiry, relative)
}
// createDir creates a directory path, along with any necessary parents
func createDir(dir string) error {
return file.MkdirAll(dir, 0700)
}
// createRootDir creates a single cache root directory
func createRootDir(parentOSPath string, name string, relativeDirOSPath string) (path string, err error) {
path = file.UNCPath(filepath.Join(parentOSPath, name, relativeDirOSPath))
err = createDir(path)
return
}
// createRootDirs creates all cache root directories
func createRootDirs(parentOSPath string, relativeDirOSPath string) (dataOSPath string, metaOSPath string, err error) {
if dataOSPath, err = createRootDir(parentOSPath, "vfs", relativeDirOSPath); err != nil {
err = fmt.Errorf("failed to create data cache directory: %w", err)
} else if metaOSPath, err = createRootDir(parentOSPath, "vfsMeta", relativeDirOSPath); err != nil {
err = fmt.Errorf("failed to create metadata cache directory: %w", err)
}
return
}
// createItemDir creates the directory for named item in all cache roots
//
// Returns an os path for the data cache file.
func (c *Cache) createItemDir(name string) (string, error) {
parent := vfscommon.FindParent(name)
parentPath := c.toOSPath(parent)
err := createDir(parentPath)
if err != nil {
return "", fmt.Errorf("failed to create data cache item directory: %w", err)
}
parentPathMeta := c.toOSPathMeta(parent)
err = createDir(parentPathMeta)
if err != nil {
return "", fmt.Errorf("failed to create metadata cache item directory: %w", err)
}
return c.toOSPath(name), nil
}
// getBackend gets a backend for a cache root dir
func getBackend(ctx context.Context, parentPath string, name string, relativeDirPath string) (fs.Fs, error) {
// Make sure we turn off the global links flag as it overrides the backend specific one
ctx, ci := fs.AddConfig(ctx)
ci.Links = false
path := fmt.Sprintf(":local,encoding='%v',links=false:%s/%s/%s", encoder.OS, parentPath, name, relativeDirPath)
return fscache.Get(ctx, path)
}
// getBackends gets backends for all cache root dirs
func getBackends(ctx context.Context, parentPath string, relativeDirPath string) (fdata fs.Fs, fmeta fs.Fs, err error) {
if fdata, err = getBackend(ctx, parentPath, "vfs", relativeDirPath); err != nil {
err = fmt.Errorf("failed to get data cache backend: %w", err)
} else if fmeta, err = getBackend(ctx, parentPath, "vfsMeta", relativeDirPath); err != nil {
err = fmt.Errorf("failed to get metadata cache backend: %w", err)
}
return
}
// clean returns the cleaned version of name for use in the index map
//
// name should be a remote path not an osPath
func clean(name string) string {
name = strings.Trim(name, "/")
name = path.Clean(name)
if name == "." || name == "/" {
name = ""
}
return name
}
// fromOSPath turns a OS path into a standard/remote path
func fromOSPath(osPath string) string {
return encoder.OS.ToStandardPath(filepath.ToSlash(osPath))
}
// toOSPath turns a standard/remote path into an OS path
func toOSPath(standardPath string) string {
return filepath.FromSlash(encoder.OS.FromStandardPath(standardPath))
}
// toOSPath turns a remote relative name into an OS path in the cache
func (c *Cache) toOSPath(name string) string {
return filepath.Join(c.root, toOSPath(name))
}
// toOSPathMeta turns a remote relative name into an OS path in the
// cache for the metadata
func (c *Cache) toOSPathMeta(name string) string {
return filepath.Join(c.metaRoot, toOSPath(name))
}
// _get gets name from the cache or creates a new one
//
// It returns the item and found as to whether this item was found in
// the cache (or just created).
//
// name should be a remote path not an osPath
//
// must be called with mu held
func (c *Cache) _get(name string) (item *Item, found bool) {
item = c.item[name]
found = item != nil
if !found {
item = newItem(c, name)
c.item[name] = item
}
return item, found
}
// put puts item under name in the cache
//
// It returns an old item if there was one or nil if not.
//
// name should be a remote path not an osPath
func (c *Cache) put(name string, item *Item) (oldItem *Item) {
name = clean(name)
c.mu.Lock()
oldItem = c.item[name]
if oldItem != item {
c.item[name] = item
} else {
oldItem = nil
}
c.mu.Unlock()
return oldItem
}
// InUse returns whether the name is in use in the cache
//
// name should be a remote path not an osPath
func (c *Cache) InUse(name string) bool {
name = clean(name)
c.mu.Lock()
item := c.item[name]
c.mu.Unlock()
if item == nil {
return false
}
return item.inUse()
}
// DirtyItem returns the Item if it exists in the cache **and** is
// dirty otherwise it returns nil.
//
// name should be a remote path not an osPath
func (c *Cache) DirtyItem(name string) (item *Item) {
name = clean(name)
c.mu.Lock()
defer c.mu.Unlock()
item = c.item[name]
if item != nil && !item.IsDirty() {
item = nil
}
return item
}
// get gets a file name from the cache or creates a new one
//
// It returns the item and found as to whether this item was found in
// the cache (or just created).
//
// name should be a remote path not an osPath
func (c *Cache) get(name string) (item *Item, found bool) {
name = clean(name)
c.mu.Lock()
item, found = c._get(name)
c.mu.Unlock()
return item, found
}
// Item gets a cache item for name
//
// To use it item.Open will need to be called.
//
// name should be a remote path not an osPath
func (c *Cache) Item(name string) (item *Item) {
item, _ = c.get(name)
return item
}
// Exists checks to see if the file exists in the cache or not.
//
// This is done by bringing the item into the cache which will
// validate the backing file and metadata and then asking if the Item
// exists or not.
func (c *Cache) Exists(name string) bool {
item, _ := c.get(name)
return item.Exists()
}
// rename with os.Rename and more checking
func rename(osOldPath, osNewPath string) error {
sfi, err := os.Stat(osOldPath)
if err != nil {
// Just do nothing if the source does not exist
if os.IsNotExist(err) {
return nil
}
return fmt.Errorf("failed to stat source: %s: %w", osOldPath, err)
}
if !sfi.Mode().IsRegular() {
// cannot copy non-regular files (e.g., directories, symlinks, devices, etc.)
return fmt.Errorf("non-regular source file: %s (%q)", sfi.Name(), sfi.Mode().String())
}
dfi, err := os.Stat(osNewPath)
if err != nil {
if !os.IsNotExist(err) {
return fmt.Errorf("failed to stat destination: %s: %w", osNewPath, err)
}
parent := vfscommon.OSFindParent(osNewPath)
err = createDir(parent)
if err != nil {
return fmt.Errorf("failed to create parent dir: %s: %w", parent, err)
}
} else {
if !(dfi.Mode().IsRegular()) {
return fmt.Errorf("non-regular destination file: %s (%q)", dfi.Name(), dfi.Mode().String())
}
if os.SameFile(sfi, dfi) {
return nil
}
}
if err = os.Rename(osOldPath, osNewPath); err != nil {
return fmt.Errorf("failed to rename in cache: %s to %s: %w", osOldPath, osNewPath, err)
}
return nil
}
// Rename the item in cache
func (c *Cache) Rename(name string, newName string, newObj fs.Object) (err error) {
item, _ := c.get(name)
err = item.rename(name, newName, newObj)
if err != nil {
return err
}
// Move the item in the cache
c.mu.Lock()
if item, ok := c.item[name]; ok {
c.item[newName] = item
delete(c.item, name)
}
c.mu.Unlock()
fs.Infof(name, "vfs cache: renamed in cache to %q", newName)
return nil
}
// DirExists checks to see if the directory exists in the cache or not.
func (c *Cache) DirExists(name string) bool {
path := c.toOSPath(name)
_, err := os.Stat(path)
return err == nil
}
// DirRename the dir in cache
func (c *Cache) DirRename(oldDirName string, newDirName string) (err error) {
// Make sure names are / suffixed for reading keys out of c.item
if !strings.HasSuffix(oldDirName, "/") {
oldDirName += "/"
}
if !strings.HasSuffix(newDirName, "/") {
newDirName += "/"
}
// Find all items to rename
var renames []string
c.mu.Lock()
for itemName := range c.item {
if strings.HasPrefix(itemName, oldDirName) {
renames = append(renames, itemName)
}
}
c.mu.Unlock()
// Rename the items
for _, itemName := range renames {
newPath := newDirName + itemName[len(oldDirName):]
renameErr := c.Rename(itemName, newPath, nil)
if renameErr != nil {
err = renameErr
}
}
// Old path should be empty now so remove it
c.purgeEmptyDirs(oldDirName[:len(oldDirName)-1], false)
fs.Infof(oldDirName, "vfs cache: renamed dir in cache to %q", newDirName)
return err
}
// Remove should be called if name is deleted
//
// This returns true if the file was in the transfer queue so may not
// have completely uploaded yet.
func (c *Cache) Remove(name string) (wasWriting bool) {
name = clean(name)
c.mu.Lock()
item := c.item[name]
if item != nil {
delete(c.item, name)
}
c.mu.Unlock()
if item == nil {
return false
}
return item.remove("file deleted")
}
// SetModTime should be called to set the modification time of the cache file
func (c *Cache) SetModTime(name string, modTime time.Time) {
item, _ := c.get(name)
item.setModTime(modTime)
}
// CleanUp empties the cache of everything
func (c *Cache) CleanUp() error {
err1 := os.RemoveAll(c.root)
err2 := os.RemoveAll(c.metaRoot)
if err1 != nil {
return err1
}
return err2
}
// walk walks the cache calling the function
func (c *Cache) walk(dir string, fn func(osPath string, fi os.FileInfo, name string) error) error {
return filepath.Walk(dir, func(osPath string, fi os.FileInfo, err error) error {
if err != nil {
return err
}
// Find path relative to the cache root
name, err := filepath.Rel(dir, osPath)
if err != nil {
return fmt.Errorf("filepath.Rel failed in walk: %w", err)
}
if name == "." {
name = ""
}
// And convert into slashes
name = filepath.ToSlash(name)
return fn(osPath, fi, name)
})
}
// reload walks the cache loading metadata files
//
// It iterates the files first then metadata trees. It doesn't expect
// to find any new items iterating the metadata but it will clear up
// orphan files.
func (c *Cache) reload(ctx context.Context) error {
for _, dir := range []string{c.root, c.metaRoot} {
err := c.walk(dir, func(osPath string, fi os.FileInfo, name string) error {
if fi.IsDir() {
return nil
}
item, found := c.get(name)
if !found {
err := item.reload(ctx)
if err != nil {
fs.Errorf(name, "vfs cache: failed to reload item: %v", err)
}
}
return nil
})
if err != nil {
return fmt.Errorf("failed to walk cache %q: %w", dir, err)
}
}
return nil
}
// KickCleaner kicks cache cleaner upon out of space situation
func (c *Cache) KickCleaner() {
/* Use a separate kicker mutex for the kick to go through without waiting for the
cache mutex to avoid letting a thread kick again after the clearer just
finished cleaning and unlock the cache mutex. */
fs.Debugf(c.fremote, "vfs cache: at the beginning of KickCleaner")
c.kickerMu.Lock()
if !c.cleanerKicked {
c.cleanerKicked = true
fs.Debugf(c.fremote, "vfs cache: in KickCleaner, ready to lock cache mutex")
c.mu.Lock()
c.outOfSpace = true
fs.Logf(c.fremote, "vfs cache: in KickCleaner, ready to kick cleaner")
c.kick <- struct{}{}
c.mu.Unlock()
}
c.kickerMu.Unlock()
c.mu.Lock()
for c.outOfSpace {
fs.Debugf(c.fremote, "vfs cache: in KickCleaner, looping on c.outOfSpace")
c.cond.Wait()
}
fs.Debugf(c.fremote, "vfs cache: in KickCleaner, leaving c.outOfSpace loop")
c.mu.Unlock()
}
// removeNotInUse removes items not in use with a possible maxAge cutoff
// called with cache mutex locked and up-to-date c.used (as we update it directly here)
func (c *Cache) removeNotInUse(item *Item, maxAge time.Duration, emptyOnly bool) {
removed, spaceFreed := item.RemoveNotInUse(maxAge, emptyOnly)
// The item space might be freed even if we get an error after the cache file is removed
// The item will not be removed or reset the cache data is dirty (DataDirty)
c.used -= spaceFreed
if removed {
fs.Infof(c.fremote, "vfs cache RemoveNotInUse (maxAge=%d, emptyOnly=%v): item %s was removed, freed %d bytes", maxAge, emptyOnly, item.GetName(), spaceFreed)
// Remove the entry
delete(c.item, item.name)
} else {
fs.Debugf(c.fremote, "vfs cache RemoveNotInUse (maxAge=%d, emptyOnly=%v): item %s not removed, freed %d bytes", maxAge, emptyOnly, item.GetName(), spaceFreed)
}
}
// Retry failed resets during purgeClean()
func (c *Cache) retryFailedResets() {
// Some items may have failed to reset because there was not enough space
// for saving the cache item's metadata. Redo the Reset()'s here now that
// we may have some available space.
if len(c.errItems) != 0 {
fs.Debugf(c.fremote, "vfs cache reset: before redoing reset errItems = %v", c.errItems)
for itemName := range c.errItems {
if retryItem, ok := c.item[itemName]; ok {
_, _, err := retryItem.Reset()
if err == nil || !fserrors.IsErrNoSpace(err) {
// TODO: not trying to handle non-ENOSPC errors yet
delete(c.errItems, itemName)
}
} else {
// The retry item was deleted because it was closed.
// No need to redo the failed reset now.
delete(c.errItems, itemName)
}
}
fs.Debugf(c.fremote, "vfs cache reset: after redoing reset errItems = %v", c.errItems)
}
}
// Remove cache files that are not dirty until the quota is satisfied
func (c *Cache) purgeClean() {
c.mu.Lock()
defer c.mu.Unlock()
if c.quotasOK() {
return
}
var items Items
// Make a slice of clean cache files
for _, item := range c.item {
if !item.IsDirty() {
items = append(items, item)
}
}
sort.Sort(items)
// Reset items until the quota is OK
for _, item := range items {
if c.quotasOK() {
break
}
resetResult, spaceFreed, err := item.Reset()
// The item space might be freed even if we get an error after the cache file is removed
// The item will not be removed or reset if the cache data is dirty (DataDirty)
c.used -= spaceFreed
fs.Infof(c.fremote, "vfs cache purgeClean item.Reset %s: %s, freed %d bytes", item.GetName(), resetResult.String(), spaceFreed)
if resetResult == RemovedNotInUse {
delete(c.item, item.name)
}
if err != nil {
fs.Errorf(c.fremote, "vfs cache purgeClean item.Reset %s reset failed, err = %v, freed %d bytes", item.GetName(), err, spaceFreed)
c.errItems[item.name] = err
}
}
// Reset outOfSpace without checking whether we have reduced cache space below the quota.
// This allows some files to reduce their pendingAccesses count to allow them to be reset
// in the next iteration of the purge cleaner loop.
c.outOfSpace = false
c.cond.Broadcast()
}
// purgeOld gets rid of any files that are over age
func (c *Cache) purgeOld(maxAge time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
// cutoff := time.Now().Add(-maxAge)
for _, item := range c.item {
c.removeNotInUse(item, maxAge, false)
}
if c.quotasOK() {
c.outOfSpace = false
c.cond.Broadcast()
}
}
// Purge any empty directories
func (c *Cache) purgeEmptyDirs(dir string, leaveRoot bool) {
ctx := context.Background()
err := operations.Rmdirs(ctx, c.fcache, dir, leaveRoot)
if err != nil {
fs.Errorf(c.fcache, "vfs cache: failed to remove empty directories from cache path %q: %v", dir, err)
}
err = operations.Rmdirs(ctx, c.fcacheMeta, dir, leaveRoot)
if err != nil {
fs.Errorf(c.fcache, "vfs cache: failed to remove empty directories from metadata cache path %q: %v", dir, err)
}
}
// updateUsed updates c.used so it is accurate
func (c *Cache) updateUsed() (used int64) {
c.mu.Lock()
defer c.mu.Unlock()
newUsed := int64(0)
for _, item := range c.item {
newUsed += item.getDiskSize()
}
c.used = newUsed
return newUsed
}
// Check the available space for a disk is in limits.
func (c *Cache) minFreeSpaceQuotaOK() bool {
if c.opt.CacheMinFreeSpace <= 0 {
return true
}
du, err := diskusage.New(config.GetCacheDir())
if err == diskusage.ErrUnsupported {
return true
}
if err != nil {
fs.Errorf(c.fremote, "disk usage returned error: %v", err)
return true
}
return du.Available >= uint64(c.opt.CacheMinFreeSpace)
}
// Check the available quota for a disk is in limits.
//
// must be called with mu held.
func (c *Cache) maxSizeQuotaOK() bool {
if c.opt.CacheMaxSize <= 0 {
return true
}
return c.used <= int64(c.opt.CacheMaxSize)
}
// Check the available quotas for a disk is in limits.
//
// must be called with mu held.
func (c *Cache) quotasOK() bool {
return c.maxSizeQuotaOK() && c.minFreeSpaceQuotaOK()
}
// Return true if any quotas set
func (c *Cache) haveQuotas() bool {
return c.opt.CacheMaxSize > 0 || c.opt.CacheMinFreeSpace > 0
}
// Remove clean cache files that are not open until the total space
// is reduced below quota starting from the oldest first
func (c *Cache) purgeOverQuota() {
c.updateUsed()
c.mu.Lock()
defer c.mu.Unlock()
if c.quotasOK() {
return
}
var items Items
// Make a slice of unused files
for _, item := range c.item {
if !item.inUse() {
items = append(items, item)
}
}
sort.Sort(items)
// Remove items until the quota is OK
for _, item := range items {
c.removeNotInUse(item, 0, c.quotasOK())
}
if c.quotasOK() {
c.outOfSpace = false
c.cond.Broadcast()
}
}
// clean empties the cache of stuff if it can
func (c *Cache) clean(kicked bool) {
// Cache may be empty so end
_, err := os.Stat(c.root)
if os.IsNotExist(err) {
return
}
c.updateUsed()
c.mu.Lock()
oldItems, oldUsed := len(c.item), fs.SizeSuffix(c.used)
c.mu.Unlock()
// Remove any files that are over age
c.purgeOld(time.Duration(c.opt.CacheMaxAge))
// If have a maximum cache size...
if c.haveQuotas() {
// Remove files not in use until cache size is below quota starting from the oldest first
c.purgeOverQuota()
// Remove cache files that are not dirty if we are still above the max cache size
c.purgeClean()
c.retryFailedResets()
}
// Was kicked?
if kicked {
c.kickerMu.Lock() // Make sure this is called with cache mutex unlocked
// Re-enable io threads to kick me
c.cleanerKicked = false
c.kickerMu.Unlock()
}
// Stats
c.mu.Lock()
newItems, newUsed := len(c.item), fs.SizeSuffix(c.used)
totalInUse := 0
for _, item := range c.item {
if item.inUse() {
totalInUse++
}
}
c.mu.Unlock()
uploadsInProgress, uploadsQueued := c.writeback.Stats()
stats := fmt.Sprintf("objects %d (was %d) in use %d, to upload %d, uploading %d, total size %v (was %v)",
newItems, oldItems, totalInUse, uploadsQueued, uploadsInProgress, newUsed, oldUsed)
fs.Infof(c.fremote, "vfs cache: cleaned: %s", stats)
if err = systemd.UpdateStatus(fmt.Sprintf("[%s] vfs cache: %s", time.Now().Format("15:04"), stats)); err != nil {
fs.Errorf(c.fremote, "vfs cache: updating systemd status with current stats failed: %s", err)
}
}
// cleaner calls clean at regular intervals and upon being kicked for out-of-space condition
//
// doesn't return until context is cancelled
func (c *Cache) cleaner(ctx context.Context) {
if c.opt.CachePollInterval <= 0 {
fs.Debugf(c.fremote, "vfs cache: cleaning thread disabled because poll interval <= 0")
return
}
// Start cleaning the cache immediately
c.clean(false)
// Then every interval specified
timer := time.NewTicker(time.Duration(c.opt.CachePollInterval))
defer timer.Stop()
for {
select {
case <-c.kick: // a thread encountering ENOSPC kicked me
c.clean(true) // kicked is true
case <-timer.C:
c.clean(false) // timer driven cache poll, kicked is false
case <-ctx.Done():
fs.Debugf(c.fremote, "vfs cache: cleaner exiting")
return
}
}
}
// TotalInUse returns the number of items in the cache which are InUse
func (c *Cache) TotalInUse() (n int) {
c.mu.Lock()
defer c.mu.Unlock()
for _, item := range c.item {
if item.inUse() {
n++
}
}
return n
}
// Dump the cache into a string for debugging purposes
func (c *Cache) Dump() string {
if c == nil {
return "Cache: <nil>\n"
}
c.mu.Lock()
defer c.mu.Unlock()
var out strings.Builder
out.WriteString("Cache{\n")
for name, item := range c.item {
fmt.Fprintf(&out, "\t%q: %+v,\n", name, item)
}
out.WriteString("}\n")
return out.String()
}
// AddVirtual adds a virtual directory entry by calling the addVirtual
// callback if one has been registered.
func (c *Cache) AddVirtual(remote string, size int64, isDir bool) error {
if c.avFn == nil {
return errors.New("no AddVirtual function registered")
}
return c.avFn(remote, size, isDir)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscache/cache_test.go | vfs/vfscache/cache_test.go | package vfscache
import (
"context"
"fmt"
"os"
"path/filepath"
"sort"
"testing"
"time"
_ "github.com/rclone/rclone/backend/local" // import the local backend
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/config"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/diskusage"
"github.com/rclone/rclone/vfs/vfscache/writeback"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestMain drives the tests
func TestMain(m *testing.M) {
fstest.TestMain(m)
}
// convert c.item to a string
func itemAsString(c *Cache) []string {
c.mu.Lock()
defer c.mu.Unlock()
var out []string
for name, item := range c.item {
out = append(out, fmt.Sprintf("name=%q opens=%d size=%d", filepath.ToSlash(name), item.opens, item.info.Size))
}
sort.Strings(out)
return out
}
// convert c.item to a string
func itemSpaceAsString(c *Cache) []string {
c.mu.Lock()
defer c.mu.Unlock()
var out []string
for name, item := range c.item {
space := item.info.Rs.Size()
out = append(out, fmt.Sprintf("name=%q opens=%d size=%d space=%d", filepath.ToSlash(name), item.opens, item.info.Size, space))
}
sort.Strings(out)
return out
}
// open an item and write to it
func itemWrite(t *testing.T, item *Item, contents string) {
require.NoError(t, item.Open(nil))
_, err := item.WriteAt([]byte(contents), 0)
require.NoError(t, err)
}
func assertPathNotExist(t *testing.T, path string) {
_, err := os.Stat(path)
assert.True(t, os.IsNotExist(err))
}
func assertPathExist(t *testing.T, path string) os.FileInfo {
fi, err := os.Stat(path)
assert.NoError(t, err)
return fi
}
type avInfo struct {
Remote string
Size int64
IsDir bool
}
var avInfos []avInfo
func addVirtual(remote string, size int64, isDir bool) error {
avInfos = append(avInfos, avInfo{
Remote: remote,
Size: size,
IsDir: isDir,
})
return nil
}
func newTestCacheOpt(t *testing.T, opt vfscommon.Options) (r *fstest.Run, c *Cache) {
r = fstest.NewRun(t)
ctx, cancel := context.WithCancel(context.Background())
avInfos = nil
c, err := New(ctx, r.Fremote, &opt, addVirtual)
require.NoError(t, err)
t.Cleanup(func() {
err := c.CleanUp()
require.NoError(t, err)
assertPathNotExist(t, c.root)
cancel()
})
return r, c
}
func newTestCache(t *testing.T) (r *fstest.Run, c *Cache) {
opt := vfscommon.Opt
// Disable the cache cleaner as it interferes with these tests
opt.CachePollInterval = 0
// Disable synchronous write
opt.WriteBack = 0
return newTestCacheOpt(t, opt)
}
func TestCacheNew(t *testing.T) {
r, c := newTestCache(t)
assert.Contains(t, c.root, "vfs")
assert.Contains(t, c.fcache.Root(), filepath.Base(r.Fremote.Root()))
assert.Equal(t, []string(nil), itemAsString(c))
// createItemDir
p, err := c.createItemDir("potato")
require.NoError(t, err)
assert.Equal(t, "potato", filepath.Base(p))
assert.Equal(t, []string(nil), itemAsString(c))
fi := assertPathExist(t, filepath.Dir(p))
assert.True(t, fi.IsDir())
// get
item, _ := c.get("potato")
item2, _ := c.get("potato")
assert.Equal(t, item, item2)
assert.WithinDuration(t, time.Now(), item.info.ATime, time.Second)
// open
assert.Equal(t, []string{
`name="potato" opens=0 size=0`,
}, itemAsString(c))
potato := c.Item("/potato")
require.NoError(t, potato.Open(nil))
assert.Equal(t, []string{
`name="potato" opens=1 size=0`,
}, itemAsString(c))
assert.WithinDuration(t, time.Now(), potato.info.ATime, time.Second)
assert.Equal(t, 1, potato.opens)
// write the file
require.NoError(t, potato.Truncate(5))
atime := time.Now()
potato.info.ATime = atime
assert.Equal(t, []string{
`name="potato" opens=1 size=5`,
}, itemAsString(c))
assert.True(t, atime.Equal(potato.info.ATime), fmt.Sprintf("%v != %v", atime, potato.info.ATime))
// try purging with file open
c.purgeOld(10 * time.Second)
assertPathExist(t, p)
// close
assert.Equal(t, []string{
`name="potato" opens=1 size=5`,
}, itemAsString(c))
require.NoError(t, potato.Truncate(6))
assert.Equal(t, []string{
`name="potato" opens=1 size=6`,
}, itemAsString(c))
require.NoError(t, potato.Close(nil))
assert.Equal(t, []string{
`name="potato" opens=0 size=6`,
}, itemAsString(c))
item, _ = c.get("potato")
assert.WithinDuration(t, time.Now(), item.info.ATime, time.Second)
assert.Equal(t, 0, item.opens)
// try purging with file closed
c.purgeOld(10 * time.Second)
assertPathExist(t, p)
//.. purge again with -ve age
c.purgeOld(-10 * time.Second)
assertPathNotExist(t, p)
// clean - have tested the internals already
c.clean(false)
}
func TestCacheOpens(t *testing.T) {
_, c := newTestCache(t)
assert.Equal(t, []string(nil), itemAsString(c))
potato := c.Item("potato")
require.NoError(t, potato.Open(nil))
assert.Equal(t, []string{
`name="potato" opens=1 size=0`,
}, itemAsString(c))
require.NoError(t, potato.Open(nil))
assert.Equal(t, []string{
`name="potato" opens=2 size=0`,
}, itemAsString(c))
require.NoError(t, potato.Close(nil))
assert.Equal(t, []string{
`name="potato" opens=1 size=0`,
}, itemAsString(c))
require.NoError(t, potato.Close(nil))
assert.Equal(t, []string{
`name="potato" opens=0 size=0`,
}, itemAsString(c))
require.NoError(t, potato.Open(nil))
a1 := c.Item("a//b/c/d/one")
a2 := c.Item("a/b/c/d/e/two")
a3 := c.Item("a/b/c/d/e/f/three")
require.NoError(t, a1.Open(nil))
require.NoError(t, a2.Open(nil))
require.NoError(t, a3.Open(nil))
assert.Equal(t, []string{
`name="a/b/c/d/e/f/three" opens=1 size=0`,
`name="a/b/c/d/e/two" opens=1 size=0`,
`name="a/b/c/d/one" opens=1 size=0`,
`name="potato" opens=1 size=0`,
}, itemAsString(c))
require.NoError(t, potato.Close(nil))
require.NoError(t, a1.Close(nil))
require.NoError(t, a2.Close(nil))
require.NoError(t, a3.Close(nil))
assert.Equal(t, []string{
`name="a/b/c/d/e/f/three" opens=0 size=0`,
`name="a/b/c/d/e/two" opens=0 size=0`,
`name="a/b/c/d/one" opens=0 size=0`,
`name="potato" opens=0 size=0`,
}, itemAsString(c))
}
// test the open, createItemDir, purge, close, purge sequence
func TestCacheOpenMkdir(t *testing.T) {
_, c := newTestCache(t)
// open
potato := c.Item("sub/potato")
require.NoError(t, potato.Open(nil))
assert.Equal(t, []string{
`name="sub/potato" opens=1 size=0`,
}, itemAsString(c))
// createItemDir
p, err := c.createItemDir("sub/potato")
require.NoError(t, err)
assert.Equal(t, "potato", filepath.Base(p))
assert.Equal(t, []string{
`name="sub/potato" opens=1 size=0`,
}, itemAsString(c))
// test directory exists
fi := assertPathExist(t, filepath.Dir(p))
assert.True(t, fi.IsDir())
// clean the cache
c.purgeOld(-10 * time.Second)
// test directory still exists
fi = assertPathExist(t, filepath.Dir(p))
assert.True(t, fi.IsDir())
// close
require.NoError(t, potato.Close(nil))
assert.Equal(t, []string{
`name="sub/potato" opens=0 size=0`,
}, itemAsString(c))
// clean the cache
c.purgeOld(-10 * time.Second)
c.purgeEmptyDirs("", true)
assert.Equal(t, []string(nil), itemAsString(c))
// test directory does not exist
assertPathNotExist(t, filepath.Dir(p))
}
func TestCachePurgeOld(t *testing.T) {
_, c := newTestCache(t)
// Test funcs
c.purgeOld(-10 * time.Second)
potato2 := c.Item("sub/dir2/potato2")
require.NoError(t, potato2.Open(nil))
potato := c.Item("sub/dir/potato")
require.NoError(t, potato.Open(nil))
require.NoError(t, potato2.Close(nil))
require.NoError(t, potato.Open(nil))
assert.Equal(t, []string{
`name="sub/dir/potato" opens=2 size=0`,
`name="sub/dir2/potato2" opens=0 size=0`,
}, itemAsString(c))
c.purgeOld(-10 * time.Second)
assert.Equal(t, []string{
`name="sub/dir/potato" opens=2 size=0`,
}, itemAsString(c))
require.NoError(t, potato.Close(nil))
assert.Equal(t, []string{
`name="sub/dir/potato" opens=1 size=0`,
}, itemAsString(c))
c.purgeOld(-10 * time.Second)
assert.Equal(t, []string{
`name="sub/dir/potato" opens=1 size=0`,
}, itemAsString(c))
require.NoError(t, potato.Close(nil))
assert.Equal(t, []string{
`name="sub/dir/potato" opens=0 size=0`,
}, itemAsString(c))
c.purgeOld(10 * time.Second)
assert.Equal(t, []string{
`name="sub/dir/potato" opens=0 size=0`,
}, itemAsString(c))
c.purgeOld(-10 * time.Second)
assert.Equal(t, []string(nil), itemAsString(c))
}
func TestCachePurgeOverQuota(t *testing.T) {
_, c := newTestCache(t)
// Test funcs
// Make some test files
potato := c.Item("sub/dir/potato")
itemWrite(t, potato, "hello")
potato2 := c.Item("sub/dir2/potato2")
itemWrite(t, potato2, "hello2")
assert.Equal(t, []string{
`name="sub/dir/potato" opens=1 size=5`,
`name="sub/dir2/potato2" opens=1 size=6`,
}, itemAsString(c))
// Check nothing removed
c.opt.CacheMaxSize = 1
c.purgeOverQuota()
// Close the files
require.NoError(t, potato.Close(nil))
require.NoError(t, potato2.Close(nil))
assert.Equal(t, []string{
`name="sub/dir/potato" opens=0 size=5`,
`name="sub/dir2/potato2" opens=0 size=6`,
}, itemAsString(c))
// Update the stats to read the total size
c.updateUsed()
// make potato2 definitely after potato
t1 := time.Now().Add(10 * time.Second)
potato2.info.ATime = t1
// Check only potato removed to get below quota
c.opt.CacheMaxSize = 10
c.purgeOverQuota()
assert.Equal(t, int64(6), c.used)
assert.Equal(t, []string{
`name="sub/dir2/potato2" opens=0 size=6`,
}, itemAsString(c))
// Put potato back
potato = c.Item("sub/dir/potato")
require.NoError(t, potato.Open(nil))
require.NoError(t, potato.Truncate(5))
require.NoError(t, potato.Close(nil))
// Update the stats to read the total size
c.updateUsed()
assert.Equal(t, []string{
`name="sub/dir/potato" opens=0 size=5`,
`name="sub/dir2/potato2" opens=0 size=6`,
}, itemAsString(c))
// make potato definitely after potato2
t2 := t1.Add(20 * time.Second)
potato.info.ATime = t2
// Check only potato2 removed to get below quota
c.opt.CacheMaxSize = 10
c.purgeOverQuota()
assert.Equal(t, int64(5), c.used)
c.purgeEmptyDirs("", true)
assert.Equal(t, []string{
`name="sub/dir/potato" opens=0 size=5`,
}, itemAsString(c))
// Now purge everything
c.opt.CacheMaxSize = 1
c.purgeOverQuota()
assert.Equal(t, int64(0), c.used)
c.purgeEmptyDirs("", true)
assert.Equal(t, []string(nil), itemAsString(c))
// Check nothing left behind
c.clean(false)
assert.Equal(t, int64(0), c.used)
assert.Equal(t, []string(nil), itemAsString(c))
}
func TestCachePurgeMinFreeSpace(t *testing.T) {
du, err := diskusage.New(config.GetCacheDir())
if err == diskusage.ErrUnsupported {
t.Skip(err)
}
// We've tested the quota mechanism already, so just test the
// min free space quota is working.
_, c := newTestCache(t)
// First set free space quota very small and check it is OK
c.opt.CacheMinFreeSpace = 1
assert.True(t, c.minFreeSpaceQuotaOK())
assert.True(t, c.quotasOK())
// Now set it a bit larger than the current disk available and check it is BAD
c.opt.CacheMinFreeSpace = fs.SizeSuffix(du.Available) + fs.Gibi
assert.False(t, c.minFreeSpaceQuotaOK())
assert.False(t, c.quotasOK())
}
// test reset clean files
func TestCachePurgeClean(t *testing.T) {
r, c := newItemTestCache(t)
contents, obj, potato1 := newFile(t, r, c, "existing")
_ = contents
// Open the object to create metadata for it
require.NoError(t, potato1.Open(obj))
require.NoError(t, potato1.Open(obj))
size, err := potato1.GetSize()
require.NoError(t, err)
assert.Equal(t, int64(100), size)
// Read something to instantiate the cache file
buf := make([]byte, 10)
_, err = potato1.ReadAt(buf, 10)
require.NoError(t, err)
// Test cache file present
_, err = os.Stat(potato1.c.toOSPath(potato1.name))
require.NoError(t, err)
// Add some potatoes
potato2 := c.Item("sub/dir/potato2")
require.NoError(t, potato2.Open(nil))
require.NoError(t, potato2.Truncate(5))
potato3 := c.Item("sub/dir/potato3")
require.NoError(t, potato3.Open(nil))
require.NoError(t, potato3.Truncate(6))
c.updateUsed()
c.opt.CacheMaxSize = 1
c.purgeClean()
assert.Equal(t, []string{
`name="existing" opens=2 size=100 space=0`,
`name="sub/dir/potato2" opens=1 size=5 space=5`,
`name="sub/dir/potato3" opens=1 size=6 space=6`,
}, itemSpaceAsString(c))
assert.Equal(t, int64(11), c.used)
require.NoError(t, potato2.Close(nil))
c.opt.CacheMaxSize = 1
c.purgeClean()
assert.Equal(t, []string{
`name="existing" opens=2 size=100 space=0`,
`name="sub/dir/potato3" opens=1 size=6 space=6`,
}, itemSpaceAsString(c))
assert.Equal(t, int64(6), c.used)
require.NoError(t, potato1.Close(nil))
require.NoError(t, potato1.Close(nil))
require.NoError(t, potato3.Close(nil))
// Remove all files now. The are all not in use.
// purgeClean does not remove empty cache files. purgeOverQuota does.
// So we use purgeOverQuota here for the cleanup.
c.opt.CacheMaxSize = 1
c.purgeOverQuota()
c.purgeEmptyDirs("", true)
assert.Equal(t, []string(nil), itemAsString(c))
}
func TestCacheInUse(t *testing.T) {
_, c := newTestCache(t)
assert.False(t, c.InUse("potato"))
potato := c.Item("potato")
assert.False(t, c.InUse("potato"))
require.NoError(t, potato.Open(nil))
assert.True(t, c.InUse("potato"))
require.NoError(t, potato.Close(nil))
assert.False(t, c.InUse("potato"))
}
func TestCacheDirtyItem(t *testing.T) {
_, c := newTestCache(t)
assert.Nil(t, c.DirtyItem("potato"))
potato := c.Item("potato")
assert.Nil(t, c.DirtyItem("potato"))
require.NoError(t, potato.Open(nil))
require.NoError(t, potato.Truncate(5))
assert.Equal(t, potato, c.DirtyItem("potato"))
require.NoError(t, potato.Close(nil))
assert.Nil(t, c.DirtyItem("potato"))
}
func TestCacheExistsAndRemove(t *testing.T) {
_, c := newTestCache(t)
assert.False(t, c.Exists("potato"))
potato := c.Item("potato")
assert.False(t, c.Exists("potato"))
require.NoError(t, potato.Open(nil))
assert.True(t, c.Exists("potato"))
require.NoError(t, potato.Close(nil))
assert.True(t, c.Exists("potato"))
c.Remove("potato")
assert.False(t, c.Exists("potato"))
}
func TestCacheRename(t *testing.T) {
_, c := newTestCache(t)
// setup
assert.False(t, c.Exists("potato"))
potato := c.Item("potato")
require.NoError(t, potato.Open(nil))
require.NoError(t, potato.Close(nil))
assert.True(t, c.Exists("potato"))
osPath := c.toOSPath("potato")
osPathMeta := c.toOSPathMeta("potato")
assertPathExist(t, osPath)
assertPathExist(t, osPathMeta)
// rename potato -> newPotato
require.NoError(t, c.Rename("potato", "newPotato", nil))
assertPathNotExist(t, osPath)
assertPathNotExist(t, osPathMeta)
assert.False(t, c.Exists("potato"))
osPath = c.toOSPath("newPotato")
osPathMeta = c.toOSPathMeta("newPotato")
assertPathExist(t, osPath)
assertPathExist(t, osPathMeta)
assert.True(t, c.Exists("newPotato"))
// rename newPotato -> sub/newPotato
require.NoError(t, c.Rename("newPotato", "sub/newPotato", nil))
assertPathNotExist(t, osPath)
assertPathNotExist(t, osPathMeta)
assert.False(t, c.Exists("potato"))
osPath = c.toOSPath("sub/newPotato")
osPathMeta = c.toOSPathMeta("sub/newPotato")
assertPathExist(t, osPath)
assertPathExist(t, osPathMeta)
assert.True(t, c.Exists("sub/newPotato"))
// remove
c.Remove("sub/newPotato")
assertPathNotExist(t, osPath)
assertPathNotExist(t, osPathMeta)
assert.False(t, c.Exists("sub/newPotato"))
// nonexistent file - is ignored
assert.NoError(t, c.Rename("nonexist", "nonexist2", nil))
}
func TestCacheCleaner(t *testing.T) {
opt := vfscommon.Opt
opt.CachePollInterval = fs.Duration(10 * time.Millisecond)
opt.CacheMaxAge = fs.Duration(20 * time.Millisecond)
_, c := newTestCacheOpt(t, opt)
time.Sleep(time.Duration(2 * opt.CachePollInterval))
potato := c.Item("potato")
potato2, found := c.get("potato")
assert.Equal(t, fmt.Sprintf("%p", potato), fmt.Sprintf("%p", potato2))
assert.True(t, found)
for range 100 {
time.Sleep(time.Duration(10 * opt.CachePollInterval))
potato2, found = c.get("potato")
if !found {
break
}
}
assert.NotEqual(t, fmt.Sprintf("%p", potato), fmt.Sprintf("%p", potato2))
assert.False(t, found)
}
func TestCacheSetModTime(t *testing.T) {
_, c := newTestCache(t)
t1 := time.Date(2010, 1, 2, 3, 4, 5, 9, time.UTC)
potato := c.Item("potato")
require.NoError(t, potato.Open(nil))
require.NoError(t, potato.Truncate(5))
require.NoError(t, potato.Close(nil))
c.SetModTime("potato", t1)
osPath := potato.c.toOSPath("potato")
fi, err := os.Stat(osPath)
require.NoError(t, err)
fstest.AssertTimeEqualWithPrecision(t, "potato", t1, fi.ModTime(), time.Second)
}
func TestCacheTotaInUse(t *testing.T) {
_, c := newTestCache(t)
assert.Equal(t, int(0), c.TotalInUse())
potato := c.Item("potato")
assert.Equal(t, int(0), c.TotalInUse())
require.NoError(t, potato.Open(nil))
assert.Equal(t, int(1), c.TotalInUse())
require.NoError(t, potato.Truncate(5))
assert.Equal(t, int(1), c.TotalInUse())
potato2 := c.Item("potato2")
assert.Equal(t, int(1), c.TotalInUse())
require.NoError(t, potato2.Open(nil))
assert.Equal(t, int(2), c.TotalInUse())
require.NoError(t, potato2.Close(nil))
assert.Equal(t, int(1), c.TotalInUse())
require.NoError(t, potato.Close(nil))
assert.Equal(t, int(0), c.TotalInUse())
}
func TestCacheDump(t *testing.T) {
_, c := newTestCache(t)
out := (*Cache)(nil).Dump()
assert.Equal(t, "Cache: <nil>\n", out)
out = c.Dump()
assert.Equal(t, "Cache{\n}\n", out)
c.Item("potato")
out = c.Dump()
want := "Cache{\n\t\"potato\": "
assert.Equal(t, want, out[:len(want)])
c.Remove("potato")
out = c.Dump()
assert.Equal(t, "Cache{\n}\n", out)
}
func TestCacheStats(t *testing.T) {
_, c := newTestCache(t)
out := c.Stats()
assert.Equal(t, int64(0), out["bytesUsed"])
assert.Equal(t, 0, out["erroredFiles"])
assert.Equal(t, 0, out["files"])
assert.Equal(t, 0, out["uploadsInProgress"])
assert.Equal(t, 0, out["uploadsQueued"])
}
func TestCacheQueue(t *testing.T) {
_, c := newTestCache(t)
out := c.Queue()
// We've checked the contents of queue in the writeback tests
// Just check it is present here
queue, found := out["queue"]
require.True(t, found)
_, ok := queue.([]writeback.QueueInfo)
require.True(t, ok)
}
func TestCacheQueueSetExpiry(t *testing.T) {
_, c := newTestCache(t)
// Check this returns the correct error when called so we know
// it is plumbed in correctly. The actual tests are done in
// writeback.
err := c.QueueSetExpiry(123123, time.Now(), 0)
assert.Equal(t, writeback.ErrorIDNotFound, err)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscache/item.go | vfs/vfscache/item.go | package vfscache
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"sync"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/lib/file"
"github.com/rclone/rclone/lib/ranges"
"github.com/rclone/rclone/vfs/vfscache/downloaders"
"github.com/rclone/rclone/vfs/vfscache/writeback"
)
// NB as Cache and Item are tightly linked it is necessary to have a
// total lock ordering between them. So Cache.mu must always be
// taken before Item.mu to avoid deadlocks.
//
// Cache may call into Item but care is needed if Item calls Cache
//
// A lot of the Cache methods do not require locking, these include
//
// - Cache.toOSPath
// - Cache.toOSPathMeta
// - Cache.createItemDir
// - Cache.objectFingerprint
// - Cache.AddVirtual
// NB Item and downloader are tightly linked so it is necessary to
// have a total lock ordering between them. downloader.mu must always
// be taken before Item.mu. downloader may call into Item but Item may
// **not** call downloader methods with Item.mu held
// NB Item and writeback are tightly linked so it is necessary to
// have a total lock ordering between them. writeback.mu must always
// be taken before Item.mu. writeback may call into Item but Item may
// **not** call writeback methods with Item.mu held
// LL Item reset is invoked by cache cleaner for synchronous recovery
// from ENOSPC errors. The reset operation removes the cache file and
// closes/reopens the downloaders. Although most parts of reset and
// other item operations are done with the item mutex held, the mutex
// is released during fd.WriteAt and downloaders calls. We use preAccess
// and postAccess calls to serialize reset and other item operations.
// Item is stored in the item map
//
// The Info field is written to the backing store to store status
type Item struct {
// read only
c *Cache // cache this is part of
mu sync.Mutex // protect the variables
cond sync.Cond // synchronize with cache cleaner
name string // name in the VFS
opens int // number of times file is open
downloaders *downloaders.Downloaders // a record of the downloaders in action - may be nil
o fs.Object // object we are caching - may be nil
fd *os.File // handle we are using to read and write to the file
info Info // info about the file to persist to backing store
writeBackID writeback.Handle // id of any writebacks in progress
pendingAccesses int // number of threads - cache reset not allowed if not zero
modified bool // set if the file has been modified since the last Open
beingReset bool // cache cleaner is resetting the cache file, access not allowed
}
// Info is persisted to backing store
type Info struct {
ModTime time.Time // last time file was modified
ATime time.Time // last time file was accessed
Size int64 // size of the file
Rs ranges.Ranges // which parts of the file are present
Fingerprint string // fingerprint of remote object
Dirty bool // set if the backing file has been modified
}
// Items are a slice of *Item ordered by ATime
type Items []*Item
// ResetResult reports the actual action taken in the Reset function and reason
type ResetResult int
// Constants used to report actual action taken in the Reset function and reason
const (
SkippedDirty ResetResult = iota // Dirty item cannot be reset
SkippedPendingAccess // Reset pending access can lead to deadlock
SkippedEmpty // Reset empty item does not save space
RemovedNotInUse // Item not used. Remove instead of reset
ResetFailed // Reset failed with an error
ResetComplete // Reset completed successfully
)
func (rr ResetResult) String() string {
return [...]string{"Dirty item skipped", "In-access item skipped", "Empty item skipped",
"Not-in-use item removed", "Item reset failed", "Item reset completed"}[rr]
}
func (v Items) Len() int { return len(v) }
func (v Items) Swap(i, j int) { v[i], v[j] = v[j], v[i] }
func (v Items) Less(i, j int) bool {
if i == j {
return false
}
iItem := v[i]
jItem := v[j]
iItem.mu.Lock()
defer iItem.mu.Unlock()
jItem.mu.Lock()
defer jItem.mu.Unlock()
return iItem.info.ATime.Before(jItem.info.ATime)
}
// clean the item after its cache file has been deleted
func (info *Info) clean() {
*info = Info{}
info.ModTime = time.Now()
info.ATime = info.ModTime
}
// StoreFn is called back with an object after it has been uploaded
type StoreFn func(fs.Object)
// newItem returns an item for the cache
func newItem(c *Cache, name string) (item *Item) {
now := time.Now()
item = &Item{
c: c,
name: name,
info: Info{
ModTime: now,
ATime: now,
},
}
item.cond = sync.Cond{L: &item.mu}
// check the cache file exists
osPath := c.toOSPath(name)
fi, statErr := os.Stat(osPath)
if statErr != nil {
if os.IsNotExist(statErr) {
item._removeMeta("cache file doesn't exist")
} else {
item.remove(fmt.Sprintf("failed to stat cache file: %v", statErr))
}
}
// Try to load the metadata
exists, err := item.load()
if !exists {
item._removeFile("metadata doesn't exist")
} else if err != nil {
item.remove(fmt.Sprintf("failed to load metadata: %v", err))
}
// Get size estimate (which is best we can do until Open() called)
if statErr == nil {
item.info.Size = fi.Size()
}
return item
}
// inUse returns true if the item is open or dirty
func (item *Item) inUse() bool {
item.mu.Lock()
defer item.mu.Unlock()
return item.opens != 0 || item.info.Dirty
}
// getDiskSize returns the size on disk (approximately) of the item
//
// We return the sizes of the chunks we have fetched, however there is
// likely to be some overhead which we are not taking into account.
func (item *Item) getDiskSize() int64 {
item.mu.Lock()
defer item.mu.Unlock()
return item.info.Rs.Size()
}
// load reads an item from the disk or returns nil if not found
func (item *Item) load() (exists bool, err error) {
item.mu.Lock()
defer item.mu.Unlock()
osPathMeta := item.c.toOSPathMeta(item.name) // No locking in Cache
in, err := os.Open(osPathMeta)
if err != nil {
if os.IsNotExist(err) {
return false, err
}
return true, fmt.Errorf("vfs cache item: failed to read metadata: %w", err)
}
defer fs.CheckClose(in, &err)
decoder := json.NewDecoder(in)
err = decoder.Decode(&item.info)
if err != nil {
return true, fmt.Errorf("vfs cache item: corrupt metadata: %w", err)
}
return true, nil
}
// save writes an item to the disk
//
// call with the lock held
func (item *Item) _save() (err error) {
osPathMeta := item.c.toOSPathMeta(item.name) // No locking in Cache
out, err := os.Create(osPathMeta)
if err != nil {
return fmt.Errorf("vfs cache item: failed to write metadata: %w", err)
}
defer fs.CheckClose(out, &err)
encoder := json.NewEncoder(out)
encoder.SetIndent("", "\t")
err = encoder.Encode(item.info)
if err != nil {
return fmt.Errorf("vfs cache item: failed to encode metadata: %w", err)
}
return nil
}
// truncate the item to the given size, creating it if necessary
//
// this does not mark the object as dirty
//
// call with the lock held
func (item *Item) _truncate(size int64) (err error) {
if size < 0 {
// FIXME ignore unknown length files
return nil
}
// Use open handle if available
fd := item.fd
if fd == nil {
// If the metadata says we have some blocks cached then the
// file should exist, so open without O_CREATE
oFlags := os.O_WRONLY
if item.info.Rs.Size() == 0 {
oFlags |= os.O_CREATE
}
osPath := item.c.toOSPath(item.name) // No locking in Cache
fd, err = file.OpenFile(osPath, oFlags, 0600)
if err != nil && os.IsNotExist(err) {
// If the metadata has info but the file doesn't
// not exist then it has been externally removed
fs.Errorf(item.name, "vfs cache: detected external removal of cache file")
item.info.Rs = nil // show we have no blocks cached
item.info.Dirty = false // file can't be dirty if it doesn't exist
item._removeMeta("cache file externally deleted")
fd, err = file.OpenFile(osPath, os.O_CREATE|os.O_WRONLY, 0600)
}
if err != nil {
return fmt.Errorf("vfs cache: truncate: failed to open cache file: %w", err)
}
defer fs.CheckClose(fd, &err)
err = file.SetSparse(fd)
if err != nil {
fs.Errorf(item.name, "vfs cache: truncate: failed to set as a sparse file: %v", err)
}
}
// Check to see what the current size is, and don't truncate
// if it is already the correct size.
//
// Apparently Windows Defender likes to check executables each
// time they are modified, and truncating a file to its
// existing size is enough to trigger the Windows Defender
// scan. This was causing a big slowdown for operations which
// opened and closed the file a lot, such as looking at
// properties on an executable.
fi, err := fd.Stat()
if err == nil && fi.Size() == size {
fs.Debugf(item.name, "vfs cache: truncate to size=%d (not needed as size correct)", size)
} else {
fs.Debugf(item.name, "vfs cache: truncate to size=%d", size)
err = fd.Truncate(size)
if err != nil {
return fmt.Errorf("vfs cache: truncate: %w", err)
}
}
item.info.Size = size
return nil
}
// Truncate the item to the current size, creating if necessary
//
// This does not mark the object as dirty.
//
// call with the lock held
func (item *Item) _truncateToCurrentSize() (err error) {
size, err := item._getSize()
if err != nil && !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("truncate to current size: %w", err)
}
if size < 0 {
// FIXME ignore unknown length files
return nil
}
err = item._truncate(size)
if err != nil {
return err
}
return nil
}
// Truncate the item to the given size, creating it if necessary
//
// If the new size is shorter than the existing size then the object
// will be shortened and marked as dirty.
//
// If the new size is longer than the old size then the object will be
// extended and the extended data will be filled with zeros. The
// object will be marked as dirty in this case also.
func (item *Item) Truncate(size int64) (err error) {
item.preAccess()
defer item.postAccess()
item.mu.Lock()
defer item.mu.Unlock()
if item.fd == nil {
return errors.New("vfs cache item truncate: internal error: didn't Open file")
}
// Read old size
oldSize, err := item._getSize()
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
return fmt.Errorf("truncate failed to read size: %w", err)
}
oldSize = 0
}
err = item._truncate(size)
if err != nil {
return err
}
changed := true
if size > oldSize {
// Truncate extends the file in which case all new bytes are
// read as zeros. In this case we must show we have written to
// the new parts of the file.
item._written(oldSize, size)
} else if size < oldSize {
// Truncate shrinks the file so clip the downloaded ranges
item.info.Rs = item.info.Rs.Intersection(ranges.Range{Pos: 0, Size: size})
} else {
changed = item.o == nil
}
if changed {
item._dirty()
}
return nil
}
// _stat gets the current stat of the backing file
//
// Call with mutex held
func (item *Item) _stat() (fi os.FileInfo, err error) {
if item.fd != nil {
return item.fd.Stat()
}
osPath := item.c.toOSPath(item.name) // No locking in Cache
return os.Stat(osPath)
}
// _getSize gets the current size of the item and updates item.info.Size
//
// Call with mutex held
func (item *Item) _getSize() (size int64, err error) {
fi, err := item._stat()
if err != nil {
if os.IsNotExist(err) && item.o != nil {
size = item.o.Size()
err = nil
}
} else {
size = fi.Size()
}
if err == nil {
item.info.Size = size
}
return size, err
}
// GetName gets the vfs name of the item
func (item *Item) GetName() (name string) {
item.mu.Lock()
defer item.mu.Unlock()
return item.name
}
// GetSize gets the current size of the item
func (item *Item) GetSize() (size int64, err error) {
item.mu.Lock()
defer item.mu.Unlock()
return item._getSize()
}
// _exists returns whether the backing file for the item exists or not
//
// call with mutex held
func (item *Item) _exists() bool {
osPath := item.c.toOSPath(item.name) // No locking in Cache
_, err := os.Stat(osPath)
return err == nil
}
// Exists returns whether the backing file for the item exists or not
func (item *Item) Exists() bool {
item.mu.Lock()
defer item.mu.Unlock()
return item._exists()
}
// _dirty marks the item as changed and needing writeback
//
// call with lock held
func (item *Item) _dirty() {
item.info.ModTime = time.Now()
item.info.ATime = item.info.ModTime
if !item.modified {
item.modified = true
item.mu.Unlock()
item.c.writeback.Remove(item.writeBackID)
item.mu.Lock()
}
if !item.info.Dirty {
item.info.Dirty = true
err := item._save()
if err != nil {
fs.Errorf(item.name, "vfs cache: failed to save item info: %v", err)
}
}
}
// Dirty marks the item as changed and needing writeback
func (item *Item) Dirty() {
item.preAccess()
defer item.postAccess()
item.mu.Lock()
item._dirty()
item.mu.Unlock()
}
// IsDirty returns true if the item data is dirty
func (item *Item) IsDirty() bool {
item.mu.Lock()
defer item.mu.Unlock()
return item.info.Dirty
}
// Create the cache file and store the metadata on disk
// Called with item.mu locked
func (item *Item) _createFile(osPath string) (err error) {
if item.fd != nil {
return errors.New("vfs cache item: internal error: didn't Close file")
}
item.modified = false
// t0 := time.Now()
fd, err := file.OpenFile(osPath, os.O_RDWR, 0600)
// fs.Debugf(item.name, "OpenFile took %v", time.Since(t0))
if err != nil {
return fmt.Errorf("vfs cache item: open failed: %w", err)
}
err = file.SetSparse(fd)
if err != nil {
fs.Errorf(item.name, "vfs cache: failed to set as a sparse file: %v", err)
}
item.fd = fd
err = item._save()
if err != nil {
closeErr := item.fd.Close()
if closeErr != nil {
fs.Errorf(item.name, "vfs cache: item.fd.Close: closeErr: %v", err)
}
item.fd = nil
return fmt.Errorf("vfs cache item: _save failed: %w", err)
}
return err
}
// Open the local file from the object passed in. Wraps open()
// to provide recovery from out of space error.
func (item *Item) Open(o fs.Object) (err error) {
for range fs.GetConfig(context.TODO()).LowLevelRetries {
item.preAccess()
err = item.open(o)
item.postAccess()
if err == nil {
break
}
fs.Errorf(item.name, "vfs cache: failed to open item: %v", err)
if !fserrors.IsErrNoSpace(err) && err.Error() != "no space left on device" {
fs.Errorf(item.name, "Non-out-of-space error encountered during open")
break
}
item.c.KickCleaner()
}
return err
}
// Open the local file from the object passed in (which may be nil)
// which implies we are about to create the file
func (item *Item) open(o fs.Object) (err error) {
// defer log.Trace(o, "item=%p", item)("err=%v", &err)
item.mu.Lock()
defer item.mu.Unlock()
item.info.ATime = time.Now()
osPath, err := item.c.createItemDir(item.name) // No locking in Cache
if err != nil {
return fmt.Errorf("vfs cache item: createItemDir failed: %w", err)
}
err = item._checkObject(o)
if err != nil {
return fmt.Errorf("vfs cache item: check object failed: %w", err)
}
item.opens++
if item.opens != 1 {
return nil
}
err = item._createFile(osPath)
if err != nil {
item._remove("item.open failed on _createFile, remove cache data/metadata files")
item.fd = nil
item.opens--
return fmt.Errorf("vfs cache item: create cache file failed: %w", err)
}
// Unlock the Item.mu so we can call some methods which take Cache.mu
item.mu.Unlock()
// Ensure this item is in the cache. It is possible a cache
// expiry has run and removed the item if it had no opens so
// we put it back here. If there was an item with opens
// already then return an error. This shouldn't happen because
// there should only be one vfs.File with a pointer to this
// item in at a time.
oldItem := item.c.put(item.name, item) // LOCKING in Cache method
if oldItem != nil {
oldItem.mu.Lock()
if oldItem.opens != 0 {
// Put the item back and return an error
item.c.put(item.name, oldItem) // LOCKING in Cache method
err = fmt.Errorf("internal error: item %q already open in the cache", item.name)
}
oldItem.mu.Unlock()
}
// Relock the Item.mu for the return
item.mu.Lock()
// Create the downloaders
if item.o != nil {
item.downloaders = downloaders.New(item, item.c.opt, item.name, item.o)
}
return err
}
// Calls f with mu unlocked, re-locking mu if a panic is raised
//
// mu must be locked when calling this function
func unlockMutexForCall(mu *sync.Mutex, f func()) {
mu.Unlock()
defer mu.Lock()
f()
}
// Store stores the local cache file to the remote object, returning
// the new remote object. objOld is the old object if known.
//
// Call with lock held
func (item *Item) _store(ctx context.Context, storeFn StoreFn) (err error) {
// defer log.Trace(item.name, "item=%p", item)("err=%v", &err)
// Transfer the temp file to the remote
cacheObj, err := item.c.fcache.NewObject(ctx, item.name)
if err != nil && err != fs.ErrorObjectNotFound {
return fmt.Errorf("vfs cache: failed to find cache file: %w", err)
}
// Object has disappeared if cacheObj == nil
if cacheObj != nil {
o, name := item.o, item.name
unlockMutexForCall(&item.mu, func() {
o, err = operations.Copy(ctx, item.c.fremote, o, name, cacheObj)
})
if err != nil {
if errors.Is(err, fs.ErrorCantUploadEmptyFiles) {
fs.Errorf(name, "Writeback failed: %v", err)
return nil
}
return fmt.Errorf("vfs cache: failed to transfer file from cache to remote: %w", err)
}
item.o = o
item._updateFingerprint()
}
// Write the object back to the VFS layer before we mark it as
// clean, otherwise it will become eligible for removal which
// can cause a deadlock
if storeFn != nil && item.o != nil {
fs.Debugf(item.name, "vfs cache: writeback object to VFS layer")
// Write the object back to the VFS layer last with mutex unlocked
o := item.o
item.mu.Unlock()
storeFn(o)
item.mu.Lock()
}
// Show item is clean and is eligible for cache removal
item.info.Dirty = false
err = item._save()
if err != nil {
fs.Errorf(item.name, "vfs cache: failed to write metadata file: %v", err)
}
return nil
}
// Store stores the local cache file to the remote object, returning
// the new remote object. objOld is the old object if known.
func (item *Item) store(ctx context.Context, storeFn StoreFn) (err error) {
item.mu.Lock()
defer item.mu.Unlock()
return item._store(ctx, storeFn)
}
// Close the cache file
func (item *Item) Close(storeFn StoreFn) (err error) {
// defer log.Trace(item.o, "Item.Close")("err=%v", &err)
item.preAccess()
defer item.postAccess()
var (
downloaders *downloaders.Downloaders
syncWriteBack = item.c.opt.WriteBack <= 0
)
item.mu.Lock()
defer item.mu.Unlock()
item.info.ATime = time.Now()
item.opens--
if item.opens < 0 {
return os.ErrClosed
} else if item.opens > 0 {
return nil
}
// Update the size on close
_, _ = item._getSize()
// If the file is dirty ensure any segments not transferred
// are brought in first.
//
// FIXME It would be nice to do this asynchronously however it
// would require keeping the downloaders alive after the item
// has been closed
if item.info.Dirty && item.o != nil {
err = item._ensure(0, item.info.Size)
if err != nil {
return fmt.Errorf("vfs cache: failed to download missing parts of cache file: %w", err)
}
}
// Accumulate and log errors
checkErr := func(e error) {
if e != nil {
fs.Errorf(item.o, "vfs cache: item close failed: %v", e)
if err == nil {
err = e
}
}
}
// Close the downloaders
if downloaders = item.downloaders; downloaders != nil {
item.downloaders = nil
// FIXME need to unlock to kill downloader - should we
// re-arrange locking so this isn't necessary? maybe
// downloader should use the item mutex for locking? or put a
// finer lock on Rs?
//
// downloader.Write calls ensure which needs the lock
// close downloader with mutex unlocked
item.mu.Unlock()
checkErr(downloaders.Close(nil))
item.mu.Lock()
}
// close the file handle
if item.fd == nil {
checkErr(errors.New("vfs cache item: internal error: didn't Open file"))
} else {
checkErr(item.fd.Close())
item.fd = nil
}
// save the metadata once more since it may be dirty
// after the downloader
checkErr(item._save())
// if the item hasn't been changed but has been completed then
// set the modtime from the object otherwise set it from the info
if item._exists() {
if !item.info.Dirty && item.o != nil {
item._setModTime(item.o.ModTime(context.Background()))
} else {
item._setModTime(item.info.ModTime)
}
}
// upload the file to backing store if changed
if item.info.Dirty {
fs.Infof(item.name, "vfs cache: queuing for upload in %v", item.c.opt.WriteBack)
if syncWriteBack {
// do synchronous writeback
checkErr(item._store(context.Background(), storeFn))
} else {
// asynchronous writeback
item.c.writeback.SetID(&item.writeBackID)
id := item.writeBackID
item.mu.Unlock()
item.c.writeback.Add(id, item.name, item.info.Size, item.modified, func(ctx context.Context) error {
return item.store(ctx, storeFn)
})
item.mu.Lock()
}
}
// mark as not modified now we have uploaded or queued for upload
item.modified = false
return err
}
// reload is called with valid items recovered from a cache reload.
//
// If they are dirty then it makes sure they get uploaded.
//
// it is called before the cache has started so opens will be 0 and
// metaDirty will be false.
func (item *Item) reload(ctx context.Context) error {
item.mu.Lock()
dirty := item.info.Dirty
item.mu.Unlock()
if !dirty {
return nil
}
// see if the object still exists
obj, _ := item.c.fremote.NewObject(ctx, item.name)
// open the file with the object (or nil)
err := item.Open(obj)
if err != nil {
return err
}
// close the file to execute the writeback if needed
err = item.Close(nil)
if err != nil {
return err
}
// put the file into the directory listings
size, err := item._getSize()
if err != nil {
return fmt.Errorf("reload: failed to read size: %w", err)
}
err = item.c.AddVirtual(item.name, size, false)
if err != nil {
return fmt.Errorf("reload: failed to add virtual dir entry: %w", err)
}
return nil
}
// check the fingerprint of an object and update the item or delete
// the cached file accordingly
//
// If we have local modifications then they take precedence
// over a change in the remote
//
// It ensures the file is the correct size for the object.
//
// call with lock held
func (item *Item) _checkObject(o fs.Object) error {
if o == nil {
if item.info.Fingerprint != "" {
// no remote object && local object
// remove local object unless dirty
if !item.info.Dirty {
item._remove("stale (remote deleted)")
} else {
fs.Debugf(item.name, "vfs cache: remote object has gone but local object modified - keeping it")
}
//} else {
// no remote object && no local object
// OK
}
} else {
remoteFingerprint := fs.Fingerprint(context.TODO(), o, item.c.opt.FastFingerprint)
fs.Debugf(item.name, "vfs cache: checking remote fingerprint %q against cached fingerprint %q", remoteFingerprint, item.info.Fingerprint)
if item.info.Fingerprint != "" {
// remote object && local object
if remoteFingerprint != item.info.Fingerprint {
if !item.info.Dirty {
fs.Debugf(item.name, "vfs cache: removing cached entry as stale (remote fingerprint %q != cached fingerprint %q)", remoteFingerprint, item.info.Fingerprint)
item._remove("stale (remote is different)")
item.info.Fingerprint = remoteFingerprint
} else {
fs.Debugf(item.name, "vfs cache: remote object has changed but local object modified - keeping it (remote fingerprint %q != cached fingerprint %q)", remoteFingerprint, item.info.Fingerprint)
}
}
} else {
// remote object && no local object
// Set fingerprint
item.info.Fingerprint = remoteFingerprint
}
item.info.Size = o.Size()
}
item.o = o
err := item._truncateToCurrentSize()
if err != nil {
return fmt.Errorf("vfs cache item: open truncate failed: %w", err)
}
return nil
}
// WrittenBack checks to see if the item has been written back or not
func (item *Item) WrittenBack() bool {
item.mu.Lock()
defer item.mu.Unlock()
return item.info.Fingerprint != ""
}
// remove the cached file
//
// call with lock held
func (item *Item) _removeFile(reason string) {
osPath := item.c.toOSPath(item.name) // No locking in Cache
err := os.Remove(osPath)
if err != nil {
if !os.IsNotExist(err) {
fs.Errorf(item.name, "vfs cache: failed to remove cache file as %s: %v", reason, err)
}
} else {
fs.Infof(item.name, "vfs cache: removed cache file as %s", reason)
}
}
// remove the metadata
//
// call with lock held
func (item *Item) _removeMeta(reason string) {
osPathMeta := item.c.toOSPathMeta(item.name) // No locking in Cache
err := os.Remove(osPathMeta)
if err != nil {
if !os.IsNotExist(err) {
fs.Errorf(item.name, "vfs cache: failed to remove metadata from cache as %s: %v", reason, err)
}
} else {
fs.Debugf(item.name, "vfs cache: removed metadata from cache as %s", reason)
}
}
// remove the cached file and empty the metadata
//
// This returns true if the file was in the transfer queue so may not
// have completely uploaded yet.
//
// call with lock held
func (item *Item) _remove(reason string) (wasWriting bool) {
// Cancel writeback, if any
item.mu.Unlock()
wasWriting = item.c.writeback.Remove(item.writeBackID)
item.mu.Lock()
item.info.clean()
item._removeFile(reason)
item._removeMeta(reason)
return wasWriting
}
// remove the cached file and empty the metadata
//
// This returns true if the file was in the transfer queue so may not
// have completely uploaded yet.
func (item *Item) remove(reason string) (wasWriting bool) {
item.mu.Lock()
defer item.mu.Unlock()
return item._remove(reason)
}
// RemoveNotInUse is called to remove cache file that has not been accessed recently
// It may also be called for removing empty cache files too when the quota is already reached.
func (item *Item) RemoveNotInUse(maxAge time.Duration, emptyOnly bool) (removed bool, spaceFreed int64) {
item.mu.Lock()
defer item.mu.Unlock()
spaceFreed = 0
removed = false
if item.opens != 0 || item.info.Dirty {
return
}
removeIt := false
if maxAge == 0 {
removeIt = true // quota-driven removal
}
if maxAge != 0 {
cutoff := time.Now().Add(-maxAge)
// If not locked and access time too long ago - delete the file
accessTime := item.info.ATime
if accessTime.Sub(cutoff) <= 0 {
removeIt = true
}
}
if removeIt {
spaceUsed := item.info.Rs.Size()
if !emptyOnly || spaceUsed == 0 {
spaceFreed = spaceUsed
removed = true
if item._remove("Removing old cache file not in use") {
fs.Errorf(item.name, "item removed when it was writing/uploaded")
}
}
}
return
}
// Reset is called by the cache purge functions only to reset (empty the contents) cache files that
// are not dirty. It is used when cache space runs out and we see some ENOSPC error.
func (item *Item) Reset() (rr ResetResult, spaceFreed int64, err error) {
item.mu.Lock()
defer item.mu.Unlock()
// The item is not being used now. Just remove it instead of resetting it.
if item.opens == 0 && !item.info.Dirty {
spaceFreed = item.info.Rs.Size()
if item._remove("Removing old cache file not in use") {
fs.Errorf(item.name, "item removed when it was writing/uploaded")
}
return RemovedNotInUse, spaceFreed, nil
}
// do not reset dirty file
if item.info.Dirty {
return SkippedDirty, 0, nil
}
/* A wait on pendingAccessCnt to become 0 can lead to deadlock when an item.Open bumps
up the pendingAccesses count, calls item.open, which calls cache.put. The cache.put
operation needs the cache mutex, which is held here. We skip this file now. The
caller (the cache cleaner thread) may retry resetting this item if the cache size does
not reduce below quota. */
if item.pendingAccesses > 0 {
return SkippedPendingAccess, 0, nil
}
/* Do not need to reset an empty cache file unless it was being reset and the reset failed.
Some thread(s) may be waiting on the reset's successful completion in that case. */
if item.info.Rs.Size() == 0 && !item.beingReset {
return SkippedEmpty, 0, nil
}
item.beingReset = true
/* Error handling from this point on (setting item.fd and item.beingReset):
Since Reset is called by the cache cleaner thread, there is no direct way to return
the error to the io threads. Set item.fd to nil upon internal errors, so that the
io threads will return internal errors seeing a nil fd. In the case when the error
is ENOSPC, keep the item in isBeingReset state and that will keep the item.ReadAt
waiting at its beginning. The cache purge loop will try to redo the reset after cache
space is made available again. This recovery design should allow most io threads to
eventually go through, unless large files are written/overwritten concurrently and
the total size of these files exceed the cache storage limit. */
// Close the downloaders
// Accumulate and log errors
checkErr := func(e error) {
if e != nil {
fs.Errorf(item.o, "vfs cache: item reset failed: %v", e)
if err == nil {
err = e
}
}
}
if downloaders := item.downloaders; downloaders != nil {
item.downloaders = nil
// FIXME need to unlock to kill downloader - should we
// re-arrange locking so this isn't necessary? maybe
// downloader should use the item mutex for locking? or put a
// finer lock on Rs?
//
// downloader.Write calls ensure which needs the lock
// close downloader with mutex unlocked
item.mu.Unlock()
checkErr(downloaders.Close(nil))
item.mu.Lock()
}
// close the file handle
// fd can be nil if we tried Reset and failed before because of ENOSPC during reset
if item.fd != nil {
checkErr(item.fd.Close())
if err != nil {
// Could not close the cache file
item.beingReset = false
item.cond.Broadcast()
return ResetFailed, 0, err
}
item.fd = nil
}
spaceFreed = item.info.Rs.Size()
// This should not be possible. We get here only if cache data is not dirty.
if item._remove("cache out of space, item is clean") {
fs.Errorf(item.o, "vfs cache item removed when it was writing/uploaded")
}
// can we have an item with no dirty data (so that we can get here) and nil item.o at the same time?
fso := item.o
checkErr(item._checkObject(fso))
if err != nil {
item.beingReset = false
item.cond.Broadcast()
return ResetFailed, spaceFreed, err
}
osPath := item.c.toOSPath(item.name)
checkErr(item._createFile(osPath))
if err != nil {
item._remove("cache reset failed on _createFile, removed cache data file")
item.fd = nil // This allows a new Reset redo to have a clean state to deal with
if !fserrors.IsErrNoSpace(err) {
item.beingReset = false
item.cond.Broadcast()
}
return ResetFailed, spaceFreed, err
}
// Create the downloaders
if item.o != nil {
item.downloaders = downloaders.New(item, item.c.opt, item.name, item.o)
}
/* The item will stay in the beingReset state if we get an error that prevents us from
reaching this point. The cache purge loop will redo the failed Reset. */
item.beingReset = false
item.cond.Broadcast()
return ResetComplete, spaceFreed, err
}
// ProtectCache either waits for an ongoing cache reset to finish or increases pendingReads
// to protect against cache reset on this item while the thread potentially uses the cache file
// Cache cleaner waits until pendingReads is zero before resetting cache.
func (item *Item) preAccess() {
item.mu.Lock()
defer item.mu.Unlock()
if item.beingReset {
for {
item.cond.Wait()
if !item.beingReset {
break
}
}
}
item.pendingAccesses++
}
// postAccess reduces the pendingReads count enabling cache reset upon ENOSPC
func (item *Item) postAccess() {
item.mu.Lock()
defer item.mu.Unlock()
item.pendingAccesses--
item.cond.Broadcast()
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | true |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscache/downloaders/downloaders_test.go | vfs/vfscache/downloaders/downloaders_test.go | package downloaders
import (
"context"
"io"
"sync"
"testing"
"time"
_ "github.com/rclone/rclone/backend/local"
"github.com/rclone/rclone/fs/operations"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/ranges"
"github.com/rclone/rclone/lib/readers"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestMain drives the tests
func TestMain(m *testing.M) {
fstest.TestMain(m)
}
type testItem struct {
mu sync.Mutex
t *testing.T
rs ranges.Ranges
size int64
}
// HasRange returns true if the current ranges entirely include range
func (item *testItem) HasRange(r ranges.Range) bool {
item.mu.Lock()
defer item.mu.Unlock()
return item.rs.Present(r)
}
// FindMissing adjusts r returning a new ranges.Range which only
// contains the range which needs to be downloaded. This could be
// empty - check with IsEmpty. It also adjust this to make sure it is
// not larger than the file.
func (item *testItem) FindMissing(r ranges.Range) (outr ranges.Range) {
item.mu.Lock()
defer item.mu.Unlock()
outr = item.rs.FindMissing(r)
// Clip returned block to size of file
outr.Clip(item.size)
return outr
}
// WriteAtNoOverwrite writes b to the file, but will not overwrite
// already present ranges.
//
// This is used by the downloader to write bytes to the file.
//
// It returns n the total bytes processed and skipped the number of
// bytes which were processed but not actually written to the file.
func (item *testItem) WriteAtNoOverwrite(b []byte, off int64) (n int, skipped int, err error) {
item.mu.Lock()
defer item.mu.Unlock()
item.rs.Insert(ranges.Range{Pos: off, Size: int64(len(b))})
// Check contents is correct
in := readers.NewPatternReader(item.size)
checkBuf := make([]byte, len(b))
_, err = in.Seek(off, io.SeekStart)
require.NoError(item.t, err)
n, _ = in.Read(checkBuf)
require.Equal(item.t, len(b), n)
assert.Equal(item.t, checkBuf, b)
return n, 0, nil
}
func TestDownloaders(t *testing.T) {
r := fstest.NewRun(t)
var (
ctx = context.Background()
remote = "potato.txt"
size = int64(50*1024*1024 - 1234)
)
// Write the test file
in := io.NopCloser(readers.NewPatternReader(size))
src, err := operations.RcatSize(ctx, r.Fremote, remote, in, size, time.Now(), nil)
require.NoError(t, err)
assert.Equal(t, size, src.Size())
newTest := func() (*testItem, *Downloaders) {
item := &testItem{
t: t,
size: size,
}
opt := vfscommon.Opt
dls := New(item, &opt, remote, src)
return item, dls
}
cancel := func(dls *Downloaders) {
assert.NoError(t, dls.Close(nil))
}
t.Run("Download", func(t *testing.T) {
item, dls := newTest()
defer cancel(dls)
for _, r := range []ranges.Range{
{Pos: 100, Size: 250},
{Pos: 500, Size: 250},
{Pos: 25000000, Size: 250},
} {
err := dls.Download(r)
require.NoError(t, err)
assert.True(t, item.HasRange(r))
}
})
t.Run("EnsureDownloader", func(t *testing.T) {
item, dls := newTest()
defer cancel(dls)
r := ranges.Range{Pos: 40 * 1024 * 1024, Size: 250}
err := dls.EnsureDownloader(r)
require.NoError(t, err)
// FIXME racy test
assert.False(t, item.HasRange(r))
time.Sleep(time.Second)
assert.True(t, item.HasRange(r))
})
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscache/downloaders/downloaders.go | vfs/vfscache/downloaders/downloaders.go | // Package downloaders provides utilities for the VFS layer
package downloaders
import (
"context"
"errors"
"fmt"
"sync"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/accounting"
"github.com/rclone/rclone/fs/asyncreader"
"github.com/rclone/rclone/fs/chunkedreader"
"github.com/rclone/rclone/fs/fserrors"
"github.com/rclone/rclone/lib/ranges"
"github.com/rclone/rclone/vfs/vfscommon"
)
// FIXME implement max downloaders
const (
// max time a downloader can be idle before closing itself
maxDownloaderIdleTime = 5 * time.Second
// max number of bytes a reader should skip over before closing it
maxSkipBytes = 1024 * 1024
// time between background kicks of waiters to pick up errors
backgroundKickerInterval = 5 * time.Second
// maximum number of errors before declaring dead
maxErrorCount = 10
// If a downloader is within this range or --buffer-size
// whichever is the larger, we will reuse the downloader
minWindow = 1024 * 1024
)
// Item is the interface that an item to download must obey
type Item interface {
// FindMissing adjusts r returning a new ranges.Range which only
// contains the range which needs to be downloaded. This could be
// empty - check with IsEmpty. It also adjust this to make sure it is
// not larger than the file.
FindMissing(r ranges.Range) (outr ranges.Range)
// HasRange returns true if the current ranges entirely include range
HasRange(r ranges.Range) bool
// WriteAtNoOverwrite writes b to the file, but will not overwrite
// already present ranges.
//
// This is used by the downloader to write bytes to the file
//
// It returns n the total bytes processed and skipped the number of
// bytes which were processed but not actually written to the file.
WriteAtNoOverwrite(b []byte, off int64) (n int, skipped int, err error)
}
// Downloaders is a number of downloader~s and a queue of waiters
// waiting for segments to be downloaded to a file.
type Downloaders struct {
// Write once - no locking required
ctx context.Context
cancel context.CancelFunc
item Item
opt *vfscommon.Options
src fs.Object // source object
remote string
wg sync.WaitGroup
// Read write
mu sync.Mutex
dls []*downloader
waiters []waiter
errorCount int // number of consecutive errors
lastErr error // last error received
}
// waiter is a range we are waiting for and a channel to signal when
// the range is found
type waiter struct {
r ranges.Range
errChan chan<- error
}
// downloader represents a running download for part of a file.
type downloader struct {
// Write once
dls *Downloaders // parent structure
quit chan struct{} // close to quit the downloader
wg sync.WaitGroup // to keep track of downloader goroutine
kick chan struct{} // kick the downloader when needed
// Read write
mu sync.Mutex
start int64 // start offset
offset int64 // current offset
maxOffset int64 // maximum offset we are reading to
tr *accounting.Transfer
in *accounting.Account // input we are reading from
skipped int64 // number of bytes we have skipped sequentially
_closed bool // set to true if downloader is closed
stop bool // set to true if we have called _stop()
}
// New makes a downloader for item
func New(item Item, opt *vfscommon.Options, remote string, src fs.Object) (dls *Downloaders) {
if src == nil {
panic("internal error: newDownloaders called with nil src object")
}
ctx, cancel := context.WithCancel(context.Background())
dls = &Downloaders{
ctx: ctx,
cancel: cancel,
item: item,
opt: opt,
src: src,
remote: remote,
}
dls.wg.Add(1)
go func() {
defer dls.wg.Done()
ticker := time.NewTicker(backgroundKickerInterval)
select {
case <-ticker.C:
err := dls.kickWaiters()
if err != nil {
fs.Errorf(dls.src, "vfs cache: failed to kick waiters: %v", err)
}
case <-ctx.Done():
break
}
ticker.Stop()
}()
return dls
}
// Accumulate errors for this downloader
//
// It should be called with
//
// n bytes downloaded
// err is error from download
//
// call with lock held
func (dls *Downloaders) _countErrors(n int64, err error) {
if err == nil && n != 0 {
if dls.errorCount != 0 {
fs.Infof(dls.src, "vfs cache: downloader: resetting error count to 0")
dls.errorCount = 0
dls.lastErr = nil
}
return
}
if err != nil {
//if err != syscall.ENOSPC {
dls.errorCount++
//}
dls.lastErr = err
fs.Infof(dls.src, "vfs cache: downloader: error count now %d: %v", dls.errorCount, err)
}
}
func (dls *Downloaders) countErrors(n int64, err error) {
dls.mu.Lock()
dls._countErrors(n, err)
dls.mu.Unlock()
}
// Make a new downloader, starting it to download r
//
// call with lock held
func (dls *Downloaders) _newDownloader(r ranges.Range) (dl *downloader, err error) {
// defer log.Trace(dls.src, "r=%v", r)("err=%v", &err)
dl = &downloader{
kick: make(chan struct{}, 1),
quit: make(chan struct{}),
dls: dls,
start: r.Pos,
offset: r.Pos,
maxOffset: r.End(),
}
err = dl.open(dl.offset)
if err != nil {
_ = dl.close(err)
return nil, fmt.Errorf("failed to open downloader: %w", err)
}
dls.dls = append(dls.dls, dl)
dl.wg.Add(1)
go func() {
defer dl.wg.Done()
n, err := dl.download()
_ = dl.close(err)
dl.dls.countErrors(n, err)
if err != nil {
fs.Errorf(dl.dls.src, "vfs cache: failed to download: %v", err)
}
err = dl.dls.kickWaiters()
if err != nil {
fs.Errorf(dl.dls.src, "vfs cache: failed to kick waiters: %v", err)
}
}()
return dl, nil
}
// _removeClosed() removes any downloaders which are closed.
//
// Call with the mutex held
func (dls *Downloaders) _removeClosed() {
newDownloaders := dls.dls[:0]
for _, dl := range dls.dls {
if !dl.closed() {
newDownloaders = append(newDownloaders, dl)
}
}
dls.dls = newDownloaders
}
// Close all running downloaders and return any unfulfilled waiters
// with inErr
func (dls *Downloaders) Close(inErr error) (err error) {
dls.mu.Lock()
defer dls.mu.Unlock()
dls._removeClosed()
for _, dl := range dls.dls {
dls.mu.Unlock()
closeErr := dl.stopAndClose(inErr)
dls.mu.Lock()
if closeErr != nil && err != nil {
err = closeErr
}
}
dls.cancel()
// dls may have entered the periodical (every 5 seconds) kickWaiters() call
// unlock the mutex to allow it to finish so that we can get its dls.wg.Done()
dls.mu.Unlock()
dls.wg.Wait()
dls.mu.Lock()
dls.dls = nil
dls._dispatchWaiters()
dls._closeWaiters(inErr)
return err
}
// Download the range passed in returning when it has been downloaded
// with an error from the downloading go routine.
func (dls *Downloaders) Download(r ranges.Range) (err error) {
// defer log.Trace(dls.src, "r=%+v", r)("err=%v", &err)
dls.mu.Lock()
errChan := make(chan error)
waiter := waiter{
r: r,
errChan: errChan,
}
err = dls._ensureDownloader(r)
if err != nil {
dls.mu.Unlock()
return err
}
dls.waiters = append(dls.waiters, waiter)
dls.mu.Unlock()
return <-errChan
}
// close any waiters with the error passed in
//
// call with lock held
func (dls *Downloaders) _closeWaiters(err error) {
for _, waiter := range dls.waiters {
waiter.errChan <- err
}
dls.waiters = nil
}
// ensure a downloader is running for the range if required. If one isn't found
// then it starts it.
//
// call with lock held
func (dls *Downloaders) _ensureDownloader(r ranges.Range) (err error) {
// defer log.Trace(dls.src, "r=%v", r)("err=%v", &err)
// The window includes potentially unread data in the buffer
window := int64(fs.GetConfig(context.TODO()).BufferSize)
// Increase the read range by the read ahead if set
if dls.opt.ReadAhead > 0 {
r.Size += int64(dls.opt.ReadAhead)
}
// We may be reopening a downloader after a failure here or
// doing a tentative prefetch so check to see that we haven't
// read some stuff already.
//
// Clip r to stuff which needs downloading
r = dls.item.FindMissing(r)
// If the range is entirely present then we only need to start a
// downloader if the window isn't full.
startNew := true
if r.IsEmpty() {
// Make a new range which includes the window
rWindow := r
rWindow.Size += window
// Clip rWindow to stuff which needs downloading
rWindowClipped := dls.item.FindMissing(rWindow)
// If rWindowClipped is empty then don't start a new downloader
// if there isn't an existing one as there is no data within the
// window which needs downloading. We do want to kick an
// existing one though to stop it timing out.
if rWindowClipped.IsEmpty() {
// Don't start any more downloaders
startNew = false
// Start downloading at the start of the unread window
// This likely has been downloaded already but it will
// kick the downloader
r.Pos = rWindow.End()
} else {
// Start downloading at the start of the unread window
r.Pos = rWindowClipped.Pos
}
// But don't write anything for the moment
r.Size = 0
}
// If buffer size is less than minWindow then make it that
if window < minWindow {
window = minWindow
}
var dl *downloader
// Look through downloaders to find one in range
// If there isn't one then start a new one
dls._removeClosed()
for _, dl = range dls.dls {
start, offset := dl.getRange()
// The downloader's offset to offset+window is the gap
// in which we would like to reuse this
// downloader. The downloader will never reach before
// start and offset+windows is too far away - we'd
// rather start another downloader.
// fs.Debugf(nil, "r=%v start=%d, offset=%d, found=%v", r, start, offset, r.Pos >= start && r.Pos < offset+window)
if r.Pos >= start && r.Pos < offset+window {
// Found downloader which will soon have our data
dl.setRange(r)
return nil
}
}
if !startNew {
return nil
}
// Size can be 0 here if file shrinks - no need to download
if r.Size == 0 {
return nil
}
// Downloader not found so start a new one
_, err = dls._newDownloader(r)
if err != nil {
dls._countErrors(0, err)
return fmt.Errorf("failed to start downloader: %w", err)
}
return err
}
// EnsureDownloader makes sure a downloader is running for the range
// passed in. If one isn't found then it starts it.
//
// It does not wait for the range to be downloaded
func (dls *Downloaders) EnsureDownloader(r ranges.Range) (err error) {
dls.mu.Lock()
defer dls.mu.Unlock()
return dls._ensureDownloader(r)
}
// _dispatchWaiters() sends any waiters which have completed back to
// their callers.
//
// Call with the mutex held
func (dls *Downloaders) _dispatchWaiters() {
if len(dls.waiters) == 0 {
return
}
newWaiters := dls.waiters[:0]
for _, waiter := range dls.waiters {
// Clip the size against the actual size in case it has shrunk
r := waiter.r
r.Clip(dls.src.Size())
if dls.item.HasRange(r) {
waiter.errChan <- nil
} else {
newWaiters = append(newWaiters, waiter)
}
}
dls.waiters = newWaiters
}
// Send any waiters which have completed back to their callers and make sure
// there is a downloader appropriate for each waiter
func (dls *Downloaders) kickWaiters() (err error) {
dls.mu.Lock()
defer dls.mu.Unlock()
dls._dispatchWaiters()
if len(dls.waiters) == 0 {
return nil
}
// Make sure each waiter has a downloader
// This is an O(waiters*Downloaders) algorithm
// However the number of waiters and the number of downloaders
// are both expected to be small.
for _, waiter := range dls.waiters {
err = dls._ensureDownloader(waiter.r)
if err != nil {
// Failures here will be retried by background kicker
fs.Errorf(dls.src, "vfs cache: restart download failed: %v", err)
}
}
if fserrors.IsErrNoSpace(dls.lastErr) {
fs.Errorf(dls.src, "vfs cache: cache is out of space %d/%d: last error: %v", dls.errorCount, maxErrorCount, dls.lastErr)
dls._closeWaiters(dls.lastErr)
return dls.lastErr
}
if dls.errorCount > maxErrorCount {
fs.Errorf(dls.src, "vfs cache: too many errors %d/%d: last error: %v", dls.errorCount, maxErrorCount, dls.lastErr)
dls._closeWaiters(dls.lastErr)
return dls.lastErr
}
return nil
}
// Write writes len(p) bytes from p to the underlying data stream. It
// returns the number of bytes written from p (0 <= n <= len(p)) and
// any error encountered that caused the write to stop early. Write
// must return a non-nil error if it returns n < len(p). Write must
// not modify the slice data, even temporarily.
//
// Implementations must not retain p.
func (dl *downloader) Write(p []byte) (n int, err error) {
// defer log.Trace(dl.dls.src, "p_len=%d", len(p))("n=%d, err=%v", &n, &err)
// Kick the waiters on exit if some characters received
defer func() {
if n <= 0 {
return
}
if waitErr := dl.dls.kickWaiters(); waitErr != nil {
fs.Errorf(dl.dls.src, "vfs cache: download write: failed to kick waiters: %v", waitErr)
if err == nil {
err = waitErr
}
}
}()
dl.mu.Lock()
defer dl.mu.Unlock()
// Wait here if we have reached maxOffset until
// - we are quitting
// - we get kicked
// - timeout happens
loop:
for dl.offset >= dl.maxOffset {
var timeout = time.NewTimer(maxDownloaderIdleTime)
dl.mu.Unlock()
select {
case <-dl.quit:
dl.mu.Lock()
timeout.Stop()
break loop
case <-dl.kick:
dl.mu.Lock()
timeout.Stop()
case <-timeout.C:
// stop any future reading
dl.mu.Lock()
if !dl.stop {
fs.Debugf(dl.dls.src, "vfs cache: stopping download thread as it timed out")
dl._stop()
}
break loop
}
}
n, skipped, err := dl.dls.item.WriteAtNoOverwrite(p, dl.offset)
if skipped == n {
dl.skipped += int64(skipped)
} else {
dl.skipped = 0
}
dl.offset += int64(n)
// Kill this downloader if skipped too many bytes
if !dl.stop && dl.skipped > maxSkipBytes {
fs.Debugf(dl.dls.src, "vfs cache: stopping download thread as it has skipped %d bytes", dl.skipped)
dl._stop()
}
// If running without a async buffer then stop now as
// StopBuffering has no effect if the Account wasn't buffered
// so we need to stop manually now rather than wait for the
// AsyncReader to stop.
if dl.stop && !dl.in.HasBuffer() {
err = asyncreader.ErrorStreamAbandoned
}
return n, err
}
// open the file from offset
//
// should be called on a fresh downloader
func (dl *downloader) open(offset int64) (err error) {
// defer log.Trace(dl.dls.src, "offset=%d", offset)("err=%v", &err)
dl.tr = accounting.Stats(dl.dls.ctx).NewTransfer(dl.dls.src, nil)
size := dl.dls.src.Size()
if size < 0 {
// FIXME should just completely download these
return errors.New("can't open unknown sized file")
}
// FIXME hashType needs to ignore when --no-checksum is set too? Which is a VFS flag.
// var rangeOption *fs.RangeOption
// if offset > 0 {
// rangeOption = &fs.RangeOption{Start: offset, End: size - 1}
// }
// in0, err := operations.NewReOpen(dl.dls.ctx, dl.dls.src, ci.LowLevelRetries, dl.dls.item.c.hashOption, rangeOption)
in0 := chunkedreader.New(context.TODO(), dl.dls.src, int64(dl.dls.opt.ChunkSize), int64(dl.dls.opt.ChunkSizeLimit), dl.dls.opt.ChunkStreams)
_, err = in0.Seek(offset, 0)
if err != nil {
return fmt.Errorf("vfs reader: failed to open source file: %w", err)
}
dl.in = dl.tr.Account(dl.dls.ctx, in0).WithBuffer() // account and buffer the transfer
dl.offset = offset
// FIXME set mod time
// FIXME check checksums
return nil
}
// close the downloader
func (dl *downloader) close(inErr error) (err error) {
// defer log.Trace(dl.dls.src, "inErr=%v", err)("err=%v", &err)
checkErr := func(e error) {
if e == nil || errors.Is(err, asyncreader.ErrorStreamAbandoned) {
return
}
err = e
}
dl.mu.Lock()
if dl.in != nil {
checkErr(dl.in.Close())
dl.in = nil
}
if dl.tr != nil {
dl.tr.Done(dl.dls.ctx, inErr)
dl.tr = nil
}
dl._closed = true
dl.mu.Unlock()
return nil
}
// closed returns true if the downloader has been closed already
func (dl *downloader) closed() bool {
dl.mu.Lock()
defer dl.mu.Unlock()
return dl._closed
}
// stop the downloader if running
//
// Call with the mutex held
func (dl *downloader) _stop() {
// defer log.Trace(dl.dls.src, "")("")
// exit if have already called _stop
if dl.stop {
return
}
dl.stop = true
// Signal quit now to unblock the downloader
close(dl.quit)
// stop the downloader by stopping the async reader buffering
// any more input. This causes all the stuff in the async
// buffer (which can be many MiB) to be written to the disk
// before exiting.
if dl.in != nil {
dl.in.StopBuffering()
}
}
// stop the downloader if running then close it with the error passed in
func (dl *downloader) stopAndClose(inErr error) (err error) {
// Stop the downloader by closing its input
dl.mu.Lock()
dl._stop()
dl.mu.Unlock()
// wait for downloader to finish...
// do this without mutex as asyncreader
// calls back into Write() which needs the lock
dl.wg.Wait()
return dl.close(inErr)
}
// Start downloading to the local file starting at offset until maxOffset.
func (dl *downloader) download() (n int64, err error) {
// defer log.Trace(dl.dls.src, "")("err=%v", &err)
n, err = dl.in.WriteTo(dl)
if err != nil && !errors.Is(err, asyncreader.ErrorStreamAbandoned) {
return n, fmt.Errorf("vfs reader: failed to write to cache file: %w", err)
}
return n, nil
}
// setRange makes sure the downloader is downloading the range passed in
func (dl *downloader) setRange(r ranges.Range) {
// defer log.Trace(dl.dls.src, "r=%v", r)("")
dl.mu.Lock()
maxOffset := r.End()
if maxOffset > dl.maxOffset {
dl.maxOffset = maxOffset
}
dl.mu.Unlock()
// fs.Debugf(dl.dls.src, "kicking downloader with maxOffset %d", maxOffset)
select {
case dl.kick <- struct{}{}:
default:
}
}
// get the current range this downloader is working on
func (dl *downloader) getRange() (start, offset int64) {
dl.mu.Lock()
defer dl.mu.Unlock()
return dl.start, dl.offset
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscache/writeback/writeback.go | vfs/vfscache/writeback/writeback.go | // Package writeback keeps track of the files which need to be written
// back to storage
package writeback
import (
"container/heap"
"context"
"errors"
"sort"
"sync"
"sync/atomic"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/vfs/vfscommon"
)
const (
maxUploadDelay = 5 * time.Minute // max delay between upload attempts
)
// PutFn is the interface that item provides to store the data
type PutFn func(context.Context) error
// Handle is returned for callers to keep track of writeback items
type Handle uint64
// WriteBack keeps track of the items which need to be written back to the disk at some point
type WriteBack struct {
// read and written with atomic, must be 64-bit aligned
id Handle // id of the last writeBackItem created
ctx context.Context
mu sync.Mutex
items writeBackItems // priority queue of *writeBackItem - writeBackItems are in here while awaiting transfer only
lookup map[Handle]*writeBackItem // for getting a *writeBackItem from a Handle - writeBackItems are in here until cancelled
opt *vfscommon.Options // VFS options
timer *time.Timer // next scheduled time for the uploader
expiry time.Time // time the next item expires or IsZero
uploads int // number of uploads in progress
}
// New make a new WriteBack
//
// cancel the context to stop the background processing
func New(ctx context.Context, opt *vfscommon.Options) *WriteBack {
wb := &WriteBack{
ctx: ctx,
items: writeBackItems{},
lookup: make(map[Handle]*writeBackItem),
opt: opt,
}
heap.Init(&wb.items)
return wb
}
// writeBackItem stores an Item awaiting writeback
//
// These are stored on the items heap when awaiting transfer but
// removed from the items heap when transferring. They remain in the
// lookup map until cancelled.
//
// writeBack.mu must be held to manipulate this
type writeBackItem struct {
name string // name of the item so we don't have to read it from item
size int64 // size of the item so we don't have to read it from item
id Handle // id of the item
index int // index into the priority queue for update
expiry time.Time // When this expires we will write it back
uploading bool // True if item is being processed by upload() method
onHeap bool // true if this item is on the items heap
cancel context.CancelFunc // To cancel the upload with
done chan struct{} // closed when the cancellation completes
putFn PutFn // To write the object data
tries int // number of times we have tried to upload
delay time.Duration // delay between upload attempts
}
// A writeBackItems implements a priority queue by implementing
// heap.Interface and holds writeBackItems.
type writeBackItems []*writeBackItem
func (ws writeBackItems) Len() int { return len(ws) }
func (ws writeBackItems) Less(i, j int) bool {
a, b := ws[i], ws[j]
// If times are equal then use ID to disambiguate
if a.expiry.Equal(b.expiry) {
return a.id < b.id
}
return a.expiry.Before(b.expiry)
}
func (ws writeBackItems) Swap(i, j int) {
ws[i], ws[j] = ws[j], ws[i]
ws[i].index = i
ws[j].index = j
}
func (ws *writeBackItems) Push(x any) {
n := len(*ws)
item := x.(*writeBackItem)
item.index = n
*ws = append(*ws, item)
}
func (ws *writeBackItems) Pop() any {
old := *ws
n := len(old)
item := old[n-1]
old[n-1] = nil // avoid memory leak
item.index = -1 // for safety
*ws = old[0 : n-1]
return item
}
// update modifies the expiry of an Item in the queue.
//
// call with lock held
func (ws *writeBackItems) _update(item *writeBackItem, expiry time.Time) {
item.expiry = expiry
heap.Fix(ws, item.index)
}
// return a new expiry time based from now until the WriteBack timeout
//
// call with lock held
func (wb *WriteBack) _newExpiry() time.Time {
expiry := time.Now()
if wb.opt.WriteBack > 0 {
expiry = expiry.Add(time.Duration(wb.opt.WriteBack))
}
// expiry = expiry.Round(time.Millisecond)
return expiry
}
// make a new writeBackItem
//
// call with the lock held
func (wb *WriteBack) _newItem(id Handle, name string, size int64) *writeBackItem {
wb.SetID(&id)
wbItem := &writeBackItem{
name: name,
size: size,
expiry: wb._newExpiry(),
delay: time.Duration(wb.opt.WriteBack),
id: id,
}
wb._addItem(wbItem)
wb._pushItem(wbItem)
return wbItem
}
// add a writeBackItem to the lookup map
//
// call with the lock held
func (wb *WriteBack) _addItem(wbItem *writeBackItem) {
wb.lookup[wbItem.id] = wbItem
}
// delete a writeBackItem from the lookup map
//
// call with the lock held
func (wb *WriteBack) _delItem(wbItem *writeBackItem) {
delete(wb.lookup, wbItem.id)
}
// pop a writeBackItem from the items heap
//
// call with the lock held
func (wb *WriteBack) _popItem() (wbItem *writeBackItem) {
wbItem = heap.Pop(&wb.items).(*writeBackItem)
wbItem.onHeap = false
return wbItem
}
// push a writeBackItem onto the items heap
//
// call with the lock held
func (wb *WriteBack) _pushItem(wbItem *writeBackItem) {
if !wbItem.onHeap {
heap.Push(&wb.items, wbItem)
wbItem.onHeap = true
}
}
// remove a writeBackItem from the items heap
//
// call with the lock held
func (wb *WriteBack) _removeItem(wbItem *writeBackItem) {
if wbItem.onHeap {
heap.Remove(&wb.items, wbItem.index)
wbItem.onHeap = false
}
}
// peek the oldest writeBackItem - may be nil
//
// call with the lock held
func (wb *WriteBack) _peekItem() (wbItem *writeBackItem) {
if len(wb.items) == 0 {
return nil
}
return wb.items[0]
}
// stop the timer which runs the expiries
func (wb *WriteBack) _stopTimer() {
if wb.expiry.IsZero() {
return
}
wb.expiry = time.Time{}
// fs.Debugf(nil, "resetTimer STOP")
if wb.timer != nil {
wb.timer.Stop()
wb.timer = nil
}
}
// reset the timer which runs the expiries
func (wb *WriteBack) _resetTimer() {
wbItem := wb._peekItem()
if wbItem == nil {
wb._stopTimer()
} else {
if wb.expiry.Equal(wbItem.expiry) {
return
}
wb.expiry = wbItem.expiry
dt := max(time.Until(wbItem.expiry), 0)
// fs.Debugf(nil, "resetTimer dt=%v", dt)
if wb.timer != nil {
wb.timer.Stop()
}
wb.timer = time.AfterFunc(dt, func() {
wb.processItems(wb.ctx)
})
}
}
// SetID sets the Handle pointed to if it is non zero to the next
// handle.
func (wb *WriteBack) SetID(pid *Handle) {
if *pid == 0 {
*pid = Handle(atomic.AddUint64((*uint64)(&wb.id), 1))
}
}
// Add adds an item to the writeback queue or resets its timer if it
// is already there.
//
// If id is 0 then a new item will always be created and the new
// Handle will be returned.
//
// Use SetID to create Handles in advance of calling Add.
//
// If modified is false then it it doesn't cancel a pending upload if
// there is one as there is no need.
func (wb *WriteBack) Add(id Handle, name string, size int64, modified bool, putFn PutFn) Handle {
wb.mu.Lock()
defer wb.mu.Unlock()
wbItem, ok := wb.lookup[id]
if !ok {
wbItem = wb._newItem(id, name, size)
} else {
if wbItem.uploading && modified {
// We are uploading already so cancel the upload
wb._cancelUpload(wbItem)
}
// Kick the timer on
wb.items._update(wbItem, wb._newExpiry())
}
wbItem.putFn = putFn
wbItem.size = size
wb._resetTimer()
return wbItem.id
}
// _remove should be called when a file should be removed from the
// writeback queue. This cancels a writeback if there is one and
// doesn't return the item to the queue.
//
// This should be called with the lock held
func (wb *WriteBack) _remove(id Handle) (found bool) {
wbItem, found := wb.lookup[id]
if found {
fs.Debugf(wbItem.name, "vfs cache: cancelling writeback (uploading %v) %p item %d", wbItem.uploading, wbItem, wbItem.id)
if wbItem.uploading {
// We are uploading already so cancel the upload
wb._cancelUpload(wbItem)
}
// Remove the item from the heap
wb._removeItem(wbItem)
// Remove the item from the lookup map
wb._delItem(wbItem)
}
wb._resetTimer()
return found
}
// Remove should be called when a file should be removed from the
// writeback queue. This cancels a writeback if there is one and
// doesn't return the item to the queue.
func (wb *WriteBack) Remove(id Handle) (found bool) {
wb.mu.Lock()
defer wb.mu.Unlock()
return wb._remove(id)
}
// Rename should be called when a file might be uploading and it gains
// a new name. This will cancel the upload and put it back in the
// queue.
func (wb *WriteBack) Rename(id Handle, name string) {
wb.mu.Lock()
defer wb.mu.Unlock()
wbItem, ok := wb.lookup[id]
if !ok {
return
}
if wbItem.uploading {
// We are uploading already so cancel the upload
wb._cancelUpload(wbItem)
}
// Check to see if there are any uploads with the existing
// name and remove them
for existingID, existingItem := range wb.lookup {
if existingID != id && existingItem.name == name {
wb._remove(existingID)
}
}
wbItem.name = name
// Kick the timer on
wb.items._update(wbItem, wb._newExpiry())
wb._resetTimer()
}
// upload the item - called as a goroutine
//
// uploading will have been incremented here already
func (wb *WriteBack) upload(ctx context.Context, wbItem *writeBackItem) {
wb.mu.Lock()
defer wb.mu.Unlock()
putFn := wbItem.putFn
wbItem.tries++
fs.Debugf(wbItem.name, "vfs cache: starting upload")
wb.mu.Unlock()
err := putFn(ctx)
wb.mu.Lock()
wbItem.cancel() // cancel context to release resources since store done
wbItem.uploading = false
wb.uploads--
if err != nil {
// FIXME should this have a max number of transfer attempts?
wbItem.delay *= 2
if wbItem.delay > maxUploadDelay {
wbItem.delay = maxUploadDelay
}
if errors.Is(err, context.Canceled) {
fs.Infof(wbItem.name, "vfs cache: upload canceled")
// Upload was cancelled so reset timer
wbItem.delay = time.Duration(wb.opt.WriteBack)
} else {
fs.Errorf(wbItem.name, "vfs cache: failed to upload try #%d, will retry in %v: %v", wbItem.tries, wbItem.delay, err)
}
// push the item back on the queue for retry
wb._pushItem(wbItem)
wb.items._update(wbItem, time.Now().Add(wbItem.delay))
} else {
fs.Infof(wbItem.name, "vfs cache: upload succeeded try #%d", wbItem.tries)
// show that we are done with the item
wb._delItem(wbItem)
}
wb._resetTimer()
close(wbItem.done)
}
// cancel the upload - the item should be on the heap after this returns
//
// call with lock held
func (wb *WriteBack) _cancelUpload(wbItem *writeBackItem) {
if !wbItem.uploading {
return
}
fs.Debugf(wbItem.name, "vfs cache: cancelling upload")
if wbItem.cancel != nil {
// Cancel the upload - this may or may not be effective
wbItem.cancel()
// wait for the uploader to finish
//
// we need to wait without the lock otherwise the
// background part will never run.
wb.mu.Unlock()
<-wbItem.done
wb.mu.Lock()
}
// uploading items are not on the heap so add them back
wb._pushItem(wbItem)
fs.Debugf(wbItem.name, "vfs cache: cancelled upload")
}
// cancelUpload cancels the upload of the item if there is one in progress
//
// it returns true if there was an upload in progress
func (wb *WriteBack) cancelUpload(id Handle) bool {
wb.mu.Lock()
defer wb.mu.Unlock()
wbItem, ok := wb.lookup[id]
if !ok || !wbItem.uploading {
return false
}
wb._cancelUpload(wbItem)
return true
}
// this uploads as many items as possible
func (wb *WriteBack) processItems(ctx context.Context) {
wb.mu.Lock()
defer wb.mu.Unlock()
if wb.ctx.Err() != nil {
return
}
resetTimer := true
for wbItem := wb._peekItem(); wbItem != nil && time.Until(wbItem.expiry) <= 0; wbItem = wb._peekItem() {
// If reached transfer limit don't restart the timer
if wb.uploads >= fs.GetConfig(context.TODO()).Transfers {
fs.Debugf(wbItem.name, "vfs cache: delaying writeback as --transfers exceeded")
resetTimer = false
break
}
// Pop the item, mark as uploading and start the uploader
wbItem = wb._popItem()
//fs.Debugf(wbItem.name, "uploading = true %p item %p", wbItem, wbItem.item)
wbItem.uploading = true
wb.uploads++
newCtx, cancel := context.WithCancel(ctx)
wbItem.cancel = cancel
wbItem.done = make(chan struct{})
go wb.upload(newCtx, wbItem)
}
if resetTimer {
wb._resetTimer()
} else {
wb._stopTimer()
}
}
// Stats return the number of uploads in progress and queued
func (wb *WriteBack) Stats() (uploadsInProgress, uploadsQueued int) {
wb.mu.Lock()
defer wb.mu.Unlock()
return wb.uploads, len(wb.items)
}
// QueueInfo is information about an item queued for upload, returned
// by Queue
type QueueInfo struct {
Name string `json:"name"` // name (full path) of the file,
ID Handle `json:"id"` // id of queue item
Size int64 `json:"size"` // integer size of the file in bytes
Expiry float64 `json:"expiry"` // seconds from now which the file is eligible for transfer, oldest goes first
Tries int `json:"tries"` // number of times we have tried to upload
Delay float64 `json:"delay"` // delay between upload attempts (s)
Uploading bool `json:"uploading"` // true if item is being uploaded
}
// Queue return info about the current upload queue
func (wb *WriteBack) Queue() []QueueInfo {
wb.mu.Lock()
defer wb.mu.Unlock()
items := make([]QueueInfo, 0, len(wb.lookup))
now := time.Now()
// Lookup all the items in no particular order
for _, wbItem := range wb.lookup {
items = append(items, QueueInfo{
Name: wbItem.name,
ID: wbItem.id,
Size: wbItem.size,
Expiry: wbItem.expiry.Sub(now).Seconds(),
Tries: wbItem.tries,
Delay: wbItem.delay.Seconds(),
Uploading: wbItem.uploading,
})
}
// Sort by Uploading first then Expiry
sort.Slice(items, func(i, j int) bool {
if items[i].Uploading != items[j].Uploading {
return items[i].Uploading
}
return items[i].Expiry < items[j].Expiry
})
return items
}
// ErrorIDNotFound is returned from SetExpiry when the item is not found
var ErrorIDNotFound = errors.New("id not found in queue")
// SetExpiry sets the expiry time for an item in the writeback queue.
//
// id should be as returned from the Queue call
//
// The expiry time is set to expiry + relative if expiry is passed in,
// otherwise the expiry of the item is used.
//
// If the item isn't found then it will return ErrorIDNotFound
func (wb *WriteBack) SetExpiry(id Handle, expiry time.Time, relative time.Duration) error {
wb.mu.Lock()
defer wb.mu.Unlock()
wbItem, ok := wb.lookup[id]
if !ok {
return ErrorIDNotFound
}
// If expiry is not supplied, use expiry of item
if expiry.IsZero() {
expiry = wbItem.expiry
}
expiry = expiry.Add(relative)
// Update the expiry with the user requested value
wb.items._update(wbItem, expiry)
wb._resetTimer()
return nil
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscache/writeback/writeback_test.go | vfs/vfscache/writeback/writeback_test.go | package writeback
import (
"container/heap"
"context"
"errors"
"fmt"
"strings"
"sync"
"testing"
"time"
"slices"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func newTestWriteBack(t *testing.T) (wb *WriteBack, cancel func()) {
ctx, cancel := context.WithCancel(context.Background())
opt := vfscommon.Opt
opt.WriteBack = fs.Duration(100 * time.Millisecond)
wb = New(ctx, &opt)
return wb, cancel
}
// string for debugging - make a copy and pop the items out in order
func (wb *WriteBack) string(t *testing.T) string {
wb.mu.Lock()
defer wb.mu.Unlock()
ws := wb.items
// check indexes OK first
for i := range ws {
assert.Equal(t, i, ws[i].index, ws[i].name)
}
wsCopy := make(writeBackItems, len(ws))
// deep copy the elements
for i := range wsCopy {
item := *ws[i]
wsCopy[i] = &item
}
// print them
var out []string
for wsCopy.Len() > 0 {
out = append(out, heap.Pop(&wsCopy).(*writeBackItem).name)
}
return strings.Join(out, ",")
}
func TestWriteBackItems(t *testing.T) {
// Test the items heap behaves properly
now := time.Now()
wbItem1 := writeBackItem{name: "one", expiry: now.Add(1 * time.Second)}
wbItem2 := writeBackItem{name: "two", expiry: now.Add(2 * time.Second)}
wbItem3 := writeBackItem{name: "three", expiry: now.Add(4 * time.Second)}
wb := &WriteBack{
items: writeBackItems{},
}
heap.Init(&wb.items)
assert.Equal(t, "", wb.string(t))
heap.Push(&wb.items, &wbItem2)
assert.Equal(t, "two", wb.string(t))
heap.Push(&wb.items, &wbItem3)
assert.Equal(t, "two,three", wb.string(t))
heap.Push(&wb.items, &wbItem1)
assert.Equal(t, "one,two,three", wb.string(t))
wb.items._update(&wbItem1, now.Add(3*time.Second))
assert.Equal(t, "two,one,three", wb.string(t))
wb.items._update(&wbItem1, now.Add(5*time.Second))
assert.Equal(t, "two,three,one", wb.string(t))
// Set all times the same - should sort in insertion order
wb.items._update(&wbItem1, now)
wb.items._update(&wbItem2, now)
wb.items._update(&wbItem3, now)
assert.Equal(t, "one,two,three", wb.string(t))
}
func checkOnHeap(t *testing.T, wb *WriteBack, wbItem *writeBackItem) {
wb.mu.Lock()
defer wb.mu.Unlock()
assert.True(t, wbItem.onHeap)
if slices.Contains(wb.items, wbItem) {
return
}
assert.Failf(t, "expecting %q on heap", wbItem.name)
}
func checkNotOnHeap(t *testing.T, wb *WriteBack, wbItem *writeBackItem) {
wb.mu.Lock()
defer wb.mu.Unlock()
assert.False(t, wbItem.onHeap)
for i := range wb.items {
if wb.items[i] == wbItem {
t.Errorf("not expecting %q on heap", wbItem.name)
}
}
}
func checkInLookup(t *testing.T, wb *WriteBack, wbItem *writeBackItem) {
wb.mu.Lock()
defer wb.mu.Unlock()
assert.Equal(t, wbItem, wb.lookup[wbItem.id])
}
func checkNotInLookup(t *testing.T, wb *WriteBack, wbItem *writeBackItem) {
wb.mu.Lock()
defer wb.mu.Unlock()
assert.Nil(t, wb.lookup[wbItem.id])
}
func TestWriteBackItemCRUD(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
// _peekItem empty
assert.Nil(t, wb._peekItem())
wbItem1 := wb._newItem(0, "one", 10)
checkOnHeap(t, wb, wbItem1)
checkInLookup(t, wb, wbItem1)
wbItem2 := wb._newItem(0, "two", 10)
checkOnHeap(t, wb, wbItem2)
checkInLookup(t, wb, wbItem2)
wbItem3 := wb._newItem(0, "three", 10)
checkOnHeap(t, wb, wbItem3)
checkInLookup(t, wb, wbItem3)
assert.Equal(t, "one,two,three", wb.string(t))
// _delItem
wb._delItem(wbItem2)
checkOnHeap(t, wb, wbItem2)
checkNotInLookup(t, wb, wbItem2)
// _addItem
wb._addItem(wbItem2)
checkOnHeap(t, wb, wbItem2)
checkInLookup(t, wb, wbItem2)
// _popItem
assert.True(t, wbItem1.onHeap)
poppedWbItem := wb._popItem()
assert.Equal(t, wbItem1, poppedWbItem)
checkNotOnHeap(t, wb, wbItem1)
checkInLookup(t, wb, wbItem1)
assert.Equal(t, "two,three", wb.string(t))
// _pushItem
wb._pushItem(wbItem1)
checkOnHeap(t, wb, wbItem1)
checkInLookup(t, wb, wbItem1)
assert.Equal(t, "one,two,three", wb.string(t))
// push twice
wb._pushItem(wbItem1)
assert.Equal(t, "one,two,three", wb.string(t))
// _peekItem
assert.Equal(t, wbItem1, wb._peekItem())
// _removeItem
assert.Equal(t, "one,two,three", wb.string(t))
wb._removeItem(wbItem2)
checkNotOnHeap(t, wb, wbItem2)
checkInLookup(t, wb, wbItem2)
assert.Equal(t, "one,three", wb.string(t))
// remove twice
wb._removeItem(wbItem2)
checkNotOnHeap(t, wb, wbItem2)
checkInLookup(t, wb, wbItem2)
assert.Equal(t, "one,three", wb.string(t))
}
func assertTimerRunning(t *testing.T, wb *WriteBack, running bool) {
wb.mu.Lock()
if running {
assert.NotEqual(t, time.Time{}, wb.expiry)
assert.NotNil(t, wb.timer)
} else {
assert.Equal(t, time.Time{}, wb.expiry)
assert.Nil(t, wb.timer)
}
wb.mu.Unlock()
}
func TestWriteBackResetTimer(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
// Reset the timer on an empty queue
wb._resetTimer()
// Check timer is stopped
assertTimerRunning(t, wb, false)
_ = wb._newItem(0, "three", 10)
// Reset the timer on an queue with stuff
wb._resetTimer()
// Check timer is not stopped
assertTimerRunning(t, wb, true)
}
// A "transfer" for testing
type putItem struct {
wg sync.WaitGroup
mu sync.Mutex
t *testing.T
started chan struct{}
errChan chan error
running bool
cancelled bool
called bool
}
func newPutItem(t *testing.T) *putItem {
return &putItem{
t: t,
started: make(chan struct{}, 1),
}
}
// put the object as per PutFn interface
func (pi *putItem) put(ctx context.Context) (err error) {
pi.wg.Add(1)
defer pi.wg.Done()
pi.mu.Lock()
pi.called = true
if pi.running {
assert.Fail(pi.t, "upload already running")
}
pi.running = true
pi.errChan = make(chan error, 1)
pi.mu.Unlock()
pi.started <- struct{}{}
cancelled := false
select {
case err = <-pi.errChan:
case <-ctx.Done():
err = ctx.Err()
cancelled = true
}
pi.mu.Lock()
pi.running = false
pi.cancelled = cancelled
pi.mu.Unlock()
return err
}
// finish the "transfer" with the error passed in
func (pi *putItem) finish(err error) {
pi.mu.Lock()
if !pi.running {
assert.Fail(pi.t, "upload not running")
}
pi.mu.Unlock()
pi.errChan <- err
pi.wg.Wait()
}
func waitUntilNoTransfers(t *testing.T, wb *WriteBack) {
for range 100 {
wb.mu.Lock()
uploads := wb.uploads
wb.mu.Unlock()
if uploads == 0 {
return
}
time.Sleep(10 * time.Millisecond)
}
t.Errorf("failed to wait for transfer to finish")
}
// This is the happy path with everything working
func TestWriteBackAddOK(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
pi := newPutItem(t)
var inID Handle
wb.SetID(&inID)
assert.Equal(t, Handle(1), inID)
id := wb.Add(inID, "one", 10, true, pi.put)
assert.Equal(t, inID, id)
wbItem := wb.lookup[id]
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
assert.Equal(t, "one", wb.string(t))
<-pi.started
checkNotOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
pi.finish(nil) // transfer successful
waitUntilNoTransfers(t, wb)
checkNotOnHeap(t, wb, wbItem)
checkNotInLookup(t, wb, wbItem)
}
// Now test the upload failing and being retried
func TestWriteBackAddFailRetry(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
pi := newPutItem(t)
id := wb.Add(0, "one", 10, true, pi.put)
wbItem := wb.lookup[id]
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
assert.Equal(t, "one", wb.string(t))
<-pi.started
checkNotOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
pi.finish(errors.New("transfer failed BOOM"))
waitUntilNoTransfers(t, wb)
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
// check the retry
<-pi.started
checkNotOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
pi.finish(nil) // transfer successful
waitUntilNoTransfers(t, wb)
checkNotOnHeap(t, wb, wbItem)
checkNotInLookup(t, wb, wbItem)
}
// Now test the upload being cancelled by another upload being added
func TestWriteBackAddUpdate(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
pi := newPutItem(t)
id := wb.Add(0, "one", 10, true, pi.put)
wbItem := wb.lookup[id]
assert.Equal(t, int64(10), wbItem.size) // check size
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
assert.Equal(t, "one", wb.string(t))
<-pi.started
checkNotOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
// Now the upload has started add another one
pi2 := newPutItem(t)
id2 := wb.Add(id, "one", 20, true, pi2.put)
assert.Equal(t, id, id2)
assert.Equal(t, int64(20), wbItem.size) // check size has changed
checkOnHeap(t, wb, wbItem) // object awaiting writeback time
checkInLookup(t, wb, wbItem)
// check the previous transfer was cancelled
assert.True(t, pi.cancelled)
// check the retry
<-pi2.started
checkNotOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
pi2.finish(nil) // transfer successful
waitUntilNoTransfers(t, wb)
checkNotOnHeap(t, wb, wbItem)
checkNotInLookup(t, wb, wbItem)
}
// Now test the upload being not cancelled by another upload being added
func TestWriteBackAddUpdateNotModified(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
pi := newPutItem(t)
id := wb.Add(0, "one", 10, false, pi.put)
wbItem := wb.lookup[id]
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
assert.Equal(t, "one", wb.string(t))
<-pi.started
checkNotOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
// Now the upload has started add another one
pi2 := newPutItem(t)
id2 := wb.Add(id, "one", 10, false, pi2.put)
assert.Equal(t, id, id2)
checkNotOnHeap(t, wb, wbItem) // object still being transferred
checkInLookup(t, wb, wbItem)
// Because modified was false above this should not cancel the
// transfer
assert.False(t, pi.cancelled)
// wait for original transfer to finish
pi.finish(nil)
waitUntilNoTransfers(t, wb)
checkNotOnHeap(t, wb, wbItem)
checkNotInLookup(t, wb, wbItem)
assert.False(t, pi2.called)
}
// Now test the upload being not cancelled by another upload being
// added because the upload hasn't started yet
func TestWriteBackAddUpdateNotStarted(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
pi := newPutItem(t)
id := wb.Add(0, "one", 10, true, pi.put)
wbItem := wb.lookup[id]
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
assert.Equal(t, "one", wb.string(t))
// Immediately add another upload before the first has started
pi2 := newPutItem(t)
id2 := wb.Add(id, "one", 10, true, pi2.put)
assert.Equal(t, id, id2)
checkOnHeap(t, wb, wbItem) // object still awaiting transfer
checkInLookup(t, wb, wbItem)
// Wait for the upload to start
<-pi2.started
checkNotOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
// Because modified was false above this should not cancel the
// transfer
assert.False(t, pi.cancelled)
// wait for new transfer to finish
pi2.finish(nil)
waitUntilNoTransfers(t, wb)
checkNotOnHeap(t, wb, wbItem)
checkNotInLookup(t, wb, wbItem)
assert.False(t, pi.called)
}
func TestWriteBackGetStats(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
pi := newPutItem(t)
wb.Add(0, "one", 10, true, pi.put)
inProgress, queued := wb.Stats()
assert.Equal(t, queued, 1)
assert.Equal(t, inProgress, 0)
<-pi.started
inProgress, queued = wb.Stats()
assert.Equal(t, queued, 0)
assert.Equal(t, inProgress, 1)
pi.finish(nil) // transfer successful
waitUntilNoTransfers(t, wb)
inProgress, queued = wb.Stats()
assert.Equal(t, queued, 0)
assert.Equal(t, inProgress, 0)
}
func TestWriteBackQueue(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
pi := newPutItem(t)
id := wb.Add(0, "one", 10, true, pi.put)
queue := wb.Queue()
require.Equal(t, 1, len(queue))
assert.Greater(t, queue[0].Expiry, 0.0)
assert.Less(t, queue[0].Expiry, 1.0)
queue[0].Expiry = 0.0
assert.Equal(t, []QueueInfo{
{
Name: "one",
Size: 10,
Expiry: 0.0,
Tries: 0,
Delay: 0.1,
Uploading: false,
ID: id,
},
}, queue)
<-pi.started
queue = wb.Queue()
require.Equal(t, 1, len(queue))
assert.Less(t, queue[0].Expiry, 0.0)
assert.Greater(t, queue[0].Expiry, -1.0)
queue[0].Expiry = 0.0
assert.Equal(t, []QueueInfo{
{
Name: "one",
Size: 10,
Expiry: 0.0,
Tries: 1,
Delay: 0.1,
Uploading: true,
ID: id,
},
}, queue)
pi.finish(nil) // transfer successful
waitUntilNoTransfers(t, wb)
queue = wb.Queue()
assert.Equal(t, []QueueInfo{}, queue)
}
func TestWriteBackSetExpiry(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
err := wb.SetExpiry(123123123, time.Now(), 0)
assert.Equal(t, ErrorIDNotFound, err)
pi := newPutItem(t)
id := wb.Add(0, "one", 10, true, pi.put)
wbItem := wb.lookup[id]
// get the expiry time with locking so we don't cause races
getExpiry := func() time.Time {
wb.mu.Lock()
defer wb.mu.Unlock()
return wbItem.expiry
}
expiry := time.Until(getExpiry()).Seconds()
assert.Greater(t, expiry, 0.0)
assert.Less(t, expiry, 1.0)
newExpiry := time.Now().Add(100 * time.Second)
require.NoError(t, wb.SetExpiry(wbItem.id, newExpiry, 0))
assert.Equal(t, newExpiry, getExpiry())
// This starts the transfer
newExpiry = wbItem.expiry.Add(-200 * time.Second)
require.NoError(t, wb.SetExpiry(wbItem.id, time.Time{}, -200*time.Second))
assert.Equal(t, newExpiry, getExpiry())
<-pi.started
expiry = time.Until(getExpiry()).Seconds()
assert.LessOrEqual(t, expiry, -100.0)
pi.finish(nil) // transfer successful
waitUntilNoTransfers(t, wb)
expiry = time.Until(getExpiry()).Seconds()
assert.LessOrEqual(t, expiry, -100.0)
}
// Test queuing more than fs.Config.Transfers
func TestWriteBackMaxQueue(t *testing.T) {
ctx := context.Background()
ci := fs.GetConfig(ctx)
wb, cancel := newTestWriteBack(t)
defer cancel()
maxTransfers := ci.Transfers
toTransfer := maxTransfers + 2
// put toTransfer things in the queue
pis := []*putItem{}
for range toTransfer {
pi := newPutItem(t)
pis = append(pis, pi)
wb.Add(0, fmt.Sprintf("number%d", 1), 10, true, pi.put)
}
inProgress, queued := wb.Stats()
assert.Equal(t, toTransfer, queued)
assert.Equal(t, 0, inProgress)
// now start the first maxTransfers - this should stop the timer
for i := range maxTransfers {
<-pis[i].started
}
// timer should be stopped now
assertTimerRunning(t, wb, false)
inProgress, queued = wb.Stats()
assert.Equal(t, toTransfer-maxTransfers, queued)
assert.Equal(t, maxTransfers, inProgress)
// now finish the first maxTransfers
for i := range maxTransfers {
pis[i].finish(nil)
}
// now start and finish the remaining transfers one at a time
for i := maxTransfers; i < toTransfer; i++ {
<-pis[i].started
pis[i].finish(nil)
}
waitUntilNoTransfers(t, wb)
inProgress, queued = wb.Stats()
assert.Equal(t, queued, 0)
assert.Equal(t, inProgress, 0)
}
func TestWriteBackRename(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
// cancel when not in writeback
wb.Rename(1, "nonExistent")
// add item
pi1 := newPutItem(t)
id := wb.Add(0, "one", 10, true, pi1.put)
wbItem := wb.lookup[id]
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
assert.Equal(t, wbItem.name, "one")
// rename when not uploading
wb.Rename(id, "two")
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
assert.False(t, pi1.cancelled)
assert.Equal(t, wbItem.name, "two")
// add item
pi2 := newPutItem(t)
id = wb.Add(id, "two", 10, true, pi2.put)
wbItem = wb.lookup[id]
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
assert.Equal(t, wbItem.name, "two")
// wait for upload to start
<-pi2.started
checkNotOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
// rename when uploading - goes back on heap
wb.Rename(id, "three")
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
assert.True(t, pi2.cancelled)
assert.Equal(t, wbItem.name, "three")
}
// TestWriteBackRenameDuplicates checks that if we rename an entry and
// make a duplicate, we remove the duplicate.
func TestWriteBackRenameDuplicates(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
// add item "one", 10
pi1 := newPutItem(t)
id1 := wb.Add(0, "one", 10, true, pi1.put)
wbItem1 := wb.lookup[id1]
checkOnHeap(t, wb, wbItem1)
checkInLookup(t, wb, wbItem1)
assert.Equal(t, wbItem1.name, "one")
<-pi1.started
checkNotOnHeap(t, wb, wbItem1)
checkInLookup(t, wb, wbItem1)
// add item "two"
pi2 := newPutItem(t)
id2 := wb.Add(0, "two", 10, true, pi2.put)
wbItem2 := wb.lookup[id2]
checkOnHeap(t, wb, wbItem2)
checkInLookup(t, wb, wbItem2)
assert.Equal(t, wbItem2.name, "two")
<-pi2.started
checkNotOnHeap(t, wb, wbItem2)
checkInLookup(t, wb, wbItem2)
// rename "two" to "one"
wb.Rename(id2, "one")
// check "one" is cancelled and removed from heap and lookup
checkNotOnHeap(t, wb, wbItem1)
checkNotInLookup(t, wb, wbItem1)
assert.True(t, pi1.cancelled)
assert.Equal(t, wbItem1.name, "one")
// check "two" (now called "one"!) has been cancelled and will
// be retried
checkOnHeap(t, wb, wbItem2)
checkInLookup(t, wb, wbItem2)
assert.True(t, pi2.cancelled)
assert.Equal(t, wbItem2.name, "one")
}
func TestWriteBackCancelUpload(t *testing.T) {
wb, cancel := newTestWriteBack(t)
defer cancel()
// cancel when not in writeback
assert.False(t, wb.cancelUpload(1))
// add item
pi := newPutItem(t)
id := wb.Add(0, "one", 10, true, pi.put)
wbItem := wb.lookup[id]
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
// cancel when not uploading
assert.False(t, wb.cancelUpload(id))
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
// wait for upload to start
<-pi.started
checkNotOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
// cancel when uploading
assert.True(t, wb.cancelUpload(id))
checkOnHeap(t, wb, wbItem)
checkInLookup(t, wb, wbItem)
assert.True(t, pi.cancelled)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/write_other.go | vfs/vfstest/write_other.go | //go:build !linux && !darwin && !freebsd && !windows
package vfstest
import (
"errors"
"runtime"
"testing"
)
// TestWriteFileDoubleClose tests double close on write
func TestWriteFileDoubleClose(t *testing.T) {
t.Skip("not supported on " + runtime.GOOS)
}
// writeTestDup performs the platform-specific implementation of the dup() unix
func writeTestDup(oldfd uintptr) (uintptr, error) {
return 0, errors.New("not supported on " + runtime.GOOS)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/file.go | vfs/vfstest/file.go | package vfstest
import (
"os"
"runtime"
"testing"
"time"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/vfs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestFileModTime tests mod times on files
func TestFileModTime(t *testing.T) {
run.skipIfNoFUSE(t)
run.createFile(t, "file", "123")
mtime := time.Date(2012, time.November, 18, 17, 32, 31, 0, time.UTC)
err := run.os.Chtimes(run.path("file"), mtime, mtime)
require.NoError(t, err)
info, err := run.os.Stat(run.path("file"))
require.NoError(t, err)
// avoid errors because of timezone differences
assert.Equal(t, info.ModTime().Unix(), mtime.Unix())
run.rm(t, "file")
}
// run.os.Create without opening for write too
func osCreate(name string) (vfs.OsFiler, error) {
return run.os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
}
// run.os.Create with append
func osAppend(name string) (vfs.OsFiler, error) {
return run.os.OpenFile(name, os.O_WRONLY|os.O_APPEND, 0666)
}
// TestFileModTimeWithOpenWriters tests mod time on open files
func TestFileModTimeWithOpenWriters(t *testing.T) {
run.skipIfNoFUSE(t)
if runtime.GOOS == "windows" {
t.Skip("Skipping test on Windows")
}
mtime := time.Date(2012, time.November, 18, 17, 32, 31, 0, time.UTC)
filepath := run.path("cp-archive-test")
f, err := osCreate(filepath)
require.NoError(t, err)
_, err = f.Write([]byte{104, 105})
require.NoError(t, err)
err = run.os.Chtimes(filepath, mtime, mtime)
require.NoError(t, err)
err = f.Close()
require.NoError(t, err)
run.waitForWriters()
info, err := run.os.Stat(filepath)
require.NoError(t, err)
// avoid errors because of timezone differences
assert.Equal(t, info.ModTime().Unix(), mtime.Unix())
run.rm(t, "cp-archive-test")
}
// TestSymlinks tests all the api of the VFS / Mount symlinks support
func TestSymlinks(t *testing.T) {
run.skipIfNoFUSE(t)
if !run.vfsOpt.Links {
t.Skip("No symlinks configured")
}
if runtime.GOOS == "windows" {
t.Skip("Skipping test on Windows")
}
fs.Logf(nil, "Links: %v, useVFS: %v, suffix: %v", run.vfsOpt.Links, run.useVFS, fs.LinkSuffix)
// Create initial setup of test files and directories we will create links to
run.mkdir(t, "dir1")
run.mkdir(t, "dir1/sub1dir1")
run.createFile(t, "dir1/file1", "potato")
run.mkdir(t, "dir2")
run.mkdir(t, "dir2/sub1dir2")
run.createFile(t, "dir2/file1", "chicken")
// base state all the tests will be build off
baseState := "dir1/|dir1/sub1dir1/|dir1/file1 6|dir2/|dir2/sub1dir2/|dir2/file1 7"
// Check the tests return to the base state
checkBaseState := func() {
run.checkDir(t, baseState)
}
checkBaseState()
t.Run("FileLink", func(t *testing.T) {
// Link to a file
run.symlink(t, "dir1/file1", "dir1file1_link")
run.checkDir(t, baseState+"|dir1file1_link 10")
run.checkMode(t, "dir1file1_link", os.FileMode(run.vfsOpt.LinkPerms), os.FileMode(run.vfsOpt.FilePerms))
assert.Equal(t, "dir1/file1", run.readlink(t, "dir1file1_link"))
// Read through a symlink
assert.Equal(t, "potato", run.readFile(t, "dir1file1_link"))
// Write through a symlink
err := writeFile(run.path("dir1file1_link"), []byte("carrot"), 0600)
require.NoError(t, err)
assert.Equal(t, "carrot", run.readFile(t, "dir1file1_link"))
assert.Equal(t, "carrot", run.readFile(t, "dir1/file1"))
// Rename a symlink
err = run.os.Rename(run.path("dir1file1_link"), run.path("dir1file1_link")+"_bla")
require.NoError(t, err)
run.checkDir(t, baseState+"|dir1file1_link_bla 10")
assert.Equal(t, "dir1/file1", run.readlink(t, "dir1file1_link_bla"))
// Delete a symlink
run.rm(t, "dir1file1_link_bla")
checkBaseState()
})
t.Run("DirLink", func(t *testing.T) {
// Link to a dir
run.symlink(t, "dir1", "dir1_link")
run.checkDir(t, baseState+"|dir1_link 4")
run.checkMode(t, "dir1_link", os.FileMode(run.vfsOpt.LinkPerms), os.FileMode(run.vfsOpt.DirPerms))
assert.Equal(t, "dir1", run.readlink(t, "dir1_link"))
// Check you can't open a directory symlink
_, err := run.os.OpenFile(run.path("dir1_link"), os.O_WRONLY, 0600)
require.Error(t, err)
// Our symlink resolution is very simple when using the VFS as when using the
// mount the OS will resolve the symlinks, so we don't recurse here
// Read entries directly
dir1Entries := make(dirMap)
run.readLocalEx(t, dir1Entries, "dir1", false)
assert.Equal(t, newDirMap("dir1/sub1dir1/|dir1/file1 6"), dir1Entries)
// Read entries through the directory symlink
dir1EntriesSymlink := make(dirMap)
run.readLocalEx(t, dir1EntriesSymlink, "dir1_link", false)
assert.Equal(t, newDirMap("dir1_link/sub1dir1/|dir1_link/file1 6"), dir1EntriesSymlink)
// Rename directory symlink
err = run.os.Rename(run.path("dir1_link"), run.path("dir1_link")+"_bla")
require.NoError(t, err)
run.checkDir(t, baseState+"|dir1_link_bla 4")
assert.Equal(t, "dir1", run.readlink(t, "dir1_link_bla"))
// Remove directory symlink
run.rm(t, "dir1_link_bla")
checkBaseState()
})
// Corner case #1 - We do not allow creating regular and symlink files having the same name (ie, test.txt and test.txt.rclonelink)
// Symlink first, then regular
t.Run("OverwriteSymlinkWithRegular", func(t *testing.T) {
link1Name := "link1.txt"
run.symlink(t, "dir1/file1", link1Name)
run.checkDir(t, baseState+"|link1.txt 10")
fh, err := run.os.OpenFile(run.path(link1Name), os.O_WRONLY|os.O_CREATE, os.FileMode(run.vfsOpt.FilePerms))
// On real mount with links enabled, that open the symlink target as expected, else that fails to create a new file
assert.NoError(t, err)
// Don't care about the result, in some cache mode the file can't be opened for writing, so closing would trigger an err
_ = fh.Close()
run.rm(t, link1Name)
checkBaseState()
})
// Regular first, then symlink
t.Run("OverwriteRegularWithSymlink", func(t *testing.T) {
link1Name := "link1.txt"
run.createFile(t, link1Name, "")
run.checkDir(t, baseState+"|link1.txt 0")
err := run.os.Symlink(".", run.path(link1Name))
assert.Error(t, err)
run.rm(t, link1Name)
checkBaseState()
})
// Corner case #2 - We do not allow creating directory and symlink file having the same name (ie, test and test.rclonelink)
// Symlink first, then directory
t.Run("OverwriteSymlinkWithDirectory", func(t *testing.T) {
link1Name := "link1"
run.symlink(t, ".", link1Name)
run.checkDir(t, baseState+"|link1 1")
err := run.os.Mkdir(run.path(link1Name), os.FileMode(run.vfsOpt.DirPerms))
assert.Error(t, err)
run.rm(t, link1Name)
checkBaseState()
})
// Directory first, then symlink
t.Run("OverwriteDirectoryWithSymlink", func(t *testing.T) {
link1Name := "link1"
run.mkdir(t, link1Name)
run.checkDir(t, baseState+"|link1/")
err := run.os.Symlink(".", run.path(link1Name))
assert.Error(t, err)
run.rm(t, link1Name)
checkBaseState()
})
// Corner case #3 - We do not allow moving directory or file having the same name in a target (ie, test and test.rclonelink)
// Move symlink -> regular file
t.Run("MoveSymlinkToFile", func(t *testing.T) {
t.Skip("FIXME not implemented")
link1Name := "link1.txt"
run.symlink(t, ".", link1Name)
run.createFile(t, "dir1/link1.txt", "")
run.checkDir(t, baseState+"|link1.txt 1|dir1/link1.txt 0")
err := run.os.Rename(run.path(link1Name), run.path("dir1/"+link1Name))
assert.Error(t, err)
run.rm(t, link1Name)
run.rm(t, "dir1/link1.txt")
checkBaseState()
})
// Move regular file -> symlink
t.Run("MoveFileToSymlink", func(t *testing.T) {
t.Skip("FIXME not implemented")
link1Name := "link1.txt"
run.createFile(t, link1Name, "")
run.symlink(t, ".", "dir1/"+link1Name)
run.checkDir(t, baseState+"|link1.txt 0|dir1/link1.txt 1")
err := run.os.Rename(run.path(link1Name), run.path("dir1/link1.txt"))
assert.Error(t, err)
run.rm(t, link1Name)
run.rm(t, "dir1/"+link1Name)
checkBaseState()
})
// Move symlink -> directory
t.Run("MoveSymlinkToDirectory", func(t *testing.T) {
t.Skip("FIXME not implemented")
link1Name := "link1"
run.symlink(t, ".", link1Name)
run.mkdir(t, "dir1/link1")
run.checkDir(t, baseState+"|link1 1|dir1/link1/")
err := run.os.Rename(run.path(link1Name), run.path("dir1/"+link1Name))
assert.Error(t, err)
run.rm(t, link1Name)
run.rm(t, "dir1/link1")
checkBaseState()
})
// Move directory -> symlink
t.Run("MoveDirectoryToSymlink", func(t *testing.T) {
t.Skip("FIXME not implemented")
link1Name := "dir1/link1"
run.mkdir(t, "link1")
run.symlink(t, ".", link1Name)
run.checkDir(t, baseState+"|link1/|dir1/link1 1")
err := run.os.Rename(run.path("link1"), run.path("dir1/link1"))
assert.Error(t, err)
run.rm(t, "link1")
run.rm(t, link1Name)
checkBaseState()
})
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/read_unix.go | vfs/vfstest/read_unix.go | //go:build linux || darwin || freebsd
package vfstest
import (
"syscall"
"testing"
"github.com/stretchr/testify/assert"
)
// TestReadFileDoubleClose tests double close on read
func TestReadFileDoubleClose(t *testing.T) {
run.skipIfVFS(t)
run.skipIfNoFUSE(t)
run.createFile(t, "testdoubleclose", "hello")
in, err := run.os.Open(run.path("testdoubleclose"))
assert.NoError(t, err)
fd := in.Fd()
fd1, err := syscall.Dup(int(fd))
assert.NoError(t, err)
fd2, err := syscall.Dup(int(fd))
assert.NoError(t, err)
// close one of the dups - should produce no error
err = syscall.Close(fd1)
assert.NoError(t, err)
// read from the file
buf := make([]byte, 1)
_, err = in.Read(buf)
assert.NoError(t, err)
// close it
err = in.Close()
assert.NoError(t, err)
// read from the other dup - should produce no error as this
// file is now buffered
n, err := syscall.Read(fd2, buf)
assert.NoError(t, err)
assert.Equal(t, 1, n)
// close the dup - should not produce an error
err = syscall.Close(fd2)
assert.NoError(t, err, "input/output error")
run.rm(t, "testdoubleclose")
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/submount.go | vfs/vfstest/submount.go | package vfstest
import (
"bufio"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"os"
"os/exec"
"runtime"
"strings"
"time"
"github.com/rclone/rclone/cmd/mountlib"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/cache"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/lib/file"
"github.com/rclone/rclone/vfs"
"github.com/rclone/rclone/vfs/vfscommon"
)
// Functions to run and control the mount subprocess
var (
runMount = flag.String("run-mount", "", "If set, run the mount subprocess with the options (internal use only)")
)
// Options for the mount sub processes passed with the -run-mount flag
type runMountOpt struct {
MountPoint string
MountOpt mountlib.Options
VFSOpt vfscommon.Options
Remote string
}
// Start the mount subprocess and wait for it to start
func (r *Run) startMountSubProcess() {
// If testing the VFS we don't start a subprocess, we just use
// the VFS directly
if r.useVFS {
vfs := vfs.New(r.fremote, r.vfsOpt)
r.os = vfsOs{vfs}
return
}
r.os = realOs{}
r.mountPath = findMountPath()
fs.Logf(nil, "startMountSubProcess %q (%q) %q", r.fremote, r.fremoteName, r.mountPath)
opt := runMountOpt{
MountPoint: r.mountPath,
MountOpt: mountlib.Opt,
VFSOpt: *r.vfsOpt,
Remote: r.fremoteName,
}
opts, err := json.Marshal(&opt)
if err != nil {
fs.Fatal(nil, fmt.Sprint(err))
}
// Re-run this executable with a new option -run-mount
args := append(os.Args, "-run-mount", string(opts))
r.cmd = exec.Command(args[0], args[1:]...)
r.cmd.Stderr = os.Stderr
r.out, err = r.cmd.StdinPipe()
if err != nil {
fs.Fatal(nil, fmt.Sprint(err))
}
r.in, err = r.cmd.StdoutPipe()
if err != nil {
fs.Fatal(nil, fmt.Sprint(err))
}
err = r.cmd.Start()
if err != nil {
fs.Fatal(nil, fmt.Sprint("startMountSubProcess failed", err))
}
r.scanner = bufio.NewScanner(r.in)
// Wait it for startup
fs.Log(nil, "Waiting for mount to start")
for r.scanner.Scan() {
rx := strings.TrimSpace(r.scanner.Text())
if rx == "STARTED" {
break
}
fs.Logf(nil, "..Mount said: %s", rx)
}
if r.scanner.Err() != nil {
fs.Logf(nil, "scanner err %v", r.scanner.Err())
}
fs.Logf(nil, "startMountSubProcess: end")
}
// Find a free path to run the mount on
func findMountPath() string {
if runtime.GOOS != "windows" {
mountPath, err := os.MkdirTemp("", "rclonefs-mount")
if err != nil {
fs.Fatalf(nil, "Failed to create mount dir: %v", err)
}
return mountPath
}
// Find a free drive letter
letter := file.FindUnusedDriveLetter()
drive := ""
if letter == 0 {
fs.Fatalf(nil, "Couldn't find free drive letter for test")
} else {
drive = string(letter) + ":"
}
return drive
}
// Return true if we are running as a subprocess to run the mount
func isSubProcess() bool {
return *runMount != ""
}
// Run the mount - this is running in a subprocesses and the config
// is passed JSON encoded as the -run-mount parameter
//
// It reads commands from standard input and writes results to
// standard output.
func startMount(mountFn mountlib.MountFn, useVFS bool, opts string) {
fs.Log(nil, "startMount")
ctx := context.Background()
var opt runMountOpt
err := json.Unmarshal([]byte(opts), &opt)
if err != nil {
fs.Fatalf(nil, "Unmarshal failed: %v", err)
}
fstest.Initialise()
f, err := cache.Get(ctx, opt.Remote)
if err != nil {
fs.Fatalf(nil, "Failed to open remote %q: %v", opt.Remote, err)
}
err = f.Mkdir(ctx, "")
if err != nil {
fs.Fatalf(nil, "Failed to mkdir %q: %v", opt.Remote, err)
}
fs.Logf(nil, "startMount: Mounting %q on %q with %q", opt.Remote, opt.MountPoint, opt.VFSOpt.CacheMode)
mnt := mountlib.NewMountPoint(mountFn, opt.MountPoint, f, &opt.MountOpt, &opt.VFSOpt)
_, err = mnt.Mount()
if err != nil {
fs.Fatalf(nil, "mount FAILED %q: %v", opt.Remote, err)
}
defer umount(mnt)
fs.Logf(nil, "startMount: mount OK")
fmt.Println("STARTED") // signal to parent all is good
// Read commands from stdin
scanner := bufio.NewScanner(os.Stdin)
exit := false
for !exit && scanner.Scan() {
rx := strings.Trim(scanner.Text(), "\r\n")
var tx string
tx, exit = doMountCommand(mnt.VFS, rx)
fmt.Println(tx)
}
err = scanner.Err()
if err != nil {
fs.Fatalf(nil, "scanner failed %q: %v", opt.Remote, err)
}
}
// Do a mount command which is a line read from stdin and return a
// line to send to stdout with an exit flag.
//
// The format of the lines is
//
// command \t parameter (optional)
//
// The response should be
//
// OK|ERR \t result (optional)
func doMountCommand(vfs *vfs.VFS, rx string) (tx string, exit bool) {
command := strings.Split(rx, "\t")
// log.Printf("doMountCommand: %q received", command)
var out = []string{"OK", ""}
switch command[0] {
case "waitForWriters":
vfs.WaitForWriters(waitForWritersDelay)
case "forget":
root, err := vfs.Root()
if err != nil {
out = []string{"ERR", err.Error()}
} else {
root.ForgetPath(command[1], fs.EntryDirectory)
}
case "exit":
exit = true
default:
out = []string{"ERR", "command not found"}
}
return strings.Join(out, "\t"), exit
}
// Send a command to the mount subprocess and await a response
func (r *Run) sendMountCommand(args ...string) {
r.cmdMu.Lock()
defer r.cmdMu.Unlock()
tx := strings.Join(args, "\t")
// log.Printf("Send mount command: %q", tx)
var rx string
if r.useVFS {
// if using VFS do the VFS command directly
rx, _ = doMountCommand(r.os.(vfsOs).VFS, tx)
} else {
_, err := io.WriteString(r.out, tx+"\n")
if err != nil {
fs.Fatalf(nil, "WriteString err %v", err)
}
if !r.scanner.Scan() {
fs.Fatalf(nil, "Mount has gone away")
}
rx = strings.Trim(r.scanner.Text(), "\r\n")
}
in := strings.Split(rx, "\t")
// log.Printf("Answer is %q", in)
if in[0] != "OK" {
fs.Fatalf(nil, "Error from mount: %q", in[1:])
}
}
// wait for any files being written to be released by fuse
func (r *Run) waitForWriters() {
r.sendMountCommand("waitForWriters")
}
// forget the directory passed in
func (r *Run) forget(dir string) {
r.sendMountCommand("forget", dir)
}
// Unmount the mount
func umount(mnt *mountlib.MountPoint) {
/*
log.Printf("Calling fusermount -u %q", mountPath)
err := exec.Command("fusermount", "-u", mountPath).Run()
if err != nil {
log.Printf("fusermount failed: %v", err)
}
*/
fs.Logf(nil, "Unmounting %q", mnt.MountPoint)
err := mnt.Unmount()
if err != nil {
fs.Logf(nil, "signal to umount failed - retrying: %v", err)
time.Sleep(3 * time.Second)
err = mnt.Unmount()
}
if err != nil {
fs.Fatalf(nil, "signal to umount failed: %v", err)
}
fs.Logf(nil, "Waiting for umount")
err = <-mnt.ErrChan
if err != nil {
fs.Fatalf(nil, "umount failed: %v", err)
}
// Cleanup the VFS cache - umount has called Shutdown
err = mnt.VFS.CleanUp()
if err != nil {
fs.Logf(nil, "Failed to cleanup the VFS cache: %v", err)
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/read_non_unix.go | vfs/vfstest/read_non_unix.go | //go:build !linux && !darwin && !freebsd
package vfstest
import (
"runtime"
"testing"
)
// TestReadFileDoubleClose tests double close on read
func TestReadFileDoubleClose(t *testing.T) {
t.Skip("not supported on " + runtime.GOOS)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/write_windows.go | vfs/vfstest/write_windows.go | //go:build windows
package vfstest
import (
"runtime"
"testing"
"golang.org/x/sys/windows"
)
// TestWriteFileDoubleClose tests double close on write
func TestWriteFileDoubleClose(t *testing.T) {
t.Skip("not supported on " + runtime.GOOS)
}
// writeTestDup performs the platform-specific implementation of the dup() syscall
func writeTestDup(oldfd uintptr) (uintptr, error) {
p := windows.CurrentProcess()
var h windows.Handle
return uintptr(h), windows.DuplicateHandle(p, windows.Handle(oldfd), p, &h, 0, true, windows.DUPLICATE_SAME_ACCESS)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/vfs.go | vfs/vfstest/vfs.go | // Package vfstest provides tests for VFS.
package vfstest
import (
"os"
"github.com/rclone/rclone/vfs"
)
// vfsOs is an implementation of Oser backed by the "vfs" package
type vfsOs struct {
*vfs.VFS
}
// Stat
func (v vfsOs) Stat(path string) (os.FileInfo, error) {
return v.VFS.Stat(path)
}
// Check interfaces
var _ Oser = vfsOs{}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/write.go | vfs/vfstest/write.go | package vfstest
import (
"os"
"runtime"
"testing"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestWriteFileNoWrite tests writing a file with no write()'s to it
func TestWriteFileNoWrite(t *testing.T) {
run.skipIfNoFUSE(t)
fd, err := osCreate(run.path("testnowrite"))
require.NoError(t, err)
err = fd.Close()
assert.NoError(t, err)
run.waitForWriters()
run.checkDir(t, "testnowrite 0")
run.rm(t, "testnowrite")
}
// FIXMETestWriteOpenFileInDirListing tests open file in directory listing
func FIXMETestWriteOpenFileInDirListing(t *testing.T) {
run.skipIfNoFUSE(t)
fd, err := osCreate(run.path("testnowrite"))
assert.NoError(t, err)
run.checkDir(t, "testnowrite 0")
err = fd.Close()
assert.NoError(t, err)
run.waitForWriters()
run.rm(t, "testnowrite")
}
// TestWriteFileWrite tests writing a file and reading it back
func TestWriteFileWrite(t *testing.T) {
run.skipIfNoFUSE(t)
run.createFile(t, "testwrite", "data")
run.checkDir(t, "testwrite 4")
contents := run.readFile(t, "testwrite")
assert.Equal(t, "data", contents)
run.rm(t, "testwrite")
}
// TestWriteFileOverwrite tests overwriting a file
func TestWriteFileOverwrite(t *testing.T) {
run.skipIfNoFUSE(t)
run.createFile(t, "testwrite", "data")
run.checkDir(t, "testwrite 4")
run.createFile(t, "testwrite", "potato")
contents := run.readFile(t, "testwrite")
assert.Equal(t, "potato", contents)
run.rm(t, "testwrite")
}
// TestWriteFileFsync tests Fsync
//
// NB the code for this is in file.go rather than write.go
func TestWriteFileFsync(t *testing.T) {
run.skipIfNoFUSE(t)
filepath := run.path("to be synced")
fd, err := osCreate(filepath)
require.NoError(t, err)
_, err = fd.Write([]byte("hello"))
require.NoError(t, err)
err = fd.Sync()
require.NoError(t, err)
err = fd.Close()
require.NoError(t, err)
run.waitForWriters()
run.rm(t, "to be synced")
}
// TestWriteFileDup tests behavior of mmap() in Python by using dup() on a file handle
func TestWriteFileDup(t *testing.T) {
run.skipIfVFS(t)
run.skipIfNoFUSE(t)
if run.vfsOpt.CacheMode < vfscommon.CacheModeWrites {
t.Skip("not supported on vfs-cache-mode < writes")
return
}
filepath := run.path("to be synced")
fh, err := osCreate(filepath)
require.NoError(t, err)
testData := []byte("0123456789")
err = fh.Truncate(int64(len(testData) + 2))
require.NoError(t, err)
err = fh.Sync()
require.NoError(t, err)
var dupFd uintptr
dupFd, err = writeTestDup(fh.Fd())
require.NoError(t, err)
dupFile := os.NewFile(dupFd, fh.Name())
_, err = dupFile.Write(testData)
require.NoError(t, err)
err = dupFile.Close()
require.NoError(t, err)
_, err = fh.Seek(int64(len(testData)), 0)
require.NoError(t, err)
_, err = fh.Write([]byte("10"))
require.NoError(t, err)
err = fh.Close()
require.NoError(t, err)
run.waitForWriters()
run.rm(t, "to be synced")
}
// TestWriteFileAppend tests that O_APPEND works on cache backends >= writes
func TestWriteFileAppend(t *testing.T) {
run.skipIfNoFUSE(t)
if run.vfsOpt.CacheMode < vfscommon.CacheModeWrites {
t.Skip("not supported on vfs-cache-mode < writes")
return
}
// TODO: Windows needs the v1.5 release of WinFsp to handle O_APPEND properly.
// Until it gets released, skip this test on Windows.
if runtime.GOOS == "windows" {
t.Skip("currently unsupported on Windows")
}
filepath := run.path("to be synced")
fh, err := osCreate(filepath)
require.NoError(t, err)
testData := []byte("0123456789")
appendData := []byte("10")
_, err = fh.Write(testData)
require.NoError(t, err)
err = fh.Close()
require.NoError(t, err)
fh, err = osAppend(filepath)
require.NoError(t, err)
_, err = fh.Write(appendData)
require.NoError(t, err)
err = fh.Close()
require.NoError(t, err)
info, err := run.os.Stat(filepath)
require.NoError(t, err)
require.EqualValues(t, len(testData)+len(appendData), info.Size())
run.waitForWriters()
run.rm(t, "to be synced")
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/read.go | vfs/vfstest/read.go | package vfstest
import (
"io"
"testing"
"github.com/stretchr/testify/assert"
)
// TestReadByByte reads by byte including don't read any bytes
func TestReadByByte(t *testing.T) {
run.skipIfNoFUSE(t)
var data = []byte("hellohello")
run.createFile(t, "testfile", string(data))
run.checkDir(t, "testfile 10")
for i := range data {
fd, err := run.os.Open(run.path("testfile"))
assert.NoError(t, err)
for j := range i {
buf := make([]byte, 1)
n, err := io.ReadFull(fd, buf)
assert.NoError(t, err)
assert.Equal(t, 1, n)
assert.Equal(t, buf[0], data[j])
}
err = fd.Close()
assert.NoError(t, err)
}
run.rm(t, "testfile")
}
// TestReadChecksum checks the checksum reading is working
func TestReadChecksum(t *testing.T) {
run.skipIfNoFUSE(t)
// create file big enough so we exceed any single FUSE read
// request
b := make([]rune, 3*128*1024)
for i := range b {
b[i] = 'r'
}
run.createFile(t, "bigfile", string(b))
// The hash comparison would fail in Flush, if we did not
// ensure we read the whole file
fd, err := run.os.Open(run.path("bigfile"))
assert.NoError(t, err)
buf := make([]byte, 10)
_, err = io.ReadFull(fd, buf)
assert.NoError(t, err)
err = fd.Close()
assert.NoError(t, err)
// The hash comparison would fail, because we only read parts
// of the file
fd, err = run.os.Open(run.path("bigfile"))
assert.NoError(t, err)
// read at start
_, err = io.ReadFull(fd, buf)
assert.NoError(t, err)
// read at end
_, err = fd.Seek(int64(len(b)-len(buf)), io.SeekStart)
assert.NoError(t, err)
_, err = io.ReadFull(fd, buf)
assert.NoError(t, err)
// ensure we don't compare hashes
err = fd.Close()
assert.NoError(t, err)
run.rm(t, "bigfile")
}
// TestReadSeek test seeking
func TestReadSeek(t *testing.T) {
run.skipIfNoFUSE(t)
var data = []byte("helloHELLO")
run.createFile(t, "testfile", string(data))
run.checkDir(t, "testfile 10")
fd, err := run.os.Open(run.path("testfile"))
assert.NoError(t, err)
// Seek to half way
_, err = fd.Seek(5, io.SeekStart)
assert.NoError(t, err)
buf, err := io.ReadAll(fd)
assert.NoError(t, err)
assert.Equal(t, buf, []byte("HELLO"))
// Test seeking to the end
_, err = fd.Seek(10, io.SeekStart)
assert.NoError(t, err)
buf, err = io.ReadAll(fd)
assert.NoError(t, err)
assert.Equal(t, buf, []byte(""))
// Test seeking beyond the end
_, err = fd.Seek(1000000, io.SeekStart)
assert.NoError(t, err)
buf, err = io.ReadAll(fd)
assert.NoError(t, err)
assert.Equal(t, buf, []byte(""))
// Now back to the start
_, err = fd.Seek(0, io.SeekStart)
assert.NoError(t, err)
buf, err = io.ReadAll(fd)
assert.NoError(t, err)
assert.Equal(t, buf, []byte("helloHELLO"))
err = fd.Close()
assert.NoError(t, err)
run.rm(t, "testfile")
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/write_unix.go | vfs/vfstest/write_unix.go | //go:build linux || darwin || freebsd
package vfstest
import (
"runtime"
"testing"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/sys/unix"
)
// TestWriteFileDoubleClose tests double close on write
func TestWriteFileDoubleClose(t *testing.T) {
run.skipIfVFS(t)
run.skipIfNoFUSE(t)
if runtime.GOOS == "darwin" {
t.Skip("Skipping test on OSX")
}
out, err := osCreate(run.path("testdoubleclose"))
require.NoError(t, err)
fd := out.Fd()
fd1, err := unix.Dup(int(fd))
assert.NoError(t, err)
fd2, err := unix.Dup(int(fd))
assert.NoError(t, err)
// close one of the dups - should produce no error
err = unix.Close(fd1)
assert.NoError(t, err)
// write to the file
buf := []byte("hello")
n, err := out.Write(buf)
assert.NoError(t, err)
assert.Equal(t, 5, n)
// close it
err = out.Close()
assert.NoError(t, err)
// write to the other dup
_, err = unix.Write(fd2, buf)
if run.vfsOpt.CacheMode < vfscommon.CacheModeWrites {
// produces an error if cache mode < writes
assert.Error(t, err, "input/output error")
} else {
// otherwise does not produce an error
assert.NoError(t, err)
}
// close the dup - should not produce an error
err = unix.Close(fd2)
assert.NoError(t, err)
run.waitForWriters()
run.rm(t, "testdoubleclose")
}
// writeTestDup performs the platform-specific implementation of the dup() unix
func writeTestDup(oldfd uintptr) (uintptr, error) {
newfd, err := unix.Dup(int(oldfd))
return uintptr(newfd), err
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/os.go | vfs/vfstest/os.go | package vfstest
import (
"os"
"time"
"github.com/rclone/rclone/lib/file"
"github.com/rclone/rclone/vfs"
)
// Oser defines the things that the "os" package can do
//
// This covers what the VFS can do also
type Oser interface {
Chtimes(name string, atime time.Time, mtime time.Time) error
Create(name string) (vfs.Handle, error)
Mkdir(name string, perm os.FileMode) error
Open(name string) (vfs.Handle, error)
OpenFile(name string, flags int, perm os.FileMode) (fd vfs.Handle, err error)
ReadDir(dirname string) ([]os.FileInfo, error)
ReadFile(filename string) (b []byte, err error)
Remove(name string) error
Rename(oldName, newName string) error
Stat(path string) (os.FileInfo, error)
Symlink(oldname, newname string) error
Readlink(name string) (s string, err error)
}
// realOs is an implementation of Oser backed by the "os" package
type realOs struct {
}
// realOsFile is an implementation of vfs.Handle
type realOsFile struct {
*os.File
}
// Flush
func (f realOsFile) Flush() error {
return nil
}
// Release
func (f realOsFile) Release() error {
return f.File.Close()
}
// Node
func (f realOsFile) Node() vfs.Node {
return nil
}
func (f realOsFile) Lock() error {
return os.ErrInvalid
}
func (f realOsFile) Unlock() error {
return os.ErrInvalid
}
// Chtimes
func (r realOs) Chtimes(name string, atime time.Time, mtime time.Time) error {
return os.Chtimes(name, atime, mtime)
}
// Create
func (r realOs) Create(name string) (vfs.Handle, error) {
fd, err := file.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return nil, err
}
return realOsFile{File: fd}, err
}
// Mkdir
func (r realOs) Mkdir(name string, perm os.FileMode) error {
return os.Mkdir(name, perm)
}
// Open
func (r realOs) Open(name string) (vfs.Handle, error) {
fd, err := os.Open(name)
if err != nil {
return nil, err
}
return realOsFile{File: fd}, err
}
// OpenFile
func (r realOs) OpenFile(name string, flags int, perm os.FileMode) (vfs.Handle, error) {
fd, err := file.OpenFile(name, flags, perm)
if err != nil {
return nil, err
}
return realOsFile{File: fd}, err
}
// ReadDir
func (r realOs) ReadDir(dirname string) ([]os.FileInfo, error) {
entries, err := os.ReadDir(dirname)
if err != nil {
return nil, err
}
infos := make([]os.FileInfo, 0, len(entries))
for _, entry := range entries {
info, err := entry.Info()
if err != nil {
return nil, err
}
infos = append(infos, info)
}
return infos, nil
}
// ReadFile
func (r realOs) ReadFile(filename string) (b []byte, err error) {
return os.ReadFile(filename)
}
// Remove
func (r realOs) Remove(name string) error {
return os.Remove(name)
}
// Rename
func (r realOs) Rename(oldName, newName string) error {
return os.Rename(oldName, newName)
}
// Stat
func (r realOs) Stat(path string) (os.FileInfo, error) {
return os.Stat(path)
}
// Symlink
func (r realOs) Symlink(oldname, newname string) error {
return os.Symlink(oldname, newname)
}
// Readlink
func (r realOs) Readlink(name string) (s string, err error) {
return os.Readlink(name)
}
// Check interfaces
var _ Oser = &realOs{}
var _ vfs.Handle = &realOsFile{}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/fs.go | vfs/vfstest/fs.go | // Test suite for rclonefs
package vfstest
import (
"bufio"
"context"
"flag"
"fmt"
"io"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"runtime"
"strings"
"sync"
"testing"
"time"
_ "github.com/rclone/rclone/backend/all" // import all the backends
"github.com/rclone/rclone/cmd/mountlib"
"github.com/rclone/rclone/fs"
"github.com/rclone/rclone/fs/walk"
"github.com/rclone/rclone/fstest"
"github.com/rclone/rclone/vfs/vfscommon"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
const (
waitForWritersDelay = 30 * time.Second // time to wait for existing writers
)
// RunTests runs all the tests against all the VFS cache modes
//
// If useVFS is set then it runs the tests against a VFS rather than a
// mount
//
// If useVFS is not set then it runs the mount in a subprocess in
// order to avoid kernel deadlocks.
func RunTests(t *testing.T, useVFS bool, minimumRequiredCacheMode vfscommon.CacheMode, enableCacheTests bool, mountFn mountlib.MountFn) {
flag.Parse()
if isSubProcess() {
startMount(mountFn, useVFS, *runMount)
return
}
tests := []struct {
cacheMode vfscommon.CacheMode
writeBack fs.Duration
links bool
}{
{cacheMode: vfscommon.CacheModeOff},
{cacheMode: vfscommon.CacheModeOff, links: true},
{cacheMode: vfscommon.CacheModeMinimal},
{cacheMode: vfscommon.CacheModeWrites},
{cacheMode: vfscommon.CacheModeFull},
{cacheMode: vfscommon.CacheModeFull, writeBack: fs.Duration(100 * time.Millisecond)},
{cacheMode: vfscommon.CacheModeFull, writeBack: fs.Duration(100 * time.Millisecond), links: true},
}
for _, test := range tests {
if test.cacheMode < minimumRequiredCacheMode {
continue
}
vfsOpt := vfscommon.Opt
vfsOpt.CacheMode = test.cacheMode
vfsOpt.WriteBack = test.writeBack
vfsOpt.Links = test.links
run = newRun(useVFS, &vfsOpt, mountFn)
what := fmt.Sprintf("CacheMode=%v", test.cacheMode)
if test.writeBack > 0 {
what += fmt.Sprintf(",WriteBack=%v", test.writeBack)
}
if test.links {
what += fmt.Sprintf(",Links=%v", test.links)
}
fs.Logf(nil, "Starting test run with %s", what)
ok := t.Run(what, func(t *testing.T) {
t.Run("TestTouchAndDelete", TestTouchAndDelete)
t.Run("TestRenameOpenHandle", TestRenameOpenHandle)
t.Run("TestDirLs", TestDirLs)
t.Run("TestDirCreateAndRemoveDir", TestDirCreateAndRemoveDir)
t.Run("TestDirCreateAndRemoveFile", TestDirCreateAndRemoveFile)
t.Run("TestDirRenameFile", TestDirRenameFile)
t.Run("TestDirRenameEmptyDir", TestDirRenameEmptyDir)
t.Run("TestDirRenameFullDir", TestDirRenameFullDir)
t.Run("TestDirModTime", TestDirModTime)
if enableCacheTests {
t.Run("TestDirCacheFlush", TestDirCacheFlush)
}
t.Run("TestDirCacheFlushOnDirRename", TestDirCacheFlushOnDirRename)
t.Run("TestFileModTime", TestFileModTime)
t.Run("TestFileModTimeWithOpenWriters", TestFileModTimeWithOpenWriters)
t.Run("TestMount", TestMount)
t.Run("TestRoot", TestRoot)
t.Run("TestReadByByte", TestReadByByte)
t.Run("TestReadChecksum", TestReadChecksum)
t.Run("TestReadFileDoubleClose", TestReadFileDoubleClose)
t.Run("TestReadSeek", TestReadSeek)
t.Run("TestWriteFileNoWrite", TestWriteFileNoWrite)
t.Run("TestWriteFileWrite", TestWriteFileWrite)
t.Run("TestWriteFileOverwrite", TestWriteFileOverwrite)
t.Run("TestWriteFileDoubleClose", TestWriteFileDoubleClose)
t.Run("TestWriteFileFsync", TestWriteFileFsync)
t.Run("TestWriteFileDup", TestWriteFileDup)
t.Run("TestWriteFileAppend", TestWriteFileAppend)
t.Run("TestSymlinks", TestSymlinks)
})
fs.Logf(nil, "Finished test run with %s (ok=%v)", what, ok)
run.Finalise()
if !ok {
break
}
}
}
// Run holds the remotes for a test run
type Run struct {
os Oser
vfsOpt *vfscommon.Options
useVFS bool // set if we are testing a VFS not a mount
mountPath string
fremote fs.Fs
fremoteName string
cleanRemote func()
skip bool
// For controlling the subprocess running the mount
cmdMu sync.Mutex
cmd *exec.Cmd
in io.ReadCloser
out io.WriteCloser
scanner *bufio.Scanner
}
// run holds the master Run data
var run *Run
// newRun initialise the remote mount for testing and returns a run
// object.
//
// r.fremote is an empty remote Fs
//
// Finalise() will tidy them away when done.
func newRun(useVFS bool, vfsOpt *vfscommon.Options, mountFn mountlib.MountFn) *Run {
r := &Run{
useVFS: useVFS,
vfsOpt: vfsOpt,
}
r.vfsOpt.Init()
fstest.Initialise()
var err error
r.fremote, r.fremoteName, r.cleanRemote, err = fstest.RandomRemote()
if err != nil {
fs.Fatalf(nil, "Failed to open remote %q: %v", *fstest.RemoteName, err)
}
err = r.fremote.Mkdir(context.Background(), "")
if err != nil {
fs.Fatalf(nil, "Failed to open mkdir %q: %v", *fstest.RemoteName, err)
}
r.startMountSubProcess()
return r
}
func (r *Run) skipIfNoFUSE(t *testing.T) {
if r.skip {
t.Skip("FUSE not found so skipping test")
}
}
func (r *Run) skipIfVFS(t *testing.T) {
if r.useVFS {
t.Skip("Not running under VFS")
}
}
// Finalise cleans the remote and unmounts
func (r *Run) Finalise() {
if !r.useVFS {
r.sendMountCommand("exit")
_, err := r.cmd.Process.Wait()
if err != nil {
fs.Fatalf(nil, "mount sub process failed: %v", err)
}
}
r.cleanRemote()
if !r.useVFS {
err := os.RemoveAll(r.mountPath)
if err != nil {
fs.Logf(nil, "Failed to clean mountPath %q: %v", r.mountPath, err)
}
}
}
// path returns an OS local path for filepath
func (r *Run) path(filePath string) string {
if r.useVFS {
return filePath
}
// return windows drive letter root as E:\
if filePath == "" && runtime.GOOS == "windows" {
return r.mountPath + `\`
}
return filepath.Join(r.mountPath, filepath.FromSlash(filePath))
}
type dirMap map[string]struct{}
// Create a dirMap from a string
func newDirMap(dirString string) (dm dirMap) {
dm = make(dirMap)
for entry := range strings.SplitSeq(dirString, "|") {
if entry != "" {
dm[entry] = struct{}{}
}
}
return dm
}
// Returns a dirmap with only the files in
func (dm dirMap) filesOnly(stripLinksSuffix bool) dirMap {
newDm := make(dirMap)
for name := range dm {
if !strings.HasSuffix(name, "/") {
if stripLinksSuffix {
index := strings.LastIndex(name, " ")
if index != -1 {
name = strings.TrimSuffix(name[0:index], fs.LinkSuffix) + name[index:]
}
}
newDm[name] = struct{}{}
}
}
return newDm
}
// reads the local tree into dir
//
// If recurse it set it will recurse into subdirectories
func (r *Run) readLocalEx(t *testing.T, dir dirMap, filePath string, recurse bool) {
realPath := r.path(filePath)
files, err := r.os.ReadDir(realPath)
require.NoError(t, err)
for _, fi := range files {
name := path.Join(filePath, fi.Name())
if fi.IsDir() {
dir[name+"/"] = struct{}{}
if recurse {
r.readLocalEx(t, dir, name, recurse)
}
assert.Equal(t, os.FileMode(r.vfsOpt.DirPerms)&os.ModePerm, fi.Mode().Perm())
} else {
dir[fmt.Sprintf("%s %d", name, fi.Size())] = struct{}{}
if fi.Mode()&os.ModeSymlink != 0 {
assert.Equal(t, os.FileMode(r.vfsOpt.LinkPerms)&os.ModePerm, fi.Mode().Perm())
} else {
assert.Equal(t, os.FileMode(r.vfsOpt.FilePerms)&os.ModePerm, fi.Mode().Perm())
}
}
}
}
// reads the local tree into dir
func (r *Run) readLocal(t *testing.T, dir dirMap, filePath string) {
r.readLocalEx(t, dir, filePath, true)
}
// reads the remote tree into dir
func (r *Run) readRemote(t *testing.T, dir dirMap, filepath string) {
objs, dirs, err := walk.GetAll(context.Background(), r.fremote, filepath, true, 1)
if err == fs.ErrorDirNotFound {
return
}
require.NoError(t, err)
for _, obj := range objs {
dir[fmt.Sprintf("%s %d", obj.Remote(), obj.Size())] = struct{}{}
}
for _, d := range dirs {
name := d.Remote()
dir[name+"/"] = struct{}{}
r.readRemote(t, dir, name)
}
}
// checkDir checks the local and remote against the string passed in
func (r *Run) checkDir(t *testing.T, dirString string) {
var retries = *fstest.ListRetries
sleep := time.Second / 5
var remoteOK, fuseOK bool
var dm, localDm, remoteDm dirMap
for i := 1; i <= retries; i++ {
dm = newDirMap(dirString)
localDm = make(dirMap)
r.readLocal(t, localDm, "")
remoteDm = make(dirMap)
r.readRemote(t, remoteDm, "")
// Ignore directories for remote compare
remoteOK = reflect.DeepEqual(dm.filesOnly(run.vfsOpt.Links), remoteDm.filesOnly(run.vfsOpt.Links))
fuseOK = reflect.DeepEqual(dm, localDm)
if remoteOK && fuseOK {
return
}
sleep *= 2
t.Logf("Sleeping for %v for list eventual consistency: %d/%d", sleep, i, retries)
time.Sleep(sleep)
}
assert.Equal(t, dm.filesOnly(run.vfsOpt.Links), remoteDm.filesOnly(run.vfsOpt.Links), "expected vs remote")
assert.Equal(t, dm, localDm, "expected vs fuse mount")
}
// writeFile writes data to a file named by filename.
// If the file does not exist, WriteFile creates it with permissions perm;
// otherwise writeFile truncates it before writing.
// If there is an error writing then writeFile
// deletes it an existing file and tries again.
func writeFile(filename string, data []byte, perm os.FileMode) error {
f, err := run.os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
if err != nil {
err = run.os.Remove(filename)
if err != nil {
return err
}
f, err = run.os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, perm)
if err != nil {
return err
}
}
n, err := f.Write(data)
if err == nil && n < len(data) {
err = io.ErrShortWrite
}
if err1 := f.Close(); err == nil {
err = err1
}
return err
}
func (r *Run) createFile(t *testing.T, filepath string, contents string) {
filepath = r.path(filepath)
err := writeFile(filepath, []byte(contents), 0644)
require.NoError(t, err)
r.waitForWriters()
}
func (r *Run) readFile(t *testing.T, filepath string) string {
filepath = r.path(filepath)
result, err := r.os.ReadFile(filepath)
require.NoError(t, err)
return string(result)
}
func (r *Run) mkdir(t *testing.T, filepath string) {
filepath = r.path(filepath)
err := r.os.Mkdir(filepath, 0755)
require.NoError(t, err)
}
func (r *Run) rm(t *testing.T, filepath string) {
filepath = r.path(filepath)
err := r.os.Remove(filepath)
require.NoError(t, err)
// Wait for file to disappear from listing
for range 100 {
_, err := r.os.Stat(filepath)
if os.IsNotExist(err) {
return
}
time.Sleep(100 * time.Millisecond)
}
assert.Fail(t, "failed to delete file", filepath)
}
func (r *Run) rmdir(t *testing.T, filepath string) {
filepath = r.path(filepath)
err := r.os.Remove(filepath)
require.NoError(t, err)
}
func (r *Run) symlink(t *testing.T, oldname, newname string) {
newname = r.path(newname)
err := r.os.Symlink(oldname, newname)
require.NoError(t, err)
}
func (r *Run) checkMode(t *testing.T, name string, lexpected os.FileMode, expected os.FileMode) {
if r.useVFS {
info, err := run.os.Stat(run.path(name))
require.NoError(t, err)
assert.Equal(t, lexpected, info.Mode())
assert.Equal(t, name, info.Name())
} else {
info, err := os.Lstat(run.path(name))
require.NoError(t, err)
assert.Equal(t, lexpected, info.Mode())
assert.Equal(t, name, info.Name())
info, err = run.os.Stat(run.path(name))
require.NoError(t, err)
assert.Equal(t, expected, info.Mode())
assert.Equal(t, name, info.Name())
}
}
func (r *Run) readlink(t *testing.T, name string) string {
result, err := r.os.Readlink(r.path(name))
require.NoError(t, err)
return result
}
// TestMount checks that the Fs is mounted by seeing if the mountpoint
// is in the mount output
func TestMount(t *testing.T) {
run.skipIfVFS(t)
run.skipIfNoFUSE(t)
if runtime.GOOS == "windows" {
t.Skip("not running on windows")
}
out, err := exec.Command("mount").Output()
require.NoError(t, err)
assert.Contains(t, string(out), run.mountPath)
}
// TestRoot checks root directory is present and correct
func TestRoot(t *testing.T) {
run.skipIfVFS(t)
run.skipIfNoFUSE(t)
fi, err := os.Lstat(run.mountPath)
require.NoError(t, err)
assert.True(t, fi.IsDir())
assert.Equal(t, os.FileMode(run.vfsOpt.DirPerms)&os.ModePerm, fi.Mode().Perm())
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/edge_cases.go | vfs/vfstest/edge_cases.go | package vfstest
import (
"runtime"
"testing"
"github.com/stretchr/testify/require"
)
// TestTouchAndDelete checks that writing a zero byte file and immediately
// deleting it is not racy. See https://github.com/rclone/rclone/issues/1181
func TestTouchAndDelete(t *testing.T) {
run.skipIfNoFUSE(t)
run.checkDir(t, "")
run.createFile(t, "touched", "")
run.rm(t, "touched")
run.checkDir(t, "")
}
// TestRenameOpenHandle checks that a file with open writers is successfully
// renamed after all writers close. See https://github.com/rclone/rclone/issues/2130
func TestRenameOpenHandle(t *testing.T) {
run.skipIfNoFUSE(t)
if runtime.GOOS == "windows" {
t.Skip("Skipping test on Windows")
}
run.checkDir(t, "")
// create file
example := []byte("Some Data")
path := run.path("rename")
file, err := osCreate(path)
require.NoError(t, err)
// write some data
_, err = file.Write(example)
require.NoError(t, err)
err = file.Sync()
require.NoError(t, err)
// attempt to rename open file
err = run.os.Rename(path, path+"bla")
require.NoError(t, err)
// close open writers to allow rename on remote to go through
err = file.Close()
require.NoError(t, err)
run.waitForWriters()
// verify file was renamed properly
run.checkDir(t, "renamebla 9")
// cleanup
run.rm(t, "renamebla")
run.checkDir(t, "")
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfstest/dir.go | vfs/vfstest/dir.go | package vfstest
import (
"context"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestDirLs checks out listing
func TestDirLs(t *testing.T) {
run.skipIfNoFUSE(t)
run.checkDir(t, "")
run.mkdir(t, "a directory")
run.createFile(t, "a file", "hello")
run.checkDir(t, "a directory/|a file 5")
run.rmdir(t, "a directory")
run.rm(t, "a file")
run.checkDir(t, "")
}
// TestDirCreateAndRemoveDir tests creating and removing a directory
func TestDirCreateAndRemoveDir(t *testing.T) {
run.skipIfNoFUSE(t)
run.mkdir(t, "dir")
run.mkdir(t, "dir/subdir")
run.checkDir(t, "dir/|dir/subdir/")
// Check we can't delete a directory with stuff in
err := run.os.Remove(run.path("dir"))
assert.Error(t, err, "file exists")
// Now delete subdir then dir - should produce no errors
run.rmdir(t, "dir/subdir")
run.checkDir(t, "dir/")
run.rmdir(t, "dir")
run.checkDir(t, "")
}
// TestDirCreateAndRemoveFile tests creating and removing a file
func TestDirCreateAndRemoveFile(t *testing.T) {
run.skipIfNoFUSE(t)
run.mkdir(t, "dir")
run.createFile(t, "dir/file", "potato")
run.checkDir(t, "dir/|dir/file 6")
// Check we can't delete a directory with stuff in
err := run.os.Remove(run.path("dir"))
assert.Error(t, err, "file exists")
// Now delete file
run.rm(t, "dir/file")
run.checkDir(t, "dir/")
run.rmdir(t, "dir")
run.checkDir(t, "")
}
// TestDirRenameFile tests renaming a file
func TestDirRenameFile(t *testing.T) {
run.skipIfNoFUSE(t)
run.mkdir(t, "dir")
run.createFile(t, "file", "potato")
run.checkDir(t, "dir/|file 6")
err := run.os.Rename(run.path("file"), run.path("file2"))
require.NoError(t, err)
run.checkDir(t, "dir/|file2 6")
data := run.readFile(t, "file2")
assert.Equal(t, "potato", data)
err = run.os.Rename(run.path("file2"), run.path("dir/file3"))
require.NoError(t, err)
run.checkDir(t, "dir/|dir/file3 6")
data = run.readFile(t, "dir/file3")
require.NoError(t, err)
assert.Equal(t, "potato", data)
run.rm(t, "dir/file3")
run.rmdir(t, "dir")
run.checkDir(t, "")
}
// TestDirRenameEmptyDir tests renaming and empty directory
func TestDirRenameEmptyDir(t *testing.T) {
run.skipIfNoFUSE(t)
run.mkdir(t, "dir")
run.mkdir(t, "dir1")
run.checkDir(t, "dir/|dir1/")
err := run.os.Rename(run.path("dir1"), run.path("dir/dir2"))
require.NoError(t, err)
run.checkDir(t, "dir/|dir/dir2/")
err = run.os.Rename(run.path("dir/dir2"), run.path("dir/dir3"))
require.NoError(t, err)
run.checkDir(t, "dir/|dir/dir3/")
run.rmdir(t, "dir/dir3")
run.rmdir(t, "dir")
run.checkDir(t, "")
}
// TestDirRenameFullDir tests renaming a full directory
func TestDirRenameFullDir(t *testing.T) {
run.skipIfNoFUSE(t)
run.mkdir(t, "dir")
run.mkdir(t, "dir1")
run.createFile(t, "dir1/potato.txt", "maris piper")
run.checkDir(t, "dir/|dir1/|dir1/potato.txt 11")
err := run.os.Rename(run.path("dir1"), run.path("dir/dir2"))
require.NoError(t, err)
run.checkDir(t, "dir/|dir/dir2/|dir/dir2/potato.txt 11")
err = run.os.Rename(run.path("dir/dir2"), run.path("dir/dir3"))
require.NoError(t, err)
run.checkDir(t, "dir/|dir/dir3/|dir/dir3/potato.txt 11")
run.rm(t, "dir/dir3/potato.txt")
run.rmdir(t, "dir/dir3")
run.rmdir(t, "dir")
run.checkDir(t, "")
}
// TestDirModTime tests mod times
func TestDirModTime(t *testing.T) {
run.skipIfNoFUSE(t)
run.mkdir(t, "dir")
mtime := time.Date(2012, time.November, 18, 17, 32, 31, 0, time.UTC)
err := run.os.Chtimes(run.path("dir"), mtime, mtime)
require.NoError(t, err)
info, err := run.os.Stat(run.path("dir"))
require.NoError(t, err)
// avoid errors because of timezone differences
assert.Equal(t, info.ModTime().Unix(), mtime.Unix())
run.rmdir(t, "dir")
}
// TestDirCacheFlush tests flushing the dir cache
func TestDirCacheFlush(t *testing.T) {
run.skipIfNoFUSE(t)
run.checkDir(t, "")
run.mkdir(t, "dir")
run.mkdir(t, "otherdir")
run.createFile(t, "dir/file", "1")
run.createFile(t, "otherdir/file", "1")
dm := newDirMap("otherdir/|otherdir/file 1|dir/|dir/file 1")
localDm := make(dirMap)
run.readLocal(t, localDm, "")
assert.Equal(t, dm, localDm, "expected vs fuse mount")
err := run.fremote.Mkdir(context.Background(), "dir/subdir")
require.NoError(t, err)
// expect newly created "subdir" on remote to not show up
run.forget("otherdir")
run.readLocal(t, localDm, "")
assert.Equal(t, dm, localDm, "expected vs fuse mount")
run.forget("dir")
dm = newDirMap("otherdir/|otherdir/file 1|dir/|dir/file 1|dir/subdir/")
run.readLocal(t, localDm, "")
assert.Equal(t, dm, localDm, "expected vs fuse mount")
run.rm(t, "otherdir/file")
run.rmdir(t, "otherdir")
run.rm(t, "dir/file")
run.rmdir(t, "dir/subdir")
run.rmdir(t, "dir")
run.checkDir(t, "")
}
// TestDirCacheFlushOnDirRename tests flushing the dir cache on rename
func TestDirCacheFlushOnDirRename(t *testing.T) {
run.skipIfNoFUSE(t)
run.mkdir(t, "dir")
run.createFile(t, "dir/file", "1")
dm := newDirMap("dir/|dir/file 1")
localDm := make(dirMap)
run.readLocal(t, localDm, "")
assert.Equal(t, dm, localDm, "expected vs fuse mount")
// expect remotely created directory to not show up
err := run.fremote.Mkdir(context.Background(), "dir/subdir")
require.NoError(t, err)
run.readLocal(t, localDm, "")
assert.Equal(t, dm, localDm, "expected vs fuse mount")
err = run.os.Rename(run.path("dir"), run.path("rid"))
require.NoError(t, err)
dm = newDirMap("rid/|rid/subdir/|rid/file 1")
localDm = make(dirMap)
run.readLocal(t, localDm, "")
assert.Equal(t, dm, localDm, "expected vs fuse mount")
run.rm(t, "rid/file")
run.rmdir(t, "rid/subdir")
run.rmdir(t, "rid")
run.checkDir(t, "")
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscommon/cachemode_test.go | vfs/vfscommon/cachemode_test.go | package vfscommon
import (
"encoding/json"
"strconv"
"testing"
"github.com/spf13/pflag"
"github.com/stretchr/testify/assert"
)
// Check CacheMode it satisfies the pflag interface
var _ pflag.Value = (*CacheMode)(nil)
// Check CacheMode it satisfies the json.Unmarshaller interface
var _ json.Unmarshaler = (*CacheMode)(nil)
func TestCacheModeString(t *testing.T) {
assert.Equal(t, "off", CacheModeOff.String())
assert.Equal(t, "full", CacheModeFull.String())
assert.Equal(t, "Unknown(17)", CacheMode(17).String())
}
func TestCacheModeSet(t *testing.T) {
var m CacheMode
err := m.Set("full")
assert.NoError(t, err)
assert.Equal(t, CacheModeFull, m)
err = m.Set("potato")
assert.Error(t, err, "Unknown cache mode level")
err = m.Set("")
assert.Error(t, err, "Unknown cache mode level")
}
func TestCacheModeType(t *testing.T) {
var m CacheMode
assert.Equal(t, "CacheMode", m.Type())
}
func TestCacheModeUnmarshalJSON(t *testing.T) {
var m CacheMode
err := json.Unmarshal([]byte(`"full"`), &m)
assert.NoError(t, err)
assert.Equal(t, CacheModeFull, m)
err = json.Unmarshal([]byte(`"potato"`), &m)
assert.Error(t, err, "Unknown cache mode level")
err = json.Unmarshal([]byte(`""`), &m)
assert.Error(t, err, "Unknown cache mode level")
err = json.Unmarshal([]byte(strconv.Itoa(int(CacheModeFull))), &m)
assert.NoError(t, err)
assert.Equal(t, CacheModeFull, m)
err = json.Unmarshal([]byte("-1"), &m)
assert.Error(t, err, "Unknown cache mode level")
err = json.Unmarshal([]byte("99"), &m)
assert.Error(t, err, "Unknown cache mode level")
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscommon/cachemode.go | vfs/vfscommon/cachemode.go | // Package vfscommon provides utilities for VFS.
package vfscommon
import (
"github.com/rclone/rclone/fs"
)
type cacheModeChoices struct{}
func (cacheModeChoices) Choices() []string {
return []string{
CacheModeOff: "off",
CacheModeMinimal: "minimal",
CacheModeWrites: "writes",
CacheModeFull: "full",
}
}
// CacheMode controls the functionality of the cache
type CacheMode = fs.Enum[cacheModeChoices]
// CacheMode options
const (
CacheModeOff CacheMode = iota // cache nothing - return errors for writes which can't be satisfied
CacheModeMinimal // cache only the minimum, e.g. read/write opens
CacheModeWrites // cache all files opened with write intent
CacheModeFull // cache all files opened in any mode
)
// Type of the value
func (cacheModeChoices) Type() string {
return "CacheMode"
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscommon/path.go | vfs/vfscommon/path.go | package vfscommon
import (
"path"
"path/filepath"
)
// OSFindParent returns the parent directory of name, or "" for the
// root for OS native paths.
func OSFindParent(name string) string {
parent := filepath.Dir(name)
if parent == "." || (len(parent) == 1 && parent[0] == filepath.Separator) {
parent = ""
}
return parent
}
// FindParent returns the parent directory of name, or "" for the root
// for rclone paths.
func FindParent(name string) string {
parent := path.Dir(name)
if parent == "." || parent == "/" {
parent = ""
}
return parent
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscommon/vfsflags_unix.go | vfs/vfscommon/vfsflags_unix.go | //go:build linux || darwin || freebsd
package vfscommon
import (
"golang.org/x/sys/unix"
)
// get the current umask
func getUmask() int {
umask := unix.Umask(0) // read the umask
unix.Umask(umask) // set it back to what it was
return umask
}
// get the current uid
func getUID() uint32 {
return uint32(unix.Geteuid())
}
// get the current gid
func getGID() uint32 {
return uint32(unix.Getegid())
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscommon/filemode.go | vfs/vfscommon/filemode.go | package vfscommon
import (
"fmt"
"os"
"strconv"
"github.com/rclone/rclone/fs"
)
// FileMode is a command line friendly os.FileMode
type FileMode os.FileMode
// String turns FileMode into a string
func (x FileMode) String() string {
return fmt.Sprintf("%03o", x)
}
// Set a FileMode
func (x *FileMode) Set(s string) error {
i, err := strconv.ParseInt(s, 8, 32)
if err != nil {
return fmt.Errorf("bad FileMode - must be octal digits: %w", err)
}
*x = (FileMode)(i)
return nil
}
// Type of the value
func (x FileMode) Type() string {
return "FileMode"
}
// UnmarshalJSON makes sure the value can be parsed as a string or integer in JSON
func (x *FileMode) UnmarshalJSON(in []byte) error {
return fs.UnmarshalJSONFlag(in, x, func(i int64) error {
*x = FileMode(i)
return nil
})
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscommon/filemode_test.go | vfs/vfscommon/filemode_test.go | package vfscommon
import (
"encoding/json"
"testing"
"github.com/rclone/rclone/fs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// Check it satisfies the interfaces
var (
_ fs.Flagger = (*FileMode)(nil)
_ fs.FlaggerNP = FileMode(0)
)
func TestFileModeString(t *testing.T) {
for _, test := range []struct {
in FileMode
want string
}{
{0, "000"},
{0666, "666"},
{02666, "2666"},
} {
got := test.in.String()
assert.Equal(t, test.want, got)
}
}
func TestFileModeSet(t *testing.T) {
for _, test := range []struct {
in string
want FileMode
err bool
}{
{"0", 0, false},
{"0666", 0666, false},
{"666", 0666, false},
{"2666", 02666, false},
{"999", 0, true},
} {
got := FileMode(0)
err := got.Set(test.in)
if test.err {
require.Error(t, err, test.in)
} else {
require.NoError(t, err, test.in)
}
assert.Equal(t, test.want, got)
}
}
func TestFileModeUnmarshalJSON(t *testing.T) {
for _, test := range []struct {
in string
want FileMode
err bool
}{
{`"0"`, 0, false},
{`"666"`, 0666, false},
{`"02666"`, 02666, false},
{`"999"`, 0, true},
{`438`, 0666, false},
{`"999"`, 0, true},
} {
var ss FileMode
err := json.Unmarshal([]byte(test.in), &ss)
if test.err {
require.Error(t, err, test.in)
} else {
require.NoError(t, err, test.in)
}
assert.Equal(t, test.want, ss, test.in)
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscommon/options.go | vfs/vfscommon/options.go | package vfscommon
import (
"context"
"os"
"runtime"
"time"
"github.com/rclone/rclone/fs"
)
// OptionsInfo describes the Options in use
var OptionsInfo = fs.Options{{
Name: "no_modtime",
Default: false,
Help: "Don't read/write the modification time (can speed things up)",
Groups: "VFS",
}, {
Name: "no_checksum",
Default: false,
Help: "Don't compare checksums on up/download",
Groups: "VFS",
}, {
Name: "no_seek",
Default: false,
Help: "Don't allow seeking in files",
Groups: "VFS",
}, {
Name: "dir_cache_time",
Default: fs.Duration(5 * 60 * time.Second),
Help: "Time to cache directory entries for",
Groups: "VFS",
}, {
Name: "vfs_refresh",
Default: false,
Help: "Refreshes the directory cache recursively in the background on start",
Groups: "VFS",
}, {
Name: "poll_interval",
Default: fs.Duration(time.Minute),
Help: "Time to wait between polling for changes, must be smaller than dir-cache-time and only on supported remotes (set 0 to disable)",
Groups: "VFS",
}, {
Name: "read_only",
Default: false,
Help: "Only allow read-only access",
Groups: "VFS",
}, {
Name: "vfs_links",
Default: false,
Help: "Translate symlinks to/from regular files with a '" + fs.LinkSuffix + "' extension for the VFS",
Groups: "VFS",
}, {
Name: "vfs_cache_mode",
Default: CacheModeOff,
Help: "Cache mode off|minimal|writes|full",
Groups: "VFS",
}, {
Name: "vfs_cache_poll_interval",
Default: fs.Duration(60 * time.Second),
Help: "Interval to poll the cache for stale objects",
Groups: "VFS",
}, {
Name: "vfs_cache_max_age",
Default: fs.Duration(3600 * time.Second),
Help: "Max time since last access of objects in the cache",
Groups: "VFS",
}, {
Name: "vfs_cache_max_size",
Default: fs.SizeSuffix(-1),
Help: "Max total size of objects in the cache",
Groups: "VFS",
}, {
Name: "vfs_cache_min_free_space",
Default: fs.SizeSuffix(-1),
Help: "Target minimum free space on the disk containing the cache",
Groups: "VFS",
}, {
Name: "vfs_read_chunk_size",
Default: 128 * fs.Mebi,
Help: "Read the source objects in chunks",
Groups: "VFS",
}, {
Name: "vfs_read_chunk_size_limit",
Default: fs.SizeSuffix(-1),
Help: "If greater than --vfs-read-chunk-size, double the chunk size after each chunk read, until the limit is reached ('off' is unlimited)",
Groups: "VFS",
}, {
Name: "vfs_read_chunk_streams",
Default: 0,
Help: "The number of parallel streams to read at once",
Groups: "VFS",
}, {
Name: "dir_perms",
Default: FileMode(0777),
Help: "Directory permissions",
Groups: "VFS",
}, {
Name: "file_perms",
Default: FileMode(0666),
Help: "File permissions",
Groups: "VFS",
}, {
Name: "link_perms",
Default: FileMode(0666),
Help: "Link permissions",
Groups: "VFS",
}, {
Name: "vfs_case_insensitive",
Default: runtime.GOOS == "windows" || runtime.GOOS == "darwin", // default to true on Windows and Mac, false otherwise,
Help: "If a file name not found, find a case insensitive match",
Groups: "VFS",
}, {
Name: "vfs_block_norm_dupes",
Default: false,
Help: "If duplicate filenames exist in the same directory (after normalization), log an error and hide the duplicates (may have a performance cost)",
Groups: "VFS",
}, {
Name: "vfs_write_wait",
Default: fs.Duration(1000 * time.Millisecond),
Help: "Time to wait for in-sequence write before giving error",
Groups: "VFS",
}, {
Name: "vfs_read_wait",
Default: fs.Duration(20 * time.Millisecond),
Help: "Time to wait for in-sequence read before seeking",
Groups: "VFS",
}, {
Name: "vfs_write_back",
Default: fs.Duration(5 * time.Second),
Help: "Time to writeback files after last use when using cache",
Groups: "VFS",
}, {
Name: "vfs_read_ahead",
Default: 0 * fs.Mebi,
Help: "Extra read ahead over --buffer-size when using cache-mode full",
Groups: "VFS",
}, {
Name: "vfs_used_is_size",
Default: false,
Help: "Use the `rclone size` algorithm for Used size",
Groups: "VFS",
}, {
Name: "vfs_fast_fingerprint",
Default: false,
Help: "Use fast (less accurate) fingerprints for change detection",
Groups: "VFS",
}, {
Name: "vfs_disk_space_total_size",
Default: fs.SizeSuffix(-1),
Help: "Specify the total space of disk",
Groups: "VFS",
}, {
Name: "umask",
Default: FileMode(getUmask()),
Help: "Override the permission bits set by the filesystem (not supported on Windows)",
Groups: "VFS",
}, {
Name: "uid",
Default: getUID(),
Help: "Override the uid field set by the filesystem (not supported on Windows)",
Groups: "VFS",
}, {
Name: "gid",
Default: getGID(),
Help: "Override the gid field set by the filesystem (not supported on Windows)",
Groups: "VFS",
}, {
Name: "vfs_metadata_extension",
Default: "",
Help: "Set the extension to read metadata from.",
Groups: "VFS",
}}
func init() {
fs.RegisterGlobalOptions(fs.OptionsInfo{Name: "vfs", Opt: &Opt, Options: OptionsInfo})
}
// Options is options for creating the vfs
type Options struct {
NoSeek bool `config:"no_seek"` // don't allow seeking if set
NoChecksum bool `config:"no_checksum"` // don't check checksums if set
ReadOnly bool `config:"read_only"` // if set VFS is read only
Links bool `config:"vfs_links"` // if set interpret link files
NoModTime bool `config:"no_modtime"` // don't read mod times for files
DirCacheTime fs.Duration `config:"dir_cache_time"` // how long to consider directory listing cache valid
Refresh bool `config:"vfs_refresh"` // refreshes the directory listing recursively on start
PollInterval fs.Duration `config:"poll_interval"`
Umask FileMode `config:"umask"`
UID uint32 `config:"uid"`
GID uint32 `config:"gid"`
DirPerms FileMode `config:"dir_perms"`
FilePerms FileMode `config:"file_perms"`
LinkPerms FileMode `config:"link_perms"`
ChunkSize fs.SizeSuffix `config:"vfs_read_chunk_size"` // if > 0 read files in chunks
ChunkSizeLimit fs.SizeSuffix `config:"vfs_read_chunk_size_limit"` // if > ChunkSize double the chunk size after each chunk until reached
ChunkStreams int `config:"vfs_read_chunk_streams"` // Number of download streams to use
CacheMode CacheMode `config:"vfs_cache_mode"`
CacheMaxAge fs.Duration `config:"vfs_cache_max_age"`
CacheMaxSize fs.SizeSuffix `config:"vfs_cache_max_size"`
CacheMinFreeSpace fs.SizeSuffix `config:"vfs_cache_min_free_space"`
CachePollInterval fs.Duration `config:"vfs_cache_poll_interval"`
CaseInsensitive bool `config:"vfs_case_insensitive"`
BlockNormDupes bool `config:"vfs_block_norm_dupes"`
WriteWait fs.Duration `config:"vfs_write_wait"` // time to wait for in-sequence write
ReadWait fs.Duration `config:"vfs_read_wait"` // time to wait for in-sequence read
WriteBack fs.Duration `config:"vfs_write_back"` // time to wait before writing back dirty files
ReadAhead fs.SizeSuffix `config:"vfs_read_ahead"` // bytes to read ahead in cache mode "full"
UsedIsSize bool `config:"vfs_used_is_size"` // if true, use the `rclone size` algorithm for Used size
FastFingerprint bool `config:"vfs_fast_fingerprint"` // if set use fast fingerprints
DiskSpaceTotalSize fs.SizeSuffix `config:"vfs_disk_space_total_size"`
MetadataExtension string `config:"vfs_metadata_extension"` // if set respond to files with this extension with metadata
}
// Opt is the default options modified by the environment variables and command line flags
var Opt Options
// Init the options, making sure everything is within range
func (opt *Options) Init() {
ci := fs.GetConfig(context.Background())
// Override --vfs-links with --links if set
if ci.Links {
opt.Links = true
}
// Mask the permissions with the umask
opt.DirPerms &= ^opt.Umask
opt.FilePerms &= ^opt.Umask
opt.LinkPerms &= ^opt.Umask
// Make sure directories are returned as directories
opt.DirPerms |= FileMode(os.ModeDir)
// Make sure links are returned as links
opt.LinkPerms |= FileMode(os.ModeSymlink)
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/vfs/vfscommon/vfsflags_non_unix.go | vfs/vfscommon/vfsflags_non_unix.go | //go:build !linux && !darwin && !freebsd
package vfscommon
// get the current umask
func getUmask() int {
return 0000
}
// get the current uid
func getUID() uint32 {
return ^uint32(0) // these values instruct WinFSP-FUSE to use the current user
}
// get the current gid
func getGID() uint32 {
return ^uint32(0) // these values instruct WinFSP-FUSE to use the current user
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/cmdtest/cmdtest.go | cmdtest/cmdtest.go | // Package cmdtest creates a testable interface to rclone main
//
// The interface is used to perform end-to-end test of
// commands, flags, environment variables etc.
package cmdtest
// The rest of this file is a 1:1 copy from rclone.go
import (
_ "github.com/rclone/rclone/backend/all" // import all backends
"github.com/rclone/rclone/cmd"
_ "github.com/rclone/rclone/cmd/all" // import all commands
_ "github.com/rclone/rclone/lib/plugin" // import plugins
)
func main() {
cmd.Main()
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/cmdtest/environment_test.go | cmdtest/environment_test.go | // environment_test tests the use and precedence of environment variables
//
// The tests rely on functions defined in cmdtest_test.go
package cmdtest
import (
"os"
"regexp"
"runtime"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestEnvironmentVariables demonstrates and verifies the test functions for end-to-end testing of rclone
func TestEnvironmentVariables(t *testing.T) {
createTestEnvironment(t)
testdataPath := createSimpleTestData(t)
// Non backend flags
// =================
// First verify default behaviour of the implicit max_depth=-1
env := ""
out, err := rcloneEnv(env, "lsl", testFolder)
//t.Logf("\n" + out)
if assert.NoError(t, err) {
assert.Contains(t, out, "rclone.config") // depth 1
assert.Contains(t, out, "file1.txt") // depth 2
assert.Contains(t, out, "fileA1.txt") // depth 3
assert.Contains(t, out, "fileAA1.txt") // depth 4
}
// Test of flag.Value
env = "RCLONE_MAX_DEPTH=2"
out, err = rcloneEnv(env, "lsl", testFolder)
if assert.NoError(t, err) {
assert.Contains(t, out, "file1.txt") // depth 2
assert.NotContains(t, out, "fileA1.txt") // depth 3
}
// Test of flag.Changed (tests #5341 Issue1)
env = "RCLONE_LOG_LEVEL=DEBUG"
out, err = rcloneEnv(env, "version", "--quiet")
if assert.Error(t, err) {
assert.Contains(t, out, " DEBUG ")
assert.Contains(t, out, "Can't set -q and --log-level")
assert.Contains(t, "exit status 1", err.Error())
}
// Test of flag.DefValue
env = "RCLONE_STATS=173ms"
out, err = rcloneEnv(env, "help", "flags")
if assert.NoError(t, err) {
assert.Contains(t, out, "(default 173ms)")
}
// Test of command line flags overriding environment flags
env = "RCLONE_MAX_DEPTH=2"
out, err = rcloneEnv(env, "lsl", testFolder, "--max-depth", "3")
if assert.NoError(t, err) {
assert.Contains(t, out, "fileA1.txt") // depth 3
assert.NotContains(t, out, "fileAA1.txt") // depth 4
}
// Test of debug logging while initialising flags from environment (tests #5341 Enhance1)
env = "RCLONE_STATS=173ms"
out, err = rcloneEnv(env, "version", "-vv")
if assert.NoError(t, err) {
assert.Contains(t, out, " DEBUG : ")
assert.Contains(t, out, "--stats")
assert.Contains(t, out, "173ms")
assert.Contains(t, out, "RCLONE_STATS=")
}
// Backend flags and remote name
// - The listremotes command includes names from environment variables,
// the part between "RCLONE_CONFIG_" and "_TYPE", converted to lowercase.
// - When using a remote created from env, e.g. with lsd command,
// the name is case insensitive in contrast to remotes in config file
// (fs.ConfigToEnv converts to uppercase before checking environment).
// - Previously using a remote created from env, e.g. with lsd command,
// would not be possible for remotes with '-' in names, and remote names
// with '_' could be referred to with both '-' and '_', because any '-'
// were replaced with '_' before lookup.
// ===================================
env = "RCLONE_CONFIG_MY-LOCAL_TYPE=local"
out, err = rcloneEnv(env, "listremotes")
if assert.NoError(t, err) {
assert.Contains(t, out, "my-local:")
}
out, err = rcloneEnv(env, "lsl", "my-local:"+testFolder)
if assert.NoError(t, err) {
assert.Contains(t, out, "rclone.config")
assert.Contains(t, out, "file1.txt")
assert.Contains(t, out, "fileA1.txt")
assert.Contains(t, out, "fileAA1.txt")
}
out, err = rcloneEnv(env, "lsl", "mY-LoCaL:"+testFolder)
if assert.NoError(t, err) {
assert.Contains(t, out, "rclone.config")
assert.Contains(t, out, "file1.txt")
assert.Contains(t, out, "fileA1.txt")
assert.Contains(t, out, "fileAA1.txt")
}
out, err = rcloneEnv(env, "lsl", "my_local:"+testFolder)
if assert.Error(t, err) {
assert.Contains(t, out, "Failed to create file system")
}
env = "RCLONE_CONFIG_MY_LOCAL_TYPE=local"
out, err = rcloneEnv(env, "listremotes")
if assert.NoError(t, err) {
assert.Contains(t, out, "my_local:")
}
out, err = rcloneEnv(env, "lsl", "my_local:"+testFolder)
if assert.NoError(t, err) {
assert.Contains(t, out, "rclone.config")
assert.Contains(t, out, "file1.txt")
assert.Contains(t, out, "fileA1.txt")
assert.Contains(t, out, "fileAA1.txt")
}
out, err = rcloneEnv(env, "lsl", "my-local:"+testFolder)
if assert.Error(t, err) {
assert.Contains(t, out, "Failed to create file system")
}
// Backend flags and option precedence
// ===================================
// Test approach:
// Verify no symlink warning when skip_links=true one the level with highest precedence
// and skip_links=false on all levels with lower precedence
//
// Reference: https://rclone.org/docs/#precedence
// Create a symlink in test data
err = os.Symlink(testdataPath+"/folderA", testdataPath+"/symlinkA")
if runtime.GOOS == "windows" {
errNote := "The policy settings on Windows often prohibit the creation of symlinks due to security issues.\n"
errNote += "You can safely ignore this test, if your change didn't affect environment variables."
require.NoError(t, err, errNote)
} else {
require.NoError(t, err)
}
// Create a local remote with explicit skip_links=false
out, err = rclone("config", "create", "myLocal", "local", "skip_links", "false")
if assert.NoError(t, err) {
assert.Contains(t, out, "[myLocal]")
assert.Contains(t, out, "type = local")
assert.Contains(t, out, "skip_links = false")
}
// Verify symlink warning when skip_links=false on all levels
env = "RCLONE_SKIP_LINKS=false;RCLONE_LOCAL_SKIP_LINKS=false;RCLONE_CONFIG_MYLOCAL_SKIP_LINKS=false"
out, err = rcloneEnv(env, "lsd", "myLocal,skip_links=false:"+testdataPath, "--skip-links=false")
//t.Logf("\n" + out)
if assert.NoError(t, err) {
assert.Contains(t, out, "NOTICE: symlinkA:")
assert.Contains(t, out, "folderA")
}
// Test precedence of connection strings
env = "RCLONE_SKIP_LINKS=false;RCLONE_LOCAL_SKIP_LINKS=false;RCLONE_CONFIG_MYLOCAL_SKIP_LINKS=false"
out, err = rcloneEnv(env, "lsd", "myLocal,skip_links:"+testdataPath, "--skip-links=false")
if assert.NoError(t, err) {
assert.NotContains(t, out, "symlinkA")
assert.Contains(t, out, "folderA")
}
// Test precedence of command line flags
env = "RCLONE_SKIP_LINKS=false;RCLONE_LOCAL_SKIP_LINKS=false;RCLONE_CONFIG_MYLOCAL_SKIP_LINKS=false"
out, err = rcloneEnv(env, "lsd", "myLocal:"+testdataPath, "--skip-links")
if assert.NoError(t, err) {
assert.NotContains(t, out, "symlinkA")
assert.Contains(t, out, "folderA")
}
// Test precedence of remote specific environment variables (tests #5341 Issue2)
env = "RCLONE_SKIP_LINKS=false;RCLONE_LOCAL_SKIP_LINKS=false;RCLONE_CONFIG_MYLOCAL_SKIP_LINKS=true"
out, err = rcloneEnv(env, "lsd", "myLocal:"+testdataPath)
if assert.NoError(t, err) {
assert.NotContains(t, out, "symlinkA")
assert.Contains(t, out, "folderA")
}
// Test precedence of backend specific environment variables (tests #5341 Issue3)
env = "RCLONE_SKIP_LINKS=false;RCLONE_LOCAL_SKIP_LINKS=true"
out, err = rcloneEnv(env, "lsd", "myLocal:"+testdataPath)
if assert.NoError(t, err) {
assert.NotContains(t, out, "symlinkA")
assert.Contains(t, out, "folderA")
}
// Test precedence of backend generic environment variables
env = "RCLONE_SKIP_LINKS=true"
out, err = rcloneEnv(env, "lsd", "myLocal:"+testdataPath)
if assert.NoError(t, err) {
assert.NotContains(t, out, "symlinkA")
assert.Contains(t, out, "folderA")
}
// Recreate the test remote with explicit skip_links=true
out, err = rclone("config", "create", "myLocal", "local", "skip_links", "true")
if assert.NoError(t, err) {
assert.Contains(t, out, "[myLocal]")
assert.Contains(t, out, "type = local")
assert.Contains(t, out, "skip_links = true")
}
// Test precedence of config file options
env = ""
out, err = rcloneEnv(env, "lsd", "myLocal:"+testdataPath)
if assert.NoError(t, err) {
assert.NotContains(t, out, "symlinkA")
assert.Contains(t, out, "folderA")
}
// Recreate the test remote with rclone defaults, that is implicit skip_links=false
out, err = rclone("config", "create", "myLocal", "local")
if assert.NoError(t, err) {
assert.Contains(t, out, "[myLocal]")
assert.Contains(t, out, "type = local")
assert.NotContains(t, out, "skip_links")
}
// Verify the rclone default value (implicit skip_links=false)
env = ""
out, err = rcloneEnv(env, "lsd", "myLocal:"+testdataPath)
if assert.NoError(t, err) {
assert.Contains(t, out, "NOTICE: symlinkA:")
assert.Contains(t, out, "folderA")
}
// Display of backend defaults (tests #4659)
//------------------------------------------
env = "RCLONE_DRIVE_CHUNK_SIZE=111M"
out, err = rcloneEnv(env, "help", "flags")
if assert.NoError(t, err) {
assert.Regexp(t, "--drive-chunk-size[^\\(]+\\(default 111M\\)", out)
}
// Options on referencing remotes (alias, crypt, etc.)
//----------------------------------------------------
// Create alias remote on myLocal having implicit skip_links=false
out, err = rclone("config", "create", "myAlias", "alias", "remote", "myLocal:"+testdataPath)
if assert.NoError(t, err) {
assert.Contains(t, out, "[myAlias]")
assert.Contains(t, out, "type = alias")
assert.Contains(t, out, "remote = myLocal:")
}
// Verify symlink warnings on the alias
env = ""
out, err = rcloneEnv(env, "lsd", "myAlias:")
if assert.NoError(t, err) {
assert.Contains(t, out, "NOTICE: symlinkA:")
assert.Contains(t, out, "folderA")
}
// Test backend generic flags
// having effect on the underlying local remote
env = "RCLONE_SKIP_LINKS=true"
out, err = rcloneEnv(env, "lsd", "myAlias:")
if assert.NoError(t, err) {
assert.NotContains(t, out, "symlinkA")
assert.Contains(t, out, "folderA")
}
// Test backend specific flags
// having effect on the underlying local remote
env = "RCLONE_LOCAL_SKIP_LINKS=true"
out, err = rcloneEnv(env, "lsd", "myAlias:")
if assert.NoError(t, err) {
assert.NotContains(t, out, "symlinkA")
assert.Contains(t, out, "folderA")
}
// Test remote specific flags
// having no effect unless supported by the immediate remote (alias)
env = "RCLONE_CONFIG_MYALIAS_SKIP_LINKS=true"
out, err = rcloneEnv(env, "lsd", "myAlias:")
if assert.NoError(t, err) {
assert.Contains(t, out, "NOTICE: symlinkA:")
assert.Contains(t, out, "folderA")
}
env = "RCLONE_CONFIG_MYALIAS_REMOTE=" + "myLocal:" + testdataPath + "/folderA"
out, err = rcloneEnv(env, "lsl", "myAlias:")
if assert.NoError(t, err) {
assert.Contains(t, out, "fileA1.txt")
assert.NotContains(t, out, "fileB1.txt")
}
// Test command line flags
// having effect on the underlying local remote
env = ""
out, err = rcloneEnv(env, "lsd", "myAlias:", "--skip-links")
if assert.NoError(t, err) {
assert.NotContains(t, out, "symlinkA")
assert.Contains(t, out, "folderA")
}
// Test connection specific flags
// having no effect unless supported by the immediate remote (alias)
env = ""
out, err = rcloneEnv(env, "lsd", "myAlias,skip_links:")
if assert.NoError(t, err) {
assert.Contains(t, out, "NOTICE: symlinkA:")
assert.Contains(t, out, "folderA")
}
env = ""
out, err = rcloneEnv(env, "lsl", "myAlias,remote='myLocal:"+testdataPath+"/folderA':", "-vv")
if assert.NoError(t, err) {
assert.Contains(t, out, "fileA1.txt")
assert.NotContains(t, out, "fileB1.txt")
}
// Test --use-json-log and -vv combinations
jsonLogOK := func() {
t.Helper()
if assert.NoError(t, err) {
assert.Contains(t, out, `"level":"debug"`)
assert.Contains(t, out, `"msg":"Version `)
assert.Contains(t, out, `"}`)
}
}
env = "RCLONE_USE_JSON_LOG=1;RCLONE_LOG_LEVEL=DEBUG"
out, err = rcloneEnv(env, "version")
jsonLogOK()
env = "RCLONE_USE_JSON_LOG=1"
out, err = rcloneEnv(env, "version", "-vv")
jsonLogOK()
env = "RCLONE_LOG_LEVEL=DEBUG"
out, err = rcloneEnv(env, "version", "--use-json-log")
jsonLogOK()
env = ""
out, err = rcloneEnv(env, "version", "-vv", "--use-json-log")
jsonLogOK()
// Find all the File filter lines in out and return them
parseFileFilters := func(out string) (extensions []string) {
// Match: - (^|/)[^/]*\.jpg$
find := regexp.MustCompile(`^- \(\^\|\/\)\[\^\/\]\*\\\.(.*?)\$$`)
for line := range strings.SplitSeq(out, "\n") {
if m := find.FindStringSubmatch(line); m != nil {
extensions = append(extensions, m[1])
}
}
return extensions
}
// Make sure that multiple valued (stringArray) environment variables are handled properly
env = ``
out, err = rcloneEnv(env, "version", "-vv", "--dump", "filters", "--exclude", "*.gif", "--exclude", "*.tif")
require.NoError(t, err)
assert.Equal(t, []string{"gif", "tif"}, parseFileFilters(out))
env = `RCLONE_EXCLUDE=*.jpg`
out, err = rcloneEnv(env, "version", "-vv", "--dump", "filters", "--exclude", "*.gif")
require.NoError(t, err)
assert.Equal(t, []string{"jpg", "gif"}, parseFileFilters(out))
env = `RCLONE_EXCLUDE=*.jpg,*.png`
out, err = rcloneEnv(env, "version", "-vv", "--dump", "filters", "--exclude", "*.gif", "--exclude", "*.tif")
require.NoError(t, err)
assert.Equal(t, []string{"jpg", "png", "gif", "tif"}, parseFileFilters(out))
env = `RCLONE_EXCLUDE="*.jpg","*.png"`
out, err = rcloneEnv(env, "version", "-vv", "--dump", "filters")
require.NoError(t, err)
assert.Equal(t, []string{"jpg", "png"}, parseFileFilters(out))
env = `RCLONE_EXCLUDE="*.,,,","*.png"`
out, err = rcloneEnv(env, "version", "-vv", "--dump", "filters")
require.NoError(t, err)
assert.Equal(t, []string{",,,", "png"}, parseFileFilters(out))
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
rclone/rclone | https://github.com/rclone/rclone/blob/5f4e4b1a200708f5f36999a9d289823b742e4fd3/cmdtest/cmdtest_test.go | cmdtest/cmdtest_test.go | // cmdtest_test creates a testable interface to rclone main
//
// The interface is used to perform end-to-end test of
// commands, flags, environment variables etc.
package cmdtest
import (
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
"github.com/rclone/rclone/fs"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestMain is initially called by go test to initiate the testing.
// TestMain is also called during the tests to start rclone main in a fresh context (using exec.Command).
// The context is determined by setting/finding the environment variable RCLONE_TEST_MAIN
func TestMain(m *testing.M) {
_, found := os.LookupEnv(rcloneTestMain)
if !found {
// started by Go test => execute tests
err := os.Setenv(rcloneTestMain, "true")
if err != nil {
fs.Fatalf(nil, "Unable to set %s: %s", rcloneTestMain, err.Error())
}
os.Exit(m.Run())
} else {
// started by func rcloneExecMain => call rclone main in cmdtest.go
err := os.Unsetenv(rcloneTestMain)
if err != nil {
fs.Fatalf(nil, "Unable to unset %s: %s", rcloneTestMain, err.Error())
}
main()
}
}
const rcloneTestMain = "RCLONE_TEST_MAIN"
// rcloneExecMain calls rclone with the given environment and arguments.
// The environment variables are in a single string separated by ;
// The terminal output is returned as a string.
func rcloneExecMain(env string, args ...string) (string, error) {
_, found := os.LookupEnv(rcloneTestMain)
if !found {
fs.Fatalf(nil, "Unexpected execution path: %s is missing.", rcloneTestMain)
}
// make a call to self to execute rclone main in a predefined environment (enters TestMain above)
command := exec.Command(os.Args[0], args...)
command.Env = getEnvInitial()
if env != "" {
command.Env = append(command.Env, strings.Split(env, ";")...)
}
out, err := command.CombinedOutput()
return string(out), err
}
// rcloneEnv calls rclone with the given environment and arguments.
// The environment variables are in a single string separated by ;
// The test config file is automatically configured in RCLONE_CONFIG.
// The terminal output is returned as a string.
func rcloneEnv(env string, args ...string) (string, error) {
envConfig := env
if testConfig != "" {
if envConfig != "" {
envConfig += ";"
}
envConfig += "RCLONE_CONFIG=" + testConfig
}
return rcloneExecMain(envConfig, args...)
}
// rclone calls rclone with the given arguments, E.g. "version","--help".
// The test config file is automatically configured in RCLONE_CONFIG.
// The terminal output is returned as a string.
func rclone(args ...string) (string, error) {
return rcloneEnv("", args...)
}
// getEnvInitial returns the os environment variables cleaned for RCLONE_ vars (except RCLONE_TEST_MAIN).
func getEnvInitial() []string {
if envInitial == nil {
// Set initial environment variables
osEnv := os.Environ()
for i := range osEnv {
if !strings.HasPrefix(osEnv[i], "RCLONE_") || strings.HasPrefix(osEnv[i], rcloneTestMain) {
envInitial = append(envInitial, osEnv[i])
}
}
}
return envInitial
}
var envInitial []string
// createTestEnvironment creates a temporary testFolder and
// sets testConfig to testFolder/rclone.config.
func createTestEnvironment(t *testing.T) {
//Set temporary folder for config and test data
tempFolder := t.TempDir()
testFolder = filepath.ToSlash(tempFolder)
// Set path to temporary config file
testConfig = testFolder + "/rclone.config"
}
var testFolder string
var testConfig string
// createTestFile creates the file testFolder/name
func createTestFile(name string, t *testing.T) string {
err := os.WriteFile(testFolder+"/"+name, []byte("content_of_"+name), 0666)
require.NoError(t, err)
return testFolder + "/" + name
}
// createTestFolder creates the folder testFolder/name
func createTestFolder(name string, t *testing.T) string {
err := os.Mkdir(testFolder+"/"+name, 0777)
require.NoError(t, err)
return testFolder + "/" + name
}
// createSimpleTestData creates simple test data in testFolder/subFolder
func createSimpleTestData(t *testing.T) string {
createTestFolder("testdata", t)
createTestFile("testdata/file1.txt", t)
createTestFile("testdata/file2.txt", t)
createTestFolder("testdata/folderA", t)
createTestFile("testdata/folderA/fileA1.txt", t)
createTestFile("testdata/folderA/fileA2.txt", t)
createTestFolder("testdata/folderA/folderAA", t)
createTestFile("testdata/folderA/folderAA/fileAA1.txt", t)
createTestFile("testdata/folderA/folderAA/fileAA2.txt", t)
createTestFolder("testdata/folderB", t)
createTestFile("testdata/folderB/fileB1.txt", t)
createTestFile("testdata/folderB/fileB2.txt", t)
t.Cleanup(func() {
err := os.RemoveAll(testFolder + "/testdata")
require.NoError(t, err)
})
return testFolder + "/testdata"
}
// TestCmdTest demonstrates and verifies the test functions for end-to-end testing of rclone
func TestCmdTest(t *testing.T) {
createTestEnvironment(t)
// Test simple call and output from rclone
out, err := rclone("version")
t.Log("rclone version\n" + out)
if assert.NoError(t, err) {
assert.Contains(t, out, "rclone v")
assert.Contains(t, out, "version: ")
assert.NotContains(t, out, "Error:")
assert.NotContains(t, out, "--help")
assert.NotContains(t, out, " DEBUG : ")
assert.Regexp(t, "rclone\\s+v\\d+\\.\\d+", out) // rclone v_.__
}
// Test multiple arguments and DEBUG output
out, err = rclone("version", "-vv")
if assert.NoError(t, err) {
assert.Contains(t, out, "rclone v")
assert.Contains(t, out, " DEBUG : ")
}
// Test error and error output
out, err = rclone("version", "--provoke-an-error")
if assert.Error(t, err) {
assert.Contains(t, err.Error(), "exit status 2")
assert.Contains(t, out, "Error: unknown flag")
}
// Test effect of environment variable
env := "RCLONE_LOG_LEVEL=DEBUG"
out, err = rcloneEnv(env, "version")
if assert.NoError(t, err) {
assert.Contains(t, out, "rclone v")
assert.Contains(t, out, " DEBUG : ")
}
// Test effect of multiple environment variables, including one with ,
env = "RCLONE_LOG_LEVEL=DEBUG;RCLONE_LOG_FORMAT=date,shortfile;RCLONE_STATS=173ms"
out, err = rcloneEnv(env, "version")
if assert.NoError(t, err) {
assert.Contains(t, out, "rclone v")
assert.Contains(t, out, " DEBUG : ")
assert.Regexp(t, "[^\\s]+\\.go:\\d+:", out) // ___.go:__:
assert.Contains(t, out, "173ms")
}
// Test setup of config file
out, err = rclone("config", "create", "myLocal", "local")
if assert.NoError(t, err) {
assert.Contains(t, out, "[myLocal]")
assert.Contains(t, out, "type = local")
}
// Test creation of simple test data
createSimpleTestData(t)
// Test access to config file and simple test data
out, err = rclone("lsl", "myLocal:"+testFolder)
t.Log("rclone lsl myLocal:testFolder\n" + out)
if assert.NoError(t, err) {
assert.Contains(t, out, "rclone.config")
assert.Contains(t, out, "testdata/folderA/fileA1.txt")
}
}
| go | MIT | 5f4e4b1a200708f5f36999a9d289823b742e4fd3 | 2026-01-07T08:35:43.525317Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/build.go | build.go | // Description
//
// This program aims to make building Go programs for end users easier by just
// calling it with `go run`, without having to setup a GOPATH.
//
// This program checks for a minimum Go version. It will use Go modules for
// compilation. It builds the package configured as Main in the Config struct.
// BSD 2-Clause License
//
// Copyright (c) 2016-2018, Alexander Neumann <alexander@bumpern.de>
// All rights reserved.
//
// This file has been derived from the repository at:
// https://github.com/fd0/build-go
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//go:build ignore_build_go
package main
import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
)
// config contains the configuration for the program to build.
var config = Config{
Name: "restic", // name of the program executable and directory
Namespace: "github.com/restic/restic", // subdir of GOPATH, e.g. "github.com/foo/bar"
Main: "./cmd/restic", // package name for the main package
// disable_grpc_modules is necessary to reduce the binary size since cloud.google.com/go/storage v1.44.0
// see https://github.com/googleapis/google-cloud-go/issues/11448
DefaultBuildTags: []string{"selfupdate", "disable_grpc_modules"}, // specify build tags which are always used
Tests: []string{"./..."}, // tests to run
MinVersion: GoVersion{Major: 1, Minor: 24, Patch: 0}, // minimum Go version supported
}
// Config configures the build.
type Config struct {
Name string
Namespace string
Main string
DefaultBuildTags []string
Tests []string
MinVersion GoVersion
}
var (
verbose bool
runTests bool
enableCGO bool
enablePIE bool
goVersion = ParseGoVersion(runtime.Version())
)
// die prints the message with fmt.Fprintf() to stderr and exits with an error
// code.
func die(message string, args ...interface{}) {
fmt.Fprintf(os.Stderr, message, args...)
os.Exit(1)
}
func showUsage(output io.Writer) {
fmt.Fprintf(output, "USAGE: go run build.go OPTIONS\n")
fmt.Fprintf(output, "\n")
fmt.Fprintf(output, "OPTIONS:\n")
fmt.Fprintf(output, " -v --verbose output more messages\n")
fmt.Fprintf(output, " -t --tags specify additional build tags\n")
fmt.Fprintf(output, " -T --test run tests\n")
fmt.Fprintf(output, " -o --output set output file name\n")
fmt.Fprintf(output, " --enable-cgo use CGO to link against libc\n")
fmt.Fprintf(output, " --enable-pie use PIE buildmode\n")
fmt.Fprintf(output, " --goos value set GOOS for cross-compilation\n")
fmt.Fprintf(output, " --goarch value set GOARCH for cross-compilation\n")
fmt.Fprintf(output, " --goarm value set GOARM for cross-compilation\n")
}
func verbosePrintf(message string, args ...interface{}) {
if !verbose {
return
}
fmt.Printf("build: "+message, args...)
}
// printEnv prints Go-relevant environment variables in a nice way using verbosePrintf.
func printEnv(env []string) {
verbosePrintf("environment (GO*):\n")
for _, v := range env {
// ignore environment variables which do not start with GO*.
if !strings.HasPrefix(v, "GO") {
continue
}
verbosePrintf(" %s\n", v)
}
}
// build runs "go build args..." with GOPATH set to gopath.
func build(cwd string, env map[string]string, args ...string) error {
// -trimpath removes all absolute paths from the binary.
a := []string{"build", "-trimpath"}
if enablePIE {
a = append(a, "-buildmode=pie")
}
a = append(a, args...)
cmd := exec.Command("go", a...)
cmd.Env = os.Environ()
for k, v := range env {
cmd.Env = append(cmd.Env, k+"="+v)
}
if !enableCGO {
cmd.Env = append(cmd.Env, "CGO_ENABLED=0")
}
printEnv(cmd.Env)
cmd.Dir = cwd
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
verbosePrintf("chdir %q\n", cwd)
verbosePrintf("go %q\n", a)
return cmd.Run()
}
// test runs "go test args..." with GOPATH set to gopath.
func test(cwd string, env map[string]string, args ...string) error {
args = append([]string{"test", "-count", "1"}, args...)
cmd := exec.Command("go", args...)
cmd.Env = os.Environ()
for k, v := range env {
cmd.Env = append(cmd.Env, k+"="+v)
}
if !enableCGO {
cmd.Env = append(cmd.Env, "CGO_ENABLED=0")
}
cmd.Dir = cwd
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
printEnv(cmd.Env)
verbosePrintf("chdir %q\n", cwd)
verbosePrintf("go %q\n", args)
return cmd.Run()
}
// getVersion returns the version string from the file VERSION in the current
// directory.
func getVersionFromFile() string {
buf, err := os.ReadFile("VERSION")
if err != nil {
verbosePrintf("error reading file VERSION: %v\n", err)
return ""
}
return strings.TrimSpace(string(buf))
}
// getVersion returns a version string which is a combination of the contents
// of the file VERSION in the current directory and the version from git (if
// available).
func getVersion() string {
versionFile := getVersionFromFile()
versionGit := getVersionFromGit()
verbosePrintf("version from file 'VERSION' is %q, version from git %q\n",
versionFile, versionGit)
switch {
case versionFile == "":
return versionGit
case versionGit == "":
return versionFile
}
return fmt.Sprintf("%s (%s)", versionFile, versionGit)
}
// getVersionFromGit returns a version string that identifies the currently
// checked out git commit.
func getVersionFromGit() string {
cmd := exec.Command("git", "describe",
"--long", "--tags", "--dirty", "--always")
out, err := cmd.Output()
if err != nil {
verbosePrintf("git describe returned error: %v\n", err)
return ""
}
version := strings.TrimSpace(string(out))
verbosePrintf("git version is %s\n", version)
return version
}
// Constants represents a set of constants that are set in the final binary to
// the given value via compiler flags.
type Constants map[string]string
// LDFlags returns the string that can be passed to go build's `-ldflags`.
func (cs Constants) LDFlags() string {
l := make([]string, 0, len(cs))
for k, v := range cs {
l = append(l, fmt.Sprintf(`-X "%s=%s"`, k, v))
}
return strings.Join(l, " ")
}
// GoVersion is the version of Go used to compile the project.
type GoVersion struct {
Major int
Minor int
Patch int
}
// ParseGoVersion parses the Go version s. If s cannot be parsed, the returned GoVersion is null.
func ParseGoVersion(s string) (v GoVersion) {
if !strings.HasPrefix(s, "go") {
return
}
s = s[2:]
data := strings.Split(s, ".")
if len(data) < 2 || len(data) > 3 {
// invalid version
return GoVersion{}
}
var err error
v.Major, err = strconv.Atoi(data[0])
if err != nil {
return GoVersion{}
}
// try to parse the minor version while removing an eventual suffix (like
// "rc2" or so)
for s := data[1]; s != ""; s = s[:len(s)-1] {
v.Minor, err = strconv.Atoi(s)
if err == nil {
break
}
}
if v.Minor == 0 {
// no minor version found
return GoVersion{}
}
if len(data) >= 3 {
v.Patch, err = strconv.Atoi(data[2])
if err != nil {
return GoVersion{}
}
}
return
}
// AtLeast returns true if v is at least as new as other. If v is empty, true is returned.
func (v GoVersion) AtLeast(other GoVersion) bool {
var empty GoVersion
// the empty version satisfies all versions
if v == empty {
return true
}
if v.Major > other.Major {
return true
}
if v.Major < other.Major {
return false
}
if v.Minor > other.Minor {
return true
}
if v.Minor < other.Minor {
return false
}
return v.Patch >= other.Patch
}
func (v GoVersion) String() string {
return fmt.Sprintf("Go %d.%d.%d", v.Major, v.Minor, v.Patch)
}
func main() {
if !goVersion.AtLeast(config.MinVersion) {
fmt.Fprintf(os.Stderr, "Detected version %s is too old, restic requires at least %s\n", goVersion, config.MinVersion)
os.Exit(1)
}
buildTags := config.DefaultBuildTags
skipNext := false
params := os.Args[1:]
env := map[string]string{
"GO111MODULE": "on", // make sure we build in Module mode
"GOOS": runtime.GOOS,
"GOARCH": runtime.GOARCH,
"GOARM": "",
}
var outputFilename string
for i, arg := range params {
if skipNext {
skipNext = false
continue
}
switch arg {
case "-v", "--verbose":
verbose = true
case "-t", "-tags", "--tags":
if i+1 >= len(params) {
die("-t given but no tag specified")
}
skipNext = true
buildTags = append(buildTags, strings.Split(params[i+1], " ")...)
case "-o", "--output":
skipNext = true
outputFilename = params[i+1]
case "-T", "--test":
runTests = true
case "--enable-cgo":
enableCGO = true
case "--enable-pie":
enablePIE = true
case "--goos":
skipNext = true
env["GOOS"] = params[i+1]
case "--goarch":
skipNext = true
env["GOARCH"] = params[i+1]
case "--goarm":
skipNext = true
env["GOARM"] = params[i+1]
case "-h":
showUsage(os.Stdout)
return
default:
fmt.Fprintf(os.Stderr, "Error: unknown option %q\n\n", arg)
showUsage(os.Stderr)
os.Exit(1)
}
}
verbosePrintf("detected Go version %v\n", goVersion)
preserveSymbols := false
for i := range buildTags {
buildTags[i] = strings.TrimSpace(buildTags[i])
if buildTags[i] == "debug" || buildTags[i] == "profile" {
preserveSymbols = true
}
}
verbosePrintf("build tags: %s\n", buildTags)
root, err := os.Getwd()
if err != nil {
die("Getwd(): %v\n", err)
}
if outputFilename == "" {
outputFilename = config.Name
if env["GOOS"] == "windows" {
outputFilename += ".exe"
}
}
output := outputFilename
if !filepath.IsAbs(output) {
output = filepath.Join(root, output)
}
version := getVersion()
constants := Constants{}
if version != "" {
constants["main.version"] = version
}
ldflags := constants.LDFlags()
if !preserveSymbols {
// Strip debug symbols.
ldflags = "-s -w " + ldflags
}
verbosePrintf("ldflags: %s\n", ldflags)
var (
buildArgs []string
testArgs []string
)
mainPackage := config.Main
if strings.HasPrefix(mainPackage, config.Namespace) {
mainPackage = strings.Replace(mainPackage, config.Namespace, "./", 1)
}
buildTarget := filepath.FromSlash(mainPackage)
buildCWD, err := os.Getwd()
if err != nil {
die("unable to determine current working directory: %v\n", err)
}
buildArgs = append(buildArgs,
"-tags", strings.Join(buildTags, " "),
"-ldflags", ldflags,
"-o", output, buildTarget,
)
err = build(buildCWD, env, buildArgs...)
if err != nil {
die("build failed: %v\n", err)
}
if runTests {
verbosePrintf("running tests\n")
testArgs = append(testArgs, config.Tests...)
err = test(buildCWD, env, testArgs...)
if err != nil {
die("running tests failed: %v\n", err)
}
}
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/doc.go | doc.go | // Package restic gives a (very brief) introduction to the structure of source code.
//
// # Overview
//
// The packages are structured so that cmd/ contains the main package for the
// restic binary, and internal/ contains almost all code in library form. We've
// chosen to use the internal/ path so that the packages cannot be imported by
// other programs. This was done on purpose, at the moment restic is a
// command-line program and not a library. This may be revisited at a later
// point in time.
package restic
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
restic/restic | https://github.com/restic/restic/blob/9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59/cmd/restic/cleanup.go | cmd/restic/cleanup.go | package main
import (
"context"
"fmt"
"io"
"os"
"os/signal"
"syscall"
"github.com/restic/restic/internal/debug"
)
func createGlobalContext(stderr io.Writer) context.Context {
ctx, cancel := context.WithCancel(context.Background())
ch := make(chan os.Signal, 1)
go cleanupHandler(ch, cancel, stderr)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
return ctx
}
// cleanupHandler handles the SIGINT and SIGTERM signals.
func cleanupHandler(c <-chan os.Signal, cancel context.CancelFunc, stderr io.Writer) {
s := <-c
debug.Log("signal %v received, cleaning up", s)
// ignore error as there's no good way to handle it
_, _ = fmt.Fprintf(stderr, "\rsignal %v received, cleaning up \n", s)
if val, _ := os.LookupEnv("RESTIC_DEBUG_STACKTRACE_SIGINT"); val != "" {
_, _ = stderr.Write([]byte("\n--- STACKTRACE START ---\n\n"))
_, _ = stderr.Write([]byte(debug.DumpStacktrace()))
_, _ = stderr.Write([]byte("\n--- STACKTRACE END ---\n"))
}
cancel()
}
// Exit terminates the process with the given exit code.
func Exit(code int) {
debug.Log("exiting with status code %d", code)
os.Exit(code)
}
| go | BSD-2-Clause | 9e2d60e28c662ee6e3a3d4f19e9f2d560abf9a59 | 2026-01-07T08:36:32.238827Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.