idx
int64
0
63k
question
stringlengths
53
5.28k
target
stringlengths
5
805
34,800
def run_clingo ( draco_query : List [ str ] , constants : Dict [ str , str ] = None , files : List [ str ] = None , relax_hard = False , silence_warnings = False , debug = False , ) -> Tuple [ str , str ] : files = files or DRACO_LP if relax_hard and "hard-integrity.lp" in files : files . remove ( "hard-integrity.lp" )...
Run draco and return stderr and stdout
34,801
def run ( draco_query : List [ str ] , constants : Dict [ str , str ] = None , files : List [ str ] = None , relax_hard = False , silence_warnings = False , debug = False , clear_cache = False , ) -> Optional [ Result ] : if clear_cache and file_cache : logger . warning ( "Cleared file cache" ) file_cache . clear ( ) s...
Run clingo to compute a completion of a partial spec or violations .
34,802
def get ( self ) : self . index += 1 if self . index == len ( self ) : self . shuffle ( ) self . rotate ( 1 ) try : return self [ 0 ] except : return "wow"
Get one item . This will rotate the deque one step . Repeated gets will return different items .
34,803
def shuffle ( self ) : args = list ( self ) random . shuffle ( args ) self . clear ( ) super ( DogeDeque , self ) . __init__ ( args )
Shuffle the deque
34,804
def get ( self ) : if len ( self ) < 1 : return "wow" if self . index >= len ( self ) : self . index = 0 step = random . randint ( 1 , min ( self . step , len ( self ) ) ) res = self [ 0 ] self . index += step self . rotate ( step ) return res
Get one item and prepare to get an item with lower rank on the next call .
34,805
def onscreen_len ( s ) : if sys . version_info < ( 3 , 0 ) and isinstance ( s , str ) : return len ( s ) length = 0 for ch in s : length += 2 if unicodedata . east_asian_width ( ch ) == 'W' else 1 return length
Calculate the length of a unicode string on screen accounting for double - width characters
34,806
def setup_seasonal ( self ) : if self . ns . season : return self . load_season ( self . ns . season ) if self . ns . doge_path is not None and not self . ns . no_shibe : return now = datetime . datetime . now ( ) for season , data in wow . SEASONS . items ( ) : start , end = data [ 'dates' ] start_dt = datetime . date...
Check if there s some seasonal holiday going on setup appropriate Shibe picture and load holiday words .
34,807
def apply_text ( self ) : linelen = len ( self . lines ) affected = sorted ( random . sample ( range ( linelen ) , int ( linelen / 3.5 ) ) ) for i , target in enumerate ( affected , start = 1 ) : line = self . lines [ target ] line = re . sub ( '\n' , ' ' , line ) word = self . words . get ( ) if i == 1 or i == len ( a...
Apply text around doge
34,808
def load_doge ( self ) : if self . ns . no_shibe : return [ '' ] with open ( self . doge_path ) as f : if sys . version_info < ( 3 , 0 ) : if locale . getpreferredencoding ( ) == 'UTF-8' : doge_lines = [ l . decode ( 'utf-8' ) for l in f . xreadlines ( ) ] else : doge_lines = [ l . decode ( 'utf-8' ) . encode ( locale ...
Return pretty ASCII Shibe .
34,809
def get_real_data ( self ) : ret = [ ] username = os . environ . get ( 'USER' ) if username : ret . append ( username ) editor = os . environ . get ( 'EDITOR' ) if editor : editor = editor . split ( '/' ) [ - 1 ] ret . append ( editor ) if hasattr ( os , 'uname' ) : uname = os . uname ( ) ret . append ( uname [ 0 ] ) r...
Grab actual data from the system
34,810
def get_stdin_data ( self ) : if self . tty . in_is_tty : return False if sys . version_info < ( 3 , 0 ) : stdin_lines = ( l . decode ( 'utf-8' ) for l in sys . stdin . xreadlines ( ) ) else : stdin_lines = ( l for l in sys . stdin . readlines ( ) ) rx_word = re . compile ( "\w+" , re . UNICODE ) self . words . clear (...
Get words from stdin .
34,811
def get_processes ( self ) : procs = set ( ) try : p = sp . Popen ( [ 'ps' , '-A' , '-o' , 'comm=' ] , stdout = sp . PIPE ) output , error = p . communicate ( ) if sys . version_info > ( 3 , 0 ) : output = output . decode ( 'utf-8' ) for comm in output . split ( '\n' ) : name = comm . split ( '/' ) [ - 1 ] if name and ...
Grab a shuffled list of all currently running process names
34,812
def get_tty_size ( self ) : if sys . platform == 'win32' : ret = self . _tty_size_windows ( - 10 ) ret = ret or self . _tty_size_windows ( - 11 ) ret = ret or self . _tty_size_windows ( - 12 ) else : ret = self . _tty_size_linux ( 0 ) ret = ret or self . _tty_size_linux ( 1 ) ret = ret or self . _tty_size_linux ( 2 ) r...
Get the current terminal size without using a subprocess
34,813
def _coords ( shape ) : assert shape . geom_type == 'Polygon' coords = [ list ( shape . exterior . coords ) ] for interior in shape . interiors : coords . append ( list ( interior . coords ) ) return coords
Return a list of lists of coordinates of the polygon . The list consists firstly of the list of exterior coordinates followed by zero or more lists of any interior coordinates .
34,814
def _union_in_blocks ( contours , block_size ) : n_contours = len ( contours ) for i in range ( 0 , n_contours , block_size ) : j = min ( i + block_size , n_contours ) inners = [ ] for c in contours [ i : j ] : p = _contour_to_poly ( c ) if p . type == 'Polygon' : inners . append ( p ) elif p . type == 'MultiPolygon' :...
Generator which yields a valid shape for each block_size multiple of input contours . This merges together the contours for each block before yielding them .
34,815
def _polytree_node_to_shapely ( node ) : polygons = [ ] children = [ ] for ch in node . Childs : p , c = _polytree_node_to_shapely ( ch ) polygons . extend ( p ) children . extend ( c ) if node . IsHole : assert len ( children ) == 0 if node . Contour : children = [ node . Contour ] else : children = [ ] elif node . Co...
Recurses down a Clipper PolyTree extracting the results as Shapely objects .
34,816
def make_valid_pyclipper ( shape ) : clean_shape = _drop_degenerate_inners ( shape ) pc = pyclipper . Pyclipper ( ) try : pc . AddPaths ( _coords ( clean_shape ) , pyclipper . PT_SUBJECT , True ) result = pc . Execute2 ( pyclipper . CT_UNION , pyclipper . PFT_EVENODD ) except pyclipper . ClipperException : return Multi...
Use the pyclipper library to union a polygon on its own . This operation uses the even - odd rule to determine which points are in the interior of the polygon and can reconstruct the orientation of the polygon from that . The pyclipper library is robust and uses integer coordinates so should not produce any additional ...
34,817
def make_valid_polygon ( shape ) : assert shape . geom_type == 'Polygon' shape = make_valid_pyclipper ( shape ) assert shape . is_valid return shape
Make a polygon valid . Polygons can be invalid in many ways such as self - intersection self - touching and degeneracy . This process attempts to make a polygon valid while retaining as much of its extent or area as possible .
34,818
def make_it_valid ( shape ) : if shape . is_empty : return shape elif shape . type == 'MultiPolygon' : shape = make_valid_multipolygon ( shape ) elif shape . type == 'Polygon' : shape = make_valid_polygon ( shape ) return shape
Attempt to make any polygon or multipolygon valid .
34,819
def _decode_lines ( geom ) : lines = [ ] current_line = [ ] current_moveto = None x = 0 y = 0 end = len ( geom ) i = 0 while i < end : header = geom [ i ] cmd = header & 7 run_length = header // 8 if cmd == 1 : if current_moveto : lines . append ( Line ( current_moveto , EndsAt ( x , y ) , current_line ) ) current_line...
Decode a linear MVT geometry into a list of Lines .
34,820
def _reorder_lines ( lines ) : x = 0 y = 0 new_lines = [ ] while lines : min_dist = None min_i = None for i , line in enumerate ( lines ) : moveto , _ , _ = line dist = abs ( moveto . x - x ) + abs ( moveto . y - y ) if min_dist is None or dist < min_dist : min_dist = dist min_i = i assert min_i is not None line = line...
Reorder lines so that the distance from the end of one to the beginning of the next is minimised .
34,821
def _rewrite_geometry ( geom , new_lines ) : new_geom = [ ] x = 0 y = 0 for line in new_lines : moveto , endsat , lineto_cmds = line dx = moveto . x - x dy = moveto . y - y x = endsat . x y = endsat . y new_geom . append ( 9 ) new_geom . append ( zigzag ( dx ) ) new_geom . append ( zigzag ( dy ) ) new_geom . extend ( l...
Re - encode a list of Lines with absolute MoveTos as a continuous stream of MVT geometry commands each relative to the last . Replace geom with that stream .
34,822
def optimise_tile ( tile_bytes ) : t = tile ( ) t . ParseFromString ( tile_bytes ) for layer in t . layers : sto = StringTableOptimiser ( ) for feature in layer . features : if feature . type == 2 : optimise_multilinestring ( feature . geometry ) sto . add_tags ( feature . tags ) sto . update_string_table ( layer ) ret...
Decode a sequence of bytes as an MVT tile and reorder the string table of its layers and the order of its multilinestrings to save a few bytes .
34,823
def coords_on_grid ( self , x , y ) : if isinstance ( x , float ) : x = int ( self . _round ( x ) ) if isinstance ( y , float ) : y = int ( self . _round ( y ) ) if not self . _y_coord_down : y = self . _extents - y return x , y
Snap coordinates on the grid with integer coordinates
34,824
def encode_arc ( self , coords ) : last_x , last_y = self . _last_x , self . _last_y float_x , float_y = next ( coords ) x , y = self . coords_on_grid ( float_x , float_y ) dx , dy = x - last_x , y - last_y cmd_encoded = encode_cmd_length ( CMD_MOVE_TO , 1 ) commands = [ cmd_encoded , zigzag ( dx ) , zigzag ( dy ) , CM...
Appends commands to _geometry to create an arc . - Returns False if nothing was added - Returns True and moves _last_x _last_y if some points where added
34,825
def sigterm ( self , signum , frame ) : self . logger . warning ( "Caught signal %s. Stopping daemon." % signum ) sys . exit ( 0 )
These actions will be done after SIGTERM .
34,826
def exit ( self ) : self . logger . warning ( "Stopping daemon." ) os . remove ( self . pid ) sys . exit ( 0 )
Cleanup pid file at exit .
34,827
def js_reverse_inline ( context ) : if 'request' in context : default_urlresolver = get_resolver ( getattr ( context [ 'request' ] , 'urlconf' , None ) ) else : default_urlresolver = get_resolver ( None ) return mark_safe ( generate_js ( default_urlresolver ) )
Outputs a string of javascript that can generate URLs via the use of the names given to those URLs .
34,828
def _iterate_records ( self ) : raise_invalid_gzip = False empty_record = False while True : try : self . record = self . _next_record ( self . next_line ) if raise_invalid_gzip : self . _raise_invalid_gzip_err ( ) yield self . record except EOFError : empty_record = True self . read_to_end ( ) if self . reader . decom...
iterate over each record
34,829
def _consume_blanklines ( self ) : empty_size = 0 first_line = True while True : line = self . reader . readline ( ) if len ( line ) == 0 : return None , empty_size stripped = line . rstrip ( ) if len ( stripped ) == 0 or first_line : empty_size += len ( line ) if len ( stripped ) != 0 : err_offset = self . fh . tell (...
Consume blank lines that are between records - For warcs there are usually 2 - For arcs may be 1 or 0 - For block gzipped files these are at end of each gzip envelope and are included in record length which is the full gzip envelope - For uncompressed they are between records and so are NOT part of the record length
34,830
def read_to_end ( self , record = None ) : if not self . record : return None if self . member_info : return None curr_offset = self . offset while True : b = self . record . raw_stream . read ( BUFF_SIZE ) if not b : break self . next_line , empty_size = self . _consume_blanklines ( ) self . offset = self . fh . tell ...
Read remainder of the stream If a digester is included update it with the data read
34,831
def _next_record ( self , next_line ) : record = self . loader . parse_record_stream ( self . reader , next_line , self . known_format , self . no_record_parse , self . ensure_http_headers ) self . member_info = None if not self . mixed_arc_warc : self . known_format = record . format return record
Use loader to parse the record from the reader stream Supporting warc and arc records
34,832
def wrap_stream ( stream , content_length ) : try : content_length = int ( content_length ) if content_length >= 0 : if isinstance ( stream , LimitReader ) : stream . limit = min ( stream . limit , content_length ) else : stream = LimitReader ( stream , content_length ) except ( ValueError , TypeError ) : pass return s...
If given content_length is an int > 0 wrap the stream in a LimitReader . Otherwise return the stream unaltered
34,833
def replace_header ( self , name , value ) : name_lower = name . lower ( ) for index in range ( len ( self . headers ) - 1 , - 1 , - 1 ) : curr_name , curr_value = self . headers [ index ] if curr_name . lower ( ) == name_lower : self . headers [ index ] = ( curr_name , value ) return curr_value self . headers . append...
replace header with new value or add new header return old header value if any
34,834
def validate_statusline ( self , valid_statusline ) : code = self . get_statuscode ( ) try : code = int ( code ) assert ( code > 0 ) return True except ( ValueError , AssertionError ) : self . statusline = valid_statusline return False
Check that the statusline is valid eg . starts with a numeric code . If not replace with passed in valid_statusline
34,835
def add_range ( self , start , part_len , total_len ) : content_range = 'bytes {0}-{1}/{2}' . format ( start , start + part_len - 1 , total_len ) self . statusline = '206 Partial Content' self . replace_header ( 'Content-Range' , content_range ) self . replace_header ( 'Content-Length' , str ( part_len ) ) self . repla...
Add range headers indicating that this a partial response
34,836
def parse ( self , stream , full_statusline = None ) : if full_statusline is None : full_statusline = stream . readline ( ) full_statusline = self . decode_header ( full_statusline ) statusline , total_read = _strip_count ( full_statusline , 0 ) headers = [ ] if total_read == 0 : raise EOFError ( ) elif not statusline ...
parse stream for status line and headers return a StatusAndHeaders object
34,837
def split_prefix ( key , prefixs ) : key_upper = key . upper ( ) for prefix in prefixs : if key_upper . startswith ( prefix ) : plen = len ( prefix ) return ( key_upper [ : plen ] , key [ plen : ] )
split key string into prefix and remainder for first matching prefix from a list
34,838
def ask_questions ( self ) : out_config = { } for key in c . CONFIG_QUESTIONS : section = key [ 1 ] print for question in section : answer = utils . ask ( question [ 1 ] , question [ 2 ] ) out_config [ "{0}_{1}" . format ( key [ 0 ] , question [ 0 ] ) ] = answer for key in c . CONFIG_MULTIPLE_CHOICE_QUESTIONS : section...
Obtain config settings from the user .
34,839
def log ( color , * args ) : if color in c . LOG_COLOR . keys ( ) : out_color = c . LOG_COLOR [ color ] else : out_color = color for arg in args : print clr . stringc ( arg , out_color )
Print a message with a specific color .
34,840
def usage ( ) : l_bracket = clr . stringc ( "[" , "dark gray" ) r_bracket = clr . stringc ( "]" , "dark gray" ) pipe = clr . stringc ( "|" , "dark gray" ) app_name = clr . stringc ( "%prog" , "bright blue" ) commands = clr . stringc ( "{0}" . format ( pipe ) . join ( c . VALID_ACTIONS ) , "normal" ) help = clr . string...
Return the usage for the help command .
34,841
def epilogue ( app_name ) : app_name = clr . stringc ( app_name , "bright blue" ) command = clr . stringc ( "command" , "cyan" ) help = clr . stringc ( "--help" , "green" ) return "\n%s %s %s for more info on a command\n" % ( app_name , command , help )
Return the epilogue for the help command .
34,842
def command_name ( app_name , command , help_text ) : command = clr . stringc ( command , "cyan" ) help = clr . stringc ( "--help" , "green" ) return "{0} {1} {2}\n{3}\n\n" . format ( app_name , command , help , help_text )
Return a snippet of help text for this command .
34,843
def role ( name , report , role_name_length ) : pad_role_name_by = 11 + role_name_length defaults = field_value ( report [ "total_defaults" ] , "defaults" , "blue" , 16 ) facts = field_value ( report [ "total_facts" ] , "facts" , "purple" , 16 ) files = field_value ( report [ "total_files" ] , "files" , "dark gray" , 1...
Print the role information .
34,844
def field_value ( key , label , color , padding ) : if not clr . has_colors and padding > 0 : padding = 7 if color == "bright gray" or color == "dark gray" : bright_prefix = "" else : bright_prefix = "bright " field = clr . stringc ( key , "{0}{1}" . format ( bright_prefix , color ) ) field_label = clr . stringc ( labe...
Print a specific field s stats .
34,845
def totals ( report , total_roles , role_name_length ) : roles_len_string = len ( str ( total_roles ) ) roles_label_len = 6 if clr . has_colors : roles_count_offset = 22 else : roles_count_offset = 13 roles_count_offset += role_name_length if roles_len_string > 1 : roles_count_offset -= 2 pad_roles_by = roles_count_off...
Print the totals for each role s stats .
34,846
def gen_totals ( report , file_type ) : label = clr . stringc ( file_type + " files " , "bright purple" ) ok = field_value ( report [ "ok_role" ] , "ok" , c . LOG_COLOR [ "ok" ] , 0 ) skipped = field_value ( report [ "skipped_role" ] , "skipped" , c . LOG_COLOR [ "skipped" ] , 16 ) changed = field_value ( report [ "c...
Print the gen totals .
34,847
def scan_totals ( report ) : ok = field_value ( report [ "ok_role" ] , "ok" , c . LOG_COLOR [ "ok" ] , 0 ) missing_readme = field_value ( report [ "missing_readme_role" ] , "missing readme(s)" , c . LOG_COLOR [ "missing_readme" ] , 16 ) missing_meta = field_value ( report [ "missing_meta_role" ] , "missing meta(s)" , c...
Print the scan totals .
34,848
def has_colors ( stream ) : if not hasattr ( stream , "isatty" ) : return False if not stream . isatty ( ) : return False try : import curses curses . setupterm ( ) return curses . tigetnum ( "colors" ) > 2 except : return False
Determine if the terminal supports ansi colors .
34,849
def stringc ( text , color ) : if has_colors : text = str ( text ) return "\033[" + codeCodes [ color ] + "m" + text + "\033[0m" else : return text
Return a string with terminal colors .
34,850
def execute_command ( self ) : stderr = "" role_count = 0 for role in utils . roles_dict ( self . roles_path ) : self . command = self . command . replace ( "%role_name" , role ) ( _ , err ) = utils . capture_shell ( "cd {0} && {1}" . format ( os . path . join ( self . roles_path , role ) , self . command ) ) stderr = ...
Execute the shell command .
34,851
def mkdir_p ( path ) : try : os . makedirs ( path ) except OSError as err : if err . errno == errno . EEXIST and os . path . isdir ( path ) : pass else : ui . error ( c . MESSAGES [ "path_unmakable" ] , err ) sys . exit ( 1 )
Emulate the behavior of mkdir - p .
34,852
def string_to_file ( path , input ) : mkdir_p ( os . path . dirname ( path ) ) with codecs . open ( path , "w+" , "UTF-8" ) as file : file . write ( input )
Write a file from a given string .
34,853
def file_to_string ( path ) : if not os . path . exists ( path ) : ui . error ( c . MESSAGES [ "path_missing" ] , path ) sys . exit ( 1 ) with codecs . open ( path , "r" , "UTF-8" ) as contents : return contents . read ( )
Return the contents of a file when given a path .
34,854
def file_to_list ( path ) : if not os . path . exists ( path ) : ui . error ( c . MESSAGES [ "path_missing" ] , path ) sys . exit ( 1 ) with codecs . open ( path , "r" , "UTF-8" ) as contents : lines = contents . read ( ) . splitlines ( ) return lines
Return the contents of a file as a list when given a path .
34,855
def url_to_string ( url ) : try : page = urllib2 . urlopen ( url ) except ( urllib2 . HTTPError , urllib2 . URLError ) as err : ui . error ( c . MESSAGES [ "url_unreachable" ] , err ) sys . exit ( 1 ) return page
Return the contents of a web site url as a string .
34,856
def template ( path , extend_path , out ) : files = [ ] if len ( extend_path ) > 0 : base_path = os . path . dirname ( extend_path ) new_base_path = os . path . join ( base_path , "README.{0}.j2" . format ( out ) ) if os . path . exists ( new_base_path ) : path = new_base_path if os . path . exists ( extend_path ) : fi...
Return a jinja2 template instance with extends support .
34,857
def files_in_path ( path ) : aggregated_files = [ ] for dir_ , _ , files in os . walk ( path ) : for file in files : relative_dir = os . path . relpath ( dir_ , path ) if ".git" not in relative_dir : relative_file = os . path . join ( relative_dir , file ) aggregated_files . append ( relative_file ) return aggregated_f...
Return a list of all files in a path but exclude git folders .
34,858
def exit_if_path_not_found ( path ) : if not os . path . exists ( path ) : ui . error ( c . MESSAGES [ "path_missing" ] , path ) sys . exit ( 1 )
Exit if the path is not found .
34,859
def yaml_load ( path , input = "" , err_quit = False ) : try : if len ( input ) > 0 : return yaml . safe_load ( input ) elif len ( path ) > 0 : return yaml . safe_load ( file_to_string ( path ) ) except Exception as err : file = os . path . basename ( path ) ui . error ( "" , c . MESSAGES [ "yaml_error" ] . replace ( "...
Return a yaml dict from a file or string with error handling .
34,860
def to_nice_yaml ( yaml_input , indentation = 2 ) : return yaml . safe_dump ( yaml_input , indent = indentation , allow_unicode = True , default_flow_style = False )
Return condensed yaml into human readable yaml .
34,861
def keys_in_dict ( d , parent_key , keys ) : for key , value in d . iteritems ( ) : if isinstance ( value , dict ) : keys_in_dict ( value , key , keys ) else : if parent_key : prefix = parent_key + "." else : prefix = "" keys . append ( prefix + key ) return keys
Create a list of keys from a dict recursively .
34,862
def swap_yaml_string ( file_path , swaps ) : original_file = file_to_string ( file_path ) new_file = original_file changed = False for item in swaps : match = re . compile ( r'(?<={0}: )(["\']?)(.*)\1' . format ( item [ 0 ] ) , re . MULTILINE ) new_file = re . sub ( match , item [ 1 ] , new_file ) if new_file != origin...
Swap a string in a yaml file without touching the existing formatting .
34,863
def exit_if_no_roles ( roles_count , roles_path ) : if roles_count == 0 : ui . warn ( c . MESSAGES [ "empty_roles_path" ] , roles_path ) sys . exit ( )
Exit if there were no roles found .
34,864
def roles_dict ( path , repo_prefix = "" , repo_sub_dir = "" ) : exit_if_path_not_found ( path ) aggregated_roles = { } roles = os . walk ( path ) . next ( ) [ 1 ] for role in roles : for sub_role in roles_dict ( path + "/" + role , repo_prefix = "" , repo_sub_dir = role + "/" ) : aggregated_roles [ role + "/" + sub_ro...
Return a dict of role names and repo paths .
34,865
def is_role ( path ) : seems_legit = False for folder in c . ANSIBLE_FOLDERS : if os . path . exists ( os . path . join ( path , folder ) ) : seems_legit = True return seems_legit
Determine if a path is an ansible role .
34,866
def stripped_args ( args ) : stripped_args = [ ] for arg in args : stripped_args . append ( arg . strip ( ) ) return stripped_args
Return the stripped version of the arguments .
34,867
def normalize_role ( role , config ) : if role . startswith ( config [ "scm_repo_prefix" ] ) : role_name = role . replace ( config [ "scm_repo_prefix" ] , "" ) else : if "." in role : galaxy_prefix = "{0}." . format ( config [ "scm_user" ] ) role_name = role . replace ( galaxy_prefix , "" ) elif "-" in role : role_name...
Normalize a role name .
34,868
def create_meta_main ( create_path , config , role , categories ) : meta_file = c . DEFAULT_META_FILE . replace ( "%author_name" , config [ "author_name" ] ) meta_file = meta_file . replace ( "%author_company" , config [ "author_company" ] ) meta_file = meta_file . replace ( "%license_type" , config [ "license_type" ] ...
Create a meta template .
34,869
def get_version ( path , default = "master" ) : version = default if os . path . exists ( path ) : version_contents = file_to_string ( path ) if version_contents : version = version_contents . strip ( ) return version
Return the version from a VERSION file
34,870
def write_config ( path , config ) : config_as_string = to_nice_yaml ( config ) config_as_string = "---\n" + config_as_string string_to_file ( path , config_as_string )
Write the config with a little post - converting formatting .
34,871
def limit_roles ( self ) : new_roles = { } roles = self . options . limit . split ( "," ) for key , value in self . roles . iteritems ( ) : for role in roles : role = role . strip ( ) if key == role : new_roles [ key ] = value self . roles = new_roles
Limit the roles being scanned .
34,872
def scan_roles ( self ) : for key , value in sorted ( self . roles . iteritems ( ) ) : self . paths [ "role" ] = os . path . join ( self . roles_path , key ) self . paths [ "meta" ] = os . path . join ( self . paths [ "role" ] , "meta" , "main.yml" ) self . paths [ "readme" ] = os . path . join ( self . paths [ "role" ...
Iterate over each role and report its stats .
34,873
def export_roles ( self ) : del self . report [ "state" ] del self . report [ "stats" ] for role in self . report [ "roles" ] : del self . report [ "roles" ] [ role ] [ "state" ] defaults_path = os . path . join ( self . roles_path , role , "defaults" , "main.yml" ) if os . path . exists ( defaults_path ) : defaults = ...
Export the roles to one of the export types .
34,874
def report_role ( self , role ) : self . yaml_files = [ ] fields = { "state" : "skipped" , "total_files" : self . gather_files ( ) , "total_lines" : self . gather_lines ( ) , "total_facts" : self . gather_facts ( ) , "total_defaults" : self . gather_defaults ( ) , "facts" : self . facts , "defaults" : self . defaults ,...
Return the fields gathered .
34,875
def gather_meta ( self ) : if not os . path . exists ( self . paths [ "meta" ] ) : return "" meta_dict = utils . yaml_load ( self . paths [ "meta" ] ) if meta_dict and "dependencies" in meta_dict : dep_list = [ ] for dependency in meta_dict [ "dependencies" ] : if type ( dependency ) is dict : dep_list . append ( depen...
Return the meta file .
34,876
def gather_readme ( self ) : if not os . path . exists ( self . paths [ "readme" ] ) : return "" return utils . file_to_string ( self . paths [ "readme" ] )
Return the readme file .
34,877
def gather_defaults ( self ) : total_defaults = 0 defaults_lines = [ ] if not os . path . exists ( self . paths [ "defaults" ] ) : self . defaults = "" return 0 file = open ( self . paths [ "defaults" ] , "r" ) for line in file : if len ( line ) > 0 : first_char = line [ 0 ] else : first_char = "" defaults_lines . appe...
Return the number of default variables .
34,878
def gather_facts ( self ) : facts = [ ] for file in self . yaml_files : facts += self . gather_facts_list ( file ) unique_facts = list ( set ( facts ) ) self . facts = unique_facts return len ( unique_facts )
Return the number of facts .
34,879
def gather_facts_list ( self , file ) : facts = [ ] contents = utils . file_to_string ( os . path . join ( self . paths [ "role" ] , file ) ) contents = re . sub ( r"\s+" , "" , contents ) matches = self . regex_facts . findall ( contents ) for match in matches : facts . append ( match . split ( ":" ) [ 1 ] ) return fa...
Return a list of facts .
34,880
def gather_files ( self ) : self . all_files = utils . files_in_path ( self . paths [ "role" ] ) return len ( self . all_files )
Return the number of files .
34,881
def gather_lines ( self ) : total_lines = 0 for file in self . all_files : full_path = os . path . join ( self . paths [ "role" ] , file ) with open ( full_path , "r" ) as f : for line in f : total_lines += 1 if full_path . endswith ( ".yml" ) : self . yaml_files . append ( full_path ) return total_lines
Return the number of lines .
34,882
def tally_role_columns ( self ) : totals = self . report [ "totals" ] roles = self . report [ "roles" ] totals [ "dependencies" ] = sum ( roles [ item ] [ "total_dependencies" ] for item in roles ) totals [ "defaults" ] = sum ( roles [ item ] [ "total_defaults" ] for item in roles ) totals [ "facts" ] = sum ( roles [ i...
Sum up all of the stat columns .
34,883
def valid_meta ( self , role ) : if os . path . exists ( self . paths [ "meta" ] ) : self . meta_dict = utils . yaml_load ( self . paths [ "meta" ] ) else : self . report [ "state" ] [ "missing_meta_role" ] += 1 self . report [ "roles" ] [ role ] [ "state" ] = "missing_meta" return False is_valid = True if isinstance (...
Return whether or not the meta file being read is valid .
34,884
def make_or_augment_meta ( self , role ) : if not os . path . exists ( self . paths [ "meta" ] ) : utils . create_meta_main ( self . paths [ "meta" ] , self . config , role , "" ) self . report [ "state" ] [ "ok_role" ] += 1 self . report [ "roles" ] [ role ] [ "state" ] = "ok" swaps = [ ( "author" , self . config [ "a...
Create or augment a meta file .
34,885
def write_readme ( self , role ) : j2_out = self . readme_template . render ( self . readme_template_vars ) self . update_gen_report ( role , "readme" , j2_out )
Write out a new readme file .
34,886
def write_meta ( self , role ) : meta_file = utils . file_to_string ( self . paths [ "meta" ] ) self . update_gen_report ( role , "meta" , meta_file )
Write out a new meta file .
34,887
def update_scan_report ( self , role ) : state = self . report [ "state" ] if self . gendoc : if self . report [ "roles" ] [ role ] [ "state" ] == "missing_meta" : return if os . path . exists ( self . paths [ "readme" ] ) : state [ "ok_role" ] += 1 self . report [ "roles" ] [ role ] [ "state" ] = "ok" else : state [ "...
Update the role state and adjust the scan totals .
34,888
def update_gen_report ( self , role , file , original ) : state = self . report [ "state" ] if not os . path . exists ( self . paths [ file ] ) : state [ "ok_role" ] += 1 self . report [ "roles" ] [ role ] [ "state" ] = "ok" elif ( self . report [ "roles" ] [ role ] [ file ] != original and self . report [ "roles" ] [ ...
Update the role state and adjust the gen totals .
34,889
def make_meta_dict_consistent ( self ) : if self . meta_dict is None : self . meta_dict = { } if "galaxy_info" not in self . meta_dict : self . meta_dict [ "galaxy_info" ] = { } if "dependencies" not in self . meta_dict : self . meta_dict [ "dependencies" ] = [ ] if "ansigenome_info" not in self . meta_dict : self . me...
Remove the possibility of the main keys being undefined .
34,890
def set_readme_template_vars ( self , role , repo_name ) : authors = [ ] author = { "name" : self . config [ "author_name" ] , "company" : self . config [ "author_company" ] , "url" : self . config [ "author_url" ] , "email" : self . config [ "author_email" ] , "twitter" : self . config [ "author_twitter" ] , } scm = {...
Set the readme template variables .
34,891
def exit_if_path_exists ( self ) : if os . path . exists ( self . output_path ) : ui . error ( c . MESSAGES [ "path_exists" ] , self . output_path ) sys . exit ( 1 )
Exit early if the path cannot be found .
34,892
def create_skeleton ( self ) : utils . string_to_file ( os . path . join ( self . output_path , "VERSION" ) , "master\n" ) for folder in c . ANSIBLE_FOLDERS : create_folder_path = os . path . join ( self . output_path , folder ) utils . mkdir_p ( create_folder_path ) mainyml_template = default_mainyml_template . replac...
Create the role s directory and file structure .
34,893
def create_travis_config ( self ) : test_runner = self . config [ "options_test_runner" ] role_url = "{0}" . format ( os . path . join ( self . config [ "scm_host" ] , self . config [ "scm_user" ] , self . config [ "scm_repo_prefix" ] + self . normalized_role ) ) travisyml_template = default_travisyml_template . replac...
Create a travis test setup .
34,894
def set_format ( self , format ) : if self . options . format : self . format = self . options . format else : self . format = self . config [ "default_format_" + format ]
Pick the correct default format .
34,895
def validate_format ( self , allowed_formats ) : if self . format in allowed_formats : return ui . error ( "Export type '{0}' does not accept '{1}' format, only: " "{2}" . format ( self . type , self . format , allowed_formats ) ) sys . exit ( 1 )
Validate the allowed formats for a specific type .
34,896
def graph_dot ( self ) : default_graphviz_template = roles_list = "" edges = "" adjusted_colors = c . X11_COLORS [ 125 : - 325 ] random . shuffle ( adjusted_colors ) backup_colors = adjusted_colors [ : ] for role , fields in sorted ( self . report [ "roles" ] . iteritems ( ) ) : name = utils . normalize_role ( role , s...
Export a graph of the data in dot format .
34,897
def exit_if_missing_graphviz ( self ) : ( out , err ) = utils . capture_shell ( "which dot" ) if "dot" not in out : ui . error ( c . MESSAGES [ "dot_missing" ] )
Detect the presence of the dot utility to make a png graph .
34,898
def reqs_txt ( self ) : role_lines = "" for role in sorted ( self . report [ "roles" ] ) : name = utils . normalize_role ( role , self . config ) galaxy_name = "{0}.{1}" . format ( self . config [ "scm_user" ] , name ) version_path = os . path . join ( self . roles_path , role , "VERSION" ) version = utils . get_versio...
Export a requirements file in txt format .
34,899
def reqs_yml ( self ) : default_yml_item = role_lines = "---\n" for role in sorted ( self . report [ "roles" ] ) : name = utils . normalize_role ( role , self . config ) galaxy_name = "{0}.{1}" . format ( self . config [ "scm_user" ] , name ) yml_item = default_yml_item if self . config [ "scm_host" ] : yml_item = yml_...
Export a requirements file in yml format .