api.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package config
  3. import (
  4. "bufio"
  5. "bytes"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/fs"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "regexp"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "kitty"
  18. "kitty/tools/utils"
  19. "github.com/shirou/gopsutil/v3/process"
  20. "golang.org/x/sys/unix"
  21. )
  22. var _ = fmt.Print
  23. func StringToBool(x string) bool {
  24. x = strings.ToLower(x)
  25. return x == "y" || x == "yes" || x == "true"
  26. }
  27. type ConfigLine struct {
  28. Src_file, Line string
  29. Line_number int
  30. Err error
  31. }
  32. type ConfigParser struct {
  33. LineHandler func(key, val string) error
  34. CommentsHandler func(line string) error
  35. SourceHandler func(text, path string)
  36. bad_lines []ConfigLine
  37. seen_includes map[string]bool
  38. override_env []string
  39. }
  40. type Scanner interface {
  41. Scan() bool
  42. Text() string
  43. Err() error
  44. }
  45. func (self *ConfigParser) BadLines() []ConfigLine {
  46. return self.bad_lines
  47. }
  48. var key_pat = sync.OnceValue(func() *regexp.Regexp {
  49. return regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9_-]*)\s+(.+)$`)
  50. })
  51. func (self *ConfigParser) parse(scanner Scanner, name, base_path_for_includes string, depth int) error {
  52. if self.seen_includes[name] { // avoid include loops
  53. return nil
  54. }
  55. self.seen_includes[name] = true
  56. recurse := func(r io.Reader, nname, base_path_for_includes string) error {
  57. if depth > 32 {
  58. return fmt.Errorf("Too many nested include directives while processing config file: %s", name)
  59. }
  60. escanner := bufio.NewScanner(r)
  61. return self.parse(escanner, nname, base_path_for_includes, depth+1)
  62. }
  63. make_absolute := func(path string) (string, error) {
  64. if path == "" {
  65. return "", fmt.Errorf("Empty include paths not allowed")
  66. }
  67. if !filepath.IsAbs(path) {
  68. path = filepath.Join(base_path_for_includes, path)
  69. }
  70. return path, nil
  71. }
  72. lnum := 0
  73. next_line_num := 0
  74. next_line := ""
  75. var line string
  76. for {
  77. if next_line != "" {
  78. line = next_line
  79. } else {
  80. if scanner.Scan() {
  81. line = strings.TrimLeft(scanner.Text(), " \t")
  82. next_line_num++
  83. } else {
  84. break
  85. }
  86. if line == "" {
  87. continue
  88. }
  89. }
  90. lnum = next_line_num
  91. if scanner.Scan() {
  92. next_line = strings.TrimLeft(scanner.Text(), " \t")
  93. next_line_num++
  94. for strings.HasPrefix(next_line, `\`) {
  95. line += next_line[1:]
  96. if scanner.Scan() {
  97. next_line = strings.TrimLeft(scanner.Text(), " \t")
  98. next_line_num++
  99. } else {
  100. next_line = ""
  101. }
  102. }
  103. } else {
  104. next_line = ""
  105. }
  106. if line[0] == '#' {
  107. if self.CommentsHandler != nil {
  108. err := self.CommentsHandler(line)
  109. if err != nil {
  110. self.bad_lines = append(self.bad_lines, ConfigLine{Src_file: name, Line: line, Line_number: lnum, Err: err})
  111. }
  112. }
  113. continue
  114. }
  115. m := key_pat().FindStringSubmatch(line)
  116. if len(m) < 3 {
  117. self.bad_lines = append(self.bad_lines, ConfigLine{Src_file: name, Line: line, Line_number: lnum, Err: fmt.Errorf("Invalid config line: %#v", line)})
  118. continue
  119. }
  120. key, val := m[1], m[2]
  121. for i, ch := range line {
  122. if ch == ' ' || ch == '\t' {
  123. key = line[:i]
  124. val = strings.TrimSpace(line[i+1:])
  125. break
  126. }
  127. }
  128. switch key {
  129. default:
  130. err := self.LineHandler(key, val)
  131. if err != nil {
  132. self.bad_lines = append(self.bad_lines, ConfigLine{Src_file: name, Line: line, Line_number: lnum, Err: err})
  133. }
  134. case "include", "globinclude", "envinclude":
  135. var includes []string
  136. switch key {
  137. case "include":
  138. aval, err := make_absolute(val)
  139. if err == nil {
  140. includes = []string{aval}
  141. }
  142. case "globinclude":
  143. aval, err := make_absolute(val)
  144. if err == nil {
  145. matches, err := filepath.Glob(aval)
  146. if err == nil {
  147. includes = matches
  148. }
  149. }
  150. case "envinclude":
  151. env := self.override_env
  152. if env == nil {
  153. env = os.Environ()
  154. }
  155. for _, x := range env {
  156. key, eval, _ := strings.Cut(x, "=")
  157. is_match, err := filepath.Match(val, key)
  158. if is_match && err == nil {
  159. err := recurse(strings.NewReader(eval), "<env var: "+key+">", base_path_for_includes)
  160. if err != nil {
  161. return err
  162. }
  163. }
  164. }
  165. }
  166. if len(includes) > 0 {
  167. for _, incpath := range includes {
  168. raw, err := os.ReadFile(incpath)
  169. if err == nil {
  170. err := recurse(bytes.NewReader(raw), incpath, filepath.Dir(incpath))
  171. if err != nil {
  172. return err
  173. }
  174. } else if !errors.Is(err, fs.ErrNotExist) {
  175. return fmt.Errorf("Failed to process include %#v with error: %w", incpath, err)
  176. }
  177. }
  178. }
  179. }
  180. }
  181. return nil
  182. }
  183. func (self *ConfigParser) ParseFiles(paths ...string) error {
  184. for _, path := range paths {
  185. apath, err := filepath.Abs(path)
  186. if err == nil {
  187. path = apath
  188. }
  189. raw, err := os.ReadFile(path)
  190. if err != nil {
  191. return err
  192. }
  193. scanner := utils.NewLineScanner(utils.UnsafeBytesToString(raw))
  194. self.seen_includes = make(map[string]bool)
  195. err = self.parse(scanner, path, filepath.Dir(path), 0)
  196. if err != nil {
  197. return err
  198. }
  199. if self.SourceHandler != nil {
  200. self.SourceHandler(utils.UnsafeBytesToString(raw), path)
  201. }
  202. }
  203. return nil
  204. }
  205. func (self *ConfigParser) LoadConfig(name string, paths []string, overrides []string) (err error) {
  206. const SYSTEM_CONF = "/etc/xdg/kitty"
  207. system_conf := filepath.Join(SYSTEM_CONF, name)
  208. add_if_exists := func(q string) {
  209. err = self.ParseFiles(q)
  210. if err != nil && errors.Is(err, fs.ErrNotExist) {
  211. err = nil
  212. }
  213. }
  214. if add_if_exists(system_conf); err != nil {
  215. return err
  216. }
  217. if len(paths) > 0 {
  218. for _, path := range paths {
  219. if add_if_exists(path); err != nil {
  220. return err
  221. }
  222. }
  223. } else {
  224. if add_if_exists(filepath.Join(utils.ConfigDirForName(name), name)); err != nil {
  225. return err
  226. }
  227. }
  228. if len(overrides) > 0 {
  229. err = self.ParseOverrides(overrides...)
  230. if err != nil {
  231. return err
  232. }
  233. }
  234. return
  235. }
  236. type LinesScanner struct {
  237. lines []string
  238. }
  239. func (self *LinesScanner) Scan() bool {
  240. return len(self.lines) > 0
  241. }
  242. func (self *LinesScanner) Text() string {
  243. ans := self.lines[0]
  244. self.lines = self.lines[1:]
  245. return ans
  246. }
  247. func (self *LinesScanner) Err() error {
  248. return nil
  249. }
  250. func (self *ConfigParser) ParseOverrides(overrides ...string) error {
  251. s := LinesScanner{lines: utils.Map(func(x string) string {
  252. return strings.Replace(x, "=", " ", 1)
  253. }, overrides)}
  254. self.seen_includes = make(map[string]bool)
  255. return self.parse(&s, "<overrides>", utils.ConfigDir(), 0)
  256. }
  257. func is_kitty_gui_cmdline(exe string, cmd ...string) bool {
  258. if len(cmd) == 0 {
  259. return false
  260. }
  261. if filepath.Base(exe) != "kitty" {
  262. return false
  263. }
  264. if len(cmd) == 1 {
  265. return true
  266. }
  267. s := cmd[1][:1]
  268. switch s {
  269. case `@`:
  270. return false
  271. case `+`:
  272. if cmd[1] == `+` {
  273. return len(cmd) > 2 && cmd[2] == `open`
  274. }
  275. return cmd[1] == `+open`
  276. }
  277. return true
  278. }
  279. type Patcher struct {
  280. Write_backup bool
  281. Mode fs.FileMode
  282. }
  283. func (self Patcher) Patch(path, sentinel, content string, settings_to_comment_out ...string) (updated bool, err error) {
  284. if self.Mode == 0 {
  285. self.Mode = 0o644
  286. }
  287. backup_path := path
  288. if q, err := filepath.EvalSymlinks(path); err == nil {
  289. path = q
  290. }
  291. raw, err := os.ReadFile(path)
  292. if err != nil && !errors.Is(err, fs.ErrNotExist) {
  293. return false, err
  294. }
  295. add_at_top := ""
  296. backup := true
  297. if raw == nil {
  298. cc := kitty.CommentedOutDefaultConfig
  299. if idx := strings.Index(cc, "\n\n"); idx > 0 {
  300. add_at_top = cc[:idx+2]
  301. raw = []byte(cc[idx+2:])
  302. backup = false
  303. }
  304. }
  305. pat := utils.MustCompile(fmt.Sprintf(`(?m)^\s*(%s)\b`, strings.Join(settings_to_comment_out, "|")))
  306. text := pat.ReplaceAllString(utils.UnsafeBytesToString(raw), `# $1`)
  307. pat = utils.MustCompile(fmt.Sprintf(`(?ms)^# BEGIN_%s.+?# END_%s`, sentinel, sentinel))
  308. replaced := false
  309. addition := fmt.Sprintf("# BEGIN_%s\n%s\n# END_%s", sentinel, content, sentinel)
  310. ntext := pat.ReplaceAllStringFunc(text, func(string) string {
  311. replaced = true
  312. return addition
  313. })
  314. if !replaced {
  315. if add_at_top != "" {
  316. ntext = add_at_top + addition
  317. if text != "" {
  318. ntext += "\n\n" + text
  319. }
  320. } else {
  321. if text != "" {
  322. text += "\n\n"
  323. }
  324. ntext = text + addition
  325. }
  326. }
  327. nraw := utils.UnsafeStringToBytes(ntext)
  328. if !bytes.Equal(raw, nraw) {
  329. if len(raw) > 0 && self.Write_backup && backup {
  330. _ = os.WriteFile(backup_path+".bak", raw, self.Mode)
  331. }
  332. return true, utils.AtomicUpdateFile(path, bytes.NewReader(nraw), self.Mode)
  333. }
  334. return false, nil
  335. }
  336. func ReloadConfigInKitty(in_parent_only bool) error {
  337. if in_parent_only {
  338. if pid, err := strconv.Atoi(os.Getenv("KITTY_PID")); err == nil {
  339. if p, err := process.NewProcess(int32(pid)); err == nil {
  340. if exe, eerr := p.Exe(); eerr == nil {
  341. if c, err := p.CmdlineSlice(); err == nil && is_kitty_gui_cmdline(exe, c...) {
  342. return p.SendSignal(unix.SIGUSR1)
  343. }
  344. }
  345. }
  346. }
  347. return nil
  348. }
  349. // process.Processes() followed by filtering by getting the process
  350. // exe and cmdline is very slow on non-Linux systems as CGO is not allowed
  351. // which means getting exe works by calling lsof on every process. So instead do
  352. // initial filtering based on ps output.
  353. if ps_out, err := exec.Command("ps", "-x", "-o", "pid=,comm=").Output(); err == nil {
  354. for _, line := range utils.Splitlines(utils.UnsafeBytesToString(ps_out)) {
  355. line = strings.TrimSpace(line)
  356. if pid_string, argv0, found := strings.Cut(line, " "); found {
  357. if pid, err := strconv.Atoi(strings.TrimSpace(pid_string)); err == nil && strings.Contains(argv0, "kitty") {
  358. if p, err := process.NewProcess(int32(pid)); err == nil {
  359. if cmdline, err := p.CmdlineSlice(); err == nil {
  360. if exe, err := p.Exe(); err == nil && is_kitty_gui_cmdline(exe, cmdline...) {
  361. _ = p.SendSignal(unix.SIGUSR1)
  362. }
  363. }
  364. }
  365. }
  366. }
  367. }
  368. }
  369. return nil
  370. }