flowiq 0.1.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.
- flowiq/__init__.py +64 -0
- flowiq/__main__.py +6 -0
- flowiq/_version.py +1 -0
- flowiq/cli.py +429 -0
- flowiq/client.py +752 -0
- flowiq/errors.py +114 -0
- flowiq/py.typed +0 -0
- flowiq/text.py +47 -0
- flowiq/types.py +255 -0
- flowiq-0.1.0.dist-info/METADATA +137 -0
- flowiq-0.1.0.dist-info/RECORD +15 -0
- flowiq-0.1.0.dist-info/WHEEL +5 -0
- flowiq-0.1.0.dist-info/entry_points.txt +2 -0
- flowiq-0.1.0.dist-info/licenses/LICENSE +21 -0
- flowiq-0.1.0.dist-info/top_level.txt +1 -0
flowiq/__init__.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
"""Client for the FlowIQ REST API. Standard library only.
|
|
2
|
+
|
|
3
|
+
from flowiq import FlowIQ
|
|
4
|
+
|
|
5
|
+
fq = FlowIQ() # key from FLOWIQ_API_KEY
|
|
6
|
+
for s in fq.search("protocol:mongodb country:BR", limit=500):
|
|
7
|
+
print(s["ip"], s["port"], s["last_seen"])
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from ._version import __version__
|
|
11
|
+
from .client import (
|
|
12
|
+
DEFAULT_BASE_URL,
|
|
13
|
+
MAX_BREAKDOWN_BUCKETS,
|
|
14
|
+
MAX_DOMAIN_NAMES,
|
|
15
|
+
MAX_EXPORT_ROWS,
|
|
16
|
+
MAX_SEARCH_ROWS,
|
|
17
|
+
DomainNames,
|
|
18
|
+
FlowIQ,
|
|
19
|
+
SearchResults,
|
|
20
|
+
)
|
|
21
|
+
from .errors import (
|
|
22
|
+
APIError,
|
|
23
|
+
BadRequest,
|
|
24
|
+
ConfigError,
|
|
25
|
+
ConnectionFailed,
|
|
26
|
+
ExportFailed,
|
|
27
|
+
FlowIQError,
|
|
28
|
+
Forbidden,
|
|
29
|
+
Gone,
|
|
30
|
+
IncompleteResponse,
|
|
31
|
+
NotFound,
|
|
32
|
+
NotReady,
|
|
33
|
+
RateLimited,
|
|
34
|
+
ServerError,
|
|
35
|
+
ServiceUnavailable,
|
|
36
|
+
Unauthorized,
|
|
37
|
+
)
|
|
38
|
+
|
|
39
|
+
__all__ = [
|
|
40
|
+
"__version__",
|
|
41
|
+
"FlowIQ",
|
|
42
|
+
"SearchResults",
|
|
43
|
+
"DomainNames",
|
|
44
|
+
"DEFAULT_BASE_URL",
|
|
45
|
+
"MAX_SEARCH_ROWS",
|
|
46
|
+
"MAX_BREAKDOWN_BUCKETS",
|
|
47
|
+
"MAX_DOMAIN_NAMES",
|
|
48
|
+
"MAX_EXPORT_ROWS",
|
|
49
|
+
"FlowIQError",
|
|
50
|
+
"ConfigError",
|
|
51
|
+
"ConnectionFailed",
|
|
52
|
+
"IncompleteResponse",
|
|
53
|
+
"ExportFailed",
|
|
54
|
+
"APIError",
|
|
55
|
+
"BadRequest",
|
|
56
|
+
"Unauthorized",
|
|
57
|
+
"Forbidden",
|
|
58
|
+
"NotFound",
|
|
59
|
+
"NotReady",
|
|
60
|
+
"Gone",
|
|
61
|
+
"RateLimited",
|
|
62
|
+
"ServerError",
|
|
63
|
+
"ServiceUnavailable",
|
|
64
|
+
]
|
flowiq/__main__.py
ADDED
flowiq/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.1.0"
|
flowiq/cli.py
ADDED
|
@@ -0,0 +1,429 @@
|
|
|
1
|
+
"""The flowiq command.
|
|
2
|
+
|
|
3
|
+
The key comes from FLOWIQ_API_KEY and from nowhere else: an argument would be readable by
|
|
4
|
+
every other process on the machine and kept in the shell's history.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import csv
|
|
11
|
+
import io
|
|
12
|
+
import itertools
|
|
13
|
+
import os
|
|
14
|
+
import sys
|
|
15
|
+
from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, TextIO
|
|
16
|
+
|
|
17
|
+
from .text import dumps, one_line, spreadsheet_safe
|
|
18
|
+
from ._version import __version__
|
|
19
|
+
from .client import (
|
|
20
|
+
DEFAULT_BASE_URL,
|
|
21
|
+
EXPORT_FORMATS,
|
|
22
|
+
MAX_BREAKDOWN_BUCKETS,
|
|
23
|
+
MAX_EXPORT_ROWS,
|
|
24
|
+
FlowIQ,
|
|
25
|
+
)
|
|
26
|
+
from .errors import FlowIQError, NotReady
|
|
27
|
+
|
|
28
|
+
# A call that can cost more credits than this is described and not run without --yes.
|
|
29
|
+
CONFIRM_ABOVE = 1000
|
|
30
|
+
|
|
31
|
+
OUTPUTS = ("json", "ndjson", "csv", "table")
|
|
32
|
+
SEARCH_COLUMNS = ("ip", "port", "protocol", "server", "version", "title", "country", "asn", "org", "last_seen")
|
|
33
|
+
HOST_COLUMNS = ("port", "transport", "protocol", "server", "version", "title", "state", "last_seen")
|
|
34
|
+
DOMAIN_COLUMNS = ("name", "addresses", "last_resolved", "first_seen", "sources")
|
|
35
|
+
|
|
36
|
+
_SAMPLE = 200 # rows a table is sized from
|
|
37
|
+
_WIDEST = 48 # the widest a table cell is drawn
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class NeedsYes(Exception):
|
|
41
|
+
"""The call was described and not made."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
45
|
+
args = _parser().parse_args(argv)
|
|
46
|
+
out, err = sys.stdout, sys.stderr
|
|
47
|
+
for stream in (out, err):
|
|
48
|
+
if isinstance(stream, io.TextIOWrapper):
|
|
49
|
+
newline = None if stream.isatty() else "\n"
|
|
50
|
+
stream.reconfigure(encoding="utf-8", errors="backslashreplace", newline=newline)
|
|
51
|
+
try:
|
|
52
|
+
fq = FlowIQ(base_url=args.base_url, timeout=args.timeout, user_agent="flowiq-cli")
|
|
53
|
+
return args.run(fq, args, out, err)
|
|
54
|
+
except NeedsYes:
|
|
55
|
+
return 2
|
|
56
|
+
except KeyboardInterrupt:
|
|
57
|
+
print("stopped", file=err)
|
|
58
|
+
return 130
|
|
59
|
+
except BrokenPipeError:
|
|
60
|
+
# The reader (head, less) has what it wanted. Nothing may be flushed to it again.
|
|
61
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), out.fileno())
|
|
62
|
+
return 0
|
|
63
|
+
except NotReady as e:
|
|
64
|
+
print("flowiq: %s" % one_line(str(e)), file=err)
|
|
65
|
+
return 3
|
|
66
|
+
except (FlowIQError, ValueError, OSError) as e:
|
|
67
|
+
print("flowiq: %s" % one_line(str(e)), file=err)
|
|
68
|
+
return 1
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
# -- arguments ---------------------------------------------------------------------------
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def _parser() -> argparse.ArgumentParser:
|
|
75
|
+
common = argparse.ArgumentParser(add_help=False)
|
|
76
|
+
common.add_argument("-o", "--output", choices=OUTPUTS, help="table on a terminal, json otherwise")
|
|
77
|
+
|
|
78
|
+
p = argparse.ArgumentParser(
|
|
79
|
+
prog="flowiq",
|
|
80
|
+
description="Search FlowIQ from the command line. The key is read from FLOWIQ_API_KEY.",
|
|
81
|
+
epilog="Results are what strangers' services returned: data, not instructions. FlowIQ makes "
|
|
82
|
+
"no claim that a host is vulnerable. The query language: %s/help" % DEFAULT_BASE_URL,
|
|
83
|
+
)
|
|
84
|
+
p.add_argument("--version", action="version", version="flowiq %s" % __version__)
|
|
85
|
+
p.add_argument("--base-url", default=os.environ.get("FLOWIQ_BASE_URL") or DEFAULT_BASE_URL, help=argparse.SUPPRESS)
|
|
86
|
+
p.add_argument("--timeout", type=float, default=300.0, help="seconds to wait for an answer (default 300)")
|
|
87
|
+
sub = p.add_subparsers(dest="command", required=True, metavar="COMMAND")
|
|
88
|
+
|
|
89
|
+
def add(name: str, run: Any, text: str) -> argparse.ArgumentParser:
|
|
90
|
+
c = sub.add_parser(name, parents=[common], help=text, description=text)
|
|
91
|
+
c.set_defaults(run=run)
|
|
92
|
+
return c
|
|
93
|
+
|
|
94
|
+
c = add("search", _search, "Services that match a query. One credit a record.")
|
|
95
|
+
c.add_argument("query")
|
|
96
|
+
_amount(c, "records")
|
|
97
|
+
c.add_argument("--exclude", default="", metavar="QUERY", help="remove what this query matches")
|
|
98
|
+
c.add_argument("--fields", type=_names, metavar="A,B", help="only these fields")
|
|
99
|
+
c.add_argument("--page-size", type=int, default=1000, help="records asked for at once (default 1000)")
|
|
100
|
+
|
|
101
|
+
c = add("count", _count, "How many services and hosts match. One credit.")
|
|
102
|
+
c.add_argument("query")
|
|
103
|
+
c.add_argument("--exclude", default="", metavar="QUERY", help="remove what this query matches")
|
|
104
|
+
|
|
105
|
+
c = add("host", _host, "Everything held about an address. One credit a service on it.")
|
|
106
|
+
c.add_argument("ip", nargs="+")
|
|
107
|
+
c.add_argument("--no-content", action="store_true", help="leave out the response text (same price)")
|
|
108
|
+
|
|
109
|
+
c = add("domain", _domain, "Every name held under a domain. One credit a name.")
|
|
110
|
+
c.add_argument("name")
|
|
111
|
+
_amount(c, "names")
|
|
112
|
+
c.add_argument("--contains", default="", metavar="TEXT", help="only names with this in the part above the domain")
|
|
113
|
+
c.add_argument("--resolved", action="store_true", help="only names that resolved when we looked")
|
|
114
|
+
|
|
115
|
+
c = add("breakdown", _breakdown, "The most common values of a field. One credit a value.")
|
|
116
|
+
c.add_argument("field", help="a name from: flowiq fields")
|
|
117
|
+
c.add_argument("query", nargs="?", default="*")
|
|
118
|
+
c.add_argument("--limit", type=int, default=20, help="values (default 20, at most %d)" % MAX_BREAKDOWN_BUCKETS)
|
|
119
|
+
|
|
120
|
+
c = add("export", _export, "A large result as one file, written on the server. One credit a record.")
|
|
121
|
+
c.add_argument("query", nargs="?")
|
|
122
|
+
c.add_argument("-O", "--out", required=True, metavar="FILE")
|
|
123
|
+
c.add_argument("--limit", type=int, default=100, help="records at most (default 100, at most %d)" % MAX_EXPORT_ROWS)
|
|
124
|
+
c.add_argument("--format", choices=EXPORT_FORMATS, default="ndjson")
|
|
125
|
+
c.add_argument("--exclude", default="", metavar="QUERY", help="remove what this query matches")
|
|
126
|
+
c.add_argument("--fields", type=_names, metavar="A,B", help="only these fields, in this order")
|
|
127
|
+
c.add_argument("--resume", type=int, metavar="ID", help="wait for and download an export already started (free)")
|
|
128
|
+
c.add_argument("--force", action="store_true", help="replace FILE if it exists")
|
|
129
|
+
c.add_argument("--yes", action="store_true", help="run it although it costs more than %s credits" % _n(CONFIRM_ABOVE))
|
|
130
|
+
|
|
131
|
+
add("account", _account, "What the key may still spend. Free.")
|
|
132
|
+
add("fields", _fields, "The fields a breakdown accepts. Free.")
|
|
133
|
+
return p
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _amount(c: argparse.ArgumentParser, what: str) -> None:
|
|
137
|
+
g = c.add_mutually_exclusive_group()
|
|
138
|
+
g.add_argument("--limit", type=int, default=100, help="%s at most (default 100)" % what)
|
|
139
|
+
g.add_argument("--all", action="store_true", help="all of them (one credit to count them first)")
|
|
140
|
+
c.add_argument("--yes", action="store_true", help="run it although it costs more than %s credits" % _n(CONFIRM_ABOVE))
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _names(text: str) -> List[str]:
|
|
144
|
+
out = [x.strip() for x in text.split(",") if x.strip()]
|
|
145
|
+
if not out:
|
|
146
|
+
raise argparse.ArgumentTypeError("no field names in %r" % text)
|
|
147
|
+
return out
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
# -- what a call will cost ---------------------------------------------------------------
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _n(value: int) -> str:
|
|
154
|
+
return "{:,}".format(value)
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def _confirm(fq: FlowIQ, most: int, what: str, yes: bool, err: TextIO, how: str = "up to") -> None:
|
|
158
|
+
"""Say what a large call costs, and stop unless --yes was given. Both reads are free."""
|
|
159
|
+
if most <= CONFIRM_ABOVE:
|
|
160
|
+
return
|
|
161
|
+
a = fq.account()
|
|
162
|
+
left = "This key is not charged." if a.get("unlimited") else "You have %s left until %s." % (
|
|
163
|
+
_n(a["credits_remaining"]), a["resets_at"])
|
|
164
|
+
print(
|
|
165
|
+
"This returns %s %s %s and costs the same number of credits. %s"
|
|
166
|
+
% (how, _n(most), what, left),
|
|
167
|
+
file=err,
|
|
168
|
+
)
|
|
169
|
+
if not yes:
|
|
170
|
+
print("Add --yes to run it.", file=err)
|
|
171
|
+
raise NeedsYes
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# -- commands ----------------------------------------------------------------------------
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _search(fq: FlowIQ, args: argparse.Namespace, out: TextIO, err: TextIO) -> int:
|
|
178
|
+
limit: Optional[int] = args.limit
|
|
179
|
+
if args.all:
|
|
180
|
+
limit = None
|
|
181
|
+
total = fq.count(args.query, exclude=args.exclude)["total_found"]
|
|
182
|
+
_confirm(fq, total, "services", args.yes, err, "about")
|
|
183
|
+
else:
|
|
184
|
+
_confirm(fq, args.limit, "services", args.yes, err)
|
|
185
|
+
output = _output(args, out, "json")
|
|
186
|
+
fields = args.fields
|
|
187
|
+
if fields is None and output == "table":
|
|
188
|
+
fields = list(SEARCH_COLUMNS)
|
|
189
|
+
rows = fq.search(args.query, limit, exclude=args.exclude, fields=fields, page_size=args.page_size)
|
|
190
|
+
rows.first_page()
|
|
191
|
+
_notes(rows.notes, err)
|
|
192
|
+
if rows.content_truncated:
|
|
193
|
+
print("note: a text term matched more than is carried, so this is part of the result; narrow the query", file=err)
|
|
194
|
+
if rows.where_truncated:
|
|
195
|
+
print("note: the hosts of the where clause were cut, so this is part of the result", file=err)
|
|
196
|
+
_rows(rows, output, fields, out)
|
|
197
|
+
if output == "table":
|
|
198
|
+
print("%s of %s" % (_n(rows.fetched), _n(rows.total_found or 0)), file=err)
|
|
199
|
+
return 0
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _count(fq: FlowIQ, args: argparse.Namespace, out: TextIO, err: TextIO) -> int:
|
|
203
|
+
c = fq.count(args.query, exclude=args.exclude)
|
|
204
|
+
_notes(c["notes"], err)
|
|
205
|
+
_object(c, _output(args, out, "json"), ("total_found", "hosts", "honeypots"), out)
|
|
206
|
+
return 0
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _host(fq: FlowIQ, args: argparse.Namespace, out: TextIO, err: TextIO) -> int:
|
|
210
|
+
output = _output(args, out, "json")
|
|
211
|
+
found = [fq.host(ip, content=not args.no_content) for ip in args.ip]
|
|
212
|
+
if output == "json":
|
|
213
|
+
print(dumps(found[0] if len(found) == 1 else found, indent=2), file=out)
|
|
214
|
+
return 0
|
|
215
|
+
if output == "ndjson":
|
|
216
|
+
for h in found:
|
|
217
|
+
print(dumps(h, compact=True), file=out)
|
|
218
|
+
return 0
|
|
219
|
+
rows = []
|
|
220
|
+
for h in found:
|
|
221
|
+
if not h["found"]:
|
|
222
|
+
print("%s: nothing held" % h["ip"], file=err)
|
|
223
|
+
if h.get("truncated"):
|
|
224
|
+
print("%s: more services than one read returns" % h["ip"], file=err)
|
|
225
|
+
for s in h.get("services") or []:
|
|
226
|
+
state = (s.get("liveness") or {}).get("state", "")
|
|
227
|
+
rows.append({"ip": h["ip"], **s, "state": state})
|
|
228
|
+
cols = (("ip",) if len(found) > 1 else ()) + HOST_COLUMNS
|
|
229
|
+
if output == "csv":
|
|
230
|
+
_csv(iter(rows), ["ip"] + list(HOST_COLUMNS), out)
|
|
231
|
+
return 0
|
|
232
|
+
for h in found:
|
|
233
|
+
if h["found"]:
|
|
234
|
+
where = " ".join(x for x in (h.get("city"), h.get("country")) if x)
|
|
235
|
+
line = [h["ip"], h.get("asn"), h.get("org"), where]
|
|
236
|
+
print(one_line(" ".join(x for x in line if x)), file=out)
|
|
237
|
+
names = [n["name"] for n in (h.get("names") or [])]
|
|
238
|
+
if names:
|
|
239
|
+
more = " and %s more" % _n(len(names) - 8) if len(names) > 8 else ""
|
|
240
|
+
print(one_line("names: " + ", ".join(names[:8]) + more), file=out)
|
|
241
|
+
_table(iter(rows), cols, out)
|
|
242
|
+
return 0
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def _domain(fq: FlowIQ, args: argparse.Namespace, out: TextIO, err: TextIO) -> int:
|
|
246
|
+
limit: Optional[int] = args.limit
|
|
247
|
+
if args.all:
|
|
248
|
+
limit = None
|
|
249
|
+
first = fq.domain_page(args.name, limit=1, contains=args.contains, resolved=args.resolved)
|
|
250
|
+
total = first.get("total")
|
|
251
|
+
how = "at least" if total and total["lower_bound"] else "up to"
|
|
252
|
+
_confirm(fq, total["names"] if total else 0, "names", args.yes, err, how)
|
|
253
|
+
else:
|
|
254
|
+
_confirm(fq, args.limit, "names", args.yes, err)
|
|
255
|
+
output = _output(args, out, "json")
|
|
256
|
+
names = fq.domain(args.name, limit, contains=args.contains, resolved=args.resolved)
|
|
257
|
+
_rows(names, output, None, out, DOMAIN_COLUMNS)
|
|
258
|
+
if output == "table" and names.total:
|
|
259
|
+
more = "more than " if names.total["lower_bound"] else ""
|
|
260
|
+
print("%s of %s%s" % (_n(names.fetched), more, _n(names.total["names"])), file=err)
|
|
261
|
+
return 0
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _breakdown(fq: FlowIQ, args: argparse.Namespace, out: TextIO, err: TextIO) -> int:
|
|
265
|
+
b = fq.breakdown(args.field, args.query, limit=args.limit)
|
|
266
|
+
output = _output(args, out, "json")
|
|
267
|
+
if output == "json":
|
|
268
|
+
print(dumps(b, indent=2), file=out)
|
|
269
|
+
return 0
|
|
270
|
+
buckets: List[Dict[str, Any]] = [dict(x) for x in b["buckets"] or []]
|
|
271
|
+
if output == "table":
|
|
272
|
+
total = b["total"] or 0
|
|
273
|
+
for x in buckets:
|
|
274
|
+
x["share"] = "%.1f%%" % (100.0 * x["count"] / total) if total else ""
|
|
275
|
+
cols = ["key", "count", "share"] + (["name"] if any(x.get("name") for x in buckets) else [])
|
|
276
|
+
_table(iter(buckets), cols, out)
|
|
277
|
+
print("of %s services with a value" % _n(total), file=err)
|
|
278
|
+
return 0
|
|
279
|
+
_rows(iter(buckets), output, ["key", "count", "name"], out)
|
|
280
|
+
return 0
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _export(fq: FlowIQ, args: argparse.Namespace, out: TextIO, err: TextIO) -> int:
|
|
284
|
+
if (args.resume is None) == (args.query is None):
|
|
285
|
+
print("flowiq: give a query, or --resume ID", file=err)
|
|
286
|
+
return 2
|
|
287
|
+
|
|
288
|
+
def status(s: Any) -> None:
|
|
289
|
+
print(
|
|
290
|
+
"export %d: %s, %s of %s" % (s["id"], s["status"], _n(s.get("records_count", 0)), _n(s["requested_rows"])),
|
|
291
|
+
file=err,
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
if args.resume is not None:
|
|
295
|
+
fq.export_wait(args.resume, on_status=status)
|
|
296
|
+
path = fq.export_download(args.resume, args.out, overwrite=args.force)
|
|
297
|
+
else:
|
|
298
|
+
_confirm(fq, args.limit, "records", args.yes, err)
|
|
299
|
+
path = fq.export(
|
|
300
|
+
args.query, args.out, limit=args.limit, format=args.format, fields=args.fields,
|
|
301
|
+
exclude=args.exclude, overwrite=args.force, on_status=status,
|
|
302
|
+
)
|
|
303
|
+
print("%s (%s bytes)" % (path, _n(os.path.getsize(path))), file=err)
|
|
304
|
+
return 0
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
def _account(fq: FlowIQ, args: argparse.Namespace, out: TextIO, err: TextIO) -> int:
|
|
308
|
+
a = fq.account()
|
|
309
|
+
cols = ("plan", "credits_remaining", "credits_total", "searches_remaining", "resets_at", "access_expires")
|
|
310
|
+
_object(a, _output(args, out, "json"), cols, out)
|
|
311
|
+
return 0
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _fields(fq: FlowIQ, args: argparse.Namespace, out: TextIO, err: TextIO) -> int:
|
|
315
|
+
_rows(iter(fq.fields()), _output(args, out, "json"), ["field", "label"], out)
|
|
316
|
+
return 0
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
# -- output ------------------------------------------------------------------------------
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _output(args: argparse.Namespace, out: TextIO, otherwise: str) -> str:
|
|
323
|
+
return args.output or ("table" if out.isatty() else otherwise)
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _notes(notes: Iterable[Any], err: TextIO) -> None:
|
|
327
|
+
for n in notes or []:
|
|
328
|
+
line = "note: %s: %s" % (n["term"], n["message"])
|
|
329
|
+
if n.get("try"):
|
|
330
|
+
line += " Try: %s" % n["try"]
|
|
331
|
+
print(one_line(line), file=err)
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _rows(
|
|
335
|
+
rows: Iterator[Any],
|
|
336
|
+
output: str,
|
|
337
|
+
fields: Optional[Sequence[str]],
|
|
338
|
+
out: TextIO,
|
|
339
|
+
columns: Sequence[str] = SEARCH_COLUMNS,
|
|
340
|
+
) -> None:
|
|
341
|
+
# The first row before the first byte: a refused call must not leave half a file.
|
|
342
|
+
rows = itertools.chain(list(itertools.islice(rows, 1)), rows)
|
|
343
|
+
if output == "ndjson":
|
|
344
|
+
for r in rows:
|
|
345
|
+
print(dumps(r, compact=True), file=out)
|
|
346
|
+
elif output == "json":
|
|
347
|
+
# One array, written as the rows arrive rather than held.
|
|
348
|
+
out.write("[")
|
|
349
|
+
sep = "\n"
|
|
350
|
+
for r in rows:
|
|
351
|
+
out.write(sep + dumps(r))
|
|
352
|
+
sep = ",\n"
|
|
353
|
+
out.write("\n]\n")
|
|
354
|
+
elif output == "csv":
|
|
355
|
+
_csv(rows, fields, out)
|
|
356
|
+
else:
|
|
357
|
+
_table(rows, fields or columns, out)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def _object(value: Any, output: str, columns: Sequence[str], out: TextIO) -> None:
|
|
361
|
+
if output == "csv":
|
|
362
|
+
_csv(iter([value]), columns, out)
|
|
363
|
+
elif output == "table":
|
|
364
|
+
width = max(len(c) for c in columns)
|
|
365
|
+
for c in columns:
|
|
366
|
+
print("%s %s" % (c.ljust(width), _cell(value.get(c))), file=out)
|
|
367
|
+
else:
|
|
368
|
+
print(dumps(value, indent=2 if output == "json" else None, compact=output == "ndjson"), file=out)
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
def _flat(value: Any) -> str:
|
|
372
|
+
if value is None:
|
|
373
|
+
return ""
|
|
374
|
+
if isinstance(value, str):
|
|
375
|
+
return value
|
|
376
|
+
if isinstance(value, bool):
|
|
377
|
+
return "true" if value else "false"
|
|
378
|
+
if isinstance(value, (list, tuple)) and all(isinstance(x, str) for x in value):
|
|
379
|
+
return " ".join(value)
|
|
380
|
+
if isinstance(value, (list, tuple, dict)):
|
|
381
|
+
return dumps(value, compact=True)
|
|
382
|
+
return str(value)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def _cell(value: Any) -> str:
|
|
386
|
+
text = "{:,}".format(value) if isinstance(value, int) and not isinstance(value, bool) and value >= 100000 else _flat(value)
|
|
387
|
+
text = one_line(text)
|
|
388
|
+
return text if len(text) <= _WIDEST else text[: _WIDEST - 1] + "\u2026"
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _csv(rows: Iterator[Any], columns: Optional[Sequence[str]], out: TextIO) -> None:
|
|
392
|
+
w = csv.writer(out, lineterminator="\n")
|
|
393
|
+
tty = out.isatty()
|
|
394
|
+
for i, r in enumerate(rows):
|
|
395
|
+
if i == 0:
|
|
396
|
+
columns = columns or list(r)
|
|
397
|
+
w.writerow(columns)
|
|
398
|
+
cells = []
|
|
399
|
+
for c in columns or []:
|
|
400
|
+
v = r.get(c)
|
|
401
|
+
text = _flat(v)
|
|
402
|
+
if isinstance(v, (str, list)):
|
|
403
|
+
text = spreadsheet_safe(text)
|
|
404
|
+
cells.append(one_line(text) if tty else text)
|
|
405
|
+
w.writerow(cells)
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def _table(rows: Iterator[Any], columns: Sequence[str], out: TextIO) -> None:
|
|
409
|
+
sample: List[List[str]] = []
|
|
410
|
+
for r in rows:
|
|
411
|
+
sample.append([_cell(r.get(c)) for c in columns])
|
|
412
|
+
if len(sample) >= _SAMPLE:
|
|
413
|
+
break
|
|
414
|
+
if not sample:
|
|
415
|
+
return
|
|
416
|
+
widths = [max(len(c), max(len(s[i]) for s in sample)) for i, c in enumerate(columns)]
|
|
417
|
+
|
|
418
|
+
def line(cells: Sequence[str]) -> None:
|
|
419
|
+
out.write(" ".join(x.ljust(w) for x, w in zip(cells, widths)).rstrip() + "\n")
|
|
420
|
+
|
|
421
|
+
line([c.upper() for c in columns])
|
|
422
|
+
for s in sample:
|
|
423
|
+
line(s)
|
|
424
|
+
for r in rows:
|
|
425
|
+
line([_cell(r.get(c)) for c in columns])
|
|
426
|
+
|
|
427
|
+
|
|
428
|
+
if __name__ == "__main__":
|
|
429
|
+
sys.exit(main())
|