config: use xdg package instead of configdir

pull/129/head
Dawid Dziurla 5 years ago
parent f384e57917
commit 2b3d380d10
No known key found for this signature in database
GPG Key ID: 7B6D8368172E9B0B

@ -5,6 +5,7 @@ go 1.12
require (
github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78 // indirect
github.com/Microsoft/go-winio v0.4.12 // indirect
github.com/OpenPeeDeeP/xdg v0.2.0
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d
github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21
github.com/docker/distribution v2.7.1+incompatible // indirect
@ -33,7 +34,7 @@ require (
github.com/onsi/gomega v1.5.0 // indirect
github.com/opencontainers/go-digest v1.0.0-rc1 // indirect
github.com/opencontainers/image-spec v1.0.1 // indirect
github.com/shibukawa/configdir v0.0.0-20170330084843-e180dbdc8da0
github.com/shibukawa/configdir v0.0.0-20170330084843-e180dbdc8da0 // indirect
github.com/sirupsen/logrus v1.3.0
github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad
github.com/stretchr/testify v1.2.2

@ -4,6 +4,8 @@ github.com/Azure/go-ansiterm v0.0.0-20170929234023-d6e3b3328b78/go.mod h1:LmzpDX
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/Microsoft/go-winio v0.4.12 h1:xAfWHN1IrQ0NJ9TBC0KBZoqLjzDTr1ML+4MywiUOryc=
github.com/Microsoft/go-winio v0.4.12/go.mod h1:VhR8bwka0BXejwEJY73c50VrPtXAaKcyvVC4A4RozmA=
github.com/OpenPeeDeeP/xdg v0.2.0 h1:xr89rnllbkRkM7SV9Y++FJ8TGkbdkhhBQm5kOkGT7AE=
github.com/OpenPeeDeeP/xdg v0.2.0/go.mod h1:tMoSueLQlMf0TCldjrJLNIjAc5qAOIcHt5REi88/Ygo=
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d h1:licZJFw2RwpHMqeKTCYkitsPqHNxTmd4SNR5r94FGM8=
github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d/go.mod h1:asat636LX7Bqt5lYEZ27JNDcqxfjdBQuJ/MM4CN/Lzo=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=

@ -19,8 +19,8 @@ import (
"strings"
"time"
"github.com/OpenPeeDeeP/xdg"
yaml "github.com/jesseduffield/yaml"
"github.com/shibukawa/configdir"
)
// UserConfig holds all of the user-configurable options
@ -412,14 +412,15 @@ func NewAppConfig(name, version, commit, date string, buildSource string, debugg
}
func findOrCreateConfigDir(projectName string) (string, error) {
configDirs := configdir.New("jesseduffield", projectName)
folders := configDirs.QueryFolders(configdir.Global)
configDirs := xdg.New("jesseduffield", projectName)
folder := configDirs.ConfigHome()
if err := folders[0].CreateParentDir("foo"); err != nil {
err := os.MkdirAll(folder, 0755)
if err != nil {
return "", err
}
return folders[0].Path, nil
return folder, nil
}
func loadUserConfigWithDefaults(configDir string) (*UserConfig, error) {

@ -0,0 +1,3 @@
*.test
*.out
.DS_STORE

@ -0,0 +1,12 @@
language: go
go:
- 1.11.x
os:
- linux
- osx
before_install:
- go get -t -v ./...
script:
- go test -v -race -covermode=atomic -coverprofile=coverage.txt
after_success:
- bash <(curl -s https://codecov.io/bash)

@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2017, OpenPeeDeeP
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

@ -0,0 +1,25 @@
# XDG [![Build status](https://ci.appveyor.com/api/projects/status/9eoupq9jgsu2p0jv?svg=true)](https://ci.appveyor.com/project/dixonwille/xdg) [![Build Status](https://travis-ci.org/OpenPeeDeeP/xdg.svg?branch=master)](https://travis-ci.org/OpenPeeDeeP/xdg) [![Go Report Card](https://goreportcard.com/badge/github.com/OpenPeeDeeP/xdg)](https://goreportcard.com/report/github.com/OpenPeeDeeP/xdg) [![GoDoc](https://godoc.org/github.com/OpenPeeDeeP/xdg?status.svg)](https://godoc.org/github.com/OpenPeeDeeP/xdg) [![codecov](https://codecov.io/gh/OpenPeeDeeP/xdg/branch/master/graph/badge.svg)](https://codecov.io/gh/OpenPeeDeeP/xdg)
A cross platform package that tries to follow [XDG Standard](https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html) when possible. Since XDG is linux specific, I am only able to follow standards to the T on linux. But for the other operating systems I am finding similar best practice locations for the files.
## Locations Per OS
The following table shows what is used if the envrionment variable is not set. If the variable is set then this package uses that. Linux follows the default standards. Mac does when it comes to the home directory but for system wide it uses the standard `/Library/Application Support`. As for Windows, the variable defaults are just other environment variables set up by the operation system.
> When creating `XDG` application the `Vendor` and `Application` names are appeneded to the end of the path to keep projects unique.
| | Linux | Mac | Windows |
| ---: | :---: | :---: | :---: |
| `XDG_DATA_DIRS` | [`/usr/local/share`, `/usr/share`] | [`/Library/Application Support`] | `%PROGRAMDATA%` |
| `XDG_DATA_HOME` | `~/.local/share` | `~/Library/Application Support` | `%APPDATA%` |
| `XDG_CONFIG_DIRS` | [`/etc/xdg`] | [`/Library/Application Support`] | `%PROGRAMDATA%` |
| `XDG_CONFIG_HOME` | `~/.config` | `~/Library/Application Support` | `%APPDATA%` |
| `XDG_CACHE_HOME` | `~/.cache` | `~/Library/Cache` | `%LOCALAPPDATA%` |
## Notes
- This package does not merge files if they exist across different directories.
- The `Query` methods search through the system variables, `DIRS`, first (when using environment variables first in the variable has presidence). It then checks home variables, `HOME`.
- This package will not create any directories for you. In the standard, it states the following:
> If, when attempting to write a file, the destination directory is non-existant an attempt should be made to create it with permission `0700`. If the destination directory exists already the permissions should not be changed. The application should be prepared to handle the case where the file could not be written, either because the directory was non-existant and could not be created, or for any other reason. In such case it may chose to present an error message to the user.

@ -0,0 +1,16 @@
version: 0.0.1_{build}
build: off
platform: x64
clone_folder: c:\gopath\src\github.com\OpenPeeDeeP\xdg
environment:
GOPATH: c:\gopath
stack: go 1.11
install:
- go get -t -v ./...
- cinst codecov
before_test:
- go vet ./...
test_script:
- go test -v -race -covermode=atomic -coverprofile=coverage.txt
on_success:
- codecov -f coverage.txt

@ -0,0 +1,8 @@
module github.com/OpenPeeDeeP/xdg
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/objx v0.1.1 // indirect
github.com/stretchr/testify v1.2.2
)

@ -0,0 +1,8 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/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.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=

@ -0,0 +1,163 @@
// Copyright (c) 2017, OpenPeeDeeP. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package xdg impelements the XDG standard for application file locations.
package xdg
import (
"os"
"path/filepath"
"strings"
)
var defaulter xdgDefaulter = new(osDefaulter)
type xdgDefaulter interface {
defaultDataHome() string
defaultDataDirs() []string
defaultConfigHome() string
defaultConfigDirs() []string
defaultCacheHome() string
}
type osDefaulter struct {
}
//This method is used in the testing suit
// nolint: deadcode
func setDefaulter(def xdgDefaulter) {
defaulter = def
}
// XDG is information about the currently running application
type XDG struct {
Vendor string
Application string
}
// New returns an instance of XDG that is used to grab files for application use
func New(vendor, application string) *XDG {
return &XDG{
Vendor: vendor,
Application: application,
}
}
// DataHome returns the location that should be used for user specific data files for this specific application
func (x *XDG) DataHome() string {
return filepath.Join(DataHome(), x.Vendor, x.Application)
}
// DataDirs returns a list of locations that should be used for system wide data files for this specific application
func (x *XDG) DataDirs() []string {
dataDirs := DataDirs()
for i, dir := range dataDirs {
dataDirs[i] = filepath.Join(dir, x.Vendor, x.Application)
}
return dataDirs
}
// ConfigHome returns the location that should be used for user specific config files for this specific application
func (x *XDG) ConfigHome() string {
return filepath.Join(ConfigHome(), x.Vendor, x.Application)
}
// ConfigDirs returns a list of locations that should be used for system wide config files for this specific application
func (x *XDG) ConfigDirs() []string {
configDirs := ConfigDirs()
for i, dir := range configDirs {
configDirs[i] = filepath.Join(dir, x.Vendor, x.Application)
}
return configDirs
}
// CacheHome returns the location that should be used for application cache files for this specific application
func (x *XDG) CacheHome() string {
return filepath.Join(CacheHome(), x.Vendor, x.Application)
}
// QueryData looks for the given filename in XDG paths for data files.
// Returns an empty string if one was not found.
func (x *XDG) QueryData(filename string) string {
dirs := x.DataDirs()
dirs = append([]string{x.DataHome()}, dirs...)
return returnExist(filename, dirs)
}
// QueryConfig looks for the given filename in XDG paths for config files.
// Returns an empty string if one was not found.
func (x *XDG) QueryConfig(filename string) string {
dirs := x.ConfigDirs()
dirs = append([]string{x.ConfigHome()}, dirs...)
return returnExist(filename, dirs)
}
// QueryCache looks for the given filename in XDG paths for cache files.
// Returns an empty string if one was not found.
func (x *XDG) QueryCache(filename string) string {
return returnExist(filename, []string{x.CacheHome()})
}
func returnExist(filename string, dirs []string) string {
for _, dir := range dirs {
_, err := os.Stat(filepath.Join(dir, filename))
if (err != nil && os.IsExist(err)) || err == nil {
return filepath.Join(dir, filename)
}
}
return ""
}
// DataHome returns the location that should be used for user specific data files
func DataHome() string {
dataHome := os.Getenv("XDG_DATA_HOME")
if dataHome == "" {
dataHome = defaulter.defaultDataHome()
}
return dataHome
}
// DataDirs returns a list of locations that should be used for system wide data files
func DataDirs() []string {
var dataDirs []string
dataDirsStr := os.Getenv("XDG_DATA_DIRS")
if dataDirsStr != "" {
dataDirs = strings.Split(dataDirsStr, string(os.PathListSeparator))
}
if len(dataDirs) == 0 {
dataDirs = defaulter.defaultDataDirs()
}
return dataDirs
}
// ConfigHome returns the location that should be used for user specific config files
func ConfigHome() string {
configHome := os.Getenv("XDG_CONFIG_HOME")
if configHome == "" {
configHome = defaulter.defaultConfigHome()
}
return configHome
}
// ConfigDirs returns a list of locations that should be used for system wide config files
func ConfigDirs() []string {
var configDirs []string
configDirsStr := os.Getenv("XDG_CONFIG_DIRS")
if configDirsStr != "" {
configDirs = strings.Split(configDirsStr, string(os.PathListSeparator))
}
if len(configDirs) == 0 {
configDirs = defaulter.defaultConfigDirs()
}
return configDirs
}
// CacheHome returns the location that should be used for application cache files
func CacheHome() string {
cacheHome := os.Getenv("XDG_CACHE_HOME")
if cacheHome == "" {
cacheHome = defaulter.defaultCacheHome()
}
return cacheHome
}

@ -0,0 +1,30 @@
// Copyright (c) 2017, OpenPeeDeeP. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xdg
import (
"os"
"path/filepath"
)
func (o *osDefaulter) defaultDataHome() string {
return filepath.Join(os.Getenv("HOME"), "Library", "Application Support")
}
func (o *osDefaulter) defaultDataDirs() []string {
return []string{filepath.Join("/Library", "Application Support")}
}
func (o *osDefaulter) defaultConfigHome() string {
return filepath.Join(os.Getenv("HOME"), "Library", "Application Support")
}
func (o *osDefaulter) defaultConfigDirs() []string {
return []string{filepath.Join("/Library", "Application Support")}
}
func (o *osDefaulter) defaultCacheHome() string {
return filepath.Join(os.Getenv("HOME"), "Library", "Caches")
}

@ -0,0 +1,30 @@
// Copyright (c) 2017, OpenPeeDeeP. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xdg
import (
"os"
"path/filepath"
)
func (o *osDefaulter) defaultDataHome() string {
return filepath.Join(os.Getenv("HOME"), ".local", "share")
}
func (o *osDefaulter) defaultDataDirs() []string {
return []string{"/usr/local/share/", "/usr/share/"}
}
func (o *osDefaulter) defaultConfigHome() string {
return filepath.Join(os.Getenv("HOME"), ".config")
}
func (o *osDefaulter) defaultConfigDirs() []string {
return []string{"/etc/xdg"}
}
func (o *osDefaulter) defaultCacheHome() string {
return filepath.Join(os.Getenv("HOME"), ".cache")
}

@ -0,0 +1,27 @@
// Copyright (c) 2017, OpenPeeDeeP. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package xdg
import "os"
func (o *osDefaulter) defaultDataHome() string {
return os.Getenv("APPDATA")
}
func (o *osDefaulter) defaultDataDirs() []string {
return []string{os.Getenv("PROGRAMDATA")}
}
func (o *osDefaulter) defaultConfigHome() string {
return os.Getenv("APPDATA")
}
func (o *osDefaulter) defaultConfigDirs() []string {
return []string{os.Getenv("PROGRAMDATA")}
}
func (o *osDefaulter) defaultCacheHome() string {
return os.Getenv("LOCALAPPDATA")
}

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2016 shibukawa
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.

@ -1,111 +0,0 @@
configdir for Golang
=====================
Multi platform library of configuration directory for Golang.
This library helps to get regular directories for configuration files or cache files that matches target operationg system's convention.
It assumes the following folders are standard paths of each environment:
.. list-table::
:header-rows: 1
- *
* Windows:
* Linux/BSDs:
* MacOSX:
- * System level configuration folder
* ``%PROGRAMDATA%`` (``C:\\ProgramData``)
* ``${XDG_CONFIG_DIRS}`` (``/etc/xdg``)
* ``/Library/Application Support``
- * User level configuration folder
* ``%APPDATA%`` (``C:\\Users\\<User>\\AppData\\Roaming``)
* ``${XDG_CONFIG_HOME}`` (``${HOME}/.config``)
* ``${HOME}/Library/Application Support``
- * User wide cache folder
* ``%LOCALAPPDATA%`` ``(C:\\Users\\<User>\\AppData\\Local)``
* ``${XDG_CACHE_HOME}`` (``${HOME}/.cache``)
* ``${HOME}/Library/Caches``
Examples
------------
Getting Configuration
~~~~~~~~~~~~~~~~~~~~~~~~
``configdir.ConfigDir.QueryFolderContainsFile()`` searches files in the following order:
* Local path (if you add the path via LocalPath parameter)
* User level configuration folder(e.g. ``$HOME/.config/<vendor-name>/<application-name>/setting.json`` in Linux)
* System level configuration folder(e.g. ``/etc/xdg/<vendor-name>/<application-name>/setting.json`` in Linux)
``configdir.Config`` provides some convenient methods(``ReadFile``, ``WriteFile`` and so on).
.. code-block:: go
var config Config
configDirs := configdir.New("vendor-name", "application-name")
// optional: local path has the highest priority
configDirs.LocalPath, _ = filepath.Abs(".")
folder := configDirs.QueryFolderContainsFile("setting.json")
if folder != nil {
data, _ := folder.ReadFile("setting.json")
json.Unmarshal(data, &config)
} else {
config = DefaultConfig
}
Write Configuration
~~~~~~~~~~~~~~~~~~~~~~
When storing configuration, get configuration folder by using ``configdir.ConfigDir.QueryFolders()`` method.
.. code-block:: go
configDirs := configdir.New("vendor-name", "application-name")
var config Config
data, _ := json.Marshal(&config)
// Stores to local folder
folders := configDirs.QueryFolders(configdir.Local)
folders[0].WriteFile("setting.json", data)
// Stores to user folder
folders = configDirs.QueryFolders(configdir.Global)
folders[0].WriteFile("setting.json", data)
// Stores to system folder
folders = configDirs.QueryFolders(configdir.System)
folders[0].WriteFile("setting.json", data)
Getting Cache Folder
~~~~~~~~~~~~~~~~~~~~~~
It is similar to the above example, but returns cache folder.
.. code-block:: go
configDirs := configdir.New("vendor-name", "application-name")
cache := configDirs.QueryCacheFolder()
resp, err := http.Get("http://examples.com/sdk.zip")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
cache.WriteFile("sdk.zip", body)
Document
------------
https://godoc.org/github.com/shibukawa/configdir
License
------------
MIT

@ -1,160 +0,0 @@
// configdir provides access to configuration folder in each platforms.
//
// System wide configuration folders:
//
// - Windows: %PROGRAMDATA% (C:\ProgramData)
// - Linux/BSDs: ${XDG_CONFIG_DIRS} (/etc/xdg)
// - MacOSX: "/Library/Application Support"
//
// User wide configuration folders:
//
// - Windows: %APPDATA% (C:\Users\<User>\AppData\Roaming)
// - Linux/BSDs: ${XDG_CONFIG_HOME} (${HOME}/.config)
// - MacOSX: "${HOME}/Library/Application Support"
//
// User wide cache folders:
//
// - Windows: %LOCALAPPDATA% (C:\Users\<User>\AppData\Local)
// - Linux/BSDs: ${XDG_CACHE_HOME} (${HOME}/.cache)
// - MacOSX: "${HOME}/Library/Caches"
//
// configdir returns paths inside the above folders.
package configdir
import (
"io/ioutil"
"os"
"path/filepath"
)
type ConfigType int
const (
System ConfigType = iota
Global
All
Existing
Local
Cache
)
// Config represents each folder
type Config struct {
Path string
Type ConfigType
}
func (c Config) Open(fileName string) (*os.File, error) {
return os.Open(filepath.Join(c.Path, fileName))
}
func (c Config) Create(fileName string) (*os.File, error) {
err := c.CreateParentDir(fileName)
if err != nil {
return nil, err
}
return os.Create(filepath.Join(c.Path, fileName))
}
func (c Config) ReadFile(fileName string) ([]byte, error) {
return ioutil.ReadFile(filepath.Join(c.Path, fileName))
}
// CreateParentDir creates the parent directory of fileName inside c. fileName
// is a relative path inside c, containing zero or more path separators.
func (c Config) CreateParentDir(fileName string) error {
return os.MkdirAll(filepath.Dir(filepath.Join(c.Path, fileName)), 0755)
}
func (c Config) WriteFile(fileName string, data []byte) error {
err := c.CreateParentDir(fileName)
if err != nil {
return err
}
return ioutil.WriteFile(filepath.Join(c.Path, fileName), data, 0644)
}
func (c Config) MkdirAll() error {
return os.MkdirAll(c.Path, 0755)
}
func (c Config) Exists(fileName string) bool {
_, err := os.Stat(filepath.Join(c.Path, fileName))
return !os.IsNotExist(err)
}
// ConfigDir keeps setting for querying folders.
type ConfigDir struct {
VendorName string
ApplicationName string
LocalPath string
}
func New(vendorName, applicationName string) ConfigDir {
return ConfigDir{
VendorName: vendorName,
ApplicationName: applicationName,
}
}
func (c ConfigDir) joinPath(root string) string {
if c.VendorName != "" && hasVendorName {
return filepath.Join(root, c.VendorName, c.ApplicationName)
}
return filepath.Join(root, c.ApplicationName)
}
func (c ConfigDir) QueryFolders(configType ConfigType) []*Config {
if configType == Cache {
return []*Config{c.QueryCacheFolder()}
}
var result []*Config
if c.LocalPath != "" && configType != System && configType != Global {
result = append(result, &Config{
Path: c.LocalPath,
Type: Local,
})
}
if configType != System && configType != Local {
result = append(result, &Config{
Path: c.joinPath(globalSettingFolder),
Type: Global,
})
}
if configType != Global && configType != Local {
for _, root := range systemSettingFolders {
result = append(result, &Config{
Path: c.joinPath(root),
Type: System,
})
}
}
if configType != Existing {
return result
}
var existing []*Config
for _, entry := range result {
if _, err := os.Stat(entry.Path); !os.IsNotExist(err) {
existing = append(existing, entry)
}
}
return existing
}
func (c ConfigDir) QueryFolderContainsFile(fileName string) *Config {
configs := c.QueryFolders(Existing)
for _, config := range configs {
if _, err := os.Stat(filepath.Join(config.Path, fileName)); !os.IsNotExist(err) {
return config
}
}
return nil
}
func (c ConfigDir) QueryCacheFolder() *Config {
return &Config{
Path: c.joinPath(cacheFolder),
Type: Cache,
}
}

@ -1,8 +0,0 @@
package configdir
import "os"
var hasVendorName = true
var systemSettingFolders = []string{"/Library/Application Support"}
var globalSettingFolder = os.Getenv("HOME") + "/Library/Application Support"
var cacheFolder = os.Getenv("HOME") + "/Library/Caches"

@ -1,8 +0,0 @@
package configdir
import "os"
var hasVendorName = true
var systemSettingFolders = []string{os.Getenv("PROGRAMDATA")}
var globalSettingFolder = os.Getenv("APPDATA")
var cacheFolder = os.Getenv("LOCALAPPDATA")

@ -1,34 +0,0 @@
// +build !windows,!darwin
package configdir
import (
"os"
"path/filepath"
"strings"
)
// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
var hasVendorName = true
var systemSettingFolders []string
var globalSettingFolder string
var cacheFolder string
func init() {
if os.Getenv("XDG_CONFIG_HOME") != "" {
globalSettingFolder = os.Getenv("XDG_CONFIG_HOME")
} else {
globalSettingFolder = filepath.Join(os.Getenv("HOME"), ".config")
}
if os.Getenv("XDG_CONFIG_DIRS") != "" {
systemSettingFolders = strings.Split(os.Getenv("XDG_CONFIG_DIRS"), ":")
} else {
systemSettingFolders = []string{"/etc/xdg"}
}
if os.Getenv("XDG_CACHE_HOME") != "" {
cacheFolder = os.Getenv("XDG_CACHE_HOME")
} else {
cacheFolder = filepath.Join(os.Getenv("HOME"), ".cache")
}
}

@ -1,5 +1,7 @@
# github.com/Microsoft/go-winio v0.4.12
github.com/Microsoft/go-winio
# github.com/OpenPeeDeeP/xdg v0.2.0
github.com/OpenPeeDeeP/xdg
# github.com/acarl005/stripansi v0.0.0-20180116102854-5a71ef0e047d
github.com/acarl005/stripansi
# github.com/cloudfoundry/jibber_jabber v0.0.0-20151120183258-bcc4c8345a21
@ -77,8 +79,6 @@ github.com/opencontainers/image-spec/specs-go
github.com/pkg/errors
# github.com/pmezard/go-difflib v1.0.0
github.com/pmezard/go-difflib/difflib
# github.com/shibukawa/configdir v0.0.0-20170330084843-e180dbdc8da0
github.com/shibukawa/configdir
# github.com/sirupsen/logrus v1.3.0
github.com/sirupsen/logrus
# github.com/spkg/bom v0.0.0-20160624110644-59b7046e48ad

Loading…
Cancel
Save