2021-02-12 16:12:58 +02:00
|
|
|
package serial
|
|
|
|
|
|
|
|
import (
|
2021-09-20 16:00:55 +03:00
|
|
|
"io"
|
|
|
|
|
2023-12-29 18:16:48 +02:00
|
|
|
creflect "github.com/xtls/xray-core/common/reflect"
|
2021-02-12 16:12:58 +02:00
|
|
|
"github.com/xtls/xray-core/core"
|
|
|
|
"github.com/xtls/xray-core/infra/conf"
|
|
|
|
"github.com/xtls/xray-core/main/confloader"
|
|
|
|
)
|
|
|
|
|
2023-12-29 18:16:48 +02:00
|
|
|
func MergeConfigFromFiles(files []string, formats []string) (string, error) {
|
|
|
|
c, err := mergeConfigs(files, formats)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
|
|
|
|
if j, ok := creflect.MarshalToJson(c); ok {
|
|
|
|
return j, nil
|
|
|
|
}
|
|
|
|
return "", newError("marshal to json failed.").AtError()
|
|
|
|
}
|
|
|
|
|
|
|
|
func mergeConfigs(files []string, formats []string) (*conf.Config, error) {
|
2021-02-12 16:12:58 +02:00
|
|
|
cf := &conf.Config{}
|
2023-01-07 17:11:23 +02:00
|
|
|
for i, file := range files {
|
2021-02-12 16:12:58 +02:00
|
|
|
newError("Reading config: ", file).AtInfo().WriteToLog()
|
|
|
|
r, err := confloader.LoadConfig(file)
|
|
|
|
if err != nil {
|
|
|
|
return nil, newError("failed to read config: ", file).Base(err)
|
|
|
|
}
|
|
|
|
c, err := ReaderDecoderByFormat[formats[i]](r)
|
|
|
|
if err != nil {
|
|
|
|
return nil, newError("failed to decode config: ", file).Base(err)
|
|
|
|
}
|
|
|
|
if i == 0 {
|
|
|
|
*cf = *c
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
cf.Override(c, file)
|
|
|
|
}
|
2023-12-29 18:16:48 +02:00
|
|
|
return cf, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func BuildConfig(files []string, formats []string) (*core.Config, error) {
|
|
|
|
config, err := mergeConfigs(files, formats)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
return config.Build()
|
2021-02-12 16:12:58 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type readerDecoder func(io.Reader) (*conf.Config, error)
|
|
|
|
|
2021-10-19 19:57:14 +03:00
|
|
|
var ReaderDecoderByFormat = make(map[string]readerDecoder)
|
2021-02-12 16:12:58 +02:00
|
|
|
|
|
|
|
func init() {
|
|
|
|
ReaderDecoderByFormat["json"] = DecodeJSONConfig
|
|
|
|
ReaderDecoderByFormat["yaml"] = DecodeYAMLConfig
|
|
|
|
ReaderDecoderByFormat["toml"] = DecodeTOMLConfig
|
|
|
|
|
|
|
|
core.ConfigBuilderForFiles = BuildConfig
|
2023-12-29 18:16:48 +02:00
|
|
|
core.ConfigMergedFormFiles = MergeConfigFromFiles
|
2021-02-12 16:12:58 +02:00
|
|
|
}
|