chalk-worker 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.
@@ -0,0 +1,6 @@
1
+ """
2
+ Pull worker for Codehood: claims grading jobs of code questions, grades them
3
+ with chalk-grader in a local sandbox and sends the feedback back.
4
+ """
5
+
6
+ __version__ = "0.1.0"
chalk_worker/cli.py ADDED
@@ -0,0 +1,281 @@
1
+ """
2
+ Command line of the worker.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import fcntl
8
+ import os
9
+ import signal
10
+ import sys
11
+ import threading
12
+ import tomllib
13
+ import traceback
14
+ from datetime import datetime
15
+ from pathlib import Path
16
+ from typing import IO, Annotated, Any
17
+
18
+ import pydantic
19
+ import typer
20
+ from chalk_grader import cgroup
21
+ from mdq.models import CodeQuestion
22
+
23
+ from .client import WorkerClient
24
+ from .grading import QuestionGrader, question_hash
25
+ from .loop import Filters, Worker
26
+
27
+ MiB = 1024 * 1024
28
+
29
+ app = typer.Typer(add_completion=False)
30
+
31
+ #: Environment variable with the key of the grading bot.
32
+ BOT_KEY_VAR = "CODEHOOD_BOT_KEY"
33
+
34
+
35
+ @app.command()
36
+ def run(
37
+ server: Annotated[
38
+ str | None, typer.Option(help="Codehood URL; default: [server] url of codehood.toml.")
39
+ ] = None,
40
+ key_file: Annotated[
41
+ Path | None, typer.Option(help=f"File with the BOT key; default: ${BOT_KEY_VAR}.")
42
+ ] = None,
43
+ worker: Annotated[
44
+ list[str] | None, typer.Option(help="Worker id to take jobs of (repeatable).")
45
+ ] = None,
46
+ exam: Annotated[str | None, typer.Option(help="Take only jobs of this exam (slug).")] = None,
47
+ discipline: Annotated[
48
+ str | None, typer.Option(help="Take only jobs of the courses of this discipline (slug).")
49
+ ] = None,
50
+ course: Annotated[
51
+ str | None,
52
+ typer.Option(
53
+ help="Take only jobs of this course (<discipline>/<user>_<edition>); "
54
+ "default: the course of codehood.toml, unless --discipline is given."
55
+ ),
56
+ ] = None,
57
+ poll: Annotated[
58
+ float, typer.Option(help="Seconds between claims when the queue is empty.")
59
+ ] = 10,
60
+ jobs: Annotated[
61
+ int | None, typer.Option(help="Jobs graded at once; default: the number of cores.")
62
+ ] = None,
63
+ batch: Annotated[
64
+ int | None, typer.Option(help="Most jobs asked for in one claim; default: --jobs.")
65
+ ] = None,
66
+ lease: Annotated[float, typer.Option(help="Seconds a claimed job is reserved.")] = 120,
67
+ memory: Annotated[
68
+ str,
69
+ typer.Option(
70
+ help="Memory each run of a job may take, as in 512MiB (with a delegated cgroup, "
71
+ "a run that goes past it is stopped: resource-limit); jobs start only while the "
72
+ "available memory holds them. 0: the profile's default, and no check of the "
73
+ "available memory."
74
+ ),
75
+ ] = "512MiB",
76
+ memory_reserve: Annotated[
77
+ str, typer.Option(help="Memory left to the rest of the machine when starting jobs.")
78
+ ] = "512MiB",
79
+ sandbox: Annotated[
80
+ str | None, typer.Option(help="Sandbox of the runs: bwrap (default) or none.")
81
+ ] = None,
82
+ cache_dir: Annotated[
83
+ Path | None, typer.Option(help="Where graders and packages are kept.")
84
+ ] = None,
85
+ once: Annotated[
86
+ bool, typer.Option(help="Grade what is pending and exit instead of polling.")
87
+ ] = False,
88
+ tui: Annotated[
89
+ bool | None,
90
+ typer.Option(help="Show the slots and the jobs in a terminal UI; default: on a terminal."),
91
+ ] = None,
92
+ ) -> None:
93
+ """
94
+ Claim grading jobs from Codehood, grade them locally and send the reports.
95
+ """
96
+ if exam and discipline:
97
+ raise typer.BadParameter("use --exam or --discipline, not both")
98
+ on_terminal = sys.stdin.isatty() and sys.stdout.isatty()
99
+ if tui is None:
100
+ tui = on_terminal
101
+ elif tui and not on_terminal:
102
+ raise typer.BadParameter("--tui needs a terminal on stdin and stdout; use --no-tui")
103
+ config = _course_config(Path.cwd())
104
+ url = server or config.get("server", {}).get("url")
105
+ if not url:
106
+ raise typer.BadParameter("no server: use --server or set [server] url in codehood.toml")
107
+ if course is None and discipline is None:
108
+ course = _course_ref(config)
109
+ key = _read_key(key_file)
110
+ per_job = _bytes(memory, "--memory") or None
111
+ reserve = _bytes(memory_reserve, "--memory-reserve")
112
+ root = cache_dir or _default_cache()
113
+ _cache_lock = _lock_cache(root) # held until the process exits
114
+ jobs = jobs or os.process_cpu_count() or 1
115
+
116
+ def make_grader(question: CodeQuestion) -> QuestionGrader:
117
+ return QuestionGrader(
118
+ question, root / question_hash(question)[:16], sandbox=sandbox, memory=per_job
119
+ )
120
+
121
+ loop = Worker(
122
+ WorkerClient(url, key),
123
+ make_grader,
124
+ workers=worker or ["elm-test"],
125
+ jobs=jobs,
126
+ batch=batch,
127
+ poll=poll,
128
+ lease=lease,
129
+ filters=Filters(discipline=discipline, course=course, exam=exam),
130
+ log=(lambda _: None) if tui else _log,
131
+ memory=per_job,
132
+ reserve=reserve,
133
+ )
134
+ workers = ", ".join(worker or ["elm-test"])
135
+ limited, limits = _limits_note(per_job)
136
+ loop.status.log(limits)
137
+ if tui:
138
+ shown = "run limits on" if limited else "NO run limits"
139
+ _run_tui(loop, once, f"{workers} · {jobs} slots · {shown} · {url}")
140
+ return
141
+
142
+ _log(limits if limited else f"warning: {limits}")
143
+
144
+ def abort(signum: int, _frame: Any) -> None:
145
+ # The runs in progress live in cgroups of their own: kill them first.
146
+ if (runs := cgroup.controller()) is not None:
147
+ runs.kill_all()
148
+ signal.signal(signum, signal.SIG_DFL)
149
+ os.kill(os.getpid(), signum)
150
+
151
+ def stop(signum: int, _frame: Any) -> None:
152
+ _log("stopping after the jobs in progress (again to abort)")
153
+ loop.stop()
154
+ signal.signal(signum, abort)
155
+
156
+ signal.signal(signal.SIGINT, stop)
157
+ signal.signal(signal.SIGTERM, stop)
158
+ _log(f"claiming {workers} jobs from {url}, {jobs} at once")
159
+ done = loop.run(once=once)
160
+ _log(f"{done} jobs processed")
161
+
162
+
163
+ def _run_tui(loop: Worker, once: bool, subtitle: str) -> None:
164
+ from .tui import WorkerApp
165
+
166
+ app = WorkerApp(loop, once=once, subtitle=subtitle)
167
+
168
+ hung_up = threading.Event()
169
+
170
+ def hangup(_signum: int, _frame: Any) -> None:
171
+ # The terminal is gone, and the display may block writing to it: let
172
+ # the jobs in progress end, then leave without it. Again: at once.
173
+ if app.finished.is_set():
174
+ _exit(0)
175
+ if hung_up.is_set():
176
+ _exit(130)
177
+ hung_up.set()
178
+ loop.stop()
179
+ threading.Thread(target=lambda: (app.finished.wait(), _exit(0)), daemon=True).start()
180
+
181
+ signal.signal(signal.SIGHUP, hangup)
182
+ done = app.run()
183
+ if app.error is not None:
184
+ traceback.print_exception(app.error)
185
+ _log(f"the claim loop failed: {type(app.error).__name__}: {app.error}")
186
+ _exit(1)
187
+ if done is None:
188
+ # Aborted with jobs in progress: their leases run out on the server.
189
+ # Leave now, without waiting for the grading threads.
190
+ _log("aborted")
191
+ _exit(130)
192
+ _log(f"{done} jobs processed")
193
+
194
+
195
+ def _exit(code: int) -> None:
196
+ # os._exit skips atexit, so the runs left in their cgroups are killed here.
197
+ if (runs := cgroup.controller()) is not None:
198
+ runs.kill_all()
199
+ sys.stdout.flush()
200
+ sys.stderr.flush()
201
+ os._exit(code)
202
+
203
+
204
+ def _limits_note(memory: int | None) -> tuple[bool, str]:
205
+ """
206
+ Whether runs have a cgroup of their own, with a line that says so.
207
+ """
208
+ if cgroup.controller() is None:
209
+ return False, (
210
+ "runs have no memory or process limit: no delegated cgroup (start the worker "
211
+ "where the systemd of the user answers; see the README)"
212
+ )
213
+ budget = f"{memory // MiB} MiB" if memory else "the profile's default memory"
214
+ return True, f"each run in a cgroup of its own, with {budget}"
215
+
216
+
217
+ def _bytes(text: str, option: str) -> int:
218
+ try:
219
+ return int(pydantic.TypeAdapter(pydantic.ByteSize).validate_python(text))
220
+ except pydantic.ValidationError:
221
+ raise typer.BadParameter(f"{option}: not a size: {text!r}") from None
222
+
223
+
224
+ def _lock_cache(root: Path) -> IO[str]:
225
+ """
226
+ Take the cache directory for this process, so that two workers do not
227
+ prepare the same question in it at once.
228
+ """
229
+ root.mkdir(parents=True, exist_ok=True)
230
+ lock = (root / ".lock").open("w")
231
+ try:
232
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
233
+ except BlockingIOError:
234
+ lock.close()
235
+ raise typer.BadParameter(
236
+ f"another chalk-worker uses {root}; stop it, or give this one its own --cache-dir"
237
+ ) from None
238
+ return lock
239
+
240
+
241
+ def _course_config(start: Path) -> dict[str, Any]:
242
+ for folder in (start, *start.parents):
243
+ if (path := folder / "codehood.toml").is_file():
244
+ return tomllib.loads(path.read_text())
245
+ return {}
246
+
247
+
248
+ def _course_ref(config: dict[str, Any]) -> str | None:
249
+ course = config.get("course", {})
250
+ parts = [course.get(k) for k in ("discipline", "instructor", "edition")]
251
+ if not all(parts):
252
+ return None
253
+ discipline, instructor, edition = parts
254
+ return f"{discipline}/{instructor}_{edition}"
255
+
256
+
257
+ def _read_key(key_file: Path | None) -> str:
258
+ key = key_file.read_text().strip() if key_file else os.environ.get(BOT_KEY_VAR, "").strip()
259
+ if not key:
260
+ raise typer.BadParameter(f"no BOT key: set {BOT_KEY_VAR} or use --key-file")
261
+ return key
262
+
263
+
264
+ def _default_cache() -> Path:
265
+ base = os.environ.get("XDG_CACHE_HOME") or str(Path.home() / ".cache")
266
+ return Path(base) / "chalk-worker"
267
+
268
+
269
+ def _log(line: str) -> None:
270
+ typer.echo(f"{datetime.now():%H:%M:%S} {line}", err=True)
271
+
272
+
273
+ def main() -> None:
274
+ if "--help" not in sys.argv:
275
+ # Every command grades. Under a scope with Delegate=yes, each run
276
+ # gets a cgroup with its memory and process limits.
277
+ cgroup.reexec_delegated()
278
+ # Before any thread or process: the setup of the cgroups gives up
279
+ # when the delegated cgroup has other processes.
280
+ cgroup.controller()
281
+ app()
chalk_worker/client.py ADDED
@@ -0,0 +1,103 @@
1
+ """
2
+ The REST calls of a pull worker (`/api/grading-jobs/`), authenticated with
3
+ the instructor's `BOT` key.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import Sequence
9
+ from typing import Any
10
+
11
+ import httpx
12
+
13
+ __all__ = ["ApiError", "Conflict", "WorkerClient"]
14
+
15
+
16
+ class ApiError(RuntimeError):
17
+ """
18
+ The server refused a request.
19
+ """
20
+
21
+ def __init__(self, status: int, message: str) -> None:
22
+ super().__init__(f"{status}: {message}")
23
+ self.status = status
24
+
25
+
26
+ class Conflict(ApiError):
27
+ """
28
+ The job moved on without this worker: the lease was lost, the student
29
+ replaced the submission, or an instructor graded it.
30
+ """
31
+
32
+
33
+ class WorkerClient:
34
+ """
35
+ Claims grading jobs and sends their results.
36
+ """
37
+
38
+ def __init__(
39
+ self, server: str, key: str, *, http: httpx.Client | None = None, timeout: float = 30
40
+ ) -> None:
41
+ self.base = server.rstrip("/") + "/api/grading-jobs"
42
+ self.http = http or httpx.Client(timeout=timeout)
43
+ self.headers = {"Authorization": f"Bearer {key}"}
44
+
45
+ def claim(
46
+ self,
47
+ workers: Sequence[str],
48
+ *,
49
+ limit: int,
50
+ lease: float,
51
+ discipline: str | None = None,
52
+ course: str | None = None,
53
+ exam: str | None = None,
54
+ questions: Sequence[str] | None = None,
55
+ ) -> list[dict[str, Any]]:
56
+ """
57
+ Take up to `limit` queued jobs of the given workers, leased for
58
+ `lease` seconds.
59
+ """
60
+ body: dict[str, Any] = {"workers": list(workers), "limit": limit, "lease": lease}
61
+ optional = {"discipline": discipline, "course": course, "exam": exam}
62
+ body |= {k: v for k, v in optional.items() if v is not None}
63
+ if questions is not None:
64
+ body["questions"] = list(questions)
65
+ return self._post("claim", body)["jobs"]
66
+
67
+ def renew(self, submission: str, lease: float) -> None:
68
+ """
69
+ Extend the lease of a job this worker holds.
70
+ """
71
+ self._post(f"{submission}/renew", {"lease": lease})
72
+
73
+ def fail(self, submission: str, error: str, retry: bool) -> None:
74
+ """
75
+ Give a job back: `retry` counts an infrastructure failure, without it
76
+ the job returns to the queue as it was.
77
+ """
78
+ self._post(f"{submission}/fail", {"error": error, "retry": retry})
79
+
80
+ def result(self, submission: str, report: dict[str, Any]) -> dict[str, Any]:
81
+ """
82
+ Send the runner report of a job, which closes it.
83
+ """
84
+ return self._post(f"{submission}/result", report)
85
+
86
+ def _post(self, path: str, body: dict[str, Any]) -> dict[str, Any]:
87
+ response = self.http.post(f"{self.base}/{path}", json=body, headers=self.headers)
88
+ if response.status_code >= 400:
89
+ error = Conflict if response.status_code == 409 else ApiError
90
+ raise error(response.status_code, _message(response))
91
+ return response.json() if response.content else {}
92
+
93
+
94
+ def _message(response: httpx.Response) -> str:
95
+ try:
96
+ data = response.json()
97
+ except ValueError:
98
+ return response.text[:500] or response.reason_phrase
99
+ if isinstance(data, dict):
100
+ for key in ("message", "error", "detail"):
101
+ if isinstance(data.get(key), str):
102
+ return data[key]
103
+ return str(data)[:500]
@@ -0,0 +1,263 @@
1
+ """
2
+ Elm tests written as examples, one `expr ==> value` or `expr ~= value` per line.
3
+
4
+ A fenced test source of an Elm question that has no `module` header is an
5
+ examples block, turned into an elm-test module. The format has a twin in
6
+ TypeScript (`src/services/elm-examples.ts` of codehood), and both run the
7
+ table `tests/resources/elm-examples-cases.json`.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ from dataclasses import dataclass
14
+ from typing import Literal
15
+
16
+ from mdq._parser import scan_annotations
17
+
18
+ __all__ = [
19
+ "Example",
20
+ "ExampleError",
21
+ "answer_module",
22
+ "example_cases",
23
+ "examples_module",
24
+ "locate_example",
25
+ "module_name",
26
+ ]
27
+
28
+ #: Prefix of the name of the generated module, followed by the source index.
29
+ MODULE_PREFIX = "Examples"
30
+
31
+ #: The operators of a case, with the matcher each one generates.
32
+ OPERATORS = {
33
+ "==>": "Expect.equal",
34
+ "~=": "Expect.within (Expect.AbsoluteOrRelative 1.0e-9 1.0e-6)",
35
+ }
36
+
37
+ type ErrorKind = Literal[
38
+ "invalid-line",
39
+ "invalid-annotation",
40
+ "late-import",
41
+ "duplicate-name",
42
+ "no-cases",
43
+ "empty-region",
44
+ ]
45
+
46
+ #: The `ANNOTATION_START` terminal of the MDQ spec (`docs/question-types/code.md`,
47
+ #: "Annotations"), anchored at the start of a line. mdq-py does not expose it.
48
+ _ANNOTATION_START = re.compile(r"[ \t!-/:-@\[-`{-~]*mdq:")
49
+
50
+
51
+ class ExampleError(ValueError):
52
+ """
53
+ An examples block breaks the format. It is a mistake of the question
54
+ author, never of a student.
55
+ """
56
+
57
+ def __init__(self, message: str, line: int | None, kind: ErrorKind) -> None:
58
+ super().__init__(message)
59
+ #: The line of the block, from 1, or None when the error has no line.
60
+ self.line = line
61
+ self.kind = kind
62
+
63
+
64
+ @dataclass(frozen=True)
65
+ class Example:
66
+ """
67
+ One case of an examples block.
68
+ """
69
+
70
+ #: The line of the source, from 1.
71
+ line: int
72
+ operator: str
73
+ expr: str
74
+ value: str
75
+ comment: str = ""
76
+ #: Whether the case is in a `{public}` or `{example}` region.
77
+ public: bool = False
78
+
79
+ @property
80
+ def name(self) -> str:
81
+ """
82
+ The name of the test the student sees: `expr ==> value (comment)`.
83
+ """
84
+ base = f"{self.expr} {self.operator} {self.value}"
85
+ return f"{base} ({self.comment})" if self.comment else base
86
+
87
+
88
+ def module_name(index: int) -> str:
89
+ """
90
+ The name of the module generated for the test source at `index`.
91
+ """
92
+ return f"{MODULE_PREFIX}{index}"
93
+
94
+
95
+ def answer_module(file: str) -> str:
96
+ """
97
+ The module of an Elm answer file: `Foo/Bar.elm` is `Foo.Bar`.
98
+ """
99
+ return file.removesuffix(".elm").replace("/", ".")
100
+
101
+
102
+ def example_cases(text: str) -> list[Example]:
103
+ """
104
+ The cases of an examples block, in source order.
105
+
106
+ Raises:
107
+ ExampleError: the block is invalid.
108
+ """
109
+ return _parse(text)[1]
110
+
111
+
112
+ def examples_module(
113
+ text: str, index: int, answer_file: str, public_only: bool = False
114
+ ) -> str | None:
115
+ """
116
+ The elm-test module of an examples block, importing the answer module, or
117
+ None when `public_only` is set and no case is public.
118
+
119
+ Raises:
120
+ ExampleError: the block is invalid.
121
+ """
122
+ imports, cases = _parse(text)
123
+ chosen = [c for c in cases if c.public] if public_only else cases
124
+ if not chosen:
125
+ return None
126
+ entries = [
127
+ f" {'[' if i == 0 else ','} Test.test {_string(c.name)} "
128
+ f"(\\_ -> {OPERATORS[c.operator]} ({c.value}) ({c.expr}))"
129
+ for i, c in enumerate(chosen)
130
+ ]
131
+ lines = [
132
+ f"module {module_name(index)} exposing (tests)",
133
+ "",
134
+ "import Expect",
135
+ "import Test",
136
+ f"import {answer_module(answer_file)} exposing (..)",
137
+ *imports,
138
+ "",
139
+ "",
140
+ "tests : Test.Test",
141
+ "tests =",
142
+ " Test.concat",
143
+ *entries,
144
+ " ]",
145
+ "",
146
+ ]
147
+ return "\n".join(lines)
148
+
149
+
150
+ def locate_example(text: str, name: str) -> int | None:
151
+ """
152
+ The line of the case of a block whose test is called `name`.
153
+ """
154
+ try:
155
+ return next((e.line for e in example_cases(text) if e.name == name), None)
156
+ except ExampleError:
157
+ return None
158
+
159
+
160
+ def _string(text: str) -> str:
161
+ return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"'
162
+
163
+
164
+ def _parse(text: str) -> tuple[list[str], list[Example]]:
165
+ """
166
+ The `import` lines and the cases of a block.
167
+ """
168
+ scan = scan_annotations(text)
169
+ if scan.problems:
170
+ problem = scan.problems[0]
171
+ raise ExampleError(
172
+ f"line {problem.line}: {problem.message}", problem.line, "invalid-annotation"
173
+ )
174
+ imports: list[str] = []
175
+ cases: list[Example] = []
176
+ names: set[str] = set()
177
+ for number, line in enumerate(scan.lines, start=1):
178
+ if _ANNOTATION_START.match(line):
179
+ continue
180
+ if not line.strip(" \t") or line.lstrip(" \t").startswith("--"):
181
+ continue
182
+ if re.match(r"import[ \t]", line):
183
+ if cases:
184
+ raise ExampleError(
185
+ f"line {number}: import after the first case", number, "late-import"
186
+ )
187
+ imports.append(line.rstrip(" \t"))
188
+ continue
189
+ region = next((it for it in reversed(scan.items) if it.line <= number), None)
190
+ case = _parse_case(line, number, region is not None and region.public)
191
+ if case.name in names:
192
+ raise ExampleError(
193
+ f"line {number}: duplicate case {case.name!r}", number, "duplicate-name"
194
+ )
195
+ names.add(case.name)
196
+ cases.append(case)
197
+ for item in scan.items:
198
+ first = item.line + item.annotation_lines
199
+ if not any(first <= c.line <= item.end for c in cases):
200
+ raise _empty_region(item.line)
201
+ if not cases:
202
+ raise ExampleError("the block has no case", None, "no-cases")
203
+ return imports, cases
204
+
205
+
206
+ def _empty_region(line: int) -> ExampleError:
207
+ return ExampleError(f"line {line}: the annotated region has no case", line, "empty-region")
208
+
209
+
210
+ def _parse_case(line: str, number: int, public: bool) -> Example:
211
+ comments = _outside_literals(line, "--")
212
+ code = line[: comments[0]] if comments else line
213
+ comment = line[comments[0] + 2 :].strip(" \t") if comments else ""
214
+ found = [(op, at) for op in OPERATORS for at in _outside_literals(code, op)]
215
+ if len(found) != 1:
216
+ raise _invalid(number, line)
217
+ operator, at = found[0]
218
+ expr = code[:at].strip(" \t")
219
+ value = code[at + len(operator) :].strip(" \t")
220
+ if not expr or not value:
221
+ raise _invalid(number, line)
222
+ return Example(number, operator, expr, value, comment, public)
223
+
224
+
225
+ def _invalid(number: int, line: str) -> ExampleError:
226
+ hint = " (triple-quoted strings are not supported)" if '"""' in line else ""
227
+ return ExampleError(
228
+ f"line {number}: expected `expr ==> value` or `expr ~= value`{hint}", number, "invalid-line"
229
+ )
230
+
231
+
232
+ def _outside_literals(text: str, token: str) -> list[int]:
233
+ """
234
+ The positions of `token` in `text` outside string and character literals.
235
+ An unterminated literal runs to the end of the text.
236
+ """
237
+ found: list[int] = []
238
+ i = 0
239
+ while i < len(text):
240
+ c = text[i]
241
+ if c == '"' or (
242
+ c == "'" and not (i > 0 and (text[i - 1].isalnum() or text[i - 1] in "_'"))
243
+ ):
244
+ i = _literal_end(text, i)
245
+ elif text.startswith(token, i):
246
+ found.append(i)
247
+ i += len(token)
248
+ else:
249
+ i += 1
250
+ return found
251
+
252
+
253
+ def _literal_end(text: str, start: int) -> int:
254
+ quote = text[start]
255
+ i = start + 1
256
+ while i < len(text):
257
+ if text[i] == "\\":
258
+ i += 2
259
+ elif text[i] == quote:
260
+ return i + 1
261
+ else:
262
+ i += 1
263
+ return len(text)