devenv.go 11 KB

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