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.
This commit is contained in:
albertony 2022-01-13 13:50:53 +01:00
parent 0e77072dcc
commit d2edf67b28

View File

@ -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