cf-tool-cli 1.0.0__tar.gz

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 (62) hide show
  1. cf_tool_cli-1.0.0/LICENSE +48 -0
  2. cf_tool_cli-1.0.0/PKG-INFO +106 -0
  3. cf_tool_cli-1.0.0/README.md +61 -0
  4. cf_tool_cli-1.0.0/cf_tool/__init__.py +3 -0
  5. cf_tool_cli-1.0.0/cf_tool/__main__.py +6 -0
  6. cf_tool_cli-1.0.0/cf_tool/build.py +211 -0
  7. cf_tool_cli-1.0.0/cf_tool/cli/__init__.py +117 -0
  8. cf_tool_cli-1.0.0/cf_tool/cli/account.py +32 -0
  9. cf_tool_cli-1.0.0/cf_tool/cli/common.py +262 -0
  10. cf_tool_cli-1.0.0/cf_tool/cli/completion.py +226 -0
  11. cf_tool_cli-1.0.0/cf_tool/cli/configure.py +386 -0
  12. cf_tool_cli-1.0.0/cf_tool/cli/problems.py +399 -0
  13. cf_tool_cli-1.0.0/cf_tool/cli/setup.py +195 -0
  14. cf_tool_cli-1.0.0/cf_tool/cli/submitting.py +309 -0
  15. cf_tool_cli-1.0.0/cf_tool/cli/testing.py +354 -0
  16. cf_tool_cli-1.0.0/cf_tool/codeforces/__init__.py +3 -0
  17. cf_tool_cli-1.0.0/cf_tool/codeforces/browser.py +346 -0
  18. cf_tool_cli-1.0.0/cf_tool/codeforces/client.py +521 -0
  19. cf_tool_cli-1.0.0/cf_tool/codeforces/crypto.py +41 -0
  20. cf_tool_cli-1.0.0/cf_tool/codeforces/gateway.py +288 -0
  21. cf_tool_cli-1.0.0/cf_tool/codeforces/http.py +213 -0
  22. cf_tool_cli-1.0.0/cf_tool/codeforces/pages.py +767 -0
  23. cf_tool_cli-1.0.0/cf_tool/codeforces/session.py +103 -0
  24. cf_tool_cli-1.0.0/cf_tool/doctor.py +124 -0
  25. cf_tool_cli-1.0.0/cf_tool/errors.py +37 -0
  26. cf_tool_cli-1.0.0/cf_tool/judge.py +481 -0
  27. cf_tool_cli-1.0.0/cf_tool/languages.py +1195 -0
  28. cf_tool_cli-1.0.0/cf_tool/listen.py +178 -0
  29. cf_tool_cli-1.0.0/cf_tool/paths.py +57 -0
  30. cf_tool_cli-1.0.0/cf_tool/process.py +431 -0
  31. cf_tool_cli-1.0.0/cf_tool/settings.py +386 -0
  32. cf_tool_cli-1.0.0/cf_tool/stress.py +167 -0
  33. cf_tool_cli-1.0.0/cf_tool/ui.py +455 -0
  34. cf_tool_cli-1.0.0/cf_tool/views.py +306 -0
  35. cf_tool_cli-1.0.0/cf_tool/workspace.py +777 -0
  36. cf_tool_cli-1.0.0/cf_tool_cli.egg-info/PKG-INFO +106 -0
  37. cf_tool_cli-1.0.0/cf_tool_cli.egg-info/SOURCES.txt +60 -0
  38. cf_tool_cli-1.0.0/cf_tool_cli.egg-info/dependency_links.txt +1 -0
  39. cf_tool_cli-1.0.0/cf_tool_cli.egg-info/entry_points.txt +2 -0
  40. cf_tool_cli-1.0.0/cf_tool_cli.egg-info/requires.txt +18 -0
  41. cf_tool_cli-1.0.0/cf_tool_cli.egg-info/top_level.txt +1 -0
  42. cf_tool_cli-1.0.0/pyproject.toml +86 -0
  43. cf_tool_cli-1.0.0/setup.cfg +4 -0
  44. cf_tool_cli-1.0.0/tests/test_browser.py +146 -0
  45. cf_tool_cli-1.0.0/tests/test_build.py +187 -0
  46. cf_tool_cli-1.0.0/tests/test_cli.py +1031 -0
  47. cf_tool_cli-1.0.0/tests/test_client.py +314 -0
  48. cf_tool_cli-1.0.0/tests/test_crypto.py +33 -0
  49. cf_tool_cli-1.0.0/tests/test_doctor.py +128 -0
  50. cf_tool_cli-1.0.0/tests/test_gateway.py +377 -0
  51. cf_tool_cli-1.0.0/tests/test_judge.py +295 -0
  52. cf_tool_cli-1.0.0/tests/test_languages.py +498 -0
  53. cf_tool_cli-1.0.0/tests/test_listen.py +184 -0
  54. cf_tool_cli-1.0.0/tests/test_live.py +138 -0
  55. cf_tool_cli-1.0.0/tests/test_pages.py +592 -0
  56. cf_tool_cli-1.0.0/tests/test_process.py +172 -0
  57. cf_tool_cli-1.0.0/tests/test_session.py +205 -0
  58. cf_tool_cli-1.0.0/tests/test_settings.py +297 -0
  59. cf_tool_cli-1.0.0/tests/test_stress.py +102 -0
  60. cf_tool_cli-1.0.0/tests/test_ui.py +178 -0
  61. cf_tool_cli-1.0.0/tests/test_views.py +89 -0
  62. cf_tool_cli-1.0.0/tests/test_workspace.py +499 -0
@@ -0,0 +1,48 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Fau818
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ --------------------------------------------------------------------------------
24
+
25
+ cf-tool is a Python port of xalanq/cf-tool (https://github.com/xalanq/cf-tool),
26
+ whose license follows:
27
+
28
+ The MIT License (MIT)
29
+
30
+ Copyright (c) 2014 Manuel Martínez-Almeida
31
+
32
+ Permission is hereby granted, free of charge, to any person obtaining a copy
33
+ of this software and associated documentation files (the "Software"), to deal
34
+ in the Software without restriction, including without limitation the rights
35
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
36
+ copies of the Software, and to permit persons to whom the Software is
37
+ furnished to do so, subject to the following conditions:
38
+
39
+ The above copyright notice and this permission notice shall be included in
40
+ all copies or substantial portions of the Software.
41
+
42
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
43
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
44
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
45
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
46
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
47
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
48
+ THE SOFTWARE.
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.4
2
+ Name: cf-tool-cli
3
+ Version: 1.0.0
4
+ Summary: Codeforces from your terminal: get problems, test your code on their samples, submit
5
+ Author: Fau818
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Fau818/cf-tool
8
+ Project-URL: Issues, https://github.com/Fau818/cf-tool/issues
9
+ Project-URL: Changelog, https://github.com/Fau818/cf-tool/blob/main/CHANGELOG.md
10
+ Keywords: codeforces,competitive-programming,cli,cp
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Education
15
+ Classifier: Topic :: Education
16
+ Classifier: Topic :: Software Development :: Testing
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Programming Language :: Python :: 3.13
24
+ Requires-Python: >=3.10
25
+ Description-Content-Type: text/markdown
26
+ License-File: LICENSE
27
+ Requires-Dist: click>=8.1.0
28
+ Requires-Dist: curl_cffi>=0.10.0
29
+ Requires-Dist: beautifulsoup4>=4.12.0
30
+ Requires-Dist: lxml>=4.9.0
31
+ Requires-Dist: rich>=13.0.0
32
+ Requires-Dist: questionary>=2.0.0
33
+ Requires-Dist: cryptography>=42.0.0
34
+ Requires-Dist: psutil>=5.9.0
35
+ Requires-Dist: DrissionPage>=4.0.0
36
+ Requires-Dist: tomlkit>=0.12.0
37
+ Provides-Extra: dev
38
+ Requires-Dist: pytest>=7.4.0; extra == "dev"
39
+ Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
40
+ Requires-Dist: black>=23.0.0; extra == "dev"
41
+ Requires-Dist: flake8>=6.0.0; extra == "dev"
42
+ Requires-Dist: mypy>=1.4.0; extra == "dev"
43
+ Requires-Dist: basedpyright>=1.38.0; extra == "dev"
44
+ Dynamic: license-file
45
+
46
+ # cf-tool
47
+
48
+ [![CI](https://github.com/Fau818/cf-tool/actions/workflows/ci.yml/badge.svg)](https://github.com/Fau818/cf-tool/actions/workflows/ci.yml)
49
+ [![PyPI](https://img.shields.io/pypi/v/cf-tool-cli)](https://pypi.org/project/cf-tool-cli/)
50
+
51
+ Codeforces from your terminal: get a contest, test your code on the samples, submit, and
52
+ watch the verdict. No setup first.
53
+
54
+ ![cf get, cf test and cf submit](https://raw.githubusercontent.com/Fau818/cf-tool/main/docs/images/hero.png)
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ uv tool install cf-tool-cli # or: pipx install cf-tool-cli
60
+ ```
61
+
62
+ You need Python 3.10+, a compiler or interpreter for your language, and Google Chrome to
63
+ log in (it works in the background).
64
+
65
+ ## A contest, start to finish
66
+
67
+ **`cf get 2050`** makes a folder per problem: the statement, the samples and your starter
68
+ code. The first time, cf asks which language you write in.
69
+
70
+ **`cf test`** builds your code and runs it on the samples. A wrong answer shows the input
71
+ and where your output parts from the answer, down to the test case:
72
+
73
+ ![cf test finding a wrong answer](https://raw.githubusercontent.com/Fau818/cf-tool/main/docs/images/test.png)
74
+
75
+ **`cf submit`** sends it and shows the verdict as it comes. Once the contest is over, a
76
+ failed test comes with it, as Codeforces keeps it, and is saved for `cf test`:
77
+
78
+ ![a wrong answer and its failed test](https://raw.githubusercontent.com/Fau818/cf-tool/main/docs/images/failed.png)
79
+
80
+ **`cf status`** lists your submissions, refreshed until they're judged:
81
+
82
+ ![cf status](https://raw.githubusercontent.com/Fau818/cf-tool/main/docs/images/status.png)
83
+
84
+ ## Commands
85
+
86
+ | Command | What it does |
87
+ | --- | --- |
88
+ | `cf get 2050` / `cf get 2050b` | folders, samples and starter code for a contest or a problem |
89
+ | `cf test [problem] [test...]` | build your code and run it on the problem's tests (`-w`: on every save) |
90
+ | `cf submit [problem] [file]` | submit, then watch the verdict |
91
+ | `cf status [submission]` | your submissions, or one with the test it failed |
92
+ | `cf stress` | random tests until your code and a brute force disagree |
93
+ | `cf race 2050` | count down to the start, then get the problems |
94
+ | `cf open` / `cf problems` / `cf contests` | the problem in the browser, a contest's problems, upcoming contests |
95
+ | `cf pick -r 1600 -t dp` | a random problem you haven't solved |
96
+ | `cf new` / `cf listen` | a code file from your starter code; problems from Competitive Companion |
97
+ | `cf pull` / `cf clone` | download the code of your (or anyone's) submissions |
98
+ | `cf login` / `cf config` / `cf doctor` | log in; settings from menus; check the setup |
99
+
100
+ More in the [guide](https://github.com/Fau818/cf-tool/blob/main/docs/guide.md): your own
101
+ tests, checkers, interactive problems, settings, CP Editor, Tab completion, coming from
102
+ cf-tool 0.3.
103
+
104
+ ## License
105
+
106
+ MIT. cf-tool began as a port of [xalanq/cf-tool](https://github.com/xalanq/cf-tool).
@@ -0,0 +1,61 @@
1
+ # cf-tool
2
+
3
+ [![CI](https://github.com/Fau818/cf-tool/actions/workflows/ci.yml/badge.svg)](https://github.com/Fau818/cf-tool/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/cf-tool-cli)](https://pypi.org/project/cf-tool-cli/)
5
+
6
+ Codeforces from your terminal: get a contest, test your code on the samples, submit, and
7
+ watch the verdict. No setup first.
8
+
9
+ ![cf get, cf test and cf submit](https://raw.githubusercontent.com/Fau818/cf-tool/main/docs/images/hero.png)
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ uv tool install cf-tool-cli # or: pipx install cf-tool-cli
15
+ ```
16
+
17
+ You need Python 3.10+, a compiler or interpreter for your language, and Google Chrome to
18
+ log in (it works in the background).
19
+
20
+ ## A contest, start to finish
21
+
22
+ **`cf get 2050`** makes a folder per problem: the statement, the samples and your starter
23
+ code. The first time, cf asks which language you write in.
24
+
25
+ **`cf test`** builds your code and runs it on the samples. A wrong answer shows the input
26
+ and where your output parts from the answer, down to the test case:
27
+
28
+ ![cf test finding a wrong answer](https://raw.githubusercontent.com/Fau818/cf-tool/main/docs/images/test.png)
29
+
30
+ **`cf submit`** sends it and shows the verdict as it comes. Once the contest is over, a
31
+ failed test comes with it, as Codeforces keeps it, and is saved for `cf test`:
32
+
33
+ ![a wrong answer and its failed test](https://raw.githubusercontent.com/Fau818/cf-tool/main/docs/images/failed.png)
34
+
35
+ **`cf status`** lists your submissions, refreshed until they're judged:
36
+
37
+ ![cf status](https://raw.githubusercontent.com/Fau818/cf-tool/main/docs/images/status.png)
38
+
39
+ ## Commands
40
+
41
+ | Command | What it does |
42
+ | --- | --- |
43
+ | `cf get 2050` / `cf get 2050b` | folders, samples and starter code for a contest or a problem |
44
+ | `cf test [problem] [test...]` | build your code and run it on the problem's tests (`-w`: on every save) |
45
+ | `cf submit [problem] [file]` | submit, then watch the verdict |
46
+ | `cf status [submission]` | your submissions, or one with the test it failed |
47
+ | `cf stress` | random tests until your code and a brute force disagree |
48
+ | `cf race 2050` | count down to the start, then get the problems |
49
+ | `cf open` / `cf problems` / `cf contests` | the problem in the browser, a contest's problems, upcoming contests |
50
+ | `cf pick -r 1600 -t dp` | a random problem you haven't solved |
51
+ | `cf new` / `cf listen` | a code file from your starter code; problems from Competitive Companion |
52
+ | `cf pull` / `cf clone` | download the code of your (or anyone's) submissions |
53
+ | `cf login` / `cf config` / `cf doctor` | log in; settings from menus; check the setup |
54
+
55
+ More in the [guide](https://github.com/Fau818/cf-tool/blob/main/docs/guide.md): your own
56
+ tests, checkers, interactive problems, settings, CP Editor, Tab completion, coming from
57
+ cf-tool 0.3.
58
+
59
+ ## License
60
+
61
+ MIT. cf-tool began as a port of [xalanq/cf-tool](https://github.com/xalanq/cf-tool).
@@ -0,0 +1,3 @@
1
+ """cf-tool: Codeforces from your terminal."""
2
+
3
+ __version__ = "1.0.0"
@@ -0,0 +1,6 @@
1
+ """Entry point for running as a module: python -m cf_tool"""
2
+
3
+ from cf_tool.cli import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,211 @@
1
+ """Building a code file before it runs, with a cache: a source that hasn't
2
+ changed is not compiled again.
3
+
4
+ Builds live in $XDG_CACHE_HOME/cf/build/<key>/, never next to the code. The
5
+ key covers the source, the build and run commands, the compiler's version
6
+ text and the files in the build's include folders (-I), so a change to any of
7
+ them builds afresh; a C/C++ source with a local `#include "..."` is rebuilt
8
+ every time (the header may have changed). Builds unused for a week are
9
+ removed.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import contextlib
15
+ import hashlib
16
+ import os
17
+ import re
18
+ import shutil
19
+ import sys
20
+ import time
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+
24
+ from cf_tool import paths, process
25
+ from cf_tool.errors import CFError
26
+ from cf_tool.languages import Setup
27
+
28
+ BUILD_TIMEOUT = 300.0 # seconds a compiler may take
29
+ MAX_AGE = 7 * 24 * 3600 # seconds an unused build is kept
30
+ _MARK = ".built" # in a finished build's folder
31
+ _LOCAL_INCLUDE_RE = re.compile(rb'^\s*#\s*include\s*"', re.MULTILINE)
32
+ _pruned = False
33
+
34
+
35
+ class BuildFailed(CFError):
36
+ """The compiler refused the code; its message is in output."""
37
+
38
+ def __init__(self, message: str, output: str) -> None:
39
+ super().__init__(message)
40
+ self.output = output
41
+
42
+
43
+ @dataclass(frozen=True)
44
+ class Built:
45
+ cached: bool # nothing was compiled
46
+ seconds: float
47
+ messages: str # what the compiler printed (warnings)
48
+
49
+
50
+ class Program:
51
+ """A code file and how its language builds and runs it."""
52
+
53
+ def __init__(self, source: Path | str, setup: Setup) -> None:
54
+ self.source = Path(os.path.abspath(source))
55
+ self.setup = setup
56
+ self._folder: Path | None = None
57
+
58
+ @property
59
+ def name(self) -> str:
60
+ return self.source.name
61
+
62
+ @property
63
+ def label(self) -> str:
64
+ """How messages name it: its file, or a command as it was given."""
65
+ return self.setup.tool if self.setup.key == "command" else self.name
66
+
67
+ def _key(self, code: bytes, headers: str) -> str:
68
+ digest = hashlib.sha256()
69
+ for part in (
70
+ self.setup.fingerprint,
71
+ "\0".join(self.setup.build or ()),
72
+ "\0".join(self.setup.run),
73
+ sys.platform,
74
+ str(self.source),
75
+ headers,
76
+ ):
77
+ digest.update(part.encode() + b"\1")
78
+ digest.update(code)
79
+ return digest.hexdigest()[:32]
80
+
81
+ def _values(self, folder: Path | None) -> dict[str, str]:
82
+ exe = self.source.stem + (".exe" if sys.platform == "win32" else "")
83
+ values = {"src": str(self.source), "name": self.source.stem, "class": self.source.stem}
84
+ if folder is not None:
85
+ copy = folder / (self.setup.copy_as or self.source.name)
86
+ values.update(dir=str(folder), exe=str(folder / exe), copy=str(copy))
87
+ return values
88
+
89
+ def build(self) -> Built:
90
+ """Build the program, unless an identical build is cached; returns how
91
+ it went. Raises BuildFailed with the compiler's output when it fails."""
92
+ if self.setup.build is None:
93
+ return Built(cached=True, seconds=0.0, messages="")
94
+ try:
95
+ code = self.source.read_bytes()
96
+ except OSError as e:
97
+ raise CFError(f"Cannot read {self.source}: {e.strerror or e}") from e
98
+ headers = _headers_stamp(self.setup.build, self.source.parent)
99
+ always = headers is None or bool(_LOCAL_INCLUDE_RE.search(code))
100
+ folder = paths.CACHE_DIR / "build" / self._key(code, headers or "")
101
+ self._folder = folder
102
+ if (folder / _MARK).is_file() and not always:
103
+ with contextlib.suppress(OSError):
104
+ os.utime(folder / _MARK) # NOTE: still in use, so not pruned
105
+ return Built(cached=True, seconds=0.0, messages="")
106
+ _prune()
107
+ work = folder.with_name(f"{folder.name}.{os.getpid()}.tmp")
108
+ shutil.rmtree(work, ignore_errors=True)
109
+ work.mkdir(parents=True)
110
+ values = self._values(work)
111
+ if any("{copy}" in word for word in self.setup.build):
112
+ shutil.copyfile(self.source, values["copy"])
113
+ argv = fill(self.setup.build, values)
114
+ started = time.perf_counter()
115
+ result = process.run(argv, cwd=self.source.parent, timeout=BUILD_TIMEOUT)
116
+ seconds = time.perf_counter() - started
117
+ messages = (result.stdout + result.stderr).decode(errors="replace").strip()
118
+ if not result.ok:
119
+ shutil.rmtree(work, ignore_errors=True)
120
+ if result.status == process.TIMEOUT:
121
+ raise BuildFailed(f"Building {self.name} took over {BUILD_TIMEOUT:g}s", messages)
122
+ raise BuildFailed(f"{self.name} doesn't compile ({result.reason()})", messages)
123
+ (work / _MARK).write_text("", encoding="utf-8")
124
+ if (folder / _MARK).is_file() and not always:
125
+ shutil.rmtree(work, ignore_errors=True) # NOTE: another cf built the same meanwhile
126
+ else:
127
+ shutil.rmtree(folder, ignore_errors=True) # NOTE: a half-built or outdated one
128
+ try:
129
+ os.replace(work, folder)
130
+ except OSError: # NOTE: another cf put its build there just now
131
+ shutil.rmtree(work, ignore_errors=True)
132
+ return Built(cached=False, seconds=seconds, messages=messages)
133
+
134
+ def argv(self) -> list[str]:
135
+ """The command that runs the program (after build())."""
136
+ if self.setup.build is not None and self._folder is None:
137
+ raise CFError(f"{self.name} isn't built yet")
138
+ return fill(self.setup.run, self._values(self._folder))
139
+
140
+ def run(self, **options) -> process.Result:
141
+ """Run the built program in its own folder (see process.run for options)."""
142
+ return process.run(
143
+ self.argv(), cwd=self.source.parent, big_stack=self.setup.big_stack, **options
144
+ )
145
+
146
+
147
+ _INCLUDE_FLAGS = ("-isystem", "-iquote", "-idirafter", "-I")
148
+ MAX_HEADERS = 5000 # files under -I folders looked at; more: built every time
149
+
150
+
151
+ def _headers_stamp(build: tuple[str, ...], base: Path) -> str | None:
152
+ """What the build's include folders (-I and the like, other than cf-tool's
153
+ own) hold, as one text that changes whenever a file there does; None when
154
+ they hold too many files to look at."""
155
+ from cf_tool.languages import shim_folder
156
+
157
+ folders = []
158
+ for i, word in enumerate(build):
159
+ for flag in _INCLUDE_FLAGS:
160
+ if word == flag and i + 1 < len(build):
161
+ folders.append(build[i + 1])
162
+ elif word.startswith(flag) and len(word) > len(flag):
163
+ folders.append(word[len(flag) :])
164
+ else:
165
+ continue
166
+ break
167
+ own = shim_folder()
168
+ stamp = []
169
+ for name in folders:
170
+ folder = (base / Path(name).expanduser()).resolve()
171
+ if "{" in name or folder == own.resolve() or not folder.is_dir():
172
+ continue
173
+ for root, _, files in os.walk(folder):
174
+ for file in files:
175
+ try:
176
+ info = os.stat(os.path.join(root, file))
177
+ except OSError:
178
+ continue
179
+ stamp.append(f"{root}/{file}:{info.st_mtime_ns}:{info.st_size}")
180
+ if len(stamp) > MAX_HEADERS:
181
+ return None
182
+ return "\n".join(sorted(stamp))
183
+
184
+
185
+ def fill(words: tuple[str, ...] | list[str], values: dict[str, str]) -> list[str]:
186
+ """The words of a command with its placeholders filled in: {src} {exe}
187
+ {dir} {name} {class} {copy} (the code, copied into {dir} before the
188
+ build); one left unknown stays as written."""
189
+ filled = []
190
+ for word in words:
191
+ for key, value in values.items():
192
+ word = word.replace("{" + key + "}", value)
193
+ filled.append(word)
194
+ return filled
195
+
196
+
197
+ def _prune() -> None:
198
+ """Remove builds unused for MAX_AGE (once per run)."""
199
+ global _pruned
200
+ if _pruned:
201
+ return
202
+ _pruned = True
203
+ now = time.time()
204
+ for entry in (paths.CACHE_DIR / "build").glob("*"):
205
+ try:
206
+ stamp = entry / _MARK
207
+ age = now - (stamp.stat().st_mtime if stamp.exists() else entry.stat().st_mtime)
208
+ except OSError:
209
+ continue
210
+ if age > MAX_AGE:
211
+ shutil.rmtree(entry, ignore_errors=True)
@@ -0,0 +1,117 @@
1
+ """The cf command. Each command's body stays thin: work out the problem and
2
+ the file meant, then call one function; errors end in a red line, not a
3
+ traceback (CF_DEBUG=1 shows the traceback too)."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import contextlib
8
+ import signal
9
+
10
+ import click
11
+
12
+ from cf_tool import __version__, settings as settings_module, ui
13
+ from cf_tool.cli import account, problems, setup, submitting, testing
14
+ from cf_tool.cli.completion import completion
15
+
16
+ # cf-tool 0.3's command names, still understood
17
+ ALIASES = {"parse": "get", "gen": "new", "watch": "status", "list": "problems"}
18
+
19
+ # the commands in the order the help lists them
20
+ ORDER = [
21
+ "get",
22
+ "test",
23
+ "submit",
24
+ "status",
25
+ "race",
26
+ "open",
27
+ "problems",
28
+ "contests",
29
+ "pick",
30
+ "stress",
31
+ "listen",
32
+ "new",
33
+ "pull",
34
+ "clone",
35
+ "login",
36
+ "logout",
37
+ "langs",
38
+ "config",
39
+ "doctor",
40
+ "upgrade",
41
+ "completion",
42
+ ]
43
+
44
+
45
+ class Group(click.Group):
46
+ """Commands listed in a useful order, and the old names as aliases."""
47
+
48
+ def get_command(self, ctx, cmd_name):
49
+ return super().get_command(ctx, ALIASES.get(cmd_name, cmd_name))
50
+
51
+ def list_commands(self, ctx):
52
+ names = super().list_commands(ctx)
53
+ return sorted(names, key=lambda name: ORDER.index(name) if name in ORDER else len(ORDER))
54
+
55
+
56
+ @click.group(cls=Group, context_settings={"help_option_names": ["-h", "--help"]})
57
+ # NOTE: CP Editor reads the version as the digits after a v
58
+ @click.version_option(__version__, prog_name="cf", message="cf-tool v%(version)s")
59
+ @click.pass_context
60
+ def main(ctx: click.Context) -> None:
61
+ """cf-tool: Codeforces from your terminal.
62
+
63
+ \b
64
+ cf get 2050 folders, samples and starter code for contest 2050
65
+ cd 2050/a
66
+ cf test build and run your code on the samples
67
+ cf submit submit it, and watch the verdict
68
+ """
69
+ if ctx.invoked_subcommand == "completion":
70
+ return # NOTE: its output is a script the shell evaluates; notes would break it
71
+ # NOTE: a stopped cf (kill, a tool's timeout) unwinds like Ctrl-C, so the
72
+ # \ browser or program it started is closed, not left running
73
+ with contextlib.suppress(ValueError): # NOTE: only possible in the main thread
74
+ signal.signal(signal.SIGTERM, _interrupt)
75
+ try:
76
+ notes = settings_module.migrate()
77
+ except OSError as e:
78
+ notes = [f"Could not move your old settings ({e})"]
79
+ for note in notes:
80
+ ui.yellow(note)
81
+
82
+
83
+ def _interrupt(signum, frame) -> None:
84
+ raise KeyboardInterrupt
85
+
86
+
87
+ # one line each in cf --help
88
+ SHORT_HELP = {
89
+ "get": "Set up problems: folders, samples, starter code",
90
+ "test": "Run your code on the problem's tests",
91
+ "submit": "Submit your code and watch the verdict",
92
+ "status": "Your submissions, refreshed until judged",
93
+ "race": "Count down to a contest, then get its problems",
94
+ "open": "Open a problem, the standings, or a submission",
95
+ "problems": "A contest's problems and how many solved them",
96
+ "contests": "Upcoming contests",
97
+ "pick": "A random unsolved problem to practice on",
98
+ "stress": "Random tests until your code and a brute force differ",
99
+ "listen": "Receive problems from Competitive Companion",
100
+ "new": "A code file from your starter code",
101
+ "pull": "Download the code of your submissions",
102
+ "clone": "Download the code of all of a user's submissions",
103
+ "login": "Log in to Codeforces",
104
+ "logout": "Forget your login",
105
+ "langs": "How each language is built, run and submitted",
106
+ "config": "Open the settings in your editor",
107
+ "doctor": "Check the setup and say how to fix it",
108
+ "upgrade": "Check GitHub for a newer cf-tool",
109
+ "completion": "The Tab-completion script for your shell",
110
+ }
111
+
112
+ for module in (problems, testing, submitting, account, setup):
113
+ for command in module.COMMANDS:
114
+ main.add_command(command)
115
+ main.add_command(completion)
116
+ for name, text in SHORT_HELP.items():
117
+ main.commands[name].short_help = text
@@ -0,0 +1,32 @@
1
+ """Commands for your Codeforces account: login and logout."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import click
6
+
7
+ from cf_tool import ui
8
+ from cf_tool.cli.common import ask_login, cf_command, client
9
+
10
+
11
+ @click.command()
12
+ @cf_command
13
+ def login() -> None:
14
+ """Log in to Codeforces (the password is saved encrypted, so an expired
15
+ login renews itself)."""
16
+ c = client()
17
+ if c.handle:
18
+ ui.plain(f"Logged in as {c.handle} now; logging in again.")
19
+ ask_login(c)
20
+
21
+
22
+ @click.command()
23
+ @cf_command
24
+ def logout() -> None:
25
+ """Forget your login: the saved password and session."""
26
+ c = client()
27
+ who = c.handle
28
+ c.logout()
29
+ ui.green(f"Logged out{f' {who}' if who else ''}")
30
+
31
+
32
+ COMMANDS = [login, logout]