pax_global_header00006660000000000000000000000064141362353320014514gustar00rootroot0000000000000052 comment=4ec40e24f0cf1039f93c773f2984decdea9719b5 xdg-0.4.0/000077500000000000000000000000001413623533200122775ustar00rootroot00000000000000xdg-0.4.0/.github/000077500000000000000000000000001413623533200136375ustar00rootroot00000000000000xdg-0.4.0/.github/FUNDING.yml000066400000000000000000000000151413623533200154500ustar00rootroot00000000000000ko_fi: adrgb xdg-0.4.0/.github/dependabot.yml000066400000000000000000000004111413623533200164630ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "gomod" directory: "/" schedule: interval: "daily" reviewers: - "adrg" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" reviewers: - "adrg" xdg-0.4.0/.github/workflows/000077500000000000000000000000001413623533200156745ustar00rootroot00000000000000xdg-0.4.0/.github/workflows/ci.yml000066400000000000000000000015451413623533200170170ustar00rootroot00000000000000name: CI on: push: branches: [master] pull_request: branches: [master] jobs: build: strategy: matrix: go: ['1.16'] os: [ubuntu-latest, macos-latest, windows-latest] runs-on: ${{ matrix.os }} steps: - name: Setup uses: actions/setup-go@v2 with: go-version: ${{ matrix.go }} - name: Prepare checkout run: git config --global core.autocrlf false - name: Checkout uses: actions/checkout@v2 - name: Dependencies run: | go version go get -v -t -d ./... go get -u golang.org/x/lint/golint - name: Lint run: golint -set_exit_status=1 ./... - name: Vet run: go vet ./... - name: Test run: go test -v -coverprofile coverage.txt -covermode atomic ./... - name: Coverage uses: codecov/codecov-action@v2.1.0 xdg-0.4.0/.github/workflows/codeql-analysis.yml000066400000000000000000000013071413623533200215100ustar00rootroot00000000000000name: "CodeQL" on: push: branches: [ master ] pull_request: branches: [ master ] schedule: - cron: '0 6 * * 1' jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'go' ] steps: - name: Checkout repository uses: actions/checkout@v2 - name: Initialize CodeQL uses: github/codeql-action/init@v1 with: languages: ${{ matrix.language }} - name: Autobuild uses: github/codeql-action/autobuild@v1 - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v1 xdg-0.4.0/CODE_OF_CONDUCT.md000066400000000000000000000064351413623533200151060ustar00rootroot00000000000000# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behaviour that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behaviour by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behaviour and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behaviour. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviour that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behaviour may be reported by contacting the project team at adrg@epistack.com. All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html [homepage]: https://www.contributor-covenant.org For answers to common questions about this code of conduct, see https://www.contributor-covenant.org/faq xdg-0.4.0/CONTRIBUTING.md000066400000000000000000000115541413623533200145360ustar00rootroot00000000000000# Contributing to this project Contributions in the form of pull requests, issues or just general feedback, are always welcome. Please take a moment to review this document in order to make the contribution process easy and effective for everyone involved. Following these guidelines helps to communicate that you respect the time of the developers managing and developing this open source project. In return, they should reciprocate that respect in addressing your issue or assessing patches and features. ## Using the issue tracker The issue tracker is the preferred channel for [bug reports](#bugs), [features requests](#features) and [submitting pull requests](#pull-requests), but please respect the following restrictions: * Please **do not** use the issue tracker for personal support requests (use [Stack Overflow](http://stackoverflow.com) or IRC). * Please **do not** derail or troll issues. Keep the discussion on topic and respect the opinions of others. ## Bug reports A bug is a _demonstrable problem_ that is caused by the code in the repository. Good bug reports are extremely helpful - thank you! Guidelines for bug reports: 1. **Use the GitHub issue search** — check if the issue has already been reported. 2. **Check if the issue has been fixed** — try to reproduce it using the latest `master` or development branch in the repository. 3. **Isolate the problem** — create a reduced test case. A good bug report shouldn't leave others needing to chase you up for more information. Please try to be as detailed as possible in your report. What is your environment? What steps will reproduce the issue? What browser(s) and OS experience the problem? What would you expect to be the outcome? All these details will help people to fix any potential bugs. Example: > Short and descriptive example bug report title > > A summary of the issue and the browser/OS environment in which it occurs. If > suitable, include the steps required to reproduce the bug. > > 1. This is the first step > 2. This is the second step > 3. Further steps, etc. > > `` - a link to the reduced test case > > Any other information you want to share that is relevant to the issue being > reported. This might include the lines of code that you have identified as > causing the bug, and potential solutions (and your opinions on their > merits). ## Feature requests Feature requests are welcome. But take a moment to find out whether your idea fits with the scope and aims of the project. It's up to *you* to make a strong case to convince the project's developers of the merits of this feature. Please provide as much detail and context as possible. ## Pull requests Good pull requests - patches, improvements, new features - are a fantastic help. They should remain focused in scope and avoid containing unrelated commits. **Please ask first** before embarking on any significant pull request (e.g. implementing features, refactoring code, porting to a different language), otherwise you risk spending a lot of time working on something that the project's developers might not want to merge into the project. Please adhere to the coding conventions used throughout a project (indentation, accurate comments, etc.) and any other requirements (such as test coverage). Follow this process if you'd like your work considered for inclusion in the project: 1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork, and configure the remotes: ```bash # Clone your fork of the repo into the current directory git clone https://github.com// # Navigate to the newly cloned directory cd # Assign the original repo to a remote called "upstream" git remote add upstream https://github.com// ``` 2. If you cloned a while ago, get the latest changes from upstream: ```bash git checkout git pull upstream ``` 3. Create a new topic branch (off the main project development branch) to contain your feature, change, or fix: ```bash git checkout -b ``` 4. Commit your changes in logical chunks and use descriptive commit messages. Use [interactive rebase](https://help.github.com/articles/interactive-rebase) to tidy up your commits before making them public. 5. Locally merge (or rebase) the upstream development branch into your topic branch: ```bash git pull [--rebase] upstream ``` 6. Push your topic branch up to your fork: ```bash git push origin ``` 7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/) with a clear title and description. **IMPORTANT**: By submitting a patch, you agree to allow the project owner to license your work under the same license as that used by the project. xdg-0.4.0/LICENSE000066400000000000000000000021231413623533200133020ustar00rootroot00000000000000The MIT License (MIT) Copyright (c) 2014 Adrian-George Bostan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. xdg-0.4.0/README.md000066400000000000000000000540541413623533200135660ustar00rootroot00000000000000

xdg logo

Go implementation of the XDG Base Directory Specification and XDG user directories.

Build status Code coverage pkg.go.dev documentation MIT license
Go report card Awesome Go GitHub contributors GitHub open issues Buy me a coffee

Provides an implementation of the [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html). The specification defines a set of standard paths for storing application files, including data and configuration files. For portability and flexibility reasons, applications should use the XDG defined locations instead of hardcoding paths. The package also includes the locations of well known [user directories](https://wiki.archlinux.org/index.php/XDG_user_directories), as well as other common directories such as fonts and applications. The current implementation supports **most flavors of Unix**, **Windows**, **macOS** and **Plan 9**. On Windows, where XDG environment variables are not usually set, the package uses [Known Folders](https://docs.microsoft.com/en-us/windows/win32/shell/known-folders) as defaults. Therefore, appropriate locations are used for common [folders](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid) which may have been redirected. See usage [examples](#usage) below. Full documentation can be found at https://pkg.go.dev/github.com/adrg/xdg. ## Installation go get github.com/adrg/xdg ## Default locations The package defines sensible defaults for XDG variables which are empty or not present in the environment. - On Unix-like operating systems, XDG environment variables are tipically defined. Appropriate default locations are used for the environment variables which are not set. - On Windows, XDG environment variables are usually not set. If that is the case, the package relies on the appropriate [Known Folders](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid). Sensible fallback locations are used for the folders which are not set. ### XDG Base Directory
Unix-like operating systems
| |

Unix

|

macOS

|

Plan 9

| | :------------------------------------------------------------: | :-----------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------: | | XDG_DATA_HOME | ~/.local/share | ~/Library/Application Support | $home/lib | | XDG_DATA_DIRS | /usr/local/share
/usr/share | /Library/Application Support | /lib | | XDG_CONFIG_HOME | ~/.config | ~/Library/Application Support | $home/lib | | XDG_CONFIG_DIRS | /etc/xdg | ~/Library/Preferences
/Library/Application Support
/Library/Preferences | /lib | | XDG_STATE_HOME | ~/.local/state | ~/Library/Application Support | $home/lib/state | | XDG_CACHE_HOME | ~/.cache | ~/Library/Caches | $home/lib/cache | | XDG_RUNTIME_DIR | /run/user/UID | ~/Library/Application Support | /tmp |
Microsoft Windows
| |

Known Folder(s)

|

Fallback(s)

| | :------------------------------------------------------------: | :---------------------------------------------------------------------------------------: | :------------------------------------------------------------------------------: | | XDG_DATA_HOME | LocalAppData | %LOCALAPPDATA% | | XDG_DATA_DIRS | RoamingAppData
ProgramData | %APPADATA%
%ProgramData% | | XDG_CONFIG_HOME | LocalAppData | %LOCALAPPDATA% | | XDG_CONFIG_DIRS | ProgramData
RoamingAppData | %ProgramData%
%APPDATA% | | XDG_STATE_HOME | LocalAppData | %LOCALAPPDATA% | | XDG_CACHE_HOME | LocalAppData\cache | %LOCALAPPDATA%\cache | | XDG_RUNTIME_DIR | LocalAppData | %LOCALAPPDATA% |
### XDG user directories
Unix-like operating systems
| |

Unix

|

macOS

|

Plan 9

| | :--------------------------------------------------------------: | :-------------------------------------------------------------------------: | :---------------------------------------------------------------------------: | :---------------------------------------------------------------------------: | | XDG_DESKTOP_DIR | ~/Desktop | ~/Desktop | $home/desktop | | XDG_DOWNLOAD_DIR | ~/Downloads | ~/Downloads | $home/downloads | | XDG_DOCUMENTS_DIR | ~/Documents | ~/Documents | $home/documents | | XDG_MUSIC_DIR | ~/Music | ~/Music | $home/music | | XDG_PICTURES_DIR | ~/Pictures | ~/Pictures | $home/pictures | | XDG_VIDEOS_DIR | ~/Videos | ~/Movies | $home/videos | | XDG_TEMPLATES_DIR | ~/Templates | ~/Templates | $home/templates | | XDG_PUBLICSHARE_DIR | ~/Public | ~/Public | $home/public |
Microsoft Windows
| |

Known Folder(s)

|

Fallback(s)

| | :--------------------------------------------------------------: | :-----------------------------------------------------------------------------------------: | :--------------------------------------------------------------------------------: | | XDG_DESKTOP_DIR | Desktop | %USERPROFILE%\Desktop | | XDG_DOWNLOAD_DIR | Downloads | %USERPROFILE%\Downloads | | XDG_DOCUMENTS_DIR | Documents | %USERPROFILE%\Documents | | XDG_MUSIC_DIR | Music | %USERPROFILE%\Music | | XDG_PICTURES_DIR | Pictures | %USERPROFILE%\Pictures | | XDG_VIDEOS_DIR | Videos | %USERPROFILE%\Videos | | XDG_TEMPLATES_DIR | Templates | %APPDATA%\Microsoft\Windows\Templates | | XDG_PUBLICSHARE_DIR | Public | %PUBLIC% |
### Other directories
Unix-like operating systems
| |

Unix

|

macOS

|

Plan 9

| | :-----------------------------------------------------------: | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------: | :------------------------------------------------------------------------: | | Home | $HOME | $HOME | $home | | Applications | $XDG_DATA_HOME/applications
~/.local/share/applications
/usr/local/share/applications
/usr/share/applications
$XDG_DATA_DIRS/applications | /Applications | $home/bin
/bin | | Fonts | $XDG_DATA_HOME/fonts
~/.fonts
~/.local/share/fonts
/usr/local/share/fonts
/usr/share/fonts
$XDG_DATA_DIRS/fonts | ~/Library/Fonts
/Library/Fonts
/System/Library/Fonts
/Network/Library/Fonts | $home/lib/font
/lib/font |
Microsoft Windows
| |

Known Folder(s)

|

Fallback(s)

| | :-----------------------------------------------------------: | :--------------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------------------------------------------------------------: | | Home | Profile | %USERPROFILE% | | Applications | Programs
CommonPrograms | %APPDATA%\Microsoft\Windows\Start Menu\Programs
%ProgramData%\Microsoft\Windows\Start Menu\Programs | | Fonts | Fonts
- | %SystemRoot%\Fonts
%LOCALAPPDATA%\Microsoft\Windows\Fonts |
## Usage #### XDG Base Directory ```go package main import ( "log" "github.com/adrg/xdg" ) func main() { // XDG Base Directory paths. log.Println("Home data directory:", xdg.DataHome) log.Println("Data directories:", xdg.DataDirs) log.Println("Home config directory:", xdg.ConfigHome) log.Println("Config directories:", xdg.ConfigDirs) log.Println("Home state directory:", xdg.StateHome) log.Println("Cache directory:", xdg.CacheHome) log.Println("Runtime directory:", xdg.RuntimeDir) // Other common directories. log.Println("Home directory:", xdg.Home) log.Println("Application directories:", xdg.ApplicationDirs) log.Println("Font directories:", xdg.FontDirs) // Obtain a suitable location for application config files. // ConfigFile takes one parameter which must contain the name of the file, // but it can also contain a set of parent directories. If the directories // don't exist, they will be created relative to the base config directory. configFilePath, err := xdg.ConfigFile("appname/config.yaml") if err != nil { log.Fatal(err) } log.Println("Save the config file at:", configFilePath) // For other types of application files use: // xdg.DataFile() // xdg.StateFile() // xdg.CacheFile() // xdg.RuntimeFile() // Finding application config files. // SearchConfigFile takes one parameter which must contain the name of // the file, but it can also contain a set of parent directories relative // to the config search paths (xdg.ConfigHome and xdg.ConfigDirs). configFilePath, err = xdg.SearchConfigFile("appname/config.yaml") if err != nil { log.Fatal(err) } log.Println("Config file was found at:", configFilePath) // For other types of application files use: // xdg.SearchDataFile() // xdg.SearchStateFile() // xdg.SearchCacheFile() // xdg.SearchRuntimeFile() } ``` #### XDG user directories ```go package main import ( "log" "github.com/adrg/xdg" ) func main() { // XDG user directories. log.Println("Desktop directory:", xdg.UserDirs.Desktop) log.Println("Download directory:", xdg.UserDirs.Download) log.Println("Documents directory:", xdg.UserDirs.Documents) log.Println("Music directory:", xdg.UserDirs.Music) log.Println("Pictures directory:", xdg.UserDirs.Pictures) log.Println("Videos directory:", xdg.UserDirs.Videos) log.Println("Templates directory:", xdg.UserDirs.Templates) log.Println("Public directory:", xdg.UserDirs.PublicShare) } ``` ## Stargazers over time [![Stargazers over time](https://starchart.cc/adrg/xdg.svg)](https://starchart.cc/adrg/xdg) ## Contributing Contributions in the form of pull requests, issues or just general feedback, are always welcome. See [CONTRIBUTING.MD](CONTRIBUTING.md). **Contributors**: [adrg](https://github.com/adrg), [wichert](https://github.com/wichert), [bouncepaw](https://github.com/bouncepaw), [gabriel-vasile](https://github.com/gabriel-vasile), [KalleDK](https://github.com/KalleDK), [nvkv](https://github.com/nvkv), [djdv](https://github.com/djdv). ## References For more information see: * [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html) * [XDG user directories](https://wiki.archlinux.org/index.php/XDG_user_directories) * [Windows Known Folders](https://docs.microsoft.com/en-us/windows/win32/shell/knownfolderid) ## License Copyright (c) 2014 Adrian-George Bostan. This project is licensed under the [MIT license](https://opensource.org/licenses/MIT). See [LICENSE](LICENSE) for more details. xdg-0.4.0/base_dirs.go000066400000000000000000000037401413623533200145650ustar00rootroot00000000000000package xdg import "github.com/adrg/xdg/internal/pathutil" // XDG Base Directory environment variables. const ( envDataHome = "XDG_DATA_HOME" envDataDirs = "XDG_DATA_DIRS" envConfigHome = "XDG_CONFIG_HOME" envConfigDirs = "XDG_CONFIG_DIRS" envStateHome = "XDG_STATE_HOME" envCacheHome = "XDG_CACHE_HOME" envRuntimeDir = "XDG_RUNTIME_DIR" ) type baseDirectories struct { dataHome string data []string configHome string config []string stateHome string cacheHome string runtime string // Non-standard directories. fonts []string applications []string } func (bd baseDirectories) dataFile(relPath string) (string, error) { return pathutil.Create(relPath, append([]string{bd.dataHome}, bd.data...)) } func (bd baseDirectories) configFile(relPath string) (string, error) { return pathutil.Create(relPath, append([]string{bd.configHome}, bd.config...)) } func (bd baseDirectories) stateFile(relPath string) (string, error) { return pathutil.Create(relPath, []string{bd.stateHome}) } func (bd baseDirectories) cacheFile(relPath string) (string, error) { return pathutil.Create(relPath, []string{bd.cacheHome}) } func (bd baseDirectories) runtimeFile(relPath string) (string, error) { return pathutil.Create(relPath, []string{bd.runtime}) } func (bd baseDirectories) searchDataFile(relPath string) (string, error) { return pathutil.Search(relPath, append([]string{bd.dataHome}, bd.data...)) } func (bd baseDirectories) searchConfigFile(relPath string) (string, error) { return pathutil.Search(relPath, append([]string{bd.configHome}, bd.config...)) } func (bd baseDirectories) searchStateFile(relPath string) (string, error) { return pathutil.Search(relPath, []string{bd.stateHome}) } func (bd baseDirectories) searchCacheFile(relPath string) (string, error) { return pathutil.Search(relPath, []string{bd.cacheHome}) } func (bd baseDirectories) searchRuntimeFile(relPath string) (string, error) { return pathutil.Search(relPath, []string{bd.runtime}) } xdg-0.4.0/codecov.yml000066400000000000000000000002461413623533200144460ustar00rootroot00000000000000coverage: status: project: default: target: 90% threshold: 1% patch: default: target: 100% ignore: - "paths_plan9.go" xdg-0.4.0/doc.go000066400000000000000000000064471413623533200134060ustar00rootroot00000000000000/* Package xdg provides an implementation of the XDG Base Directory Specification. The specification defines a set of standard paths for storing application files including data and configuration files. For portability and flexibility reasons, applications should use the XDG defined locations instead of hardcoding paths. The package also includes the locations of well known user directories. The current implementation supports most flavors of Unix, Windows, Mac OS and Plan 9. For more information regarding the XDG Base Directory Specification see: https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html For more information regarding the XDG user directories see: https://wiki.archlinux.org/index.php/XDG_user_directories For more information regarding the Windows Known Folders see: https://docs.microsoft.com/en-us/windows/win32/shell/known-folders Usage XDG Base Directory package main import ( "log" "github.com/adrg/xdg" ) func main() { // XDG Base Directory paths. log.Println("Home data directory:", xdg.DataHome) log.Println("Data directories:", xdg.DataDirs) log.Println("Home config directory:", xdg.ConfigHome) log.Println("Config directories:", xdg.ConfigDirs) log.Println("Home state directory:", xdg.StateHome) log.Println("Cache directory:", xdg.CacheHome) log.Println("Runtime directory:", xdg.RuntimeDir) // Other common directories. log.Println("Home directory:", xdg.Home) log.Println("Application directories:", xdg.ApplicationDirs) log.Println("Font directories:", xdg.FontDirs) // Obtain a suitable location for application config files. // ConfigFile takes one parameter which must contain the name of the file, // but it can also contain a set of parent directories. If the directories // don't exist, they will be created relative to the base config directory. configFilePath, err := xdg.ConfigFile("appname/config.yaml") if err != nil { log.Fatal(err) } log.Println("Save the config file at:", configFilePath) // For other types of application files use: // xdg.DataFile() // xdg.StateFile() // xdg.CacheFile() // xdg.RuntimeFile() // Finding application config files. // SearchConfigFile takes one parameter which must contain the name of // the file, but it can also contain a set of parent directories relative // to the config search paths (xdg.ConfigHome and xdg.ConfigDirs). configFilePath, err = xdg.SearchConfigFile("appname/config.yaml") if err != nil { log.Fatal(err) } log.Println("Config file was found at:", configFilePath) // For other types of application files use: // xdg.SearchDataFile() // xdg.SearchStateFile() // xdg.SearchCacheFile() // xdg.SearchRuntimeFile() } XDG user directories package main import ( "log" "github.com/adrg/xdg" ) func main() { // XDG user directories. log.Println("Desktop directory:", xdg.UserDirs.Desktop) log.Println("Download directory:", xdg.UserDirs.Download) log.Println("Documents directory:", xdg.UserDirs.Documents) log.Println("Music directory:", xdg.UserDirs.Music) log.Println("Pictures directory:", xdg.UserDirs.Pictures) log.Println("Videos directory:", xdg.UserDirs.Videos) log.Println("Templates directory:", xdg.UserDirs.Templates) log.Println("Public directory:", xdg.UserDirs.PublicShare) } */ package xdg xdg-0.4.0/example_test.go000066400000000000000000000040121413623533200153150ustar00rootroot00000000000000package xdg_test import ( "fmt" "github.com/adrg/xdg" ) func ExampleDataFile() { dataFilePath, err := xdg.DataFile("appname/app.data") if err != nil { // Treat error. } fmt.Println("Save data file at:", dataFilePath) } func ExampleConfigFile() { configFilePath, err := xdg.ConfigFile("appname/app.yaml") if err != nil { // Treat error. } fmt.Println("Save config file at:", configFilePath) } func ExampleStateFile() { stateFilePath, err := xdg.DataFile("appname/app.state") if err != nil { // Treat error. } fmt.Println("Save state file at:", stateFilePath) } func ExampleCacheFile() { cacheFilePath, err := xdg.CacheFile("appname/app.cache") if err != nil { // Treat error. } fmt.Println("Save cache file at:", cacheFilePath) } func ExampleRuntimeFile() { runtimeFilePath, err := xdg.RuntimeFile("appname/app.pid") if err != nil { // Treat error. } fmt.Println("Save runtime file at:", runtimeFilePath) } func ExampleSearchDataFile() { dataFilePath, err := xdg.SearchDataFile("appname/app.data") if err != nil { // The data file could not be found. } fmt.Println("The data file was found at:", dataFilePath) } func ExampleSearchConfigFile() { configFilePath, err := xdg.SearchConfigFile("appname/app.yaml") if err != nil { // The config file could not be found. } fmt.Println("The config file was found at:", configFilePath) } func ExampleSearchStateFile() { stateFilePath, err := xdg.SearchStateFile("appname/app.state") if err != nil { // The state file could not be found. } fmt.Println("The state file was found at:", stateFilePath) } func ExampleSearchCacheFile() { cacheFilePath, err := xdg.SearchCacheFile("appname/app.cache") if err != nil { // The cache file could not be found. } fmt.Println("The cache file was found at:", cacheFilePath) } func ExampleSearchRuntimeFile() { runtimeFilePath, err := xdg.SearchRuntimeFile("appname/app.pid") if err != nil { // The runtime file could not be found. } fmt.Println("The runtime file was found at:", runtimeFilePath) } xdg-0.4.0/go.mod000066400000000000000000000002121413623533200134000ustar00rootroot00000000000000module github.com/adrg/xdg go 1.14 require ( github.com/stretchr/testify v1.7.0 golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359 ) xdg-0.4.0/go.sum000066400000000000000000000023171413623533200134350ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359 h1:2B5p2L5IfGiD7+b9BOoRMC6DgObAVZV+Fsp050NqXik= golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= xdg-0.4.0/internal/000077500000000000000000000000001413623533200141135ustar00rootroot00000000000000xdg-0.4.0/internal/pathutil/000077500000000000000000000000001413623533200157455ustar00rootroot00000000000000xdg-0.4.0/internal/pathutil/pathutil.go000066400000000000000000000042661413623533200201360ustar00rootroot00000000000000package pathutil import ( "fmt" "os" "path/filepath" "strings" ) // Unique eliminates the duplicate paths from the provided slice and returns // the result. The items in the output slice are in the order in which they // occur in the input slice. If a `home` location is provided, the paths are // expanded using the `ExpandHome` function. func Unique(paths []string, home string) []string { var ( uniq []string registry = map[string]struct{}{} ) for _, p := range paths { p = ExpandHome(p, home) if p != "" && filepath.IsAbs(p) { if _, ok := registry[p]; ok { continue } registry[p] = struct{}{} uniq = append(uniq, p) } } return uniq } // Create returns a suitable location relative to which the file with the // specified `name` can be written. The first path from the provided `paths` // slice which is successfully created (or already exists) is used as a base // path for the file. The `name` parameter should contain the name of the file // which is going to be written in the location returned by this function, but // it can also contain a set of parent directories, which will be created // relative to the selected parent path. func Create(name string, paths []string) (string, error) { var searchedPaths []string for _, p := range paths { p = filepath.Join(p, name) dir := filepath.Dir(p) if Exists(dir) { return p, nil } if err := os.MkdirAll(dir, os.ModeDir|0700); err == nil { return p, nil } searchedPaths = append(searchedPaths, dir) } return "", fmt.Errorf("could not create any of the following paths: %s", strings.Join(searchedPaths, ", ")) } // Search searches for the file with the specified `name` in the provided // slice of `paths`. The `name` parameter must contain the name of the file, // but it can also contain a set of parent directories. func Search(name string, paths []string) (string, error) { var searchedPaths []string for _, p := range paths { p = filepath.Join(p, name) if Exists(p) { return p, nil } searchedPaths = append(searchedPaths, filepath.Dir(p)) } return "", fmt.Errorf("could not locate `%s` in any of the following paths: %s", filepath.Base(name), strings.Join(searchedPaths, ", ")) } xdg-0.4.0/internal/pathutil/pathutil_plan9.go000066400000000000000000000011111413623533200212230ustar00rootroot00000000000000package pathutil import ( "os" "path/filepath" "strings" ) // Exists returns true if the specified path exists. func Exists(path string) bool { _, err := os.Stat(path) return err == nil || os.IsExist(err) } // ExpandHome substitutes `~` and `$home` at the start of the specified // `path` using the provided `home` location. func ExpandHome(path, home string) string { if path == "" || home == "" { return path } if path[0] == '~' { return filepath.Join(home, path[1:]) } if strings.HasPrefix(path, "$home") { return filepath.Join(home, path[5:]) } return path } xdg-0.4.0/internal/pathutil/pathutil_plan9_test.go000066400000000000000000000024361413623533200222750ustar00rootroot00000000000000//go:build plan9 // +build plan9 package pathutil_test import ( "path/filepath" "testing" "github.com/adrg/xdg/internal/pathutil" "github.com/stretchr/testify/require" ) func TestExpandHome(t *testing.T) { home := "/home/test" require.Equal(t, home, pathutil.ExpandHome("~", home)) require.Equal(t, home, pathutil.ExpandHome("$home", home)) require.Equal(t, filepath.Join(home, "appname"), pathutil.ExpandHome("~/appname", home)) require.Equal(t, filepath.Join(home, "appname"), pathutil.ExpandHome("$home/appname", home)) require.Equal(t, "", pathutil.ExpandHome("", home)) require.Equal(t, home, pathutil.ExpandHome(home, "")) require.Equal(t, "", pathutil.ExpandHome("", "")) require.Equal(t, home, pathutil.ExpandHome(home, home)) require.Equal(t, "/", pathutil.ExpandHome("~", "/")) require.Equal(t, "/", pathutil.ExpandHome("$home", "/")) require.Equal(t, "/usr/bin", pathutil.ExpandHome("~/bin", "/usr")) require.Equal(t, "/usr/bin", pathutil.ExpandHome("$home/bin", "/usr")) } func TestUnique(t *testing.T) { input := []string{ "", "/home", "/home/test", "a", "~/appname", "$home/appname", "a", "/home", } expected := []string{ "/home", "/home/test", "/home/test/appname", } require.EqualValues(t, expected, pathutil.Unique(input, "/home/test")) } xdg-0.4.0/internal/pathutil/pathutil_test.go000066400000000000000000000063241413623533200211720ustar00rootroot00000000000000package pathutil_test import ( "os" "path/filepath" "testing" "github.com/adrg/xdg/internal/pathutil" "github.com/stretchr/testify/require" ) func TestExists(t *testing.T) { tempDir := os.TempDir() // Test regular file. pathFile := filepath.Join(tempDir, "regular") f, err := os.Create(pathFile) require.NoError(t, err) require.NoError(t, f.Close()) require.True(t, pathutil.Exists(pathFile)) // Test symlink. pathSymlink := filepath.Join(tempDir, "symlink") require.NoError(t, os.Symlink(pathFile, pathSymlink)) require.True(t, pathutil.Exists(pathSymlink)) // Test non-existent file. require.NoError(t, os.Remove(pathFile)) require.False(t, pathutil.Exists(pathFile)) require.False(t, pathutil.Exists(pathSymlink)) require.NoError(t, os.Remove(pathSymlink)) require.False(t, pathutil.Exists(pathSymlink)) } func TestCreate(t *testing.T) { tempDir := os.TempDir() // Test path selection order. p, err := pathutil.Create("test", []string{tempDir, "\000a"}) require.NoError(t, err) require.Equal(t, filepath.Join(tempDir, "test"), p) p, err = pathutil.Create("test", []string{"\000a", tempDir}) require.NoError(t, err) require.Equal(t, filepath.Join(tempDir, "test"), p) // Test relative parent directories. expected := filepath.Join(tempDir, "appname", "config", "test") p, err = pathutil.Create(filepath.Join("appname", "config", "test"), []string{"\000a", tempDir}) require.NoError(t, err) require.Equal(t, expected, p) require.NoError(t, os.RemoveAll(filepath.Dir(expected))) expected = filepath.Join(tempDir, "appname", "test") p, err = pathutil.Create(filepath.Join("appname", "test"), []string{"\000a", tempDir}) require.NoError(t, err) require.Equal(t, expected, p) require.NoError(t, os.RemoveAll(filepath.Dir(expected))) // Test invalid paths. _, err = pathutil.Create(filepath.Join("appname", "test"), []string{"\000a"}) require.Error(t, err) _, err = pathutil.Create("test", []string{filepath.Join(tempDir, "\000a")}) require.Error(t, err) } func TestSearch(t *testing.T) { tempDir := os.TempDir() // Test file not found. _, err := pathutil.Search("test", []string{tempDir, filepath.Join(tempDir, "appname")}) require.Error(t, err) // Test file found. expected := filepath.Join(tempDir, "test") f, err := os.Create(expected) require.NoError(t, err) require.NoError(t, f.Close()) p, err := pathutil.Search("test", []string{tempDir}) require.NoError(t, err) require.Equal(t, expected, p) p, err = pathutil.Search("test", []string{filepath.Join(tempDir, "appname"), tempDir}) require.NoError(t, err) require.Equal(t, expected, p) require.NoError(t, os.Remove(expected)) // Test relative parent directories. expected = filepath.Join(tempDir, "appname", "test") _, err = pathutil.Create(filepath.Join("appname", "test"), []string{tempDir}) require.NoError(t, err) f, err = os.Create(expected) require.NoError(t, err) require.NoError(t, f.Close()) p, err = pathutil.Search(filepath.Join("appname", "test"), []string{tempDir}) require.NoError(t, err) require.Equal(t, expected, p) p, err = pathutil.Search("test", []string{tempDir, filepath.Join(tempDir, "appname")}) require.NoError(t, err) require.Equal(t, expected, p) require.NoError(t, os.RemoveAll(filepath.Dir(expected))) } xdg-0.4.0/internal/pathutil/pathutil_unix.go000066400000000000000000000014151413623533200211720ustar00rootroot00000000000000//go:build aix || darwin || dragonfly || freebsd || (js && wasm) || nacl || linux || netbsd || openbsd || solaris // +build aix darwin dragonfly freebsd js,wasm nacl linux netbsd openbsd solaris package pathutil import ( "os" "path/filepath" "strings" ) // Exists returns true if the specified path exists. func Exists(path string) bool { _, err := os.Stat(path) return err == nil || os.IsExist(err) } // ExpandHome substitutes `~` and `$HOME` at the start of the specified // `path` using the provided `home` location. func ExpandHome(path, home string) string { if path == "" || home == "" { return path } if path[0] == '~' { return filepath.Join(home, path[1:]) } if strings.HasPrefix(path, "$HOME") { return filepath.Join(home, path[5:]) } return path } xdg-0.4.0/internal/pathutil/pathutil_unix_test.go000066400000000000000000000027001413623533200222270ustar00rootroot00000000000000//go:build aix || darwin || dragonfly || freebsd || (js && wasm) || nacl || linux || netbsd || openbsd || solaris // +build aix darwin dragonfly freebsd js,wasm nacl linux netbsd openbsd solaris package pathutil_test import ( "path/filepath" "testing" "github.com/adrg/xdg/internal/pathutil" "github.com/stretchr/testify/require" ) func TestExpandHome(t *testing.T) { home := "/home/test" require.Equal(t, home, pathutil.ExpandHome("~", home)) require.Equal(t, home, pathutil.ExpandHome("$HOME", home)) require.Equal(t, filepath.Join(home, "appname"), pathutil.ExpandHome("~/appname", home)) require.Equal(t, filepath.Join(home, "appname"), pathutil.ExpandHome("$HOME/appname", home)) require.Equal(t, "", pathutil.ExpandHome("", home)) require.Equal(t, home, pathutil.ExpandHome(home, "")) require.Equal(t, "", pathutil.ExpandHome("", "")) require.Equal(t, home, pathutil.ExpandHome(home, home)) require.Equal(t, "/", pathutil.ExpandHome("~", "/")) require.Equal(t, "/", pathutil.ExpandHome("$HOME", "/")) require.Equal(t, "/usr/bin", pathutil.ExpandHome("~/bin", "/usr")) require.Equal(t, "/usr/bin", pathutil.ExpandHome("$HOME/bin", "/usr")) } func TestUnique(t *testing.T) { input := []string{ "", "/home", "/home/test", "a", "~/appname", "$HOME/appname", "a", "/home", } expected := []string{ "/home", "/home/test", "/home/test/appname", } require.EqualValues(t, expected, pathutil.Unique(input, "/home/test")) } xdg-0.4.0/internal/pathutil/pathutil_windows.go000066400000000000000000000027751413623533200217130ustar00rootroot00000000000000package pathutil import ( "os" "path/filepath" "strings" "golang.org/x/sys/windows" ) // Exists returns true if the specified path exists. func Exists(path string) bool { fi, err := os.Lstat(path) if fi != nil && fi.Mode()&os.ModeSymlink != 0 { _, err = filepath.EvalSymlinks(path) } return err == nil || os.IsExist(err) } // ExpandHome substitutes `%USERPROFILE%` at the start of the specified // `path` using the provided `home` location. func ExpandHome(path, home string) string { if path == "" || home == "" { return path } if strings.HasPrefix(path, `%USERPROFILE%`) { return filepath.Join(home, path[13:]) } return path } // KnownFolder returns the location of the folder with the specified ID. // If that fails, the folder location is determined by reading the provided // environment variables (the first non-empty read value is returned). // If that fails as well, the first non-empty fallback is returned. // If all of the above fails, the function returns an empty string. func KnownFolder(id *windows.KNOWNFOLDERID, envVars []string, fallbacks []string) string { if id != nil { flags := []uint32{windows.KF_FLAG_DEFAULT, windows.KF_FLAG_DEFAULT_PATH} for _, flag := range flags { p, _ := windows.KnownFolderPath(id, flag|windows.KF_FLAG_DONT_VERIFY) if p != "" { return p } } } for _, envVar := range envVars { p := os.Getenv(envVar) if p != "" { return p } } for _, fallback := range fallbacks { if fallback != "" { return fallback } } return "" } xdg-0.4.0/internal/pathutil/pathutil_windows_test.go000066400000000000000000000025541413623533200227450ustar00rootroot00000000000000//go:build windows // +build windows package pathutil_test import ( "path/filepath" "testing" "github.com/adrg/xdg/internal/pathutil" "github.com/stretchr/testify/require" "golang.org/x/sys/windows" ) func TestKnownFolder(t *testing.T) { expected := `C:\ProgramData` require.Equal(t, expected, pathutil.KnownFolder(windows.FOLDERID_ProgramData, nil, nil)) require.Equal(t, expected, pathutil.KnownFolder(nil, []string{"ProgramData"}, nil)) require.Equal(t, expected, pathutil.KnownFolder(nil, nil, []string{expected})) require.Equal(t, "", pathutil.KnownFolder(nil, nil, nil)) } func TestExpandHome(t *testing.T) { home := `C:\Users\test` require.Equal(t, home, pathutil.ExpandHome(`%USERPROFILE%`, home)) require.Equal(t, filepath.Join(home, "appname"), pathutil.ExpandHome(`%USERPROFILE%\appname`, home)) require.Equal(t, "", pathutil.ExpandHome("", home)) require.Equal(t, home, pathutil.ExpandHome(home, "")) require.Equal(t, "", pathutil.ExpandHome("", "")) require.Equal(t, home, pathutil.ExpandHome(home, home)) } func TestUnique(t *testing.T) { input := []string{ "", `C:\Users`, `C:\Users\test`, "a", `C:\Users\test\appname`, `%USERPROFILE%/appname`, "a", `C:\Users`, } expected := []string{ `C:\Users`, `C:\Users\test`, `C:\Users\test\appname`, } require.EqualValues(t, expected, pathutil.Unique(input, `C:\Users\test`)) } xdg-0.4.0/paths_darwin.go000066400000000000000000000034531413623533200153160ustar00rootroot00000000000000package xdg import ( "os" "path/filepath" ) func homeDir() string { if home := os.Getenv("HOME"); home != "" { return home } return "/" } func initDirs(home string) { initBaseDirs(home) initUserDirs(home) } func initBaseDirs(home string) { homeAppSupport := filepath.Join(home, "Library", "Application Support") rootAppSupport := "/Library/Application Support" // Initialize standard directories. baseDirs.dataHome = xdgPath(envDataHome, homeAppSupport) baseDirs.data = xdgPaths(envDataDirs, rootAppSupport) baseDirs.configHome = xdgPath(envConfigHome, homeAppSupport) baseDirs.config = xdgPaths(envConfigDirs, filepath.Join(home, "Library", "Preferences"), rootAppSupport, "/Library/Preferences", ) baseDirs.stateHome = xdgPath(envStateHome, homeAppSupport) baseDirs.cacheHome = xdgPath(envCacheHome, filepath.Join(home, "Library", "Caches")) baseDirs.runtime = xdgPath(envRuntimeDir, homeAppSupport) // Initialize non-standard directories. baseDirs.applications = []string{ "/Applications", } baseDirs.fonts = []string{ filepath.Join(home, "Library/Fonts"), "/Library/Fonts", "/System/Library/Fonts", "/Network/Library/Fonts", } } func initUserDirs(home string) { UserDirs.Desktop = xdgPath(envDesktopDir, filepath.Join(home, "Desktop")) UserDirs.Download = xdgPath(envDownloadDir, filepath.Join(home, "Downloads")) UserDirs.Documents = xdgPath(envDocumentsDir, filepath.Join(home, "Documents")) UserDirs.Music = xdgPath(envMusicDir, filepath.Join(home, "Music")) UserDirs.Pictures = xdgPath(envPicturesDir, filepath.Join(home, "Pictures")) UserDirs.Videos = xdgPath(envVideosDir, filepath.Join(home, "Movies")) UserDirs.Templates = xdgPath(envTemplatesDir, filepath.Join(home, "Templates")) UserDirs.PublicShare = xdgPath(envPublicShareDir, filepath.Join(home, "Public")) } xdg-0.4.0/paths_darwin_test.go000066400000000000000000000134501413623533200163530ustar00rootroot00000000000000//go:build darwin // +build darwin package xdg_test import ( "os" "path/filepath" "testing" "github.com/adrg/xdg" "github.com/stretchr/testify/require" ) func TestDefaultBaseDirs(t *testing.T) { home := xdg.Home homeAppSupport := filepath.Join(home, "Library", "Application Support") rootAppSupport := "/Library/Application Support" testDirs(t, &envSample{ name: "XDG_DATA_HOME", expected: homeAppSupport, actual: &xdg.DataHome, }, &envSample{ name: "XDG_DATA_DIRS", expected: []string{rootAppSupport}, actual: &xdg.DataDirs, }, &envSample{ name: "XDG_CONFIG_HOME", expected: homeAppSupport, actual: &xdg.ConfigHome, }, &envSample{ name: "XDG_CONFIG_DIRS", expected: []string{ filepath.Join(home, "Library", "Preferences"), rootAppSupport, "/Library/Preferences", }, actual: &xdg.ConfigDirs, }, &envSample{ name: "XDG_STATE_HOME", expected: homeAppSupport, actual: &xdg.StateHome, }, &envSample{ name: "XDG_CACHE_HOME", expected: filepath.Join(home, "Library", "Caches"), actual: &xdg.CacheHome, }, &envSample{ name: "XDG_RUNTIME_DIR", expected: homeAppSupport, actual: &xdg.RuntimeDir, }, &envSample{ name: "XDG_APPLICATION_DIRS", expected: []string{ "/Applications", }, actual: &xdg.ApplicationDirs, }, &envSample{ name: "XDG_FONT_DIRS", expected: []string{ filepath.Join(home, "Library/Fonts"), "/Library/Fonts", "/System/Library/Fonts", "/Network/Library/Fonts", }, actual: &xdg.FontDirs, }, ) } func TestCustomBaseDirs(t *testing.T) { home := xdg.Home testDirs(t, &envSample{ name: "XDG_DATA_HOME", value: "~/Library/data", expected: filepath.Join(home, "Library/data"), actual: &xdg.DataHome, }, &envSample{ name: "XDG_DATA_DIRS", value: "~/Library/data:/Library/Application Support", expected: []string{filepath.Join(home, "Library/data"), "/Library/Application Support"}, actual: &xdg.DataDirs, }, &envSample{ name: "XDG_CONFIG_HOME", value: "~/Library/config", expected: filepath.Join(home, "Library/config"), actual: &xdg.ConfigHome, }, &envSample{ name: "XDG_CONFIG_DIRS", value: "~/Library/config:/Library/Preferences", expected: []string{filepath.Join(home, "Library/config"), "/Library/Preferences"}, actual: &xdg.ConfigDirs, }, &envSample{ name: "XDG_STATE_HOME", value: "~/Library/state", expected: filepath.Join(home, "Library/state"), actual: &xdg.StateHome, }, &envSample{ name: "XDG_CACHE_HOME", value: "~/Library/cache", expected: filepath.Join(home, "Library/cache"), actual: &xdg.CacheHome, }, &envSample{ name: "XDG_RUNTIME_DIR", value: "~/Library/runtime", expected: filepath.Join(home, "Library/runtime"), actual: &xdg.RuntimeDir, }, ) } func TestDefaultUserDirs(t *testing.T) { home := xdg.Home testDirs(t, &envSample{ name: "XDG_DESKTOP_DIR", expected: filepath.Join(home, "Desktop"), actual: &xdg.UserDirs.Desktop, }, &envSample{ name: "XDG_DOWNLOAD_DIR", expected: filepath.Join(home, "Downloads"), actual: &xdg.UserDirs.Download, }, &envSample{ name: "XDG_DOCUMENTS_DIR", expected: filepath.Join(home, "Documents"), actual: &xdg.UserDirs.Documents, }, &envSample{ name: "XDG_MUSIC_DIR", expected: filepath.Join(home, "Music"), actual: &xdg.UserDirs.Music, }, &envSample{ name: "XDG_PICTURES_DIR", expected: filepath.Join(home, "Pictures"), actual: &xdg.UserDirs.Pictures, }, &envSample{ name: "XDG_VIDEOS_DIR", expected: filepath.Join(home, "Movies"), actual: &xdg.UserDirs.Videos, }, &envSample{ name: "XDG_TEMPLATES_DIR", expected: filepath.Join(home, "Templates"), actual: &xdg.UserDirs.Templates, }, &envSample{ name: "XDG_PUBLICSHARE_DIR", expected: filepath.Join(home, "Public"), actual: &xdg.UserDirs.PublicShare, }, ) } func TestCustomUserDirs(t *testing.T) { home := xdg.Home testDirs(t, &envSample{ name: "XDG_DESKTOP_DIR", value: "$HOME/Library/Desktop", expected: filepath.Join(home, "Library/Desktop"), actual: &xdg.UserDirs.Desktop, }, &envSample{ name: "XDG_DOWNLOAD_DIR", value: "$HOME/Library/Downloads", expected: filepath.Join(home, "Library/Downloads"), actual: &xdg.UserDirs.Download, }, &envSample{ name: "XDG_DOCUMENTS_DIR", value: "$HOME/Library/Documents", expected: filepath.Join(home, "Library/Documents"), actual: &xdg.UserDirs.Documents, }, &envSample{ name: "XDG_MUSIC_DIR", value: "$HOME/Library/Music", expected: filepath.Join(home, "Library/Music"), actual: &xdg.UserDirs.Music, }, &envSample{ name: "XDG_PICTURES_DIR", value: "$HOME/Library/Pictures", expected: filepath.Join(home, "Library/Pictures"), actual: &xdg.UserDirs.Pictures, }, &envSample{ name: "XDG_VIDEOS_DIR", value: "$HOME/Library/Movies", expected: filepath.Join(home, "Library/Movies"), actual: &xdg.UserDirs.Videos, }, &envSample{ name: "XDG_TEMPLATES_DIR", value: "$HOME/Library/Templates", expected: filepath.Join(home, "Library/Templates"), actual: &xdg.UserDirs.Templates, }, &envSample{ name: "XDG_PUBLICSHARE_DIR", value: "$HOME/Library/Public", expected: filepath.Join(home, "Library/Public"), actual: &xdg.UserDirs.PublicShare, }, ) } func TestHomeNotSet(t *testing.T) { envHomeVar := "HOME" envHomeVal := os.Getenv(envHomeVar) require.NoError(t, os.Unsetenv(envHomeVar)) xdg.Reload() require.Equal(t, "/", xdg.Home) require.NoError(t, os.Setenv(envHomeVar, envHomeVal)) xdg.Reload() require.Equal(t, envHomeVal, xdg.Home) } xdg-0.4.0/paths_plan9.go000066400000000000000000000031541413623533200150530ustar00rootroot00000000000000package xdg import ( "os" "path/filepath" ) func homeDir() string { if home := os.Getenv("home"); home != "" { return home } return "/" } func initDirs(home string) { initBaseDirs(home) initUserDirs(home) } func initBaseDirs(home string) { homeLibDir := filepath.Join(home, "lib") rootLibDir := "/lib" // Initialize standard directories. baseDirs.dataHome = xdgPath(envDataHome, homeLibDir) baseDirs.data = xdgPaths(envDataDirs, rootLibDir) baseDirs.configHome = xdgPath(envConfigHome, homeLibDir) baseDirs.config = xdgPaths(envConfigDirs, rootLibDir) baseDirs.stateHome = xdgPath(envStateHome, filepath.Join(homeLibDir, "state")) baseDirs.cacheHome = xdgPath(envCacheHome, filepath.Join(homeLibDir, "cache")) baseDirs.runtime = xdgPath(envRuntimeDir, "/tmp") // Initialize non-standard directories. baseDirs.applications = []string{ filepath.Join(home, "bin"), "/bin", } baseDirs.fonts = []string{ filepath.Join(homeLibDir, "font"), "/lib/font", } } func initUserDirs(home string) { UserDirs.Desktop = xdgPath(envDesktopDir, filepath.Join(home, "desktop")) UserDirs.Download = xdgPath(envDownloadDir, filepath.Join(home, "downloads")) UserDirs.Documents = xdgPath(envDocumentsDir, filepath.Join(home, "documents")) UserDirs.Music = xdgPath(envMusicDir, filepath.Join(home, "music")) UserDirs.Pictures = xdgPath(envPicturesDir, filepath.Join(home, "pictures")) UserDirs.Videos = xdgPath(envVideosDir, filepath.Join(home, "videos")) UserDirs.Templates = xdgPath(envTemplatesDir, filepath.Join(home, "templates")) UserDirs.PublicShare = xdgPath(envPublicShareDir, filepath.Join(home, "public")) } xdg-0.4.0/paths_plan9_test.go000066400000000000000000000127001413623533200161070ustar00rootroot00000000000000//go:build plan9 // +build plan9 package xdg_test import ( "os" "path/filepath" "testing" "github.com/adrg/xdg" "github.com/stretchr/testify/require" ) func TestDefaultBaseDirs(t *testing.T) { home := xdg.Home testDirs(t, &envSample{ name: "XDG_DATA_HOME", expected: filepath.Join(home, "lib"), actual: &xdg.DataHome, }, &envSample{ name: "XDG_DATA_DIRS", expected: []string{"/lib"}, actual: &xdg.DataDirs, }, &envSample{ name: "XDG_CONFIG_HOME", expected: filepath.Join(home, "lib"), actual: &xdg.ConfigHome, }, &envSample{ name: "XDG_CONFIG_DIRS", expected: []string{"/lib"}, actual: &xdg.ConfigDirs, }, &envSample{ name: "XDG_STATE_HOME", expected: filepath.Join(home, "lib", "state"), actual: &xdg.StateHome, }, &envSample{ name: "XDG_CACHE_HOME", expected: filepath.Join(home, "lib", "cache"), actual: &xdg.CacheHome, }, &envSample{ name: "XDG_RUNTIME_DIR", expected: "/tmp", actual: &xdg.RuntimeDir, }, &envSample{ name: "XDG_APPLICATION_DIRS", expected: []string{ filepath.Join(home, "bin"), "/bin", }, actual: &xdg.ApplicationDirs, }, &envSample{ name: "XDG_FONT_DIRS", expected: []string{ filepath.Join(home, "lib", "font"), "/lib/font", }, actual: &xdg.FontDirs, }, ) } func TestCustomBaseDirs(t *testing.T) { homeLib := filepath.Join(xdg.Home, "lib") testDirs(t, &envSample{ name: "XDG_DATA_HOME", value: filepath.Join(homeLib, "data"), expected: filepath.Join(homeLib, "data"), actual: &xdg.DataHome, }, &envSample{ name: "XDG_DATA_DIRS", value: "/lib/data", expected: []string{"/lib/data"}, actual: &xdg.DataDirs, }, &envSample{ name: "XDG_CONFIG_HOME", value: filepath.Join(homeLib, "config"), expected: filepath.Join(homeLib, "config"), actual: &xdg.ConfigHome, }, &envSample{ name: "XDG_CONFIG_DIRS", value: "/lib/config", expected: []string{"/lib/config"}, actual: &xdg.ConfigDirs, }, &envSample{ name: "XDG_STATE_HOME", value: homeLib, expected: homeLib, actual: &xdg.StateHome, }, &envSample{ name: "XDG_CACHE_HOME", value: homeLib, expected: homeLib, actual: &xdg.CacheHome, }, &envSample{ name: "XDG_RUNTIME_DIR", value: filepath.Join(homeLib, "runtime"), expected: filepath.Join(homeLib, "runtime"), actual: &xdg.RuntimeDir, }, ) } func TestDefaultUserDirs(t *testing.T) { home := xdg.Home testDirs(t, &envSample{ name: "XDG_DESKTOP_DIR", expected: filepath.Join(home, "desktop"), actual: &xdg.UserDirs.Desktop, }, &envSample{ name: "XDG_DOWNLOAD_DIR", expected: filepath.Join(home, "downloads"), actual: &xdg.UserDirs.Download, }, &envSample{ name: "XDG_DOCUMENTS_DIR", expected: filepath.Join(home, "documents"), actual: &xdg.UserDirs.Documents, }, &envSample{ name: "XDG_MUSIC_DIR", expected: filepath.Join(home, "music"), actual: &xdg.UserDirs.Music, }, &envSample{ name: "XDG_PICTURES_DIR", expected: filepath.Join(home, "pictures"), actual: &xdg.UserDirs.Pictures, }, &envSample{ name: "XDG_VIDEOS_DIR", expected: filepath.Join(home, "videos"), actual: &xdg.UserDirs.Videos, }, &envSample{ name: "XDG_TEMPLATES_DIR", expected: filepath.Join(home, "templates"), actual: &xdg.UserDirs.Templates, }, &envSample{ name: "XDG_PUBLICSHARE_DIR", expected: filepath.Join(home, "public"), actual: &xdg.UserDirs.PublicShare, }, ) } func TestCustomUserDirs(t *testing.T) { homeLib := filepath.Join(xdg.Home, "lib") testDirs(t, &envSample{ name: "XDG_DESKTOP_DIR", value: filepath.Join(homeLib, "desktop"), expected: filepath.Join(homeLib, "desktop"), actual: &xdg.UserDirs.Desktop, }, &envSample{ name: "XDG_DOWNLOAD_DIR", value: filepath.Join(homeLib, "downloads"), expected: filepath.Join(homeLib, "downloads"), actual: &xdg.UserDirs.Download, }, &envSample{ name: "XDG_DOCUMENTS_DIR", value: filepath.Join(homeLib, "documents"), expected: filepath.Join(homeLib, "documents"), actual: &xdg.UserDirs.Documents, }, &envSample{ name: "XDG_MUSIC_DIR", value: filepath.Join(homeLib, "music"), expected: filepath.Join(homeLib, "music"), actual: &xdg.UserDirs.Music, }, &envSample{ name: "XDG_PICTURES_DIR", value: filepath.Join(homeLib, "pictures"), expected: filepath.Join(homeLib, "pictures"), actual: &xdg.UserDirs.Pictures, }, &envSample{ name: "XDG_VIDEOS_DIR", value: filepath.Join(homeLib, "videos"), expected: filepath.Join(homeLib, "videos"), actual: &xdg.UserDirs.Videos, }, &envSample{ name: "XDG_TEMPLATES_DIR", value: filepath.Join(homeLib, "templates"), expected: filepath.Join(homeLib, "templates"), actual: &xdg.UserDirs.Templates, }, &envSample{ name: "XDG_PUBLICSHARE_DIR", value: filepath.Join(homeLib, "public"), expected: filepath.Join(homeLib, "public"), actual: &xdg.UserDirs.PublicShare, }, ) } func TestHomeNotSet(t *testing.T) { envHomeVar := "home" envHomeVal := os.Getenv(envHomeVar) require.NoError(t, os.Unsetenv(envHomeVar)) xdg.Reload() require.Equal(t, "/", xdg.Home) require.NoError(t, os.Setenv(envHomeVar, envHomeVal)) xdg.Reload() require.Equal(t, envHomeVal, xdg.Home) } xdg-0.4.0/paths_unix.go000066400000000000000000000045751413623533200150230ustar00rootroot00000000000000//go:build aix || dragonfly || freebsd || (js && wasm) || nacl || linux || netbsd || openbsd || solaris // +build aix dragonfly freebsd js,wasm nacl linux netbsd openbsd solaris package xdg import ( "os" "path/filepath" "strconv" "github.com/adrg/xdg/internal/pathutil" ) func homeDir() string { if home := os.Getenv("HOME"); home != "" { return home } return "/" } func initDirs(home string) { initBaseDirs(home) initUserDirs(home) } func initBaseDirs(home string) { // Initialize standard directories. baseDirs.dataHome = xdgPath(envDataHome, filepath.Join(home, ".local", "share")) baseDirs.data = xdgPaths(envDataDirs, "/usr/local/share", "/usr/share") baseDirs.configHome = xdgPath(envConfigHome, filepath.Join(home, ".config")) baseDirs.config = xdgPaths(envConfigDirs, "/etc/xdg") baseDirs.stateHome = xdgPath(envStateHome, filepath.Join(home, ".local", "state")) baseDirs.cacheHome = xdgPath(envCacheHome, filepath.Join(home, ".cache")) baseDirs.runtime = xdgPath(envRuntimeDir, filepath.Join("/run/user", strconv.Itoa(os.Getuid()))) // Initialize non-standard directories. appDirs := []string{ filepath.Join(baseDirs.dataHome, "applications"), filepath.Join(home, ".local/share/applications"), "/usr/local/share/applications", "/usr/share/applications", } fontDirs := []string{ filepath.Join(baseDirs.dataHome, "fonts"), filepath.Join(home, ".fonts"), filepath.Join(home, ".local/share/fonts"), "/usr/local/share/fonts", "/usr/share/fonts", } for _, dir := range baseDirs.data { appDirs = append(appDirs, filepath.Join(dir, "applications")) fontDirs = append(fontDirs, filepath.Join(dir, "fonts")) } baseDirs.applications = pathutil.Unique(appDirs, Home) baseDirs.fonts = pathutil.Unique(fontDirs, Home) } func initUserDirs(home string) { UserDirs.Desktop = xdgPath(envDesktopDir, filepath.Join(home, "Desktop")) UserDirs.Download = xdgPath(envDownloadDir, filepath.Join(home, "Downloads")) UserDirs.Documents = xdgPath(envDocumentsDir, filepath.Join(home, "Documents")) UserDirs.Music = xdgPath(envMusicDir, filepath.Join(home, "Music")) UserDirs.Pictures = xdgPath(envPicturesDir, filepath.Join(home, "Pictures")) UserDirs.Videos = xdgPath(envVideosDir, filepath.Join(home, "Videos")) UserDirs.Templates = xdgPath(envTemplatesDir, filepath.Join(home, "Templates")) UserDirs.PublicShare = xdgPath(envPublicShareDir, filepath.Join(home, "Public")) } xdg-0.4.0/paths_unix_test.go000066400000000000000000000135571413623533200160620ustar00rootroot00000000000000//go:build aix || dragonfly || freebsd || (js && wasm) || nacl || linux || netbsd || openbsd || solaris // +build aix dragonfly freebsd js,wasm nacl linux netbsd openbsd solaris package xdg_test import ( "os" "path/filepath" "strconv" "testing" "github.com/adrg/xdg" "github.com/stretchr/testify/require" ) func TestDefaultBaseDirs(t *testing.T) { home := xdg.Home testDirs(t, &envSample{ name: "XDG_DATA_HOME", expected: filepath.Join(home, ".local/share"), actual: &xdg.DataHome, }, &envSample{ name: "XDG_DATA_DIRS", expected: []string{"/usr/local/share", "/usr/share"}, actual: &xdg.DataDirs, }, &envSample{ name: "XDG_CONFIG_HOME", expected: filepath.Join(home, ".config"), actual: &xdg.ConfigHome, }, &envSample{ name: "XDG_CONFIG_DIRS", expected: []string{"/etc/xdg"}, actual: &xdg.ConfigDirs, }, &envSample{ name: "XDG_STATE_HOME", expected: filepath.Join(home, ".local", "state"), actual: &xdg.StateHome, }, &envSample{ name: "XDG_CACHE_HOME", expected: filepath.Join(home, ".cache"), actual: &xdg.CacheHome, }, &envSample{ name: "XDG_RUNTIME_DIR", expected: filepath.Join("/run/user", strconv.Itoa(os.Getuid())), actual: &xdg.RuntimeDir, }, &envSample{ name: "XDG_APPLICATION_DIRS", expected: []string{ filepath.Join(home, ".local/share/applications"), "/usr/local/share/applications", "/usr/share/applications", }, actual: &xdg.ApplicationDirs, }, &envSample{ name: "XDG_FONT_DIRS", expected: []string{ filepath.Join(home, ".local/share/fonts"), filepath.Join(home, ".fonts"), "/usr/local/share/fonts", "/usr/share/fonts", }, actual: &xdg.FontDirs, }, ) } func TestCustomBaseDirs(t *testing.T) { home := xdg.Home testDirs(t, &envSample{ name: "XDG_DATA_HOME", value: "~/.local/data", expected: filepath.Join(home, ".local/data"), actual: &xdg.DataHome, }, &envSample{ name: "XDG_DATA_DIRS", value: "~/.local/data:/usr/share", expected: []string{filepath.Join(home, ".local/data"), "/usr/share"}, actual: &xdg.DataDirs, }, &envSample{ name: "XDG_CONFIG_HOME", value: "~/.local/config", expected: filepath.Join(home, ".local/config"), actual: &xdg.ConfigHome, }, &envSample{ name: "XDG_CONFIG_DIRS", value: "~/.local/config:/etc/xdg", expected: []string{filepath.Join(home, ".local/config"), "/etc/xdg"}, actual: &xdg.ConfigDirs, }, &envSample{ name: "XDG_STATE_HOME", value: "~/.local/var", expected: filepath.Join(home, ".local/var"), actual: &xdg.StateHome, }, &envSample{ name: "XDG_CACHE_HOME", value: "~/.local/cache", expected: filepath.Join(home, ".local/cache"), actual: &xdg.CacheHome, }, &envSample{ name: "XDG_RUNTIME_DIR", value: "~/.local/runtime", expected: filepath.Join(home, ".local/runtime"), actual: &xdg.RuntimeDir, }, ) } func TestDefaultUserDirs(t *testing.T) { home := xdg.Home testDirs(t, &envSample{ name: "XDG_DESKTOP_DIR", expected: filepath.Join(home, "Desktop"), actual: &xdg.UserDirs.Desktop, }, &envSample{ name: "XDG_DOWNLOAD_DIR", expected: filepath.Join(home, "Downloads"), actual: &xdg.UserDirs.Download, }, &envSample{ name: "XDG_DOCUMENTS_DIR", expected: filepath.Join(home, "Documents"), actual: &xdg.UserDirs.Documents, }, &envSample{ name: "XDG_MUSIC_DIR", expected: filepath.Join(home, "Music"), actual: &xdg.UserDirs.Music, }, &envSample{ name: "XDG_PICTURES_DIR", expected: filepath.Join(home, "Pictures"), actual: &xdg.UserDirs.Pictures, }, &envSample{ name: "XDG_VIDEOS_DIR", expected: filepath.Join(home, "Videos"), actual: &xdg.UserDirs.Videos, }, &envSample{ name: "XDG_TEMPLATES_DIR", expected: filepath.Join(home, "Templates"), actual: &xdg.UserDirs.Templates, }, &envSample{ name: "XDG_PUBLICSHARE_DIR", expected: filepath.Join(home, "Public"), actual: &xdg.UserDirs.PublicShare, }, ) } func TestCustomUserDirs(t *testing.T) { home := xdg.Home testDirs(t, &envSample{ name: "XDG_DESKTOP_DIR", value: "$HOME/.local/Desktop", expected: filepath.Join(home, ".local/Desktop"), actual: &xdg.UserDirs.Desktop, }, &envSample{ name: "XDG_DOWNLOAD_DIR", value: "$HOME/.local/Downloads", expected: filepath.Join(home, ".local/Downloads"), actual: &xdg.UserDirs.Download, }, &envSample{ name: "XDG_DOCUMENTS_DIR", value: "$HOME/.local/Documents", expected: filepath.Join(home, ".local/Documents"), actual: &xdg.UserDirs.Documents, }, &envSample{ name: "XDG_MUSIC_DIR", value: "$HOME/.local/Music", expected: filepath.Join(home, ".local/Music"), actual: &xdg.UserDirs.Music, }, &envSample{ name: "XDG_PICTURES_DIR", value: "$HOME/.local/Pictures", expected: filepath.Join(home, ".local/Pictures"), actual: &xdg.UserDirs.Pictures, }, &envSample{ name: "XDG_VIDEOS_DIR", value: "$HOME/.local/Videos", expected: filepath.Join(home, ".local/Videos"), actual: &xdg.UserDirs.Videos, }, &envSample{ name: "XDG_TEMPLATES_DIR", value: "$HOME/.local/Templates", expected: filepath.Join(home, ".local/Templates"), actual: &xdg.UserDirs.Templates, }, &envSample{ name: "XDG_PUBLICSHARE_DIR", value: "$HOME/.local/Public", expected: filepath.Join(home, ".local/Public"), actual: &xdg.UserDirs.PublicShare, }, ) } func TestHomeNotSet(t *testing.T) { envHomeVar := "HOME" envHomeVal := os.Getenv(envHomeVar) require.NoError(t, os.Unsetenv(envHomeVar)) xdg.Reload() require.Equal(t, "/", xdg.Home) require.NoError(t, os.Setenv(envHomeVar, envHomeVal)) xdg.Reload() require.Equal(t, envHomeVal, xdg.Home) } xdg-0.4.0/paths_windows.go000066400000000000000000000111151413623533200155160ustar00rootroot00000000000000package xdg import ( "path/filepath" "github.com/adrg/xdg/internal/pathutil" "golang.org/x/sys/windows" ) func homeDir() string { return pathutil.KnownFolder( windows.FOLDERID_Profile, []string{"USERPROFILE"}, nil, ) } func initDirs(home string) { kf := initKnownFolders(home) initBaseDirs(home, kf) initUserDirs(home, kf) } func initBaseDirs(home string, kf *knownFolders) { // Initialize standard directories. baseDirs.dataHome = xdgPath(envDataHome, kf.localAppData) baseDirs.data = xdgPaths(envDataDirs, kf.roamingAppData, kf.programData) baseDirs.configHome = xdgPath(envConfigHome, kf.localAppData) baseDirs.config = xdgPaths(envConfigDirs, kf.programData, kf.roamingAppData) baseDirs.stateHome = xdgPath(envStateHome, kf.localAppData) baseDirs.cacheHome = xdgPath(envCacheHome, filepath.Join(kf.localAppData, "cache")) baseDirs.runtime = xdgPath(envRuntimeDir, kf.localAppData) // Initialize non-standard directories. baseDirs.applications = []string{ kf.programs, kf.commonPrograms, } baseDirs.fonts = []string{ kf.fonts, filepath.Join(kf.localAppData, "Microsoft", "Windows", "Fonts"), } } func initUserDirs(home string, kf *knownFolders) { UserDirs.Desktop = xdgPath(envDesktopDir, kf.desktop) UserDirs.Download = xdgPath(envDownloadDir, kf.downloads) UserDirs.Documents = xdgPath(envDocumentsDir, kf.documents) UserDirs.Music = xdgPath(envMusicDir, kf.music) UserDirs.Pictures = xdgPath(envPicturesDir, kf.pictures) UserDirs.Videos = xdgPath(envVideosDir, kf.videos) UserDirs.Templates = xdgPath(envTemplatesDir, kf.templates) UserDirs.PublicShare = xdgPath(envPublicShareDir, kf.public) } type knownFolders struct { systemDrive string systemRoot string programData string userProfile string userProfiles string roamingAppData string localAppData string desktop string downloads string documents string music string pictures string videos string templates string public string fonts string programs string commonPrograms string } func initKnownFolders(home string) *knownFolders { kf := &knownFolders{ userProfile: home, } kf.systemDrive = filepath.VolumeName(pathutil.KnownFolder( windows.FOLDERID_Windows, []string{"SystemDrive", "SystemRoot", "windir"}, []string{home, `C:`}, )) + string(filepath.Separator) kf.systemRoot = pathutil.KnownFolder( windows.FOLDERID_Windows, []string{"SystemRoot", "windir"}, []string{filepath.Join(kf.systemDrive, "Windows")}, ) kf.programData = pathutil.KnownFolder( windows.FOLDERID_ProgramData, []string{"ProgramData", "ALLUSERSPROFILE"}, []string{filepath.Join(kf.systemDrive, "ProgramData")}, ) kf.userProfiles = pathutil.KnownFolder( windows.FOLDERID_UserProfiles, nil, []string{filepath.Join(kf.systemDrive, "Users")}, ) kf.roamingAppData = pathutil.KnownFolder( windows.FOLDERID_RoamingAppData, []string{"APPDATA"}, []string{filepath.Join(home, "AppData", "Roaming")}, ) kf.localAppData = pathutil.KnownFolder( windows.FOLDERID_LocalAppData, []string{"LOCALAPPDATA"}, []string{filepath.Join(home, "AppData", "Local")}, ) kf.desktop = pathutil.KnownFolder( windows.FOLDERID_Desktop, nil, []string{filepath.Join(home, "Desktop")}, ) kf.downloads = pathutil.KnownFolder( windows.FOLDERID_Downloads, nil, []string{filepath.Join(home, "Downloads")}, ) kf.documents = pathutil.KnownFolder( windows.FOLDERID_Documents, nil, []string{filepath.Join(home, "Documents")}, ) kf.music = pathutil.KnownFolder( windows.FOLDERID_Music, nil, []string{filepath.Join(home, "Music")}, ) kf.pictures = pathutil.KnownFolder( windows.FOLDERID_Pictures, nil, []string{filepath.Join(home, "Pictures")}, ) kf.videos = pathutil.KnownFolder( windows.FOLDERID_Videos, nil, []string{filepath.Join(home, "Videos")}, ) kf.templates = pathutil.KnownFolder( windows.FOLDERID_Templates, nil, []string{filepath.Join(kf.roamingAppData, "Microsoft", "Windows", "Templates")}, ) kf.public = pathutil.KnownFolder( windows.FOLDERID_Public, []string{"PUBLIC"}, []string{filepath.Join(kf.userProfiles, "Public")}, ) kf.fonts = pathutil.KnownFolder( windows.FOLDERID_Fonts, nil, []string{filepath.Join(kf.systemRoot, "Fonts")}, ) kf.programs = pathutil.KnownFolder( windows.FOLDERID_Programs, nil, []string{filepath.Join(kf.roamingAppData, "Microsoft", "Windows", "Start Menu", "Programs")}, ) kf.commonPrograms = pathutil.KnownFolder( windows.FOLDERID_CommonPrograms, nil, []string{filepath.Join(kf.programData, "Microsoft", "Windows", "Start Menu", "Programs")}, ) return kf } xdg-0.4.0/paths_windows_test.go000066400000000000000000000157441413623533200165710ustar00rootroot00000000000000//go:build windows // +build windows package xdg_test import ( "fmt" "os" "path/filepath" "testing" "github.com/adrg/xdg" "github.com/stretchr/testify/require" ) func TestDefaultBaseDirs(t *testing.T) { home := xdg.Home systemDrive := `C:\` roamingAppData := filepath.Join(home, "AppData", "Roaming") localAppData := filepath.Join(home, "AppData", "Local") systemRoot := filepath.Join(systemDrive, "Windows") programData := filepath.Join(systemDrive, "ProgramData") envSamples := []*envSample{ { name: "XDG_DATA_HOME", expected: localAppData, actual: &xdg.DataHome, }, { name: "XDG_DATA_DIRS", expected: []string{roamingAppData, programData}, actual: &xdg.DataDirs, }, { name: "XDG_CONFIG_HOME", expected: localAppData, actual: &xdg.ConfigHome, }, { name: "XDG_CONFIG_DIRS", expected: []string{programData, roamingAppData}, actual: &xdg.ConfigDirs, }, { name: "XDG_STATE_HOME", expected: localAppData, actual: &xdg.StateHome, }, { name: "XDG_CACHE_HOME", expected: filepath.Join(localAppData, "cache"), actual: &xdg.CacheHome, }, { name: "XDG_RUNTIME_DIR", expected: localAppData, actual: &xdg.RuntimeDir, }, { name: "XDG_APPLICATION_DIRS", expected: []string{ filepath.Join(roamingAppData, "Microsoft", "Windows", "Start Menu", "Programs"), filepath.Join(programData, "Microsoft", "Windows", "Start Menu", "Programs"), }, actual: &xdg.ApplicationDirs, }, { name: "XDG_FONT_DIRS", expected: []string{ filepath.Join(systemRoot, "Fonts"), filepath.Join(localAppData, "Microsoft", "Windows", "Fonts"), }, actual: &xdg.FontDirs, }, } // Test default environment. testDirs(t, envSamples...) // Test system drive not set. envSystemDrive := os.Getenv("SystemDrive") require.NoError(t, os.Unsetenv("SystemDrive")) testDirs(t, envSamples...) require.NoError(t, os.Setenv("SystemDrive", envSystemDrive)) } func TestCustomBaseDirs(t *testing.T) { home := xdg.Home roamingAppData := filepath.Join(home, "Custom", "Appdata", "Roaming") localAppData := filepath.Join(home, "Custom", "AppData", "Local") programData := filepath.Join(home, "Custom", "ProgramData") envRoamingAppData := os.Getenv("APPDATA") require.NoError(t, os.Setenv("APPDATA", roamingAppData)) envLocalAppData := os.Getenv("LOCALAPPDATA") require.NoError(t, os.Setenv("LOCALAPPDATA", localAppData)) envProgramData := os.Getenv("ProgramData") require.NoError(t, os.Setenv("ProgramData", programData)) testDirs(t, &envSample{ name: "XDG_DATA_HOME", value: filepath.Join(localAppData, "Data"), expected: filepath.Join(localAppData, "Data"), actual: &xdg.DataHome, }, &envSample{ name: "XDG_DATA_DIRS", value: fmt.Sprintf("%s;%s", filepath.Join(localAppData, "Data"), filepath.Join(roamingAppData, "Data")), expected: []string{filepath.Join(localAppData, "Data"), filepath.Join(roamingAppData, "Data")}, actual: &xdg.DataDirs, }, &envSample{ name: "XDG_CONFIG_HOME", value: filepath.Join(localAppData, "Config"), expected: filepath.Join(localAppData, "Config"), actual: &xdg.ConfigHome, }, &envSample{ name: "XDG_CONFIG_DIRS", value: fmt.Sprintf("%s;%s", filepath.Join(localAppData, "Config"), filepath.Join(roamingAppData, "Config")), expected: []string{filepath.Join(localAppData, "Config"), filepath.Join(roamingAppData, "Config")}, actual: &xdg.ConfigDirs, }, &envSample{ name: "XDG_STATE_HOME", value: filepath.Join(programData, "State"), expected: filepath.Join(programData, "State"), actual: &xdg.StateHome, }, &envSample{ name: "XDG_CACHE_HOME", value: filepath.Join(programData, "Cache"), expected: filepath.Join(programData, "Cache"), actual: &xdg.CacheHome, }, &envSample{ name: "XDG_RUNTIME_DIR", value: filepath.Join(programData, "Runtime"), expected: filepath.Join(programData, "Runtime"), actual: &xdg.RuntimeDir, }, ) require.NoError(t, os.Setenv("APPDATA", envRoamingAppData)) require.NoError(t, os.Setenv("LOCALAPPDATA", envLocalAppData)) require.NoError(t, os.Setenv("ProgramData", envProgramData)) } func TestDefaultUserDirs(t *testing.T) { home := xdg.Home roamingAppData := filepath.Join(home, "AppData", "Roaming") testDirs(t, &envSample{ name: "XDG_DESKTOP_DIR", expected: filepath.Join(home, "Desktop"), actual: &xdg.UserDirs.Desktop, }, &envSample{ name: "XDG_DOWNLOAD_DIR", expected: filepath.Join(home, "Downloads"), actual: &xdg.UserDirs.Download, }, &envSample{ name: "XDG_DOCUMENTS_DIR", expected: filepath.Join(home, "Documents"), actual: &xdg.UserDirs.Documents, }, &envSample{ name: "XDG_MUSIC_DIR", expected: filepath.Join(home, "Music"), actual: &xdg.UserDirs.Music, }, &envSample{ name: "XDG_PICTURES_DIR", expected: filepath.Join(home, "Pictures"), actual: &xdg.UserDirs.Pictures, }, &envSample{ name: "XDG_VIDEOS_DIR", expected: filepath.Join(home, "Videos"), actual: &xdg.UserDirs.Videos, }, &envSample{ name: "XDG_TEMPLATES_DIR", expected: filepath.Join(roamingAppData, "Microsoft", "Windows", "Templates"), actual: &xdg.UserDirs.Templates, }, &envSample{ name: "XDG_PUBLICSHARE_DIR", expected: filepath.Join(`C:\`, "Users", "Public"), actual: &xdg.UserDirs.PublicShare, }, ) } func TestCustomUserDirs(t *testing.T) { home := xdg.Home testDirs(t, &envSample{ name: "XDG_DESKTOP_DIR", value: filepath.Join(home, "Files/Desktop"), expected: filepath.Join(home, "Files/Desktop"), actual: &xdg.UserDirs.Desktop, }, &envSample{ name: "XDG_DOWNLOAD_DIR", value: filepath.Join(home, "Files/Downloads"), expected: filepath.Join(home, "Files/Downloads"), actual: &xdg.UserDirs.Download, }, &envSample{ name: "XDG_DOCUMENTS_DIR", value: filepath.Join(home, "Files/Documents"), expected: filepath.Join(home, "Files/Documents"), actual: &xdg.UserDirs.Documents, }, &envSample{ name: "XDG_MUSIC_DIR", value: filepath.Join(home, "Files/Music"), expected: filepath.Join(home, "Files/Music"), actual: &xdg.UserDirs.Music, }, &envSample{ name: "XDG_PICTURES_DIR", value: filepath.Join(home, "Files/Pictures"), expected: filepath.Join(home, "Files/Pictures"), actual: &xdg.UserDirs.Pictures, }, &envSample{ name: "XDG_VIDEOS_DIR", value: filepath.Join(home, "Files/Videos"), expected: filepath.Join(home, "Files/Videos"), actual: &xdg.UserDirs.Videos, }, &envSample{ name: "XDG_TEMPLATES_DIR", value: filepath.Join(home, "Files/Templates"), expected: filepath.Join(home, "Files/Templates"), actual: &xdg.UserDirs.Templates, }, &envSample{ name: "XDG_PUBLICSHARE_DIR", value: filepath.Join(home, "Files/Public"), expected: filepath.Join(home, "Files/Public"), actual: &xdg.UserDirs.PublicShare, }, ) } xdg-0.4.0/user_dirs.go000066400000000000000000000022071413623533200146260ustar00rootroot00000000000000package xdg // XDG user directories environment variables. const ( envDesktopDir = "XDG_DESKTOP_DIR" envDownloadDir = "XDG_DOWNLOAD_DIR" envDocumentsDir = "XDG_DOCUMENTS_DIR" envMusicDir = "XDG_MUSIC_DIR" envPicturesDir = "XDG_PICTURES_DIR" envVideosDir = "XDG_VIDEOS_DIR" envTemplatesDir = "XDG_TEMPLATES_DIR" envPublicShareDir = "XDG_PUBLICSHARE_DIR" ) // UserDirectories defines the locations of well known user directories. type UserDirectories struct { // Desktop defines the location of the user's desktop directory. Desktop string // Download defines a suitable location for user downloaded files. Download string // Documents defines a suitable location for user document files. Documents string // Music defines a suitable location for user audio files. Music string // Pictures defines a suitable location for user image files. Pictures string // VideosDir defines a suitable location for user video files. Videos string // Templates defines a suitable location for user template files. Templates string // PublicShare defines a suitable location for user shared files. PublicShare string } xdg-0.4.0/xdg.go000066400000000000000000000214641413623533200134170ustar00rootroot00000000000000package xdg import ( "os" "path/filepath" "github.com/adrg/xdg/internal/pathutil" ) var ( // Home contains the path of the user's home directory. Home string // DataHome defines the base directory relative to which user-specific // data files should be stored. This directory is defined by the // $XDG_DATA_HOME environment variable. If the variable is not set, // a default equal to $HOME/.local/share should be used. DataHome string // DataDirs defines the preference-ordered set of base directories to // search for data files in addition to the DataHome base directory. // This set of directories is defined by the $XDG_DATA_DIRS environment // variable. If the variable is not set, the default directories // to be used are /usr/local/share and /usr/share, in that order. The // DataHome directory is considered more important than any of the // directories defined by DataDirs. Therefore, user data files should be // written relative to the DataHome directory, if possible. DataDirs []string // ConfigHome defines the base directory relative to which user-specific // configuration files should be written. This directory is defined by // the $XDG_CONFIG_HOME environment variable. If the variable is not // not set, a default equal to $HOME/.config should be used. ConfigHome string // ConfigDirs defines the preference-ordered set of base directories to // search for configuration files in addition to the ConfigHome base // directory. This set of directories is defined by the $XDG_CONFIG_DIRS // environment variable. If the variable is not set, a default equal // to /etc/xdg should be used. The ConfigHome directory is considered // more important than any of the directories defined by ConfigDirs. // Therefore, user config files should be written relative to the // ConfigHome directory, if possible. ConfigDirs []string // StateHome defines the base directory relative to which user-specific // state files should be stored. This directory is defined by the // $XDG_STATE_HOME environment variable. If the variable is not set, // a default equal to ~/.local/state should be used. StateHome string // CacheHome defines the base directory relative to which user-specific // non-essential (cached) data should be written. This directory is // defined by the $XDG_CACHE_HOME environment variable. If the variable // is not set, a default equal to $HOME/.cache should be used. CacheHome string // RuntimeDir defines the base directory relative to which user-specific // non-essential runtime files and other file objects (such as sockets, // named pipes, etc.) should be stored. This directory is defined by the // $XDG_RUNTIME_DIR environment variable. If the variable is not set, // applications should fall back to a replacement directory with similar // capabilities. Applications should use this directory for communication // and synchronization purposes and should not place larger files in it, // since it might reside in runtime memory and cannot necessarily be // swapped out to disk. RuntimeDir string // UserDirs defines the locations of well known user directories. UserDirs UserDirectories // FontDirs defines the common locations where font files are stored. FontDirs []string // ApplicationDirs defines the common locations of applications. ApplicationDirs []string // baseDirs defines the locations of base directories. baseDirs baseDirectories ) func init() { Reload() } // Reload refreshes base and user directories by reading the environment. // Defaults are applied for XDG variables which are empty or not present // in the environment. func Reload() { // Initialize home directory. Home = homeDir() // Initialize base and user directories. initDirs(Home) // Set standard directories. DataHome = baseDirs.dataHome DataDirs = baseDirs.data ConfigHome = baseDirs.configHome ConfigDirs = baseDirs.config StateHome = baseDirs.stateHome CacheHome = baseDirs.cacheHome RuntimeDir = baseDirs.runtime // Set non-standard directories. FontDirs = baseDirs.fonts ApplicationDirs = baseDirs.applications } // DataFile returns a suitable location for the specified data file. // The relPath parameter must contain the name of the data file, and // optionally, a set of parent directories (e.g. appname/app.data). // If the specified directories do not exist, they will be created relative // to the base data directory. On failure, an error containing the // attempted paths is returned. func DataFile(relPath string) (string, error) { return baseDirs.dataFile(relPath) } // ConfigFile returns a suitable location for the specified config file. // The relPath parameter must contain the name of the config file, and // optionally, a set of parent directories (e.g. appname/app.yaml). // If the specified directories do not exist, they will be created relative // to the base config directory. On failure, an error containing the // attempted paths is returned. func ConfigFile(relPath string) (string, error) { return baseDirs.configFile(relPath) } // StateFile returns a suitable location for the specified state file. State // files are usually volatile data files, not suitable to be stored relative // to the $XDG_DATA_HOME directory. // The relPath parameter must contain the name of the state file, and // optionally, a set of parent directories (e.g. appname/app.state). // If the specified directories do not exist, they will be created relative // to the base state directory. On failure, an error containing the // attempted paths is returned. func StateFile(relPath string) (string, error) { return baseDirs.stateFile(relPath) } // CacheFile returns a suitable location for the specified cache file. // The relPath parameter must contain the name of the cache file, and // optionally, a set of parent directories (e.g. appname/app.cache). // If the specified directories do not exist, they will be created relative // to the base cache directory. On failure, an error containing the // attempted paths is returned. func CacheFile(relPath string) (string, error) { return baseDirs.cacheFile(relPath) } // RuntimeFile returns a suitable location for the specified runtime file. // The relPath parameter must contain the name of the runtime file, and // optionally, a set of parent directories (e.g. appname/app.pid). // If the specified directories do not exist, they will be created relative // to the base runtime directory. On failure, an error containing the // attempted paths is returned. func RuntimeFile(relPath string) (string, error) { return baseDirs.runtimeFile(relPath) } // SearchDataFile searches for specified file in the data search paths. // The relPath parameter must contain the name of the data file, and // optionally, a set of parent directories (e.g. appname/app.data). If the // file cannot be found, an error specifying the searched paths is returned. func SearchDataFile(relPath string) (string, error) { return baseDirs.searchDataFile(relPath) } // SearchConfigFile searches for the specified file in config search paths. // The relPath parameter must contain the name of the config file, and // optionally, a set of parent directories (e.g. appname/app.yaml). If the // file cannot be found, an error specifying the searched paths is returned. func SearchConfigFile(relPath string) (string, error) { return baseDirs.searchConfigFile(relPath) } // SearchStateFile searches for the specified file in the state search path. // The relPath parameter must contain the name of the state file, and // optionally, a set of parent directories (e.g. appname/app.state). If the // file cannot be found, an error specifying the searched path is returned. func SearchStateFile(relPath string) (string, error) { return baseDirs.searchStateFile(relPath) } // SearchCacheFile searches for the specified file in the cache search path. // The relPath parameter must contain the name of the cache file, and // optionally, a set of parent directories (e.g. appname/app.cache). If the // file cannot be found, an error specifying the searched path is returned. func SearchCacheFile(relPath string) (string, error) { return baseDirs.searchCacheFile(relPath) } // SearchRuntimeFile searches for the specified file in the runtime search path. // The relPath parameter must contain the name of the runtime file, and // optionally, a set of parent directories (e.g. appname/app.pid). If the // file cannot be found, an error specifying the searched path is returned. func SearchRuntimeFile(relPath string) (string, error) { return baseDirs.searchRuntimeFile(relPath) } func xdgPath(name, defaultPath string) string { dir := pathutil.ExpandHome(os.Getenv(name), Home) if dir != "" && filepath.IsAbs(dir) { return dir } return defaultPath } func xdgPaths(name string, defaultPaths ...string) []string { dirs := pathutil.Unique(filepath.SplitList(os.Getenv(name)), Home) if len(dirs) != 0 { return dirs } return pathutil.Unique(defaultPaths, Home) } xdg-0.4.0/xdg_test.go000066400000000000000000000111601413623533200144460ustar00rootroot00000000000000package xdg_test import ( "os" "path/filepath" "testing" "github.com/adrg/xdg" "github.com/stretchr/testify/require" ) type envSample struct { name string value string expected interface{} actual interface{} } func testDirs(t *testing.T, samples ...*envSample) { // Test home directory. require.NotEmpty(t, xdg.Home) t.Logf("Home: %s", xdg.Home) // Set environment variables. for _, sample := range samples { require.NoError(t, os.Setenv(sample.name, sample.value)) } xdg.Reload() // Test results. for _, sample := range samples { var actual interface{} switch v := sample.actual.(type) { case *string: actual = *v case *[]string: actual = *v } require.Equal(t, sample.expected, actual) t.Logf("%s: %v", sample.name, actual) } } type testInputData struct { relPaths []string pathFunc func(string) (string, error) searchFunc func(string) (string, error) } func TestBaseDirFuncs(t *testing.T) { inputs := []*testInputData{ { relPaths: []string{"app.data", "appname/app.data"}, pathFunc: xdg.DataFile, searchFunc: xdg.SearchDataFile, }, { relPaths: []string{"app.yaml", "appname/app.yaml"}, pathFunc: xdg.ConfigFile, searchFunc: xdg.SearchConfigFile, }, { relPaths: []string{"app.state", "appname/app.state"}, pathFunc: xdg.StateFile, searchFunc: xdg.SearchStateFile, }, { relPaths: []string{"app.cache", "appname/app.cache"}, pathFunc: xdg.CacheFile, searchFunc: xdg.SearchCacheFile, }, { relPaths: []string{"app.pid", "appname/app.pid"}, pathFunc: xdg.RuntimeFile, searchFunc: xdg.SearchRuntimeFile, }, } // Test base directories for regular files. testBaseDirsRegular(t, inputs) // Test base directories for symbolic links. for _, input := range inputs { input.relPaths = []string{input.relPaths[1]} } testBaseDirsSymlinks(t, inputs) } func testBaseDirsRegular(t *testing.T, inputs []*testInputData) { for _, input := range inputs { for _, relPath := range input.relPaths { // Get suitable path for input file. expFullPath, err := input.pathFunc(relPath) require.NoError(t, err) // Create input file. f, err := os.Create(expFullPath) require.NoError(t, err) require.NoError(t, f.Close()) // Search input file after creation. actFullPath, err := input.searchFunc(relPath) require.NoError(t, err) require.Equal(t, expFullPath, actFullPath) // Remove created file. require.NoError(t, os.Remove(expFullPath)) // Search input file after removal. _, err = input.searchFunc(relPath) require.Error(t, err) // Check that the same path is returned. actFullPath, err = input.pathFunc(relPath) require.NoError(t, err) require.Equal(t, expFullPath, actFullPath) } } } func testBaseDirsSymlinks(t *testing.T, inputs []*testInputData) { for _, input := range inputs { for _, relPath := range input.relPaths { // Get suitable path for input file. expFullPath, err := input.pathFunc(relPath) require.NoError(t, err) // Replace input directory with symlink. symlinkDir := filepath.Dir(expFullPath) inputDir := filepath.Join(filepath.Dir(symlinkDir), "inputdir") require.NoError(t, os.Remove(symlinkDir)) require.NoError(t, os.Mkdir(inputDir, os.ModeDir|0700)) require.NoError(t, os.Symlink(inputDir, symlinkDir)) // Create input file. inputPath := filepath.Join(symlinkDir, "input.file") f, err := os.Create(inputPath) require.NoError(t, err) require.NoError(t, f.Close()) // Create symbolic link. require.NoError(t, os.Symlink(inputPath, expFullPath)) // Search input file after creation. actFullPath, err := input.searchFunc(relPath) require.NoError(t, err) require.Equal(t, expFullPath, actFullPath) // Remove created symbolic links, files and directories. require.NoError(t, os.Remove(expFullPath)) require.NoError(t, os.Remove(inputPath)) require.NoError(t, os.Remove(symlinkDir)) require.NoError(t, os.Remove(inputDir)) // Search input file after removal. _, err = input.searchFunc(relPath) require.Error(t, err) // Check that the same path is returned. actFullPath, err = input.pathFunc(relPath) require.NoError(t, err) require.Equal(t, expFullPath, actFullPath) } } } func TestInvalidPaths(t *testing.T) { inputs := map[string]func(string) (string, error){ "\000/app.data": xdg.DataFile, "appname\000/app.yaml": xdg.ConfigFile, "appname/\000/app.state": xdg.StateFile, "\000appname/app.cache": xdg.CacheFile, "\000/appname/app.pid": xdg.RuntimeFile, } for inputPath, xdgFunc := range inputs { _, err := xdgFunc(inputPath) require.Error(t, err) } }