Feature: update config API support raw yaml payload

This commit is contained in:
Dreamacro
2019-12-01 13:22:47 +08:00
parent 8e10e67b89
commit 3e4bc9f85c
4 changed files with 94 additions and 60 deletions

View File

@ -1,6 +1,11 @@
package executor
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"github.com/Dreamacro/clash/component/auth"
trie "github.com/Dreamacro/clash/component/domain-trie"
"github.com/Dreamacro/clash/config"
@ -12,6 +17,41 @@ import (
T "github.com/Dreamacro/clash/tunnel"
)
// forward compatibility before 1.0
func readRawConfig(path string) ([]byte, error) {
data, err := ioutil.ReadFile(path)
if err == nil && len(data) != 0 {
return data, nil
}
if filepath.Ext(path) != ".yaml" {
return nil, err
}
path = path[:len(path)-5] + ".yml"
if _, fallbackErr := os.Stat(path); fallbackErr == nil {
return ioutil.ReadFile(path)
}
return data, err
}
func readConfig(path string) ([]byte, error) {
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, err
}
data, err := readRawConfig(path)
if err != nil {
return nil, err
}
if len(data) == 0 {
return nil, fmt.Errorf("Configuration file %s is empty", path)
}
return data, err
}
// Parse config with default config path
func Parse() (*config.Config, error) {
return ParseWithPath(C.Path.Config())
@ -19,7 +59,17 @@ func Parse() (*config.Config, error) {
// ParseWithPath parse config with custom config path
func ParseWithPath(path string) (*config.Config, error) {
return config.Parse(path)
buf, err := readConfig(path)
if err != nil {
return nil, err
}
return config.Parse(buf)
}
// Parse config with default config path
func ParseWithBytes(buf []byte) (*config.Config, error) {
return ParseWithPath(C.Path.Config())
}
// ApplyConfig dispatch configure to all parts