Skip to content
Snippets Groups Projects
Verified Commit 16566494 authored by Volker Schukai's avatar Volker Schukai :alien:
Browse files

initial version

parent 35fab608
No related branches found
No related tags found
No related merge requests found
# Created by https://www.toptal.com/developers/gitignore/api/intellij,go
# Edit at https://www.toptal.com/developers/gitignore?templates=intellij,go
### Go ###
# If you prefer the allow list template instead of the deny list, see community template:
# https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore
#
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
### Go Patch ###
/vendor/
/Godeps/
### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721
# *.iml
# modules.xml
# .idea/misc.xml
# *.ipr
# Sonarlint plugin
# https://plugins.jetbrains.com/plugin/7973-sonarlint
.idea/**/sonarlint/
# SonarQube Plugin
# https://plugins.jetbrains.com/plugin/7238-sonarqube-community-plugin
.idea/**/sonarIssues.xml
# Markdown Navigator plugin
# https://plugins.jetbrains.com/plugin/7896-markdown-navigator-enhanced
.idea/**/markdown-navigator.xml
.idea/**/markdown-navigator-enh.xml
.idea/**/markdown-navigator/
# Cache file creation bug
# See https://youtrack.jetbrains.com/issue/JBR-2257
.idea/$CACHE_FILE$
# CodeStream plugin
# https://plugins.jetbrains.com/plugin/12206-codestream
.idea/codestream.xml
# Azure Toolkit for IntelliJ plugin
# https://plugins.jetbrains.com/plugin/8053-azure-toolkit-for-intellij
.idea/**/azureSettings.xml
# End of https://www.toptal.com/developers/gitignore/api/intellij,go
\ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="accountSettings">
<option name="activeProfile" value="profile:default" />
<option name="activeRegion" value="eu-west-1" />
<option name="recentlyUsedProfiles">
<list>
<option value="profile:default" />
</list>
</option>
<option name="recentlyUsedRegions">
<list>
<option value="eu-west-1" />
</list>
</option>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="MarkdownSettings">
<enabledExtensions>
<entry key="MermaidLanguageExtension" value="false" />
<entry key="PlantUMLLanguageExtension" value="true" />
</enabledExtensions>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/configuration.iml" filepath="$PROJECT_DIR$/configuration.iml" />
<module fileurl="file://$PROJECT_DIR$/../http-negotiation/http-negotiation.iml" filepath="$PROJECT_DIR$/../http-negotiation/http-negotiation.iml" />
</modules>
</component>
</project>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="" vcs="Git" />
</component>
</project>
\ No newline at end of file
Makefile 0 → 100644
PROJECT_ROOT:=$(dir $(realpath $(lastword $(MAKEFILE_LIST))))
THIS_MAKEFILE:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST))
THIS_MAKEFILE_PATH:=$(PROJECT_ROOT)$(THIS_MAKEFILE)
# @see .PHONY https://www.gnu.org/software/make/manual/html_node/Phony-Targets.html#Phony-Targets
.DEFAULT_GOAL := help
.PHONY: print
## Print Path
print:
@echo "THIS_MAKEFILE: $(THIS_MAKEFILE)"
@echo "THIS_MAKEFILE_PATH: $(THIS_MAKEFILE_PATH)"
@echo "PROJECT_ROOT: $(PROJECT_ROOT)"
# Add a comment to the public targets so that it appears
# in this help Use two # characters for a help comment
.PHONY: help
help:
@printf "${COMMENT}Usage:${RESET}\n"
@printf " make [target] [arg=\"val\"...]\n\n"
@printf "${COMMENT}Available targets:${RESET}\n"
@awk '/^[a-zA-Z\-\\_0-9\.@]+:/ { \
helpMessage = match(lastLine, /^## (.*)/); \
if (helpMessage) { \
helpCommand = substr($$1, 0, index($$1, ":")); \
helpMessage = substr(lastLine, RSTART + 3, RLENGTH); \
printf " ${INFO}%-22s${RESET} %s\n", helpCommand, helpMessage; \
} \
} \
{ lastLine = $$0 }' $(MAKEFILE_LIST)
@printf "\n${COMMENT}Available arguments:${RESET}\n\n"
@awk '/^(([a-zA-Z\-\\_0-9\.@]+)\s[?:]?=)/ { \
helpMessage = match(lastLine, /^## (.*)/); \
if (helpMessage) { \
helpMessage = substr(lastLine, RSTART + 3, RLENGTH); \
printf " ${INFO}%-22s${RESET} %s (Default: %s)\n", $$1, helpMessage, $$3; \
} \
} \
{ lastLine = $$0 }' $(MAKEFILE_LIST)
## run tests
test:
echo "Running tests"
go test -cover -v ./...
## run tests with fuzzing
test-fuzz:
echo "Running fuzz tests"
go test -v -fuzztime=30s -fuzz=Fuzz ./...
#### VERSION
BIN_DIR ?= $(shell echo $$HOME)/.local/bin/
VERSION_NAME := version
EXECUTABLES = $(EXECUTABLES:-) $(VERSION_NAME)
VERSION_BIN_PATH := $(BIN_DIR)$(VERSION_NAME)
VERSION_BIN := $(shell command -v $(VERSION_NAME) 2> /dev/null)
ifndef VERSION_BIN
$(shell curl -o $(VERSION_BIN_PATH) http://download.schukai.com/tools/version/version-$(shell uname -s | tr [:upper:] [:lower:])-$(shell echo `uname -m | sed s/aarch64/arm64/ | sed s/x86_64/amd64/`))
$(shell chmod +x $(VERSION_BIN_PATH))
endif
RELEASE_FILE ?= $(PROJECT_ROOT)release.json
ifeq ("$(wildcard $(RELEASE_FILE))","")
$(shell echo '{"version":"0.1.0"}' > $(RELEASE_FILE))
endif
PROJECT_VERSION ?= $(shell cat $(RELEASE_FILE) | jq -r .version)
PROJECT_BUILD_DATE ?= $(shell $(VERSION_BIN) date)
.PHONY: next-patch-version
## create next patch version
next-patch-version: check-clean-repo
echo "Creating next version"
$(VERSION_BIN) patch --path $(RELEASE_FILE) --selector "version"
git add $(RELEASE_FILE) && git commit -m "Bump version to $$(cat $(RELEASE_FILE) | jq -r .version)"
.PHONY: next-minor-version
## create next minor version
next-minor-version: check-clean-repo
echo "Creating next minor version"
$(VERSION_BIN) minor --path $(RELEASE_FILE) --selector "version"
git add $(RELEASE_FILE) && git commit -m "Bump version to $$( cat $(RELEASE_FILE) | jq -r .version)"
.PHONY: next-major-version
## create next major version
next-major-version: check-clean-repo
echo "Creating next minor version"
$(VERSION_BIN) major --path $(RELEASE_FILE) --selector "version"
git add $(RELEASE_FILE) && git commit -m "Bump version to $$(cat $(RELEASE_FILE) | jq -r .version)"
.PHONY: check-clean-repo
check-clean-repo:
git diff-index --quiet HEAD || (echo "There are uncommitted changes after running make. Please commit or stash them before running make."; exit 1)
## tag repository with next patch version
tag-patch-version: next-patch-version
echo "Tagging patch version"
$(eval PROJECT_VERSION := $(shell cat $(RELEASE_FILE) | jq -r .version))
git tag -a v$(PROJECT_VERSION) -m "Version $(PROJECT_VERSION)"
## tag repository with next minor version
tag-minor-version: next-minor-version
echo "Tagging minor version"
$(eval PROJECT_VERSION := $(shell cat $(RELEASE_FILE) | jq -r .version))
git tag -a v$(PROJECT_VERSION) -m "Version $(PROJECT_VERSION)"
## tag repository with next major version
tag-major-version: next-major-version
echo "Tagging major version"
$(eval PROJECT_VERSION := $(shell cat $(RELEASE_FILE) | jq -r .version))
git tag -a v$(PROJECT_VERSION) -m "Version $(PROJECT_VERSION)"
GO_MOD_FILE := $(SOURCE_PATH)go.mod
ifeq ($(shell test -e $(GO_MOD_FILE) && echo -n yes),yes)
GO_CURRENT_MODULE := $(shell cat $(GO_MOD_FILE) | head -n1 | cut -d" " -f2)
# go install github.com/google/go-licenses@latest
EXECUTABLES = $(EXECUTABLES:-) go-licenses;
endif
.PHONY: fetch-licenses
## Fetch licenses for all modules
fetch-licenses:
go-licenses save $(GO_CURRENT_MODULE) --ignore gitlab.schukai.com --force --save_path $(PROJECT_ROOT)licenses/ ; cd -
# Configuration ## Configuration
## Installation
```shell
go get gitlab.schukai.com/oss/libraries/go/application/configuration
```
**Note:** This library uses [Go Modules](https://github.com/golang/go/wiki/Modules) to manage dependencies.
## What do this library?
This library provides a simple way to load configuration from different sources.
It supports:
* [x] Environment variables
* [x] Command line flags
* [x] Configuration files
* [x] JSON
* [x] YAML
* [x] TOML
* [x] Properties
* [x] Configuration from a struct
* [x] HTTP API (get and set configuration)
## Usage
### Initialize
A new configuration is created using the `configuration.New()` function. The passed
structure is used type for the configuration. The values are taken as default values
of the configuration.
```go
package main
import (
"fmt"
"os"
"gitlab.schukai.com/oss/libraries/go/application/configuration"
)
func main(){
config := struct {
Host string
Port int
}{
Host: "localhost",
Port: 8080,
}
c := configuration.New(config)
fmt.Println(c.Config().Host)
fmt.Println(c.Config().Port)
}
```
Configuration values can come from different sources. The order of
sources is important.
#### Environment variables
With the `Environment` function, you can load configuration from environment variables.
```go
package main
import (
"fmt"
"os"
"gitlab.schukai.com/oss/libraries/go/application/configuration"
)
## Getting started func main(){
config := struct {
Host string `env:"HOST"`
}{
Host: "localhost",
}
To make it easy for you to get started with GitLab, here's a list of recommended next steps. // Set value
os.Setenv("HOST", "www.example.com")
Already a pro? Just edit this README.md and make it your own. Want to make it easy? [Use the template at the bottom](#editing-this-readme)! s := configuration.New(config)
fmt.Println(s.Config().Host) // localhost
## Add your files s.InitFromEnv("") // no prefix
fmt.Println(s.Config().Host) // www.example.com
- [ ] [Create](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#create-a-file) or [upload](https://docs.gitlab.com/ee/user/project/repository/web_editor.html#upload-a-file) files }
- [ ] [Add files using the command line](https://docs.gitlab.com/ee/gitlab-basics/add-file.html#add-a-file-using-the-command-line) or push an existing Git repository with the following command:
``` ```
cd existing_repo
git remote add origin https://gitlab.schukai.com/oss/libraries/go/application/configuration.git #### Command line flags
git branch -M master
git push -uf origin master Obviously, you can also load configuration from command line flags. This library supports
the standard library [flag](https://golang.org/pkg/flag/) package.
```go
package main
import (
"fmt"
"os"
"flag"
"gitlab.schukai.com/oss/libraries/go/application/configuration"
)
func main(){
config := struct {
Host string `flag:"host"`
}{
Host: "localhost",
}
// Set value
flag.String("host", "www.example.com", "help message for host flag")
flag.Parse()
s := configuration.New(config)
s.InitFromFlagSet(flag.CommandLine)
fmt.Println(s.Config().Host) // www.example.com
}
``` ```
## Integrate with your tools Do you want to allow the user to specify a configuration via the command line,
so you can use the `AddFileFromFlagSet` function. This function expects a `flag.FlagSet`.
- [ ] [Set up project integrations](https://gitlab.schukai.com/oss/libraries/go/application/configuration/-/settings/integrations)
## Collaborate with your team ### Import files and streams
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/) You can load configuration from files and streams. With the `Import()` function you
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html) import files and streams. The specified files are loaded first, and then the
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically) streams.
- [ ] [Enable merge request approvals](https://docs.gitlab.com/ee/user/project/merge_requests/approvals/)
- [ ] [Automatically merge when pipeline succeeds](https://docs.gitlab.com/ee/user/project/merge_requests/merge_when_pipeline_succeeds.html)
## Test and Deploy The configurations are merged. If a value is already set, it is overwritten by the
specified value. So if a value is set in `etc` and in the more specific
File in the user home directory, the value is taken from the user home directory.
Use the built-in continuous integration in GitLab. ```go
package main
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) import (
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/) "fmt"
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html) "os"
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/) "flag"
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html) "gitlab.schukai.com/oss/libraries/go/application/configuration"
)
*** func main() {
# Editing this README config := struct {
Host string
}{
Host: "localhost",
}
When you're ready to make this README your own, just edit this file and use the handy template below (or feel free to structure it however you want - this is just a starting point!). Thank you to [makeareadme.com](https://www.makeareadme.com/) for this template. c := configuration.New(config)
## Suggestions for a good README c.SetMnemonic("my-app")
Every project is different, so consider which of these sections apply to yours. The sections used in the template are suggestions for most open source projects. Also keep in mind that while a README can be too long and detailed, too long is better than too short. If you think your README is too long, consider utilizing another form of documentation rather than cutting out information. c.SetDefaultDirectories()
c.Import()
## Name fmt.Println(c.Config().Host)
Choose a self-explaining name for your project.
## Description }
Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
## Badges
On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
## Visuals ```
Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
## Installation The configuration would then be looked for in the following places:
Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
## Usage * ~/config.yaml (working directory)
Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README. * ~/.config/my-app/config.yaml
* /etc/my-app/config.yaml
## Support #### Configuration files
Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
## Roadmap Configuration files are certainly the most common way to define configurations.
If you have ideas for releases in the future, it is a good idea to list them in the README. These can be in different formats. The following formats are currently supported:
JSON, YAML, TOML and Properties.
## Contributing With files, the approach is slightly different. Here the function `AddDirectory()`
State if you are open to contributions and what your requirements are for accepting them. first, specify directories in which to search for the file. The file
is then searched for in the order of the directories. If the file is found
is loaded.
The helper function `AddWorkingDirectory()` adds the current working directory.
With `AddEtcDirectory()` the directory `etc` is added under Unix.
`AddUserConfigDirectory()` adds the directory `~.config` on Unix. It will
uses the `os.UserConfigDir()` method. Thus, it is possible to use the directory
can also be used on other operating systems.
The `SetDefaultDirectories()` method sets the paths to the default values. Become internal
the paths with `AddWorkingDirectory()`, `AddEtcDirectory()` and `AddUserConfigDirectory()`
set.
The directory structure can be specified directly with the `SetDirectories()` function.
This overwrites the directory structure specified with `AddDirectory()`.
The filename of the configuration file is specified with `SetFileName()`. The file name
is searched for with the extension `.json`, `.yaml`, `.yml`, `.toml` or `.properties`.
If a format is specified with the `SetFileFormat()` method, only files with
searched for this ending.
As an extra, you can specify your own file system with `SetFilesystem()`.
This is useful for testing.
Furthermore, the `AddFile()` function can be used to add a file directly.
This makes sense if you are given a file as a parameter
or if you don't want to have a multi-level structure.
**Watch files**
For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self. If you want to watch configuration files for changes, you can use the `Watch()` function.
With the function `StopWatch()` you can stop watching the files. The function
returns a bool channel on which the status of the watch is reported.
If the watch has ended, a true is sent over the channel. If an error occurs, a false is sent.
```go
#### Streams
The configuration can also be loaded from a stream. This is useful if you want to
load the configuration from other sources. For example, from a database.
With the `AddReader()` function, you can add a stream to the configuration. The
stream is then searched for in the order of the streams. If the stream is found
is loaded.
### HTTP API
The configuration can also be changed via HTTP. This is useful if you want to
change the configuration at runtime. For example, if you would like to change the
configuration of a service.
With a Get request, the configuration is returned as the format specified in the
`Accept` header. If no format is specified, the configuration is returned in JSON format.
With a Post request, the configuration can be changed. The configuration is then
taken from the body of the request. The format is determined by the `Content-Type`
header. If no format is specified, the configuration is taken from the JSON format.
```go
config := struct {
Host string
}
s := New(config)
mux := http.NewServeMux()
mux.HandleFunc("/config", s.ServeHTTP)
```
There is also a middleware to get access to the configuration.
```go
config := struct {
Host string
}
s := New(config)
mux := http.NewServeMux()
mux.Use(s.Middleware)
```
The configuration can then be accessed via the `config` context.
```go
func handler(w http.ResponseWriter, r *http.Request) {
config := r.Context().Value("config").(struct {
Host string
})
fmt.Println(config.Host)
}
```
### On change
If you want to be notified when the configuration changes, you can use the
`OnChange()` function. This function takes a callback function as a parameter.
The following program gives the following output `Change from localhost to www.example.com`.
```go
package main
import (
"fmt"
"os"
"flag"
"gitlab.schukai.com/oss/libraries/go/application/configuration"
)
func main() {
config := struct {
Host string
}{
Host: "localhost",
}
s := configuration.New(config)
closeChan := make(chan bool)
s.OnChange(func(event configuration.ChangeEvent) {
log := event.Changlog
msg := fmt.Sprintf("Change from %s to %s", log[0].From, log[0].To)
fmt.Println(msg)
closeChan <- true
})
c := s.Config()
c.Host = "www.example.com"
s.SetConfig(c)
// Wait for change
select {
case <-closeChan:
}
}
```
### Error handling
If an error occurs, it is returned by the function `Errors()`. The errors can be handled as usual.
The `HasErrors()` function can be used to check whether errors have occurred.
## Change Log
### 1.0.0
* Initial release
## Contributing
You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser. Merge requests are welcome. For major changes, please open an issue first to discuss what
you would like to change.
## Authors and acknowledgment Please make sure to update tests as appropriate.
Show your appreciation to those who have contributed to the project.
## License ## License
For open source projects, say how it is licensed.
## Project status [AGPL-3.0](https://choosealicense.com/licenses/agpl-3.0/)
If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers. \ No newline at end of file
api.go 0 → 100644
package configuration
import "github.com/imdario/mergo"
// NewSetting creates a new configuration setting
// with the given defaults.
func New[C any](defaults C) *setting[C] {
s := &setting[C]{}
s.initDefaults()
if err := mergo.Merge(&defaults, s.config); err != nil {
s.errors = append(s.errors, err)
}
s.config = defaults
err := validateConfig[C](defaults)
if err != nil {
s.errors = append(s.errors, err)
var r C
s.config = r
}
initFileBackend(&s.files)
return s
}
// Set the mnemonic
// The mnemonic is used to identify the configuration in the configuration file
func (s *setting[C]) SetMnemonic(mnemonic string) *setting[C] {
if mnemonic == "" {
s.errors = append(s.errors, MnemonicEmptyError)
} else {
s.mnemonic = mnemonic
}
return s
}
// Check if the setting contains errors
func (s *setting[C]) HasError() bool {
return len(s.errors) > 0
}
// Get all errors
func (s *setting[C]) Errors() []error {
return s.errors
}
// Config() returns the configuration
func (s *setting[C]) Config() C {
return s.config
}
package configuration
import (
"github.com/magiconair/properties/assert"
"testing"
)
// Example for README
// Print are commented out because they are only for demonstration
func TestReadExample1(t *testing.T) {
config := struct {
Host string
Port int
}{
Host: "localhost",
Port: 8080,
}
c := New(config)
//fmt.Println(c.Config().Host)
//fmt.Println(c.Config().Port)
assert.Equal(t, c.Config().Host, "localhost")
assert.Equal(t, c.Config().Port, 8080)
}
func TestNew(t *testing.T) {
var config ConfigStruct2
s := New(config)
if s == nil {
t.Error("Expected not nil")
}
}
func TestNewWithDefaults(t *testing.T) {
var config ConfigStruct2
s := New(config)
if s == nil {
t.Error("Expected not nil")
}
// use external api to read the value
if s.Config().H.HA != 1 {
t.Error("Expected 1")
}
// use internal api to read the value
if s.config.H.HB != "yes" {
t.Error("Expected yes")
}
if s.config.H.HC != true {
t.Error("Expected true")
}
if s.config.H.HD != false {
t.Error("Expected false")
}
}
package configuration
import (
"bytes"
"testing"
)
func BenchmarkCreateConfig(b *testing.B) {
// run the Fib function b.N times
for n := 0; n < b.N; n++ {
config := ConfigStruct2{
A: "1",
B: true,
F: 2,
}
s := New(config)
buffer := bytes.NewBufferString("")
s.Write(buffer, Yaml)
}
}
package configuration
import (
"github.com/r3labs/diff/v3"
)
type ChangeEvent struct {
Changlog diff.Changelog
}
type EventHook func(event ChangeEvent)
func (s *setting[C]) OnChange(hook EventHook) *setting[C] {
s.hooks.change = append(s.hooks.change, hook)
return s
}
func (s *setting[C]) notifyChangeHooks(changelog diff.Changelog) *setting[C] {
for _, h := range s.hooks.change {
h(ChangeEvent{Changlog: changelog})
}
return s
}
func (s *setting[C]) setConfigInternal(config C, lock bool) *setting[C] {
var (
changelog diff.Changelog
err error
)
if lock {
s.Lock()
}
defer func() {
if lock {
s.Unlock()
}
if len(changelog) > 0 {
go s.notifyChangeHooks(changelog)
}
}()
if err := validateConfig[C](config); err != nil {
s.errors = append(s.errors, err)
return s
}
d, err := diff.NewDiffer()
if err != nil {
s.errors = append(s.errors, err)
return s
}
d.ConvertCompatibleTypes = true
d.AllowTypeMismatch = true
changelog, err = d.Diff(s.config, config)
if err != nil {
s.errors = append(s.errors, err)
return s
}
s.config = config
return s
}
func (s *setting[C]) SetConfig(config C) *setting[C] {
return s.setConfigInternal(config, true)
}
package configuration
import (
"bytes"
"fmt"
"io"
"testing"
"time"
)
func TestReadmeExample(t *testing.T) {
config := struct {
Host string
}{
Host: "localhost",
}
s := New(config)
closeChan := make(chan bool)
msg := ""
s.OnChange(func(event ChangeEvent) {
log := event.Changlog
msg = fmt.Sprintf("Change from %s to %s", log[0].From, log[0].To)
// for Readme
//fmt.Println(msg)
closeChan <- true
})
c := s.Config()
c.Host = "www.example.com"
s.SetConfig(c)
// Wait for change
select {
case <-closeChan:
case <-time.After(time.Second):
t.Fatalf("Timeout")
}
if msg != "Change from localhost to www.example.com" {
t.Error("Expected \"Change from localhost to www.example.com\" got ", msg)
}
}
func TestCangeOnChange(t *testing.T) {
defaults := ConfigStruct2{
A: "",
B: false,
C: nil,
D: nil,
F: 0,
G: "",
}
s := New(defaults)
s.SetMnemonic("test")
var buf bytes.Buffer
buf.WriteString("A: a\n")
r := (io.Reader)(&buf)
s.AddReader(r, Yaml)
s.Import()
if s.HasError() {
t.Error("Expected not error", s.Errors())
}
c := s.Config()
if c.A != "a" {
t.Error("Expected \"a\" got ", c)
}
closeChan := make(chan bool)
counter := 0
s.OnChange(func(event ChangeEvent) {
counter++
closeChan <- true
})
c.A = "b"
s.SetConfig(c)
select {
case <-closeChan:
case <-time.After(time.Second):
t.Fatalf("Timeout")
}
if counter != 1 {
t.Error("Expected 1 got ", counter)
}
}
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="Go" enabled="true" />
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
package configuration
const fileName = "config"
const contextKey = "config"
const envTagKey = "env"
const flagTagKey = "flag"
env.go 0 → 100644
package configuration
import (
"os"
"reflect"
"strconv"
)
func (s *setting[C]) InitFromEnv(prefix string) *setting[C] {
s.Lock()
defer s.Unlock()
err := runOnTags(&s.config, []string{envTagKey}, func(k string, field reflect.Value) {
if !field.CanSet() {
return
}
v, found := os.LookupEnv(k)
if !found {
return // env not found
}
t := reflect.TypeOf(v)
switch field.Kind() {
case reflect.String:
field.SetString(v)
case reflect.Int:
intVar, err := strconv.Atoi(v)
if err != nil {
s.errors = append(s.errors, err)
return
}
field.SetInt(int64(intVar))
case reflect.Bool:
field.SetBool(v == "true")
default:
s.errors = append(s.errors, newMismatchedTypeError(t, field.Type()))
}
})
if err != nil {
s.errors = append(s.errors, err)
}
return s
}
package configuration
import (
"github.com/magiconair/properties/assert"
"os"
"testing"
)
// Example for README
// Print are commented out because they are only for demonstration
func TestReadmeExample2(t *testing.T) {
config := struct {
Host string `env:"HOST"`
}{
Host: "localhost",
}
// Set value
os.Setenv("HOST", "www.example.com")
s := New(config)
//fmt.Println(s.Config().Host) // localhost
assert.Equal(t, s.Config().Host, "localhost")
s.InitFromEnv("") // no prefix
//fmt.Println(s.Config().Host) // www.example.com
assert.Equal(t, s.Config().Host, "www.example.com")
}
func TestFromEnvNotSet(t *testing.T) {
config := ConfigStruct6{
IA: 1234,
IB: "no",
IC: false,
ID: true,
}
s := New(config)
// Value not set
s.InitFromEnv("VALUE_IB")
if s.Config().IA != 1234 {
t.Errorf("Expected 1234, got %d", s.Config().IA)
}
}
func TestFromEnv(t *testing.T) {
config := ConfigStruct6{
IA: 1234,
IB: "no",
IC: false,
ID: true,
}
s := New(config)
// Value not set
s.InitFromEnv("VALUE_IB")
if s.Config().IA != 1234 {
t.Errorf("Expected 1234, got %d", s.Config().IA)
}
// Set value
os.Setenv("VALUE_IB", "i-am-b")
s.InitFromEnv("VALUE_IB")
if s.Config().IB != "i-am-b" {
t.Errorf("Expected i-am-b, got %s", s.Config().IB)
}
}
error.go 0 → 100644
package configuration
import (
"errors"
"reflect"
)
var FileNameEmptyError = errors.New("file name is empty")
var MnemonicEmptyError = errors.New("mnemonic is empty")
var NoFileImportedError = errors.New("no file imported")
var NoFilesToWatchError = errors.New("no files to watch")
var WatchAlreadyInitializedError = errors.New("watch already initialized")
var WatchAlreadyRunningError = errors.New("watch already running")
var WatchNotInitializedError = errors.New("watch not initialized")
var WatchNotRunningError = errors.New("watch not running")
var WatchListNotInitializedError = errors.New("watch list not initialized")
type FlagDoesNotExistError error
func newFlagDoesNotExistError(flag string) FlagDoesNotExistError {
return FlagDoesNotExistError(errors.New("flag " + flag + " does not exist"))
}
// PathAlreadyExistsError is returned when a files already exists
type PathAlreadyExistsError error
func newPathAlreadyExistsError(path string) PathAlreadyExistsError {
return PathAlreadyExistsError(errors.New("files " + path + " already exists"))
}
// PathDoesNotExistError is returned when a files does not exist
type PathDoesNotExistError error
func newPathDoesNotExistError(path string) PathDoesNotExistError {
return PathDoesNotExistError(errors.New("files " + path + " does not exist"))
}
// FormatNotSupportedError is returned when the format is not supported
type FormatNotSupportedError error
func newFormatNotSupportedError(format Format) FormatNotSupportedError {
return FormatNotSupportedError(errors.New("format " + format.String() + " is not supported"))
}
// UnsupportedTypeError is returned when the type is not supported
type UnsupportedTypeError error
func newUnsupportedTypeError(t reflect.Type) UnsupportedTypeError {
return UnsupportedTypeError(errors.New("type " + t.String() + " is not supported"))
}
// ResetError is used to reset the error to nil
// After calling this function, the call HasError() will return false
func (s *setting[C]) ResetErrors() *setting[C] {
s.errors = []error{}
return s
}
// At the reflect level, some types are not supported
type UnsupportedReflectKindError error
func newUnsupportedReflectKindError(t reflect.Type) UnsupportedTypeError {
return UnsupportedReflectKindError(errors.New("type " + t.String() + " is not supported"))
}
// This error indicates that the flag is not found
type FlagNotFoundError error
func newFlagNotFoundError(name string) FlagNotFoundError {
return FlagNotFoundError(errors.New("flag " + name + " not found"))
}
// MismatchedTypeError is used to indicate that the type is not matching
type MismatchedTypeError error
func newMismatchedTypeError(expected, actual reflect.Type) MismatchedTypeError {
return MismatchedTypeError(errors.New("expected type " + expected.String() + " but got " + actual.String()))
}
package configuration
import (
"encoding/json"
"github.com/magiconair/properties"
"io"
"os"
"github.com/pelletier/go-toml/v2"
"gopkg.in/yaml.v3"
)
func (s *setting[C]) Export() *setting[C] {
return s
}
func (s *setting[C]) writeJson(writer io.Writer) error {
encoder := json.NewEncoder(writer)
return encoder.Encode(s.config)
}
func (s *setting[C]) writeYaml(writer io.Writer) error {
encoder := yaml.NewEncoder(writer)
return encoder.Encode(s.config)
}
func (s *setting[C]) writeToml(writer io.Writer) error {
encoder := toml.NewEncoder(writer)
return encoder.Encode(s.config)
}
func (s *setting[C]) writeProperties(writer io.Writer) error {
m, errors := getMapForProperties[C](s.config)
if len(errors) > 0 {
for _, err := range errors {
s.errors = append(s.errors, err)
}
}
p := properties.LoadMap(m)
_, err := p.Write(writer, properties.UTF8)
return err
}
func (s *setting[C]) WriteFile(fn string, format Format) *setting[C] {
var err error
var file *os.File
if fn == "" {
file = os.Stdout
} else {
file, err = os.Create(fn)
if err != nil {
s.errors = append(s.errors, err)
return s
}
}
defer file.Close()
s.Write(io.Writer(file), format)
return s
}
func (s *setting[C]) Write(writer io.Writer, format Format) *setting[C] {
var err error
switch format {
case Json:
err = s.writeJson(writer)
case Yaml:
err = s.writeYaml(writer)
case Toml:
err = s.writeToml(writer)
case Properties:
err = s.writeProperties(writer)
default:
err = newFormatNotSupportedError(format)
}
if err != nil {
s.errors = append(s.errors, err)
}
return s
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment