devenv.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. // License: GPLv3 Copyright: 2023, Kovid Goyal, <kovid at kovidgoyal.net>
  2. package main
  3. import (
  4. "bufio"
  5. "bytes"
  6. "errors"
  7. "flag"
  8. "fmt"
  9. "io"
  10. "io/fs"
  11. "net/http"
  12. "os"
  13. "os/exec"
  14. "path/filepath"
  15. "regexp"
  16. "runtime"
  17. "strings"
  18. )
  19. const (
  20. folder = "dependencies"
  21. fonts_folder = "fonts"
  22. macos_prefix = "/Users/Shared/kitty-build/sw/sw"
  23. macos_python = "python/Python.framework/Versions/Current/bin/python3"
  24. macos_python_framework = "python/Python.framework/Versions/Current/Python"
  25. macos_python_framework_exe = "python/Python.framework/Versions/Current/Resources/Python.app/Contents/MacOS/Python"
  26. NERD_URL = "https://github.com/ryanoasis/nerd-fonts/releases/latest/download/NerdFontsSymbolsOnly.tar.xz"
  27. )
  28. func root_dir() string {
  29. f, e := filepath.Abs(filepath.Join(folder, runtime.GOOS+"-"+runtime.GOARCH))
  30. if e != nil {
  31. exit(e)
  32. }
  33. return f
  34. }
  35. func fonts_dir() string {
  36. f, e := filepath.Abs(fonts_folder)
  37. if e != nil {
  38. exit(e)
  39. }
  40. return f
  41. }
  42. var _ = fmt.Print
  43. func exit(x any) {
  44. switch v := x.(type) {
  45. case error:
  46. if v == nil {
  47. os.Exit(0)
  48. }
  49. var ee *exec.ExitError
  50. if errors.As(v, &ee) {
  51. os.Exit(ee.ExitCode())
  52. }
  53. case string:
  54. if v == "" {
  55. os.Exit(0)
  56. }
  57. case int:
  58. os.Exit(v)
  59. }
  60. fmt.Fprintf(os.Stderr, "\x1b[31mError\x1b[m: %s\n", x)
  61. os.Exit(1)
  62. }
  63. // download deps {{{
  64. type dependency struct {
  65. path string
  66. basename string
  67. is_id bool
  68. }
  69. func lines(exe string, cmd ...string) []string {
  70. c := exec.Command(exe, cmd...)
  71. c.Stderr = os.Stderr
  72. out, err := c.Output()
  73. if err != nil {
  74. exit(fmt.Errorf("Failed to run '%s' with error: %w", strings.Join(append([]string{exe}, cmd...), " "), err))
  75. }
  76. ans := []string{}
  77. for s := bufio.NewScanner(bytes.NewReader(out)); s.Scan(); {
  78. ans = append(ans, s.Text())
  79. }
  80. return ans
  81. }
  82. func get_dependencies(path string) (ans []dependency) {
  83. a := lines("otool", "-D", path)
  84. install_name := strings.TrimSpace(a[len(a)-1])
  85. for _, line := range lines("otool", "-L", path) {
  86. line = strings.TrimSpace(line)
  87. if strings.Contains(line, "compatibility") && !strings.HasSuffix(line, ":") {
  88. idx := strings.IndexByte(line, '(')
  89. dep := strings.TrimSpace(line[:idx])
  90. ans = append(ans, dependency{path: dep, is_id: dep == install_name})
  91. }
  92. }
  93. return
  94. }
  95. func get_local_dependencies(path string) (ans []dependency) {
  96. for _, dep := range get_dependencies(path) {
  97. for _, y := range []string{filepath.Join(macos_prefix, "lib") + "/", filepath.Join(macos_prefix, "python", "Python.framework") + "/", "@rpath/"} {
  98. if strings.HasPrefix(dep.path, y) {
  99. if y == "@rpath/" {
  100. dep.basename = "lib/" + dep.path[len(y):]
  101. } else {
  102. y = macos_prefix + "/"
  103. dep.basename = dep.path[len(y):]
  104. }
  105. ans = append(ans, dep)
  106. break
  107. }
  108. }
  109. }
  110. return
  111. }
  112. func change_dep(path string, dep dependency) {
  113. cmd := []string{}
  114. fid := filepath.Join(root_dir(), dep.basename)
  115. if dep.is_id {
  116. cmd = append(cmd, "-id", fid)
  117. } else {
  118. cmd = append(cmd, "-change", dep.path, fid)
  119. }
  120. cmd = append(cmd, path)
  121. c := exec.Command("install_name_tool", cmd...)
  122. c.Stdout = os.Stdout
  123. c.Stderr = os.Stderr
  124. if err := c.Run(); err != nil {
  125. exit(fmt.Errorf("Failed to run command '%s' with error: %w", strings.Join(c.Args, " "), err))
  126. }
  127. }
  128. func fix_dependencies_in_lib(path string) {
  129. path, err := filepath.EvalSymlinks(path)
  130. if err != nil {
  131. exit(err)
  132. }
  133. if s, err := os.Stat(path); err != nil {
  134. exit(err)
  135. } else if err := os.Chmod(path, s.Mode().Perm()|0o200); err != nil {
  136. exit(err)
  137. }
  138. for _, dep := range get_local_dependencies(path) {
  139. change_dep(path, dep)
  140. }
  141. if ldeps := get_local_dependencies(path); len(ldeps) > 0 {
  142. exit(fmt.Errorf("Failed to fix local dependencies in: %s", path))
  143. }
  144. }
  145. func cached_download(url string) string {
  146. fname := filepath.Base(url)
  147. fmt.Println("Downloading", fname)
  148. req, err := http.NewRequest("GET", url, nil)
  149. if err != nil {
  150. exit(err)
  151. }
  152. etag_file := filepath.Join(folder, fname+".etag")
  153. if etag, err := os.ReadFile(etag_file); err == nil {
  154. if _, err := os.Stat(filepath.Join(folder, fname)); err == nil {
  155. req.Header.Add("If-None-Match", string(etag))
  156. }
  157. }
  158. client := &http.Client{}
  159. resp, err := client.Do(req)
  160. if err != nil {
  161. exit(err)
  162. }
  163. defer resp.Body.Close()
  164. if resp.StatusCode != http.StatusOK {
  165. if resp.StatusCode == http.StatusNotModified {
  166. return filepath.Join(folder, fname)
  167. }
  168. exit(fmt.Errorf("The server responded with the HTTP error: %s", resp.Status))
  169. }
  170. f, err := os.Create(filepath.Join(folder, fname))
  171. if err != nil {
  172. exit(err)
  173. }
  174. defer f.Close()
  175. if _, err := io.Copy(f, resp.Body); err != nil {
  176. exit(fmt.Errorf("Failed to download file with error: %w", err))
  177. }
  178. if etag := resp.Header.Get("ETag"); etag != "" {
  179. if err := os.WriteFile(etag_file, []byte(etag), 0o644); err != nil {
  180. exit(err)
  181. }
  182. }
  183. return f.Name()
  184. }
  185. func relocate_pkgconfig(path, old_prefix, new_prefix string) error {
  186. raw, err := os.ReadFile(path)
  187. if err != nil {
  188. return err
  189. }
  190. nraw := bytes.ReplaceAll(raw, []byte(old_prefix), []byte(new_prefix))
  191. return os.WriteFile(path, nraw, 0o644)
  192. }
  193. func chdir_to_base() {
  194. _, filename, _, _ := runtime.Caller(0)
  195. base_dir := filepath.Dir(filepath.Dir(filename))
  196. if err := os.Chdir(base_dir); err != nil {
  197. exit(err)
  198. }
  199. }
  200. func dependencies_for_docs() {
  201. fmt.Println("Downloading get-pip.py")
  202. rq, err := http.Get("https://bootstrap.pypa.io/get-pip.py")
  203. if err != nil {
  204. exit(err)
  205. }
  206. defer rq.Body.Close()
  207. if rq.StatusCode != http.StatusOK {
  208. exit(fmt.Errorf("Server responded with HTTP error: %s", rq.Status))
  209. }
  210. gp, err := os.Create(filepath.Join(folder, "get-pip.py"))
  211. if err != nil {
  212. exit(err)
  213. }
  214. defer gp.Close()
  215. if _, err = io.Copy(gp, rq.Body); err != nil {
  216. exit(err)
  217. }
  218. python := setup_to_run_python()
  219. run := func(exe string, args ...string) {
  220. c := exec.Command(exe, args...)
  221. c.Stdout = os.Stdout
  222. c.Stderr = os.Stderr
  223. if err := c.Run(); err != nil {
  224. exit(err)
  225. }
  226. }
  227. run(python, gp.Name())
  228. run(python, "-m", "pip", "install", "-r", "docs/requirements.txt")
  229. }
  230. func dependencies(args []string) {
  231. chdir_to_base()
  232. nf := flag.NewFlagSet("deps", flag.ExitOnError)
  233. docsptr := nf.Bool("for-docs", false, "download the dependencies needed to build the documentation")
  234. if err := nf.Parse(args); err != nil {
  235. exit(err)
  236. }
  237. if *docsptr {
  238. dependencies_for_docs()
  239. fmt.Println("Dependencies needed to generate documentation have been installed. Build docs with ./dev.sh docs")
  240. exit(0)
  241. }
  242. data, err := os.ReadFile(".github/workflows/ci.py")
  243. if err != nil {
  244. exit(err)
  245. }
  246. pat := regexp.MustCompile("BUNDLE_URL = '(.+?)'")
  247. prefix := "/sw/sw"
  248. var url string
  249. if m := pat.FindStringSubmatch(string(data)); len(m) < 2 {
  250. exit("Failed to find BUNDLE_URL in ci.py")
  251. } else {
  252. url = m[1]
  253. }
  254. var which string
  255. switch runtime.GOOS {
  256. case "darwin":
  257. prefix = macos_prefix
  258. which = "macos"
  259. case "linux":
  260. which = "linux"
  261. if runtime.GOARCH != "amd64" {
  262. exit("Pre-built dependencies are only available for the amd64 CPU architecture")
  263. }
  264. }
  265. if which == "" {
  266. exit("Prebuilt dependencies are only available for Linux and macOS")
  267. }
  268. url = strings.Replace(url, "{}", which, 1)
  269. if err := os.RemoveAll(root_dir()); err != nil {
  270. exit(err)
  271. }
  272. if err := os.MkdirAll(folder, 0o755); err != nil {
  273. exit(err)
  274. }
  275. tarfile, _ := filepath.Abs(cached_download(url))
  276. root := root_dir()
  277. if err := os.MkdirAll(root, 0o755); err != nil {
  278. exit(err)
  279. }
  280. cmd := exec.Command("tar", "xf", tarfile)
  281. cmd.Dir = root
  282. cmd.Stdout = os.Stdout
  283. cmd.Stderr = os.Stderr
  284. if err = cmd.Run(); err != nil {
  285. exit(err)
  286. }
  287. if runtime.GOOS == "darwin" {
  288. fix_dependencies_in_lib(filepath.Join(root, macos_python))
  289. fix_dependencies_in_lib(filepath.Join(root, macos_python_framework))
  290. fix_dependencies_in_lib(filepath.Join(root, macos_python_framework_exe))
  291. }
  292. if err = filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
  293. if err != nil {
  294. return err
  295. }
  296. if d.Type().IsRegular() {
  297. name := d.Name()
  298. ext := filepath.Ext(name)
  299. if ext == ".pc" || (ext == ".py" && strings.HasPrefix(name, "_sysconfigdata_")) {
  300. err = relocate_pkgconfig(path, prefix, root)
  301. }
  302. // remove libfontconfig so that we use the system one because
  303. // different distros stupidly use different fontconfig configuration dirs
  304. if strings.HasPrefix(name, "libfontconfig.so") {
  305. os.Remove(path)
  306. }
  307. if runtime.GOOS == "darwin" {
  308. if ext == ".so" || ext == ".dylib" {
  309. fix_dependencies_in_lib(path)
  310. }
  311. }
  312. }
  313. return err
  314. }); err != nil {
  315. exit(err)
  316. }
  317. tarfile, _ = filepath.Abs(cached_download(NERD_URL))
  318. root = fonts_dir()
  319. if err := os.MkdirAll(root, 0o755); err != nil {
  320. exit(err)
  321. }
  322. cmd = exec.Command("tar", "xf", tarfile, "SymbolsNerdFontMono-Regular.ttf")
  323. cmd.Dir = root
  324. cmd.Stdout = os.Stdout
  325. cmd.Stderr = os.Stderr
  326. if err = cmd.Run(); err != nil {
  327. exit(err)
  328. }
  329. fmt.Println(`Dependencies downloaded. Now build kitty with: ./dev.sh build`)
  330. }
  331. // }}}
  332. func prepend(env_var, path string) {
  333. val := os.Getenv(env_var)
  334. if val != "" {
  335. val = string(filepath.ListSeparator) + val
  336. }
  337. os.Setenv(env_var, path+val)
  338. }
  339. func setup_to_run_python() (python string) {
  340. root := root_dir()
  341. for _, x := range os.Environ() {
  342. if strings.HasPrefix(x, "PYTHON") {
  343. a, _, _ := strings.Cut(x, "=")
  344. os.Unsetenv(a)
  345. }
  346. }
  347. switch runtime.GOOS {
  348. case "linux":
  349. prepend("LD_LIBRARY_PATH", filepath.Join(root, "lib"))
  350. os.Setenv("PYTHONHOME", root)
  351. python = filepath.Join(root, "bin", "python")
  352. case `darwin`:
  353. python = filepath.Join(root, macos_python)
  354. default:
  355. exit("Building is only supported on Linux and macOS")
  356. }
  357. return
  358. }
  359. func build(args []string) {
  360. chdir_to_base()
  361. if _, err := os.Stat(folder); err != nil {
  362. dependencies(nil)
  363. }
  364. root := root_dir()
  365. os.Setenv("DEVELOP_ROOT", root)
  366. prepend("PKG_CONFIG_PATH", filepath.Join(root, "lib", "pkgconfig"))
  367. if runtime.GOOS == "darwin" {
  368. os.Setenv("PKGCONFIG_EXE", filepath.Join(root, "bin", "pkg-config"))
  369. }
  370. python := setup_to_run_python()
  371. args = append([]string{"setup.py", "develop"}, args...)
  372. cmd := exec.Command(python, args...)
  373. cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
  374. if err := cmd.Run(); err != nil {
  375. fmt.Fprintln(os.Stderr, "The following build command failed:", python, strings.Join(args, " "))
  376. exit(err)
  377. }
  378. fmt.Println("Build successful. Run kitty as: kitty/launcher/kitty")
  379. }
  380. func docs(args []string) {
  381. setup_to_run_python()
  382. nf := flag.NewFlagSet("deps", flag.ExitOnError)
  383. livereload := nf.Bool("live-reload", false, "build the docs and make them available via s local server with live reloading for ease of development")
  384. failwarn := nf.Bool("fail-warn", false, "make warnings fatal when building the docs")
  385. if err := nf.Parse(args); err != nil {
  386. exit(err)
  387. }
  388. exe := filepath.Join(root_dir(), "bin", "sphinx-build")
  389. aexe := filepath.Join(root_dir(), "bin", "sphinx-autobuild")
  390. target := "docs"
  391. if *livereload {
  392. target = "develop-docs"
  393. }
  394. cmd := []string{target, "SPHINXBUILD=" + exe, "SPHINXAUTOBUILD=" + aexe}
  395. if *failwarn {
  396. cmd = append(cmd, "FAILWARN=1")
  397. }
  398. c := exec.Command("make", cmd...)
  399. c.Stdout = os.Stdout
  400. c.Stderr = os.Stderr
  401. err := c.Run()
  402. if err != nil {
  403. exit(err)
  404. }
  405. fmt.Println("docs successfully built")
  406. }
  407. func main() {
  408. if len(os.Args) < 2 {
  409. exit(`Expected "deps" or "build" subcommands`)
  410. }
  411. switch os.Args[1] {
  412. case "deps":
  413. dependencies(os.Args[2:])
  414. case "build":
  415. build(os.Args[2:])
  416. case "docs":
  417. docs(os.Args[2:])
  418. case "-h", "--help":
  419. fmt.Fprintln(os.Stderr, "Usage: ./dev.sh [build|deps|docs] [options...]")
  420. default:
  421. exit(`Expected "deps" or "build" subcommands`)
  422. }
  423. }