ludex-cli 0.60.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.
- ludex_cli/__init__.py +0 -0
- ludex_cli/__main__.py +3 -0
- ludex_cli/cli.py +1043 -0
- ludex_cli-0.60.0.dist-info/METADATA +26 -0
- ludex_cli-0.60.0.dist-info/RECORD +9 -0
- ludex_cli-0.60.0.dist-info/WHEEL +5 -0
- ludex_cli-0.60.0.dist-info/entry_points.txt +2 -0
- ludex_cli-0.60.0.dist-info/licenses/LICENSE +674 -0
- ludex_cli-0.60.0.dist-info/top_level.txt +1 -0
ludex_cli/cli.py
ADDED
|
@@ -0,0 +1,1043 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import csv
|
|
5
|
+
import io
|
|
6
|
+
import getpass
|
|
7
|
+
import glob
|
|
8
|
+
import json
|
|
9
|
+
import os
|
|
10
|
+
import shlex
|
|
11
|
+
import sys
|
|
12
|
+
from dataclasses import asdict
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Any
|
|
15
|
+
|
|
16
|
+
from ludex import __version__
|
|
17
|
+
from ludex.accounts import add_account, get_account, list_accounts, remove_account, update_account
|
|
18
|
+
from ludex.provider_settings import describe, field_for, get_values, set_value
|
|
19
|
+
from ludex.errors import LudexError
|
|
20
|
+
from ludex.game_settings import default_download_dir, get_download_dir, get_prefix_root, get_settings, pick_copy, set_download_dir, set_prefix_root, update_settings
|
|
21
|
+
from ludex.plugin_manager import CHANNELS, add_plugin, list_plugins, remove_plugin, set_plugin_enabled, update_core, update_plugins
|
|
22
|
+
from ludex.runners import find_runners
|
|
23
|
+
from ludex.find import find_games, owned_keys
|
|
24
|
+
from ludex.installed import installed_keys
|
|
25
|
+
from ludex.executables import find_executables
|
|
26
|
+
from ludex.acquire import acquire_game, download_game, format_acquired, job_reporter
|
|
27
|
+
from ludex.jobs import Job, eta_seconds, list_jobs, progress, progress_line, stop_job
|
|
28
|
+
from ludex.playtime import Played, describe_played, epoch, play_stats
|
|
29
|
+
from ludex.launch import install_game, launch_game, prepare_install, prepare_launch
|
|
30
|
+
from ludex.library import resolve_game, delete_account_records, export_games, dismiss_review, get_game, list_games, list_review, merge_games, run_import
|
|
31
|
+
from ludex.loader import load_providers
|
|
32
|
+
from ludex.refresh import get_auto_refresh, set_auto_refresh
|
|
33
|
+
from ludex.metadata import cached_match, choose_match, clear_match, default_query, game_metadata, match_candidates, get_auto_details, get_auto_match, set_auto_details, set_auto_match
|
|
34
|
+
from ludex.paths import state_paths
|
|
35
|
+
from ludex.plugins import CommandContext, CommandResult, Provider
|
|
36
|
+
from ludex.storage import connect, writer_lock
|
|
37
|
+
from ludex.switches import SWITCHES, get_switch, set_switch
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _parser() -> argparse.ArgumentParser:
|
|
41
|
+
parser = argparse.ArgumentParser(prog="ludex", description="Headless library of the games you own across stores.")
|
|
42
|
+
parser.add_argument("--version", action="version", version=f"ludex {__version__}")
|
|
43
|
+
parser.add_argument("--json", action="store_true", help="machine-readable output (before the subcommand)")
|
|
44
|
+
commands = parser.add_subparsers(dest="command", metavar="command")
|
|
45
|
+
|
|
46
|
+
commands.add_parser("providers", help="list available providers and their capabilities")
|
|
47
|
+
|
|
48
|
+
account = commands.add_parser("account", help="manage store accounts")
|
|
49
|
+
account_commands = account.add_subparsers(dest="account_command", metavar="action")
|
|
50
|
+
add = account_commands.add_parser("add", help="add an account")
|
|
51
|
+
add.add_argument("source")
|
|
52
|
+
add.add_argument("name")
|
|
53
|
+
add.add_argument("--set", dest="fields", action="append", default=[], metavar="KEY=VALUE", help="non-secret field value")
|
|
54
|
+
change = account_commands.add_parser("set", help="change an account's settings (its games are kept; import again afterwards)")
|
|
55
|
+
change.add_argument("name")
|
|
56
|
+
change.add_argument("--set", dest="fields", action="append", default=[], metavar="KEY=VALUE", help="non-secret field value")
|
|
57
|
+
change.add_argument("--secret", dest="secrets", action="append", default=[], metavar="KEY", help="read this secret field from the prompt or stdin")
|
|
58
|
+
change.add_argument("--unset", dest="unset", action="append", default=[], metavar="KEY", help="remove an optional field")
|
|
59
|
+
account_commands.add_parser("ls", help="list accounts")
|
|
60
|
+
remove = account_commands.add_parser("rm", help="remove an account")
|
|
61
|
+
remove.add_argument("name")
|
|
62
|
+
|
|
63
|
+
plugin = commands.add_parser("plugin", help="manage plugins installed by ludex (one folder each in the state directory)")
|
|
64
|
+
plugin_commands = plugin.add_subparsers(dest="plugin_command", metavar="action")
|
|
65
|
+
plugin_add = plugin_commands.add_parser("add", help="install a plugin (a package name, URL or path; it runs with your permissions)")
|
|
66
|
+
plugin_add.add_argument("spec")
|
|
67
|
+
plugin_commands.add_parser("ls", help="list installed plugins")
|
|
68
|
+
plugin_rm = plugin_commands.add_parser("rm", help="remove a plugin (its accounts and games stay until 'account rm')")
|
|
69
|
+
plugin_rm.add_argument("name")
|
|
70
|
+
for action, text in (("enable", "load a disabled plugin again"), ("disable", "keep a plugin installed but do not load it")):
|
|
71
|
+
plugin_commands.add_parser(action, help=text).add_argument("name")
|
|
72
|
+
plugin_up = plugin_commands.add_parser("update", help="reinstall plugins from the spec they were added with")
|
|
73
|
+
plugin_up.add_argument("name", nargs="?", help="one plugin (default: all)")
|
|
74
|
+
|
|
75
|
+
update = commands.add_parser("update", help="update ludex itself from its release channel")
|
|
76
|
+
update.add_argument("--channel", choices=CHANNELS, help="default: the channel this install came from")
|
|
77
|
+
update.add_argument("--dry-run", action="store_true", help="show the command without running it")
|
|
78
|
+
|
|
79
|
+
setup = commands.add_parser("setup", help="guided: add an account for a source and import it")
|
|
80
|
+
setup.add_argument("source", nargs="?")
|
|
81
|
+
setup.add_argument("--name", help="account name (default: the source name)")
|
|
82
|
+
|
|
83
|
+
imp = commands.add_parser("import", help="import owned games from an account")
|
|
84
|
+
imp.add_argument("account", nargs="?")
|
|
85
|
+
imp.add_argument("--all", action="store_true", help="import every account")
|
|
86
|
+
|
|
87
|
+
listing = commands.add_parser("ls", help="list or search games")
|
|
88
|
+
listing.add_argument("query", nargs="?")
|
|
89
|
+
listing.add_argument("--store")
|
|
90
|
+
listing.add_argument("--account")
|
|
91
|
+
listing.add_argument("--removed", action="store_true", help="include removed games")
|
|
92
|
+
listing.add_argument("--installed", action="store_true", help="only games installed on this machine")
|
|
93
|
+
listing.add_argument("--sort", choices=("title", "recent", "played"), default="title", help="title (default), most recently played first, or most played first; the last two show play time")
|
|
94
|
+
listing.add_argument("--limit", type=int, default=50)
|
|
95
|
+
listing.add_argument("--offset", type=int, default=0)
|
|
96
|
+
|
|
97
|
+
show = commands.add_parser("show", help="show one game")
|
|
98
|
+
show.add_argument("game", help="game id or title")
|
|
99
|
+
|
|
100
|
+
find = commands.add_parser("find", help="search the stores' catalogs (uses the network)")
|
|
101
|
+
find.add_argument("query")
|
|
102
|
+
|
|
103
|
+
launch = commands.add_parser("launch", help="start a game through its store's client")
|
|
104
|
+
launch.add_argument("game", nargs="?", help="game id or title")
|
|
105
|
+
launch.add_argument("--store", help="store to launch from when several can")
|
|
106
|
+
launch.add_argument("--dry-run", action="store_true", help="show how the game would be started and do not start it")
|
|
107
|
+
launch.add_argument("--status", action="store_true", help="list the games ludex started itself (of the game, when one is named) and whether they still run")
|
|
108
|
+
launch.add_argument("--stop", action="store_true", help="stop the game ludex started")
|
|
109
|
+
|
|
110
|
+
install = commands.add_parser("install", help="ask the owning store's client to install a game you own")
|
|
111
|
+
install.add_argument("game", nargs="?", help="game id or title")
|
|
112
|
+
install.add_argument("--store", help="store to install from when several can")
|
|
113
|
+
install.add_argument("--dry-run", action="store_true", help="show what would be run and do not start it")
|
|
114
|
+
install.add_argument("--status", action="store_true", help="list installs ludex started (of the game, when one is named) and how far they are")
|
|
115
|
+
install.add_argument("--stop", action="store_true", help="stop the game's running install")
|
|
116
|
+
|
|
117
|
+
meta = commands.add_parser("metadata", help="show a game's description, genres and developer (asks the store's plugin once, then keeps the answer)")
|
|
118
|
+
meta.add_argument("game", help="game id or title")
|
|
119
|
+
meta.add_argument("--refresh", action="store_true", help="ask the plugin again instead of using the kept answer")
|
|
120
|
+
meta.add_argument("--match", action="store_true", help="for a game no store describes, look it up by name in a game database plugin (also on with 'ludex config auto_match yes')")
|
|
121
|
+
|
|
122
|
+
match = commands.add_parser("match", help="choose which database entry a game's title and details come from (lists the candidates; --use picks one)")
|
|
123
|
+
match.add_argument("game", help="game id or title")
|
|
124
|
+
match.add_argument("query", nargs="?", help="what to search for (default: the game's folder name without tags and version)")
|
|
125
|
+
match.add_argument("--use", metavar="PLUGIN:ID", help="keep this candidate's title and details for the game")
|
|
126
|
+
match.add_argument("--clear", action="store_true", help="forget the match and go back to the folder name")
|
|
127
|
+
|
|
128
|
+
acquire = commands.add_parser("acquire", help="ask a provider to fetch a game into a directory")
|
|
129
|
+
acquire.add_argument("store")
|
|
130
|
+
acquire.add_argument("store_id")
|
|
131
|
+
acquire.add_argument("--to", help="destination directory (default: the download_dir setting)")
|
|
132
|
+
acquire.add_argument("--title", default="", help="game title, if the provider wants one")
|
|
133
|
+
|
|
134
|
+
download = commands.add_parser("download", help="like acquire, in the background: a job you can check and stop")
|
|
135
|
+
download.add_argument("store", nargs="?")
|
|
136
|
+
download.add_argument("store_id", nargs="?")
|
|
137
|
+
download.add_argument("--to", help="destination directory (default: the download_dir setting)")
|
|
138
|
+
download.add_argument("--title", default="", help="game title, if the provider wants one")
|
|
139
|
+
download.add_argument("--status", action="store_true", help="show downloads started by ludex")
|
|
140
|
+
download.add_argument("--stop", action="store_true", help="stop the running download of STORE STORE_ID")
|
|
141
|
+
|
|
142
|
+
commands.add_parser("runners", help="list detected Proton builds")
|
|
143
|
+
|
|
144
|
+
config = commands.add_parser(
|
|
145
|
+
"config",
|
|
146
|
+
help="show or change global settings: prefix_dir (folder for default Wine prefixes), download_dir (where downloads go), "
|
|
147
|
+
"steam_shortcuts and heroic_sideload (yes/no; no removes those games from the library), "
|
|
148
|
+
"and <plugin>.<setting> for plugins that declare settings",
|
|
149
|
+
)
|
|
150
|
+
config.add_argument("key", nargs="?", help="setting to show or change")
|
|
151
|
+
config.add_argument("value", nargs="?", help="new value: an absolute folder, yes/no, or text")
|
|
152
|
+
config.add_argument("--reset", action="store_true", help="go back to the built-in value (removes a plugin setting)")
|
|
153
|
+
config.add_argument("--secret", action="store_true", help="read a secret plugin setting from the prompt or stdin")
|
|
154
|
+
|
|
155
|
+
game = commands.add_parser("game", help="per-game launch settings (runner, prefix, executable, environment)")
|
|
156
|
+
game_commands = game.add_subparsers(dest="game_command", metavar="action")
|
|
157
|
+
game_show = game_commands.add_parser("show", help="show a game's launch settings")
|
|
158
|
+
game_show.add_argument("game", help="game id or title")
|
|
159
|
+
game_show.add_argument("--store", help="store whose copy to use when several exist")
|
|
160
|
+
game_exes = game_commands.add_parser("exes", help="list the files in a game's folder that could be its executable, best guess first")
|
|
161
|
+
game_exes.add_argument("game", help="game id or title")
|
|
162
|
+
game_exes.add_argument("--store", help="store whose copy to use when several exist")
|
|
163
|
+
game_set = game_commands.add_parser("set", help="change a game's launch settings")
|
|
164
|
+
game_set.add_argument("game", help="game id or title")
|
|
165
|
+
game_set.add_argument("--store", help="store whose copy to use when several exist")
|
|
166
|
+
game_set.add_argument("--runner", help="runner name from 'ludex runners', or the path of a Proton folder")
|
|
167
|
+
game_set.add_argument("--prefix", help="absolute path of the Wine prefix folder")
|
|
168
|
+
game_set.add_argument("--exe", help="executable, relative to the game folder or absolute")
|
|
169
|
+
game_set.add_argument("--args", help="arguments passed to the game, one quoted string; write --args='-w' when it starts with a dash")
|
|
170
|
+
game_set.add_argument("--env", action="append", default=[], metavar="NAME=VALUE", help="environment variable (repeatable)")
|
|
171
|
+
game_set.add_argument("--unset-env", action="append", default=[], metavar="NAME", help="remove an environment variable (repeatable)")
|
|
172
|
+
game_set.add_argument("--clear", action="store_true", help="reset all settings first")
|
|
173
|
+
|
|
174
|
+
commands.add_parser("tui", help="browse, search and launch games in the terminal")
|
|
175
|
+
|
|
176
|
+
review = commands.add_parser("review", help="list title matches that need a decision")
|
|
177
|
+
review.add_argument("--dismiss", type=int, metavar="ID", help="keep this item's game separate and drop it from the list")
|
|
178
|
+
|
|
179
|
+
export = commands.add_parser("export", help="write the library to stdout as JSON or CSV")
|
|
180
|
+
export.add_argument("--format", choices=("json", "csv"), default="json")
|
|
181
|
+
export.add_argument("--removed", action="store_true", help="include removed records")
|
|
182
|
+
|
|
183
|
+
merge = commands.add_parser("merge", help="merge game DROP into game KEEP")
|
|
184
|
+
merge.add_argument("keep", type=int)
|
|
185
|
+
merge.add_argument("drop", type=int)
|
|
186
|
+
return parser
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _emit_json(ok: bool, data: object | None = None, error: LudexError | None = None) -> None:
|
|
190
|
+
if ok:
|
|
191
|
+
payload: dict[str, Any] = {"ok": True, "data": data}
|
|
192
|
+
target = sys.stdout
|
|
193
|
+
else:
|
|
194
|
+
assert error is not None
|
|
195
|
+
payload = {"ok": False, "error": {"code": error.code, "message": error.message}}
|
|
196
|
+
target = sys.stderr
|
|
197
|
+
print(json.dumps(payload, ensure_ascii=False, separators=(",", ":")), file=target)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _plugin(sources: dict[str, Provider], problems: dict[str, str], name: str) -> Provider:
|
|
201
|
+
plugin = sources.get(name)
|
|
202
|
+
if plugin is None:
|
|
203
|
+
detail = f" ({problems[name]})" if name in problems else ""
|
|
204
|
+
raise LudexError("unknown_source", f"unknown source {name}{detail}")
|
|
205
|
+
return plugin
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _complete_path(text: str, state: int) -> str | None:
|
|
209
|
+
matches = sorted(glob.glob(os.path.expanduser(text) + "*"))
|
|
210
|
+
matches = [m + "/" if os.path.isdir(m) else m for m in matches]
|
|
211
|
+
return matches[state] if state < len(matches) else None
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def _input_path(prompt: str) -> str:
|
|
215
|
+
try:
|
|
216
|
+
import readline
|
|
217
|
+
except ImportError: # no readline: plain prompt
|
|
218
|
+
return input(prompt)
|
|
219
|
+
readline.set_completer(_complete_path)
|
|
220
|
+
readline.set_completer_delims(" \t\n;")
|
|
221
|
+
readline.parse_and_bind("bind ^I rl_complete" if "libedit" in (readline.__doc__ or "") else "tab: complete")
|
|
222
|
+
try:
|
|
223
|
+
return input(prompt)
|
|
224
|
+
finally:
|
|
225
|
+
readline.set_completer(None)
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _read_value(prompt: str, secret: bool, path: bool = False) -> str:
|
|
229
|
+
if sys.stdin.isatty():
|
|
230
|
+
value = getpass.getpass(prompt) if secret else _input_path(prompt) if path else input(prompt)
|
|
231
|
+
else:
|
|
232
|
+
value = sys.stdin.readline().rstrip("\r\n")
|
|
233
|
+
return value
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _cmd_providers(args: argparse.Namespace) -> tuple[object, str]:
|
|
237
|
+
sources, problems = load_providers()
|
|
238
|
+
data = {
|
|
239
|
+
"providers": [
|
|
240
|
+
{
|
|
241
|
+
"name": plugin.name,
|
|
242
|
+
"help": plugin.help,
|
|
243
|
+
"capabilities": list(plugin.capabilities),
|
|
244
|
+
"commands": [{"name": c.name, "help": c.help} for c in plugin.commands],
|
|
245
|
+
"fields": [{"name": f.name, "help": f.help, "secret": f.secret, "optional": f.optional, "kind": f.kind, "choices": list(f.choices)} for f in plugin.config_fields],
|
|
246
|
+
"settings": [{"name": f.name, "help": f.help, "secret": f.secret, "optional": f.optional, "kind": f.kind, "choices": list(f.choices)} for f in plugin.settings],
|
|
247
|
+
}
|
|
248
|
+
for _, plugin in sorted(sources.items())
|
|
249
|
+
],
|
|
250
|
+
"problems": dict(sorted(problems.items())),
|
|
251
|
+
}
|
|
252
|
+
lines = []
|
|
253
|
+
for p in data["providers"]:
|
|
254
|
+
lines.append(f"{p['name']} [{', '.join(p['capabilities'])}] {p['help']}")
|
|
255
|
+
lines += [f" ludex {p['name']} {c['name']} {c['help']}" for c in p["commands"]]
|
|
256
|
+
lines += [f"problem: {name}: {reason}" for name, reason in data["problems"].items()]
|
|
257
|
+
return data, "\n".join(lines) if lines else "no providers available"
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _cmd_account_add(args: argparse.Namespace) -> tuple[object, str]:
|
|
261
|
+
sources, problems = load_providers()
|
|
262
|
+
plugin = _plugin(sources, problems, args.source)
|
|
263
|
+
if plugin.fetch is None:
|
|
264
|
+
raise LudexError("no_owned_capability", f"provider {plugin.name} cannot list owned games, so it has no accounts")
|
|
265
|
+
fields = {f.name: f for f in plugin.config_fields}
|
|
266
|
+
config: dict[str, str] = {}
|
|
267
|
+
for item in args.fields:
|
|
268
|
+
key, separator, value = item.partition("=")
|
|
269
|
+
if not separator:
|
|
270
|
+
raise LudexError("invalid_field", "--set expects KEY=VALUE")
|
|
271
|
+
if key not in fields:
|
|
272
|
+
raise LudexError("unknown_field", f"source {plugin.name} has no field {key}")
|
|
273
|
+
if fields[key].secret:
|
|
274
|
+
raise LudexError("secret_via_argv", f"field {key} is secret; enter it at the prompt or on stdin")
|
|
275
|
+
if not value:
|
|
276
|
+
raise LudexError("empty_value", f"field {key} must not be empty")
|
|
277
|
+
config[key] = fields[key].clean(value)
|
|
278
|
+
paths = state_paths()
|
|
279
|
+
for field in plugin.config_fields:
|
|
280
|
+
if field.name in config:
|
|
281
|
+
continue
|
|
282
|
+
hint = " [yes/no]" if field.kind == "yes_no" else f" [{'/'.join(field.choices)}]" if field.kind == "choice" else ""
|
|
283
|
+
value = _read_value(f"{field.name} ({field.help}){hint}: ", field.secret, field.path)
|
|
284
|
+
if not value and not field.optional:
|
|
285
|
+
raise LudexError("empty_value", f"field {field.name} must not be empty")
|
|
286
|
+
if value:
|
|
287
|
+
config[field.name] = field.clean(value)
|
|
288
|
+
add_account(paths, args.name, plugin.name, config)
|
|
289
|
+
return {"account": args.name, "source": plugin.name}, f"added account {args.name} ({plugin.name})"
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _cmd_account_set(args: argparse.Namespace) -> tuple[object, str]:
|
|
293
|
+
if not (args.fields or args.secrets or args.unset):
|
|
294
|
+
raise LudexError("nothing_to_change", "give --set KEY=VALUE, --secret KEY or --unset KEY")
|
|
295
|
+
sources, problems = load_providers()
|
|
296
|
+
paths = state_paths()
|
|
297
|
+
account = get_account(paths, args.name)
|
|
298
|
+
plugin = _plugin(sources, problems, account.source)
|
|
299
|
+
by_name = {f.name: f for f in plugin.config_fields}
|
|
300
|
+
values: dict[str, str] = {}
|
|
301
|
+
for item in args.fields:
|
|
302
|
+
key, separator, value = item.partition("=")
|
|
303
|
+
if not separator:
|
|
304
|
+
raise LudexError("invalid_field", "--set expects KEY=VALUE")
|
|
305
|
+
if key in by_name and by_name[key].secret:
|
|
306
|
+
raise LudexError("secret_via_argv", f"field {key} is secret; use --secret {key}")
|
|
307
|
+
values[key] = value
|
|
308
|
+
for key in args.secrets:
|
|
309
|
+
if key not in by_name:
|
|
310
|
+
raise LudexError("unknown_field", f"source {plugin.name} has no field {key}")
|
|
311
|
+
values[key] = _read_value(f"{key} ({by_name[key].help}): ", True)
|
|
312
|
+
changed = update_account(paths, args.name, plugin.config_fields, values, args.unset)
|
|
313
|
+
return {"account": args.name, "changed": changed}, f"changed {', '.join(changed)} on account {args.name}; run: ludex import {args.name}"
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _cmd_account_ls(args: argparse.Namespace) -> tuple[object, str]:
|
|
317
|
+
accounts = [{"name": name, "source": source} for name, source in list_accounts(state_paths())]
|
|
318
|
+
lines = [f"{a['name']} {a['source']}" for a in accounts]
|
|
319
|
+
return {"accounts": accounts}, "\n".join(lines) if lines else "no accounts"
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _cmd_account_rm(args: argparse.Namespace) -> tuple[object, str]:
|
|
323
|
+
paths = state_paths()
|
|
324
|
+
try:
|
|
325
|
+
account = get_account(paths, args.name)
|
|
326
|
+
except LudexError as exc:
|
|
327
|
+
if exc.code != "account_not_found" or ":" in args.name:
|
|
328
|
+
raise
|
|
329
|
+
# an account already gone from the file can still have stale records: clear those
|
|
330
|
+
name, scope = args.name, {"keep_stores": [s for n, s in list_accounts(paths) if n == args.name]}
|
|
331
|
+
else:
|
|
332
|
+
remove_account(paths, args.name)
|
|
333
|
+
name, scope = account.name, {"store": account.source}
|
|
334
|
+
with writer_lock(paths.import_lock):
|
|
335
|
+
conn = connect(paths.database)
|
|
336
|
+
try:
|
|
337
|
+
changed = delete_account_records(conn, name, **scope)
|
|
338
|
+
finally:
|
|
339
|
+
conn.close()
|
|
340
|
+
if "keep_stores" in scope and not changed:
|
|
341
|
+
raise LudexError("account_not_found", f"account {args.name} not found")
|
|
342
|
+
return {"account": args.name, "records_removed": changed}, f"removed account {args.name}; deleted {changed} records"
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _import_one(conn: Any, paths: Any, sources: dict[str, Provider], problems: dict[str, str], name: str) -> dict[str, Any]:
|
|
346
|
+
account = get_account(paths, name)
|
|
347
|
+
plugin = _plugin(sources, problems, account.source)
|
|
348
|
+
summary = run_import(conn, account.name, plugin, account.config)
|
|
349
|
+
return {"account": account.name, "source": account.source, "ok": True, **summary.as_dict()}
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
def _cmd_import(args: argparse.Namespace) -> tuple[object, str, int]:
|
|
353
|
+
paths = state_paths()
|
|
354
|
+
with writer_lock(paths.import_lock):
|
|
355
|
+
conn = connect(paths.database)
|
|
356
|
+
try:
|
|
357
|
+
sources, problems = load_providers()
|
|
358
|
+
if not args.all:
|
|
359
|
+
result = _import_one(conn, paths, sources, problems, args.account)
|
|
360
|
+
return {k: v for k, v in result.items() if k != "ok"}, _import_line(result), 0
|
|
361
|
+
results: list[dict[str, Any]] = []
|
|
362
|
+
for name, source in list_accounts(paths):
|
|
363
|
+
try:
|
|
364
|
+
results.append(_import_one(conn, paths, sources, problems, f"{source}:{name}"))
|
|
365
|
+
except LudexError as exc:
|
|
366
|
+
results.append({"account": name, "source": source, "ok": False, "error": {"code": exc.code, "message": exc.message}})
|
|
367
|
+
finally:
|
|
368
|
+
conn.close()
|
|
369
|
+
lines = [_import_line(r) if r["ok"] else f"{r['source']}:{r['account']}: error: {r['error']['message']}" for r in results]
|
|
370
|
+
status = 1 if any(not r["ok"] for r in results) else 0
|
|
371
|
+
return {"results": results}, "\n".join(lines) if lines else "no accounts", status
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _ask(prompt: str, default: str) -> str:
|
|
375
|
+
print(prompt, end="", file=sys.stderr, flush=True)
|
|
376
|
+
return _read_value("", False) or default
|
|
377
|
+
|
|
378
|
+
|
|
379
|
+
def _cmd_setup(args: argparse.Namespace) -> tuple[object, str]:
|
|
380
|
+
sources, problems = load_providers()
|
|
381
|
+
if not sources:
|
|
382
|
+
raise LudexError("no_sources", "no source plugins are available")
|
|
383
|
+
names = sorted(sources)
|
|
384
|
+
source = args.source or _ask(f"source ({', '.join(names)}) [{names[0]}]: ", names[0])
|
|
385
|
+
plugin = _plugin(sources, problems, source)
|
|
386
|
+
name = args.name or _ask(f"account name [{source}]: ", source)
|
|
387
|
+
if (name, source) in list_accounts(state_paths()):
|
|
388
|
+
raise LudexError("account_exists", f"account {name} already exists for source {source}")
|
|
389
|
+
print(f"{plugin.help}\nEnter skips optional fields.", file=sys.stderr)
|
|
390
|
+
added = _cmd_account_add(argparse.Namespace(source=source, name=name, fields=[]))
|
|
391
|
+
try:
|
|
392
|
+
data, human, _ = _cmd_import(argparse.Namespace(account=f"{source}:{name}", all=False))
|
|
393
|
+
except LudexError as exc:
|
|
394
|
+
raise LudexError(exc.code, f"{exc.message}; account {name} was saved, fix the cause and run: ludex import {source}:{name}") from None
|
|
395
|
+
return data, f"{added[1]}\n{human}"
|
|
396
|
+
|
|
397
|
+
|
|
398
|
+
def _import_line(result: dict[str, Any]) -> str:
|
|
399
|
+
note = f" [{result['mode']}]" if result["mode"] else ""
|
|
400
|
+
if not result["complete"]:
|
|
401
|
+
note += " partial: nothing removed"
|
|
402
|
+
return (
|
|
403
|
+
f"{result['source']}:{result['account']}: {result['added']} added, {result['restored']} restored, "
|
|
404
|
+
f"{result['removed']} removed, {result['total']} total{note}"
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _cmd_ls(args: argparse.Namespace) -> tuple[object, str]:
|
|
409
|
+
if args.limit < 1 or args.offset < 0:
|
|
410
|
+
raise LudexError("invalid_paging", "--limit must be at least 1 and --offset must not be negative")
|
|
411
|
+
paths = state_paths()
|
|
412
|
+
only = None
|
|
413
|
+
if args.installed:
|
|
414
|
+
providers, _ = load_providers()
|
|
415
|
+
only, problems = installed_keys(paths, providers)
|
|
416
|
+
for ref, reason in sorted(problems.items()):
|
|
417
|
+
print(f"warning: {ref}: {reason}", file=sys.stderr)
|
|
418
|
+
conn = connect(paths.database)
|
|
419
|
+
try:
|
|
420
|
+
stats: dict[int, Played] = {}
|
|
421
|
+
if args.sort != "title":
|
|
422
|
+
providers, _ = load_providers()
|
|
423
|
+
stats, problems = play_stats(paths, providers, conn)
|
|
424
|
+
for ref, reason in sorted(problems.items()):
|
|
425
|
+
print(f"warning: {ref}: {reason}", file=sys.stderr)
|
|
426
|
+
order = {g: (p.minutes if args.sort == "played" else epoch(p.last_played) if p.last_played else -1) for g, p in stats.items()} if stats else None
|
|
427
|
+
games = list_games(
|
|
428
|
+
conn,
|
|
429
|
+
only=only,
|
|
430
|
+
order=order if args.sort != "title" else None,
|
|
431
|
+
query=args.query,
|
|
432
|
+
store=args.store,
|
|
433
|
+
account=args.account,
|
|
434
|
+
include_removed=args.removed,
|
|
435
|
+
limit=args.limit,
|
|
436
|
+
offset=args.offset,
|
|
437
|
+
)
|
|
438
|
+
finally:
|
|
439
|
+
conn.close()
|
|
440
|
+
if args.sort != "title":
|
|
441
|
+
for g in games:
|
|
442
|
+
p = stats.get(g["id"])
|
|
443
|
+
g["played_minutes"], g["last_played"] = (p.minutes, p.last_played) if p else (0, None)
|
|
444
|
+
id_width = max((len(str(g["id"])) for g in games), default=0)
|
|
445
|
+
title_width = max((len(g["title"]) for g in games), default=0)
|
|
446
|
+
lines = [
|
|
447
|
+
f"{g['id']:>{id_width}} {g['title']:<{title_width}} [{', '.join(g['stores'])}]" + (" (removed)" if g["removed"] else "")
|
|
448
|
+
+ (f" {describe_played(stats.get(g['id']))}" if args.sort != "title" else "")
|
|
449
|
+
for g in games
|
|
450
|
+
]
|
|
451
|
+
return {"games": games, "limit": args.limit, "offset": args.offset}, "\n".join(lines) if lines else "no games"
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
def _cmd_show(args: argparse.Namespace) -> tuple[object, str]:
|
|
455
|
+
paths = state_paths()
|
|
456
|
+
conn = connect(paths.database)
|
|
457
|
+
try:
|
|
458
|
+
game = get_game(conn, resolve_game(conn, args.game))
|
|
459
|
+
stats, problems = play_stats(paths, load_providers()[0], conn)
|
|
460
|
+
finally:
|
|
461
|
+
conn.close()
|
|
462
|
+
for ref, reason in sorted(problems.items()):
|
|
463
|
+
print(f"warning: {ref}: {reason}", file=sys.stderr)
|
|
464
|
+
played = stats.get(game["id"])
|
|
465
|
+
game["played_minutes"], game["last_played"] = (played.minutes, played.last_played) if played else (0, None)
|
|
466
|
+
lines = [f"{game['id']} {game['title']} (added {game['created_at']})", f" played: {describe_played(played)}"]
|
|
467
|
+
for o in game["ownership"]:
|
|
468
|
+
state = "removed" if o["removed"] else "owned"
|
|
469
|
+
lines.append(
|
|
470
|
+
f" {o['store']}:{o['store_id']} account={o['account']} {o['title']} "
|
|
471
|
+
f"{state} first_seen={o['first_seen']} last_seen={o['last_seen']}"
|
|
472
|
+
)
|
|
473
|
+
return game, "\n".join(lines)
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _cmd_find(args: argparse.Namespace) -> tuple[object, str]:
|
|
477
|
+
providers, _ = load_providers()
|
|
478
|
+
conn = connect(state_paths().database)
|
|
479
|
+
try:
|
|
480
|
+
owned = owned_keys(conn)
|
|
481
|
+
finally:
|
|
482
|
+
conn.close()
|
|
483
|
+
hits, problems = find_games(providers, args.query, owned)
|
|
484
|
+
for name, reason in sorted(problems.items()):
|
|
485
|
+
print(f"warning: {name}: {reason}", file=sys.stderr)
|
|
486
|
+
lines = [
|
|
487
|
+
f"[{h['store']}] {h['title']} {h['price'] or '-'} {h['url']}" + (" (owned)" if h["owned"] else "") for h in hits
|
|
488
|
+
]
|
|
489
|
+
return {"hits": hits, "problems": problems}, "\n".join(lines) if lines else "no results"
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _cmd_install(args: argparse.Namespace) -> tuple[object, str]:
|
|
493
|
+
providers, _ = load_providers()
|
|
494
|
+
paths = state_paths()
|
|
495
|
+
config_for = lambda store, account: get_account(paths, f"{store}:{account}").config
|
|
496
|
+
conn = connect(paths.database)
|
|
497
|
+
try:
|
|
498
|
+
if args.status:
|
|
499
|
+
return _job_status(conn, "install", resolve_game(conn, args.game) if args.game else None)
|
|
500
|
+
if not args.game:
|
|
501
|
+
raise LudexError("missing_game", "name the game to install (or use --status)")
|
|
502
|
+
game_id = resolve_game(conn, args.game)
|
|
503
|
+
if args.stop:
|
|
504
|
+
return _job_stop(conn, "install", game_id)
|
|
505
|
+
if args.dry_run:
|
|
506
|
+
plan = prepare_install(conn, providers, game_id, args.store, config_for)
|
|
507
|
+
return {"id": game_id, "install": plan.target, "url": plan.url, "argv": list(plan.argv)}, f"would install {plan.target}: {plan.url or shlex.join(plan.argv)}"
|
|
508
|
+
target, job = install_game(conn, providers, game_id, args.store, config_for, paths.root / "logs")
|
|
509
|
+
finally:
|
|
510
|
+
conn.close()
|
|
511
|
+
if job is None:
|
|
512
|
+
return {"id": game_id, "install": target}, f"asking the client to install {target}"
|
|
513
|
+
return {"id": game_id, "install": target, "job": _job_data(job)}, f"installing {target} in the background (job {job.id}); 'ludex install --status' shows progress, '--stop' cancels; log: {job.log}"
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _job_data(job: Job) -> dict[str, object]:
|
|
517
|
+
return {"id": job.id, "game_id": job.game_id, "target": job.target, "title": job.title, "state": job.state, "exit_code": job.exit_code,
|
|
518
|
+
"started_at": job.started_at, "ended_at": job.ended_at, "log": str(job.log), "progress": progress_line(job) if job.state == "running" else "", "progress_detail": _progress_detail(job)}
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _progress_detail(job: Job) -> dict[str, object] | None:
|
|
522
|
+
report = progress(job)
|
|
523
|
+
if report is None or report.fraction is None:
|
|
524
|
+
return None
|
|
525
|
+
return {"done": report.done, "total": report.total, "fraction": report.fraction, "eta_seconds": eta_seconds(job, report)}
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _job_status(conn, kind: str, game_id: int | None) -> tuple[object, str]:
|
|
529
|
+
jobs = list_jobs(conn, kind, game_id)
|
|
530
|
+
# an install shows its progress; a game's own output is no progress, so it shows when it started
|
|
531
|
+
running = progress_line if kind in {"install", "download"} else (lambda j: f"since {j.started_at}")
|
|
532
|
+
lines = [
|
|
533
|
+
f"#{j.id} {j.state:<8} {j.title} ({j.target}) " + (running(j) if j.state == "running" else f"exit {j.exit_code}" if j.exit_code not in (None, 0) else j.ended_at or "")
|
|
534
|
+
for j in jobs
|
|
535
|
+
]
|
|
536
|
+
return {"jobs": [_job_data(j) for j in jobs]}, "\n".join(lines) if lines else f"no {({'install': 'installs', 'download': 'downloads'}).get(kind, 'games')} started by ludex"
|
|
537
|
+
|
|
538
|
+
|
|
539
|
+
def _job_stop(conn, kind: str, game_id: int) -> tuple[object, str]:
|
|
540
|
+
running = list_jobs(conn, kind, game_id, running=True)
|
|
541
|
+
if not running:
|
|
542
|
+
raise LudexError("job_not_running", f"no {'install of that game' if kind == 'install' else 'game started by ludex'} is running")
|
|
543
|
+
job = stop_job(conn, running[0].id)
|
|
544
|
+
what = f"the install of {job.title}" if kind == "install" else job.title
|
|
545
|
+
return {"id": game_id, "job": _job_data(job)}, f"stopped {what} (job {job.id})" + ("; run it again to resume" if kind == "install" else "")
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def _cmd_match(args: argparse.Namespace) -> tuple[object, str]:
|
|
549
|
+
providers, _ = load_providers()
|
|
550
|
+
conn = connect(state_paths().database)
|
|
551
|
+
try:
|
|
552
|
+
game_id = resolve_game(conn, args.game)
|
|
553
|
+
if args.clear:
|
|
554
|
+
cleared = clear_match(conn, game_id)
|
|
555
|
+
return {"id": game_id, "cleared": cleared}, "match cleared" if cleared else "no match to clear"
|
|
556
|
+
query = args.query or default_query(conn, game_id)
|
|
557
|
+
hits, problems = match_candidates(providers, query)
|
|
558
|
+
if not args.use:
|
|
559
|
+
data = {"id": game_id, "query": query, "candidates": [{"plugin": p, "id": h.store_id, "title": h.title, "url": h.url} for p, h in hits], "problems": problems}
|
|
560
|
+
lines = [f"{p}:{h.store_id} {h.title} {h.url}" for p, h in hits] or [f"no match for {query!r}"]
|
|
561
|
+
lines += [f"{name}: {reason}" for name, reason in problems.items()]
|
|
562
|
+
return data, "\n".join(lines)
|
|
563
|
+
plugin, _, store_id = args.use.partition(":")
|
|
564
|
+
hit = next((h for p, h in hits if p == plugin and h.store_id == store_id), None)
|
|
565
|
+
if hit is None:
|
|
566
|
+
raise LudexError("not_found", f"{args.use} is not among the candidates for {query!r}; list them first")
|
|
567
|
+
choose_match(conn, providers, game_id, plugin, hit)
|
|
568
|
+
finally:
|
|
569
|
+
conn.close()
|
|
570
|
+
return {"id": game_id, "matched": {"plugin": plugin, "id": hit.store_id, "title": hit.title, "url": hit.url}}, f"matched to {plugin}: {hit.title} ({hit.url})"
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _cmd_metadata(args: argparse.Namespace) -> tuple[object, str]:
|
|
574
|
+
providers, _ = load_providers()
|
|
575
|
+
conn = connect(state_paths().database)
|
|
576
|
+
try:
|
|
577
|
+
game_id = resolve_game(conn, args.game)
|
|
578
|
+
found = game_metadata(conn, providers, game_id, args.refresh, args.match or get_auto_match(conn))
|
|
579
|
+
matched = next((m for o in get_game(conn, game_id)["ownership"] if (m := cached_match(conn, o["store"], str(o["store_id"])))), None)
|
|
580
|
+
finally:
|
|
581
|
+
conn.close()
|
|
582
|
+
if found is None:
|
|
583
|
+
return {"id": game_id, "metadata": None}, "no store has details for this game"
|
|
584
|
+
lines = [found.description or "", f"genres: {', '.join(found.genres)}" if found.genres else "", f"by: {', '.join(found.developers)}" if found.developers else "", f"released: {found.released}" if found.released else "", f"matched to {matched['plugin']}: {matched['title']}" + (f" ({matched['url']})" if matched['url'] else "") if matched else ""]
|
|
585
|
+
return {"id": game_id, "metadata": asdict(found), "matched": matched}, "\n".join(x for x in lines if x)
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _download_dir() -> Path:
|
|
589
|
+
conn = connect(state_paths().database)
|
|
590
|
+
try:
|
|
591
|
+
return get_download_dir(conn, default_download_dir())
|
|
592
|
+
finally:
|
|
593
|
+
conn.close()
|
|
594
|
+
|
|
595
|
+
|
|
596
|
+
def _cmd_acquire(args: argparse.Namespace) -> tuple[object, str]:
|
|
597
|
+
providers, _ = load_providers()
|
|
598
|
+
destination = Path(args.to) if args.to else _download_dir()
|
|
599
|
+
result = acquire_game(
|
|
600
|
+
providers, args.store, args.store_id, args.title, destination, job_reporter(lambda message: print(message, file=sys.stderr))
|
|
601
|
+
)
|
|
602
|
+
data = {"directory": str(result.directory), "hints": dict(result.hints)}
|
|
603
|
+
return data, format_acquired(result)
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _cmd_download(args: argparse.Namespace) -> tuple[object, str]:
|
|
607
|
+
paths = state_paths()
|
|
608
|
+
conn = connect(paths.database)
|
|
609
|
+
try:
|
|
610
|
+
if args.status:
|
|
611
|
+
return _job_status(conn, "download", None)
|
|
612
|
+
if not args.store or not args.store_id:
|
|
613
|
+
raise LudexError("missing_game", "name the store and its id (or use --status)")
|
|
614
|
+
target = f"{args.store}:{args.store_id}"
|
|
615
|
+
if args.stop:
|
|
616
|
+
running = [j for j in list_jobs(conn, "download", running=True, limit=100) if j.target == target]
|
|
617
|
+
if not running:
|
|
618
|
+
raise LudexError("job_not_running", f"no download of {target} is running")
|
|
619
|
+
job = stop_job(conn, running[0].id)
|
|
620
|
+
return {"job": _job_data(job)}, f"stopped the download of {job.title} (job {job.id})"
|
|
621
|
+
providers, _ = load_providers()
|
|
622
|
+
destination = Path(args.to) if args.to else get_download_dir(conn, default_download_dir())
|
|
623
|
+
job = download_game(conn, providers, args.store, args.store_id, args.title, destination, paths.root / "logs")
|
|
624
|
+
finally:
|
|
625
|
+
conn.close()
|
|
626
|
+
return {"job": _job_data(job)}, f"downloading {target} in the background (job {job.id}); 'ludex download --status' shows progress, '--stop {target}' cancels; log: {job.log}"
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def _cmd_plugin_add(args: argparse.Namespace) -> tuple[object, str]:
|
|
630
|
+
print("note: a plugin runs with your permissions; install only code you trust", file=sys.stderr)
|
|
631
|
+
added = add_plugin(args.spec)
|
|
632
|
+
return added, f"added plugin {added['name']} {added['version']} (providers: {', '.join(added['providers'])})"
|
|
633
|
+
|
|
634
|
+
|
|
635
|
+
def _cmd_plugin_ls(args: argparse.Namespace) -> tuple[object, str]:
|
|
636
|
+
plugins = list_plugins()
|
|
637
|
+
lines = [
|
|
638
|
+
f"{p['name']} {p['version']} providers: {', '.join(p['providers'])}" + ("" if p["enabled"] else " (disabled)")
|
|
639
|
+
+ f"\n from: {p['spec'] or 'unknown (update skips it)'}"
|
|
640
|
+
for p in plugins
|
|
641
|
+
]
|
|
642
|
+
return {"plugins": plugins}, "\n".join(lines) if lines else "no plugins installed by ludex"
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
def _cmd_plugin_rm(args: argparse.Namespace) -> tuple[object, str]:
|
|
646
|
+
removed = remove_plugin(args.name)
|
|
647
|
+
note = f"; accounts for {', '.join(removed['providers'])} stay until 'ludex account rm'" if removed["providers"] else ""
|
|
648
|
+
return removed, f"removed plugin {removed['name']}{note}"
|
|
649
|
+
|
|
650
|
+
|
|
651
|
+
def _cmd_plugin_enable(args: argparse.Namespace) -> tuple[object, str]:
|
|
652
|
+
done = set_plugin_enabled(args.name, args.plugin_command == "enable")
|
|
653
|
+
return done, f"{'enabled' if done['enabled'] else 'disabled'} plugin {done['name']}"
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def _cmd_plugin_update(args: argparse.Namespace) -> tuple[object, str, int]:
|
|
657
|
+
results = update_plugins(args.name)
|
|
658
|
+
lines = [
|
|
659
|
+
f"{r['name']}: {r['from']} -> {r['to']}" if r["ok"] else f"{r['name']}: error: {r['error']['message']}"
|
|
660
|
+
for r in results
|
|
661
|
+
]
|
|
662
|
+
return {"results": results}, "\n".join(lines) if lines else "no plugins installed by ludex", int(any(not r["ok"] for r in results))
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
def _cmd_update(args: argparse.Namespace) -> tuple[object, str]:
|
|
666
|
+
result = update_core(args.channel, args.dry_run)
|
|
667
|
+
if args.dry_run:
|
|
668
|
+
return result, f"would run: {shlex.join(result['command'])}"
|
|
669
|
+
return result, f"updated ludex {result['from']} -> {result['to'] or 'unknown'} ({result['channel']})"
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def _cmd_runners(args: argparse.Namespace) -> tuple[object, str]:
|
|
673
|
+
runners = [{"name": r.name, "path": str(r.path), "origin": r.origin} for r in find_runners()]
|
|
674
|
+
lines = [f"{r['name']} ({r['origin']}) {r['path']}" for r in runners]
|
|
675
|
+
return {"runners": runners}, "\n".join(lines) if lines else "no Proton builds found"
|
|
676
|
+
|
|
677
|
+
|
|
678
|
+
_YES_NO = {"yes": True, "on": True, "true": True, "no": False, "off": False, "false": False}
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _plugin_setting(sources: dict[str, Provider], key: str) -> tuple[Provider, str]:
|
|
682
|
+
provider, _, name = key.partition(".")
|
|
683
|
+
plugin = sources.get(provider)
|
|
684
|
+
if plugin is None or not name or all(f.name != name for f in plugin.settings):
|
|
685
|
+
raise LudexError("invalid_setting", f"unknown setting {key}; see 'ludex config'")
|
|
686
|
+
return plugin, name
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def _cmd_config(args: argparse.Namespace) -> tuple[object, str]:
|
|
690
|
+
paths = state_paths()
|
|
691
|
+
default = paths.root / "prefixes"
|
|
692
|
+
default_downloads = default_download_dir()
|
|
693
|
+
sources, _ = load_providers()
|
|
694
|
+
key = args.key
|
|
695
|
+
core = {"prefix_dir", "download_dir", "auto_details", "auto_match", "auto_refresh", *SWITCHES}
|
|
696
|
+
changing = bool(args.value or args.reset or args.secret)
|
|
697
|
+
if changing and not key:
|
|
698
|
+
raise LudexError("invalid_setting", "name the setting to change")
|
|
699
|
+
if sum(map(bool, (args.value, args.reset, args.secret))) > 1:
|
|
700
|
+
raise LudexError("invalid_setting", "give a value, --secret or --reset, one at a time")
|
|
701
|
+
if key is not None and key not in core:
|
|
702
|
+
plugin, name = _plugin_setting(sources, key)
|
|
703
|
+
field = field_for(plugin, name)
|
|
704
|
+
if args.value and field.secret:
|
|
705
|
+
raise LudexError("secret_via_argv", f"{key} is secret; use: ludex config {key} --secret")
|
|
706
|
+
if args.secret and not field.secret:
|
|
707
|
+
raise LudexError("invalid_setting", f"{key} is not a secret setting")
|
|
708
|
+
if changing:
|
|
709
|
+
value = None if args.reset else _read_value(f"{key} ({field.help}): ", True) if args.secret else args.value
|
|
710
|
+
set_value(paths, plugin, name, value)
|
|
711
|
+
else:
|
|
712
|
+
if args.secret:
|
|
713
|
+
raise LudexError("invalid_setting", f"{key} is not a secret setting")
|
|
714
|
+
if args.reset and key in SWITCHES:
|
|
715
|
+
raise LudexError("invalid_setting", f"{key} has no default to reset to; set yes or no")
|
|
716
|
+
if args.value and (key in SWITCHES or key in {"auto_details", "auto_match", "auto_refresh"}) and args.value.lower() not in _YES_NO:
|
|
717
|
+
raise LudexError("invalid_setting", f"{key} takes yes or no")
|
|
718
|
+
with writer_lock(paths.import_lock):
|
|
719
|
+
conn = connect(paths.database)
|
|
720
|
+
try:
|
|
721
|
+
if changing and key == "prefix_dir":
|
|
722
|
+
set_prefix_root(conn, None if args.reset else args.value)
|
|
723
|
+
elif changing and key == "download_dir":
|
|
724
|
+
set_download_dir(conn, None if args.reset else args.value)
|
|
725
|
+
elif changing and key == "auto_refresh":
|
|
726
|
+
set_auto_refresh(conn, None if args.reset else _YES_NO[args.value.lower()])
|
|
727
|
+
elif changing and key == "auto_details":
|
|
728
|
+
set_auto_details(conn, None if args.reset else _YES_NO[args.value.lower()])
|
|
729
|
+
elif changing and key == "auto_match":
|
|
730
|
+
set_auto_match(conn, None if args.reset else _YES_NO[args.value.lower()])
|
|
731
|
+
elif changing and key in SWITCHES:
|
|
732
|
+
set_switch(paths, conn, sources, key, _YES_NO[args.value.lower()])
|
|
733
|
+
folder = get_prefix_root(conn, default)
|
|
734
|
+
downloads = get_download_dir(conn, default_downloads)
|
|
735
|
+
auto = get_auto_details(conn)
|
|
736
|
+
refresh = get_auto_refresh(conn)
|
|
737
|
+
match = get_auto_match(conn)
|
|
738
|
+
finally:
|
|
739
|
+
conn.close()
|
|
740
|
+
plugin_values = {name: describe(paths, plugin) for name, plugin in sorted(sources.items()) if plugin.settings}
|
|
741
|
+
data: dict[str, Any] = {
|
|
742
|
+
"prefix_dir": str(folder),
|
|
743
|
+
"download_dir": str(downloads),
|
|
744
|
+
"auto_details": auto,
|
|
745
|
+
"auto_refresh": refresh,
|
|
746
|
+
"auto_match": match,
|
|
747
|
+
**{k: get_switch(paths, k) for k in sorted(SWITCHES)},
|
|
748
|
+
"plugins": plugin_values,
|
|
749
|
+
}
|
|
750
|
+
shown = {
|
|
751
|
+
"prefix_dir": f"prefix_dir: {folder}" + (" (default)" if folder == default else ""),
|
|
752
|
+
"download_dir": f"download_dir: {downloads}" + (" (default)" if downloads == default_downloads else ""),
|
|
753
|
+
}
|
|
754
|
+
shown.update({k: f"{k}: {'yes' if data[k] else 'no'}" for k in ("auto_details", "auto_match", "auto_refresh", *sorted(SWITCHES))})
|
|
755
|
+
for name, values in plugin_values.items():
|
|
756
|
+
shown.update({f"{name}.{k}": f"{name}.{k}: {v if v is not None else '(not set)'}" for k, v in values.items()})
|
|
757
|
+
return data, "\n".join(shown.values() if key is None else [shown[key]])
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def _settings_view(conn: Any, game_id: int, store: str | None) -> tuple[dict[str, Any], str]:
|
|
761
|
+
copy = pick_copy(conn, game_id, store)
|
|
762
|
+
data = {"id": game_id, "store": copy[0], "store_id": copy[1], **get_settings(conn, *copy).as_dict()}
|
|
763
|
+
lines = [f"{copy[0]}:{copy[1]}"] + [
|
|
764
|
+
f" {key}: {data[key] if data[key] not in (None, [], {}) else '-'}" for key in ("runner", "prefix", "executable", "args", "env")
|
|
765
|
+
]
|
|
766
|
+
return data, "\n".join(lines)
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
def _cmd_game_show(args: argparse.Namespace) -> tuple[object, str]:
|
|
770
|
+
conn = connect(state_paths().database)
|
|
771
|
+
try:
|
|
772
|
+
return _settings_view(conn, resolve_game(conn, args.game), args.store)
|
|
773
|
+
finally:
|
|
774
|
+
conn.close()
|
|
775
|
+
|
|
776
|
+
|
|
777
|
+
def _cmd_game_exes(args: argparse.Namespace) -> tuple[object, str]:
|
|
778
|
+
providers, _ = load_providers()
|
|
779
|
+
paths = state_paths()
|
|
780
|
+
conn = connect(paths.database)
|
|
781
|
+
try:
|
|
782
|
+
game_id = resolve_game(conn, args.game)
|
|
783
|
+
store, store_id = pick_copy(conn, game_id, args.store)
|
|
784
|
+
provider = providers.get(store)
|
|
785
|
+
if provider is None or provider.game_folder is None:
|
|
786
|
+
raise LudexError("no_game_folder", f"{store} does not keep games in a folder on this machine")
|
|
787
|
+
row = conn.execute("SELECT account FROM ownership WHERE store = ? AND store_id = ? AND removed = 0 ORDER BY account", (store, store_id)).fetchone()
|
|
788
|
+
folder = Path(provider.game_folder(get_account(paths, f"{store}:{row['account']}").config, store_id))
|
|
789
|
+
title = get_game(conn, game_id)["title"]
|
|
790
|
+
finally:
|
|
791
|
+
conn.close()
|
|
792
|
+
if not folder.is_dir():
|
|
793
|
+
raise LudexError("no_game_folder", "the game's folder does not exist")
|
|
794
|
+
found = find_executables(folder, title)
|
|
795
|
+
return {"folder": str(folder), "executables": [str(p) for p in found]}, "\n".join(str(p) for p in found) or "no executable found in the game folder"
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
def _cmd_game_set(args: argparse.Namespace) -> tuple[object, str]:
|
|
799
|
+
env: dict[str, str] = {}
|
|
800
|
+
for item in args.env:
|
|
801
|
+
name, sep, value = item.partition("=")
|
|
802
|
+
if not sep:
|
|
803
|
+
raise LudexError("invalid_setting", "--env needs NAME=VALUE")
|
|
804
|
+
env[name] = value
|
|
805
|
+
try:
|
|
806
|
+
extra = shlex.split(args.args) if args.args is not None else None
|
|
807
|
+
except ValueError:
|
|
808
|
+
raise LudexError("invalid_setting", "--args has unbalanced quotes") from None
|
|
809
|
+
paths = state_paths()
|
|
810
|
+
with writer_lock(paths.import_lock):
|
|
811
|
+
conn = connect(paths.database)
|
|
812
|
+
try:
|
|
813
|
+
game_id = resolve_game(conn, args.game)
|
|
814
|
+
copy = pick_copy(conn, game_id, args.store)
|
|
815
|
+
update_settings(
|
|
816
|
+
conn, *copy, runner=args.runner, prefix=args.prefix, executable=args.exe, args=extra,
|
|
817
|
+
env=env, unset_env=args.unset_env, clear=args.clear,
|
|
818
|
+
)
|
|
819
|
+
return _settings_view(conn, game_id, args.store)
|
|
820
|
+
finally:
|
|
821
|
+
conn.close()
|
|
822
|
+
|
|
823
|
+
|
|
824
|
+
def _cmd_launch(args: argparse.Namespace) -> tuple[object, str]:
|
|
825
|
+
sources, _ = load_providers()
|
|
826
|
+
paths = state_paths()
|
|
827
|
+
conn = connect(paths.database)
|
|
828
|
+
config_for = lambda store, account: get_account(paths, f"{store}:{account}").config
|
|
829
|
+
try:
|
|
830
|
+
if args.status:
|
|
831
|
+
return _job_status(conn, "play", resolve_game(conn, args.game) if args.game else None)
|
|
832
|
+
if not args.game:
|
|
833
|
+
raise LudexError("missing_game", "name the game to launch (or use --status)")
|
|
834
|
+
game_id = resolve_game(conn, args.game)
|
|
835
|
+
if args.stop:
|
|
836
|
+
return _job_stop(conn, "play", game_id)
|
|
837
|
+
if args.dry_run:
|
|
838
|
+
plan = prepare_launch(conn, sources, game_id, args.store, config_for, get_prefix_root(conn, paths.root / "prefixes"))
|
|
839
|
+
data = {
|
|
840
|
+
"id": game_id, "target": plan.target, "url": plan.url, "argv": list(plan.argv),
|
|
841
|
+
"cwd": str(plan.cwd) if plan.cwd else None, "env": sorted(plan.env), # names only: values may be secrets
|
|
842
|
+
}
|
|
843
|
+
how = plan.url or shlex.join(plan.argv)
|
|
844
|
+
env = f" [env: {', '.join(data['env'])}]" if data["env"] else ""
|
|
845
|
+
return data, f"would start {plan.target}: {how}{env}"
|
|
846
|
+
target, job = launch_game(conn, sources, game_id, args.store, config_for, get_prefix_root(conn, paths.root / "prefixes"), paths.root / "logs")
|
|
847
|
+
finally:
|
|
848
|
+
conn.close()
|
|
849
|
+
if job is None:
|
|
850
|
+
return {"id": game_id, "launched": target, "job": None}, f"launching {target}"
|
|
851
|
+
return {"id": game_id, "launched": target, "job": _job_data(job)}, f"launching {target} (job {job.id}); 'ludex launch --status' shows whether it runs, '--stop' ends it; log: {job.log}"
|
|
852
|
+
|
|
853
|
+
|
|
854
|
+
def _cmd_tui(args: argparse.Namespace) -> tuple[object, str]:
|
|
855
|
+
try:
|
|
856
|
+
from ludex_tui.app import main as run_tui
|
|
857
|
+
except ModuleNotFoundError as exc:
|
|
858
|
+
if exc.name != "ludex_tui":
|
|
859
|
+
raise
|
|
860
|
+
raise LudexError("tui_missing", "install ludex-tui alongside ludex-cli, or install ludex-games") from None
|
|
861
|
+
run_tui()
|
|
862
|
+
return {}, ""
|
|
863
|
+
|
|
864
|
+
|
|
865
|
+
def _cmd_review(args: argparse.Namespace) -> tuple[object, str]:
|
|
866
|
+
paths = state_paths()
|
|
867
|
+
with writer_lock(paths.import_lock):
|
|
868
|
+
conn = connect(paths.database)
|
|
869
|
+
try:
|
|
870
|
+
if args.dismiss is not None:
|
|
871
|
+
dismiss_review(conn, args.dismiss)
|
|
872
|
+
return {"dismissed": args.dismiss}, f"dismissed review item {args.dismiss}"
|
|
873
|
+
items = list_review(conn)
|
|
874
|
+
finally:
|
|
875
|
+
conn.close()
|
|
876
|
+
lines = []
|
|
877
|
+
for item in items:
|
|
878
|
+
lines.append(f"{item['id']} game {item['game_id']}: {item['title']} [{item['store']}] may be the same as:")
|
|
879
|
+
lines += [f" game {c['id']}: {c['title']}" for c in item["candidates"]]
|
|
880
|
+
return {"items": items}, "\n".join(lines) if lines else "nothing to review"
|
|
881
|
+
|
|
882
|
+
|
|
883
|
+
def _cmd_merge(args: argparse.Namespace) -> tuple[object, str]:
|
|
884
|
+
paths = state_paths()
|
|
885
|
+
with writer_lock(paths.import_lock):
|
|
886
|
+
conn = connect(paths.database)
|
|
887
|
+
try:
|
|
888
|
+
moved = merge_games(conn, args.keep, args.drop)
|
|
889
|
+
finally:
|
|
890
|
+
conn.close()
|
|
891
|
+
return {"keep": args.keep, "drop": args.drop, "moved": moved}, f"merged game {args.drop} into {args.keep} ({moved} records)"
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
_CSV_FIELDS = ("game_id", "title", "store", "store_id", "account", "removed", "first_seen", "last_seen")
|
|
895
|
+
|
|
896
|
+
|
|
897
|
+
def _cmd_export(args: argparse.Namespace) -> tuple[object, str]:
|
|
898
|
+
conn = connect(state_paths().database)
|
|
899
|
+
try:
|
|
900
|
+
games = export_games(conn, include_removed=args.removed)
|
|
901
|
+
finally:
|
|
902
|
+
conn.close()
|
|
903
|
+
if args.format == "json":
|
|
904
|
+
return {"games": games}, json.dumps(games, ensure_ascii=False, indent=2)
|
|
905
|
+
out = io.StringIO()
|
|
906
|
+
writer = csv.writer(out, lineterminator="\n")
|
|
907
|
+
writer.writerow(_CSV_FIELDS)
|
|
908
|
+
for game in games:
|
|
909
|
+
for o in game["ownership"]:
|
|
910
|
+
writer.writerow([game["id"], o["title"], o["store"], o["store_id"], o["account"], int(o["removed"]), o["first_seen"], o["last_seen"]])
|
|
911
|
+
return {"games": games}, out.getvalue().rstrip("\n")
|
|
912
|
+
|
|
913
|
+
|
|
914
|
+
_HANDLERS = {
|
|
915
|
+
("export", None): _cmd_export,
|
|
916
|
+
("review", None): _cmd_review,
|
|
917
|
+
("merge", None): _cmd_merge,
|
|
918
|
+
("providers", None): _cmd_providers,
|
|
919
|
+
("setup", None): _cmd_setup,
|
|
920
|
+
("account", "add"): _cmd_account_add,
|
|
921
|
+
("account", "set"): _cmd_account_set,
|
|
922
|
+
("account", "ls"): _cmd_account_ls,
|
|
923
|
+
("account", "rm"): _cmd_account_rm,
|
|
924
|
+
("plugin", "add"): _cmd_plugin_add,
|
|
925
|
+
("plugin", "ls"): _cmd_plugin_ls,
|
|
926
|
+
("plugin", "rm"): _cmd_plugin_rm,
|
|
927
|
+
("plugin", "enable"): _cmd_plugin_enable,
|
|
928
|
+
("plugin", "disable"): _cmd_plugin_enable,
|
|
929
|
+
("plugin", "update"): _cmd_plugin_update,
|
|
930
|
+
("update", None): _cmd_update,
|
|
931
|
+
("import", None): _cmd_import,
|
|
932
|
+
("ls", None): _cmd_ls,
|
|
933
|
+
("show", None): _cmd_show,
|
|
934
|
+
("find", None): _cmd_find,
|
|
935
|
+
("install", None): _cmd_install,
|
|
936
|
+
("metadata", None): _cmd_metadata,
|
|
937
|
+
("match", None): _cmd_match,
|
|
938
|
+
("acquire", None): _cmd_acquire,
|
|
939
|
+
("download", None): _cmd_download,
|
|
940
|
+
("runners", None): _cmd_runners,
|
|
941
|
+
("config", None): _cmd_config,
|
|
942
|
+
("game", "show"): _cmd_game_show,
|
|
943
|
+
("game", "exes"): _cmd_game_exes,
|
|
944
|
+
("game", "set"): _cmd_game_set,
|
|
945
|
+
("launch", None): _cmd_launch,
|
|
946
|
+
("tui", None): _cmd_tui,
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
|
|
950
|
+
def _run(parser: argparse.ArgumentParser, args: argparse.Namespace) -> int:
|
|
951
|
+
handler = _HANDLERS[(args.command, getattr(args, "account_command", None) or getattr(args, "game_command", None) or getattr(args, "plugin_command", None))]
|
|
952
|
+
return _execute(args.json, lambda: handler(args))
|
|
953
|
+
|
|
954
|
+
|
|
955
|
+
def _execute(as_json: bool, call: Any) -> int:
|
|
956
|
+
status = 0
|
|
957
|
+
try:
|
|
958
|
+
outcome = call()
|
|
959
|
+
data, human = outcome[0], outcome[1]
|
|
960
|
+
if len(outcome) == 3:
|
|
961
|
+
status = outcome[2]
|
|
962
|
+
except LudexError as exc:
|
|
963
|
+
error = exc
|
|
964
|
+
except PermissionError as exc:
|
|
965
|
+
error = LudexError("state_unavailable", str(exc))
|
|
966
|
+
else:
|
|
967
|
+
if as_json:
|
|
968
|
+
_emit_json(True, data)
|
|
969
|
+
else:
|
|
970
|
+
if human:
|
|
971
|
+
print(human)
|
|
972
|
+
return status
|
|
973
|
+
if as_json:
|
|
974
|
+
_emit_json(False, error=error)
|
|
975
|
+
else:
|
|
976
|
+
print(f"error: {error.message}", file=sys.stderr)
|
|
977
|
+
return 1
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
def _plugin_command(argv: list[str]) -> int | None:
|
|
981
|
+
"""Run ``ludex <provider> <command> ...`` when the first word names a provider with commands."""
|
|
982
|
+
as_json = bool(argv) and argv[0] == "--json"
|
|
983
|
+
words = argv[1:] if as_json else argv
|
|
984
|
+
if not words or words[0].startswith("-") or words[0] in {key[0] for key in _HANDLERS}:
|
|
985
|
+
return None
|
|
986
|
+
providers, _ = load_providers()
|
|
987
|
+
provider = providers.get(words[0])
|
|
988
|
+
if provider is None or not provider.commands:
|
|
989
|
+
return None
|
|
990
|
+
|
|
991
|
+
def call() -> tuple[object, str]:
|
|
992
|
+
commands = {c.name: c for c in provider.commands}
|
|
993
|
+
if len(words) < 2 or words[1] not in commands:
|
|
994
|
+
raise LudexError("unknown_command", f"{provider.name} commands: {', '.join(sorted(commands))}")
|
|
995
|
+
command = commands[words[1]]
|
|
996
|
+
paths = state_paths()
|
|
997
|
+
with writer_lock(paths.import_lock):
|
|
998
|
+
conn = connect(paths.database)
|
|
999
|
+
try:
|
|
1000
|
+
result = command.run(CommandContext(conn, providers, get_values(paths, provider.name)), words[2:])
|
|
1001
|
+
except (LudexError, SystemExit):
|
|
1002
|
+
raise
|
|
1003
|
+
except Exception as exc:
|
|
1004
|
+
raise LudexError("command_failed", f"{provider.name} {command.name} failed ({type(exc).__name__})") from None
|
|
1005
|
+
finally:
|
|
1006
|
+
conn.close()
|
|
1007
|
+
if not isinstance(result, CommandResult):
|
|
1008
|
+
raise LudexError("command_failed", f"{provider.name} {command.name} returned an invalid result")
|
|
1009
|
+
return result.data, result.text
|
|
1010
|
+
|
|
1011
|
+
previous_umask = os.umask(0o077)
|
|
1012
|
+
try:
|
|
1013
|
+
return _execute(as_json, call)
|
|
1014
|
+
except SystemExit as exc: # the plugin's own argparse: -h exits 0, usage errors 2
|
|
1015
|
+
return exc.code if isinstance(exc.code, int) else 2
|
|
1016
|
+
finally:
|
|
1017
|
+
os.umask(previous_umask)
|
|
1018
|
+
|
|
1019
|
+
|
|
1020
|
+
def main(argv: list[str] | None = None) -> int:
|
|
1021
|
+
handled = _plugin_command(list(sys.argv[1:] if argv is None else argv))
|
|
1022
|
+
if handled is not None:
|
|
1023
|
+
return handled
|
|
1024
|
+
parser = _parser()
|
|
1025
|
+
args = parser.parse_args(argv)
|
|
1026
|
+
if args.command is None:
|
|
1027
|
+
parser.print_help(sys.stderr)
|
|
1028
|
+
return 2
|
|
1029
|
+
if args.command == "account" and args.account_command is None:
|
|
1030
|
+
parser.error("account requires an action: add, set, ls or rm")
|
|
1031
|
+
if args.command == "plugin" and args.plugin_command is None:
|
|
1032
|
+
parser.error("plugin requires an action: add, ls, rm, enable, disable or update")
|
|
1033
|
+
if args.command == "game" and args.game_command is None:
|
|
1034
|
+
parser.error("game requires an action: show or set")
|
|
1035
|
+
if args.command == "import" and not args.all and not args.account:
|
|
1036
|
+
parser.error("import requires an account name or --all")
|
|
1037
|
+
if args.command == "import" and args.all and args.account:
|
|
1038
|
+
parser.error("import takes an account name or --all, not both")
|
|
1039
|
+
previous_umask = os.umask(0o077)
|
|
1040
|
+
try:
|
|
1041
|
+
return _run(parser, args)
|
|
1042
|
+
finally:
|
|
1043
|
+
os.umask(previous_umask)
|