vfs: re-implement CacheMode with fs.Enum

This almost 100% backwards compatible. The only difference being that
in the rc options/get output CacheMode will be output as strings
instead of integers. This is a lot more convenient for the user. They
still accept integer inputs though so the fallout from this should be
minimal.
This commit is contained in:
Nick Craig-Wood 2023-09-27 15:31:47 +01:00
parent 3092f82dcc
commit 1cc22da87d
2 changed files with 14 additions and 42 deletions

View File

@ -2,13 +2,22 @@
package vfscommon package vfscommon
import ( import (
"fmt"
"github.com/rclone/rclone/fs" "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 // CacheMode controls the functionality of the cache
type CacheMode byte type CacheMode = fs.Enum[cacheModeChoices]
// CacheMode options // CacheMode options
const ( const (
@ -18,44 +27,7 @@ const (
CacheModeFull // cache all files opened in any mode CacheModeFull // cache all files opened in any mode
) )
var cacheModeToString = []string{
CacheModeOff: "off",
CacheModeMinimal: "minimal",
CacheModeWrites: "writes",
CacheModeFull: "full",
}
// String turns a CacheMode into a string
func (l CacheMode) String() string {
if l >= CacheMode(len(cacheModeToString)) {
return fmt.Sprintf("CacheMode(%d)", l)
}
return cacheModeToString[l]
}
// Set a CacheMode
func (l *CacheMode) Set(s string) error {
for n, name := range cacheModeToString {
if s != "" && name == s {
*l = CacheMode(n)
return nil
}
}
return fmt.Errorf("unknown cache mode level %q", s)
}
// Type of the value // Type of the value
func (l *CacheMode) Type() string { func (cacheModeChoices) Type() string {
return "CacheMode" return "CacheMode"
} }
// UnmarshalJSON makes sure the value can be parsed as a string or integer in JSON
func (l *CacheMode) UnmarshalJSON(in []byte) error {
return fs.UnmarshalJSONFlag(in, l, func(i int64) error {
if i < 0 || i >= int64(len(cacheModeToString)) {
return fmt.Errorf("unknown cache mode level %d", i)
}
*l = CacheMode(i)
return nil
})
}

View File

@ -18,7 +18,7 @@ var _ json.Unmarshaler = (*CacheMode)(nil)
func TestCacheModeString(t *testing.T) { func TestCacheModeString(t *testing.T) {
assert.Equal(t, "off", CacheModeOff.String()) assert.Equal(t, "off", CacheModeOff.String())
assert.Equal(t, "full", CacheModeFull.String()) assert.Equal(t, "full", CacheModeFull.String())
assert.Equal(t, "CacheMode(17)", CacheMode(17).String()) assert.Equal(t, "Unknown(17)", CacheMode(17).String())
} }
func TestCacheModeSet(t *testing.T) { func TestCacheModeSet(t *testing.T) {