treepos 0.0.1__py3-none-any.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 (287) hide show
  1. treepos/__init__.py +1 -0
  2. treepos/adapters/__init__.py +1 -0
  3. treepos/adapters/github_api/__init__.py +1 -0
  4. treepos/adapters/github_api/api.py +198 -0
  5. treepos/adapters/github_api/githubkit_api.py +463 -0
  6. treepos/adapters/github_api/mark_properties.py +47 -0
  7. treepos/adapters/github_api/org_members.py +106 -0
  8. treepos/adapters/github_api/repos.py +139 -0
  9. treepos/adapters/github_api/source.py +91 -0
  10. treepos/adapters/github_api/team_members.py +117 -0
  11. treepos/adapters/github_api/team_names.py +27 -0
  12. treepos/adapters/github_api/teams.py +104 -0
  13. treepos/adapters/local_source/__init__.py +62 -0
  14. treepos/adapters/memory_github/__init__.py +1 -0
  15. treepos/adapters/memory_github/live_state.py +254 -0
  16. treepos/adapters/memory_github/mark_properties.py +40 -0
  17. treepos/adapters/memory_github/org_members.py +57 -0
  18. treepos/adapters/memory_github/repos.py +115 -0
  19. treepos/adapters/memory_github/store.py +134 -0
  20. treepos/adapters/memory_github/team_members.py +69 -0
  21. treepos/adapters/memory_github/teams.py +103 -0
  22. treepos/adapters/memory_source/__init__.py +22 -0
  23. treepos/adapters/renderer_none/__init__.py +1 -0
  24. treepos/adapters/renderer_none/parse.py +140 -0
  25. treepos/adapters/renderer_none/renderer.py +11 -0
  26. treepos/adapters/renderer_none/scalars.py +54 -0
  27. treepos/catalogue/__init__.py +74 -0
  28. treepos/cli/__init__.py +1 -0
  29. treepos/cli/apply.py +57 -0
  30. treepos/cli/github_output.py +24 -0
  31. treepos/cli/log.py +25 -0
  32. treepos/cli/main.py +35 -0
  33. treepos/cli/options.py +76 -0
  34. treepos/cli/out.py +24 -0
  35. treepos/cli/plan.py +73 -0
  36. treepos/core/__init__.py +1 -0
  37. treepos/core/codes.py +165 -0
  38. treepos/core/files.py +63 -0
  39. treepos/core/findings.py +34 -0
  40. treepos/core/json.py +3 -0
  41. treepos/core/live.py +10 -0
  42. treepos/core/outcome.py +11 -0
  43. treepos/core/paths.py +46 -0
  44. treepos/core/versions.py +84 -0
  45. treepos/framework/__init__.py +1 -0
  46. treepos/framework/accepted_lines.py +37 -0
  47. treepos/framework/account_id.py +10 -0
  48. treepos/framework/built.py +34 -0
  49. treepos/framework/catalogue.py +94 -0
  50. treepos/framework/compile.py +125 -0
  51. treepos/framework/described.py +16 -0
  52. treepos/framework/envelope.py +34 -0
  53. treepos/framework/errors.py +5 -0
  54. treepos/framework/handle.py +19 -0
  55. treepos/framework/holds.py +113 -0
  56. treepos/framework/host.py +23 -0
  57. treepos/framework/identity.py +36 -0
  58. treepos/framework/interfaces.py +44 -0
  59. treepos/framework/kind.py +99 -0
  60. treepos/framework/login.py +20 -0
  61. treepos/framework/many.py +24 -0
  62. treepos/framework/node_fields.py +27 -0
  63. treepos/framework/notice.py +13 -0
  64. treepos/framework/object_type.py +89 -0
  65. treepos/framework/parts.py +67 -0
  66. treepos/framework/pass_through.py +49 -0
  67. treepos/framework/patterns/__init__.py +2 -0
  68. treepos/framework/patterns/field_path.py +72 -0
  69. treepos/framework/patterns/name.py +73 -0
  70. treepos/framework/patterns/segments.py +67 -0
  71. treepos/framework/placed.py +16 -0
  72. treepos/framework/plan_error.py +5 -0
  73. treepos/framework/problem.py +14 -0
  74. treepos/framework/repo_name.py +24 -0
  75. treepos/framework/secret_name.py +21 -0
  76. treepos/framework/sets.py +30 -0
  77. treepos/framework/spec.py +11 -0
  78. treepos/framework/topic.py +21 -0
  79. treepos/framework/tree.py +40 -0
  80. treepos/framework/tree_id.py +22 -0
  81. treepos/github/__init__.py +1 -0
  82. treepos/github/mark_properties/__init__.py +1 -0
  83. treepos/github/mark_properties/definitions.py +27 -0
  84. treepos/github/mark_properties/describe.py +9 -0
  85. treepos/github/mark_properties/diff.py +13 -0
  86. treepos/github/mark_properties/model.py +15 -0
  87. treepos/github/mark_properties/object_type.py +22 -0
  88. treepos/github/mark_properties/operations.py +11 -0
  89. treepos/github/mark_properties/order.py +13 -0
  90. treepos/github/mark_properties/precondition.py +10 -0
  91. treepos/github/mark_properties/read_back.py +17 -0
  92. treepos/github/mark_properties/type_name.py +3 -0
  93. treepos/github/org_member/__init__.py +1 -0
  94. treepos/github/org_member/describe.py +34 -0
  95. treepos/github/org_member/diff.py +18 -0
  96. treepos/github/org_member/model.py +15 -0
  97. treepos/github/org_member/object_type.py +22 -0
  98. treepos/github/org_member/operations.py +33 -0
  99. treepos/github/org_member/order.py +19 -0
  100. treepos/github/org_member/precondition.py +24 -0
  101. treepos/github/org_member/read_back.py +75 -0
  102. treepos/github/org_member/type_name.py +3 -0
  103. treepos/github/repository/__init__.py +1 -0
  104. treepos/github/repository/address.py +29 -0
  105. treepos/github/repository/clash.py +31 -0
  106. treepos/github/repository/describe.py +78 -0
  107. treepos/github/repository/diff.py +39 -0
  108. treepos/github/repository/marks.py +58 -0
  109. treepos/github/repository/model.py +34 -0
  110. treepos/github/repository/notice.py +20 -0
  111. treepos/github/repository/object_type.py +29 -0
  112. treepos/github/repository/operations.py +57 -0
  113. treepos/github/repository/order.py +21 -0
  114. treepos/github/repository/placed.py +25 -0
  115. treepos/github/repository/placing.py +9 -0
  116. treepos/github/repository/precondition.py +27 -0
  117. treepos/github/repository/read_back.py +155 -0
  118. treepos/github/repository/removal.py +46 -0
  119. treepos/github/repository/settings.py +13 -0
  120. treepos/github/repository/type_name.py +3 -0
  121. treepos/github/team/__init__.py +1 -0
  122. treepos/github/team/alongside.py +31 -0
  123. treepos/github/team/describe.py +49 -0
  124. treepos/github/team/diff.py +18 -0
  125. treepos/github/team/follow.py +15 -0
  126. treepos/github/team/model.py +22 -0
  127. treepos/github/team/object_type.py +28 -0
  128. treepos/github/team/operations.py +31 -0
  129. treepos/github/team/order.py +45 -0
  130. treepos/github/team/precondition.py +27 -0
  131. treepos/github/team/read_back.py +94 -0
  132. treepos/github/team/settings.py +16 -0
  133. treepos/github/team/slug.py +22 -0
  134. treepos/github/team/type_name.py +3 -0
  135. treepos/github/team_member/__init__.py +1 -0
  136. treepos/github/team_member/address.py +7 -0
  137. treepos/github/team_member/describe.py +35 -0
  138. treepos/github/team_member/diff.py +18 -0
  139. treepos/github/team_member/follow.py +13 -0
  140. treepos/github/team_member/model.py +17 -0
  141. treepos/github/team_member/object_type.py +26 -0
  142. treepos/github/team_member/operations.py +34 -0
  143. treepos/github/team_member/order.py +30 -0
  144. treepos/github/team_member/precondition.py +28 -0
  145. treepos/github/team_member/read_as.py +8 -0
  146. treepos/github/team_member/read_back.py +65 -0
  147. treepos/github/team_member/type_name.py +3 -0
  148. treepos/kinds/__init__.py +1 -0
  149. treepos/kinds/account/__init__.py +11 -0
  150. treepos/kinds/account/spec.py +18 -0
  151. treepos/kinds/credential/__init__.py +18 -0
  152. treepos/kinds/credential/app_installation/__init__.py +11 -0
  153. treepos/kinds/credential/app_installation/spec.py +22 -0
  154. treepos/kinds/credential/fine_grained_pat/__init__.py +11 -0
  155. treepos/kinds/credential/fine_grained_pat/spec.py +22 -0
  156. treepos/kinds/credential/spec.py +22 -0
  157. treepos/kinds/member_source/__init__.py +11 -0
  158. treepos/kinds/member_source/list/__init__.py +13 -0
  159. treepos/kinds/member_source/list/spec.py +14 -0
  160. treepos/kinds/member_source/list/tree_check.py +50 -0
  161. treepos/kinds/member_source/spec.py +7 -0
  162. treepos/kinds/organization/__init__.py +26 -0
  163. treepos/kinds/organization/desired.py +32 -0
  164. treepos/kinds/organization/host.py +4 -0
  165. treepos/kinds/organization/people.py +34 -0
  166. treepos/kinds/organization/spec.py +75 -0
  167. treepos/kinds/organization/suspended.py +44 -0
  168. treepos/kinds/organization/tree_check.py +67 -0
  169. treepos/kinds/people/__init__.py +19 -0
  170. treepos/kinds/people/registry.py +39 -0
  171. treepos/kinds/people/resolve.py +60 -0
  172. treepos/kinds/people/spec.py +15 -0
  173. treepos/kinds/people/tree_check.py +45 -0
  174. treepos/kinds/policy/__init__.py +19 -0
  175. treepos/kinds/policy/admits.py +34 -0
  176. treepos/kinds/policy/bounds.py +65 -0
  177. treepos/kinds/policy/check.py +56 -0
  178. treepos/kinds/policy/evaluate/__init__.py +2 -0
  179. treepos/kinds/policy/evaluate/checks.py +54 -0
  180. treepos/kinds/policy/evaluate/matches.py +41 -0
  181. treepos/kinds/policy/evaluate/target.py +34 -0
  182. treepos/kinds/policy/evaluate/values.py +126 -0
  183. treepos/kinds/policy/evaluate/writable.py +51 -0
  184. treepos/kinds/policy/match.py +35 -0
  185. treepos/kinds/policy/overlap.py +12 -0
  186. treepos/kinds/policy/problems.py +25 -0
  187. treepos/kinds/policy/rule.py +52 -0
  188. treepos/kinds/policy/spec.py +30 -0
  189. treepos/kinds/policy/subtree.py +147 -0
  190. treepos/kinds/policy/tree_check.py +66 -0
  191. treepos/kinds/ref/__init__.py +11 -0
  192. treepos/kinds/ref/file/__init__.py +19 -0
  193. treepos/kinds/ref/file/locate.py +14 -0
  194. treepos/kinds/ref/file/spec.py +20 -0
  195. treepos/kinds/ref/repo/__init__.py +20 -0
  196. treepos/kinds/ref/repo/locate.py +19 -0
  197. treepos/kinds/ref/repo/spec.py +39 -0
  198. treepos/kinds/ref/spec.py +10 -0
  199. treepos/kinds/renderer/__init__.py +11 -0
  200. treepos/kinds/renderer/none/__init__.py +11 -0
  201. treepos/kinds/renderer/none/spec.py +7 -0
  202. treepos/kinds/renderer/spec.py +7 -0
  203. treepos/kinds/repository/__init__.py +21 -0
  204. treepos/kinds/repository/desired.py +49 -0
  205. treepos/kinds/repository/spec.py +37 -0
  206. treepos/kinds/repository/tree_check.py +33 -0
  207. treepos/kinds/repository_config/__init__.py +24 -0
  208. treepos/kinds/repository_config/spec.py +33 -0
  209. treepos/kinds/repository_config/tree_check.py +28 -0
  210. treepos/kinds/revision/__init__.py +11 -0
  211. treepos/kinds/revision/branch/__init__.py +11 -0
  212. treepos/kinds/revision/branch/spec.py +35 -0
  213. treepos/kinds/revision/commit/__init__.py +11 -0
  214. treepos/kinds/revision/commit/spec.py +29 -0
  215. treepos/kinds/revision/spec.py +12 -0
  216. treepos/kinds/runner/__init__.py +20 -0
  217. treepos/kinds/runner/spec.py +25 -0
  218. treepos/kinds/runner/tree_check.py +29 -0
  219. treepos/kinds/runner_secret/__init__.py +11 -0
  220. treepos/kinds/runner_secret/environment_secret/__init__.py +12 -0
  221. treepos/kinds/runner_secret/environment_secret/spec.py +8 -0
  222. treepos/kinds/runner_secret/spec.py +7 -0
  223. treepos/kinds/team/__init__.py +17 -0
  224. treepos/kinds/team/desired.py +55 -0
  225. treepos/kinds/team/spec.py +64 -0
  226. treepos/kinds/team/tree_check.py +40 -0
  227. treepos/phases/__init__.py +1 -0
  228. treepos/phases/apply/__init__.py +1 -0
  229. treepos/phases/apply/runner.py +96 -0
  230. treepos/phases/compile/__init__.py +1 -0
  231. treepos/phases/compile/bounds.py +72 -0
  232. treepos/phases/compile/entry.py +13 -0
  233. treepos/phases/compile/lines.py +15 -0
  234. treepos/phases/compile/read.py +158 -0
  235. treepos/phases/compile/reading.py +16 -0
  236. treepos/phases/compile/tree.py +45 -0
  237. treepos/phases/compile/validate.py +88 -0
  238. treepos/phases/compile/walk.py +311 -0
  239. treepos/phases/desired/__init__.py +1 -0
  240. treepos/phases/desired/runner.py +23 -0
  241. treepos/phases/observe/__init__.py +1 -0
  242. treepos/phases/observe/runner.py +38 -0
  243. treepos/phases/reconcile/__init__.py +1 -0
  244. treepos/phases/reconcile/claims.py +36 -0
  245. treepos/phases/reconcile/holds.py +35 -0
  246. treepos/phases/reconcile/order.py +65 -0
  247. treepos/phases/reconcile/plan.py +31 -0
  248. treepos/phases/reconcile/runner.py +205 -0
  249. treepos/pipeline/__init__.py +1 -0
  250. treepos/pipeline/apply/__init__.py +1 -0
  251. treepos/pipeline/apply/plan_file.py +164 -0
  252. treepos/pipeline/apply/result.py +29 -0
  253. treepos/pipeline/apply/run.py +120 -0
  254. treepos/pipeline/credential.py +93 -0
  255. treepos/pipeline/errors.py +5 -0
  256. treepos/pipeline/live.py +133 -0
  257. treepos/pipeline/memory_github.py +87 -0
  258. treepos/pipeline/plan/__init__.py +1 -0
  259. treepos/pipeline/plan/result.py +73 -0
  260. treepos/pipeline/plan/run.py +110 -0
  261. treepos/pipeline/plan/stamp.py +18 -0
  262. treepos/pipeline/preview.py +17 -0
  263. treepos/pipeline/result/__init__.py +1 -0
  264. treepos/pipeline/result/header.py +76 -0
  265. treepos/pipeline/runner_folder.py +30 -0
  266. treepos/pipeline/runner_identity.py +12 -0
  267. treepos/pipeline/runner_repo_kept.py +31 -0
  268. treepos/pipeline/runner_source.py +26 -0
  269. treepos/pipeline/runner_tree.py +66 -0
  270. treepos/pipeline/services.py +19 -0
  271. treepos/pipeline/sign_in/__init__.py +1 -0
  272. treepos/pipeline/sign_in/app_installation.py +56 -0
  273. treepos/pipeline/sign_in/fine_grained_pat.py +44 -0
  274. treepos/pipeline/sign_in/keys.py +50 -0
  275. treepos/pipeline/sign_in/runner_credential.py +43 -0
  276. treepos/pipeline/sign_in/signed_in.py +12 -0
  277. treepos/ports/__init__.py +1 -0
  278. treepos/ports/github.py +30 -0
  279. treepos/ports/renderer.py +52 -0
  280. treepos/ports/source.py +15 -0
  281. treepos/py.typed +0 -0
  282. treepos-0.0.1.dist-info/METADATA +96 -0
  283. treepos-0.0.1.dist-info/RECORD +287 -0
  284. treepos-0.0.1.dist-info/WHEEL +4 -0
  285. treepos-0.0.1.dist-info/entry_points.txt +3 -0
  286. treepos-0.0.1.dist-info/licenses/LICENSE +202 -0
  287. treepos-0.0.1.dist-info/licenses/NOTICE +4 -0
treepos/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """treepos: declarative, delegated management of GitHub as a tree of repos."""
@@ -0,0 +1 @@
1
+ """Adapters: the outside world behind each port, such as files, GitHub, and the simulator."""
@@ -0,0 +1 @@
1
+ """Live GitHub over its API: a reader and writer for each object type, behind a client protocol."""
@@ -0,0 +1,198 @@
1
+ """The small client protocol the GitHub adapter is written against: only the calls it makes.
2
+
3
+ githubkit fills it, and is pre-1.0, so the protocol contains it: another client, such as plain
4
+ httpx, fills the same protocol without the readers and writers changing. Each call gives GitHub's
5
+ data as plain values, and a failure as an `ApiError`.
6
+ """
7
+
8
+ from collections.abc import Mapping
9
+ from dataclasses import dataclass
10
+ from typing import Literal, Protocol
11
+
12
+ from treepos.github.mark_properties.definitions import Definition
13
+
14
+ UNAUTHENTICATED = 401 # the status for a credential GitHub doesn't take, which another key may mend
15
+
16
+
17
+ class ApiError(Exception):
18
+ """A call GitHub answered with an error, or that never reached it."""
19
+
20
+ def __init__(self, message: str, *, status: int | None = None) -> None:
21
+ super().__init__(message)
22
+ self.status = status # GitHub's HTTP status; none when the call never got an answer
23
+
24
+
25
+ @dataclass(frozen=True)
26
+ class Account:
27
+ """An account as GitHub's REST API names it."""
28
+
29
+ id: int
30
+ login: str
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class TeamData:
35
+ """A team as GitHub's REST API gives it."""
36
+
37
+ id: int
38
+ name: str
39
+ slug: str
40
+ privacy: str
41
+ parent: str | None # the parent's name
42
+
43
+
44
+ class TeamsApi(Protocol):
45
+ def teams(self, org: str) -> list[TeamData]:
46
+ """Every team in `org`, every page of them."""
47
+ ...
48
+
49
+ def create_team(self, org: str, *, name: str, privacy: str, parent_id: int | None) -> None: ...
50
+
51
+ def update_team(self, org: str, slug: str, changes: Mapping[str, object]) -> None:
52
+ """Change a team's `name`, `privacy` or `parent_team_id`, which none clears."""
53
+ ...
54
+
55
+ def delete_team(self, org: str, slug: str) -> None: ...
56
+
57
+
58
+ @dataclass(frozen=True)
59
+ class InvitationData:
60
+ """An org invitation as GitHub's REST API gives it."""
61
+
62
+ login: str | None # the invitee's; none for an invitation by email
63
+ role: str # GitHub's name for it: `direct_member`, `admin`, `billing_manager` and others
64
+
65
+
66
+ class OrgMembersApi(Protocol):
67
+ def members(self, org: str, *, role: Literal["admin", "member"]) -> list[int]:
68
+ """The account IDs of `org`'s members in `role`, every page of them."""
69
+ ...
70
+
71
+ def invitations(self, org: str) -> list[InvitationData]:
72
+ """Every invitation to `org` not yet accepted, every page of them."""
73
+ ...
74
+
75
+ def account_id(self, login: str) -> int: ...
76
+
77
+ def login(self, account_id: int) -> str: ...
78
+
79
+ def invite(
80
+ self, org: str, account_id: int, *, role: Literal["admin", "direct_member"]
81
+ ) -> None: ...
82
+
83
+ def membership_state(self, org: str, login: str) -> str | None:
84
+ """`active` or `pending`, GitHub's state for `login` in `org`; none if they're neither."""
85
+ ...
86
+
87
+ def set_membership(self, org: str, login: str, *, role: Literal["admin", "member"]) -> None:
88
+ """Set a member's role; GitHub invites someone not in the org instead."""
89
+ ...
90
+
91
+ def remove_membership(self, org: str, login: str) -> None:
92
+ """Remove a member, or cancel their invitation, as GitHub documents."""
93
+ ...
94
+
95
+
96
+ @dataclass(frozen=True)
97
+ class TeamMemberData:
98
+ """A team's member as GitHub's REST API lists them."""
99
+
100
+ account: int
101
+ role: str | None # GitHub's name for it, where it says
102
+ inherited: bool | None # whether they're in it only through a child team, where GitHub says
103
+
104
+
105
+ class TeamMembersApi(Protocol):
106
+ def teams(self, org: str) -> list[TeamData]: ...
107
+
108
+ def team_members(self, org: str, slug: str) -> list[TeamMemberData]:
109
+ """Everyone GitHub lists in the team, its child teams' members too, every page."""
110
+ ...
111
+
112
+ def team_invitations(self, org: str, slug: str) -> list[InvitationData]:
113
+ """Every invitation to the org that adds its invitee to the team, every page."""
114
+ ...
115
+
116
+ def members(self, org: str, *, role: Literal["admin", "member"]) -> list[int]: ...
117
+
118
+ def account_id(self, login: str) -> int: ...
119
+
120
+ def login(self, account_id: int) -> str: ...
121
+
122
+ def team_membership_state(self, org: str, slug: str, login: str) -> str | None:
123
+ """`active` or `pending`, GitHub's state for `login` in the team; none if neither."""
124
+ ...
125
+
126
+ def set_team_membership(self, org: str, slug: str, login: str) -> None:
127
+ """Add someone to the team as a plain member, or make them one; GitHub invites someone
128
+ not in the org."""
129
+ ...
130
+
131
+ def remove_team_membership(self, org: str, slug: str, login: str) -> None: ...
132
+
133
+
134
+ @dataclass(frozen=True)
135
+ class RepoData:
136
+ """A repo as GitHub's REST API lists it."""
137
+
138
+ id: int
139
+ name: str
140
+ visibility: str
141
+ topics: tuple[str, ...]
142
+ archived: bool
143
+
144
+
145
+ class ReposApi(Protocol):
146
+ def repos(self, org: str) -> list[RepoData]:
147
+ """Every repo in `org`, every page of them."""
148
+ ...
149
+
150
+ def property_values(self, org: str) -> dict[int, dict[str, str | tuple[str, ...]]]:
151
+ """Each repo's custom property values, by its ID, every page of them: a multi-select's as
152
+ a tuple, and a property with no value left out."""
153
+ ...
154
+
155
+ def create_repo(
156
+ self, org: str, *, name: str, visibility: str, properties: Mapping[str, str]
157
+ ) -> None: ...
158
+
159
+ def update_repo(self, org: str, name: str, changes: Mapping[str, object]) -> None:
160
+ """Change a repo's `name`, `visibility` or `archived`."""
161
+ ...
162
+
163
+ def set_topics(self, org: str, name: str, topics: tuple[str, ...]) -> None: ...
164
+
165
+ def set_properties(self, org: str, name: str, values: Mapping[str, str]) -> None: ...
166
+
167
+
168
+ class MarkPropertiesApi(Protocol):
169
+ def property_definitions(self, org: str) -> list[Definition]: ...
170
+
171
+ def define_properties(self, org: str, definitions: tuple[Definition, ...]) -> None: ...
172
+
173
+
174
+ @dataclass(frozen=True)
175
+ class FileData:
176
+ """What's at a path in a repo, as GitHub's contents API gives it."""
177
+
178
+ kind: str # GitHub's `type`: `file`, `dir`, `symlink` or `submodule`
179
+ content: bytes | None # a file's bytes; none for anything else, or a file too big to be sent
180
+
181
+
182
+ class SourceApi(Protocol):
183
+ def file(self, owner: str, repo: str, path: str, *, ref: str) -> FileData:
184
+ """What's at `path` in `owner/repo` at `ref`, a branch or a commit's SHA."""
185
+ ...
186
+
187
+ def default_branch(self, owner: str, repo: str) -> str:
188
+ """The name of `owner/repo`'s default branch."""
189
+ ...
190
+
191
+ def branches(self, owner: str, repo: str) -> list[str]:
192
+ """Every branch of `owner/repo`, by name, every page of them."""
193
+ ...
194
+
195
+ def compare(self, owner: str, repo: str, base: str, head: str) -> str:
196
+ """How `head` stands to `base` in `owner/repo`, as GitHub's compare API says: `ahead`,
197
+ `behind`, `identical` or `diverged`."""
198
+ ...
@@ -0,0 +1,463 @@
1
+ """The client protocol over githubkit: GitHub's REST API, typed, every page of a list read.
2
+
3
+ `client` builds the githubkit client treepos uses. It keeps no HTTP cache, since GitHub marks some
4
+ answers cacheable for a minute, and apply's re-read before each write must see GitHub as it is. It
5
+ retries nothing: a write GitHub made but answered with a 5xx, sent again, would be refused, and a
6
+ run that fails is planned again by the next; the rate-limit budget brings retries that are safe.
7
+ """
8
+
9
+ import base64
10
+ import binascii
11
+ import json
12
+ from collections.abc import Callable, Mapping
13
+ from typing import Any, Literal, cast
14
+ from urllib.parse import quote
15
+
16
+ from cryptography.exceptions import UnsupportedAlgorithm
17
+ from cryptography.hazmat.primitives import serialization
18
+ from cryptography.hazmat.primitives.asymmetric import rsa
19
+ from githubkit import AppAuthStrategy, AppInstallationAuthStrategy, GitHub
20
+ from githubkit.exception import GitHubException, RequestFailed
21
+ from githubkit.utils import UNSET
22
+
23
+ from treepos.adapters.github_api.api import (
24
+ Account,
25
+ ApiError,
26
+ FileData,
27
+ InvitationData,
28
+ RepoData,
29
+ TeamData,
30
+ TeamMemberData,
31
+ )
32
+ from treepos.github.mark_properties.definitions import Definition
33
+ from treepos.github.team.model import PRIVACIES, Privacy
34
+
35
+ PER_PAGE = 100 # GitHub's largest page, so a list takes the fewest calls
36
+
37
+
38
+ def client(token: str, **settings: Any) -> GitHub[Any]:
39
+ """githubkit's client for `token`, keeping no cache and retrying nothing; `settings` are
40
+ githubkit's own."""
41
+ return GitHub(token, http_cache=False, auto_retry=False, **settings)
42
+
43
+
44
+ def signs(private_key: str) -> bool:
45
+ """Whether `private_key` is an RSA private key, unencrypted, as an App's is, which signs its
46
+ JWTs with RS256. What's wrong with one is never said: it could quote the key."""
47
+ try:
48
+ key = serialization.load_pem_private_key(private_key.encode(), password=None)
49
+ except ValueError, TypeError, UnsupportedAlgorithm:
50
+ return False
51
+ return isinstance(key, rsa.RSAPrivateKey)
52
+
53
+
54
+ def app_client(
55
+ app_id: int, private_key: str, installation_id: int | None = None, **settings: Any
56
+ ) -> GitHub[Any]:
57
+ """githubkit's client for a GitHub App, signing its JWTs with `private_key`: as the App, or as
58
+ its installation `installation_id`, each keeping no cache and retrying nothing."""
59
+ auth = (
60
+ AppAuthStrategy(app_id, private_key)
61
+ if installation_id is None
62
+ else AppInstallationAuthStrategy(app_id, private_key, installation_id)
63
+ )
64
+ return GitHub(auth, http_cache=False, auto_retry=False, **settings)
65
+
66
+
67
+ class GithubkitApi:
68
+ def __init__(self, github: GitHub[Any]) -> None:
69
+ self._github = github
70
+
71
+ def identity(self) -> Account:
72
+ answer = self._call(lambda: self._github.rest.users.get_authenticated().json())
73
+ account, login = _id(answer), _field(answer, "login")
74
+ if not isinstance(account, int) or not isinstance(login, str):
75
+ raise ApiError("GitHub's answer for the signed-in account names no ID and login")
76
+ return Account(account, login)
77
+
78
+ def org_installation(self, org: str) -> int:
79
+ """The ID of the signed-in App's installation on `org`."""
80
+ apps = self._github.rest.apps
81
+ installation = _id(self._call(lambda: apps.get_org_installation(org).json()))
82
+ if not isinstance(installation, int):
83
+ raise ApiError(f"GitHub's answer for the App's installation on {org} names no ID")
84
+ return installation
85
+
86
+ def installation_reads(self) -> None:
87
+ """Read as the signed-in installation, which takes its token: a call that fails if it
88
+ can't."""
89
+ apps = self._github.rest.apps
90
+ self._call(lambda: apps.list_repos_accessible_to_installation(per_page=1))
91
+
92
+ def members(self, org: str, *, role: Literal["admin", "member"]) -> list[int]:
93
+ rest = self._github.rest
94
+ listed = self._call(
95
+ lambda: list(
96
+ rest.paginate(rest.orgs.list_members, org=org, role=role, per_page=PER_PAGE)
97
+ )
98
+ )
99
+ return [user.id for user in listed]
100
+
101
+ def invitations(self, org: str) -> list[InvitationData]:
102
+ rest = self._github.rest
103
+ listed = self._call(
104
+ lambda: list(
105
+ rest.paginate(rest.orgs.list_pending_invitations, org=org, per_page=PER_PAGE)
106
+ )
107
+ )
108
+ return [InvitationData(each.login, each.role) for each in listed]
109
+
110
+ def account_id(self, login: str) -> int:
111
+ account = _field(
112
+ self._call(lambda: self._github.rest.users.get_by_username(login).json()), "id"
113
+ )
114
+ if not isinstance(account, int):
115
+ raise ApiError(f"GitHub's answer for {login} names no ID")
116
+ return account
117
+
118
+ def login(self, account_id: int) -> str:
119
+ login = _field(
120
+ self._call(lambda: self._github.rest.users.get_by_id(account_id).json()), "login"
121
+ )
122
+ if not isinstance(login, str):
123
+ raise ApiError(f"GitHub's answer for account {account_id} names no login")
124
+ return login
125
+
126
+ def invite(self, org: str, account_id: int, *, role: Literal["admin", "direct_member"]) -> None:
127
+ orgs = self._github.rest.orgs
128
+ self._call(lambda: orgs.create_invitation(org, invitee_id=account_id, role=role))
129
+
130
+ def membership_state(self, org: str, login: str) -> str | None:
131
+ orgs = self._github.rest.orgs
132
+ return self._state(
133
+ f"{login}'s membership of {org}",
134
+ lambda: orgs.get_membership_for_user(org, login).json(),
135
+ )
136
+
137
+ def _state(self, what: str, read: Callable[[], object]) -> str | None:
138
+ """A membership's state, or none where GitHub answers there's no such membership."""
139
+ try:
140
+ answer = self._call(read)
141
+ except ApiError as error:
142
+ if error.status == 404:
143
+ return None
144
+ raise
145
+ state = _field(answer, "state")
146
+ if not isinstance(state, str):
147
+ raise ApiError(f"GitHub's answer for {what} names no state")
148
+ return state
149
+
150
+ def set_membership(self, org: str, login: str, *, role: Literal["admin", "member"]) -> None:
151
+ orgs = self._github.rest.orgs
152
+ self._call(lambda: orgs.set_membership_for_user(org, login, role=role))
153
+
154
+ def remove_membership(self, org: str, login: str) -> None:
155
+ self._call(lambda: self._github.rest.orgs.remove_membership_for_user(org, login))
156
+
157
+ def team_members(self, org: str, slug: str) -> list[TeamMemberData]:
158
+ rest = self._github.rest
159
+ listed = self._call(
160
+ lambda: list(
161
+ rest.paginate(
162
+ rest.teams.list_members_in_org, org=org, team_slug=slug, per_page=PER_PAGE
163
+ )
164
+ )
165
+ )
166
+ return [
167
+ TeamMemberData(
168
+ user.id,
169
+ user.role if isinstance(user.role, str) else None,
170
+ user.inherited if isinstance(user.inherited, bool) else None,
171
+ )
172
+ for user in listed
173
+ ]
174
+
175
+ def team_invitations(self, org: str, slug: str) -> list[InvitationData]:
176
+ rest = self._github.rest
177
+ listed = self._call(
178
+ lambda: list(
179
+ rest.paginate(
180
+ rest.teams.list_pending_invitations_in_org,
181
+ org=org,
182
+ team_slug=slug,
183
+ per_page=PER_PAGE,
184
+ )
185
+ )
186
+ )
187
+ return [InvitationData(each.login, each.role) for each in listed]
188
+
189
+ def team_membership_state(self, org: str, slug: str, login: str) -> str | None:
190
+ teams = self._github.rest.teams
191
+ return self._state(
192
+ f"{login}'s membership of {org}'s team {slug}",
193
+ lambda: teams.get_membership_for_user_in_org(org, slug, login).json(),
194
+ )
195
+
196
+ def set_team_membership(self, org: str, slug: str, login: str) -> None:
197
+ teams = self._github.rest.teams
198
+ self._call(
199
+ lambda: teams.add_or_update_membership_for_user_in_org(org, slug, login, role="member")
200
+ )
201
+
202
+ def remove_team_membership(self, org: str, slug: str, login: str) -> None:
203
+ teams = self._github.rest.teams
204
+ self._call(lambda: teams.remove_membership_for_user_in_org(org, slug, login))
205
+
206
+ def repos(self, org: str) -> list[RepoData]:
207
+ rest = self._github.rest
208
+ listed = self._call(
209
+ lambda: list(
210
+ rest.paginate(rest.repos.list_for_org, org=org, type="all", per_page=PER_PAGE)
211
+ )
212
+ )
213
+ found: list[RepoData] = []
214
+ for repo in listed:
215
+ visibility, topics, archived = repo.visibility, repo.topics, repo.archived
216
+ if not (isinstance(visibility, str) and isinstance(archived, bool)):
217
+ raise ApiError(f"GitHub's listing of repo {repo.name} in {org} lacks a setting")
218
+ if not isinstance(topics, list):
219
+ raise ApiError(f"GitHub's listing of repo {repo.name} in {org} lacks its topics")
220
+ found.append(RepoData(repo.id, repo.name, visibility, tuple(topics), archived))
221
+ return found
222
+
223
+ def property_values(self, org: str) -> dict[int, dict[str, str | tuple[str, ...]]]:
224
+ rest = self._github.rest
225
+ values = rest.orgs.custom_properties_for_repos_get_organization_values
226
+ listed = self._call(lambda: list(rest.paginate(values, org=org, per_page=PER_PAGE)))
227
+ return {
228
+ repo.repository_id: {
229
+ each.property_name: each.value if isinstance(each.value, str) else tuple(each.value)
230
+ for each in repo.properties
231
+ if each.value is not None
232
+ }
233
+ for repo in listed
234
+ }
235
+
236
+ def create_repo(
237
+ self, org: str, *, name: str, visibility: str, properties: Mapping[str, str]
238
+ ) -> None:
239
+ body: dict[str, Any] = {"name": name, "visibility": visibility}
240
+ if properties:
241
+ body["custom_properties"] = dict(properties)
242
+ self._call(lambda: self._github.rest.repos.create_in_org(org, data=cast(Any, body)))
243
+
244
+ def update_repo(self, org: str, name: str, changes: Mapping[str, object]) -> None:
245
+ body = dict(changes)
246
+ self._call(lambda: self._github.rest.repos.update(org, name, data=cast(Any, body)))
247
+
248
+ def set_topics(self, org: str, name: str, topics: tuple[str, ...]) -> None:
249
+ repos = self._github.rest.repos
250
+ self._call(lambda: repos.replace_all_topics(org, name, names=list(topics)))
251
+
252
+ def set_properties(self, org: str, name: str, values: Mapping[str, str]) -> None:
253
+ repos = self._github.rest.repos
254
+ properties: list[Any] = [{"property_name": k, "value": v} for k, v in values.items()]
255
+ self._call(
256
+ lambda: repos.custom_properties_for_repos_create_or_update_repository_values(
257
+ org, name, properties=properties
258
+ )
259
+ )
260
+
261
+ def property_definitions(self, org: str) -> list[Definition]:
262
+ orgs = self._github.rest.orgs
263
+ listed = self._call(
264
+ lambda: orgs.custom_properties_for_repos_get_organization_definitions(org).parsed_data
265
+ )
266
+ return [
267
+ Definition(
268
+ name=each.property_name,
269
+ value_type=each.value_type,
270
+ allowed_values=_strings(each.allowed_values),
271
+ values_editable_by=_given(each.values_editable_by, str),
272
+ required=_given(each.required, bool),
273
+ default_value=_given(each.default_value, str),
274
+ )
275
+ for each in listed
276
+ ]
277
+
278
+ def define_properties(self, org: str, definitions: tuple[Definition, ...]) -> None:
279
+ orgs = self._github.rest.orgs
280
+ properties: list[Any] = [
281
+ {
282
+ "property_name": d.name,
283
+ "value_type": d.value_type,
284
+ **({} if d.required is None else {"required": d.required}),
285
+ **(
286
+ {}
287
+ if d.values_editable_by is None
288
+ else {"values_editable_by": d.values_editable_by}
289
+ ),
290
+ **({"allowed_values": list(d.allowed_values)} if d.allowed_values else {}),
291
+ }
292
+ for d in definitions
293
+ ]
294
+ self._call(
295
+ lambda: orgs.custom_properties_for_repos_create_or_update_organization_definitions(
296
+ org, properties=properties
297
+ )
298
+ )
299
+
300
+ def teams(self, org: str) -> list[TeamData]:
301
+ rest = self._github.rest.teams
302
+ listed = self._call(
303
+ lambda: list(self._github.rest.paginate(rest.list, org=org, per_page=PER_PAGE))
304
+ )
305
+ return [
306
+ TeamData(
307
+ id=team.id,
308
+ name=team.name,
309
+ slug=team.slug,
310
+ privacy=team.privacy if isinstance(team.privacy, str) else "",
311
+ parent=None if team.parent is None else team.parent.name,
312
+ )
313
+ for team in listed
314
+ ]
315
+
316
+ def create_team(self, org: str, *, name: str, privacy: str, parent_id: int | None) -> None:
317
+ teams = self._github.rest.teams
318
+ self._call(
319
+ lambda: teams.create(
320
+ org,
321
+ name=name,
322
+ privacy=_privacy(privacy),
323
+ parent_team_id=UNSET if parent_id is None else parent_id,
324
+ )
325
+ )
326
+
327
+ def update_team(self, org: str, slug: str, changes: Mapping[str, object]) -> None:
328
+ name, privacy = changes.get("name", UNSET), changes.get("privacy", UNSET)
329
+ parent = changes.get("parent_team_id", UNSET)
330
+ teams = self._github.rest.teams
331
+ self._call(
332
+ lambda: teams.update_in_org(
333
+ org,
334
+ slug,
335
+ name=UNSET if name is UNSET else str(name),
336
+ privacy=UNSET if privacy is UNSET else _privacy(str(privacy)),
337
+ parent_team_id=UNSET if parent is UNSET else cast(int | None, parent),
338
+ )
339
+ )
340
+
341
+ def delete_team(self, org: str, slug: str) -> None:
342
+ self._call(lambda: self._github.rest.teams.delete_in_org(org, slug))
343
+
344
+ def file(self, owner: str, repo: str, path: str, *, ref: str) -> FileData:
345
+ answer = self._call(
346
+ lambda: self._github.rest.repos.get_content(owner, repo, path, ref=ref).json()
347
+ )
348
+ if isinstance(answer, list): # a folder's entries
349
+ return FileData("dir", None)
350
+ kind = _field(answer, "type")
351
+ if not isinstance(kind, str):
352
+ raise ApiError(f"GitHub's answer for {owner}/{repo}:{path} names no type")
353
+ if kind != "file":
354
+ return FileData(kind, None)
355
+ content, encoding = _field(answer, "content"), _field(answer, "encoding")
356
+ if encoding != "base64" or not isinstance(content, str):
357
+ return FileData(kind, None) # over GitHub's 1 MB, which it sends no content for
358
+ try:
359
+ return FileData(kind, base64.b64decode(content))
360
+ except binascii.Error as error:
361
+ raise ApiError(f"GitHub's answer for {owner}/{repo}:{path} isn't base64") from error
362
+
363
+ def default_branch(self, owner: str, repo: str) -> str:
364
+ answer = self._call(lambda: self._github.rest.repos.get(owner, repo).json())
365
+ branch = _field(answer, "default_branch")
366
+ if not isinstance(branch, str):
367
+ raise ApiError(f"GitHub's answer for {owner}/{repo} names no default branch")
368
+ return branch
369
+
370
+ def branches(self, owner: str, repo: str) -> list[str]:
371
+ rest = self._github.rest
372
+ listed = self._call(
373
+ lambda: list(
374
+ rest.paginate(rest.repos.list_branches, owner=owner, repo=repo, per_page=PER_PAGE)
375
+ )
376
+ )
377
+ return [branch.name for branch in listed]
378
+
379
+ def compare(self, owner: str, repo: str, base: str, head: str) -> str:
380
+ # githubkit puts the path in as given, so a branch's `#`, `?` or `%` is escaped here; its
381
+ # `/` stays, as GitHub reads it. One commit a page keeps the answer small.
382
+ basehead = f"{quote(base, safe='/')}...{quote(head, safe='/')}"
383
+ answer = self._call(
384
+ lambda: self._github.rest.repos.compare_commits(
385
+ owner, repo, basehead, per_page=1
386
+ ).json()
387
+ )
388
+ status = _field(answer, "status")
389
+ if not isinstance(status, str):
390
+ raise ApiError(
391
+ f"GitHub's comparison of {base} and {head} in {owner}/{repo} has no status"
392
+ )
393
+ return status
394
+
395
+ def _call[T](self, call: Callable[[], T]) -> T:
396
+ try:
397
+ return call()
398
+ except RequestFailed as failed:
399
+ response = failed.response
400
+ raise ApiError(
401
+ f"GitHub answered {response.status_code}: {_message(response.text)}",
402
+ status=response.status_code,
403
+ ) from failed
404
+ except GitHubException as error:
405
+ raise ApiError(f"GitHub's answer never came: {error}") from error
406
+
407
+
408
+ def _id(answer: object) -> object:
409
+ """The `id` of a JSON object GitHub answered with, whatever it holds."""
410
+ return _field(answer, "id")
411
+
412
+
413
+ def _field(answer: object, name: str) -> object:
414
+ """A field of a JSON object GitHub answered with, whatever it holds."""
415
+ return cast(dict[str, object], answer).get(name) if isinstance(answer, dict) else None
416
+
417
+
418
+ def _strings(values: object) -> tuple[str, ...] | None:
419
+ if not isinstance(values, list):
420
+ return None
421
+ return tuple(str(each) for each in cast(list[object], values))
422
+
423
+
424
+ def _given[T](value: object, kind: type[T]) -> T | None:
425
+ """`value` where GitHub gave one of `kind`, or none: never a default in its place."""
426
+ return value if isinstance(value, kind) else None
427
+
428
+
429
+ def _privacy(privacy: str) -> Privacy:
430
+ if privacy not in PRIVACIES:
431
+ raise ApiError(f"{privacy!r} isn't a privacy GitHub takes: {', '.join(PRIVACIES)}")
432
+ return privacy
433
+
434
+
435
+ def _message(text: str) -> str:
436
+ """GitHub's own message from an error's body, with each reason its `errors` gives, such as a
437
+ 422's, or the body itself."""
438
+ try:
439
+ body = json.loads(text)
440
+ except ValueError:
441
+ return text
442
+ if not isinstance(body, dict):
443
+ return text
444
+ answer = cast(dict[str, object], body)
445
+ reasons = [_reason(each) for each in _listed(answer.get("errors"))]
446
+ message = str(answer.get("message", text))
447
+ return f"{message}: {'; '.join(reasons)}" if reasons else message
448
+
449
+
450
+ def _listed(errors: object) -> list[object]:
451
+ return list(cast(list[object], errors)) if isinstance(errors, list) else []
452
+
453
+
454
+ def _reason(error: object) -> str:
455
+ """One of GitHub's reasons: its message, or else its field and code."""
456
+ if isinstance(error, str):
457
+ return error
458
+ if not isinstance(error, dict):
459
+ return str(error)
460
+ detail = cast(dict[str, object], error)
461
+ if isinstance(message := detail.get("message"), str):
462
+ return message
463
+ return " ".join(str(detail[key]) for key in ("field", "code") if key in detail) or str(detail)