115 lines
2.4 KiB
Go
115 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
)
|
|
|
|
// TODO: This is a total work in progress. It generally works execept it's ugly and regex strings aren't parsed correctly
|
|
|
|
// Config is the full set of configuration required
|
|
type Config struct {
|
|
DefaultBrowserCommand []string
|
|
Rules []BrowserRuleConfig
|
|
}
|
|
|
|
// BrowserRuleConfig represents a BrowserRule
|
|
type BrowserRuleConfig struct {
|
|
BrowserCommand []string
|
|
Matchers []MatcherConfig
|
|
}
|
|
|
|
// MatcherConfig represents a single MatchFunc
|
|
type MatcherConfig struct {
|
|
Kind string
|
|
Targets []string
|
|
}
|
|
|
|
func parseConfig(jsonBytes []byte) (Config, error) {
|
|
var c Config
|
|
err := json.Unmarshal(jsonBytes, &c)
|
|
return c, err
|
|
}
|
|
|
|
// GetRules returns all rules parsed from a JSON string
|
|
func GetRules(jsonBytes []byte) (rules []BrowserRule, err error) {
|
|
c, err := parseConfig(jsonBytes)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
for _, rule := range c.Rules {
|
|
if len(rule.BrowserCommand) < 1 {
|
|
err = fmt.Errorf("Must provide a browser command")
|
|
return
|
|
}
|
|
browserCommand := rule.BrowserCommand[0]
|
|
args := rule.BrowserCommand[1:]
|
|
|
|
matchers := []MatchFunc{}
|
|
for _, matcher := range rule.Matchers {
|
|
switch matcher.Kind {
|
|
case "matchHostname":
|
|
fmt.Println("Match hostname for ", matcher.Targets)
|
|
matchers = append(matchers, matchHostname(matcher.Targets...))
|
|
case "matchHostRegexp":
|
|
matchers = append(matchers, matchHostRegexp(matcher.Targets...))
|
|
case "matchRegexp":
|
|
matchers = append(matchers, matchRegexp(matcher.Targets...))
|
|
default:
|
|
err = fmt.Errorf("Unknown matcher kind %s", matcher.Kind)
|
|
return
|
|
}
|
|
}
|
|
var matcher MatchFunc
|
|
if len(matchers) == 1 {
|
|
matcher = matchers[0]
|
|
} else {
|
|
matcher = matchAny(matchers...)
|
|
}
|
|
|
|
rules = append(
|
|
rules,
|
|
BrowserRule{
|
|
matcher: matcher,
|
|
command: browserCommand,
|
|
args: args,
|
|
},
|
|
BrowserRule{
|
|
matcher: defaultBrowser,
|
|
command: c.DefaultBrowserCommand[0],
|
|
args: c.DefaultBrowserCommand[1:],
|
|
},
|
|
)
|
|
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
func GetTestRules() ([]BrowserRule, error) {
|
|
jsonBytes := []byte(`{
|
|
"DefaultBrowserCommand": ["chromium-browser"],
|
|
"Rules": [
|
|
{
|
|
"BrowserCommand": ["firefox"],
|
|
"Matchers": [
|
|
{
|
|
"Kind": "matchHostname",
|
|
"Targets": [
|
|
"iamthefij.com"
|
|
]
|
|
},
|
|
{
|
|
"Kind": "matchHostRegexp",
|
|
"Targets": [
|
|
".*\.iamthefij\.com$",
|
|
]
|
|
}
|
|
]
|
|
}
|
|
]
|
|
}`)
|
|
return GetRules(jsonBytes)
|
|
}
|