cuju-engine 0.3.0__py3-none-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. cuju/__init__.py +217 -0
  2. cuju/__main__.py +262 -0
  3. cuju/_batch/__init__.py +4 -0
  4. cuju/_batch/allocator.py +52 -0
  5. cuju/_batch/assets.py +68 -0
  6. cuju/_batch/environment.py +1890 -0
  7. cuju/_batch/frame_stack.py +114 -0
  8. cuju/_batch/library.py +190 -0
  9. cuju/_batch/log.py +103 -0
  10. cuju/_batch/memory.py +70 -0
  11. cuju/_batch/operators.py +55 -0
  12. cuju/_batch/pinned.py +39 -0
  13. cuju/_batch/pixels.py +207 -0
  14. cuju/_batch/state.py +77 -0
  15. cuju/_checksums.py +60 -0
  16. cuju/_cli_contract.py +244 -0
  17. cuju/_cli_parsers.py +191 -0
  18. cuju/_completion.py +277 -0
  19. cuju/_dump_to_txt.py +66 -0
  20. cuju/_grf_config.py +331 -0
  21. cuju/_library_path.py +141 -0
  22. cuju/_media.py +113 -0
  23. cuju/_pixels.py +276 -0
  24. cuju/_plugins.py +106 -0
  25. cuju/_python_players.py +224 -0
  26. cuju/_replay_command.py +109 -0
  27. cuju/_replay_player.py +42 -0
  28. cuju/_replays.py +414 -0
  29. cuju/_script_helpers.py +109 -0
  30. cuju/_version.py +6 -0
  31. cuju/action_log.py +371 -0
  32. cuju/check.py +596 -0
  33. cuju/cuju_cpu.dll +0 -0
  34. cuju/cuju_cuda.dll +0 -0
  35. cuju/cuju_render.dll +0 -0
  36. cuju/data/SHA256SUMS +20 -0
  37. cuju/data/animations.bin +0 -0
  38. cuju/data/assets/11_vs_11_competition_l0_r0.cjb +0 -0
  39. cuju/data/assets/11_vs_11_easy_stochastic_l0_r0.cjb +0 -0
  40. cuju/data/assets/11_vs_11_hard_stochastic_l0_r0.cjb +0 -0
  41. cuju/data/assets/11_vs_11_kaggle_l0_r0.cjb +0 -0
  42. cuju/data/assets/11_vs_11_stochastic_l0_r0.cjb +0 -0
  43. cuju/data/assets/1_vs_1_easy_l0_r0.cjb +0 -0
  44. cuju/data/assets/5_vs_5_l0_r0.cjb +0 -0
  45. cuju/data/assets/academy_3_vs_1_with_keeper_l0_r0.cjb +0 -0
  46. cuju/data/assets/academy_corner_l0_r0.cjb +0 -0
  47. cuju/data/assets/academy_counterattack_easy_l0_r0.cjb +0 -0
  48. cuju/data/assets/academy_counterattack_hard_l0_r0.cjb +0 -0
  49. cuju/data/assets/academy_empty_goal_close_l0_r0.cjb +0 -0
  50. cuju/data/assets/academy_empty_goal_l0_r0.cjb +0 -0
  51. cuju/data/assets/academy_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  52. cuju/data/assets/academy_run_pass_and_shoot_with_keeper_l0_r0.cjb +0 -0
  53. cuju/data/assets/academy_run_to_score_l0_r0.cjb +0 -0
  54. cuju/data/assets/academy_run_to_score_with_keeper_l0_r0.cjb +0 -0
  55. cuju/data/assets/academy_single_goal_versus_lazy_l0_r0.cjb +0 -0
  56. cuju/data/assets/test_example_multiagent_l0_r0.cjb +0 -0
  57. cuju/data/digests.json +186 -0
  58. cuju/data/render_digests.json.z +0 -0
  59. cuju/data/scenarios/11_vs_11_competition.py +45 -0
  60. cuju/data/scenarios/11_vs_11_easy_stochastic.py +44 -0
  61. cuju/data/scenarios/11_vs_11_hard_stochastic.py +44 -0
  62. cuju/data/scenarios/11_vs_11_kaggle.py +46 -0
  63. cuju/data/scenarios/11_vs_11_stochastic.py +44 -0
  64. cuju/data/scenarios/1_vs_1_easy.py +25 -0
  65. cuju/data/scenarios/5_vs_5.py +33 -0
  66. cuju/data/scenarios/academy_3_vs_1_with_keeper.py +28 -0
  67. cuju/data/scenarios/academy_corner.py +45 -0
  68. cuju/data/scenarios/academy_counterattack_easy.py +45 -0
  69. cuju/data/scenarios/academy_counterattack_hard.py +45 -0
  70. cuju/data/scenarios/academy_empty_goal.py +25 -0
  71. cuju/data/scenarios/academy_empty_goal_close.py +25 -0
  72. cuju/data/scenarios/academy_pass_and_shoot_with_keeper.py +27 -0
  73. cuju/data/scenarios/academy_run_pass_and_shoot_with_keeper.py +27 -0
  74. cuju/data/scenarios/academy_run_to_score.py +30 -0
  75. cuju/data/scenarios/academy_run_to_score_with_keeper.py +30 -0
  76. cuju/data/scenarios/academy_single_goal_versus_lazy.py +49 -0
  77. cuju/data/scenarios/test_example_multiagent.py +28 -0
  78. cuju/dumps.py +942 -0
  79. cuju/engine_status.py +106 -0
  80. cuju/env.py +1168 -0
  81. cuju/errors.py +108 -0
  82. cuju/gfootball/GRF_SOURCES +86 -0
  83. cuju/gfootball/__init__.py +60 -0
  84. cuju/gfootball/_cv2.py +43 -0
  85. cuju/gfootball/_gym/__init__.py +88 -0
  86. cuju/gfootball/_gym/_vendored/GYM_SOURCES +22 -0
  87. cuju/gfootball/_gym/_vendored/__init__.py +43 -0
  88. cuju/gfootball/_gym/_vendored/core.py +361 -0
  89. cuju/gfootball/_gym/_vendored/envs/__init__.py +19 -0
  90. cuju/gfootball/_gym/_vendored/envs/registration.py +284 -0
  91. cuju/gfootball/_gym/_vendored/error.py +230 -0
  92. cuju/gfootball/_gym/_vendored/logger.py +56 -0
  93. cuju/gfootball/_gym/_vendored/spaces/__init__.py +30 -0
  94. cuju/gfootball/_gym/_vendored/spaces/box.py +171 -0
  95. cuju/gfootball/_gym/_vendored/spaces/dict.py +162 -0
  96. cuju/gfootball/_gym/_vendored/spaces/discrete.py +41 -0
  97. cuju/gfootball/_gym/_vendored/spaces/multi_binary.py +61 -0
  98. cuju/gfootball/_gym/_vendored/spaces/multi_discrete.py +77 -0
  99. cuju/gfootball/_gym/_vendored/spaces/space.py +94 -0
  100. cuju/gfootball/_gym/_vendored/spaces/tuple.py +96 -0
  101. cuju/gfootball/_gym/_vendored/spaces/utils.py +228 -0
  102. cuju/gfootball/_gym/_vendored/utils/__init__.py +13 -0
  103. cuju/gfootball/_gym/_vendored/utils/closer.py +72 -0
  104. cuju/gfootball/_gym/_vendored/utils/colorize.py +36 -0
  105. cuju/gfootball/_gym/_vendored/utils/ezpickle.py +37 -0
  106. cuju/gfootball/_gym/_vendored/utils/json_utils.py +27 -0
  107. cuju/gfootball/_gym/_vendored/utils/seeding.py +101 -0
  108. cuju/gfootball/_gym/_vendored/version.py +5 -0
  109. cuju/gfootball/_gym/_vendored/wrappers/__init__.py +8 -0
  110. cuju/gfootball/_gym/_vendored/wrappers/order_enforcing.py +20 -0
  111. cuju/gfootball/_gym/_vendored/wrappers/time_limit.py +31 -0
  112. cuju/gfootball/dump_to_txt.py +49 -0
  113. cuju/gfootball/dump_to_video.py +33 -0
  114. cuju/gfootball/env/__init__.py +271 -0
  115. cuju/gfootball/env/config.py +163 -0
  116. cuju/gfootball/env/constants.py +33 -0
  117. cuju/gfootball/env/controller_base.py +114 -0
  118. cuju/gfootball/env/event_queue.py +54 -0
  119. cuju/gfootball/env/football_action_set.py +220 -0
  120. cuju/gfootball/env/football_action_set_test.py +76 -0
  121. cuju/gfootball/env/football_env.py +225 -0
  122. cuju/gfootball/env/football_env_core.py +447 -0
  123. cuju/gfootball/env/football_env_test.py +692 -0
  124. cuju/gfootball/env/gym_test.py +47 -0
  125. cuju/gfootball/env/observation_preprocessing.py +94 -0
  126. cuju/gfootball/env/observation_processor.py +526 -0
  127. cuju/gfootball/env/observation_rotation.py +163 -0
  128. cuju/gfootball/env/observation_rotation_test.py +84 -0
  129. cuju/gfootball/env/player_base.py +46 -0
  130. cuju/gfootball/env/players/__init__.py +16 -0
  131. cuju/gfootball/env/players/agent.py +39 -0
  132. cuju/gfootball/env/players/bot.py +217 -0
  133. cuju/gfootball/env/players/gamepad.py +81 -0
  134. cuju/gfootball/env/players/keyboard.py +72 -0
  135. cuju/gfootball/env/players/lazy.py +31 -0
  136. cuju/gfootball/env/players/ppo2_cnn.py +119 -0
  137. cuju/gfootball/env/players/replay.py +40 -0
  138. cuju/gfootball/env/remote_football_env.py +189 -0
  139. cuju/gfootball/env/scenario_builder.py +125 -0
  140. cuju/gfootball/env/script_helpers.py +130 -0
  141. cuju/gfootball/env/script_helpers_test.py +107 -0
  142. cuju/gfootball/env/wrappers.py +440 -0
  143. cuju/gfootball/env/wrappers_test.py +150 -0
  144. cuju/gfootball/eval_server/__init__.py +17 -0
  145. cuju/gfootball/eval_server/config.py +30 -0
  146. cuju/gfootball/eval_server/example_client.py +107 -0
  147. cuju/gfootball/eval_server/proto/game_server.proto +62 -0
  148. cuju/gfootball/eval_server/proto/game_server_pb2.py +501 -0
  149. cuju/gfootball/eval_server/proto/game_server_pb2_grpc.py +113 -0
  150. cuju/gfootball/eval_server/proto/master.proto +25 -0
  151. cuju/gfootball/eval_server/proto/master_pb2.py +184 -0
  152. cuju/gfootball/eval_server/proto/master_pb2_grpc.py +62 -0
  153. cuju/gfootball/eval_server/utils.py +52 -0
  154. cuju/gfootball/examples/__init__.py +16 -0
  155. cuju/gfootball/examples/models.py +66 -0
  156. cuju/gfootball/examples/run_multiagent_rllib.py +140 -0
  157. cuju/gfootball/examples/run_ppo2.py +123 -0
  158. cuju/gfootball/play_game.py +73 -0
  159. cuju/gfootball/replay.py +43 -0
  160. cuju/gfootball/scenarios/11_vs_11_competition.py +59 -0
  161. cuju/gfootball/scenarios/11_vs_11_easy_stochastic.py +57 -0
  162. cuju/gfootball/scenarios/11_vs_11_hard_stochastic.py +57 -0
  163. cuju/gfootball/scenarios/11_vs_11_kaggle.py +60 -0
  164. cuju/gfootball/scenarios/11_vs_11_stochastic.py +57 -0
  165. cuju/gfootball/scenarios/1_vs_1_easy.py +39 -0
  166. cuju/gfootball/scenarios/5_vs_5.py +46 -0
  167. cuju/gfootball/scenarios/__init__.py +31 -0
  168. cuju/gfootball/scenarios/academy_3_vs_1_with_keeper.py +42 -0
  169. cuju/gfootball/scenarios/academy_corner.py +59 -0
  170. cuju/gfootball/scenarios/academy_counterattack_easy.py +59 -0
  171. cuju/gfootball/scenarios/academy_counterattack_hard.py +59 -0
  172. cuju/gfootball/scenarios/academy_empty_goal.py +39 -0
  173. cuju/gfootball/scenarios/academy_empty_goal_close.py +39 -0
  174. cuju/gfootball/scenarios/academy_pass_and_shoot_with_keeper.py +41 -0
  175. cuju/gfootball/scenarios/academy_run_pass_and_shoot_with_keeper.py +41 -0
  176. cuju/gfootball/scenarios/academy_run_to_score.py +44 -0
  177. cuju/gfootball/scenarios/academy_run_to_score_with_keeper.py +44 -0
  178. cuju/gfootball/scenarios/academy_single_goal_versus_lazy.py +63 -0
  179. cuju/gfootball/scenarios/test_example_multiagent.py +42 -0
  180. cuju/gfootball/scenarios/tests/11_vs_11_deterministic.py +58 -0
  181. cuju/gfootball/scenarios/tests/11_vs_11_easy_deterministic.py +58 -0
  182. cuju/gfootball/scenarios/tests/11_vs_11_hard_deterministic.py +58 -0
  183. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_deterministic.py +58 -0
  184. cuju/gfootball/scenarios/tests/11_vs_11_single_goal_stochastic.py +58 -0
  185. cuju/gfootball/scenarios/tests/11_vs_4_offence_deterministic.py +47 -0
  186. cuju/gfootball/scenarios/tests/11_vs_4_offence_stochastic.py +47 -0
  187. cuju/gfootball/scenarios/tests/__init__.py +31 -0
  188. cuju/gfootball/scenarios/tests/corner_test.py +38 -0
  189. cuju/gfootball/scenarios/tests/goal_test.py +35 -0
  190. cuju/gfootball/scenarios/tests/keeper_test.py +38 -0
  191. cuju/gfootball/scenarios/tests/kickoff_for_goal_loosing_team_test.py +34 -0
  192. cuju/gfootball/scenarios/tests/multiagent_wrapper.py +60 -0
  193. cuju/gfootball/scenarios/tests/offside_test.py +39 -0
  194. cuju/gfootball/scenarios/tests/penalty.py +34 -0
  195. cuju/gfootball/scenarios/tests/second_half.py +33 -0
  196. cuju/gfootball/scenarios/tests/symmetric.py +53 -0
  197. cuju/gfootball_engine/__init__.py +31 -0
  198. cuju/gfootball_engine/_gameplayfootball.py +1624 -0
  199. cuju/gfootball_engine/_native.py +193 -0
  200. cuju/gfootball_engine/_pickle_names.py +114 -0
  201. cuju/gfootball_engine/_render_hooks.py +156 -0
  202. cuju/kaggle.py +425 -0
  203. cuju/multi_device.py +401 -0
  204. cuju/players.py +260 -0
  205. cuju/raw.py +93 -0
  206. cuju/scenarios.py +661 -0
  207. cuju/state.py +211 -0
  208. cuju/wrappers.py +325 -0
  209. cuju_engine-0.3.0.dist-info/METADATA +325 -0
  210. cuju_engine-0.3.0.dist-info/RECORD +222 -0
  211. cuju_engine-0.3.0.dist-info/WHEEL +5 -0
  212. cuju_engine-0.3.0.dist-info/entry_points.txt +4 -0
  213. cuju_engine-0.3.0.dist-info/licenses/LICENSE +202 -0
  214. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSD-3-Clause.txt +31 -0
  215. cuju_engine-0.3.0.dist-info/licenses/LICENSES/BSL-1.0.txt +23 -0
  216. cuju_engine-0.3.0.dist-info/licenses/LICENSES/LGPL-2.1-or-later.txt +502 -0
  217. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-Mesa.txt +26 -0
  218. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT-gym.txt +23 -0
  219. cuju_engine-0.3.0.dist-info/licenses/LICENSES/MIT.txt +23 -0
  220. cuju_engine-0.3.0.dist-info/licenses/LICENSES/SunPro.txt +8 -0
  221. cuju_engine-0.3.0.dist-info/licenses/LICENSES/Zlib.txt +20 -0
  222. cuju_engine-0.3.0.dist-info/licenses/NOTICE +56 -0
cuju/_cli_parsers.py ADDED
@@ -0,0 +1,191 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Lightweight argument parsers for the engine commands."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ from typing import Any
10
+
11
+ from ._cli_contract import Parser, add_globals, add_json, examples
12
+
13
+ # The summary that `cuju help` and the root parser give each command of the engine.
14
+ SUMMARIES = {
15
+ 'check': 'check the engine against known match outputs',
16
+ 'replay': 'replay a dump and check that it plays the same',
17
+ 'dump-to-txt': 'write a dump as readable text',
18
+ 'help': 'describe the commands of the family, or one of them',
19
+ 'completion': 'print the completion script of a shell',
20
+ }
21
+ SHELLS = ('bash', 'zsh', 'fish', 'powershell')
22
+
23
+
24
+ def _make(group: Any, name: str, description: str, epilog: str) -> Parser:
25
+ """Returns the parser of the command `name`, a subparser of `group` or a stand-alone one."""
26
+ if group is None:
27
+ parser = Parser(prog=f'cuju {name}', description=description, epilog=epilog)
28
+ else:
29
+ parser = group.add_parser(
30
+ name, prog=f'cuju {name}', help=SUMMARIES[name], description=description, epilog=epilog
31
+ )
32
+ parser.set_defaults(_command_parser=parser)
33
+ return parser
34
+
35
+
36
+ def check(group: Any = None) -> Parser:
37
+ """Returns the parser of `cuju check`, as a subparser of `group` if given."""
38
+ parser = _make(
39
+ group,
40
+ 'check',
41
+ 'Check the engine against known match outputs. The check verifies the package data '
42
+ 'and compares the matches played on each selected backend with the expected digests.',
43
+ examples(
44
+ 'cuju check',
45
+ 'cuju check --device cpu',
46
+ 'cuju check --case 5_vs_5/simple115v2 --json',
47
+ 'cuju check --list',
48
+ ),
49
+ )
50
+ parser.add_argument(
51
+ '--device',
52
+ choices=['all', 'cpu', 'cuda'],
53
+ default='all',
54
+ metavar='DEVICE',
55
+ help='check all, cpu or cuda, all by default',
56
+ )
57
+ parser.add_argument(
58
+ '--long', action='store_true', help='also play the long cases, which take several minutes'
59
+ )
60
+ parser.add_argument(
61
+ '--case', action='append', metavar='NAME', help='play only the case NAME, may repeat'
62
+ )
63
+ parser.add_argument('--list', action='store_true', help='list the cases and play none')
64
+ add_json(parser)
65
+ add_globals(parser)
66
+ return parser
67
+
68
+
69
+ def _flag(text: str) -> bool:
70
+ """Returns the value of a boolean flag written as absl reads it."""
71
+ lowered = text.lower()
72
+ if lowered in ('true', 't', '1'):
73
+ return True
74
+ if lowered in ('false', 'f', '0'):
75
+ return False
76
+ raise argparse.ArgumentTypeError(f'expected true or false, found {text!r}')
77
+
78
+
79
+ def replay(group: Any = None) -> Parser:
80
+ """Returns the parser of `cuju replay`, with the flags of GRF's script."""
81
+ parser = _make(
82
+ group,
83
+ 'replay',
84
+ 'Replay a dump and check that it plays the same. The replay compares each step with '
85
+ 'the recorded step, apart from wall-clock time.',
86
+ examples(
87
+ 'cuju replay --trace_file /tmp/dumps/episode_done.dump',
88
+ 'cuju replay --trace_file /tmp/dumps/episode_done.dump --device cpu --json',
89
+ ),
90
+ )
91
+ parser.add_argument('--trace_file', required=True, metavar='FILE', help='the dump to replay')
92
+ parser.add_argument(
93
+ '--fps',
94
+ type=int,
95
+ default=None,
96
+ metavar='N',
97
+ help='frames per second, the frame rate of the dump by default',
98
+ )
99
+ parser.add_argument(
100
+ '--device',
101
+ default='cpu',
102
+ metavar='DEVICE',
103
+ help='cpu, cuda, cuda:N or auto, cpu by default',
104
+ )
105
+ add_json(parser)
106
+ add_globals(parser)
107
+ return parser
108
+
109
+
110
+ def dump_to_txt(group: Any = None) -> Parser:
111
+ """Returns the parser of `cuju dump-to-txt`, with the flags of GRF's script."""
112
+ parser = _make(
113
+ group,
114
+ 'dump-to-txt',
115
+ 'Write a dump as readable text. The command reads dumps written by GRF and cuju.',
116
+ examples(
117
+ 'cuju dump-to-txt --trace_file /tmp/input.dump --output /tmp/output.txt --json',
118
+ 'cuju dump-to-txt --trace_file in.dump --output out.txt --noinclude_debug',
119
+ ),
120
+ )
121
+ parser.add_argument('--trace_file', required=True, metavar='FILE', help='the dump to convert')
122
+ parser.add_argument('--output', required=True, metavar='FILE', help='the text file to write')
123
+ parser.add_argument(
124
+ '--include_debug',
125
+ nargs='?',
126
+ const=True,
127
+ default=True,
128
+ type=_flag,
129
+ metavar='NAME',
130
+ help='write the debug information of each step, true by default',
131
+ )
132
+ parser.add_argument(
133
+ '--noinclude_debug',
134
+ dest='include_debug',
135
+ action='store_false',
136
+ help='leave out the debug information of each step',
137
+ )
138
+ add_json(parser)
139
+ add_globals(parser)
140
+ return parser
141
+
142
+
143
+ def help_command(group: Any = None) -> Parser:
144
+ """Returns the parser of `cuju help`."""
145
+ parser = _make(
146
+ group,
147
+ 'help',
148
+ 'Describe the commands of the family. Without words it lists the commands of the engine '
149
+ 'and then those of each package installed beside it. With the words of a command it '
150
+ 'prints the help of that command, so cuju help arena team add equals cuju arena team '
151
+ 'add --help.',
152
+ examples('cuju help', 'cuju help check', 'cuju help arena team add'),
153
+ )
154
+ parser.add_argument(
155
+ 'words',
156
+ nargs='*',
157
+ metavar='NAME',
158
+ help='a command and the words below it, none to list the commands',
159
+ )
160
+ add_globals(parser)
161
+ return parser
162
+
163
+
164
+ def completion(group: Any = None) -> Parser:
165
+ """Returns the parser of `cuju completion`."""
166
+ parser = _make(
167
+ group,
168
+ 'completion',
169
+ 'Print the completion script of a shell, bash, zsh, fish or powershell. The script is '
170
+ 'static and holds the commands and options of every package installed now, so run this '
171
+ 'command again after installing or removing a package. Redirect the output into the '
172
+ 'folder of completion scripts of the shell, or source it from the startup file.',
173
+ examples(
174
+ 'cuju completion bash',
175
+ 'cuju completion zsh',
176
+ 'cuju completion fish',
177
+ 'cuju completion powershell',
178
+ ),
179
+ )
180
+ parser.add_argument('shell', choices=SHELLS, help='the shell to complete for', metavar='NAME')
181
+ add_globals(parser)
182
+ return parser
183
+
184
+
185
+ BUILDERS = {
186
+ 'check': check,
187
+ 'replay': replay,
188
+ 'dump-to-txt': dump_to_txt,
189
+ 'help': help_command,
190
+ 'completion': completion,
191
+ }
cuju/_completion.py ADDED
@@ -0,0 +1,277 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ """Builds static shell completions from the installed parsers."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import argparse
9
+ import shlex
10
+
11
+ from ._cli_contract import subcommands
12
+
13
+ _FILES = {'FILE': 'file', 'DIR': 'directory', 'PATH': 'file'}
14
+
15
+
16
+ def _tree(root, packages):
17
+ def walk(path, tree):
18
+ children = (
19
+ {name: child for group in subcommands(tree) for name, child in group.choices.items()}
20
+ if tree is not None
21
+ else {}
22
+ )
23
+ if not path:
24
+ children.update(packages)
25
+ yield path, tree, children
26
+ for name, child in children.items():
27
+ yield from walk((*path, name), child)
28
+
29
+ return list(walk((), root))
30
+
31
+
32
+ def _values(action):
33
+ if action.choices is not None:
34
+ return tuple(map(str, action.choices)), ''
35
+ return (), _FILES.get(action.metavar, '') if isinstance(action.metavar, str) else ''
36
+
37
+
38
+ def _actions(tree):
39
+ if tree is None:
40
+ return []
41
+ return [
42
+ action
43
+ for action in tree._actions
44
+ if action.help != argparse.SUPPRESS and not isinstance(action, argparse._SubParsersAction)
45
+ ]
46
+
47
+
48
+ def _rows(nodes):
49
+ for path, tree, children in nodes:
50
+ name = ' '.join(path)
51
+ flags, positionals, files = [], [], ''
52
+ for action in _actions(tree):
53
+ words, kind = _values(action)
54
+ flags.extend(action.option_strings)
55
+ if not action.option_strings:
56
+ positionals.extend(words)
57
+ files = files or kind
58
+ elif action.nargs != 0:
59
+ for option in action.option_strings:
60
+ yield f'{name}|{option}', words, kind
61
+ yield name, (*children, *flags, *positionals), files
62
+
63
+
64
+ def _transitions(nodes):
65
+ for path, tree, children in nodes:
66
+ name = ' '.join(path)
67
+ for child in children:
68
+ yield f'{name}|{child}', ' '.join((*path, child))
69
+ for action in _actions(tree):
70
+ if action.nargs != 0:
71
+ for flag in action.option_strings:
72
+ yield f'{name}|{flag}', action.nargs == '?'
73
+
74
+
75
+ def _bourne(nodes, shell):
76
+ quote = shlex.quote
77
+ body = [
78
+ '_cuju_context() {',
79
+ ' local context= pending= optional= word flag',
80
+ ' for word in "$@"; do',
81
+ ' if [ -n "$pending" ]; then',
82
+ ' [ "$word" = "=" ] && continue',
83
+ ' pending=',
84
+ ' if [ -z "$optional" ] || [[ "$word" != -* ]]; then continue; fi',
85
+ ' fi',
86
+ ' flag=${word%%=*}',
87
+ ' case "$context|$flag" in',
88
+ ]
89
+ for key, value in _transitions(nodes):
90
+ if isinstance(value, str):
91
+ code = f'context={quote(value)}'
92
+ else:
93
+ optional = 'yes' if value else "''"
94
+ code = f'[ "$word" != "$flag" ] || {{ pending=$flag; optional={optional}; }}'
95
+ body.append(f' {quote(key)}) {code} ;;')
96
+ body += [
97
+ ' esac',
98
+ ' done',
99
+ ' if [ -n "$optional" ] && [[ "$current" == -* ]]; then pending=; fi',
100
+ ' case "$context${pending:+|$pending}" in',
101
+ ]
102
+ for key, words, files in _rows(nodes):
103
+ if shell == 'bash':
104
+ command = ' '.join(['_cuju_offer', quote(files), *map(quote, words)])
105
+ else:
106
+ parts = []
107
+ if words:
108
+ parts.append('compadd -- ' + shlex.join(words))
109
+ if files:
110
+ parts.append('_files -/' if files == 'directory' else '_files')
111
+ command = '; '.join(parts) or ':'
112
+ body.append(f' {quote(key)}) {command} ;;')
113
+ body += [' esac', '}']
114
+ if shell == 'bash':
115
+ body += [
116
+ '_cuju_offer() {',
117
+ ' local files="$1" candidate',
118
+ ' shift',
119
+ ' for candidate in "$@"; do',
120
+ ' [[ "$candidate" == "$current"* ]] && COMPREPLY+=("$prefix$candidate")',
121
+ ' done',
122
+ ' if [[ -n "$files" ]]; then',
123
+ ' [[ "$files" == directory ]] && files=-d || files=-f',
124
+ ' while IFS= read -r candidate; do',
125
+ ' COMPREPLY+=("$prefix$candidate")',
126
+ ' done < <(compgen "$files" -- "$current")',
127
+ ' compopt -o filenames',
128
+ ' fi',
129
+ '}',
130
+ '_cuju() {',
131
+ ' local current="${COMP_WORDS[COMP_CWORD]}" prefix=',
132
+ ' local previous=("${COMP_WORDS[@]:1:COMP_CWORD-1}")',
133
+ ' COMPREPLY=()',
134
+ ' if [[ "$current" == -*=* ]]; then',
135
+ ' prefix="${current%%=*}="',
136
+ ' previous+=("${prefix%=}")',
137
+ ' current="${current#*=}"',
138
+ ' fi',
139
+ ' _cuju_context "${previous[@]}"',
140
+ '}',
141
+ 'complete -F _cuju cuju',
142
+ ]
143
+ else:
144
+ body += [
145
+ '_cuju_complete() {',
146
+ ' local current="$PREFIX"',
147
+ ' local -a previous',
148
+ ' previous=("${(@)words[2,CURRENT-1]}")',
149
+ ' if [[ "$current" == -*=* ]]; then',
150
+ ' previous+=("${current%%=*}")',
151
+ " compset -P '*='",
152
+ ' current="$PREFIX"',
153
+ ' fi',
154
+ ' _cuju_context "${previous[@]}"',
155
+ '}',
156
+ 'if [[ "${funcstack[1]}" == _cuju ]]; then',
157
+ ' _cuju_complete',
158
+ 'elif (( $+functions[compdef] )); then',
159
+ ' compdef _cuju_complete cuju',
160
+ 'fi',
161
+ ]
162
+ return body
163
+
164
+
165
+ def _fish_quote(value):
166
+ return "'" + value.replace('\\', '\\\\').replace("'", "\\'") + "'"
167
+
168
+
169
+ def _fish(nodes):
170
+ quote = _fish_quote
171
+ body = [
172
+ 'function __cuju_context',
173
+ ' set -l words (commandline -opc)',
174
+ ' set -l context root',
175
+ ' set -l pending 0',
176
+ ' for word in $words[2..-1]',
177
+ ' if test $pending -eq 1',
178
+ ' set pending 0',
179
+ ' continue',
180
+ ' end',
181
+ ' switch "$context|$word"',
182
+ ]
183
+ for key, value in _transitions(nodes):
184
+ key = key if not key.startswith('|') else 'root' + key
185
+ code = f'set context {quote(value)}' if isinstance(value, str) else 'set pending 1'
186
+ body.extend((f' case {quote(key)}', f' {code}'))
187
+ body += [' end', ' end', ' echo "$context"', 'end', 'complete -c cuju -f']
188
+ for path, tree, children in nodes:
189
+ context = quote(' '.join(path) or 'root')
190
+ command = 'complete -c cuju -n ' + quote(f'test (__cuju_context) = {context}')
191
+ for child in children:
192
+ body.append(f'{command} -a {quote(quote(child))}')
193
+ for action in _actions(tree):
194
+ args = []
195
+ for flag in action.option_strings:
196
+ prefix, value = ('-l', flag[2:]) if flag.startswith('--') else ('-s', flag[1:])
197
+ args.extend((prefix, quote(value)))
198
+ if action.option_strings and action.nargs not in (0, '?'):
199
+ args.append('-r')
200
+ values, files = _values(action)
201
+ if values:
202
+ args.extend(('-a', quote(' '.join(map(quote, values)))))
203
+ if files == 'directory':
204
+ args.extend(('-a', quote('(__fish_complete_directories (commandline -ct))')))
205
+ elif files:
206
+ args.append('-F')
207
+ if args:
208
+ body.append(f'{command} {" ".join(args)}')
209
+ return body
210
+
211
+
212
+ def _powershell(nodes):
213
+ def quote(value):
214
+ return "'" + value.replace("'", "''") + "'"
215
+
216
+ body = [
217
+ 'Register-ArgumentCompleter -Native -CommandName cuju -ScriptBlock {',
218
+ ' param($wordToComplete, $commandAst, $cursorPosition)',
219
+ " $context = ''",
220
+ " $option = ''",
221
+ ' foreach ($element in ($commandAst.CommandElements | Select-Object -Skip 1)) {',
222
+ ' if ($element.Extent.EndOffset -ge $cursorPosition) { break }',
223
+ " if ($option) { $option = ''; continue }",
224
+ ' $word = $element.Value',
225
+ ' if ($null -eq $word) { $word = $element.Extent.Text }',
226
+ ' switch -CaseSensitive -Exact ("$context|$word") {',
227
+ ]
228
+ for key, value in _transitions(nodes):
229
+ code = f'$context = {quote(value)}' if isinstance(value, str) else '$option = $word'
230
+ body.append(f' {quote(key)} {{ {code}; break }}')
231
+ body += [
232
+ ' }',
233
+ ' }',
234
+ ' if ($option) { $context = "$context|$option" }',
235
+ ' $candidates = @()',
236
+ " $files = ''",
237
+ ' switch -CaseSensitive -Exact ($context) {',
238
+ ]
239
+ for key, words, files in _rows(nodes):
240
+ candidates = ', '.join(map(quote, words))
241
+ values = f'$candidates = @({candidates}); $files = {quote(files)}'
242
+ body.append(f' {quote(key)} {{ {values} }}')
243
+ body += [
244
+ ' }',
245
+ ' foreach ($candidate in $candidates) {',
246
+ ' if ($candidate.StartsWith($wordToComplete, [StringComparison]::OrdinalIgnoreCase)) {',
247
+ ' $value = $candidate',
248
+ ' $quote = [string][char]39',
249
+ ' if ($value -match "[\\s$quote]") {',
250
+ ' $value = $quote + $value.Replace($quote, $quote + $quote) + $quote',
251
+ ' }',
252
+ ' [System.Management.Automation.CompletionResult]::new(',
253
+ ' $value, $candidate, "ParameterValue", $candidate)',
254
+ ' }',
255
+ ' }',
256
+ ' if ($files) {',
257
+ ' $completers = [System.Management.Automation.CompletionCompleters]',
258
+ ' $completers::CompleteFilename($wordToComplete) |',
259
+ " Where-Object { $files -eq 'file' -or $_.ResultType -eq 'ProviderContainer' }",
260
+ ' }',
261
+ '}',
262
+ ]
263
+ return body
264
+
265
+
266
+ def script(shell, root, packages, versions):
267
+ """Returns the completion script for one shell."""
268
+ nodes = _tree(root, {name: tree for name, _, tree in packages})
269
+ if shell in ('bash', 'zsh'):
270
+ body = _bourne(nodes, shell)
271
+ elif shell == 'fish':
272
+ body = _fish(nodes)
273
+ else:
274
+ body = _powershell(nodes)
275
+ header = '# Cuju completion for ' + ', '.join(' '.join(line.splitlines()) for line in versions)
276
+ lines = ['#compdef cuju', header] if shell == 'zsh' else [header]
277
+ return '\n'.join([*lines, *body])
cuju/_dump_to_txt.py ADDED
@@ -0,0 +1,66 @@
1
+ # Copyright 2026 The cuju Authors
2
+ # Copyright 2019 Google LLC
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ """`cuju dump-to-txt`, GRF's script `dump_to_txt` with GRF's flags, which writes a dump as text.
6
+
7
+ It reads the dump with `cuju.dumps`, so dumps of GRF, of `cuju.env`, of a batch and of
8
+ `cuju.gfootball` print alike, and runs no code from them.
9
+
10
+ cuju dump-to-txt --trace_file=/tmp/input.dump --output=/tmp/output.txt
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import sys
17
+
18
+ from . import _cli_contract as contract
19
+ from . import _cli_parsers, dumps
20
+ from ._script_helpers import _dump_text, _grf_steps
21
+
22
+ __all__ = ['main']
23
+
24
+
25
+ def _run(arguments: argparse.Namespace) -> int:
26
+ path = arguments.trace_file
27
+ try:
28
+ text = _dump_text(_grf_steps(dumps._read_cli_dump(path)), arguments.include_debug)
29
+ except (OSError, ValueError, KeyError, TypeError) as error:
30
+ detail = (error.strerror or str(error)).lower() if isinstance(error, OSError) else error
31
+ return contract.fail(
32
+ 'cuju dump-to-txt',
33
+ f'expected a readable dump at {contract.quote_path(path)}, found {detail}',
34
+ hint='run cuju dump-to-txt --trace_file FILE --output PATH with a GRF or Cuju dump.',
35
+ as_json=arguments.json,
36
+ error_id='dump_to_txt.dump',
37
+ values={'file': path},
38
+ )
39
+ try:
40
+ with open(arguments.output, 'w') as handle:
41
+ handle.write(text)
42
+ except OSError as error:
43
+ return contract.fail(
44
+ 'cuju dump-to-txt',
45
+ f'expected a writable output file at {contract.quote_path(arguments.output)}, '
46
+ f'found {error.strerror}',
47
+ hint='run cuju dump-to-txt --trace_file FILE --output PATH with a writable path.',
48
+ as_json=arguments.json,
49
+ status=contract.EXIT_ENVIRONMENT,
50
+ error_id='dump_to_txt.output',
51
+ values={'output': arguments.output},
52
+ )
53
+ if arguments.json:
54
+ contract.emit('engine.dump_to_txt/1', {'files': [arguments.output]})
55
+ else:
56
+ print(arguments.output)
57
+ return 0
58
+
59
+
60
+ def main(argv: list[str] | None = None) -> int:
61
+ """Runs the converter on the command line."""
62
+ return contract.run_command(_cli_parsers.dump_to_txt(), _run, argv)
63
+
64
+
65
+ if __name__ == '__main__':
66
+ sys.exit(main())