From d2edf67b28aeb4c5cae02576b5acf06ef63062a3 Mon Sep 17 00:00:00 2001 From: albertony <12441419+albertony@users.noreply.github.com> Date: Thu, 13 Jan 2022 13:50:53 +0100 Subject: [PATCH] vfs: avoid duplicate encoding of cache paths Minor refactoring to improve code, but no functional changes. Could be improved further: Currently it always calls createDir on data path and meta path. If input is a file name without path this will effectively call createDir on the cache roots. Cache roots should always exist, because this is ensured in New function. The createDir should then always end up just calling os.Stat on the cache roots and checking IsDir on result. In addition to the unnecessary stat call, this will also perform unnecessary filepath processing: Joining root with empty path still performs clean on root, but it has already been cleaned. One reason to keep calling createDir unconditionally could be that it gives an extra failsafe, if cache root directories for some reason has been deleted they will be recreated instead of cache operation failing. --- vfs/vfscache/cache.go | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/vfs/vfscache/cache.go b/vfs/vfscache/cache.go index 9c7feb646..63e666044 100644 --- a/vfs/vfscache/cache.go +++ b/vfs/vfscache/cache.go @@ -195,18 +195,19 @@ func createRootDirs(parentOSPath string, relativeDirOSPath string) (dataOSPath s // // 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 { + relativePath := toOSPath(name) + relativeDir := vfscommon.OSFindParent(relativePath) + // Ensure cache directories exists. + // Could skip this if relativeDir=="", since the cache root paths should + // always exist (ensured in New function), which would avoid unnecessary path + // operations and os.Stat, but by always doing it we get an extra failsafe... + if err := createDir(filepath.Join(c.root, relativeDir)); err != nil { return "", fmt.Errorf("failed to create data cache item directory: %w", err) } - parentPathMeta := c.toOSPathMeta(parent) - err = createDir(parentPathMeta) - if err != nil { + if err := createDir(filepath.Join(c.metaRoot, relativeDir)); err != nil { return "", fmt.Errorf("failed to create metadata cache item directory: %w", err) } - return c.toOSPath(name), nil + return filepath.Join(c.root, relativePath), nil } // getBackend gets a backend for a cache root dir