1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-17 18:06:15 -05:00
v2fly/infra/conf/merge/rules.go
Jebbs ff59bd37ce
v5: New multi-json loader (#451)
* scalable commands column

* new multi-json loader
For both internal & external json loader

This commit also:
* applies -confdir to other formats, e.g. "yaml" in the future
* multiple assign of -confdir is accepted
* add flag to load confdir recursively
* config loader can have alias name
* json loader also accepts .jsonc
* add merge command
* add help topics for json merge, format loader
* format loaders don't panic

* apply lint style

* add merge test

* merge same tag in array, solve v2fly/discussion#97

* apply lint style

* merge code optimize

* fix merge cmdarg.Arg

* update cmd description

* improve merge logic
* fix zero value overwrite
* fix "null" lost after array merge

* code optimize

* fix merged slices not sorted

* code optimize

* add package doc

* fix a typo
2020-11-28 22:06:03 +08:00

56 lines
1.3 KiB
Go

// Copyright 2020 Jebbs. All rights reserved.
// Use of this source code is governed by MIT
// license that can be found in the LICENSE file.
package merge
const priorityKey string = "_priority"
const tagKey string = "_tag"
func applyRules(m map[string]interface{}) error {
err := sortMergeSlices(m)
if err != nil {
return err
}
removeHelperFields(m)
return nil
}
// sortMergeSlices enumerates all slices in a map, to sort by priority and merge by tag
func sortMergeSlices(target map[string]interface{}) error {
for key, value := range target {
if slice, ok := value.([]interface{}); ok {
sortByPriority(slice)
s, err := mergeSameTag(slice)
if err != nil {
return err
}
target[key] = s
for _, item := range s {
if m, ok := item.(map[string]interface{}); ok {
sortMergeSlices(m)
}
}
} else if field, ok := value.(map[string]interface{}); ok {
sortMergeSlices(field)
}
}
return nil
}
func removeHelperFields(target map[string]interface{}) {
for key, value := range target {
if key == priorityKey || key == tagKey {
delete(target, key)
} else if slice, ok := value.([]interface{}); ok {
for _, e := range slice {
if el, ok := e.(map[string]interface{}); ok {
removeHelperFields(el)
}
}
} else if field, ok := value.(map[string]interface{}); ok {
removeHelperFields(field)
}
}
}