@@ -125,17 +125,6 @@ def categorize(func: Union[Callable, Iterable], category: str) -> None:
125125 else :
126126 setattr (func , HELP_CATEGORY , category )
127127
128-
129- def _which (editor : str ) -> Optional [str ]:
130- import subprocess
131- try :
132- editor_path = subprocess .check_output (['which' , editor ], stderr = subprocess .STDOUT ).strip ()
133- editor_path = editor_path .decode ()
134- except subprocess .CalledProcessError :
135- editor_path = None
136- return editor_path
137-
138-
139128def parse_quoted_string (cmdline : str ) -> List [str ]:
140129 """Parse a quoted string into a list of arguments."""
141130 if isinstance (cmdline , list ):
@@ -347,7 +336,7 @@ class Cmd(cmd.Cmd):
347336 else :
348337 # Favor command-line editors first so we don't leave the terminal to edit
349338 for editor in ['vim' , 'vi' , 'emacs' , 'nano' , 'pico' , 'gedit' , 'kate' , 'subl' , 'geany' , 'atom' ]:
350- if _which (editor ):
339+ if utils . which (editor ):
351340 break
352341 feedback_to_output = False # Do not include nonessentials in >, | output by default (things like timing)
353342 locals_in_py = False
@@ -2437,7 +2426,7 @@ def do_set(self, args):
24372426 if (val [0 ] == val [- 1 ]) and val [0 ] in ("'" , '"' ):
24382427 val = val [1 :- 1 ]
24392428 else :
2440- val = cast (current_val , val )
2429+ val = utils . cast (current_val , val )
24412430 setattr (self , param_name , val )
24422431 self .poutput ('%s - was: %s\n now: %s\n ' % (param_name , current_val , val ))
24432432 if current_val != val :
@@ -2865,7 +2854,7 @@ def do_load(self, arglist):
28652854 return
28662855
28672856 # Make sure the file is ASCII or UTF-8 encoded text
2868- if not self .is_text_file (expanded_path ):
2857+ if not utils .is_text_file (expanded_path ):
28692858 self .perror ('{} is not an ASCII or UTF-8 encoded text file' .format (expanded_path ), traceback_war = False )
28702859 return
28712860
@@ -2886,42 +2875,6 @@ def complete_load(self, text, line, begidx, endidx):
28862875 index_dict = {1 : self .path_complete }
28872876 return self .index_based_complete (text , line , begidx , endidx , index_dict )
28882877
2889- @staticmethod
2890- def is_text_file (file_path ):
2891- """
2892- Returns if a file contains only ASCII or UTF-8 encoded text
2893- :param file_path: path to the file being checked
2894- """
2895- import codecs
2896-
2897- expanded_path = os .path .abspath (os .path .expanduser (file_path .strip ()))
2898- valid_text_file = False
2899-
2900- # Check if the file is ASCII
2901- try :
2902- with codecs .open (expanded_path , encoding = 'ascii' , errors = 'strict' ) as f :
2903- # Make sure the file has at least one line of text
2904- # noinspection PyUnusedLocal
2905- if sum (1 for line in f ) > 0 :
2906- valid_text_file = True
2907- except IOError : # pragma: no cover
2908- pass
2909- except UnicodeDecodeError :
2910- # The file is not ASCII. Check if it is UTF-8.
2911- try :
2912- with codecs .open (expanded_path , encoding = 'utf-8' , errors = 'strict' ) as f :
2913- # Make sure the file has at least one line of text
2914- # noinspection PyUnusedLocal
2915- if sum (1 for line in f ) > 0 :
2916- valid_text_file = True
2917- except IOError : # pragma: no cover
2918- pass
2919- except UnicodeDecodeError :
2920- # Not UTF-8
2921- pass
2922-
2923- return valid_text_file
2924-
29252878 def run_transcript_tests (self , callargs ):
29262879 """Runs transcript tests for provided file(s).
29272880
@@ -3119,36 +3072,6 @@ def isin(hi):
31193072 return [itm for itm in self if isin (itm )]
31203073
31213074
3122- def cast (current , new ):
3123- """Tries to force a new value into the same type as the current when trying to set the value for a parameter.
3124-
3125- :param current: current value for the parameter, type varies
3126- :param new: str - new value
3127- :return: new value with same type as current, or the current value if there was an error casting
3128- """
3129- typ = type (current )
3130- if typ == bool :
3131- try :
3132- return bool (int (new ))
3133- except (ValueError , TypeError ):
3134- pass
3135- try :
3136- new = new .lower ()
3137- except AttributeError :
3138- pass
3139- if (new == 'on' ) or (new [0 ] in ('y' , 't' )):
3140- return True
3141- if (new == 'off' ) or (new [0 ] in ('n' , 'f' )):
3142- return False
3143- else :
3144- try :
3145- return typ (new )
3146- except (ValueError , TypeError ):
3147- pass
3148- print ("Problem setting parameter (now %s) to %s; incorrect type?" % (current , new ))
3149- return current
3150-
3151-
31523075class Statekeeper (object ):
31533076 """Class used to save and restore state during load and py commands as well as when redirecting output or pipes."""
31543077 def __init__ (self , obj , attribs ):
@@ -3174,22 +3097,7 @@ def restore(self):
31743097 setattr (self .obj , attrib , getattr (self , attrib ))
31753098
31763099
3177- def namedtuple_with_two_defaults (typename , field_names , default_values = ('' , '' )):
3178- """Wrapper around namedtuple which lets you treat the last value as optional.
3179-
3180- :param typename: str - type name for the Named tuple
3181- :param field_names: List[str] or space-separated string of field names
3182- :param default_values: (optional) 2-element tuple containing the default values for last 2 parameters in named tuple
3183- Defaults to an empty string for both of them
3184- :return: namedtuple type
3185- """
3186- T = collections .namedtuple (typename , field_names )
3187- # noinspection PyUnresolvedReferences
3188- T .__new__ .__defaults__ = default_values
3189- return T
3190-
3191-
3192- class CmdResult (namedtuple_with_two_defaults ('CmdResult' , ['out' , 'err' , 'war' ])):
3100+ class CmdResult (utils .namedtuple_with_two_defaults ('CmdResult' , ['out' , 'err' , 'war' ])):
31933101 """Derive a class to store results from a named tuple so we can tweak dunder methods for convenience.
31943102
31953103 This is provided as a convenience and an example for one possible way for end users to store results in
@@ -3209,5 +3117,3 @@ class CmdResult(namedtuple_with_two_defaults('CmdResult', ['out', 'err', 'war'])
32093117 def __bool__ (self ):
32103118 """If err is an empty string, treat the result as a success; otherwise treat it as a failure."""
32113119 return not self .err
3212-
3213-
0 commit comments