| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
""" |
| 4 |
CLI tool for Debian Code Search (https://codesearch.debian.net/) |
| 5 |
|
| 6 |
|
| 7 |
""" |
| 8 |
|
| 9 |
import argparse |
| 10 |
from typing import List, Dict |
| 11 |
import requests |
| 12 |
import sys |
| 13 |
import collections |
| 14 |
import html |
| 15 |
|
| 16 |
import debian_codesearch_client.swagger_client as swclient |
| 17 |
from debian_codesearch_client.swagger_client.rest import ApiException |
| 18 |
|
| 19 |
configuration = swclient.Configuration() |
| 20 |
# API key specifically for https://salsa.debian.org/debian/codesearch-cli, |
| 21 |
# please see https://codesearch.debian.net/apikeys/ for details. |
| 22 |
configuration.api_key["x-dcs-apikey"] = ( |
| 23 |
"MTYxMjczNjE4NnxkTGp0SHdDUnRuUU5WeDh2dGE0dWxtZC1MSFRwQ1o2eUJEdWs1S1VvTjlHYXBYazItUWo3U2daX2pNZ0hHWDVsajJ2TUdhUFNlZ2doU0dIMnFZQk9XNl9zLS1MOU83dTBhNGdnNzV6ZnNDWWVVYXkxVDh0WEJuLTdnUGc9fOH1MJNBLYYnkLVOmnFXFEAkXoHu1SknNqADZuJ2u8nY" |
| 24 |
) |
| 25 |
|
| 26 |
dcs = swclient.SearchApi(swclient.ApiClient(configuration)) |
| 27 |
|
| 28 |
PATHCOLOR = 33 |
| 29 |
DUPE_PATHCOLOR = 36 |
| 30 |
|
| 31 |
dedupe_results: List[swclient.models.search_result.SearchResult] = [] |
| 32 |
|
| 33 |
|
| 34 |
def say(quiet: bool, msg: str) -> None: |
| 35 |
"""Print messages to stderr""" |
| 36 |
if not quiet: |
| 37 |
sys.stderr.write("%s\n" % msg) |
| 38 |
|
| 39 |
|
| 40 |
def is_excluded(chunk, exclusions: list[str]) -> bool: |
| 41 |
for exclude in exclusions: |
| 42 |
if exclude in chunk.path: |
| 43 |
return True |
| 44 |
|
| 45 |
return False |
| 46 |
|
| 47 |
|
| 48 |
def get_result_body(chunk, print_linenum: bool, nocolor: bool) -> str: |
| 49 |
body = "" |
| 50 |
for line in chunk.context_before or (): |
| 51 |
line = html.unescape(line) |
| 52 |
if print_linenum: |
| 53 |
body += " %s\n" % line |
| 54 |
else: |
| 55 |
body += "%s\n" % line |
| 56 |
|
| 57 |
line = html.unescape(chunk.context) |
| 58 |
if print_linenum: |
| 59 |
body += "%7d %s\n" % (chunk.line, line) |
| 60 |
else: |
| 61 |
body += "%s\n" % line |
| 62 |
for line in chunk.context_after or (): |
| 63 |
line = html.unescape(line) |
| 64 |
if print_linenum: |
| 65 |
body += " %s\n" % line |
| 66 |
else: |
| 67 |
body += "%s\n" % line |
| 68 |
|
| 69 |
return body[:-1] # trim trailing line |
| 70 |
|
| 71 |
|
| 72 |
def print_results( |
| 73 |
chunk, |
| 74 |
print_linenum: bool, |
| 75 |
print_only_filenames: bool, |
| 76 |
nocolor: bool |
| 77 |
) -> None: |
| 78 |
"""Print search results""" |
| 79 |
pathline = "path: %s" % chunk.path |
| 80 |
if nocolor: |
| 81 |
print(pathline) |
| 82 |
|
| 83 |
else: |
| 84 |
print("\033[%dm%s\033[0m" % (PATHCOLOR, pathline)) |
| 85 |
|
| 86 |
if print_only_filenames: |
| 87 |
return |
| 88 |
|
| 89 |
print(get_result_body(chunk, print_linenum, nocolor)) |
| 90 |
|
| 91 |
|
| 92 |
def print_dedupe( |
| 93 |
print_linenum: bool, |
| 94 |
print_only_filenames: bool, |
| 95 |
nocolor: bool |
| 96 |
) -> None: |
| 97 |
"""amalgamate duplicate results and print summary""" |
| 98 |
|
| 99 |
bodies = collections.defaultdict(list) |
| 100 |
for chunk in dedupe_results: |
| 101 |
body = get_result_body(chunk, print_linenum, nocolor) |
| 102 |
bodies[body].append(chunk) |
| 103 |
|
| 104 |
for body, chunks in bodies.items(): |
| 105 |
print_results(chunks[0], print_linenum, print_only_filenames, nocolor) |
| 106 |
|
| 107 |
first_path = chunks[0].path |
| 108 |
for chunk in chunks[1:]: |
| 109 |
pathline = "also: %s" % chunk.path |
| 110 |
if nocolor: |
| 111 |
print(pathline) |
| 112 |
|
| 113 |
else: |
| 114 |
for common_suffix in range(1, len(pathline)): |
| 115 |
if pathline[-common_suffix:] != first_path[-common_suffix:]: |
| 116 |
break |
| 117 |
|
| 118 |
i = 1 - common_suffix |
| 119 |
print( |
| 120 |
"\033[%dm%s\033[%dm%s\033[0m" |
| 121 |
% (PATHCOLOR, pathline[:i], DUPE_PATHCOLOR, pathline[i:]) |
| 122 |
) |
| 123 |
else: |
| 124 |
print("") |
| 125 |
|
| 126 |
|
| 127 |
def parse_args() -> argparse.Namespace: |
| 128 |
ap = argparse.ArgumentParser() |
| 129 |
ap.add_argument("searchstring") |
| 130 |
ap.add_argument("--max-results", type=int, default=200) |
| 131 |
ap.add_argument("-q", "--quiet", action="store_true") |
| 132 |
ap.add_argument("-l", "--linenumber", action="store_true") |
| 133 |
ap.add_argument("--nocolor", action="store_true", |
| 134 |
default=not sys.stdout.isatty(), |
| 135 |
help="Do not colorize output") |
| 136 |
ap.add_argument("--color", dest="nocolor", action="store_false", |
| 137 |
help="Always colorize output") |
| 138 |
ap.add_argument( |
| 139 |
"-n", |
| 140 |
"--print-filenames", |
| 141 |
action="store_true", |
| 142 |
help="Print only matching filenames, no contents", |
| 143 |
) |
| 144 |
ap.add_argument( |
| 145 |
"-d", |
| 146 |
"--dedupe", |
| 147 |
action="store_true", |
| 148 |
help="amalgamate results for the same file in different packages", |
| 149 |
) |
| 150 |
ap.add_argument( |
| 151 |
"-x", |
| 152 |
"--exclude", |
| 153 |
action="append", |
| 154 |
help="list of path fragments to exclude from results", |
| 155 |
) |
| 156 |
ap.add_argument( |
| 157 |
"-m", |
| 158 |
"--mode", |
| 159 |
choices=["literal", "regexp"], |
| 160 |
default="regexp", |
| 161 |
help="search mode (literal or regexp)", |
| 162 |
) |
| 163 |
ap.add_argument( |
| 164 |
"--per-package", |
| 165 |
action="store_true", |
| 166 |
default=False, |
| 167 |
help="group results per source package", |
| 168 |
) |
| 169 |
ap.add_argument( |
| 170 |
"--only-package", |
| 171 |
action="store_true", |
| 172 |
default=False, |
| 173 |
help="only print matching source package name", |
| 174 |
) |
| 175 |
return ap.parse_args() |
| 176 |
|
| 177 |
|
| 178 |
def main() -> None: |
| 179 |
args = parse_args() |
| 180 |
|
| 181 |
if args.quiet: |
| 182 |
requests.packages.urllib3.disable_warnings() # type: ignore |
| 183 |
|
| 184 |
printed_chunks = set() |
| 185 |
try: |
| 186 |
# Searches through source code, see |
| 187 |
# https://codesearch.debian.net/apikeys/#/search/search |
| 188 |
if args.per_package or args.only_package: |
| 189 |
api_response, status, headers = dcs.searchperpackage_with_http_info( |
| 190 |
args.searchstring, match_mode=args.mode, _return_http_data_only=False |
| 191 |
) |
| 192 |
else: |
| 193 |
api_response, status, headers = dcs.search_with_http_info( |
| 194 |
args.searchstring, match_mode=args.mode, _return_http_data_only=False |
| 195 |
) |
| 196 |
printed = 0 |
| 197 |
packages = set() |
| 198 |
for chunk in api_response: |
| 199 |
if is_excluded(chunk, args.exclude or []): |
| 200 |
continue |
| 201 |
packages.add(chunk.package) |
| 202 |
if printed == args.max_results: |
| 203 |
break |
| 204 |
printed += 1 |
| 205 |
if args.per_package: |
| 206 |
chunk = chunk.results[0] |
| 207 |
if args.only_package: |
| 208 |
continue |
| 209 |
if args.dedupe: |
| 210 |
dedupe_results.append(chunk) |
| 211 |
else: |
| 212 |
print_results( |
| 213 |
chunk, args.linenumber, args.print_filenames, args.nocolor |
| 214 |
) |
| 215 |
printed_chunks.add((chunk.path, chunk.line)) |
| 216 |
|
| 217 |
if args.only_package: |
| 218 |
if packages: |
| 219 |
print('\n'.join(sorted(packages))) |
| 220 |
return |
| 221 |
|
| 222 |
if args.dedupe: |
| 223 |
print_dedupe(args.linenumber, args.print_filenames, args.nocolor) |
| 224 |
|
| 225 |
say( |
| 226 |
args.quiet, |
| 227 |
"--\n%d files found." % int(headers["X-Codesearch-Filestotal"]), |
| 228 |
) |
| 229 |
|
| 230 |
except ApiException as e: |
| 231 |
print("Exception when calling SearchApi->search: %s\n" % e) |
| 232 |
|
| 233 |
|
| 234 |
if __name__ == "__main__": |
| 235 |
try: |
| 236 |
main() |
| 237 |
except KeyboardInterrupt: |
| 238 |
print("") |
| 239 |
sys.exit() |