fork/fish-shell
git clone https://git.julia.blue/fork/fish-shell
64da7ca12
master
1#!/usr/bin/env python 2 3"""Command line test driver.""" 4 5from __future__import unicode_literals 6from __future__import print_function 7import argparse 8import asyncio 9import datetime 10from difflib import SequenceMatcher 11import io 12import re 13import shlex 14import sys 15import unicodedata 16 17try : 18from itertools import zip_longest 19except ImportError : 20from itertools import izip_longest as zip_longest # type: ignore 21 22 23# Directives can occur at the beginning of a line, or anywhere in a line that does not start with #. 24COMMENT_RE = r"^(?:[^#].*)?#\s*" 25 26# A regex showing how to run the file. 27RUN_RE = re .compile (COMMENT_RE + r"RUN:\s+(.*)\n" ) 28REQUIRES_RE = re .compile (COMMENT_RE + r"REQUIRES:\s+(.*)\n" ) 29 30# A regex capturing lines that should be checked against stdout. 31CHECK_STDOUT_RE = re .compile (COMMENT_RE + r"CHECK:\s+(.*)\n" ) 32 33# A regex capturing lines that should be checked against stderr. 34CHECK_STDERR_RE = re .compile (COMMENT_RE + r"CHECKERR:\s+(.*)\n" ) 35 36VARIABLE_OVERRIDE_RE = re .compile (r"\w+=.*" ) 37 38SKIP = object () 39 40 41def find_command (program ): 42import os 43 44path ,_ = os .path .split (program ) 45if path : 46return os .path .isfile (program )and os .access (program ,os .X_OK ) 47for path in os .environ ["PATH" ].split (os .pathsep ): 48exe = os .path .join (path ,program ) 49if os .path .isfile (exe )and os .access (exe ,os .X_OK ): 50return exe 51 52return None 53 54 55class Config (object ): 56def __init__ (self ): 57# Whether to have verbose output. 58self .verbose = False 59# Whether output gets ANSI colorization. 60self .colorize = False 61# Whether to show which file was tested. 62self .progress = False 63 64def colors (self ): 65"""Return a dictionary mapping color names to ANSI escapes""" 66 67def ansic (n ): 68return "\033[%dm" % n if self .colorize else "" 69 70return { 71"RESET" :ansic (0 ), 72"BOLD" :ansic (1 ), 73"NORMAL" :ansic (39 ), 74"BLACK" :ansic (30 ), 75"RED" :ansic (31 ), 76"GREEN" :ansic (32 ), 77"YELLOW" :ansic (33 ), 78"BLUE" :ansic (34 ), 79"MAGENTA" :ansic (35 ), 80"CYAN" :ansic (36 ), 81"LIGHTGRAY" :ansic (37 ), 82"DARKGRAY" :ansic (90 ), 83"LIGHTRED" :ansic (91 ), 84"LIGHTGREEN" :ansic (92 ), 85"LIGHTYELLOW" :ansic (93 ), 86"LIGHTBLUE" :ansic (94 ), 87"LIGHTMAGENTA" :ansic (95 ), 88"LIGHTCYAN" :ansic (96 ), 89"WHITE" :ansic (97 ), 90 } 91 92 93def output (* args ): 94"" .join (args )+ "\n" ) 95 96 97def esc (m ): 98map = { 99"\n" :"\\n" , 100"\\" :"\\\\" , 101"\a" :"\\a" , 102"\b" :"\\b" , 103"\f" :"\\f" , 104"\r" :"\\r" , 105"\t" :"\\t" , 106"\v" :"\\v" , 107 } 108if m in map : 109return map [m ] 110if unicodedata .category (m )[0 ]== "C" : 111return "\\x{:02x}" .format (ord (m )) 112else : 113return m 114 115 116def escape_string (s ): 117return "" .join (esc (ch )for ch in s ) 118 119 120class CheckerError (Exception ): 121"""Exception subclass for check line parsing. 122 123Attributes: 124line: the Line object on which the exception occurred. 125""" 126 127def __init__ (self ,message ,line = None ): 128super (CheckerError ,self ).__init__ (message ) 129self .line = line 130 131 132class Line (object ): 133"""A line that remembers where it came from.""" 134 135def __init__ (self ,text ,number ,file ): 136self .text = text 137self .number = number 138self .file = file 139 140def __hash__ (self ): 141# Chosen by fair diceroll 142# No, just kidding. 143# HACK: We pass this to the Sequencematcher, which puts the Checks into a dict. 144# To force it to match the regexes, we return a hash collision intentionally, 145# so it falls back on __eq__(). 146# 147# CheckCmd has the same thing. 148return 0 149 150def __eq__ (self ,other ): 151if other is None : 152return False 153if isinstance (other ,CheckCmd ): 154return other .regex .match (self .text ) 155if isinstance (other ,Line ): 156# We only compare the text here so SequenceMatcher can reshuffle these 157return self .text == other .text 158raise NotImplementedError 159 160def subline (self ,text ): 161"""Return a substring of our line with the given text, preserving number and file.""" 162return Line (text ,self .number ,self .file ) 163 164@staticmethod 165def readfile (file ,name ): 166return [Line (text ,idx + 1 ,name )for idx ,text in enumerate (file )] 167 168def is_empty_space (self ): 169return not self .text or self .text .isspace () 170 171def escaped_text (self ,for_formatting = False ): 172ret = escape_string (self .text .rstrip ("\n" )) 173if for_formatting : 174ret = ret .replace ("{" ,"{{" ).replace ("}" ,"}}" ) 175return ret 176 177 178class RunCmd (object ): 179"""A command to run on a given Checker. 180 181Attributes: 182args: Unexpanded shell command as a string. 183""" 184 185def __init__ (self ,args ,line ): 186self .args = args 187self .line = line 188 189@staticmethod 190def parse (line ): 191if not shlex .split (line .text ): 192raise CheckerError ("Invalid RUN command" ,line ) 193return RunCmd (line .text ,line ) 194 195 196class TestFailure (object ): 197def __init__ (self ,line ,check ,testrun ,diff = None ,lines = [],checks = []): 198self .line = line 199self .check = check 200self .testrun = testrun 201self .error_annotation_lines = None 202self .diff = diff 203self .lines = lines 204self .checks = checks 205self .signal = None 206 207def message (self ): 208fields = self .testrun .config .colors () 209fields ["name" ]= self .testrun .name 210fields ["subbed_command" ]= self .testrun .subbed_command 211if self .line : 212fields .update ( 213 { 214"output_file" :self .line .file , 215"output_lineno" :self .line .number , 216"output_line" :self .line .escaped_text (), 217 } 218 ) 219if self .check : 220fields .update ( 221 { 222"input_file" :self .check .line .file , 223"input_lineno" :self .check .line .number , 224"input_line" :self .check .line .escaped_text (), 225"check_type" :self .check .type , 226 } 227 ) 228filemsg = "" if self .testrun .config .progress else " in {name}" 229fmtstrs = ["{RED}Failure{RESET}" + filemsg + ":" ,"" ] 230if self .signal : 231fmtstrs += [ 232" Process was killed by signal {BOLD}" + self .signal + "{RESET}" , 233"" , 234 ] 235if self .line and self .check : 236fmtstrs += [ 237" The {check_type} on line {input_lineno} wants:" , 238" {BOLD}{input_line}{RESET}" , 239"" , 240" which failed to match line {output_file}:{output_lineno}:" , 241" {BOLD}{output_line}{RESET}" , 242"" , 243 ] 244 245elif self .check : 246fmtstrs += [ 247" The {check_type} on line {input_lineno} wants:" , 248" {BOLD}{input_line}{RESET}" , 249"" , 250" but there was no remaining output to match." , 251"" , 252 ] 253else : 254fmtstrs += [ 255" There were no remaining checks left to match {output_file}:{output_lineno}:" , 256" {BOLD}{output_line}{RESET}" , 257"" , 258 ] 259if self .error_annotation_lines : 260fields ["error_annotation" ]= " " .join ( 261 [x .text for x in self .error_annotation_lines ] 262 ) 263fields ["error_annotation_lineno" ]= str ( 264self .error_annotation_lines [0 ].number 265 ) 266if len (self .error_annotation_lines )> 1 : 267fields ["error_annotation_lineno" ]+= ":" + str ( 268self .error_annotation_lines [- 1 ].number 269 ) 270fmtstrs += [ 271" additional output on stderr:{error_annotation_lineno}:" , 272" {BOLD}{error_annotation}{RESET}" , 273 ] 274if self .diff : 275fmtstrs += [" Context:" ] 276lasthi = 0 277lastcheckline = None 278for d in self .diff .get_grouped_opcodes (): 279for op ,alo ,ahi ,blo ,bhi in d : 280color = "{BOLD}" 281if op == "replace" or op == "delete" : 282color = "{RED}" 283# We got a new chunk, so we print a marker. 284if alo > lasthi : 285fmtstrs += [ 286" [...] from line " 287+ str (self .checks [blo ].line .number ) 288+ " (" 289+ self .lines [alo ].file 290+ ":" 291+ str (self .lines [alo ].number ) 292+ "):" 293 ] 294lasthi = ahi 295 296# We print one "no more checks" after the last check and then skip any markers 297lastcheck = False 298for a ,b in zip_longest (self .lines [alo :ahi ],self .checks [blo :bhi ]): 299# Clean up strings for use in a format string - double up the curlies. 300astr = ( 301color + a .escaped_text (for_formatting = True )+ "{RESET}" 302if a 303else "" 304 ) 305# Convince type checker that bstr will in fact be a string when read. 306bstr = "" 307if b : 308bstr = ( 309"on line " 310+ str (b .line .number ) 311+ ": {BLUE}" 312+ b .line .escaped_text (for_formatting = True ) 313+ "{RESET}" 314 ) 315lastcheckline = b .line .number 316 317if op == "equal" : 318fmtstrs += [" " + astr ] 319elif b and a : 320fmtstrs += [ 321" " 322+ astr 323+ " <= does not match " 324+ b .type 325+ " " 326+ bstr 327 ] 328elif b : 329fmtstrs += [ 330" " 331+ astr 332+ " <= nothing to match " 333+ b .type 334+ " " 335+ bstr 336 ] 337elif not b : 338string = " " + astr 339if bhi == len (self .checks ): 340if not lastcheck : 341string += " <= no more checks" 342lastcheck = True 343elif lastcheckline is not None : 344string += ( 345" <= no check matches this, previous check on line " 346+ str (lastcheckline ) 347 ) 348else : 349string += " <= no check matches" 350fmtstrs .append (string ) 351fmtstrs .append ("" ) 352fmtstrs += [" when running command:" ," {subbed_command}" ] 353return "\n" .join (fmtstrs ).format (** fields ) 354 355def print_message (self ): 356"""Print our message to stdout.""" 357self .message ()) 358 359 360def perform_substitution (input_str ,subs ): 361"""Perform the substitutions described by subs to str 362Return the substituted string. 363""" 364# Sort our substitutions into a list of tuples (key, value), descending by length. 365# It needs to be descending because we need to try longer substitutions first. 366subs_ordered = sorted (subs .items (),key = lambda s :len (s [0 ]),reverse = True ) 367 368def subber (m ): 369# We get the entire sequence of characters. 370# Replace just the prefix and return it. 371text = m .group (1 ) 372for key ,replacement in subs_ordered : 373if text .startswith (key ): 374# shell-quote the replacement, so it's usable in #RUN lines. 375# We could loosen this and only do it for #RUN/#REQUIRES, 376# but so far we don't need it anywhere. 377return shlex .quote (replacement + text [len (key ) :]) 378# No substitution found, so we default to running it as-is, 379# which will end up running it via $PATH. 380return text 381 382return re .sub (r"%(%|[a-zA-Z0-9_-]+)" ,subber ,input_str ) 383 384 385def runproc (cmd ,env = None ): 386"""Wrapper around subprocess.Popen to save typing""" 387return asyncio .run (runproc_async (cmd ,env = env )) 388 389 390async def runproc_async (cmd ,env = None ,cwd = None ): 391"""Wrapper around subprocess.Popen to save typing""" 392PIPE = asyncio .subprocess .PIPE 393DEVNULL = asyncio .subprocess .DEVNULL 394return await asyncio .create_subprocess_shell ( 395cmd ,stdin = DEVNULL ,stdout = PIPE ,stderr = PIPE ,env = env ,cwd = cwd 396 ) 397 398 399class TestRun (object ): 400def __init__ (self ,name ,runcmd ,checker ,subs ,config ,env = None ,cwd = None ): 401self .name = name 402self .runcmd = runcmd 403self .subbed_command = perform_substitution (runcmd .args ,subs ) 404self .checker = checker 405self .subs = subs 406self .config = config 407self .env = env 408self .cwd = cwd 409 410def check (self ,lines ,checks ): 411# Reverse our lines and checks so we can pop off the end. 412lineq = lines [::- 1 ] 413checkq = checks [::- 1 ] 414usedlines = [] 415usedchecks = [] 416mismatches = [] 417while lineq and checkq : 418line = lineq [- 1 ] 419check = checkq [- 1 ] 420if check == line : 421# This line matched this checker, continue on. 422usedlines .append (line ) 423usedchecks .append (check ) 424lineq .pop () 425checkq .pop () 426elif line .is_empty_space (): 427# Skip all whitespace input lines. 428lineq .pop () 429else : 430usedlines .append (line ) 431usedchecks .append (check ) 432mismatches .append ((line ,check )) 433# Failed to match. 434lineq .pop () 435checkq .pop () 436 437# Drain empties 438while lineq and lineq [- 1 ].is_empty_space (): 439lineq .pop () 440 441# Store the remaining lines for the diff 442for i in lineq [::- 1 ]: 443if not i .is_empty_space (): 444usedlines .append (i ) 445# Store remaining checks for the diff 446for i in checkq [::- 1 ]: 447usedchecks .append (i ) 448 449# If we have no more output, there's no reason to give 450# SCREENFULS of text. 451# So we truncate the check list. 452if len (usedchecks )> len (usedlines ): 453usedchecks = usedchecks [:len (usedlines )+ 5 ] 454 455# Do a SequenceMatch! This gives us a diff-like thing. 456diff = SequenceMatcher (a = usedlines ,b = usedchecks ,autojunk = False ) 457# If there's a mismatch or still lines or checkers, we have a failure. 458# Otherwise it's success. 459if mismatches : 460return TestFailure ( 461mismatches [0 ][0 ], 462mismatches [0 ][1 ], 463self , 464diff = diff , 465lines = usedlines , 466checks = usedchecks , 467 ) 468elif lineq : 469return TestFailure ( 470lineq [- 1 ],None ,self ,diff = diff ,lines = usedlines ,checks = usedchecks 471 ) 472elif checkq : 473return TestFailure ( 474None ,checkq [- 1 ],self ,diff = diff ,lines = usedlines ,checks = usedchecks 475 ) 476else : 477# Success! 478return None 479 480def run (self ): 481"""Run the command. Return a TestFailure, or None.""" 482return asyncio .run (self .run_async ()) 483 484async def run_async (self ): 485"""Run the command. Return a TestFailure, or None.""" 486 487def split_by_newlines (s ): 488"""Decode a string and split it by newlines only, 489retaining the newlines. 490""" 491return [ 492s + "\n" 493for s in s .decode ("utf-8" ,errors = "backslashreplace" ).split ("\n" ) 494 ] 495 496if self .config .verbose : 497self .subbed_command ) 498proc = await runproc_async (self .subbed_command ,env = self .env ,cwd = self .cwd ) 499stdout ,stderr = await proc .communicate () 500 501# Work around type system limitations / bad API design which makes the typechecker unhappy. 502if proc .returncode is None : 503raise RuntimeError ( 504"After `proc.communicate()` the return code must be an int." 505 ) 506status = proc .returncode 507# HACK: This is quite cheesy: POSIX specifies that sh should return 127 for a missing command. 508# It's also possible that it'll be returned in other situations, 509# most likely when the last command in a shell script doesn't exist. 510# So we check if the command *we execute* exists, and complain then. 511cmd = next ( 512 ( 513word 514for word in shlex .split (self .subbed_command ) 515if not VARIABLE_OVERRIDE_RE .match (word ) 516 ) 517 ) 518if status == 127 and not find_command (cmd ): 519raise CheckerError ("Command could not be found: " + cmd ) 520if status == 126 and not find_command (cmd ): 521raise CheckerError ("Command is not executable: " + cmd ) 522 523outlines = [ 524Line (text ,idx + 1 ,"stdout" ) 525for idx ,text in enumerate (split_by_newlines (stdout )) 526 ] 527errlines = [ 528Line (text ,idx + 1 ,"stderr" ) 529for idx ,text in enumerate (split_by_newlines (stderr )) 530 ] 531outfail = self .check (outlines ,self .checker .outchecks ) 532errfail = self .check (errlines ,self .checker .errchecks ) 533# It's possible that something going wrong on stdout resulted in new 534# text being printed on stderr. If we have an outfailure, and either 535# non-matching or unmatched stderr text, then annotate the outfail 536# with it. 537if outfail and errfail and errfail .line : 538outfail .error_annotation_lines = errlines [errfail .line .number - 1 :] 539# Trim a trailing newline 540if outfail .error_annotation_lines [- 1 ].text == "\n" : 541del outfail .error_annotation_lines [- 1 ] 542failure = outfail if outfail else errfail 543 544if failure and status < 0 : 545# Process was killed by a signal and failed, 546# add a message. 547import signal 548 549# Unfortunately strsignal only exists in python 3.8+, 550# and signal.signals is 3.5+. 551if hasattr (signal ,"Signals" ): 552try : 553sig = signal .Signals (- status ) 554failure .signal = sig .name + " (" + signal .strsignal (sig .value )+ ")" 555except ValueError : 556failure .signal = str (- status ) 557else : 558# No easy way to get the full list, 559# make up a dict. 560signals = { 561signal .SIGABRT :"SIGABRT" , 562signal .SIGBUS :"SIGBUS" , 563signal .SIGFPE :"SIGFPE" , 564signal .SIGILL :"SIGILL" , 565signal .SIGSEGV :"SIGSEGV" , 566signal .SIGTERM :"SIGTERM" , 567 } 568failure .signal = signals .get (- status ,str (- status )) 569 570return failure 571 572 573class CheckCmd (object ): 574def __init__ (self ,line ,checktype ,regex ): 575self .line = line 576self .type = checktype 577self .regex = regex 578 579def __hash__ (self ): 580# HACK: We pass this to the Sequencematcher, which puts the Checks into a dict. 581# To force it to match the regexes, we return a hash collision intentionally, 582# so it falls back on __eq__(). 583# 584# Line has the same thing. 585return 0 586 587def __eq__ (self ,other ): 588# "Magical" comparison with lines and strings. 589# Typically I wouldn't use this, but it allows us to check if a line matches any check in a dict or list via 590# the `in` operator. 591if other is None : 592return False 593if isinstance (other ,CheckCmd ): 594return self .regex == other .regex 595if isinstance (other ,Line ): 596return self .regex .match (other .text ) 597if isinstance (other ,str ): 598return self .regex .match (other ) 599raise NotImplementedError 600 601@staticmethod 602def parse (line :Line ,checktype :str )-> "CheckCmd" : 603# Everything inside {{}} is a regular expression. 604# Everything outside of it is a literal string. 605# Split around {{...}}. Then every odd index will be a regex, and 606# evens will be literals. 607# Note that if {{...}} appears first we will get an empty string in 608# the split array, so the {{...}} matches are always at odd indexes. 609bracket_re = re .compile ( 610r""" 611\{\{ # Two open brackets 612(.*?) # Nongreedy capture 613\}\} # Two close brackets 614""" , 615re .VERBOSE , 616 ) 617pieces = bracket_re .split (line .text ) 618even = True 619re_strings = [] 620for i ,piece in enumerate (pieces ): 621if even : 622if i != 0 and piece .startswith ("}" ): 623raise CheckerError ( 624"Expression ('{{%s}}}') is ambiguous, consider using '{{%s}}{{[}]}}' if you really mean that" 625% (pieces [i - 1 ],pieces [i - 1 ]), 626line , 627 ) 628# piece is a literal string. 629re_strings .append (re .escape (piece )) 630else : 631# piece is a regex (found inside {{...}}). 632# Verify the regex can be compiled. 633try : 634re .compile (piece ) 635except re .error : 636raise CheckerError ("Invalid regular expression: '%s'" % piece ,line ) 637re_strings .append (piece ) 638even = not even 639# Enclose each piece in a non-capturing group. 640# This ensures that lower-precedence operators don't trip up catenation. 641# For example: {{b|c}}d would result in /b|cd/ which is different. 642# Backreferences are assumed to match across the entire string. 643re_strings = ["(?:%s)" % s for s in re_strings ] 644# Anchor at beginning and end (allowing arbitrary whitespace), and maybe 645# a terminating newline. 646# We need the anchors because Python's match() matches an arbitrary prefix, 647# not the entire string. 648re_strings = [r"^\s*" ]+ re_strings + [r"\s*\n?$" ] 649full_re = re .compile ("" .join (re_strings )) 650return CheckCmd (line ,checktype ,full_re ) 651 652 653class Checker (object ): 654def __init__ (self ,name ,lines ): 655self .name = name 656 657# Helper to yield subline containing group1 from all matching lines. 658def group1s (regex ): 659for line in lines : 660m = regex .match (line .text ) 661if m : 662yield line .subline (m .group (1 )) 663 664# Find run commands. 665self .runcmds = [RunCmd .parse (sl )for sl in group1s (RUN_RE )] 666self .shebang_cmd = None 667if not self .runcmds : 668# If no RUN command has been given, fall back to the shebang. 669if lines [0 ].text .startswith ("#!" ): 670# Remove the "#!" at the beginning, and the newline at the end. 671cmd = lines [0 ].text [2 :- 1 ] 672self .shebang_cmd = cmd 673self .runcmds = [RunCmd (cmd + " %s" ,lines [0 ])] 674else : 675raise CheckerError ("No runlines ('# RUN') found" ) 676 677self .requirecmds = [RunCmd .parse (sl )for sl in group1s (REQUIRES_RE )] 678 679# Find check cmds. 680self .outchecks = [ 681CheckCmd .parse (sl ,"CHECK" )for sl in group1s (CHECK_STDOUT_RE ) 682 ] 683self .errchecks = [ 684CheckCmd .parse (sl ,"CHECKERR" )for sl in group1s (CHECK_STDERR_RE ) 685 ] 686 687 688def check_file (input_file ,name ,subs ,config ,failure_handler ,env = None ): 689"""Check a single file. Return a True on success, False on error.""" 690return asyncio .run ( 691check_file_async (input_file ,name ,subs ,config ,failure_handler ,env = env ) 692 ) 693 694 695async def check_file_async ( 696input_file ,name ,subs ,config ,failure_handler ,env = None ,cwd = None 697): 698"""Check a single file. Return a True on success, False on error.""" 699success = True 700lines = Line .readfile (input_file ,name ) 701checker = Checker (name ,lines ) 702 703# Run all the REQUIRES lines first, 704# if any of them fail it's a SKIP 705for reqcmd in checker .requirecmds : 706proc = await runproc_async ( 707perform_substitution (reqcmd .args ,subs ),env = env ,cwd = cwd 708 ) 709await proc .communicate () 710# Work around type system limitations / bad API design which makes the typechecker unhappy. 711if proc .returncode is None : 712raise RuntimeError ( 713"After `proc.communicate()` the return code must be an int." 714 ) 715if proc .returncode > 0 : 716return SKIP 717 718if checker .shebang_cmd is not None and not find_command (checker .shebang_cmd ): 719raise CheckerError ("Command could not be found: " + checker .shebang_cmd ) 720 721# Only then run the RUN lines. 722for runcmd in checker .runcmds : 723failure = await TestRun ( 724name ,runcmd ,checker ,subs ,config ,env = env ,cwd = cwd 725 ).run_async () 726if failure : 727failure_handler (failure ) 728success = False 729return success 730 731 732def check_path (path ,subs ,config ,failure_handler ,env = None ): 733return asyncio .run (check_path_async (path ,subs ,config ,failure_handler ,env = env )) 734 735 736async def check_path_async (path ,subs ,config ,failure_handler ,env = None ,cwd = None ): 737with io .open (path ,encoding = "utf-8" )as fd : 738return await check_file_async ( 739fd ,path ,subs ,config ,failure_handler ,env = env ,cwd = cwd 740 ) 741 742 743def parse_subs (subs ): 744"""Given a list of input substitutions like 'foo=bar', 745return a dictionary like {foo:bar}, or exit if invalid. 746""" 747result = {} 748for sub in subs : 749try : 750key ,val = sub .split ("=" ,1 ) 751if not key : 752"Invalid substitution %s: empty key" % sub ) 753sys .exit (1 ) 754if not val : 755"Invalid substitution %s: empty value" % sub ) 756sys .exit (1 ) 757result [key ]= val 758except ValueError : 759"Invalid substitution %s: equal sign not found" % sub ) 760sys .exit (1 ) 761return result 762 763 764def get_argparse (): 765"""Return a littlecheck argument parser.""" 766parser = argparse .ArgumentParser ( 767description = "littlecheck: command line tool tester." 768 ) 769parser .add_argument ( 770"-s" , 771"--substitute" , 772type = str , 773help = "Add a new substitution for RUN lines. Example: bash=/bin/bash" , 774action = "append" , 775default = [], 776 ) 777parser .add_argument ( 778"-p" , 779"--progress" , 780action = "store_true" , 781dest = "progress" , 782help = "Show the files to be checked" , 783default = False , 784 ) 785parser .add_argument ( 786"--force-color" , 787action = "store_true" , 788dest = "force_color" , 789help = "Force usage of color even if not connected to a terminal" , 790default = False , 791 ) 792parser .add_argument ("file" ,nargs = "+" ,help = "File to check" ) 793return parser 794 795 796def main (): 797args = get_argparse ().parse_args () 798# Default substitution is %% -> % 799def_subs = {"%" :"%" } 800def_subs .update (parse_subs (args .substitute )) 801 802tests_count = 0 803failed = False 804skip_count = 0 805config = Config () 806config .colorize = args .force_color or sys .stdout .isatty () 807config .progress = args .progress 808fields = config .colors () 809 810for path in args .file : 811tests_count += 1 812fields ["path" ]= path 813if config .progress : 814"Testing file {path} ... " .format (** fields ),end = "" ) 815sys .stdout .flush () 816subs = def_subs .copy () 817subs ["s" ]= path 818starttime = datetime .datetime .now () 819ret = check_path (path ,subs ,config ,TestFailure .print_message ) 820if ret is SKIP : 821skip_count += 1 822if not ret : 823failed = True 824elif config .progress : 825endtime = datetime .datetime .now () 826duration_ms = round ((endtime - starttime ).total_seconds ()* 1000 ) 827reason = "ok" 828color = "{GREEN}" 829if ret is SKIP : 830reason = "SKIPPED" 831color = "{BLUE}" 832color + "{reason}{RESET} ({duration} ms)" ).format ( 834duration = duration_ms ,reason = reason ,** fields 835 ) 836 ) 837 838# To facilitate integration with testing frameworks, use exit code 125 to indicate that all 839# tests have been skipped (primarily for use when tests are run one at a time). Exit code 125 is 840# used to indicate to automated `git bisect` runs that a revision has been skipped; we use it 841# for the same reasons git does. 842if skip_count > 0 and skip_count == tests_count : 843sys .exit (125 ) 844 845sys .exit (1 if failed else 0 ) 846 847 848if __name__ == "__main__" : 849main ()