codehood-cli 0.5.0__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 (71) hide show
  1. codehood/__init__.py +0 -0
  2. codehood/__main__.py +4 -0
  3. codehood/actions/__init__.py +0 -0
  4. codehood/actions/base.py +119 -0
  5. codehood/actions/resources.py +30 -0
  6. codehood/api/__init__.py +0 -0
  7. codehood/api/base.py +256 -0
  8. codehood/api/generate.py +1370 -0
  9. codehood/api/generated.py +3818 -0
  10. codehood/api/openapi.py +134 -0
  11. codehood/api/pages.py +53 -0
  12. codehood/cli/__init__.py +64 -0
  13. codehood/cli/api.py +422 -0
  14. codehood/cli/attendance.py +136 -0
  15. codehood/cli/auth.py +106 -0
  16. codehood/cli/base.py +42 -0
  17. codehood/cli/chill.py +52 -0
  18. codehood/cli/exam.py +107 -0
  19. codehood/cli/grades.py +185 -0
  20. codehood/cli/init.py +161 -0
  21. codehood/cli/push.py +609 -0
  22. codehood/cli/show.py +77 -0
  23. codehood/cli/uitils.py +26 -0
  24. codehood/functional.py +40 -0
  25. codehood/globs.py +71 -0
  26. codehood/grades.py +74 -0
  27. codehood/hypothesis.py +274 -0
  28. codehood/models/__init__.py +0 -0
  29. codehood/models/base.py +15 -0
  30. codehood/models/repo.py +187 -0
  31. codehood/models/validators.py +177 -0
  32. codehood/push/__init__.py +225 -0
  33. codehood/push/base.py +216 -0
  34. codehood/push/calendar.py +664 -0
  35. codehood/push/errors.py +136 -0
  36. codehood/push/exam.py +636 -0
  37. codehood/push/exclude.py +60 -0
  38. codehood/push/grades.py +455 -0
  39. codehood/push/hook.py +48 -0
  40. codehood/push/links.py +614 -0
  41. codehood/push/ours.py +78 -0
  42. codehood/push/plan.py +1981 -0
  43. codehood/push/project.py +272 -0
  44. codehood/push/question.py +338 -0
  45. codehood/push/report.py +244 -0
  46. codehood/push/repository.py +326 -0
  47. codehood/push/resource.py +576 -0
  48. codehood/push/run.py +1275 -0
  49. codehood/push/unconsumed.py +208 -0
  50. codehood/push/wire.py +222 -0
  51. codehood/py.typed +0 -0
  52. codehood/repo/__init__.py +62 -0
  53. codehood/repo/_config.py +28 -0
  54. codehood/repo/_layout.py +132 -0
  55. codehood/repo/_scaffold.py +244 -0
  56. codehood/repo/diff.py +71 -0
  57. codehood/repo/file_tracker.py +124 -0
  58. codehood/theme.py +101 -0
  59. codehood/widgets/__init__.py +0 -0
  60. codehood/widgets/mascot.py +76 -0
  61. codehood/widgets/questions/__init__.py +65 -0
  62. codehood/widgets/questions/base.py +119 -0
  63. codehood/widgets/questions/controls.py +194 -0
  64. codehood/widgets/questions/fill_in.py +81 -0
  65. codehood/widgets/questions/responses.py +137 -0
  66. codehood/widgets/questions/simple.py +117 -0
  67. codehood_cli-0.5.0.dist-info/METADATA +294 -0
  68. codehood_cli-0.5.0.dist-info/RECORD +71 -0
  69. codehood_cli-0.5.0.dist-info/WHEEL +4 -0
  70. codehood_cli-0.5.0.dist-info/entry_points.txt +4 -0
  71. codehood_cli-0.5.0.dist-info/licenses/LICENSE +21 -0
codehood/__init__.py ADDED
File without changes
codehood/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .cli import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
File without changes
@@ -0,0 +1,119 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Protocol, cast
5
+
6
+
7
+ #
8
+ # Protocols
9
+ #
10
+ class Action[
11
+ T,
12
+ Ctx = None,
13
+ ](Protocol):
14
+ """
15
+ Base protocol for Action objects.
16
+
17
+ Actions work like a thunk over a side-effect that we can inspect
18
+ and compose. They expose a `run()` method that executes the action.
19
+
20
+ Actions might accept an optional context that is used to store arguments and
21
+ other contextual information about how the action was run
22
+ """
23
+
24
+ def run(self, ctx: Ctx | None = None, /) -> Result[T]:
25
+ """
26
+ Actually run the action.
27
+ """
28
+ ...
29
+
30
+
31
+ class Args[T](Protocol):
32
+ """
33
+ A context that exposes arguments that pass through an action.
34
+ """
35
+
36
+ args: T
37
+
38
+
39
+ #
40
+ # Action combinators
41
+ #
42
+ @dataclass(frozen=True)
43
+ class Seq[R1, R2, C1, C2](Action[R2, tuple[C1, C2]]):
44
+ """
45
+ Run two actions in sequence where the result of one do not interfere with
46
+ the result of the other.
47
+
48
+ The error of the first action takes precedence. If successful, returns the
49
+ value of the second.
50
+ """
51
+
52
+ first: Action[R1, C1]
53
+ second: Action[R2, C2]
54
+
55
+ def run(self, ctx: tuple[C1, C2] | None = None, /) -> Result[R2]:
56
+ ctx1, ctx2 = (None, None) if ctx is None else ctx
57
+ if (res := self.first.run(ctx1)).is_error:
58
+ return res.as_error_of(self.second)
59
+ return self.second.run(ctx2)
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class Try[T, Ctx]:
64
+ """
65
+ Try any number of actions in and return the first successful one.
66
+
67
+ Return the last error, if all attempts fail.
68
+ """
69
+
70
+ actions: tuple[Action[T, Ctx], ...]
71
+
72
+ def __post_init__(self):
73
+ if not self.actions:
74
+ raise ValueError("must have at least one action in the list")
75
+
76
+ def run(self, ctx: Ctx | None = None):
77
+ first, *rest = self.actions
78
+ res = first.run(ctx)
79
+ for action in rest:
80
+ if not res.is_error:
81
+ return res
82
+ res = action.run(ctx)
83
+ return res
84
+
85
+
86
+ #
87
+ # Auxiliary types
88
+ #
89
+ @dataclass(frozen=True)
90
+ class Result[T]:
91
+ """
92
+ Describes the result of an action.
93
+ """
94
+
95
+ value: T | None
96
+ errors: tuple[Error, ...] | None = None
97
+
98
+ def __post_init__(self):
99
+ if self.errors == ():
100
+ object.__setattr__(self, "errors", ())
101
+
102
+ @property
103
+ def is_error(self):
104
+ return self.errors is None
105
+
106
+ def as_error_of[S](self, action: Action[S, Any]) -> Result[S]:
107
+ """
108
+ Cast an error result to a different type.
109
+ """
110
+ if self.value is None:
111
+ return cast("Result[S]", self)
112
+ raise ValueError("cannot cast a non-error result to a different type")
113
+
114
+
115
+ @dataclass
116
+ class Error[T = None]:
117
+ message: str
118
+ code: str
119
+ data: T
@@ -0,0 +1,30 @@
1
+ from dataclasses import dataclass
2
+ from pathlib import Path
3
+ from typing import Literal, assert_never
4
+
5
+ from ..repo.diff import AddFile, DeleteFile, Diff, FileType, UpdateFile
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class ResourceAction:
10
+ resource_id: str
11
+ path: Path
12
+ method: Literal["UPLOAD", "DELETE"]
13
+
14
+ def run(self): ...
15
+
16
+
17
+ def resource_action(diff: Diff):
18
+ """
19
+ For each diff operation, create the Resource action
20
+ """
21
+ if diff.type != FileType.RESOURCE:
22
+ raise ValueError(f"{diff} is not a resource")
23
+
24
+ match diff:
25
+ case AddFile(name) | UpdateFile(name):
26
+ return ResourceAction(name, diff.path, "UPLOAD")
27
+ case DeleteFile(name):
28
+ return ResourceAction(name, diff.path, "DELETE")
29
+ case other:
30
+ assert_never(other)
File without changes
codehood/api/base.py ADDED
@@ -0,0 +1,256 @@
1
+ """
2
+ Shared plumbing for `codehood_cli.api.generated`: the HTTP client every
3
+ generated function calls through, the exception hierarchy it raises, and the
4
+ credentials store `codehood login`/`codehood logout` and the auth-gated
5
+ generated functions all read and write.
6
+
7
+ None of this is itself generated -- see `dev/specs/to-review/api.md`, "A
8
+ shared client, threaded through as an optional parameter" and "One exception
9
+ class per schema, not per (operation, status)", and `dev/specs/to-review/
10
+ login.md`, "The bearer token is attached inside generated code, gated per
11
+ operation" -- so this is the one file in `api/` codegen never touches.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import os
17
+ import tomllib
18
+ from collections.abc import Mapping, Sequence
19
+ from pathlib import Path
20
+
21
+ import httpx
22
+ import tomlkit
23
+
24
+ from .. import repo
25
+ from ..models.base import Model
26
+
27
+ DEFAULT_BASE_URL = "http://localhost:4321"
28
+
29
+ #: Sent on every request, including the ones with no body.
30
+ #:
31
+ #: Astro's cross-site guard refuses any mutating request whose
32
+ #: `Content-Type` looks like an HTML form's -- and it counts a *missing*
33
+ #: one, which is what a bodyless `DELETE` would otherwise send, giving
34
+ #: `403 Cross-site DELETE form submissions are forbidden`. Saying what we
35
+ #: actually speak is enough to clear it, and is true of every other
36
+ #: request here anyway. See `ROADBLOCKS.md`.
37
+ DEFAULT_HEADERS = {"Content-Type": "application/json"}
38
+
39
+ #: Global, not per-repo -- see `dev/specs/to-review/login.md`, "Credentials
40
+ #: are global, not per-repo".
41
+ CREDENTIALS_PATH = Path.home() / ".codehood" / "credentials.toml"
42
+
43
+
44
+ #: Environment variable that overrides every stored token, for any server.
45
+ TOKEN_ENV = "CODEHOOD_TOKEN"
46
+
47
+
48
+ def get_client(base_url: str | None = None) -> httpx.Client:
49
+ """
50
+ Build the client generated functions call through.
51
+
52
+ `base_url` defaults to `[server].url` in `codehood.toml` in the current
53
+ directory, falling back to `DEFAULT_BASE_URL` when there is no
54
+ repository here -- generated functions stay usable from a plain
55
+ checkout, a test, or a REPL with nothing scaffolded.
56
+ """
57
+ return httpx.Client(
58
+ base_url=base_url or _default_base_url(), headers=DEFAULT_HEADERS
59
+ )
60
+
61
+
62
+ def _default_base_url() -> str:
63
+ config = repo.read_config(repo.config_path(Path()))
64
+ return config.server.url if config is not None else DEFAULT_BASE_URL
65
+
66
+
67
+ #: What `httpx` accepts as one query parameter's value: a scalar, or a
68
+ #: sequence of them for a repeated parameter such as `slugs`.
69
+ type QueryValue = (
70
+ str | int | float | bool | None | Sequence[str | int | float | bool | None]
71
+ )
72
+
73
+
74
+ def query_params(params: Mapping[str, QueryValue]) -> dict[str, QueryValue]:
75
+ """
76
+ Drop the query parameters a caller left unset.
77
+
78
+ `httpx` renders a `None` value as an empty string, so passing every
79
+ optional parameter through would send `?types=&slugs=` on a call that
80
+ named neither -- which the server reads as two present-but-empty
81
+ filters and rejects. An omitted parameter has to be omitted.
82
+ """
83
+ return {name: value for name, value in params.items() if value is not None}
84
+
85
+
86
+ def header_params(params: Mapping[str, str | None]) -> dict[str, str]:
87
+ """
88
+ Drop the header parameters a caller left unset.
89
+
90
+ An optional header such as `If-Match` is either sent with a value or not
91
+ sent at all; an empty one is a malformed precondition to the server.
92
+ """
93
+ return {name: value for name, value in params.items() if value is not None}
94
+
95
+
96
+ class CodehoodAPIError(Exception):
97
+ """
98
+ Base class for every exception `codehood_cli.api.generated` raises.
99
+
100
+ Each subclass corresponds to one OpenAPI component schema used in a
101
+ documented error response. `status` is the HTTP status code the server
102
+ actually sent for this call; `payload` is that response's body, parsed
103
+ into the subclass's nested `Payload` model. Subclasses add one
104
+ `@property` per payload field so `err.field` works without the
105
+ `.payload` indirection.
106
+ """
107
+
108
+ def __init__(self, status: int, payload: Model) -> None:
109
+ super().__init__(f"{type(self).__name__} ({status}): {payload}")
110
+ self.status = status
111
+ self.payload = payload
112
+
113
+
114
+ class NotLoggedInError(Exception):
115
+ """
116
+ Raised by a generated function for an operation whose effective
117
+ `security` is non-empty, when `CREDENTIALS_PATH` has no token for its
118
+ client's `base_url`. Raised before the request is sent -- see
119
+ `dev/specs/to-review/login.md`, "The bearer token is attached inside
120
+ generated code, gated per operation".
121
+ """
122
+
123
+ def __init__(self, base_url: str) -> None:
124
+ super().__init__(f"not logged in to {base_url} -- run `codehood login`")
125
+ self.base_url = base_url
126
+
127
+
128
+ def stored_servers() -> list[str]:
129
+ """
130
+ Every server URL with a stored token, in the order `codehood login`
131
+ added them. Used by `cli/init.py`'s `_default_server` to default
132
+ `--server` when there's exactly one -- see `dev/specs/to-review/
133
+ login.md`.
134
+ """
135
+ if not CREDENTIALS_PATH.exists():
136
+ return []
137
+ servers = tomllib.loads(CREDENTIALS_PATH.read_text(encoding="utf-8")).get(
138
+ "servers", {}
139
+ )
140
+ return list(servers)
141
+
142
+
143
+ def env_token() -> str | None:
144
+ """
145
+ The token in `CODEHOOD_TOKEN`, or `None` when it is unset or empty.
146
+ """
147
+ return os.environ.get(TOKEN_ENV) or None
148
+
149
+
150
+ def load_token(base_url: str) -> str | None:
151
+ """
152
+ The CLI API key to use for `base_url`, or `None` if there is none.
153
+
154
+ `CODEHOOD_TOKEN` wins for any server, and then the credentials file is
155
+ not read. Otherwise it is the key `codehood login` stored, if any.
156
+ """
157
+ token = env_token()
158
+ if token is not None:
159
+ return token
160
+ return load_stored_token(base_url)
161
+
162
+
163
+ def load_stored_token(base_url: str) -> str | None:
164
+ """
165
+ The key `codehood login` stored for `base_url`, ignoring `CODEHOOD_TOKEN`.
166
+ """
167
+ if not CREDENTIALS_PATH.exists():
168
+ return None
169
+ servers = tomllib.loads(CREDENTIALS_PATH.read_text(encoding="utf-8")).get(
170
+ "servers", {}
171
+ )
172
+ return servers.get(base_url)
173
+
174
+
175
+ def load_login(base_url: str) -> str | None:
176
+ """
177
+ The login name `base_url`'s stored token was issued to, or `None` when
178
+ unknown (no token, or one stored before logins were recorded).
179
+ """
180
+ if not CREDENTIALS_PATH.exists():
181
+ return None
182
+ logins = tomllib.loads(CREDENTIALS_PATH.read_text(encoding="utf-8")).get(
183
+ "logins", {}
184
+ )
185
+ return logins.get(base_url)
186
+
187
+
188
+ def save_token(base_url: str, token: str, login: str | None = None) -> None:
189
+ """
190
+ Store `token` for `base_url`, overwriting whatever was there.
191
+
192
+ There is one credential per server: the CLI acts as one person on each.
193
+ `login` goes in a separate `[logins]` table, so `[servers]` keeps plain
194
+ token strings that older CLI versions read. A token saved without a
195
+ `login` forgets the previous one, which belonged to the old token.
196
+
197
+ `CREDENTIALS_PATH` is `chmod 600` after every write -- it holds a raw
198
+ bearer token, unlike `codehood.toml`, which is committed and never
199
+ holds a secret.
200
+ """
201
+ doc = read_credentials_doc()
202
+ servers = doc.setdefault("servers", tomlkit.table())
203
+ servers[base_url] = token
204
+ logins = doc.setdefault("logins", tomlkit.table())
205
+ if login is None:
206
+ logins.pop(base_url, None)
207
+ else:
208
+ logins[base_url] = login
209
+ write_credentials_doc(doc)
210
+
211
+
212
+ def delete_token(base_url: str) -> bool:
213
+ """
214
+ Forget the stored token for `base_url`, if any.
215
+
216
+ Returns whether there was one to forget, so `codehood logout` can say
217
+ which happened.
218
+ """
219
+ if not CREDENTIALS_PATH.exists():
220
+ return False
221
+ doc = read_credentials_doc()
222
+ servers = doc.get("servers", {})
223
+ if base_url not in servers:
224
+ return False
225
+ del servers[base_url]
226
+ doc.get("logins", {}).pop(base_url, None)
227
+ write_credentials_doc(doc)
228
+ return True
229
+
230
+
231
+ def auth_headers(client: httpx.Client) -> dict[str, str]:
232
+ """
233
+ The `Authorization` header a generated function attaches for an
234
+ operation that requires auth.
235
+
236
+ Raises `NotLoggedInError` rather than returning an empty mapping, so a
237
+ call with no stored token fails locally instead of reaching the server
238
+ and getting an unauthenticated 401 back.
239
+ """
240
+ base_url = str(client.base_url)
241
+ token = load_token(base_url)
242
+ if token is None:
243
+ raise NotLoggedInError(base_url)
244
+ return {"Authorization": f"Bearer {token}"}
245
+
246
+
247
+ def read_credentials_doc() -> tomlkit.TOMLDocument:
248
+ if not CREDENTIALS_PATH.exists():
249
+ return tomlkit.document()
250
+ return tomlkit.parse(CREDENTIALS_PATH.read_text(encoding="utf-8"))
251
+
252
+
253
+ def write_credentials_doc(doc: tomlkit.TOMLDocument) -> None:
254
+ CREDENTIALS_PATH.parent.mkdir(parents=True, exist_ok=True)
255
+ CREDENTIALS_PATH.write_text(tomlkit.dumps(doc), encoding="utf-8")
256
+ CREDENTIALS_PATH.chmod(0o600)