From 1cc22da87da73fa4db6fe6ff766f4276d3b7a7c5 Mon Sep 17 00:00:00 2001 From: Nick Craig-Wood Date: Wed, 27 Sep 2023 15:31:47 +0100 Subject: [PATCH] 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. --- vfs/vfscommon/cachemode.go | 54 ++++++++------------------------- vfs/vfscommon/cachemode_test.go | 2 +- 2 files changed, 14 insertions(+), 42 deletions(-) diff --git a/vfs/vfscommon/cachemode.go b/vfs/vfscommon/cachemode.go index c82f3bc98..ab1ccb3dc 100644 --- a/vfs/vfscommon/cachemode.go +++ b/vfs/vfscommon/cachemode.go @@ -2,13 +2,22 @@ package vfscommon import ( - "fmt" - "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 byte +type CacheMode = fs.Enum[cacheModeChoices] // CacheMode options const ( @@ -18,44 +27,7 @@ const ( 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 -func (l *CacheMode) Type() string { +func (cacheModeChoices) Type() string { 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 - }) -} diff --git a/vfs/vfscommon/cachemode_test.go b/vfs/vfscommon/cachemode_test.go index f36c9ad2e..fb8f86734 100644 --- a/vfs/vfscommon/cachemode_test.go +++ b/vfs/vfscommon/cachemode_test.go @@ -18,7 +18,7 @@ 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, "CacheMode(17)", CacheMode(17).String()) + assert.Equal(t, "Unknown(17)", CacheMode(17).String()) } func TestCacheModeSet(t *testing.T) {