1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

os: implement os.config_dir() like in Go's UserConfigDir (#13893)

This commit is contained in:
pancake 2022-04-01 21:04:43 +02:00 committed by GitHub
parent d7817863c6
commit af79c1e6ef
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 37 additions and 0 deletions

View File

@ -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')
}

View File

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