load.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package config
  2. import (
  3. "io/ioutil"
  4. P "path"
  5. "strings"
  6. "gopkg.in/yaml.v2"
  7. "cfa/app"
  8. "github.com/Dreamacro/clash/constant"
  9. "github.com/Dreamacro/clash/log"
  10. "github.com/Dreamacro/clash/config"
  11. "github.com/Dreamacro/clash/hub/executor"
  12. )
  13. func logDns(cfg *config.RawConfig) {
  14. bytes, err := yaml.Marshal(&cfg.DNS)
  15. if err != nil {
  16. log.Warnln("Marshal dns: %s", err.Error())
  17. return
  18. }
  19. log.Infoln("dns:")
  20. for _, line := range strings.Split(string(bytes), "\n") {
  21. log.Infoln(" %s", line)
  22. }
  23. }
  24. func UnmarshalAndPatch(profilePath string) (*config.RawConfig, error) {
  25. configPath := P.Join(profilePath, "config.yaml")
  26. configData, err := ioutil.ReadFile(configPath)
  27. if err != nil {
  28. return nil, err
  29. }
  30. rawConfig, err := config.UnmarshalRawConfig(configData)
  31. if err != nil {
  32. return nil, err
  33. }
  34. if err := process(rawConfig, profilePath); err != nil {
  35. return nil, err
  36. }
  37. return rawConfig, nil
  38. }
  39. func Parse(rawConfig *config.RawConfig) (*config.Config, error) {
  40. cfg, err := config.ParseRawConfig(rawConfig)
  41. if err != nil {
  42. return nil, err
  43. }
  44. return cfg, nil
  45. }
  46. func Load(path string) error {
  47. rawCfg, err := UnmarshalAndPatch(path)
  48. if err != nil {
  49. log.Errorln("Load %s: %s", path, err.Error())
  50. return err
  51. }
  52. logDns(rawCfg)
  53. cfg, err := Parse(rawCfg)
  54. if err != nil {
  55. log.Errorln("Load %s: %s", path, err.Error())
  56. return err
  57. }
  58. executor.ApplyConfig(cfg, true)
  59. app.ApplySubtitlePattern(rawCfg.ClashForAndroid.UiSubtitlePattern)
  60. return nil
  61. }
  62. func LoadDefault() {
  63. rawConfig, _ := config.UnmarshalRawConfig([]byte{})
  64. _ = patchDns(rawConfig, constant.Path.HomeDir())
  65. cfg, err := config.ParseRawConfig(rawConfig)
  66. if err != nil {
  67. panic(err.Error())
  68. }
  69. executor.ApplyConfig(cfg, true)
  70. }
  71. func init() {
  72. LoadDefault()
  73. }