Add xdg configuration support

Fixes #170
This commit is contained in:
erroneousboat 2019-09-28 13:11:18 +02:00
parent e17a1cd920
commit 0d8e8aca4c
16 changed files with 375 additions and 22 deletions

View File

@ -34,12 +34,15 @@ Setup
1. Get a slack token, click [here](https://api.slack.com/docs/oauth-test-tokens)
2. Create a file named `config` in the `$XDG_CONFIG_HOME/slack-term` directory
(the [XDG Base Directory Specification](https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html)
specifies `$HOME/.config/` if you do not have `$XDG_CONFIG_HOME` explicitly
set). Below is an example of such a file. You are only required to specify a
`slack_token`. For more configuration options of the `config` file, see
the [wiki](https://github.com/erroneousboat/slack-term/wiki).
2. Running `slack-term` for the first time, will create a default config file at
`~/.config/slack-term/config`.
```bash
$ slack-term
```
3. Update the config file and update your `slack_token` For more configuration
options of the `config` file, see the [wiki](https://github.com/erroneousboat/slack-term/wiki).
```javascript
{

View File

@ -6,7 +6,9 @@ import (
"fmt"
"io/ioutil"
"os"
fp "path/filepath"
"github.com/OpenPeeDeeP/xdg"
"github.com/erroneousboat/termui"
)
@ -34,17 +36,17 @@ func NewConfig(filepath string) (*Config, error) {
cfg := getDefaultConfig()
// Open config file, and when none is found or present create
// a default empty one, at the filepath location
// a default empty one, at the default filepath location
file, err := os.Open(filepath)
if err != nil {
file, err = CreateConfigFile(filepath)
if err != nil {
return &cfg, fmt.Errorf("couldn't open the slack-term config file: %v", err)
return &cfg, fmt.Errorf("couldn't open the slack-term config file: (%v)", err)
}
}
if err := json.NewDecoder(file).Decode(&cfg); err != nil {
return &cfg, fmt.Errorf("the slack-term config file isn't valid json: %v", err)
return &cfg, fmt.Errorf("the slack-term config file isn't valid json: (%v)", err)
}
if cfg.SidebarWidth < 1 || cfg.SidebarWidth > 11 {
@ -73,6 +75,12 @@ func NewConfig(filepath string) (*Config, error) {
}
func CreateConfigFile(filepath string) (*os.File, error) {
filepath = fmt.Sprintf("%s/slack-term/%s", xdg.ConfigHome(), "config")
if _, err := os.Stat(filepath); os.IsNotExist(err) {
os.MkdirAll(fp.Dir(filepath), os.ModePerm)
}
payload := "{\"slack_token\": \"\"}"
err := ioutil.WriteFile(filepath, []byte(payload), 0755)
if err != nil {

1
go.sum
View File

@ -33,6 +33,7 @@ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
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/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/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=

14
main.go
View File

@ -5,8 +5,6 @@ import (
"fmt"
"log"
"os"
"os/user"
"path"
"github.com/OpenPeeDeeP/xdg"
"github.com/erroneousboat/termui"
@ -46,19 +44,9 @@ var (
)
func init() {
// Get home dir for config file default
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
// Find the default config file
xdg := xdg.New("slack-term", "")
configFile := xdg.QueryConfig("config")
if configFile == "" {
// Fall back to $HOME/.slack_term for legacy compatibility
configFile = path.Join(usr.HomeDir, ".slack-term")
}
configFile := xdg.New("slack-term", "").QueryConfig("config")
// Parse flags
flag.StringVar(

3
vendor/github.com/OpenPeeDeeP/xdg/.gitignore generated vendored Normal file
View File

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

12
vendor/github.com/OpenPeeDeeP/xdg/.travis.yml generated vendored Normal file
View File

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

29
vendor/github.com/OpenPeeDeeP/xdg/LICENSE generated vendored Normal file
View File

@ -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.

25
vendor/github.com/OpenPeeDeeP/xdg/README.md generated vendored Normal file
View File

@ -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.

16
vendor/github.com/OpenPeeDeeP/xdg/appveyor.yml generated vendored Normal file
View File

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

8
vendor/github.com/OpenPeeDeeP/xdg/go.mod generated vendored Normal file
View File

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

8
vendor/github.com/OpenPeeDeeP/xdg/go.sum generated vendored Normal file
View File

@ -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=

163
vendor/github.com/OpenPeeDeeP/xdg/xdg.go generated vendored Normal file
View File

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

30
vendor/github.com/OpenPeeDeeP/xdg/xdg_darwin.go generated vendored Normal file
View File

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

30
vendor/github.com/OpenPeeDeeP/xdg/xdg_linux.go generated vendored Normal file
View File

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

27
vendor/github.com/OpenPeeDeeP/xdg/xdg_windows.go generated vendored Normal file
View File

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

2
vendor/modules.txt vendored
View File

@ -1,5 +1,7 @@
# github.com/0xAX/notificator v0.0.0-20171022182052-88d57ee9043b
github.com/0xAX/notificator
# github.com/OpenPeeDeeP/xdg v0.2.0
github.com/OpenPeeDeeP/xdg
# github.com/erroneousboat/termui v0.0.0-20170923115141-80f245cdfa04
github.com/erroneousboat/termui
# github.com/gorilla/websocket v1.4.1