cf-tool-cli 1.0.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.
cf_tool/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """cf-tool: Codeforces from your terminal."""
2
+
3
+ __version__ = "1.0.0"
cf_tool/__main__.py ADDED
@@ -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()
cf_tool/build.py ADDED
@@ -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
cf_tool/cli/account.py ADDED
@@ -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]
cf_tool/cli/common.py ADDED
@@ -0,0 +1,262 @@
1
+ """What the commands share: error handling, the settings and the client
2
+ (loaded once per run), finding the problem a command means, logging in on
3
+ the spot, the language for starter code, and building a program."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import functools
8
+ import getpass
9
+ import os
10
+ import sys
11
+ import traceback
12
+ import webbrowser
13
+ from pathlib import Path
14
+ from typing import TYPE_CHECKING
15
+
16
+ from cf_tool import languages, ui, workspace
17
+ from cf_tool.build import BuildFailed, Program
18
+ from cf_tool.errors import CFError
19
+ from cf_tool.settings import Settings
20
+ from cf_tool.workspace import ProblemInfo, Target
21
+
22
+ if TYPE_CHECKING:
23
+ from cf_tool.codeforces.client import Client
24
+
25
+
26
+ def fail(message: str) -> None:
27
+ if os.environ.get("CF_DEBUG"):
28
+ traceback.print_exc()
29
+ ui.red(message)
30
+ sys.exit(1)
31
+
32
+
33
+ def cf_command(f):
34
+ """A command whose errors end in a red line, not a traceback."""
35
+
36
+ @functools.wraps(f)
37
+ def wrapper(*args, **kwargs):
38
+ try:
39
+ return f(*args, **kwargs)
40
+ except CFError as e:
41
+ fail(str(e))
42
+ except OSError as e: # NOTE: unreadable or unwritable files and the like
43
+ fail(str(e))
44
+ except ui.Canceled:
45
+ ui.dim("Canceled.")
46
+ sys.exit(1)
47
+ except KeyboardInterrupt:
48
+ print("\nInterrupted.")
49
+ sys.exit(1)
50
+
51
+ return wrapper
52
+
53
+
54
+ # ┌──────────────────────────────────────────────────────────┐
55
+ # │ Settings and the client │
56
+ # └──────────────────────────────────────────────────────────┘
57
+
58
+ _settings: Settings | None = None
59
+ _client: "Client | None" = None
60
+
61
+
62
+ def settings() -> Settings:
63
+ """The settings, read once per run; their warnings are shown then."""
64
+ global _settings
65
+ if _settings is None:
66
+ _settings = Settings.load()
67
+ for warning in _settings.warnings:
68
+ ui.yellow(warning)
69
+ return _settings
70
+
71
+
72
+ def client() -> "Client":
73
+ global _client
74
+ if _client is None:
75
+ from cf_tool.codeforces.client import Client
76
+
77
+ _client = Client(settings())
78
+ return _client
79
+
80
+
81
+ def reset() -> None:
82
+ """Forget the settings and client read so far (tests run many commands)."""
83
+ global _settings, _client
84
+ _settings = _client = None
85
+
86
+
87
+ def open_url(url: str) -> None:
88
+ ui.line(("Opening ", "cyan"), (url, ""))
89
+ webbrowser.open(url)
90
+
91
+
92
+ def short(path: Path | str) -> str:
93
+ """A path for messages: relative to the current folder when inside it,
94
+ else with the home folder as ~."""
95
+ path = Path(path)
96
+ try:
97
+ relative = path.resolve().relative_to(Path.cwd().resolve())
98
+ return str(relative) if str(relative) != "." else "."
99
+ except ValueError:
100
+ pass
101
+ text, home = str(path), str(Path.home())
102
+ return "~" + text[len(home) :] if text == home or text.startswith(home + os.sep) else text
103
+
104
+
105
+ # ┌──────────────────────────────────────────────────────────┐
106
+ # │ The problem meant │
107
+ # └──────────────────────────────────────────────────────────┘
108
+
109
+
110
+ def target_of(specs: tuple[str, ...] | list[str], cwd: Path | None = None) -> Target:
111
+ """The target the arguments name, with the folder filling in the rest."""
112
+ cwd = cwd or Path.cwd()
113
+ return workspace.parse_target(list(specs), workspace.here(cwd))
114
+
115
+
116
+ def problem_folder_of(target: Target, cwd: Path | None = None) -> Path | None:
117
+ """The folder of target's problem, wherever it is from here."""
118
+ return workspace.locate(target, cwd or Path.cwd(), settings().root_folder())
119
+
120
+
121
+ def code_file_among(args: tuple[str, ...]) -> tuple[str | None, tuple[str, ...]]:
122
+ """(the code file among the arguments, the other arguments): an existing
123
+ file in a known language is the file, not a problem."""
124
+ known = languages.code_extensions(settings())
125
+ files = [a for a in args if Path(a).suffix.lower() in known and Path(a).is_file()]
126
+ if len(files) > 1:
127
+ raise CFError(f"One code file at a time, not {' and '.join(files)}")
128
+ return (files[0] if files else None), tuple(a for a in args if a not in files)
129
+
130
+
131
+ # ┌──────────────────────────────────────────────────────────┐
132
+ # │ Languages and programs │
133
+ # └──────────────────────────────────────────────────────────┘
134
+
135
+
136
+ def starter_language(asked: str | None = None) -> str:
137
+ """The language for starter code: the one asked for (-l), else the
138
+ setting; the first time, the user picks one and it is saved."""
139
+ current = settings()
140
+ if asked:
141
+ key = languages.language_key(asked, current) or asked.lower().lstrip(".")
142
+ if key not in languages.LANGUAGES and key not in current.languages:
143
+ raise CFError(f"cf-tool doesn't know the language {asked!r} (cf langs lists them)")
144
+ return key
145
+ if current.language:
146
+ return current.language
147
+ if not ui.interactive(): # NOTE: nobody to ask: C++, this once
148
+ ui.yellow("No language picked yet: writing C++ (set language in cf config, or give -l)")
149
+ return "cpp"
150
+ keys = [
151
+ *(
152
+ key for key in languages.LANGUAGES if key != "c"
153
+ ), # NOTE: C++ covers it; .c files still work
154
+ *(key for key in current.languages if key not in languages.LANGUAGES),
155
+ ]
156
+ key = ui.select(
157
+ "Which language do you write in?",
158
+ [(languages.display_name(key), key) for key in keys],
159
+ default="cpp",
160
+ )
161
+ current.update("language", key)
162
+ ui.green(
163
+ f"Starter code in {languages.display_name(key)} from now on "
164
+ f"(the language in {short(current.file)}; -l picks another once)"
165
+ )
166
+ return key
167
+
168
+
169
+ def program(path: Path, key: str | None = None) -> Program:
170
+ """The code file and how its language builds and runs it here."""
171
+ key = key or languages.language_key(path, settings())
172
+ if key is None:
173
+ raise CFError(f"cf-tool doesn't know what language {path.name} is in")
174
+ return Program(path, languages.setup(key, settings(), source=path))
175
+
176
+
177
+ def build(target: Program) -> None:
178
+ """Build a program (unless its build is cached), saying so; a compiler
179
+ error is shown in full, then raised as CFError."""
180
+ if target.setup.build is None:
181
+ return
182
+ try:
183
+ with ui.status(f"Building {target.name} with {target.setup.tool}..."):
184
+ built = target.build()
185
+ except BuildFailed as e:
186
+ if e.output:
187
+ ui.plain(e.output)
188
+ raise CFError(str(e)) from None
189
+ if not built.cached:
190
+ ui.line((f"Built {target.name} with {target.setup.tool} in {built.seconds:.1f}s", "dim"))
191
+ if built.messages:
192
+ ui.plain(built.messages)
193
+
194
+
195
+ def write_starter(folder: Path, target: Target, info: ProblemInfo | None, key: str) -> Path | None:
196
+ """Write the starter code into a problem's folder as <problem>.<ext>,
197
+ unless the folder has code in that language already; returns the file
198
+ written, if any."""
199
+ language = languages.LANGUAGES.get(key)
200
+ extensions = language.extensions if language else (key,)
201
+ has_code = any(
202
+ entry.suffix.lower().lstrip(".") in extensions and not workspace.is_helper(entry.name)
203
+ for entry in (folder.iterdir() if folder.is_dir() else [])
204
+ )
205
+ path = folder / f"{target.problem.lower()}.{key}"
206
+ if has_code or path.exists():
207
+ return None
208
+ text, _ = languages.starter(key, settings())
209
+ path.parent.mkdir(parents=True, exist_ok=True)
210
+ path.write_text(
211
+ languages.render(text, starter_values(target, info)), encoding="utf-8", newline=""
212
+ )
213
+ return path
214
+
215
+
216
+ def starter_values(target: Target | None, info: ProblemInfo | None) -> dict[str, str]:
217
+ """What starter code's placeholders are filled with."""
218
+ from cf_tool.codeforces.session import Session
219
+
220
+ return {
221
+ "handle": _client.handle if _client is not None else Session.load().handle,
222
+ "problem": target.label if target and target.problem else "",
223
+ "name": info.name if info else "",
224
+ "url": info.url if info else "",
225
+ }
226
+
227
+
228
+ # ┌──────────────────────────────────────────────────────────┐
229
+ # │ Logging in │
230
+ # └──────────────────────────────────────────────────────────┘
231
+
232
+
233
+ def ask_login(c: "Client") -> None:
234
+ """Ask for the handle and password, and log in."""
235
+ current = c.session.handle_or_email
236
+ who = ui.text(
237
+ "Handle or email:",
238
+ default=current,
239
+ validate=lambda s: bool(s.strip()) or "Your Codeforces handle or email",
240
+ allow_empty=False,
241
+ )
242
+ if sys.stdin.isatty():
243
+ ui.dim("The password stays hidden as you type it.")
244
+ password = getpass.getpass("Password: ")
245
+ else:
246
+ # NOTE: piped in (printf ... | cf login): nothing to hide, and getpass
247
+ # \ would only warn that it cannot hide it
248
+ ui.cyan("Password:")
249
+ password = ui.scanline()
250
+ if not password:
251
+ raise CFError("No password: not logged in")
252
+ c.login(who, password)
253
+
254
+
255
+ def ensure_login(c: "Client") -> None:
256
+ """Log in first when no login is saved (a terminal asks for one)."""
257
+ if c.can_log_in:
258
+ return
259
+ if not ui.interactive():
260
+ raise CFError("Not logged in: run cf login")
261
+ ui.yellow("You're not logged in to Codeforces yet.")
262
+ ask_login(c)