Coverage for src/scixplorer/cli/__init__.py: 92%

171 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-18 23:06 +0000

1"""The ``scix`` command: search SciX from the terminal in plain words. 

2 

3:: 

4 

5 scix Kewley 2008 # an author and a year 

6 scix exoplanets 2026 # a UAT concept and a year 

7 scix ApJ 608 119 # a journal, a volume and a page 

8 

9:func:`~scixplorer.cli.interpret.interpret` reads the words; in a terminal the 

10results open in a browser you move through with the keyboard, and anywhere else 

11(a pipe, or with ``--plain``) they are printed. 

12""" 

13 

14from __future__ import annotations 

15 

16import argparse 

17import json 

18import os 

19import shutil 

20import sys 

21from collections.abc import Sequence 

22from typing import Any, TextIO 

23 

24from .. import __version__ 

25from .._config import config 

26from ..exceptions import SciXError 

27from ..models.document import Document 

28from ..query import Sender 

29from .interpret import Interpretation, Reading, interpret 

30from .output import SORTS, Style, explanation, found_line, listing, page_url 

31from .session import Found, Session 

32 

33__all__ = ["Interpretation", "Reading", "interpret", "main"] 

34 

35#: The ``--format`` values sent to the export service. 

36EXPORT_FORMATS = ( 

37 "bibtex", "bibtexabs", "aastex", "ads", "endnote", "medlars", "procite", "refworks", "ris", 

38 "icarus", "mnras", "soph", "ieee", "dcxml", "refxml", "refabsxml", "votable", 

39) # fmt: skip 

40 

41FORMATS = ("list", "bibcodes", "json", *EXPORT_FORMATS) 

42 

43_EPILOG = """\ 

44how words are read: 

45 Kewley 2008 an author and a year (capitalised words are surnames) 

46 Kewley et al. 2019 the first author; so is ^Kewley 

47 "Kewley, L." 2015-2020 an author with initials, and a range of years 

48 exoplanets since 2020 a Unified Astronomy Thesaurus concept 

49 ApJ 608 119 a journal, a volume and a page 

50 2019ApJ...880...16K a bibcode; a DOI, arXiv or ORCID identifier works too 

51 "dark matter halo" a phrase in the title, abstract or keywords 

52 title:gaia a:Kewley a named field (any document field, or a: t: j: y:) 

53 citations:<bibcode> what cites it; also references: trending: reviews: 

54 

55Run `scix --explain <words>` to see how a search is read without sending it. 

56""" 

57 

58 

59def _limit(value: str) -> int | None: 

60 if value.lower() == "all": 

61 return None 

62 try: 

63 number = int(value) 

64 except ValueError: 

65 raise argparse.ArgumentTypeError(f"expected a number or 'all', not {value!r}") from None 

66 if number < 1: 

67 raise argparse.ArgumentTypeError("must be at least 1") 

68 return number 

69 

70 

71def _parser() -> argparse.ArgumentParser: 

72 parser = argparse.ArgumentParser( 

73 prog="scix", 

74 description="Search SciX (the successor to NASA/ADS) in plain words.", 

75 epilog=_EPILOG, 

76 formatter_class=argparse.RawDescriptionHelpFormatter, 

77 ) 

78 parser.add_argument("words", nargs="*", metavar="WORD", help="what to search for") 

79 parser.add_argument("-n", "--limit", type=_limit, default=10, metavar="N", help="print N documents, or 'all' (default: 10)") 

80 parser.add_argument("-s", "--sort", choices=tuple(SORTS), default=None, help="the order of the results (default: citations if the search names a year, else date)") 

81 parser.add_argument("-r", "--refereed", action="store_true", help="only refereed documents") 

82 parser.add_argument("-c", "--collection", metavar="NAME", help="only one collection, such as astronomy") 

83 parser.add_argument("-q", "--query", action="store_true", help="send the words as a Solr query, without reading them") 

84 parser.add_argument("-x", "--explain", action="store_true", help="show how the words are read, and send nothing") 

85 parser.add_argument("-p", "--plain", action="store_true", help="print the results instead of browsing them") 

86 parser.add_argument("-o", "--open", action="store_true", help="open the first result in your web browser") 

87 parser.add_argument("-f", "--format", choices=FORMATS, default=None, metavar="FORMAT", help="print the results as: " + ", ".join(FORMATS)) 

88 parser.add_argument("--bibtex", dest="format", action="store_const", const="bibtex", help="the same as --format bibtex") 

89 parser.add_argument("--json", dest="format", action="store_const", const="json", help="the same as --format json") 

90 parser.add_argument("--bibcodes", dest="format", action="store_const", const="bibcodes", help="the same as --format bibcodes") 

91 parser.add_argument("--refresh-data", action="store_true", help="download the journal list, affiliations, thesaurus and gazetteer, then stop") 

92 parser.add_argument("--mcp", action="store_true", help="run as a Model Context Protocol server on standard input and output (needs scixplorer[mcp])") 

93 parser.add_argument("--read-only", action="store_true", help="with --mcp: leave out the tools that create, change or delete libraries") 

94 parser.add_argument("--version", action="version", version=f"scix {__version__}") 

95 return parser 

96 

97 

98def main( 

99 argv: Sequence[str] | None = None, 

100 *, 

101 client: Sender | None = None, 

102 stdin: TextIO | None = None, 

103 stdout: TextIO | None = None, 

104 stderr: TextIO | None = None, 

105) -> int: 

106 """Run the ``scix`` command and return its exit status. 

107 

108 0 means documents were found (or nothing had to be searched), 1 that none 

109 matched, and 2 that the search could not be run. 

110 

111 :param argv: the arguments (default: those of the process). 

112 :param client: the client to search with (default: the default client). 

113 """ 

114 stdin, stdout, stderr = stdin or sys.stdin, stdout or sys.stdout, stderr or sys.stderr 

115 parser = _parser() 

116 args = parser.parse_intermixed_args(argv) 

117 try: 

118 return _run(args, parser, client, stdin, stdout, stderr) 

119 except KeyboardInterrupt: 

120 return 130 

121 except BrokenPipeError: 

122 return 0 

123 except SciXError as error: 

124 print(f"scix: {error}", file=stderr) 

125 return 2 

126 

127 

128def _is_terminal(stream: TextIO) -> bool: 

129 try: 

130 return stream.isatty() 

131 except (AttributeError, ValueError): 

132 return False 

133 

134 

135def _style(stream: TextIO) -> Style: 

136 plain = "NO_COLOR" in os.environ or os.environ.get("TERM") == "dumb" 

137 return Style(_is_terminal(stream) and not plain) 

138 

139 

140def _refresh(stdout: TextIO) -> int: 

141 from .. import data 

142 

143 results = data.refresh() 

144 for result in results: 

145 print(f"{result.name}: {'updated' if result.ok else 'failed'}{' - ' + result.message if result.message else ''}", file=stdout) 

146 return 0 if all(result.ok for result in results) else 2 

147 

148 

149def _read(args: argparse.Namespace) -> Interpretation: 

150 words: list[str] = args.words 

151 if args.query: 

152 text = " ".join(words) 

153 interpretation = Interpretation(text, (Reading("query", text, text, Document.raw(text)),)) 

154 else: 

155 interpretation = interpret(words) 

156 if args.refereed: 

157 refereed = Reading("property", "--refereed", "refereed", Document.property == "refereed") 

158 interpretation = Interpretation(interpretation.text, (*interpretation.readings, refereed), interpretation.notes) 

159 return interpretation 

160 

161 

162def default_sort(interpretation: Interpretation) -> str: 

163 """The order to show a search in when none is asked for. 

164 

165 Newest first, unless the search names a year: then the dates say little, 

166 and the most cited documents of those years come first. 

167 """ 

168 return "citations" if any(reading.kind == "year" for reading in interpretation.readings) else "date" 

169 

170 

171def _run( 

172 args: argparse.Namespace, 

173 parser: argparse.ArgumentParser, 

174 client: Sender | None, 

175 stdin: TextIO, 

176 stdout: TextIO, 

177 stderr: TextIO, 

178) -> int: 

179 if args.refresh_data: 

180 return _refresh(stdout) 

181 if args.collection: 

182 config.collection = args.collection 

183 if args.mcp: 

184 return _serve(client, args.read_only, stderr) 

185 if args.read_only: 

186 parser.error("--read-only goes with --mcp") 

187 session = Session(client) 

188 browse = ( 

189 not (args.plain or args.open or args.explain or args.format) 

190 and _is_terminal(stdin) 

191 and _is_terminal(stdout) 

192 and _can_browse() 

193 ) 

194 if not any(word.strip() for word in args.words): 

195 if browse: 195 ↛ 196line 195 didn't jump to line 196 because the condition on line 195 was never true

196 return _browse(session, None, args.sort, stdin, stdout) 

197 parser.print_usage(stderr) 

198 print("scix: say what to search for, such as: scix Kewley 2008", file=stderr) 

199 return 2 

200 interpretation = _read(args) 

201 sort: str = args.sort or default_sort(interpretation) 

202 if args.explain: 

203 from ..search import to_solr 

204 

205 q = to_solr(session.query(interpretation, sort)) 

206 print("\n".join(explanation(interpretation, q, sort, _style(stdout))), file=stdout) 

207 return 0 

208 if browse: 208 ↛ 209line 208 didn't jump to line 209 because the condition on line 208 was never true

209 return _browse(session, interpretation, args.sort, stdin, stdout) 

210 return _print(session, interpretation, sort, args, stdout, stderr) 

211 

212 

213def _serve(client: Sender | None, read_only: bool, stderr: TextIO) -> int: 

214 """Run the MCP server until its client disconnects.""" 

215 try: 

216 from .. import mcp_server 

217 except ImportError as error: 

218 print(f"scix: --mcp needs the mcp package, version 2 or later: install scixplorer[mcp] ({error})", file=stderr) 

219 return 2 

220 served: Any = client 

221 mcp_server.serve(served, read_only=read_only) 

222 return 0 

223 

224 

225def _can_browse() -> bool: 

226 try: 

227 import termios # noqa: F401 

228 except ImportError: # Windows 

229 return False 

230 return os.environ.get("TERM") != "dumb" 

231 

232 

233def _browse( 

234 session: Session, interpretation: Interpretation | None, sort: str | None, stdin: TextIO, stdout: TextIO 

235) -> int: 

236 from . import tui 

237 

238 browser = tui.Browser(session, sort=sort, style=Style("NO_COLOR" not in os.environ)) 

239 return tui.run(browser, interpretation, stdin=stdin, stdout=stdout) 

240 

241 

242def _print( 

243 session: Session, interpretation: Interpretation, sort: str, args: argparse.Namespace, stdout: TextIO, stderr: TextIO 

244) -> int: 

245 output = args.format or "list" 

246 # The list carries its own heading; any other format keeps standard output for the data alone. 

247 heading = stdout if output == "list" else stderr 

248 style = _style(heading) 

249 # Say how the search was read before sending it: the answer takes a moment to arrive. 

250 print(style.accent(str(interpretation)), file=heading, flush=True) 

251 for note in interpretation.notes: 

252 print(style.warn(note), file=stderr) 

253 found = session.find(interpretation, sort, limit=1 if args.open and not args.format else args.limit) 

254 if found.widened: 

255 print(style.warn(f"Nothing matched, so searched for: {found.interpretation}"), file=heading) 

256 if not found.total: 

257 print("No documents.", file=heading) 

258 return 1 

259 print(style.dim(found_line(found.total, len(found.documents), sort)), file=heading) 

260 if args.open: 

261 _open(found, heading) 

262 if not args.format: 262 ↛ 264line 262 didn't jump to line 264 because the condition on line 262 was always true

263 return 0 

264 if output == "list": 

265 width = min(shutil.get_terminal_size((88, 24)).columns, 100) 

266 print("\n" + "\n".join(listing(found.documents, width=width, style=_style(stdout))), file=stdout) 

267 elif output == "bibcodes": 

268 print("\n".join(document.bibcode for document in found.documents if document.bibcode), file=stdout) 

269 elif output == "json": 

270 rows: list[dict[str, Any]] = [document.to_dict() for document in found.documents] 

271 print(json.dumps(rows, indent=2, ensure_ascii=False), file=stdout) 

272 else: 

273 from ..services import export 

274 

275 text: str = getattr(export, output)(found.documents, client=session.client) 

276 print(text.rstrip("\n"), file=stdout) 

277 return 0 

278 

279 

280def _open(found: Found, heading: TextIO) -> None: 

281 import webbrowser 

282 

283 url = page_url(found.documents[0]) 

284 if url is not None: 284 ↛ exitline 284 didn't return from function '_open' because the condition on line 284 was always true

285 print(url, file=heading) 

286 webbrowser.open(url)