Parse positional arguments into a parameter dict, according to the command descriptions. Writes advice about nearly-matching commands ``sys.stderr`` if the arguments do not match any command. :param sigdict: A command description dictionary, as returned fro
(sigdict: Dict[str, Dict[str, Any]],
args: List[str],
verbose: Optional[bool] = False)
| 1322 | |
| 1323 | |
| 1324 | def validate_command(sigdict: Dict[str, Dict[str, Any]], |
| 1325 | args: List[str], |
| 1326 | verbose: Optional[bool] = False) -> ValidatedArgs: |
| 1327 | """ |
| 1328 | Parse positional arguments into a parameter dict, according to |
| 1329 | the command descriptions. |
| 1330 | |
| 1331 | Writes advice about nearly-matching commands ``sys.stderr`` if |
| 1332 | the arguments do not match any command. |
| 1333 | |
| 1334 | :param sigdict: A command description dictionary, as returned |
| 1335 | from Ceph daemons by the get_command_descriptions |
| 1336 | command. |
| 1337 | :param args: List of strings, should match one of the command |
| 1338 | signatures in ``sigdict`` |
| 1339 | |
| 1340 | :returns: A dict of parsed parameters (including ``prefix``), |
| 1341 | or an empty dict if the args did not match any signature |
| 1342 | """ |
| 1343 | if verbose: |
| 1344 | print("validate_command: " + " ".join(args), file=sys.stderr) |
| 1345 | found: Optional[Dict[str, Any]] = None |
| 1346 | valid_dict = {} |
| 1347 | |
| 1348 | # look for best match, accumulate possibles in bestcmds |
| 1349 | # (so we can maybe give a more-useful error message) |
| 1350 | best_match_cnt = 0.0 |
| 1351 | bestcmds: List[Dict[str, Any]] = [] |
| 1352 | for cmd in sigdict.values(): |
| 1353 | flags = cmd.get('flags', 0) |
| 1354 | if flags & Flag.OBSOLETE: |
| 1355 | continue |
| 1356 | sig = cmd['sig'] |
| 1357 | matched: float = matchnum(args, sig, partial=True) |
| 1358 | if (matched >= math.floor(best_match_cnt) and |
| 1359 | matched == matchnum(args, sig, partial=False)): |
| 1360 | # prefer those fully matched over partial patch |
| 1361 | matched += 0.5 |
| 1362 | if matched < best_match_cnt: |
| 1363 | continue |
| 1364 | if verbose: |
| 1365 | print("better match: {0} > {1}: {2} ".format( |
| 1366 | matched, best_match_cnt, concise_sig(sig) |
| 1367 | ), file=sys.stderr) |
| 1368 | if matched > best_match_cnt: |
| 1369 | best_match_cnt = matched |
| 1370 | bestcmds = [cmd] |
| 1371 | else: |
| 1372 | bestcmds.append(cmd) |
| 1373 | |
| 1374 | # Sort bestcmds by number of req args so we can try shortest first |
| 1375 | # (relies on a cmdsig being key,val where val is a list of len 1) |
| 1376 | |
| 1377 | def grade(cmd): |
| 1378 | # prefer optional arguments over required ones |
| 1379 | sigs = cmd['sig'] |
| 1380 | return sum(map(lambda sig: sig.req, sigs)) |
| 1381 |