Skip to content

Commit

Permalink
Code refactoring for app module
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexxIT committed Jun 2, 2024
1 parent 2ab1d9d commit 756be98
Show file tree
Hide file tree
Showing 15 changed files with 182 additions and 217 deletions.
155 changes: 18 additions & 137 deletions internal/app/app.go
Original file line number Diff line number Diff line change
@@ -1,29 +1,20 @@
package app

import (
"errors"
"flag"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"runtime/debug"
"strings"

"github.com/AlexxIT/go2rtc/pkg/shell"
"github.com/AlexxIT/go2rtc/pkg/yaml"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)

var Version = "1.9.2"
var UserAgent = "go2rtc/" + Version

var ConfigPath string
var Info = map[string]any{
"version": Version,
}
var (
Version string
UserAgent string
ConfigPath string
Info = make(map[string]any)
)

const usage = `Usage of go2rtc:
Expand All @@ -33,12 +24,12 @@ const usage = `Usage of go2rtc:
`

func Init() {
var confs Config
var config flagConfig
var daemon bool
var version bool

flag.Var(&confs, "config", "")
flag.Var(&confs, "c", "")
flag.Var(&config, "config", "")
flag.Var(&config, "c", "")
flag.BoolVar(&daemon, "daemon", false, "")
flag.BoolVar(&daemon, "d", false, "")
flag.BoolVar(&version, "version", false, "")
Expand Down Expand Up @@ -69,118 +60,30 @@ func Init() {
// Re-run the program in background and exit
cmd := exec.Command(os.Args[0], args...)
if err := cmd.Start(); err != nil {
log.Fatal().Err(err).Send()
fmt.Println(err)
os.Exit(1)
}
fmt.Println("Running in daemon mode with PID:", cmd.Process.Pid)
os.Exit(0)
}

if confs == nil {
confs = []string{"go2rtc.yaml"}
}

for _, conf := range confs {
if len(conf) == 0 {
continue
}
if conf[0] == '{' {
// config as raw YAML or JSON
configs = append(configs, []byte(conf))
} else if data := parseConfString(conf); data != nil {
configs = append(configs, data)
} else {
// config as file
if ConfigPath == "" {
ConfigPath = conf
}

if data, _ = os.ReadFile(conf); data == nil {
continue
}

data = []byte(shell.ReplaceEnvVars(string(data)))
configs = append(configs, data)
}
}

if ConfigPath != "" {
if !filepath.IsAbs(ConfigPath) {
if cwd, err := os.Getwd(); err == nil {
ConfigPath = filepath.Join(cwd, ConfigPath)
}
}
Info["config_path"] = ConfigPath
}
UserAgent = "go2rtc/" + Version

Info["version"] = Version
Info["revision"] = revision

var cfg struct {
Mod map[string]string `yaml:"log"`
}

cfg.Mod = map[string]string{
"format": "", // useless, but anyway
"level": "info",
"output": "stdout", // TODO: change to stderr someday
"time": zerolog.TimeFormatUnixMs,
}

LoadConfig(&cfg)

log.Logger = NewLogger(cfg.Mod)

modules = cfg.Mod
initConfig(config)
initLogger()

platform := fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH)
log.Info().Str("version", Version).Str("platform", platform).Str("revision", revision).Msg("go2rtc")
log.Debug().Str("version", runtime.Version()).Str("vcs.time", vcsTime).Msg("build")
Logger.Info().Str("version", Version).Str("platform", platform).Str("revision", revision).Msg("go2rtc")
Logger.Debug().Str("version", runtime.Version()).Str("vcs.time", vcsTime).Msg("build")

if ConfigPath != "" {
log.Info().Str("path", ConfigPath).Msg("config")
}

migrateStore()
}

func LoadConfig(v any) {
for _, data := range configs {
if err := yaml.Unmarshal(data, v); err != nil {
log.Warn().Err(err).Msg("[app] read config")
}
}
}

func PatchConfig(key string, value any, path ...string) error {
if ConfigPath == "" {
return errors.New("config file disabled")
Logger.Info().Str("path", ConfigPath).Msg("config")
}

// empty config is OK
b, _ := os.ReadFile(ConfigPath)

b, err := yaml.Patch(b, key, value, path...)
if err != nil {
return err
}

return os.WriteFile(ConfigPath, b, 0644)
}

// internal

type Config []string

func (c *Config) String() string {
return strings.Join(*c, " ")
}

func (c *Config) Set(value string) error {
*c = append(*c, value)
return nil
}

var configs [][]byte

func readRevisionTime() (revision, vcsTime string) {
if info, ok := debug.ReadBuildInfo(); ok {
for _, setting := range info.Settings {
Expand All @@ -202,25 +105,3 @@ func readRevisionTime() (revision, vcsTime string) {
}
return
}

func parseConfString(s string) []byte {
i := strings.IndexByte(s, '=')
if i < 0 {
return nil
}

items := strings.Split(s[:i], ".")
if len(items) < 2 {
return nil
}

// `log.level=trace` => `{log: {level: trace}}`
var pre string
var suf = s[i+1:]
for _, item := range items {
pre += "{" + item + ": "
suf += "}"
}

return []byte(pre + suf)
}
109 changes: 109 additions & 0 deletions internal/app/config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
package app

import (
"errors"
"os"
"path/filepath"
"strings"

"github.com/AlexxIT/go2rtc/pkg/shell"
"github.com/AlexxIT/go2rtc/pkg/yaml"
)

func LoadConfig(v any) {
for _, data := range configs {
if err := yaml.Unmarshal(data, v); err != nil {
Logger.Warn().Err(err).Send()
}
}
}

func PatchConfig(key string, value any, path ...string) error {
if ConfigPath == "" {
return errors.New("config file disabled")
}

// empty config is OK
b, _ := os.ReadFile(ConfigPath)

b, err := yaml.Patch(b, key, value, path...)
if err != nil {
return err
}

return os.WriteFile(ConfigPath, b, 0644)
}

type flagConfig []string

func (c *flagConfig) String() string {
return strings.Join(*c, " ")
}

func (c *flagConfig) Set(value string) error {
*c = append(*c, value)
return nil
}

var configs [][]byte

func initConfig(confs flagConfig) {
if confs == nil {
confs = []string{"go2rtc.yaml"}
}

for _, conf := range confs {
if len(conf) == 0 {
continue
}
if conf[0] == '{' {
// config as raw YAML or JSON
configs = append(configs, []byte(conf))
} else if data := parseConfString(conf); data != nil {
configs = append(configs, data)
} else {
// config as file
if ConfigPath == "" {
ConfigPath = conf
}

if data, _ = os.ReadFile(conf); data == nil {
continue
}

data = []byte(shell.ReplaceEnvVars(string(data)))
configs = append(configs, data)
}
}

if ConfigPath != "" {
if !filepath.IsAbs(ConfigPath) {
if cwd, err := os.Getwd(); err == nil {
ConfigPath = filepath.Join(cwd, ConfigPath)
}
}
Info["config_path"] = ConfigPath
}
}

func parseConfString(s string) []byte {
i := strings.IndexByte(s, '=')
if i < 0 {
return nil
}

items := strings.Split(s[:i], ".")
if len(items) < 2 {
return nil
}

// `log.level=trace` => `{log: {level: trace}}`
var pre string
var suf = s[i+1:]
for _, item := range items {
pre += "{" + item + ": "
suf += "}"
}

return []byte(pre + suf)
}
Loading

0 comments on commit 756be98

Please sign in to comment.