29 Commits

Author SHA1 Message Date
73c66bb531 Merge pull request #21 from unistack-org/master
merge master
2022-01-25 15:47:50 +03:00
92dd3a9736 Merge pull request #20 from unistack-org/timezone
always check in utc timezone
2022-01-25 15:47:23 +03:00
ad03446930 Merge branch 'master' into timezone 2022-01-25 15:42:50 +03:00
bb1df83d03 always check in utc timezone
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2022-01-25 15:42:34 +03:00
39b58ecb1e Merge pull request #17 from unistack-org/dependabot/go_modules/go.unistack.org/micro/v3-3.8.15
Bump go.unistack.org/micro/v3 from 3.8.14 to 3.8.15
2022-01-20 16:23:12 +03:00
dependabot[bot]
8d9c45b7d3 Bump go.unistack.org/micro/v3 from 3.8.14 to 3.8.15
Bumps [go.unistack.org/micro/v3](https://github.com/unistack-org/micro) from 3.8.14 to 3.8.15.
- [Release notes](https://github.com/unistack-org/micro/releases)
- [Commits](https://github.com/unistack-org/micro/compare/v3.8.14...v3.8.15)

---
updated-dependencies:
- dependency-name: go.unistack.org/micro/v3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-20 13:22:53 +00:00
bc9bcdac65 Merge pull request #16 from unistack-org/dependabot/go_modules/go.unistack.org/micro/v3-3.8.14
Bump go.unistack.org/micro/v3 from 3.8.11 to 3.8.14
2022-01-11 16:16:59 +03:00
dependabot[bot]
bb4bbe3bd3 Bump go.unistack.org/micro/v3 from 3.8.11 to 3.8.14
Bumps [go.unistack.org/micro/v3](https://github.com/unistack-org/micro) from 3.8.11 to 3.8.14.
- [Release notes](https://github.com/unistack-org/micro/releases)
- [Commits](https://github.com/unistack-org/micro/compare/v3.8.11...v3.8.14)

---
updated-dependencies:
- dependency-name: go.unistack.org/micro/v3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-11 13:16:41 +00:00
8c5d09a677 Merge pull request #13 from unistack-org/dependabot/go_modules/go.unistack.org/micro/v3-3.8.11
Bump go.unistack.org/micro/v3 from 3.8.10 to 3.8.11
2021-11-24 16:21:37 +03:00
dependabot[bot]
0529af279f Bump go.unistack.org/micro/v3 from 3.8.10 to 3.8.11
Bumps [go.unistack.org/micro/v3](https://github.com/unistack-org/micro) from 3.8.10 to 3.8.11.
- [Release notes](https://github.com/unistack-org/micro/releases)
- [Commits](https://github.com/unistack-org/micro/compare/v3.8.10...v3.8.11)

---
updated-dependencies:
- dependency-name: go.unistack.org/micro/v3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-24 13:21:19 +00:00
b1decd3028 Merge pull request #12 from unistack-org/dependabot/go_modules/go.unistack.org/micro/v3-3.8.10
Bump go.unistack.org/micro/v3 from 3.8.9 to 3.8.10
2021-11-19 16:21:04 +03:00
dependabot[bot]
1fb103597d Bump go.unistack.org/micro/v3 from 3.8.9 to 3.8.10
Bumps [go.unistack.org/micro/v3](https://github.com/unistack-org/micro) from 3.8.9 to 3.8.10.
- [Release notes](https://github.com/unistack-org/micro/releases)
- [Commits](https://github.com/unistack-org/micro/compare/v3.8.9...v3.8.10)

---
updated-dependencies:
- dependency-name: go.unistack.org/micro/v3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-19 13:20:46 +00:00
2f6bf10367 Merge pull request #11 from unistack-org/dependabot/go_modules/go.unistack.org/micro/v3-3.8.9
Bump go.unistack.org/micro/v3 from 3.8.7 to 3.8.9
2021-11-18 16:20:40 +03:00
dependabot[bot]
06eec8f142 Bump go.unistack.org/micro/v3 from 3.8.7 to 3.8.9
Bumps [go.unistack.org/micro/v3](https://github.com/unistack-org/micro) from 3.8.7 to 3.8.9.
- [Release notes](https://github.com/unistack-org/micro/releases)
- [Commits](https://github.com/unistack-org/micro/compare/v3.8.7...v3.8.9)

---
updated-dependencies:
- dependency-name: go.unistack.org/micro/v3
  dependency-type: direct:production
  update-type: version-update:semver-patch
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-11-18 13:20:24 +00:00
2089311c85 update deps
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-10-27 22:56:15 +03:00
bfff6a7e87 update workflows
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-10-27 19:04:22 +03:00
eb94a33848 fix import guard
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-10-26 23:27:52 +03:00
d014fc95f6 update import paths
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-10-26 23:25:18 +03:00
695d3ad1fe update for latest micro
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-09-30 01:55:01 +03:00
21da767988 update workflow
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-09-21 21:47:16 +03:00
8d6c3a723b update workflows
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-09-17 07:48:32 +03:00
github-actions[bot]
235194ac2f Merge pull request #4 from unistack-org/dependabot/go_modules/github.com/unistack-org/micro/v3-3.7.1
Bump github.com/unistack-org/micro/v3 from 3.5.9 to 3.7.1
2021-09-16 13:23:17 +00:00
dependabot[bot]
83af91430b Bump github.com/unistack-org/micro/v3 from 3.5.9 to 3.7.1
Bumps [github.com/unistack-org/micro/v3](https://github.com/unistack-org/micro) from 3.5.9 to 3.7.1.
- [Release notes](https://github.com/unistack-org/micro/releases)
- [Commits](https://github.com/unistack-org/micro/compare/v3.5.9...v3.7.1)

---
updated-dependencies:
- dependency-name: github.com/unistack-org/micro/v3
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-09-16 13:21:23 +00:00
896625e088 enable automerge
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-09-16 11:05:50 +03:00
08b836f686 add github stuff
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-09-06 14:41:38 +03:00
5ef2eb7f39 config: minor changes to split config and watcher files
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-08-04 15:06:43 +03:00
ee09f57192 update
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-06-21 16:21:27 +03:00
d6a35346cc add map support
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-06-20 14:53:14 +03:00
05720a433e complete
Signed-off-by: Vasiliy Tolstov <v.tolstov@unistack.org>
2021-06-19 16:00:47 +03:00
15 changed files with 701 additions and 49 deletions

24
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,24 @@
---
name: Bug report
about: For reporting bugs in go-micro
title: "[BUG]"
labels: ''
assignees: ''
---
**Describe the bug**
1. What are you trying to do?
2. What did you expect to happen?
3. What happens instead?
**How to reproduce the bug:**
If possible, please include a minimal code snippet here.
**Environment:**
Go Version: please paste `go version` output here
```
please paste `go env` output here
```

View File

@@ -0,0 +1,17 @@
---
name: Feature request / Enhancement
about: If you have a need not served by go-micro
title: "[FEATURE]"
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Additional context**
Add any other context or screenshots about the feature request here.

14
.github/ISSUE_TEMPLATE/question.md vendored Normal file
View File

@@ -0,0 +1,14 @@
---
name: Question
about: Ask a question about go-micro
title: ''
labels: ''
assignees: ''
---
Before asking, please check if your question has already been answered:
1. Check the documentation - https://micro.mu/docs/
2. Check the examples and plugins - https://github.com/micro/examples & https://github.com/micro/go-plugins
3. Search existing issues

9
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,9 @@
## Pull Request template
Please, go through these steps before clicking submit on this PR.
1. Give a descriptive title to your PR.
2. Provide a description of your changes.
3. Make sure you have some relevant tests.
4. Put `closes #XXXX` in your comment to auto-close the issue that your PR fixes (if applicable).
**PLEASE REMOVE THIS TEMPLATE BEFORE SUBMITTING**

19
.github/dependabot.yml vendored Normal file
View File

@@ -0,0 +1,19 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://help.github.com/github/administering-a-repository/configuration-options-for-dependency-updates
version: 2
updates:
# Maintain dependencies for GitHub Actions
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
# Maintain dependencies for Golang
- package-ecosystem: "gomod"
directory: "/"
schedule:
interval: "daily"

46
.github/workflows/build.yml vendored Normal file
View File

@@ -0,0 +1,46 @@
name: build
on:
push:
branches:
- master
jobs:
test:
name: test
runs-on: ubuntu-latest
steps:
- name: setup
uses: actions/setup-go@v2
with:
go-version: 1.16
- name: checkout
uses: actions/checkout@v2
- name: cache
uses: actions/cache@v2
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-go-
- name: deps
run: go get -v -t -d ./...
- name: test
env:
INTEGRATION_TESTS: yes
run: go test -mod readonly -v ./...
lint:
name: lint
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v2
- name: lint
uses: golangci/golangci-lint-action@v2
continue-on-error: true
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.30
# Optional: working directory, useful for monorepos
# working-directory: somedir
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0
# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true

78
.github/workflows/codeql-analysis.yml vendored Normal file
View File

@@ -0,0 +1,78 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "codeql"
on:
workflow_run:
workflows: ["prbuild"]
types:
- completed
push:
branches: [ master, v3 ]
pull_request:
# The branches below must be a subset of the branches above
branches: [ master, v3 ]
schedule:
- cron: '34 1 * * 0'
jobs:
analyze:
name: analyze
runs-on: ubuntu-latest
permissions:
actions: read
contents: read
security-events: write
strategy:
fail-fast: false
matrix:
language: [ 'go' ]
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
# Learn more:
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
steps:
- name: checkout
uses: actions/checkout@v2
- name: setup
uses: actions/setup-go@v2
with:
go-version: 1.16
# Initializes the CodeQL tools for scanning.
- name: init
uses: github/codeql-action/init@v1
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.
# queries: ./path/to/local/query, your-org/your-repo/queries@main
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below)
- name: autobuild
uses: github/codeql-action/autobuild@v1
# Command-line programs to run using the OS shell.
# 📚 https://git.io/JvXDl
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
# and modify them (or add more) to build your code if your project
# uses a compiled language
#- run: |
# make bootstrap
# make release
- name: analyze
uses: github/codeql-action/analyze@v1

View File

@@ -0,0 +1,31 @@
name: "prautomerge"
on:
pull_request_target:
types: [assigned, opened, synchronize, reopened]
permissions:
pull-requests: write
contents: write
jobs:
dependabot:
runs-on: ubuntu-latest
if: ${{ github.actor == 'dependabot[bot]' }}
steps:
- name: metadata
id: metadata
uses: dependabot/fetch-metadata@v1.1.1
with:
github-token: "${{ secrets.TOKEN }}"
- name: approve
run: gh pr review --approve "$PR_URL"
env:
PR_URL: ${{github.event.pull_request.html_url}}
GITHUB_TOKEN: ${{secrets.TOKEN}}
- name: merge
if: ${{contains(steps.metadata.outputs.dependency-names, 'go.unistack.org')}}
run: gh pr merge --auto --merge "$PR_URL"
env:
PR_URL: ${{github.event.pull_request.html_url}}
GITHUB_TOKEN: ${{secrets.TOKEN}}

46
.github/workflows/pr.yml vendored Normal file
View File

@@ -0,0 +1,46 @@
name: prbuild
on:
pull_request:
branches:
- master
jobs:
test:
name: test
runs-on: ubuntu-latest
steps:
- name: setup
uses: actions/setup-go@v2
with:
go-version: 1.16
- name: checkout
uses: actions/checkout@v2
- name: cache
uses: actions/cache@v2
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}
restore-keys: ${{ runner.os }}-go-
- name: deps
run: go get -v -t -d ./...
- name: test
env:
INTEGRATION_TESTS: yes
run: go test -mod readonly -v ./...
lint:
name: lint
runs-on: ubuntu-latest
steps:
- name: checkout
uses: actions/checkout@v2
- name: lint
uses: golangci/golangci-lint-action@v2
continue-on-error: true
with:
# Required: the version of golangci-lint is required and must be specified without patch version: we always use the latest patch version.
version: v1.30
# Optional: working directory, useful for monorepos
# working-directory: somedir
# Optional: golangci-lint command line arguments.
# args: --issues-exit-code=0
# Optional: show only new issues if it's a pull request. The default value is `false`.
# only-new-issues: true

88
flag.go
View File

@@ -1,21 +1,31 @@
package flag
package flag // import "go.unistack.org/micro-config-flag/v3"
import (
"context"
"errors"
"flag"
"fmt"
"reflect"
"strconv"
"time"
"github.com/unistack-org/micro/v3/config"
rutil "github.com/unistack-org/micro/v3/util/reflect"
"go.unistack.org/micro/v3/config"
rutil "go.unistack.org/micro/v3/util/reflect"
)
var (
DefaultStructTag = "flag"
ErrInvalidStruct = errors.New("invalid struct specified")
DefaultStructTag = "flag"
ErrInvalidValue = errors.New("invalid value specified")
DefaultSliceDelim = ","
DefaultMapDelim = ","
)
/*
var (
timeTimeKind = reflect.TypeOf(time.Time{}).Kind()
timeDurationKind = reflect.TypeOf(time.Duration(0)).Kind()
)
*/
type flagConfig struct {
opts config.Options
}
@@ -41,26 +51,74 @@ func (c *flagConfig) Init(opts ...config.Option) error {
}
fn, fv, fd := getFlagOpts(tf)
rcheck := true
switch sf.Value.Interface().(type) {
case time.Duration:
err = c.flagDuration(sf.Value, fn, fv, fd)
rcheck = false
case time.Time:
err = c.flagTime(sf.Value, fn, fv, fd)
rcheck = false
}
if err != nil {
c.opts.Logger.Errorf(c.opts.Context, "flag init error: %v", err)
if !c.opts.AllowFail {
return err
}
return nil
}
if !rcheck {
continue
}
if sf.Value.Kind() == reflect.Ptr {
sf.Value = sf.Value.Elem()
}
switch sf.Value.Kind() {
case reflect.String:
v := sf.Value.Addr().Interface().(*string)
flag.StringVar(v, fn, fv, fd)
err = c.flagString(sf.Value, fn, fv, fd)
case reflect.Bool:
v := sf.Value.Addr().Interface().(*bool)
i, _ := strconv.ParseBool(fv)
flag.BoolVar(v, fn, i, fd)
err = c.flagBool(sf.Value, fn, fv, fd)
case reflect.Int:
err = c.flagInt(sf.Value, fn, fv, fd)
case reflect.Int64:
err = c.flagInt64(sf.Value, fn, fv, fd)
case reflect.Float64:
err = c.flagFloat64(sf.Value, fn, fv, fd)
case reflect.Uint:
err = c.flagUint(sf.Value, fn, fv, fd)
case reflect.Uint64:
err = c.flagUint64(sf.Value, fn, fv, fd)
case reflect.Slice:
err = c.flagSlice(sf.Value, fn, fv, fd)
case reflect.Map:
err = c.flagMap(sf.Value, fn, fv, fd)
}
if err != nil {
c.opts.Logger.Errorf(c.opts.Context, "flag init error: %v", err)
if !c.opts.AllowFail {
return err
}
return nil
}
}
return nil
}
func (c *flagConfig) Load(ctx context.Context) error {
func (c *flagConfig) Load(ctx context.Context, opts ...config.LoadOption) error {
options := config.NewLoadOptions(opts...)
_ = options
// TODO: allow merge, append and so
flag.Parse()
return nil
}
func (c *flagConfig) Save(ctx context.Context) error {
func (c *flagConfig) Save(ctx context.Context, opts ...config.SaveOption) error {
return nil
}
@@ -72,6 +130,10 @@ func (c *flagConfig) Name() string {
return c.opts.Name
}
func (c *flagConfig) Watch(ctx context.Context, opts ...config.WatchOption) (config.Watcher, error) {
return nil, fmt.Errorf("not implemented")
}
func NewConfig(opts ...config.Option) config.Config {
options := config.NewOptions(opts...)
if len(options.StructTag) == 0 {

View File

@@ -1,49 +1,47 @@
package flag
import (
"flag"
"context"
"os"
"reflect"
"strconv"
"testing"
"time"
rutil "github.com/unistack-org/micro/v3/util/reflect"
"go.unistack.org/micro/v3/config"
)
func TestLoad(t *testing.T) {
time.Local = time.UTC
os.Args = append(os.Args, "-broker", "5566:33")
type config struct {
Broker string `flag:"name=broker,desc='description with, comma',default='127.0.0.1:9092'"`
Verbose bool `flag:"name=verbose,desc='verbose output',default='false value'"`
os.Args = append(os.Args, "-verbose")
os.Args = append(os.Args, "-wait", "5s")
os.Args = append(os.Args, "-addr", "33,44")
os.Args = append(os.Args, "-time", time.RFC822)
os.Args = append(os.Args, "-metadata", "key=20")
type Config struct {
Broker string `flag:"name=broker,desc='description with, comma',default='127.0.0.1:9092'"`
Verbose bool `flag:"name=verbose,desc='verbose output',default='false'"`
Addr []string `flag:"name=addr,desc='addrs',default='127.0.0.1:9092'"`
Wait time.Duration `flag:"name=wait,desc='wait time',default='2s'"`
Time time.Time `flag:"name=time,desc='some time',default='02 Jan 06 15:04 MST'"`
Metadata map[string]int `flag:"name=metadata,desc='some meta',default=''"`
}
cfg := &config{}
ctx := context.Background()
cfg := &Config{}
fields, err := rutil.StructFields(cfg)
if err != nil {
t.Fatal(err)
c := NewConfig(config.Struct(cfg), TimeFormat(time.RFC822))
if err := c.Init(); err != nil {
t.Fatalf("init failed: %v", err)
}
for _, sf := range fields {
tf, ok := sf.Field.Tag.Lookup("flag")
if !ok {
continue
}
fn, fv, fd := getFlagOpts(tf)
switch sf.Value.Kind() {
case reflect.String:
v := sf.Value.Addr().Interface().(*string)
flag.StringVar(v, fn, fv, fd)
case reflect.Bool:
v := sf.Value.Addr().Interface().(*bool)
i, _ := strconv.ParseBool(fv)
flag.BoolVar(v, fn, i, fd)
}
if err := c.Load(ctx); err != nil {
t.Fatalf("load failed: %v", err)
}
flag.Parse()
if cfg.Broker != "5566:33" {
t.Fatalf("failed to parse flags broker value invalid: %#+v", cfg)
}
if tf := cfg.Time.Format(time.RFC822); tf != "02 Jan 06 15:04 MST" {
t.Fatalf("parse time error: %s != %s", tf, "02 Jan 06 15:04 MST")
}
}

4
go.mod
View File

@@ -1,5 +1,5 @@
module github.com/unistack-org/micro-config-flag/v3
module go.unistack.org/micro-config-flag/v3
go 1.16
require github.com/unistack-org/micro/v3 v3.3.22
require go.unistack.org/micro/v3 v3.8.15

22
go.sum
View File

@@ -1,18 +1,28 @@
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/ef-ds/deque v1.0.4/go.mod h1:gXDnTC3yqvBcHbq2lcExjtAcVrOnJCbMcZXmuj8Z4tg=
github.com/google/uuid v1.2.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/golang-jwt/jwt/v4 v4.2.0/go.mod h1:/xlHOz8bRuivTWchD4jCa+NbatV+wEUSzwAxVc6locg=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/imdario/mergo v0.3.12 h1:b6R2BslTbIEToALKP7LxUvijTsNI9TAe80pLWN2g/HU=
github.com/imdario/mergo v0.3.12/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/silas/dag v0.0.0-20210121180416-41cf55125c34/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I=
github.com/unistack-org/micro/v3 v3.3.22 h1:4mY+lhqW6N/3A0LSfAnGHE65TakGOrbU144/FQEjZIs=
github.com/unistack-org/micro/v3 v3.3.22/go.mod h1:LXmPfbJnJNvL0kQs8HfnkV3Wya2Wb+C7keVq++RCZnk=
golang.org/x/net v0.0.0-20210510120150-4163338589ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
github.com/silas/dag v0.0.0-20210626123444-3804bac2d6d4/go.mod h1:7RTUFBdIRC9nZ7/3RyRNH1bdqIShrDejd1YbLwgPS+I=
go.unistack.org/micro-proto/v3 v3.1.1 h1:78qRmltwGek5kSQ9tNmDZ9TCRvZM7YDIOgzriKvabjA=
go.unistack.org/micro-proto/v3 v3.1.1/go.mod h1:DpRhYCBXlmSJ/AAXTmntvlh7kQkYU6eFvlmYAx4BQS8=
go.unistack.org/micro/v3 v3.8.15 h1:9KzaPmWW4CpThOT8tiq8XEG3YLmVV8hztqnzPBmJudQ=
go.unistack.org/micro/v3 v3.8.15/go.mod h1:zEbgew93bFhU+gANJubbbnPP1LtDTQRbM/17QXTbTrY=
golang.org/x/net v0.0.0-20210928044308-7d9f5e0b762b/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.3.0 h1:clyUAQHOM3G0M3f5vQj7LuJrETvjVot3Z5el9nffUtU=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=

26
options.go Normal file
View File

@@ -0,0 +1,26 @@
package flag
import (
"go.unistack.org/micro/v3/config"
)
type sliceDelimKey struct{}
// SliceDelim set the slice delimeter
func SliceDelim(s string) config.Option {
return config.SetOption(sliceDelimKey{}, s)
}
type mapDelimKey struct{}
// MapDelim set the map delimeter
func MapDelim(s string) config.Option {
return config.SetOption(mapDelimKey{}, s)
}
type timeFormatKey struct{}
// TimeFormat set the time format
func TimeFormat(s string) config.Option {
return config.SetOption(timeFormatKey{}, s)
}

272
util.go
View File

@@ -1,9 +1,281 @@
package flag
import (
"flag"
"reflect"
"strconv"
"strings"
"time"
)
func convertType(v reflect.Value, t reflect.Kind) (reflect.Value, error) {
switch v.Kind() {
case reflect.String:
switch t {
case reflect.String:
return v, nil
case reflect.Int, reflect.Int64:
i, err := strconv.ParseInt(v.String(), 10, 64)
if err != nil {
return v, err
}
return reflect.ValueOf(i), nil
case reflect.Uint, reflect.Uint64:
i, err := strconv.ParseUint(v.String(), 10, 64)
if err != nil {
return v, err
}
return reflect.ValueOf(i), nil
case reflect.Float64:
i, err := strconv.ParseFloat(v.String(), 64)
if err != nil {
return v, err
}
return reflect.ValueOf(i), nil
case reflect.Bool:
i, err := strconv.ParseBool(v.String())
if err != nil {
return v, err
}
return reflect.ValueOf(i), nil
}
}
return v, ErrInvalidValue
}
func (c *flagConfig) flagSlice(v reflect.Value, fn, fv, fd string) error {
delim := DefaultSliceDelim
if c.opts.Context != nil {
if d, ok := c.opts.Context.Value(sliceDelimKey{}).(string); ok {
delim = d
}
}
flag.Func(fn, fd, func(s string) error {
p := strings.Split(s, delim)
v.Set(reflect.MakeSlice(v.Type(), len(p), len(p)))
switch v.Type().Elem().Kind() {
case reflect.Int, reflect.Int64:
for idx := range p {
i, err := strconv.ParseInt(p[idx], 10, 64)
if err != nil {
return err
}
v.Index(idx).SetInt(i)
}
case reflect.Uint, reflect.Uint64:
for idx := range p {
i, err := strconv.ParseUint(p[idx], 10, 64)
if err != nil {
return err
}
v.Index(idx).SetUint(i)
}
case reflect.Float64:
for idx := range p {
i, err := strconv.ParseFloat(p[idx], 64)
if err != nil {
return err
}
v.Index(idx).SetFloat(i)
}
case reflect.Bool:
for idx := range p {
i, err := strconv.ParseBool(p[idx])
if err != nil {
return err
}
v.Index(idx).SetBool(i)
}
case reflect.String:
for idx := range p {
v.Index(idx).SetString(p[idx])
}
}
return nil
})
return nil
}
func (c *flagConfig) flagMap(v reflect.Value, fn, fv, fd string) error {
delim := DefaultMapDelim
if c.opts.Context != nil {
if d, ok := c.opts.Context.Value(mapDelimKey{}).(string); ok {
delim = d
}
}
flag.Func(fn, fd, func(s string) error {
ps := strings.Split(s, delim)
if len(ps) == 0 {
return nil
}
v.Set(reflect.MakeMapWithSize(v.Type(), len(ps)))
kt := v.Type().Key().Kind()
vt := v.Type().Elem().Kind()
for i := 0; i < len(ps); i++ {
fs := strings.Split(ps[i], "=")
switch len(fs) {
case 0:
return nil
case 1:
if len(fs[0]) == 0 {
return nil
}
return ErrInvalidValue
case 2:
break
default:
return ErrInvalidValue
}
key, err := convertType(reflect.ValueOf(fs[0]), kt)
if err != nil {
return err
}
val, err := convertType(reflect.ValueOf(fs[1]), vt)
if err != nil {
return err
}
v.SetMapIndex(key.Convert(v.Type().Key()), val.Convert(v.Type().Elem()))
}
return nil
})
return nil
}
func (c *flagConfig) flagTime(v reflect.Value, fn, fv, fd string) error {
var format string
if c.opts.Context != nil {
if tf, ok := c.opts.Context.Value(timeFormatKey{}).(string); ok {
format = tf
}
}
if format == "" {
return ErrInvalidValue
}
flag.Func(fn, fd, func(s string) error {
t, err := time.Parse(s, format)
if err != nil {
return err
}
v.Set(reflect.ValueOf(t))
return nil
})
return nil
}
func (c *flagConfig) flagDuration(v reflect.Value, fn, fv, fd string) error {
nv, ok := v.Addr().Interface().(*time.Duration)
if !ok {
return ErrInvalidValue
}
i, err := time.ParseDuration(fd)
if err != nil {
return err
}
flag.DurationVar(nv, fn, i, fd)
return nil
}
func (c *flagConfig) flagBool(v reflect.Value, fn, fv, fd string) error {
nv, ok := v.Addr().Interface().(*bool)
if !ok {
return ErrInvalidValue
}
i, err := strconv.ParseBool(fd)
if err != nil {
return err
}
flag.BoolVar(nv, fn, i, fd)
return nil
}
func (c *flagConfig) flagString(v reflect.Value, fn, fv, fd string) error {
nv, ok := v.Addr().Interface().(*string)
if !ok {
return ErrInvalidValue
}
flag.StringVar(nv, fn, fv, fd)
return nil
}
func (c *flagConfig) flagInt(v reflect.Value, fn, fv, fd string) error {
nv, ok := v.Addr().Interface().(*int)
if !ok {
return ErrInvalidValue
}
i, err := strconv.ParseInt(fd, 10, 64)
if err != nil {
return err
}
flag.IntVar(nv, fn, int(i), fd)
return nil
}
func (c *flagConfig) flagInt64(v reflect.Value, fn, fv, fd string) error {
nv, ok := v.Addr().Interface().(*int64)
if !ok {
return ErrInvalidValue
}
i, err := strconv.ParseInt(fd, 10, 64)
if err != nil {
return err
}
flag.Int64Var(nv, fn, int64(i), fd)
return nil
}
func (c *flagConfig) flagUint(v reflect.Value, fn, fv, fd string) error {
nv, ok := v.Addr().Interface().(*uint)
if !ok {
return ErrInvalidValue
}
i, err := strconv.ParseUint(fd, 10, 64)
if err != nil {
return err
}
flag.UintVar(nv, fn, uint(i), fd)
return nil
}
func (c *flagConfig) flagUint64(v reflect.Value, fn, fv, fd string) error {
nv, ok := v.Addr().Interface().(*uint64)
if !ok {
return ErrInvalidValue
}
i, err := strconv.ParseUint(fd, 10, 64)
if err != nil {
return err
}
flag.Uint64Var(nv, fn, uint64(i), fd)
return nil
}
func (c *flagConfig) flagFloat64(v reflect.Value, fn, fv, fd string) error {
nv, ok := v.Addr().Interface().(*float64)
if !ok {
return ErrInvalidValue
}
i, err := strconv.ParseFloat(fd, 64)
if err != nil {
return err
}
flag.Float64Var(nv, fn, float64(i), fd)
return nil
}
func (c *flagConfig) flagStringSlice(v reflect.Value, fn, fv, fd string) error {
nv, ok := v.Addr().Interface().(*string)
if !ok {
return ErrInvalidValue
}
flag.StringVar(nv, fn, fv, fd)
return nil
}
func getFlagOpts(tf string) (string, string, string) {
ret := make([]string, 3)
vals := strings.Split(tf, ",")