From af79c1e6ef3a1ebdf5660a1b5e2a57ca30dd5a0e Mon Sep 17 00:00:00 2001 From: pancake Date: Fri, 1 Apr 2022 21:04:43 +0200 Subject: [PATCH] os: implement os.config_dir() like in Go's UserConfigDir (#13893) --- vlib/os/os.v | 30 ++++++++++++++++++++++++++++++ vlib/os/os_test.v | 7 +++++++ 2 files changed, 37 insertions(+) diff --git a/vlib/os/os.v b/vlib/os/os.v index a0a8397249..8940aecb5d 100644 --- a/vlib/os/os.v +++ b/vlib/os/os.v @@ -766,3 +766,33 @@ pub fn quoted_path(path string) string { return "'$path'" } } + +// config_dir returns the path to the user configuration directory (depending on the platform). +// On windows, that is `%AppData%`. +// On macos, that is `~/Library/Application Support`. +// On the rest, that is `$XDG_CONFIG_HOME`, or if that is not available, `~/.config`. +// If the path cannot be determined, it returns an error. +// (for example, when $HOME on linux, or %AppData% on windows is not defined) +pub fn config_dir() ?string { + $if windows { + app_data := getenv('AppData') + if app_data != '' { + return app_data + } + } $else $if macos || darwin || ios { + home := home_dir() + if home != '' { + return home + '/Library/Application Support' + } + } $else { + xdg_home := getenv('XDG_CONFIG_HOME') + if xdg_home != '' { + return xdg_home + } + home := home_dir() + if home != '' { + return home + '/.config' + } + } + return error('Cannot find config directory') +} diff --git a/vlib/os/os_test.v b/vlib/os/os_test.v index d527b6bd29..ee5dfc6fb4 100644 --- a/vlib/os/os_test.v +++ b/vlib/os/os_test.v @@ -894,3 +894,10 @@ fn test_command() { // dump( cmd_to_fail ) assert cmd_to_fail.exit_code != 0 // 2 on linux, 1 on macos } + +fn test_config_dir() { + cdir := os.config_dir() or { panic(err) } + adir := '$cdir/test-v-config' + os.mkdir_all(adir) or { panic(err) } + os.rmdir(adir) or { panic(err) } +}