gosuki/mozilla/prefs.go

130 lines
2.4 KiB
Go
Raw Normal View History

2018-12-03 18:51:01 +00:00
package mozilla
import (
"errors"
"fmt"
"io/ioutil"
"os"
"regexp"
)
const (
2018-12-04 03:34:30 +00:00
PrefsFile = "prefs.js"
// Parses vales in prefs.js under the form:
// user_pref("my.pref.option", value);
2018-12-04 17:06:30 +00:00
REFirefoxPrefs = `user_pref\("(?P<option>%s)",\s+"*(?P<value>.*[^"])"*\)\s*;\s*(\n|$)`
)
var (
ErrPrefNotFound = errors.New("pref not defined")
ErrPrefNotBool = errors.New("pref is not bool")
2018-12-03 18:51:01 +00:00
)
2018-12-04 03:34:30 +00:00
// Finds and returns a prefernce definition.
// Returns empty string ("") if no pref found
2018-12-03 18:51:01 +00:00
func FindPref(path string, name string) (string, error) {
text, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
re := regexp.MustCompile(fmt.Sprintf(REFirefoxPrefs, name))
match := re.FindSubmatch(text)
if match == nil {
return "", nil
}
results := map[string]string{}
for i, name := range match {
results[re.SubexpNames()[i]] = string(name)
}
return results["value"], nil
}
2018-12-04 17:06:30 +00:00
// Returns true if the `name` preference is found in `prefs.js`
2018-12-04 03:34:30 +00:00
func HasPref(path string, name string) (bool, error) {
res, err := FindPref(path, name)
if err != nil {
return false, err
}
if res != "" {
return true, nil
}
return false, nil
}
2018-12-03 18:51:01 +00:00
func GetPrefBool(path string, name string) (bool, error) {
val, err := FindPref(path, name)
if err != nil {
return false, err
}
switch val {
case "":
2018-12-04 17:06:30 +00:00
return false, ErrPrefNotFound
case "true":
2018-12-03 18:51:01 +00:00
return true, nil
case "false":
2018-12-03 18:51:01 +00:00
return false, nil
default:
return false, ErrPrefNotBool
2018-12-03 18:51:01 +00:00
}
}
// Set a preference in the preference file under `path`
func SetPrefBool(path string, name string, val bool) error {
// Get file mode
info, err := os.Stat(path)
if err != nil {
return err
}
mode := info.Mode()
2018-12-04 17:06:30 +00:00
// Pref already defined, replace it
if v, _ := HasPref(path, name); v {
2018-12-03 18:51:01 +00:00
2018-12-04 17:06:30 +00:00
f, err := os.OpenFile(path, os.O_RDWR, mode)
defer f.Sync()
defer f.Close()
2018-12-03 18:51:01 +00:00
2018-12-04 17:06:30 +00:00
if err != nil {
return err
}
re := regexp.MustCompile(fmt.Sprintf(REFirefoxPrefs, name))
template := []byte(fmt.Sprintf("user_pref(\"$option\", %t) ;\n", val))
text, err := ioutil.ReadAll(f)
if err != nil {
return err
}
_, err = f.Seek(0, 0)
if err != nil {
return err
}
output := string(re.ReplaceAll(text, template))
fmt.Fprint(f, output)
} else {
f, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND, mode)
defer f.Sync()
defer f.Close()
if err != nil {
return err
}
// Append pref
fmt.Fprintf(f, "user_pref(\"%s\", %t);\n", name, val)
2018-12-03 18:51:01 +00:00
}
return nil
}