build_web_example.odin 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package karl2d_build_web_example
  2. import "core:os"
  3. import "core:fmt"
  4. import "core:path/filepath"
  5. import "core:os/os2"
  6. main :: proc() {
  7. if len(os.args) != 2 {
  8. fmt.eprintfln("Usage: 'odin run build_web_example -- example_directory_name'\nExample: 'odin run build_web_example -- minimal'")
  9. return
  10. }
  11. WEB_ENTRY_TEMPLATE :: #load("web_entry_templates/web_entry_template.odin")
  12. WEB_ENTRY_INDEX :: #load("web_entry_templates/index_template.html")
  13. dir := os.args[1]
  14. dir_handle, dir_handle_err := os.open(dir)
  15. fmt.ensuref(dir_handle_err == nil, "Failed finding directory %v. Error: %v", dir, dir_handle_err)
  16. dir_stat, dir_stat_err := os.fstat(dir_handle)
  17. fmt.ensuref(dir_stat_err == nil, "Failed checking status of directory %v. Error: %v", dir, dir_stat_err)
  18. fmt.ensuref(dir_stat.is_dir, "%v is not a directory!", dir)
  19. web_dir := filepath.join({dir, "web"})
  20. os.make_directory(web_dir, 0o644)
  21. web_build_dir := filepath.join({web_dir, "build"})
  22. os.make_directory(web_build_dir, 0o644)
  23. os.write_entire_file(
  24. filepath.join(
  25. {web_dir, fmt.tprintf("%v_web_entry.odin", filepath.stem(dir))},
  26. ),
  27. WEB_ENTRY_TEMPLATE,
  28. )
  29. os.write_entire_file(filepath.join({web_build_dir, "index.html"}), WEB_ENTRY_INDEX)
  30. _, odin_root_stdout, _, odin_root_err := os2.process_exec({
  31. command = { "odin", "root" },
  32. }, allocator = context.allocator)
  33. ensure(odin_root_err == nil, "Failed fetching 'odin root' (Odin in PATH needed!)")
  34. odin_root := string(odin_root_stdout)
  35. js_runtime_path := filepath.join({odin_root, "core", "sys", "wasm", "js", "odin.js"})
  36. fmt.ensuref(os2.exists(js_runtime_path), "File does not exist: %v -- It is the Odin Javascript runtime that this program needs to copy to the web build output folder!", js_runtime_path)
  37. os2.copy_file(filepath.join({web_build_dir, "odin.js"}), js_runtime_path)
  38. wasm_out_path := filepath.join({web_build_dir, "main.wasm"})
  39. build_status, build_std_out, build_std_err, build_err := os2.process_exec({
  40. command = {
  41. "odin",
  42. "build",
  43. web_dir,
  44. fmt.tprintf("-out:%v", wasm_out_path),
  45. "-target:js_wasm32",
  46. "-o:speed",
  47. "-vet",
  48. "-strict-style",
  49. },
  50. }, allocator = context.allocator)
  51. if len(build_std_out) > 0 {
  52. fmt.println(string(build_std_out))
  53. }
  54. if len(build_std_err) > 0 {
  55. fmt.println(string(build_std_err))
  56. }
  57. }