Skip to content

Commit 816154b

Browse files
committed
os: add UserCacheDir
Adds a function that returns an OS-dependent location for user-specific cache data. Fixes #22536 Change-Id: Ifff015452494571ad357fa2d945d66a5992c751d Reviewed-on: https://go-review.googlesource.com/78835 Run-TryBot: Andrew Bonventre <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent 45ca979 commit 816154b

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/os/file.go

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ import (
4141
"internal/poll"
4242
"internal/testlog"
4343
"io"
44+
"runtime"
4445
"syscall"
4546
"time"
4647
)
@@ -315,6 +316,54 @@ func TempDir() string {
315316
return tempDir()
316317
}
317318

319+
// UserCacheDir returns the default root directory to use for user-specific
320+
// cached data. Users should create their own application-specific subdirectory
321+
// within this one and use that.
322+
//
323+
// On Unix systems, it returns $XDG_CACHE_HOME as specified by
324+
// https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html if
325+
// non-empty, else $HOME/.cache.
326+
// On Darwin, it returns $HOME/Library/Caches.
327+
// On Windows, it returns %LocalAppData%.
328+
// On Plan 9, it returns $home/lib/cache.
329+
//
330+
// If the location cannot be determined (for example, $HOME is not defined),
331+
// then it will return an empty string.
332+
func UserCacheDir() string {
333+
var dir string
334+
335+
switch runtime.GOOS {
336+
case "windows":
337+
dir = Getenv("LocalAppData")
338+
339+
case "darwin":
340+
dir = Getenv("HOME")
341+
if dir == "" {
342+
return ""
343+
}
344+
dir += "/Library/Caches"
345+
346+
case "plan9":
347+
dir = Getenv("home")
348+
if dir == "" {
349+
return ""
350+
}
351+
dir += "/lib/cache"
352+
353+
default: // Unix
354+
dir = Getenv("XDG_CACHE_HOME")
355+
if dir == "" {
356+
dir = Getenv("HOME")
357+
if dir == "" {
358+
return ""
359+
}
360+
dir += "/.cache"
361+
}
362+
}
363+
364+
return dir
365+
}
366+
318367
// Chmod changes the mode of the named file to mode.
319368
// If the file is a symbolic link, it changes the mode of the link's target.
320369
// If there is an error, it will be of type *PathError.

0 commit comments

Comments
 (0)