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

feat takeover from other project

parent b1fd703c
No related branches found
No related tags found
No related merge requests found
{{ range .Versions }}
<a name="{{ .Tag.Name }}"></a>
## {{ if .Tag.Previous }}[{{ .Tag.Name }}]{{ else }}{{ .Tag.Name }}{{ end }} - {{ datetime "2006-01-02" .Tag.Date }}
{{ range .CommitGroups -}}
### {{ .Title }}
{{ range .Commits -}}
- {{ if .Scope }}**{{ .Scope }}:** {{ end }}{{ .Subject }}
{{ end }}
{{ end -}}
{{- if .NoteGroups -}}
{{ range .NoteGroups -}}
### {{ .Title }}
{{ range .Notes }}
{{ .Body }}
{{ end }}
{{ end -}}
{{ end -}}
{{ end -}}
{{- if .Versions }}
{{ range .Versions -}}
{{ if .Tag.Previous -}}
[{{ .Tag.Name }}]: {{ $.Info.RepositoryURL }}/compare/{{ .Tag.Previous.Name }}...{{ .Tag.Name }}
{{ end -}}
{{ end -}}
{{ end -}}
\ No newline at end of file
style: gitlab
template: CHANGELOG.tpl.md
info:
title: CHANGELOG
repository_url: https://gitlab.schukai.com/oss/libraries/go/utilities/pathfinder
options:
commits:
filters:
Type:
- feat
- fix
- doc
- refactor
- perf
- test
- chore
## deprecated types and typos
- docs
- documentation
- feat
- added
- add
- bugfix
- revert
- update
- updates
- change
- changed
commit_groups:
title_maps:
feat: Add Features
fix: Bug Fixes
doc: Documentation
refactor: Code Refactoring
perf: Performance Improvements
test: Tests
## Chore is used for all other changes that don't fit in the other categories
chore: Changes
## deprecated types and typos
docs: Documentation
documentation: Documentation
added: Add Features
add: Add Features
bugfix: Bug Fixes
revert: Reverts
update: Changes
updates: Changes
change: Changes
changed: Changes
header:
pattern: "^((\\w+)\\s.*)$"
pattern_maps:
- Subject
- Type
notes:
keywords:
- BREAKING CHANGE
# 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
testdata/
# Dependency directories (remove the comment below to include it)
# vendor/
# Go workspace file
go.work
# Go Fuzz build
testdata/
### 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
LICENSE 0 → 100644
This diff is collapsed.
Makefile 0 → 100644
## Copyright 2022 schukai GmbH. All rights reserved.
## Use of this source code is governed by a AGPL-3.0
## license that can be found in the LICENSE file.
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
GIT_CHGLOG_BIN := $(shell command -v git-chglog 2> /dev/null)
ifeq ($(GIT_CHGLOG_BIN),)
$(shell go install github.com/git-chglog/git-chglog/cmd/git-chglog@latest)
endif
RELEASE_FILE ?= $(PROJECT_ROOT)release.json
CHANGELOG_FILE ?= $(PROJECT_ROOT)CHANGELOG.md
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
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
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
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-chglog --next-tag v$(PROJECT_VERSION) -o $(CHANGELOG_FILE)
git add $(CHANGELOG_FILE) && git commit -m "Update changelog"
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-chglog --next-tag v$(PROJECT_VERSION) -o $(CHANGELOG_FILE)
git add $(CHANGELOG_FILE) && git commit -m "Update changelog"
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-chglog --next-tag v$(PROJECT_VERSION) -o $(CHANGELOG_FILE)
git add $(CHANGELOG_FILE) && git commit -m "Update changelog"
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/
# https://spdx.github.io/spdx-spec/v2.3/SPDX-license-list/
ADDLICENSE_BIN ?= addlicense
ifeq ($(shell command -v $(ADDLICENSE_BIN) 2> /dev/null),)
$(shell go install github.com/google/addlicense@latest)
EXECUTABLES = $(EXECUTABLES:-) $(ADDLICENSE_BIN);
endif
.PHONY: add-licenses
## Add license headers to all go files
add-licenses:
addlicense -c "schukai GmbH" -s -l "AGPL-3.0" ./*.go
# Pathfinder ## Pathfinder
## What does this library?
This library provides a simple way to get and set values in a nested structure.
## Getting started It supports:
To make it easy for you to get started with GitLab, here's a list of recommended next steps. * [X] Set values in a nested structure
* [X] Get values from a nested structure
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)! ## Installation
## Add your files
- [ ] [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:
```shell
go get gitlab.schukai.com/oss/libraries/go/utilities/pathfinder
``` ```
cd existing_repo
git remote add origin https://gitlab.schukai.com/oss/libraries/go/utilities/pathfinder.git
git branch -M master
git push -uf origin master
```
## Integrate with your tools
- [ ] [Set up project integrations](https://gitlab.schukai.com/oss/libraries/go/utilities/pathfinder/-/settings/integrations)
## Collaborate with your team
- [ ] [Invite team members and collaborators](https://docs.gitlab.com/ee/user/project/members/)
- [ ] [Create a new merge request](https://docs.gitlab.com/ee/user/project/merge_requests/creating_merge_requests.html)
- [ ] [Automatically close issues from merge requests](https://docs.gitlab.com/ee/user/project/issues/managing_issues.html#closing-issues-automatically)
- [ ] [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
Use the built-in continuous integration in GitLab.
- [ ] [Get started with GitLab CI/CD](https://docs.gitlab.com/ee/ci/quick_start/index.html) **Note:** This library uses [Go Modules](https://github.com/golang/go/wiki/Modules) to manage dependencies.
- [ ] [Analyze your code for known vulnerabilities with Static Application Security Testing(SAST)](https://docs.gitlab.com/ee/user/application_security/sast/)
- [ ] [Deploy to Kubernetes, Amazon EC2, or Amazon ECS using Auto Deploy](https://docs.gitlab.com/ee/topics/autodevops/requirements.html)
- [ ] [Use pull-based deployments for improved Kubernetes management](https://docs.gitlab.com/ee/user/clusters/agent/)
- [ ] [Set up protected environments](https://docs.gitlab.com/ee/ci/environments/protected_environments.html)
*** ## Usage
# Editing this README
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.
## Suggestions for a good README
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.
## Name
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 ## Contributing
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 Merge requests are welcome. For major changes, please open an issue first to discuss what
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. you would like to change. **Please make sure to update tests as appropriate.**
## Usage Versioning is done with [SemVer](https://semver.org/).
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. Changelog is generated with [git-chglog](https://github.com/git-chglog/git-chglog#git-chglog)
## Support Commit messages should follow the [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) specification.
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. Messages are started with a type, which is one of the following:
## Roadmap - **feat**: A new feature
If you have ideas for releases in the future, it is a good idea to list them in the README. - **fix**: A bug fix
- **doc**: Documentation only changes
- **refactor**: A code change that neither fixes a bug nor adds a feature
- **perf**: A code change that improves performance
- **test**: Adding missing or correcting existing tests
- **chore**: Other changes that don't modify src or test files
## Contributing The footer would be used for a reference to an issue or a breaking change.
State if you are open to contributions and what your requirements are for accepting them.
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. A commit that has a footer `BREAKING CHANGE:`, or appends a ! after the type/scope,
introduces a breaking API change (correlating with MAJOR in semantic versioning).
A BREAKING CHANGE can be part of commits of any type.
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. the following is an example of a commit message:
## Authors and acknowledgment ```text
Show your appreciation to those who have contributed to the project. feat: add 'extras' field
```
## 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.
error.go 0 → 100644
// Copyright 2022 schukai GmbH
// SPDX-License-Identifier: AGPL-3.0
package pathfinder
import (
"errors"
"reflect"
)
type InvalidPathError error
func newInvalidPathError(path string) InvalidPathError {
return InvalidPathError(errors.New("invalid path " + path))
}
type UnsupportedTypeAtTopOfPathError error
func newUnsupportedTypeAtTopOfPathError(path string, t reflect.Type) UnsupportedTypeAtTopOfPathError {
return UnsupportedTypeAtTopOfPathError(errors.New("unsupported type " + t.String() + " at top of path " + path))
}
type UnsupportedTypePathError error
func newUnsupportedTypePathError(path string, t reflect.Type) UnsupportedTypePathError {
return UnsupportedTypePathError(errors.New("unsupported type " + t.String() + " at path " + path))
}
type CannotSetError error
func newCannotSetError(name string) CannotSetError {
return CannotSetError(errors.New("cannot set " + name))
}
type InvalidTypeForPathError error
func newInvalidTypeForPathError(path string, pt string, nt string) InvalidTypeForPathError {
return InvalidTypeForPathError(errors.New("invalid type for path " + path + ": expected " + pt + ", got " + nt))
}
// Copyright 2022 schukai GmbH
// SPDX-License-Identifier: AGPL-3.0
package pathfinder
import (
"github.com/stretchr/testify/assert"
"reflect"
"testing"
)
func TestInvalidPathError(t *testing.T) {
err := newInvalidPathError("test")
_, ok := err.(InvalidPathError)
assert.True(t, ok)
}
func TestUnsupportedTypeAtTopOfPathError(t *testing.T) {
err := newUnsupportedTypeAtTopOfPathError("test", reflect.TypeOf(1))
_, ok := err.(UnsupportedTypeAtTopOfPathError)
assert.True(t, ok)
}
func TestUnsupportedTypePathError(t *testing.T) {
err := newUnsupportedTypePathError("test", reflect.TypeOf(1))
_, ok := err.(UnsupportedTypePathError)
assert.True(t, ok)
}
func TestCannotSetError(t *testing.T) {
err := newCannotSetError("test")
_, ok := err.(CannotSetError)
assert.True(t, ok)
}
func TestInvalidTypeForPathError(t *testing.T) {
err := newInvalidTypeForPathError("test", "test", "test")
_, ok := err.(InvalidTypeForPathError)
assert.True(t, ok)
}
go.mod 0 → 100644
module gitlab.schukai.com/oss/libraries/go/utilities/pathfinder
go 1.19
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/stretchr/testify v1.8.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
// Copyright 2022 schukai GmbH
// SPDX-License-Identifier: AGPL-3.0
package pathfinder
import (
"fmt"
"reflect"
"strconv"
"strings"
)
// This function returns the value of a field in a struct, given a path to the field.
func GetValueFrom[D any](obj D, keyWithDots string) (any, error) {
keySlice := strings.Split(keyWithDots, ".")
v := reflect.ValueOf(obj)
for _, key := range keySlice[0 : len(keySlice)-1] {
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
if v.Kind() != reflect.Struct {
return nil, newUnsupportedTypePathError(keyWithDots, v.Type())
}
v = v.FieldByName(key)
}
if v.Kind() == reflect.Invalid {
return nil, newInvalidPathError(keyWithDots)
}
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
// non-supporter type at the top of the path
if v.Kind() != reflect.Struct {
return nil, newUnsupportedTypeAtTopOfPathError(keyWithDots, v.Type())
}
v = v.FieldByName(keySlice[len(keySlice)-1])
if !v.IsValid() {
return nil, newInvalidPathError(keyWithDots)
}
return v.Interface(), nil
}
// This function sets the value of a field in a struct, given a path to the field.
func SetValueUsingPath[D any](obj D, keyWithDots string, newValue any) error {
keySlice := strings.Split(keyWithDots, ".")
v := reflect.ValueOf(obj)
for _, key := range keySlice[0 : len(keySlice)-1] {
for v.Kind() != reflect.Ptr {
v = v.Addr()
}
if v.Kind() != reflect.Ptr {
return newUnsupportedTypePathError(keyWithDots, v.Type())
}
elem := v.Elem()
if elem.Kind() != reflect.Struct {
return newUnsupportedTypePathError(keyWithDots, v.Type())
}
v = elem.FieldByName(key)
}
if v.Kind() == reflect.Invalid {
return newInvalidPathError(keyWithDots)
}
for v.Kind() == reflect.Ptr {
v = v.Elem()
}
// non-supporter type at the top of the path
if v.Kind() != reflect.Struct {
return newUnsupportedTypeAtTopOfPathError(keyWithDots, v.Type())
}
v = v.FieldByName(keySlice[len(keySlice)-1])
if !v.IsValid() {
return newInvalidPathError(keyWithDots)
}
if !v.CanSet() {
return newCannotSetError(keyWithDots)
}
switch v.Kind() {
case reflect.Ptr:
if newValue == nil {
v.Set(reflect.Zero(v.Type()))
} else {
v.Set(reflect.ValueOf(&newValue))
}
return nil
}
newValueType := reflect.TypeOf(newValue)
if newValueType == nil {
return newUnsupportedTypePathError(keyWithDots, v.Type())
}
newValueKind := reflect.TypeOf(newValue).Kind()
switch v.Kind() {
case reflect.String:
if newValueKind == reflect.String {
v.SetString(newValue.(string))
} else {
v.SetString(fmt.Sprintf("%v", newValue))
}
case reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Int:
if newValueKind == reflect.Int {
v.SetInt(int64(newValue.(int)))
} else {
s, err := strconv.ParseInt(newValue.(string), 10, 64)
if err != nil {
return err
}
v.SetInt(s)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if newValueKind == reflect.Int {
v.SetUint(uint64(newValue.(int)))
} else {
s, err := strconv.ParseInt(newValue.(string), 10, 64)
if err != nil {
return err
}
v.SetUint(uint64(s))
}
case reflect.Bool:
if newValueKind == reflect.Bool {
v.SetBool(newValue.(bool))
} else {
b, err := strconv.ParseBool(newValue.(string))
if err != nil {
return err
}
v.SetBool(b)
}
case reflect.Float64, reflect.Float32:
if newValueKind == reflect.Float64 {
v.SetFloat(newValue.(float64))
} else {
s, err := strconv.ParseFloat(newValue.(string), 64)
if err != nil {
return err
}
v.SetFloat(s)
}
default:
return newInvalidTypeForPathError(keyWithDots, v.Type().String(), newValueKind.String())
}
return nil
}
// Copyright 2022 schukai GmbH
// SPDX-License-Identifier: AGPL-3.0
package pathfinder
import "testing"
type PathfindTestStruct1 struct {
A bool
Sub1 struct {
B bool
Bi int
Bs string
Bf float64
Sub2 struct {
C bool
Ci int
Cs string
Cf float64
Sub3 struct {
D bool
Di int
Ds string
Df float64
}
}
}
}
func TestPathFindError(t *testing.T) {
s := PathfindTestStruct1{}
_, err := GetValueFrom[PathfindTestStruct1](s, "Sub1.Sub2.Sub3.XX")
if err == nil {
t.Error("err == nil")
}
}
func TestPathFindSetValueString(t *testing.T) {
testData := map[string]string{
"Sub1.B": "true",
"Sub1.Bi": "2",
"Sub1.Bs": "3",
"Sub1.Bf": "4.0",
"Sub1.Sub2.C": "true",
"Sub1.Sub2.Ci": "2",
"Sub1.Sub2.Cs": "3",
"Sub1.Sub2.Cf": "4.0",
"Sub1.Sub2.Sub3.D": "true",
"Sub1.Sub2.Sub3.Di": "2",
"Sub1.Sub2.Sub3.Ds": "3",
"Sub1.Sub2.Sub3.Df": "4.0",
}
for k, v := range testData {
s := &PathfindTestStruct1{}
err := SetValueUsingPath[*PathfindTestStruct1](s, k, v)
if err != nil {
t.Error(err)
}
}
}
func TestPathFindGetValueFrom(t *testing.T) {
s := PathfindTestStruct1{}
s.Sub1.B = true
s.Sub1.Bi = 2
s.Sub1.Bs = "3"
s.Sub1.Bf = 4.0
v, err := GetValueFrom[PathfindTestStruct1](s, "Sub1.B")
if err != nil {
t.Error(err)
}
if v != true {
t.Error("v != true")
}
v, err = GetValueFrom[PathfindTestStruct1](s, "Sub1.Bi")
if err != nil {
t.Error(err)
}
if v != 2 {
t.Error("v != 2")
}
v, err = GetValueFrom[PathfindTestStruct1](s, "Sub1.Bs")
if err != nil {
t.Error(err)
}
if v != "3" {
t.Error("v != 3")
}
v, err = GetValueFrom[PathfindTestStruct1](s, "Sub1.Bf")
if err != nil {
t.Error(err)
}
if v != 4.0 {
t.Error("v != 4.0")
}
s.Sub1.Sub2.C = true
s.Sub1.Sub2.Ci = 2
s.Sub1.Sub2.Cs = "3"
s.Sub1.Sub2.Cf = 4.0
v, err = GetValueFrom[PathfindTestStruct1](s, "Sub1.Sub2.C")
if err != nil {
t.Error(err)
}
if v != true {
t.Error("v != true")
}
v, err = GetValueFrom[PathfindTestStruct1](s, "Sub1.Sub2.Ci")
if err != nil {
t.Error(err)
}
if v != 2 {
t.Error("v != 2")
}
v, err = GetValueFrom[PathfindTestStruct1](s, "Sub1.Sub2.Cs")
if err != nil {
t.Error(err)
}
if v != "3" {
t.Error("v != 3")
}
v, err = GetValueFrom[PathfindTestStruct1](s, "Sub1.Sub2.Cf")
if err != nil {
t.Error(err)
}
if v != 4.0 {
t.Error("v != 4.0")
}
s.Sub1.Sub2.Sub3.D = true
s.Sub1.Sub2.Sub3.Di = 2
s.Sub1.Sub2.Sub3.Ds = "3"
s.Sub1.Sub2.Sub3.Df = 4.0
v, err = GetValueFrom[PathfindTestStruct1](s, "Sub1.Sub2.Sub3.D")
if err != nil {
t.Error(err)
}
if v != true {
t.Error("v != true")
}
v, err = GetValueFrom[PathfindTestStruct1](s, "Sub1.Sub2.Sub3.Di")
if err != nil {
t.Error(err)
}
if v != 2 {
t.Error("v != 2")
}
v, err = GetValueFrom[PathfindTestStruct1](s, "Sub1.Sub2.Sub3.Ds")
if err != nil {
t.Error(err)
}
if v != "3" {
t.Error("v != 3")
}
v, err = GetValueFrom[PathfindTestStruct1](s, "Sub1.Sub2.Sub3.Df")
if err != nil {
t.Error(err)
}
if v != 4.0 {
t.Error("v != 4.0")
}
}
func TestPathFindSetValueFrom(t *testing.T) {
s := &PathfindTestStruct1{}
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.B", "true")
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.Bi", "2")
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.Bs", "3")
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.Bf", "4.0")
if s.Sub1.B != true {
t.Error("s.Sub1.B != true")
}
if s.Sub1.Bi != 2 {
t.Error("s.Sub1.Bi != 2")
}
if s.Sub1.Bs != "3" {
t.Error("s.Sub1.Bs != 3")
}
if s.Sub1.Bf != 4.0 {
t.Error("s.Sub1.Bf != 4.0")
}
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.Sub2.C", "true")
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.Sub2.Ci", "2")
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.Sub2.Cs", "3")
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.Sub2.Cf", "4.0")
if s.Sub1.Sub2.C != true {
t.Error("s.Sub1.Sub2.C != true")
}
if s.Sub1.Sub2.Ci != 2 {
t.Error("s.Sub1.Sub2.Ci != 2")
}
if s.Sub1.Sub2.Cs != "3" {
t.Error("s.Sub1.Sub2.Cs != 3")
}
if s.Sub1.Sub2.Cf != 4.0 {
t.Error("s.Sub1.Sub2.Cf != 4.0")
}
if s.Sub1.Sub2.Sub3.D != false {
t.Error("s.Sub1.Sub2.Sub3.D != false")
}
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.Sub2.Sub3.D", "true")
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.Sub2.Sub3.Di", "2")
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.Sub2.Sub3.Ds", "3")
SetValueUsingPath[*PathfindTestStruct1](s, "Sub1.Sub2.Sub3.Df", "4.0")
if s.Sub1.Sub2.Sub3.D != true {
t.Error("s.Sub1.Sub2.Sub3.D != true")
}
if s.Sub1.Sub2.Sub3.Di != 2 {
t.Error("s.Sub1.Sub2.Sub3.Di != 2")
}
if s.Sub1.Sub2.Sub3.Ds != "3" {
t.Error("s.Sub1.Sub2.Sub3.Ds != 3")
}
if s.Sub1.Sub2.Sub3.Df != 4.0 {
t.Error("s.Sub1.Sub2.Sub3.Df != 4.0")
}
}
<?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
{"version":"0.1.0"}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment