idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
240,200 | def getFile ( self , name , relative = None ) : if self . pathCallback is not None : return getFile ( self . _getFileDeprecated ( name , relative ) ) return getFile ( name , relative or self . pathDirectory ) | Returns a file name or None | 52 | 6 |
240,201 | def getFontName ( self , names , default = "helvetica" ) : # print names, self.fontList if type ( names ) is not ListType : if type ( names ) not in six . string_types : names = str ( names ) names = names . strip ( ) . split ( "," ) for name in names : if type ( name ) not in six . string_types : name = str ( name ) font = self . fontList . get ( name . strip ( ) . lower ( ) , None ) if font is not None : return font return self . fontList . get ( default , None ) | Name of a font | 133 | 4 |
240,202 | def pisaPreLoop ( node , context , collect = False ) : data = u"" if node . nodeType == Node . TEXT_NODE and collect : data = node . data elif node . nodeType == Node . ELEMENT_NODE : name = node . tagName . lower ( ) if name in ( "style" , "link" ) : attr = pisaGetAttributes ( context , name , node . attributes ) media = [ x . strip ( ) for x in attr . media . lower ( ) . split ( "," ) if x . strip ( ) ] if attr . get ( "type" , "" ) . lower ( ) in ( "" , "text/css" ) and ( not media or "all" in media or "print" in media or "pdf" in media ) : if name == "style" : for node in node . childNodes : data += pisaPreLoop ( node , context , collect = True ) context . addCSS ( data ) return u"" if name == "link" and attr . href and attr . rel . lower ( ) == "stylesheet" : # print "CSS LINK", attr context . addCSS ( '\n@import "%s" %s;' % ( attr . href , "," . join ( media ) ) ) for node in node . childNodes : result = pisaPreLoop ( node , context , collect = collect ) if collect : data += result return data | Collect all CSS definitions | 315 | 4 |
240,203 | def pisaParser ( src , context , default_css = "" , xhtml = False , encoding = None , xml_output = None ) : global CSSAttrCache CSSAttrCache = { } if xhtml : # TODO: XHTMLParser doesn't see to exist... parser = html5lib . XHTMLParser ( tree = treebuilders . getTreeBuilder ( "dom" ) ) else : parser = html5lib . HTMLParser ( tree = treebuilders . getTreeBuilder ( "dom" ) ) if isinstance ( src , six . text_type ) : # If an encoding was provided, do not change it. if not encoding : encoding = "utf-8" src = src . encode ( encoding ) src = pisaTempFile ( src , capacity = context . capacity ) # # Test for the restrictions of html5lib # if encoding: # # Workaround for html5lib<0.11.1 # if hasattr(inputstream, "isValidEncoding"): # if encoding.strip().lower() == "utf8": # encoding = "utf-8" # if not inputstream.isValidEncoding(encoding): # log.error("%r is not a valid encoding e.g. 'utf8' is not valid but 'utf-8' is!", encoding) # else: # if inputstream.codecName(encoding) is None: # log.error("%r is not a valid encoding", encoding) document = parser . parse ( src , ) # encoding=encoding) if xml_output : if encoding : xml_output . write ( document . toprettyxml ( encoding = encoding ) ) else : xml_output . write ( document . toprettyxml ( encoding = "utf8" ) ) if default_css : context . addDefaultCSS ( default_css ) pisaPreLoop ( document , context ) # try: context . parseCSS ( ) # except: # context.cssText = DEFAULT_CSS # context.parseCSS() # context.debug(9, pprint.pformat(context.css)) pisaLoop ( document , context ) return context | - Parse HTML and get miniDOM - Extract CSS informations add default CSS parse CSS - Handle the document DOM itself and build reportlab story - Return Context object | 455 | 33 |
240,204 | def doLayout ( self , width ) : # Calculate dimensions self . width = width font_sizes = [ 0 ] + [ frag . get ( "fontSize" , 0 ) for frag in self ] self . fontSize = max ( font_sizes ) self . height = self . lineHeight = max ( frag * self . LINEHEIGHT for frag in font_sizes ) # Apply line height y = ( self . lineHeight - self . fontSize ) # / 2 for frag in self : frag [ "y" ] = y return self . height | Align words in previous line . | 119 | 7 |
240,205 | def splitIntoLines ( self , maxWidth , maxHeight , splitted = False ) : self . lines = [ ] self . height = 0 self . maxWidth = self . width = maxWidth self . maxHeight = maxHeight boxStack = [ ] style = self . style x = 0 # Start with indent in first line of text if not splitted : x = style [ "textIndent" ] lenText = len ( self ) pos = 0 while pos < lenText : # Reset values for new line posBegin = pos line = Line ( style ) # Update boxes for next line for box in copy . copy ( boxStack ) : box [ "x" ] = 0 line . append ( BoxBegin ( box ) ) while pos < lenText : # Get fragment, its width and set X frag = self [ pos ] fragWidth = frag [ "width" ] frag [ "x" ] = x pos += 1 # Keep in mind boxes for next lines if isinstance ( frag , BoxBegin ) : boxStack . append ( frag ) elif isinstance ( frag , BoxEnd ) : boxStack . pop ( ) # If space or linebreak handle special way if frag . isSoft : if frag . isLF : line . append ( frag ) break # First element of line should not be a space if x == 0 : continue # Keep in mind last possible line break # The elements exceed the current line elif fragWidth + x > maxWidth : break # Add fragment to line and update x x += fragWidth line . append ( frag ) # Remove trailing white spaces while line and line [ - 1 ] . name in ( "space" , "br" ) : line . pop ( ) # Add line to list line . dumpFragments ( ) # if line: self . height += line . doLayout ( self . width ) self . lines . append ( line ) # If not enough space for current line force to split if self . height > maxHeight : return posBegin # Reset variables x = 0 # Apply alignment self . lines [ - 1 ] . isLast = True for line in self . lines : line . doAlignment ( maxWidth , style [ "textAlign" ] ) return None | Split text into lines and calculate X positions . If we need more space in height than available we return the rest of the text | 464 | 25 |
240,206 | def dumpLines ( self ) : for i , line in enumerate ( self . lines ) : logger . debug ( "Line %d:" , i ) logger . debug ( line . dumpFragments ( ) ) | For debugging dump all line and their content | 45 | 8 |
240,207 | def wrap ( self , availWidth , availHeight ) : # memorize available space self . avWidth = availWidth self . avHeight = availHeight logger . debug ( "*** wrap (%f, %f)" , availWidth , availHeight ) if not self . text : logger . debug ( "*** wrap (%f, %f) needed" , 0 , 0 ) return 0 , 0 # Split lines width = availWidth self . splitIndex = self . text . splitIntoLines ( width , availHeight ) self . width , self . height = availWidth , self . text . height logger . debug ( "*** wrap (%f, %f) needed, splitIndex %r" , self . width , self . height , self . splitIndex ) return self . width , self . height | Determine the rectangle this paragraph really needs . | 166 | 10 |
240,208 | def split ( self , availWidth , availHeight ) : logger . debug ( "*** split (%f, %f)" , availWidth , availHeight ) splitted = [ ] if self . splitIndex : text1 = self . text [ : self . splitIndex ] text2 = self . text [ self . splitIndex : ] p1 = Paragraph ( Text ( text1 ) , self . style , debug = self . debug ) p2 = Paragraph ( Text ( text2 ) , self . style , debug = self . debug , splitted = True ) splitted = [ p1 , p2 ] logger . debug ( "*** text1 %s / text %s" , len ( text1 ) , len ( text2 ) ) logger . debug ( '*** return %s' , self . splitted ) return splitted | Split ourselves in two paragraphs . | 175 | 6 |
240,209 | def draw ( self ) : logger . debug ( "*** draw" ) if not self . text : return canvas = self . canv style = self . style canvas . saveState ( ) # Draw box arround paragraph for debugging if self . debug : bw = 0.5 bc = Color ( 1 , 1 , 0 ) bg = Color ( 0.9 , 0.9 , 0.9 ) canvas . setStrokeColor ( bc ) canvas . setLineWidth ( bw ) canvas . setFillColor ( bg ) canvas . rect ( style . leftIndent , 0 , self . width , self . height , fill = 1 , stroke = 1 ) y = 0 dy = self . height for line in self . text . lines : y += line . height for frag in line : # Box if hasattr ( frag , "draw" ) : frag . draw ( canvas , dy - y ) # Text if frag . get ( "text" , "" ) : canvas . setFont ( frag [ "fontName" ] , frag [ "fontSize" ] ) canvas . setFillColor ( frag . get ( "color" , style [ "color" ] ) ) canvas . drawString ( frag [ "x" ] , dy - y + frag [ "y" ] , frag [ "text" ] ) # XXX LINK link = frag . get ( "link" , None ) if link : _scheme_re = re . compile ( '^[a-zA-Z][-+a-zA-Z0-9]+$' ) x , y , w , h = frag [ "x" ] , dy - y , frag [ "width" ] , frag [ "fontSize" ] rect = ( x , y , w , h ) if isinstance ( link , six . text_type ) : link = link . encode ( 'utf8' ) parts = link . split ( ':' , 1 ) scheme = len ( parts ) == 2 and parts [ 0 ] . lower ( ) or '' if _scheme_re . match ( scheme ) and scheme != 'document' : kind = scheme . lower ( ) == 'pdf' and 'GoToR' or 'URI' if kind == 'GoToR' : link = parts [ 1 ] canvas . linkURL ( link , rect , relative = 1 , kind = kind ) else : if link [ 0 ] == '#' : link = link [ 1 : ] scheme = '' canvas . linkRect ( "" , scheme != 'document' and link or parts [ 1 ] , rect , relative = 1 ) canvas . restoreState ( ) | Render the content of the paragraph . | 552 | 7 |
240,210 | def showLogging ( debug = False ) : try : log_level = logging . WARN log_format = LOG_FORMAT_DEBUG if debug : log_level = logging . DEBUG logging . basicConfig ( level = log_level , format = log_format ) except : logging . basicConfig ( ) | Shortcut for enabling log dump | 64 | 6 |
240,211 | def parseFile ( self , srcFile , closeFile = False ) : try : result = self . parse ( srcFile . read ( ) ) finally : if closeFile : srcFile . close ( ) return result | Parses CSS file - like objects using the current cssBuilder . Use for external stylesheets . | 44 | 22 |
240,212 | def parse ( self , src ) : self . cssBuilder . beginStylesheet ( ) try : # XXX Some simple preprocessing src = cssSpecial . cleanupCSS ( src ) try : src , stylesheet = self . _parseStylesheet ( src ) except self . ParseError as err : err . setFullCSSSource ( src ) raise finally : self . cssBuilder . endStylesheet ( ) return stylesheet | Parses CSS string source using the current cssBuilder . Use for embedded stylesheets . | 92 | 20 |
240,213 | def parseInline ( self , src ) : self . cssBuilder . beginInline ( ) try : try : src , properties = self . _parseDeclarationGroup ( src . strip ( ) , braces = False ) except self . ParseError as err : err . setFullCSSSource ( src , inline = True ) raise result = self . cssBuilder . inline ( properties ) finally : self . cssBuilder . endInline ( ) return result | Parses CSS inline source string using the current cssBuilder . Use to parse a tag s sytle - like attribute . | 97 | 26 |
240,214 | def parseAttributes ( self , attributes = None , * * kwAttributes ) : attributes = attributes if attributes is not None else { } if attributes : kwAttributes . update ( attributes ) self . cssBuilder . beginInline ( ) try : properties = [ ] try : for propertyName , src in six . iteritems ( kwAttributes ) : src , property = self . _parseDeclarationProperty ( src . strip ( ) , propertyName ) properties . append ( property ) except self . ParseError as err : err . setFullCSSSource ( src , inline = True ) raise result = self . cssBuilder . inline ( properties ) finally : self . cssBuilder . endInline ( ) return result | Parses CSS attribute source strings and return as an inline stylesheet . Use to parse a tag s highly CSS - based attributes like font . | 151 | 29 |
240,215 | def parseSingleAttr ( self , attrValue ) : results = self . parseAttributes ( temp = attrValue ) if 'temp' in results [ 1 ] : return results [ 1 ] [ 'temp' ] else : return results [ 0 ] [ 'temp' ] | Parse a single CSS attribute source string and returns the built CSS expression . Use to parse a tag s highly CSS - based attributes like font . | 58 | 29 |
240,216 | def _parseAtFrame ( self , src ) : src = src [ len ( '@frame ' ) : ] . lstrip ( ) box , src = self . _getIdent ( src ) src , properties = self . _parseDeclarationGroup ( src . lstrip ( ) ) result = [ self . cssBuilder . atFrame ( box , properties ) ] return src . lstrip ( ) , result | XXX Proprietary for PDF | 86 | 6 |
240,217 | def ErrorMsg ( ) : import traceback limit = None _type , value , tb = sys . exc_info ( ) _list = traceback . format_tb ( tb , limit ) + traceback . format_exception_only ( _type , value ) return "Traceback (innermost last):\n" + "%-20s %s" % ( " " . join ( _list [ : - 1 ] ) , _list [ - 1 ] ) | Helper to get a nice traceback as string | 103 | 9 |
240,218 | def transform_attrs ( obj , keys , container , func , extras = None ) : cpextras = extras for reportlab , css in keys : extras = cpextras if extras is None : extras = [ ] elif not isinstance ( extras , list ) : extras = [ extras ] if css in container : extras . insert ( 0 , container [ css ] ) setattr ( obj , reportlab , func ( * extras ) ) | Allows to apply one function to set of keys cheching if key is in container also trasform ccs key to report lab keys . | 97 | 28 |
240,219 | def copy_attrs ( obj1 , obj2 , attrs ) : for attr in attrs : value = getattr ( obj2 , attr ) if hasattr ( obj2 , attr ) else None if value is None and isinstance ( obj2 , dict ) and attr in obj2 : value = obj2 [ attr ] setattr ( obj1 , attr , value ) | Allows copy a list of attributes from object2 to object1 . Useful for copy ccs attributes to fragment | 85 | 21 |
240,220 | def set_value ( obj , attrs , value , _copy = False ) : for attr in attrs : if _copy : value = copy ( value ) setattr ( obj , attr , value ) | Allows set the same value to a list of attributes | 45 | 10 |
240,221 | def getColor ( value , default = None ) : if isinstance ( value , Color ) : return value value = str ( value ) . strip ( ) . lower ( ) if value == "transparent" or value == "none" : return default if value in COLOR_BY_NAME : return COLOR_BY_NAME [ value ] if value . startswith ( "#" ) and len ( value ) == 4 : value = "#" + value [ 1 ] + value [ 1 ] + value [ 2 ] + value [ 2 ] + value [ 3 ] + value [ 3 ] elif rgb_re . search ( value ) : # e.g., value = "<css function: rgb(153, 51, 153)>", go figure: r , g , b = [ int ( x ) for x in rgb_re . search ( value ) . groups ( ) ] value = "#%02x%02x%02x" % ( r , g , b ) else : # Shrug pass return toColor ( value , default ) | Convert to color value . This returns a Color object instance from a text bit . | 221 | 17 |
240,222 | def getCoords ( x , y , w , h , pagesize ) : #~ print pagesize ax , ay = pagesize if x < 0 : x = ax + x if y < 0 : y = ay + y if w is not None and h is not None : if w <= 0 : w = ( ax - x + w ) if h <= 0 : h = ( ay - y + h ) return x , ( ay - y - h ) , w , h return x , ( ay - y ) | As a stupid programmer I like to use the upper left corner of the document as the 0 0 coords therefore we need to do some fancy calculations | 109 | 29 |
240,223 | def getFrameDimensions ( data , page_width , page_height ) : box = data . get ( "-pdf-frame-box" , [ ] ) if len ( box ) == 4 : return [ getSize ( x ) for x in box ] top = getSize ( data . get ( "top" , 0 ) ) left = getSize ( data . get ( "left" , 0 ) ) bottom = getSize ( data . get ( "bottom" , 0 ) ) right = getSize ( data . get ( "right" , 0 ) ) if "height" in data : height = getSize ( data [ "height" ] ) if "top" in data : top = getSize ( data [ "top" ] ) bottom = page_height - ( top + height ) elif "bottom" in data : bottom = getSize ( data [ "bottom" ] ) top = page_height - ( bottom + height ) if "width" in data : width = getSize ( data [ "width" ] ) if "left" in data : left = getSize ( data [ "left" ] ) right = page_width - ( left + width ) elif "right" in data : right = getSize ( data [ "right" ] ) left = page_width - ( right + width ) top += getSize ( data . get ( "margin-top" , 0 ) ) left += getSize ( data . get ( "margin-left" , 0 ) ) bottom += getSize ( data . get ( "margin-bottom" , 0 ) ) right += getSize ( data . get ( "margin-right" , 0 ) ) width = page_width - ( left + right ) height = page_height - ( top + bottom ) return left , top , width , height | Calculate dimensions of a frame | 380 | 7 |
240,224 | def getPos ( position , pagesize ) : position = str ( position ) . split ( ) if len ( position ) != 2 : raise Exception ( "position not defined right way" ) x , y = [ getSize ( pos ) for pos in position ] return getCoords ( x , y , None , None , pagesize ) | Pair of coordinates | 70 | 4 |
240,225 | def makeTempFile ( self ) : if self . strategy == 0 : try : new_delegate = self . STRATEGIES [ 1 ] ( ) new_delegate . write ( self . getvalue ( ) ) self . _delegate = new_delegate self . strategy = 1 log . warn ( "Created temporary file %s" , self . name ) except : self . capacity = - 1 | Switch to next startegy . If an error occured stay with the first strategy | 86 | 17 |
240,226 | def getvalue ( self ) : if self . strategy == 0 : return self . _delegate . getvalue ( ) self . _delegate . flush ( ) self . _delegate . seek ( 0 ) value = self . _delegate . read ( ) if not isinstance ( value , six . binary_type ) : value = value . encode ( 'utf-8' ) return value | Get value of file . Work around for second strategy . Always returns bytes | 83 | 14 |
240,227 | def write ( self , value ) : if self . capacity > 0 and self . strategy == 0 : len_value = len ( value ) if len_value >= self . capacity : needs_new_strategy = True else : self . seek ( 0 , 2 ) # find end of file needs_new_strategy = ( self . tell ( ) + len_value ) >= self . capacity if needs_new_strategy : self . makeTempFile ( ) if not isinstance ( value , six . binary_type ) : value = value . encode ( 'utf-8' ) self . _delegate . write ( value ) | If capacity ! = - 1 and length of file > capacity it is time to switch | 134 | 17 |
240,228 | def setMimeTypeByName ( self , name ) : mimetype = mimetypes . guess_type ( name ) [ 0 ] if mimetype is not None : self . mimetype = mimetypes . guess_type ( name ) [ 0 ] . split ( ";" ) [ 0 ] | Guess the mime type | 66 | 6 |
240,229 | def _sameFrag ( f , g ) : if ( hasattr ( f , 'cbDefn' ) or hasattr ( g , 'cbDefn' ) or hasattr ( f , 'lineBreak' ) or hasattr ( g , 'lineBreak' ) ) : return 0 for a in ( 'fontName' , 'fontSize' , 'textColor' , 'backColor' , 'rise' , 'underline' , 'strike' , 'link' ) : if getattr ( f , a , None ) != getattr ( g , a , None ) : return 0 return 1 | returns 1 if two ParaFrags map out the same | 128 | 13 |
240,230 | def _drawBullet ( canvas , offset , cur_y , bulletText , style ) : tx2 = canvas . beginText ( style . bulletIndent , cur_y + getattr ( style , "bulletOffsetY" , 0 ) ) tx2 . setFont ( style . bulletFontName , style . bulletFontSize ) tx2 . setFillColor ( hasattr ( style , 'bulletColor' ) and style . bulletColor or style . textColor ) if isinstance ( bulletText , basestring ) : tx2 . textOut ( bulletText ) else : for f in bulletText : if hasattr ( f , "image" ) : image = f . image width = image . drawWidth height = image . drawHeight gap = style . bulletFontSize * 0.25 img = image . getImage ( ) # print style.bulletIndent, offset, width canvas . drawImage ( img , style . leftIndent - width - gap , cur_y + getattr ( style , "bulletOffsetY" , 0 ) , width , height ) else : tx2 . setFont ( f . fontName , f . fontSize ) tx2 . setFillColor ( f . textColor ) tx2 . textOut ( f . text ) canvas . drawText ( tx2 ) #AR making definition lists a bit less ugly #bulletEnd = tx2.getX() bulletEnd = tx2 . getX ( ) + style . bulletFontSize * 0.6 offset = max ( offset , bulletEnd - style . leftIndent ) return offset | draw a bullet text could be a simple string or a frag list | 330 | 13 |
240,231 | def splitLines0 ( frags , widths ) : #initialise the algorithm lineNum = 0 maxW = widths [ lineNum ] i = - 1 l = len ( frags ) lim = start = 0 text = frags [ 0 ] while 1 : #find a non whitespace character while i < l : while start < lim and text [ start ] == ' ' : start += 1 if start == lim : i += 1 if i == l : break start = 0 f = frags [ i ] text = f . text lim = len ( text ) else : break # we found one if start == lim : break # if we didn't find one we are done #start of a line g = ( None , None , None ) line = [ ] cLen = 0 nSpaces = 0 while cLen < maxW : j = text . find ( ' ' , start ) if j < 0 : j == lim w = stringWidth ( text [ start : j ] , f . fontName , f . fontSize ) cLen += w if cLen > maxW and line != [ ] : cLen = cLen - w #this is the end of the line while g . text [ lim ] == ' ' : lim -= 1 nSpaces -= 1 break if j < 0 : j = lim if g [ 0 ] is f : g [ 2 ] = j #extend else : g = ( f , start , j ) line . append ( g ) if j == lim : i += 1 | given a list of ParaFrags we return a list of ParaLines | 319 | 17 |
240,232 | def cjkFragSplit ( frags , maxWidths , calcBounds , encoding = 'utf8' ) : from reportlab . rl_config import _FUZZ U = [ ] # get a list of single glyphs with their widths etc etc for f in frags : text = f . text if not isinstance ( text , unicode ) : text = text . decode ( encoding ) if text : U . extend ( [ cjkU ( t , f , encoding ) for t in text ] ) else : U . append ( cjkU ( text , f , encoding ) ) lines = [ ] widthUsed = lineStartPos = 0 maxWidth = maxWidths [ 0 ] for i , u in enumerate ( U ) : w = u . width widthUsed += w lineBreak = hasattr ( u . frag , 'lineBreak' ) endLine = ( widthUsed > maxWidth + _FUZZ and widthUsed > 0 ) or lineBreak if endLine : if lineBreak : continue extraSpace = maxWidth - widthUsed + w #This is the most important of the Japanese typography rules. #if next character cannot start a line, wrap it up to this line so it hangs #in the right margin. We won't do two or more though - that's unlikely and #would result in growing ugliness. nextChar = U [ i ] if nextChar in ALL_CANNOT_START : extraSpace -= w i += 1 lines . append ( makeCJKParaLine ( U [ lineStartPos : i ] , extraSpace , calcBounds ) ) try : maxWidth = maxWidths [ len ( lines ) ] except IndexError : maxWidth = maxWidths [ - 1 ] # use the last one lineStartPos = i widthUsed = w i -= 1 #any characters left? if widthUsed > 0 : lines . append ( makeCJKParaLine ( U [ lineStartPos : ] , maxWidth - widthUsed , calcBounds ) ) return ParaLines ( kind = 1 , lines = lines ) | This attempts to be wordSplit for frags using the dumb algorithm | 441 | 13 |
240,233 | def minWidth ( self ) : frags = self . frags nFrags = len ( frags ) if not nFrags : return 0 if nFrags == 1 : f = frags [ 0 ] fS = f . fontSize fN = f . fontName words = hasattr ( f , 'text' ) and split ( f . text , ' ' ) or f . words func = lambda w , fS = fS , fN = fN : stringWidth ( w , fN , fS ) else : words = _getFragWords ( frags ) func = lambda x : x [ 0 ] return max ( map ( func , words ) ) | Attempt to determine a minimum sensible width | 143 | 7 |
240,234 | def breakLinesCJK ( self , width ) : if self . debug : print ( id ( self ) , "breakLinesCJK" ) if not isinstance ( width , ( list , tuple ) ) : maxWidths = [ width ] else : maxWidths = width style = self . style #for bullets, work out width and ensure we wrap the right amount onto line one _handleBulletWidth ( self . bulletText , style , maxWidths ) if len ( self . frags ) > 1 : autoLeading = getattr ( self , 'autoLeading' , getattr ( style , 'autoLeading' , '' ) ) calcBounds = autoLeading not in ( '' , 'off' ) return cjkFragSplit ( self . frags , maxWidths , calcBounds , self . encoding ) elif not len ( self . frags ) : return ParaLines ( kind = 0 , fontSize = style . fontSize , fontName = style . fontName , textColor = style . textColor , lines = [ ] , ascent = style . fontSize , descent = - 0.2 * style . fontSize ) f = self . frags [ 0 ] if 1 and hasattr ( self , 'blPara' ) and getattr ( self , '_splitpara' , 0 ) : #NB this is an utter hack that awaits the proper information #preserving splitting algorithm return f . clone ( kind = 0 , lines = self . blPara . lines ) lines = [ ] self . height = 0 f = self . frags [ 0 ] if hasattr ( f , 'text' ) : text = f . text else : text = '' . join ( getattr ( f , 'words' , [ ] ) ) from reportlab . lib . textsplit import wordSplit lines = wordSplit ( text , maxWidths [ 0 ] , f . fontName , f . fontSize ) #the paragraph drawing routine assumes multiple frags per line, so we need an #extra list like this # [space, [text]] # wrappedLines = [ ( sp , [ line ] ) for ( sp , line ) in lines ] return f . clone ( kind = 0 , lines = wrappedLines , ascent = f . fontSize , descent = - 0.2 * f . fontSize ) | Initially the dumbest possible wrapping algorithm . Cannot handle font variations . | 500 | 13 |
240,235 | def getPlainText ( self , identify = None ) : frags = getattr ( self , 'frags' , None ) if frags : plains = [ ] for frag in frags : if hasattr ( frag , 'text' ) : plains . append ( frag . text ) return '' . join ( plains ) elif identify : text = getattr ( self , 'text' , None ) if text is None : text = repr ( self ) return text else : return '' | Convenience function for templates which want access to the raw text without XML tags . | 102 | 17 |
240,236 | def getActualLineWidths0 ( self ) : assert hasattr ( self , 'width' ) , "Cannot call this method before wrap()" if self . blPara . kind : func = lambda frag , w = self . width : w - frag . extraSpace else : func = lambda frag , w = self . width : w - frag [ 0 ] return map ( func , self . blPara . lines ) | Convenience function ; tells you how wide each line actually is . For justified styles this will be the same as the wrap width ; for others it might be useful for seeing if paragraphs will fit in spaces . | 91 | 42 |
240,237 | def link_callback ( uri , rel ) : # use short variable names sUrl = settings . STATIC_URL # Typically /static/ sRoot = settings . STATIC_ROOT # Typically /home/userX/project_static/ mUrl = settings . MEDIA_URL # Typically /static/media/ # Typically /home/userX/project_static/media/ mRoot = settings . MEDIA_ROOT # convert URIs to absolute system paths if uri . startswith ( mUrl ) : path = os . path . join ( mRoot , uri . replace ( mUrl , "" ) ) elif uri . startswith ( sUrl ) : path = os . path . join ( sRoot , uri . replace ( sUrl , "" ) ) else : return uri # handle absolute uri (ie: http://some.tld/foo.png) # make sure that file exists if not os . path . isfile ( path ) : raise Exception ( 'media URI must start with %s or %s' % ( sUrl , mUrl ) ) return path | Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources | 237 | 18 |
240,238 | def start ( ) : setupdir = dirname ( dirname ( __file__ ) ) curdir = os . getcwd ( ) # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration # from a file called 'dev.cfg'. If it's not there, the project # is probably installed and we'll look first for a file called # 'prod.cfg' in the current directory and then for a default # config file called 'default.cfg' packaged in the egg. if len ( sys . argv ) > 1 : configfile = sys . argv [ 1 ] elif exists ( join ( setupdir , "setup.py" ) ) : configfile = join ( setupdir , "dev.cfg" ) elif exists ( join ( curdir , "prod.cfg" ) ) : configfile = join ( curdir , "prod.cfg" ) else : try : configfile = pkg_resources . resource_filename ( pkg_resources . Requirement . parse ( "tgpisa" ) , "config/default.cfg" ) except pkg_resources . DistributionNotFound : raise ConfigurationError ( "Could not find default configuration." ) turbogears . update_config ( configfile = configfile , modulename = "tgpisa.config" ) from tgpisa . controllers import Root turbogears . start_server ( Root ( ) ) | Start the CherryPy application server . | 326 | 7 |
240,239 | def mergeStyles ( self , styles ) : for k , v in six . iteritems ( styles ) : if k in self and self [ k ] : self [ k ] = copy . copy ( self [ k ] ) self [ k ] . update ( v ) else : self [ k ] = v | XXX Bugfix for use in PISA | 64 | 8 |
240,240 | def atPage ( self , page , pseudopage , declarations ) : return self . ruleset ( [ self . selector ( '*' ) ] , declarations ) | This is overriden by xhtml2pdf . context . pisaCSSBuilder | 34 | 17 |
240,241 | def handle_nextPageTemplate ( self , pt ) : has_left_template = self . _has_template_for_name ( pt + '_left' ) has_right_template = self . _has_template_for_name ( pt + '_right' ) if has_left_template and has_right_template : pt = [ pt + '_left' , pt + '_right' ] '''On endPage change to the page template with name or index pt''' if isinstance ( pt , str ) : if hasattr ( self , '_nextPageTemplateCycle' ) : del self . _nextPageTemplateCycle for t in self . pageTemplates : if t . id == pt : self . _nextPageTemplateIndex = self . pageTemplates . index ( t ) return raise ValueError ( "can't find template('%s')" % pt ) elif isinstance ( pt , int ) : if hasattr ( self , '_nextPageTemplateCycle' ) : del self . _nextPageTemplateCycle self . _nextPageTemplateIndex = pt elif isinstance ( pt , ( list , tuple ) ) : #used for alternating left/right pages #collect the refs to the template objects, complain if any are bad c = PTCycle ( ) for ptn in pt : #special case name used to short circuit the iteration if ptn == '*' : c . _restart = len ( c ) continue for t in self . pageTemplates : if t . id == ptn . strip ( ) : c . append ( t ) break if not c : raise ValueError ( "No valid page templates in cycle" ) elif c . _restart > len ( c ) : raise ValueError ( "Invalid cycle restart position" ) #ensure we start on the first one$ self . _nextPageTemplateCycle = c . cyclicIterator ( ) else : raise TypeError ( "Argument pt should be string or integer or list" ) | if pt has also templates for even and odd page convert it to list | 430 | 14 |
240,242 | def getRGBData ( self ) : if self . _data is None : self . _dataA = None if sys . platform [ 0 : 4 ] == 'java' : import jarray # TODO: Move to top. from java . awt . image import PixelGrabber width , height = self . getSize ( ) buffer = jarray . zeros ( width * height , 'i' ) pg = PixelGrabber ( self . _image , 0 , 0 , width , height , buffer , 0 , width ) pg . grabPixels ( ) # there must be a way to do this with a cast not a byte-level loop, # I just haven't found it yet... pixels = [ ] a = pixels . append for rgb in buffer : a ( chr ( ( rgb >> 16 ) & 0xff ) ) a ( chr ( ( rgb >> 8 ) & 0xff ) ) a ( chr ( rgb & 0xff ) ) self . _data = '' . join ( pixels ) self . mode = 'RGB' else : im = self . _image mode = self . mode = im . mode if mode == 'RGBA' : im . load ( ) self . _dataA = PmlImageReader ( im . split ( ) [ 3 ] ) im = im . convert ( 'RGB' ) self . mode = 'RGB' elif mode not in ( 'L' , 'RGB' , 'CMYK' ) : im = im . convert ( 'RGB' ) self . mode = 'RGB' if hasattr ( im , 'tobytes' ) : self . _data = im . tobytes ( ) else : # PIL compatibility self . _data = im . tostring ( ) return self . _data | Return byte array of RGB data as string | 369 | 8 |
240,243 | def wrap ( self , availWidth , availHeight ) : availHeight = self . setMaxHeight ( availHeight ) # print "image wrap", id(self), availWidth, availHeight, self.drawWidth, self.drawHeight width = min ( self . drawWidth , availWidth ) wfactor = float ( width ) / self . drawWidth height = min ( self . drawHeight , availHeight * MAX_IMAGE_RATIO ) hfactor = float ( height ) / self . drawHeight factor = min ( wfactor , hfactor ) self . dWidth = self . drawWidth * factor self . dHeight = self . drawHeight * factor # print "imgage result", factor, self.dWidth, self.dHeight return self . dWidth , self . dHeight | This can be called more than once! Do not overwrite important data like drawWidth | 166 | 16 |
240,244 | def _normWidth ( self , w , maxw ) : if type ( w ) == type ( "" ) : w = ( ( maxw / 100.0 ) * float ( w [ : - 1 ] ) ) elif ( w is None ) or ( w == "*" ) : w = maxw return min ( w , maxw ) | Helper for calculating percentages | 74 | 4 |
240,245 | def wrap ( self , availWidth , availHeight ) : widths = ( availWidth - self . rightColumnWidth , self . rightColumnWidth ) # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len ( self . _lastEntries ) == 0 : _tempEntries = [ ( 0 , 'Placeholder for table of contents' , 0 ) ] else : _tempEntries = self . _lastEntries lastMargin = 0 tableData = [ ] tableStyle = [ ( 'VALIGN' , ( 0 , 0 ) , ( - 1 , - 1 ) , 'TOP' ) , ( 'LEFTPADDING' , ( 0 , 0 ) , ( - 1 , - 1 ) , 0 ) , ( 'RIGHTPADDING' , ( 0 , 0 ) , ( - 1 , - 1 ) , 0 ) , ( 'TOPPADDING' , ( 0 , 0 ) , ( - 1 , - 1 ) , 0 ) , ( 'BOTTOMPADDING' , ( 0 , 0 ) , ( - 1 , - 1 ) , 0 ) , ] for i , entry in enumerate ( _tempEntries ) : level , text , pageNum = entry [ : 3 ] leftColStyle = self . levelStyles [ level ] if i : # Not for first element tableStyle . append ( ( 'TOPPADDING' , ( 0 , i ) , ( - 1 , i ) , max ( lastMargin , leftColStyle . spaceBefore ) ) ) # print leftColStyle.leftIndent lastMargin = leftColStyle . spaceAfter #right col style is right aligned rightColStyle = ParagraphStyle ( name = 'leftColLevel%d' % level , parent = leftColStyle , leftIndent = 0 , alignment = TA_RIGHT ) leftPara = Paragraph ( text , leftColStyle ) rightPara = Paragraph ( str ( pageNum ) , rightColStyle ) tableData . append ( [ leftPara , rightPara ] ) self . _table = Table ( tableData , colWidths = widths , style = TableStyle ( tableStyle ) ) self . width , self . height = self . _table . wrapOn ( self . canv , availWidth , availHeight ) return self . width , self . height | All table properties should be known by now . | 517 | 9 |
240,246 | def _spawn_child ( self , command , args = None , timeout = shutit_global . shutit_global_object . default_timeout , maxread = 2000 , searchwindowsize = None , env = None , ignore_sighup = False , echo = True , preexec_fn = None , encoding = None , codec_errors = 'strict' , dimensions = None , delaybeforesend = shutit_global . shutit_global_object . delaybeforesend ) : shutit = self . shutit args = args or [ ] pexpect_child = pexpect . spawn ( command , args = args , timeout = timeout , maxread = maxread , searchwindowsize = searchwindowsize , env = env , ignore_sighup = ignore_sighup , echo = echo , preexec_fn = preexec_fn , encoding = encoding , codec_errors = codec_errors , dimensions = dimensions ) # Set the winsize to the theoretical maximum to reduce risk of trouble from terminal line wraps. # Other things have been attempted, eg tput rmam/smam without success. pexpect_child . setwinsize ( shutit_global . shutit_global_object . pexpect_window_size [ 0 ] , shutit_global . shutit_global_object . pexpect_window_size [ 1 ] ) pexpect_child . delaybeforesend = delaybeforesend shutit . log ( 'sessions before: ' + str ( shutit . shutit_pexpect_sessions ) , level = logging . DEBUG ) shutit . shutit_pexpect_sessions . update ( { self . pexpect_session_id : self } ) shutit . log ( 'sessions after: ' + str ( shutit . shutit_pexpect_sessions ) , level = logging . DEBUG ) return pexpect_child | spawn a child and manage the delaybefore send setting to 0 | 409 | 12 |
240,247 | def sendline ( self , sendspec ) : assert not sendspec . started , shutit_util . print_debug ( ) shutit = self . shutit shutit . log ( 'Sending in pexpect session (' + str ( id ( self ) ) + '): ' + str ( sendspec . send ) , level = logging . DEBUG ) if sendspec . expect : shutit . log ( 'Expecting: ' + str ( sendspec . expect ) , level = logging . DEBUG ) else : shutit . log ( 'Not expecting anything' , level = logging . DEBUG ) try : # Check there are no background commands running that have block_other_commands set iff # this sendspec says if self . _check_blocked ( sendspec ) and sendspec . ignore_background != True : shutit . log ( 'sendline: blocked' , level = logging . DEBUG ) return False # If this is marked as in the background, create a background object and run in the background. if sendspec . run_in_background : shutit . log ( 'sendline: run_in_background' , level = logging . DEBUG ) # If this is marked as in the background, create a background object and run in the background after newlines sorted. shutit_background_command_object = self . login_stack . get_current_login_item ( ) . append_background_send ( sendspec ) # Makes no sense to check exit for a background command. sendspec . check_exit = False if sendspec . nonewline != True : sendspec . send += '\n' # sendspec has newline added now, so no need to keep marker sendspec . nonewline = True if sendspec . run_in_background : shutit_background_command_object . run_background_command ( ) return True #shutit.log('sendline: actually sending: ' + sendspec.send, level=logging.DEBUG) self . pexpect_child . send ( sendspec . send ) return False except OSError : self . shutit . fail ( 'Caught failure to send, assuming user has exited from pause point.' ) | Sends line handling background and newline directives . | 465 | 10 |
240,248 | def wait ( self , cadence = 2 , sendspec = None ) : shutit = self . shutit shutit . log ( 'In wait.' , level = logging . DEBUG ) if sendspec : cadence = sendspec . wait_cadence shutit . log ( 'Login stack is:\n' + str ( self . login_stack ) , level = logging . DEBUG ) while True : # go through each background child checking whether they've finished res , res_str , background_object = self . login_stack . get_current_login_item ( ) . check_background_commands_complete ( ) shutit . log ( 'Checking: ' + str ( background_object ) + '\nres: ' + str ( res ) + '\nres_str' + str ( res_str ) , level = logging . DEBUG ) if res : # When all have completed, break return the background command objects. break elif res_str in ( 'S' , 'N' ) : # Do nothing, this is an started or not-running task. pass elif res_str == 'F' : assert background_object is not None , shutit_util . print_debug ( ) assert isinstance ( background_object , ShutItBackgroundCommand ) , shutit_util . print_debug ( ) shutit . log ( 'Failure in: ' + str ( self . login_stack ) , level = logging . DEBUG ) self . pause_point ( 'Background task: ' + background_object . sendspec . original_send + ' :failed.' ) return False else : self . shutit . fail ( 'Un-handled exit code: ' + res_str ) # pragma: no cover time . sleep ( cadence ) shutit . log ( 'Wait complete.' , level = logging . DEBUG ) return True | Does not return until all background commands are completed . | 392 | 10 |
240,249 | def expect ( self , expect , searchwindowsize = None , maxread = None , timeout = None , iteration_n = 1 ) : if isinstance ( expect , str ) : expect = [ expect ] if searchwindowsize != None : old_searchwindowsize = self . pexpect_child . searchwindowsize self . pexpect_child . searchwindowsize = searchwindowsize if maxread != None : old_maxread = self . pexpect_child . maxread self . pexpect_child . maxread = maxread res = self . pexpect_child . expect ( expect + [ pexpect . TIMEOUT ] + [ pexpect . EOF ] , timeout = timeout ) if searchwindowsize != None : self . pexpect_child . searchwindowsize = old_searchwindowsize if maxread != None : self . pexpect_child . maxread = old_maxread # Add to session lines only if pane manager exists. if shutit_global . shutit_global_object . pane_manager and iteration_n == 1 : time_seen = time . time ( ) lines_to_add = [ ] if isinstance ( self . pexpect_child . before , ( str , unicode ) ) : for line_str in self . pexpect_child . before . split ( '\n' ) : lines_to_add . append ( line_str ) if isinstance ( self . pexpect_child . after , ( str , unicode ) ) : for line_str in self . pexpect_child . after . split ( '\n' ) : lines_to_add . append ( line_str ) # If first or last line is empty, remove it. #if len(lines_to_add) > 0 and lines_to_add[1] == '': # lines_to_add = lines_to_add[1:] #if len(lines_to_add) > 0 and lines_to_add[-1] == '': # lines_to_add = lines_to_add[:-1] for line in lines_to_add : self . session_output_lines . append ( SessionPaneLine ( line_str = line , time_seen = time_seen , line_type = 'output' ) ) return res | Handle child expects with EOF and TIMEOUT handled | 503 | 10 |
240,250 | def replace_container ( self , new_target_image_name , go_home = None ) : shutit = self . shutit shutit . log ( 'Replacing container with ' + new_target_image_name + ', please wait...' , level = logging . DEBUG ) shutit . log ( shutit . print_session_state ( ) , level = logging . DEBUG ) # Destroy existing container. conn_module = None for mod in shutit . conn_modules : if mod . module_id == shutit . build [ 'conn_module' ] : conn_module = mod break if conn_module is None : shutit . fail ( '''Couldn't find conn_module ''' + shutit . build [ 'conn_module' ] ) # pragma: no cover container_id = shutit . target [ 'container_id' ] conn_module . destroy_container ( shutit , 'host_child' , 'target_child' , container_id ) # Start up a new container. shutit . target [ 'docker_image' ] = new_target_image_name target_child = conn_module . start_container ( shutit , self . pexpect_session_id ) conn_module . setup_target_child ( shutit , target_child ) shutit . log ( 'Container replaced' , level = logging . DEBUG ) shutit . log ( shutit . print_session_state ( ) , level = logging . DEBUG ) # New session - log in. This makes the assumption that we are nested # the same level in in terms of shells (root shell + 1 new login shell). target_child = shutit . get_shutit_pexpect_session_from_id ( 'target_child' ) if go_home != None : target_child . login ( ShutItSendSpec ( self , send = shutit_global . shutit_global_object . bash_startup_command , check_exit = False , echo = False , go_home = go_home ) ) else : target_child . login ( ShutItSendSpec ( self , send = shutit_global . shutit_global_object . bash_startup_command , check_exit = False , echo = False ) ) return True | Replaces a container . Assumes we are in Docker context . | 487 | 13 |
240,251 | def whoami ( self , note = None , loglevel = logging . DEBUG ) : shutit = self . shutit shutit . handle_note ( note ) res = self . send_and_get_output ( ' command whoami' , echo = False , loglevel = loglevel ) . strip ( ) if res == '' : res = self . send_and_get_output ( ' command id -u -n' , echo = False , loglevel = loglevel ) . strip ( ) shutit . handle_note_after ( note = note ) return res | Returns the current user by executing whoami . | 126 | 9 |
240,252 | def check_last_exit_values ( self , send , check_exit = True , expect = None , exit_values = None , retry = 0 , retbool = False ) : shutit = self . shutit expect = expect or self . default_expect if not self . check_exit or not check_exit : shutit . log ( 'check_exit configured off, returning' , level = logging . DEBUG ) return True if exit_values is None : exit_values = [ '0' ] if isinstance ( exit_values , int ) : exit_values = [ str ( exit_values ) ] # Don't use send here (will mess up last_output)! # Space before "echo" here is sic - we don't need this to show up in bash history send_exit_code = ' echo EXIT_CODE:$?' shutit . log ( 'Sending with sendline: ' + str ( send_exit_code ) , level = logging . DEBUG ) assert not self . sendline ( ShutItSendSpec ( self , send = send_exit_code , ignore_background = True ) ) , shutit_util . print_debug ( ) shutit . log ( 'Expecting: ' + str ( expect ) , level = logging . DEBUG ) self . expect ( expect , timeout = 10 ) shutit . log ( 'before: ' + str ( self . pexpect_child . before ) , level = logging . DEBUG ) res = shutit . match_string ( str ( self . pexpect_child . before ) , '^EXIT_CODE:([0-9][0-9]?[0-9]?)$' ) if res not in exit_values or res is None : # pragma: no cover res_str = res or str ( res ) shutit . log ( 'shutit_pexpect_child.after: ' + str ( self . pexpect_child . after ) , level = logging . DEBUG ) shutit . log ( 'Exit value from command: ' + str ( send ) + ' was:' + res_str , level = logging . DEBUG ) msg = ( '\nWARNING: command:\n' + send + '\nreturned unaccepted exit code: ' + res_str + '\nIf this is expected, pass in check_exit=False or an exit_values array into the send function call.' ) shutit . build [ 'report' ] += msg if retbool : return False elif retry == 1 and shutit_global . shutit_global_object . interactive >= 1 : # This is a failure, so we pass in level=0 shutit . pause_point ( msg + '\n\nInteractive, so not retrying.\nPause point on exit_code != 0 (' + res_str + '). CTRL-C to quit' , shutit_pexpect_child = self . pexpect_child , level = 0 ) elif retry == 1 : shutit . fail ( 'Exit value from command\n' + send + '\nwas:\n' + res_str , throw_exception = False ) # pragma: no cover else : return False return True | Internal function to check the exit value of the shell . Do not use . | 694 | 15 |
240,253 | def get_file_perms ( self , filename , note = None , loglevel = logging . DEBUG ) : shutit = self . shutit shutit . handle_note ( note ) cmd = ' command stat -c %a ' + filename self . send ( ShutItSendSpec ( self , send = ' ' + cmd , check_exit = False , echo = False , loglevel = loglevel , ignore_background = True ) ) res = shutit . match_string ( self . pexpect_child . before , '([0-9][0-9][0-9])' ) shutit . handle_note_after ( note = note ) return res | Returns the permissions of the file on the target as an octal string triplet . | 146 | 17 |
240,254 | def is_user_id_available ( self , user_id , note = None , loglevel = logging . DEBUG ) : shutit = self . shutit shutit . handle_note ( note ) # v the space is intentional, to avoid polluting bash history. self . send ( ShutItSendSpec ( self , send = ' command cut -d: -f3 /etc/paswd | grep -w ^' + user_id + '$ | wc -l' , expect = self . default_expect , echo = False , loglevel = loglevel , ignore_background = True ) ) shutit . handle_note_after ( note = note ) if shutit . match_string ( self . pexpect_child . before , '^([0-9]+)$' ) == '1' : return False return True | Determine whether the specified user_id available . | 184 | 11 |
240,255 | def lsb_release ( self , loglevel = logging . DEBUG ) : # v the space is intentional, to avoid polluting bash history. shutit = self . shutit d = { } self . send ( ShutItSendSpec ( self , send = ' command lsb_release -a' , check_exit = False , echo = False , loglevel = loglevel , ignore_background = True ) ) res = shutit . match_string ( self . pexpect_child . before , r'^Distributor[\s]*ID:[\s]*(.*)$' ) if isinstance ( res , str ) : dist_string = res d [ 'distro' ] = dist_string . lower ( ) . strip ( ) try : d [ 'install_type' ] = ( package_map . INSTALL_TYPE_MAP [ dist_string . lower ( ) ] ) except KeyError : raise Exception ( "Distribution '%s' is not supported." % dist_string ) else : return d res = shutit . match_string ( self . pexpect_child . before , r'^Release:[\s*](.*)$' ) if isinstance ( res , str ) : version_string = res d [ 'distro_version' ] = version_string return d | Get distro information from lsb_release . | 286 | 10 |
240,256 | def user_exists ( self , user , note = None , loglevel = logging . DEBUG ) : shutit = self . shutit shutit . handle_note ( note ) exists = False if user == '' : return exists # v the space is intentional, to avoid polluting bash history. # The quotes before XIST are deliberate, to prevent the command from matching the expect. ret = self . send ( ShutItSendSpec ( self , send = ' command id %s && echo E""XIST || echo N""XIST' % user , expect = [ 'NXIST' , 'EXIST' ] , echo = False , loglevel = loglevel , ignore_background = True ) ) if ret : exists = True # sync with the prompt self . expect ( self . default_expect ) shutit . handle_note_after ( note = note ) return exists | Returns true if the specified username exists . | 188 | 8 |
240,257 | def quick_send ( self , send , echo = None , loglevel = logging . INFO ) : shutit = self . shutit shutit . log ( 'Quick send: ' + send , level = loglevel ) res = self . sendline ( ShutItSendSpec ( self , send = send , check_exit = False , echo = echo , fail_on_empty_before = False , record_command = False , ignore_background = True ) ) if not res : self . expect ( self . default_expect ) | Quick and dirty send that ignores background tasks . Intended for internal use . | 114 | 15 |
240,258 | def _create_command_file ( self , expect , send ) : shutit = self . shutit random_id = shutit_util . random_id ( ) fname = shutit_global . shutit_global_object . shutit_state_dir + '/tmp_' + random_id working_str = send # truncate -s must be used as --size is not supported everywhere (eg busybox) assert not self . sendline ( ShutItSendSpec ( self , send = ' truncate -s 0 ' + fname , ignore_background = True ) ) , shutit_util . print_debug ( ) self . expect ( expect ) size = shutit_global . shutit_global_object . line_limit while working_str : curr_str = working_str [ : size ] working_str = working_str [ size : ] assert not self . sendline ( ShutItSendSpec ( self , send = ' ' + shutit . get_command ( 'head' ) + ''' -c -1 >> ''' + fname + """ << 'END_""" + random_id + """'\n""" + curr_str + """\nEND_""" + random_id , ignore_background = True ) ) , shutit_util . print_debug ( ) self . expect ( expect ) assert not self . sendline ( ShutItSendSpec ( self , send = ' chmod +x ' + fname , ignore_background = True ) ) , shutit_util . print_debug ( ) self . expect ( expect ) return fname | Internal function . Do not use . | 341 | 7 |
240,259 | def check_dependee_order ( depender , dependee , dependee_id ) : # If it depends on a module id, then the module id should be higher up # in the run order. shutit_global . shutit_global_object . yield_to_draw ( ) if dependee . run_order > depender . run_order : return 'depender module id:\n\n' + depender . module_id + '\n\n(run order: ' + str ( depender . run_order ) + ') ' + 'depends on dependee module_id:\n\n' + dependee_id + '\n\n(run order: ' + str ( dependee . run_order ) + ') ' + 'but the latter is configured to run after the former' return '' | Checks whether run orders are in the appropriate order . | 180 | 11 |
240,260 | def make_dep_graph ( depender ) : shutit_global . shutit_global_object . yield_to_draw ( ) digraph = '' for dependee_id in depender . depends_on : digraph = ( digraph + '"' + depender . module_id + '"->"' + dependee_id + '";\n' ) return digraph | Returns a digraph string fragment based on the passed - in module | 83 | 13 |
240,261 | def get_config_set ( self , section , option ) : values = set ( ) for cp , filename , fp in self . layers : filename = filename # pylint fp = fp # pylint if cp . has_option ( section , option ) : values . add ( cp . get ( section , option ) ) return values | Returns a set with each value per config file in it . | 74 | 12 |
240,262 | def reload ( self ) : oldlayers = self . layers self . layers = [ ] for cp , filename , fp in oldlayers : cp = cp # pylint if fp is None : self . read ( filename ) else : self . readfp ( fp , filename ) | Re - reads all layers again . In theory this should overwrite all the old values with any newer ones . It assumes we never delete a config item before reload . | 62 | 32 |
240,263 | def get_shutit_pexpect_session_environment ( self , environment_id ) : if not isinstance ( environment_id , str ) : self . fail ( 'Wrong argument type in get_shutit_pexpect_session_environment' ) # pragma: no cover for env in shutit_global . shutit_global_object . shutit_pexpect_session_environments : if env . environment_id == environment_id : return env return None | Returns the first shutit_pexpect_session object related to the given environment - id | 102 | 18 |
240,264 | def get_current_shutit_pexpect_session_environment ( self , note = None ) : self . handle_note ( note ) current_session = self . get_current_shutit_pexpect_session ( ) if current_session is not None : res = current_session . current_environment else : res = None self . handle_note_after ( note ) return res | Returns the current environment from the currently - set default pexpect child . | 83 | 15 |
240,265 | def get_current_shutit_pexpect_session ( self , note = None ) : self . handle_note ( note ) res = self . current_shutit_pexpect_session self . handle_note_after ( note ) return res | Returns the currently - set default pexpect child . | 53 | 11 |
240,266 | def get_shutit_pexpect_sessions ( self , note = None ) : self . handle_note ( note ) sessions = [ ] for key in self . shutit_pexpect_sessions : sessions . append ( shutit_object . shutit_pexpect_sessions [ key ] ) self . handle_note_after ( note ) return sessions | Returns all the shutit_pexpect_session keys for this object . | 78 | 15 |
240,267 | def set_default_shutit_pexpect_session ( self , shutit_pexpect_session ) : assert isinstance ( shutit_pexpect_session , ShutItPexpectSession ) , shutit_util . print_debug ( ) self . current_shutit_pexpect_session = shutit_pexpect_session return True | Sets the default pexpect child . | 75 | 9 |
240,268 | def fail ( self , msg , shutit_pexpect_child = None , throw_exception = False ) : shutit_global . shutit_global_object . yield_to_draw ( ) # Note: we must not default to a child here if shutit_pexpect_child is not None : shutit_pexpect_session = self . get_shutit_pexpect_session_from_child ( shutit_pexpect_child ) shutit_util . print_debug ( sys . exc_info ( ) ) shutit_pexpect_session . pause_point ( 'Pause point on fail: ' + msg , color = '31' ) if throw_exception : sys . stderr . write ( 'Error caught: ' + msg + '\n' ) sys . stderr . write ( '\n' ) shutit_util . print_debug ( sys . exc_info ( ) ) raise ShutItFailException ( msg ) else : # This is an "OK" failure, ie we don't need to throw an exception. # However, it's still a "failure", so return 1 shutit_global . shutit_global_object . handle_exit ( exit_code = 1 , msg = msg ) shutit_global . shutit_global_object . yield_to_draw ( ) | Handles a failure pausing if a pexpect child object is passed in . | 289 | 17 |
240,269 | def get_current_environment ( self , note = None ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . handle_note ( note ) res = self . get_current_shutit_pexpect_session_environment ( ) . environment_id self . handle_note_after ( note ) return res | Returns the current environment id from the current shutit_pexpect_session | 76 | 15 |
240,270 | def handle_note ( self , note , command = '' , training_input = '' ) : shutit_global . shutit_global_object . yield_to_draw ( ) if self . build [ 'walkthrough' ] and note != None and note != '' : assert isinstance ( note , str ) , shutit_util . print_debug ( ) wait = self . build [ 'walkthrough_wait' ] wrap = '\n' + 80 * '=' + '\n' message = wrap + note + wrap if command != '' : message += 'Command to be run is:\n\t' + command + wrap if wait >= 0 : self . pause_point ( message , color = 31 , wait = wait ) else : if training_input != '' and self . build [ 'training' ] : if len ( training_input . split ( '\n' ) ) == 1 : shutit_global . shutit_global_object . shutit_print ( shutit_util . colorise ( '31' , message ) ) while shutit_util . util_raw_input ( prompt = shutit_util . colorise ( '32' , 'Enter the command to continue (or "s" to skip typing it in): ' ) ) not in ( training_input , 's' ) : shutit_global . shutit_global_object . shutit_print ( 'Wrong! Try again!' ) shutit_global . shutit_global_object . shutit_print ( shutit_util . colorise ( '31' , 'OK!' ) ) else : self . pause_point ( message + '\nToo long to use for training, so skipping the option to type in!\nHit CTRL-] to continue' , color = 31 ) else : self . pause_point ( message + '\nHit CTRL-] to continue' , color = 31 ) return True | Handle notes and walkthrough option . | 410 | 7 |
240,271 | def expect_allow_interrupt ( self , shutit_pexpect_child , expect , timeout , iteration_s = 1 ) : shutit_global . shutit_global_object . yield_to_draw ( ) shutit_pexpect_session = self . get_shutit_pexpect_session_from_child ( shutit_pexpect_child ) accum_timeout = 0 if isinstance ( expect , str ) : expect = [ expect ] if timeout < 1 : timeout = 1 if iteration_s > timeout : iteration_s = timeout - 1 if iteration_s < 1 : iteration_s = 1 timed_out = True iteration_n = 0 while accum_timeout < timeout : iteration_n += 1 res = shutit_pexpect_session . expect ( expect , timeout = iteration_s , iteration_n = iteration_n ) if res == len ( expect ) : if self . build [ 'ctrlc_stop' ] : timed_out = False self . build [ 'ctrlc_stop' ] = False break accum_timeout += iteration_s else : return res if timed_out and not shutit_global . shutit_global_object . determine_interactive ( ) : self . log ( 'Command timed out, trying to get terminal back for you' , level = logging . DEBUG ) self . fail ( 'Timed out and could not recover' ) # pragma: no cover else : if shutit_global . shutit_global_object . determine_interactive ( ) : shutit_pexpect_child . send ( '\x03' ) res = shutit_pexpect_session . expect ( expect , timeout = 1 ) if res == len ( expect ) : shutit_pexpect_child . send ( '\x1a' ) res = shutit_pexpect_session . expect ( expect , timeout = 1 ) if res == len ( expect ) : self . fail ( 'CTRL-C sent by ShutIt following a timeout, and could not recover' ) # pragma: no cover shutit_pexpect_session . pause_point ( 'CTRL-C sent by ShutIt following a timeout; the command has been cancelled' ) return res else : if timed_out : self . fail ( 'Timed out and interactive, but could not recover' ) # pragma: no cover else : self . fail ( 'CTRL-C hit and could not recover' ) # pragma: no cover self . fail ( 'Should not get here (expect_allow_interrupt)' ) # pragma: no cover return True | This function allows you to interrupt the run at more or less any point by breaking up the timeout into interactive chunks . | 554 | 23 |
240,272 | def send_host_file ( self , path , hostfilepath , expect = None , shutit_pexpect_child = None , note = None , user = None , group = None , loglevel = logging . INFO ) : shutit_global . shutit_global_object . yield_to_draw ( ) shutit_pexpect_child = shutit_pexpect_child or self . get_current_shutit_pexpect_session ( ) . pexpect_child expect = expect or self . get_current_shutit_pexpect_session ( ) . default_expect shutit_pexpect_session = self . get_shutit_pexpect_session_from_child ( shutit_pexpect_child ) self . handle_note ( note , 'Sending file from host: ' + hostfilepath + ' to target path: ' + path ) self . log ( 'Sending file from host: ' + hostfilepath + ' to: ' + path , level = loglevel ) if user is None : user = shutit_pexpect_session . whoami ( ) if group is None : group = self . whoarewe ( ) # TODO: use gz for both if os . path . isfile ( hostfilepath ) : shutit_pexpect_session . send_file ( path , codecs . open ( hostfilepath , mode = 'rb' , encoding = 'iso-8859-1' ) . read ( ) , user = user , group = group , loglevel = loglevel , encoding = 'iso-8859-1' ) elif os . path . isdir ( hostfilepath ) : # Need a binary type encoding for gzip(?) self . send_host_dir ( path , hostfilepath , user = user , group = group , loglevel = loglevel ) else : self . fail ( 'send_host_file - file: ' + hostfilepath + ' does not exist as file or dir. cwd is: ' + os . getcwd ( ) , shutit_pexpect_child = shutit_pexpect_child , throw_exception = False ) # pragma: no cover self . handle_note_after ( note = note ) return True | Send file from host machine to given path | 491 | 8 |
240,273 | def delete_text ( self , text , fname , pattern = None , expect = None , shutit_pexpect_child = None , note = None , before = False , force = False , line_oriented = True , loglevel = logging . DEBUG ) : shutit_global . shutit_global_object . yield_to_draw ( ) return self . change_text ( text , fname , pattern , expect , shutit_pexpect_child , before , force , note = note , delete = True , line_oriented = line_oriented , loglevel = loglevel ) | Delete a chunk of text from a file . See insert_text . | 128 | 14 |
240,274 | def get_file ( self , target_path , host_path , note = None , loglevel = logging . DEBUG ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . handle_note ( note ) # Only handle for docker initially, return false in case we care if self . build [ 'delivery' ] != 'docker' : return False # on the host, run: #Usage: docker cp [OPTIONS] CONTAINER:PATH LOCALPATH|- # Need: host env, container id, path from and path to shutit_pexpect_child = self . get_shutit_pexpect_session_from_id ( 'host_child' ) . pexpect_child expect = self . expect_prompts [ 'ORIGIN_ENV' ] self . send ( 'docker cp ' + self . target [ 'container_id' ] + ':' + target_path + ' ' + host_path , shutit_pexpect_child = shutit_pexpect_child , expect = expect , check_exit = False , echo = False , loglevel = loglevel ) self . handle_note_after ( note = note ) return True | Copy a file from the target machine to the host machine | 267 | 11 |
240,275 | def prompt_cfg ( self , msg , sec , name , ispass = False ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfgstr = '[%s]/%s' % ( sec , name ) config_parser = self . config_parser usercfg = os . path . join ( self . host [ 'shutit_path' ] , 'config' ) self . log ( '\nPROMPTING FOR CONFIG: %s' % ( cfgstr , ) , transient = True , level = logging . INFO ) self . log ( '\n' + msg + '\n' , transient = True , level = logging . INFO ) if not shutit_global . shutit_global_object . determine_interactive ( ) : self . fail ( 'ShutIt is not in a terminal so cannot prompt for values.' , throw_exception = False ) # pragma: no cover if config_parser . has_option ( sec , name ) : whereset = config_parser . whereset ( sec , name ) if usercfg == whereset : self . fail ( cfgstr + ' has already been set in the user config, edit ' + usercfg + ' directly to change it' , throw_exception = False ) # pragma: no cover for subcp , filename , _ in reversed ( config_parser . layers ) : # Is the config file loaded after the user config file? if filename == whereset : self . fail ( cfgstr + ' is being set in ' + filename + ', unable to override on a user config level' , throw_exception = False ) # pragma: no cover elif filename == usercfg : break else : # The item is not currently set so we're fine to do so pass if ispass : val = getpass . getpass ( '>> ' ) else : val = shutit_util . util_raw_input ( prompt = '>> ' ) is_excluded = ( config_parser . has_option ( 'save_exclude' , sec ) and name in config_parser . get ( 'save_exclude' , sec ) . split ( ) ) # TODO: ideally we would remember the prompted config item for this invocation of shutit if not is_excluded : usercp = [ subcp for subcp , filename , _ in config_parser . layers if filename == usercfg ] [ 0 ] if shutit_util . util_raw_input ( prompt = shutit_util . colorise ( '32' , 'Do you want to save this to your user settings? y/n: ' ) , default = 'y' ) == 'y' : sec_toset , name_toset , val_toset = sec , name , val else : # Never save it if config_parser . has_option ( 'save_exclude' , sec ) : excluded = config_parser . get ( 'save_exclude' , sec ) . split ( ) else : excluded = [ ] excluded . append ( name ) excluded = ' ' . join ( excluded ) sec_toset , name_toset , val_toset = 'save_exclude' , sec , excluded if not usercp . has_section ( sec_toset ) : usercp . add_section ( sec_toset ) usercp . set ( sec_toset , name_toset , val_toset ) usercp . write ( open ( usercfg , 'w' ) ) config_parser . reload ( ) return val | Prompt for a config value optionally saving it to the user - level cfg . Only runs if we are in an interactive mode . | 781 | 27 |
240,276 | def step_through ( self , msg = '' , shutit_pexpect_child = None , level = 1 , print_input = True , value = True ) : shutit_global . shutit_global_object . yield_to_draw ( ) shutit_pexpect_child = shutit_pexpect_child or self . get_current_shutit_pexpect_session ( ) . pexpect_child shutit_pexpect_session = self . get_shutit_pexpect_session_from_child ( shutit_pexpect_child ) if ( not shutit_global . shutit_global_object . determine_interactive ( ) or not shutit_global . shutit_global_object . interactive or shutit_global . shutit_global_object . interactive < level ) : return True self . build [ 'step_through' ] = value shutit_pexpect_session . pause_point ( msg , print_input = print_input , level = level ) return True | Implements a step - through function using pause_point . | 220 | 13 |
240,277 | def interact ( self , msg = 'SHUTIT PAUSE POINT' , shutit_pexpect_child = None , print_input = True , level = 1 , resize = True , color = '32' , default_msg = None , wait = - 1 ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . pause_point ( msg = msg , shutit_pexpect_child = shutit_pexpect_child , print_input = print_input , level = level , resize = resize , color = color , default_msg = default_msg , interact = True , wait = wait ) | Same as pause_point but sets up the terminal ready for unmediated interaction . | 140 | 16 |
240,278 | def pause_point ( self , msg = 'SHUTIT PAUSE POINT' , shutit_pexpect_child = None , print_input = True , level = 1 , resize = True , color = '32' , default_msg = None , interact = False , wait = - 1 ) : shutit_global . shutit_global_object . yield_to_draw ( ) if ( not shutit_global . shutit_global_object . determine_interactive ( ) or shutit_global . shutit_global_object . interactive < 1 or shutit_global . shutit_global_object . interactive < level ) : return True shutit_pexpect_child = shutit_pexpect_child or self . get_current_shutit_pexpect_session ( ) . pexpect_child # Don't log log traces while in interactive log_trace_when_idle_original_value = shutit_global . shutit_global_object . log_trace_when_idle shutit_global . shutit_global_object . log_trace_when_idle = False if shutit_pexpect_child : if shutit_global . shutit_global_object . pane_manager is not None : shutit_global . shutit_global_object . pane_manager . draw_screen ( draw_type = 'clearscreen' ) shutit_global . shutit_global_object . pane_manager . do_render = False shutit_pexpect_session = self . get_shutit_pexpect_session_from_child ( shutit_pexpect_child ) # TODO: context added to pause point message shutit_pexpect_session . pause_point ( msg = msg , print_input = print_input , resize = resize , color = color , default_msg = default_msg , wait = wait , interact = interact ) else : self . log ( msg , level = logging . DEBUG ) self . log ( 'Nothing to interact with, so quitting to presumably the original shell' , level = logging . DEBUG ) shutit_global . shutit_global_object . handle_exit ( exit_code = 1 ) if shutit_pexpect_child : if shutit_global . shutit_global_object . pane_manager is not None : shutit_global . shutit_global_object . pane_manager . do_render = True shutit_global . shutit_global_object . pane_manager . draw_screen ( draw_type = 'clearscreen' ) self . build [ 'ctrlc_stop' ] = False # Revert value of log_trace_when_idle shutit_global . shutit_global_object . log_trace_when_idle = log_trace_when_idle_original_value return True | Inserts a pause in the build session which allows the user to try things out before continuing . Ignored if we are not in an interactive mode or the interactive level is less than the passed - in one . Designed to help debug the build or drop to on failure so the situation can be debugged . | 614 | 61 |
240,279 | def login ( self , command = 'su -' , user = None , password = None , prompt_prefix = None , expect = None , timeout = shutit_global . shutit_global_object . default_timeout , escape = False , echo = None , note = None , go_home = True , fail_on_fail = True , is_ssh = True , check_sudo = True , loglevel = logging . DEBUG ) : shutit_global . shutit_global_object . yield_to_draw ( ) shutit_pexpect_session = self . get_current_shutit_pexpect_session ( ) return shutit_pexpect_session . login ( ShutItSendSpec ( shutit_pexpect_session , user = user , send = command , password = password , prompt_prefix = prompt_prefix , expect = expect , timeout = timeout , escape = escape , echo = echo , note = note , go_home = go_home , fail_on_fail = fail_on_fail , is_ssh = is_ssh , check_sudo = check_sudo , loglevel = loglevel ) ) | Logs user in on default child . | 246 | 8 |
240,280 | def logout_all ( self , command = 'exit' , note = None , echo = None , timeout = shutit_global . shutit_global_object . default_timeout , nonewline = False , loglevel = logging . DEBUG ) : shutit_global . shutit_global_object . yield_to_draw ( ) for key in self . shutit_pexpect_sessions : shutit_pexpect_session = self . shutit_pexpect_sessions [ key ] shutit_pexpect_session . logout_all ( ShutItSendSpec ( shutit_pexpect_session , send = command , note = note , timeout = timeout , nonewline = nonewline , loglevel = loglevel , echo = echo ) ) return True | Logs the user out of all pexpect sessions within this ShutIt object . | 170 | 17 |
240,281 | def push_repository ( self , repository , docker_executable = 'docker' , shutit_pexpect_child = None , expect = None , note = None , loglevel = logging . INFO ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . handle_note ( note ) shutit_pexpect_child = shutit_pexpect_child or self . get_shutit_pexpect_session_from_id ( 'host_child' ) . pexpect_child expect = expect or self . expect_prompts [ 'ORIGIN_ENV' ] send = docker_executable + ' push ' + self . repository [ 'user' ] + '/' + repository timeout = 99999 self . log ( 'Running: ' + send , level = logging . INFO ) self . multisend ( docker_executable + ' login' , { 'Username' : self . repository [ 'user' ] , 'Password' : self . repository [ 'password' ] , 'Email' : self . repository [ 'email' ] } , shutit_pexpect_child = shutit_pexpect_child , expect = expect ) self . send ( send , shutit_pexpect_child = shutit_pexpect_child , expect = expect , timeout = timeout , check_exit = False , fail_on_empty_before = False , loglevel = loglevel ) self . handle_note_after ( note ) return True | Pushes the repository . | 327 | 5 |
240,282 | def get_emailer ( self , cfg_section ) : shutit_global . shutit_global_object . yield_to_draw ( ) import emailer return emailer . Emailer ( cfg_section , self ) | Sends an email using the mailer | 50 | 8 |
240,283 | def get_shutit_pexpect_session_id ( self , shutit_pexpect_child ) : shutit_global . shutit_global_object . yield_to_draw ( ) if not isinstance ( shutit_pexpect_child , pexpect . pty_spawn . spawn ) : self . fail ( 'Wrong type in get_shutit_pexpect_session_id' , throw_exception = True ) # pragma: no cover for key in self . shutit_pexpect_sessions : if self . shutit_pexpect_sessions [ key ] . pexpect_child == shutit_pexpect_child : return key return self . fail ( 'Should not get here in get_shutit_pexpect_session_id' , throw_exception = True ) | Given a pexpect child object return the shutit_pexpect_session_id object . | 179 | 20 |
240,284 | def get_shutit_pexpect_session_from_id ( self , shutit_pexpect_id ) : shutit_global . shutit_global_object . yield_to_draw ( ) for key in self . shutit_pexpect_sessions : if self . shutit_pexpect_sessions [ key ] . pexpect_session_id == shutit_pexpect_id : return self . shutit_pexpect_sessions [ key ] return self . fail ( 'Should not get here in get_shutit_pexpect_session_from_id' , throw_exception = True ) | Get the pexpect session from the given identifier . | 137 | 11 |
240,285 | def get_commands ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) s = '' for c in self . build [ 'shutit_command_history' ] : if isinstance ( c , str ) : #Ignore commands with leading spaces if c and c [ 0 ] != ' ' : s += c + '\n' return s | Gets command that have been run and have not been redacted . | 85 | 13 |
240,286 | def build_report ( self , msg = '' ) : shutit_global . shutit_global_object . yield_to_draw ( ) s = '\n' s += '################################################################################\n' s += '# COMMAND HISTORY BEGIN ' + shutit_global . shutit_global_object . build_id + '\n' s += self . get_commands ( ) s += '# COMMAND HISTORY END ' + shutit_global . shutit_global_object . build_id + '\n' s += '################################################################################\n' s += '################################################################################\n' s += '# BUILD REPORT FOR BUILD BEGIN ' + shutit_global . shutit_global_object . build_id + '\n' s += '# ' + msg + '\n' if self . build [ 'report' ] != '' : s += self . build [ 'report' ] + '\n' else : s += '# Nothing to report\n' if 'container_id' in self . target : s += '# CONTAINER_ID: ' + self . target [ 'container_id' ] + '\n' s += '# BUILD REPORT FOR BUILD END ' + shutit_global . shutit_global_object . build_id + '\n' s += '###############################################################################\n' s += '# INVOKING COMMAND WAS: ' + sys . executable for arg in sys . argv : s += ' ' + arg s += '\n' s += '###############################################################################\n' return s | Resposible for constructing a report to be output as part of the build . Returns report as a string . | 353 | 22 |
240,287 | def match_string ( self , string_to_match , regexp ) : shutit_global . shutit_global_object . yield_to_draw ( ) if not isinstance ( string_to_match , str ) : return None lines = string_to_match . split ( '\r\n' ) # sometimes they're separated by just a carriage return... new_lines = [ ] for line in lines : new_lines = new_lines + line . split ( '\r' ) # and sometimes they're separated by just a newline... for line in lines : new_lines = new_lines + line . split ( '\n' ) lines = new_lines if not shutit_util . check_regexp ( regexp ) : self . fail ( 'Illegal regexp found in match_string call: ' + regexp ) # pragma: no cover for line in lines : match = re . match ( regexp , line ) if match is not None : if match . groups ( ) : return match . group ( 1 ) return True return None | Get regular expression from the first of the lines passed in in string that matched . Handles first group of regexp as a return value . | 231 | 28 |
240,288 | def is_to_be_built_or_is_installed ( self , shutit_module_obj ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg if cfg [ shutit_module_obj . module_id ] [ 'shutit.core.module.build' ] : return True return self . is_installed ( shutit_module_obj ) | Returns true if this module is configured to be built or if it is already installed . | 95 | 17 |
240,289 | def is_installed ( self , shutit_module_obj ) : shutit_global . shutit_global_object . yield_to_draw ( ) # Cache first if shutit_module_obj . module_id in self . get_current_shutit_pexpect_session_environment ( ) . modules_installed : return True if shutit_module_obj . module_id in self . get_current_shutit_pexpect_session_environment ( ) . modules_not_installed : return False # Is it installed? if shutit_module_obj . is_installed ( self ) : self . get_current_shutit_pexpect_session_environment ( ) . modules_installed . append ( shutit_module_obj . module_id ) return True # If not installed, and not in cache, add it. else : if shutit_module_obj . module_id not in self . get_current_shutit_pexpect_session_environment ( ) . modules_not_installed : self . get_current_shutit_pexpect_session_environment ( ) . modules_not_installed . append ( shutit_module_obj . module_id ) return False return False | Returns true if this module is installed . Uses cache where possible . | 261 | 13 |
240,290 | def allowed_image ( self , module_id ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . log ( "In allowed_image: " + module_id , level = logging . DEBUG ) cfg = self . cfg if self . build [ 'ignoreimage' ] : self . log ( "ignoreimage == true, returning true" + module_id , level = logging . DEBUG ) return True self . log ( str ( cfg [ module_id ] [ 'shutit.core.module.allowed_images' ] ) , level = logging . DEBUG ) if cfg [ module_id ] [ 'shutit.core.module.allowed_images' ] : # Try allowed images as regexps for regexp in cfg [ module_id ] [ 'shutit.core.module.allowed_images' ] : if not shutit_util . check_regexp ( regexp ) : self . fail ( 'Illegal regexp found in allowed_images: ' + regexp ) # pragma: no cover if re . match ( '^' + regexp + '$' , self . target [ 'docker_image' ] ) : return True return False | Given a module id determine whether the image is allowed to be built . | 263 | 14 |
240,291 | def print_modules ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg module_string = '' module_string += 'Modules: \n' module_string += ' Run order Build Remove Module ID\n' for module_id in self . module_ids ( ) : module_string += ' ' + str ( self . shutit_map [ module_id ] . run_order ) + ' ' + str ( cfg [ module_id ] [ 'shutit.core.module.build' ] ) + ' ' + str ( cfg [ module_id ] [ 'shutit.core.module.remove' ] ) + ' ' + module_id + '\n' return module_string | Returns a string table representing the modules in the ShutIt module map . | 170 | 14 |
240,292 | def load_shutit_modules ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) if self . loglevel <= logging . DEBUG : self . log ( 'ShutIt module paths now: ' , level = logging . DEBUG ) self . log ( self . host [ 'shutit_module_path' ] , level = logging . DEBUG ) for shutit_module_path in self . host [ 'shutit_module_path' ] : self . load_all_from_path ( shutit_module_path ) | Responsible for loading the shutit modules based on the configured module paths . | 123 | 16 |
240,293 | def get_command ( self , command ) : shutit_global . shutit_global_object . yield_to_draw ( ) if command in ( 'md5sum' , 'sed' , 'head' ) : if self . get_current_shutit_pexpect_session_environment ( ) . distro == 'osx' : return 'g' + command return command | Helper function for osx - return gnu utils rather than default for eg head and md5sum where possible and needed . | 83 | 26 |
240,294 | def get_send_command ( self , send ) : shutit_global . shutit_global_object . yield_to_draw ( ) if send is None : return send cmd_arr = send . split ( ) if cmd_arr and cmd_arr [ 0 ] in ( 'md5sum' , 'sed' , 'head' ) : newcmd = self . get_command ( cmd_arr [ 0 ] ) send = send . replace ( cmd_arr [ 0 ] , newcmd ) return send | Internal helper function to get command that s really sent | 109 | 10 |
240,295 | def load_configs ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) # Get root default config. # TODO: change default_cnf so it places whatever the values are at this stage of the build. configs = [ ( 'defaults' , StringIO ( default_cnf ) ) , os . path . expanduser ( '~/.shutit/config' ) , os . path . join ( self . host [ 'shutit_path' ] , 'config' ) , 'configs/build.cnf' ] # Add the shutit global host- and user-specific config file. # Add the local build.cnf # Get passed-in config(s) for config_file_name in self . build [ 'extra_configs' ] : run_config_file = os . path . expanduser ( config_file_name ) if not os . path . isfile ( run_config_file ) : shutit_global . shutit_global_object . shutit_print ( 'Did not recognise ' + run_config_file + ' as a file - do you need to touch ' + run_config_file + '?' ) shutit_global . shutit_global_object . handle_exit ( exit_code = 0 ) configs . append ( run_config_file ) # Image to use to start off. The script should be idempotent, so running it # on an already built image should be ok, and is advised to reduce diff space required. if self . action [ 'list_configs' ] or self . loglevel <= logging . DEBUG : msg = '' for c in configs : if isinstance ( c , tuple ) : c = c [ 0 ] msg = msg + ' \n' + c self . log ( ' ' + c , level = logging . DEBUG ) # Interpret any config overrides, write to a file and add them to the # list of configs to be interpreted if self . build [ 'config_overrides' ] : # We don't need layers, this is a temporary configparser override_cp = ConfigParser . RawConfigParser ( ) for o_sec , o_key , o_val in self . build [ 'config_overrides' ] : if not override_cp . has_section ( o_sec ) : override_cp . add_section ( o_sec ) override_cp . set ( o_sec , o_key , o_val ) override_fd = StringIO ( ) override_cp . write ( override_fd ) override_fd . seek ( 0 ) configs . append ( ( 'overrides' , override_fd ) ) self . config_parser = self . get_configs ( configs ) self . get_base_config ( ) | Responsible for loading config files into ShutIt . Recurses down from configured shutit module paths . | 609 | 21 |
240,296 | def config_collection ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) self . log ( 'In config_collection' , level = logging . DEBUG ) cfg = self . cfg for module_id in self . module_ids ( ) : # Default to None so we can interpret as ifneeded self . get_config ( module_id , 'shutit.core.module.build' , None , boolean = True , forcenone = True ) self . get_config ( module_id , 'shutit.core.module.remove' , False , boolean = True ) self . get_config ( module_id , 'shutit.core.module.tag' , False , boolean = True ) # Default to allow any image self . get_config ( module_id , 'shutit.core.module.allowed_images' , [ ".*" ] ) module = self . shutit_map [ module_id ] cfg_file = os . path . dirname ( get_module_file ( self , module ) ) + '/configs/build.cnf' if os . path . isfile ( cfg_file ) : # use self.get_config, forcing the passed-in default config_parser = ConfigParser . ConfigParser ( ) config_parser . read ( cfg_file ) for section in config_parser . sections ( ) : if section == module_id : for option in config_parser . options ( section ) : if option == 'shutit.core.module.allowed_images' : override = False for mod , opt , val in self . build [ 'config_overrides' ] : val = val # pylint # skip overrides if mod == module_id and opt == option : override = True if override : continue value = config_parser . get ( section , option ) if option == 'shutit.core.module.allowed_images' : value = json . loads ( value ) self . get_config ( module_id , option , value , forceask = True ) # ifneeded will (by default) only take effect if 'build' is not # specified. It can, however, be forced to a value, but this # should be unusual. if cfg [ module_id ] [ 'shutit.core.module.build' ] is None : self . get_config ( module_id , 'shutit.core.module.build_ifneeded' , True , boolean = True ) cfg [ module_id ] [ 'shutit.core.module.build' ] = False else : self . get_config ( module_id , 'shutit.core.module.build_ifneeded' , False , boolean = True ) | Collect core config from config files for all seen modules . | 590 | 11 |
240,297 | def print_config ( self , cfg , hide_password = True , history = False , module_id = None ) : shutit_global . shutit_global_object . yield_to_draw ( ) cp = self . config_parser s = '' keys1 = list ( cfg . keys ( ) ) if keys1 : keys1 . sort ( ) for k in keys1 : if module_id is not None and k != module_id : continue if isinstance ( k , str ) and isinstance ( cfg [ k ] , dict ) : s += '\n[' + k + ']\n' keys2 = list ( cfg [ k ] . keys ( ) ) if keys2 : keys2 . sort ( ) for k1 in keys2 : line = '' line += k1 + ':' # If we want to hide passwords, we do so using a sha512 # done an aritrary number of times (27). if hide_password and ( k1 == 'password' or k1 == 'passphrase' ) : p = hashlib . sha512 ( cfg [ k ] [ k1 ] ) . hexdigest ( ) i = 27 while i > 0 : i -= 1 p = hashlib . sha512 ( s ) . hexdigest ( ) line += p else : if type ( cfg [ k ] [ k1 ] == bool ) : line += str ( cfg [ k ] [ k1 ] ) elif type ( cfg [ k ] [ k1 ] == str ) : line += cfg [ k ] [ k1 ] if history : try : line += ( 30 - len ( line ) ) * ' ' + ' # ' + cp . whereset ( k , k1 ) except Exception : # Assume this is because it was never set by a config parser. line += ( 30 - len ( line ) ) * ' ' + ' # ' + "defaults in code" s += line + '\n' return s | Returns a string representing the config of this ShutIt run . | 427 | 12 |
240,298 | def process_args ( self , args ) : shutit_global . shutit_global_object . yield_to_draw ( ) assert isinstance ( args , ShutItInit ) , shutit_util . print_debug ( ) if args . action == 'version' : shutit_global . shutit_global_object . shutit_print ( 'ShutIt version: ' + shutit . shutit_version ) shutit_global . shutit_global_object . handle_exit ( exit_code = 0 ) # What are we asking shutit to do? self . action [ 'list_configs' ] = args . action == 'list_configs' self . action [ 'list_modules' ] = args . action == 'list_modules' self . action [ 'list_deps' ] = args . action == 'list_deps' self . action [ 'skeleton' ] = args . action == 'skeleton' self . action [ 'build' ] = args . action == 'build' self . action [ 'run' ] = args . action == 'run' # Logging if not self . logging_setup_done : self . logfile = args . logfile self . loglevel = args . loglevel if self . loglevel is None or self . loglevel == '' : self . loglevel = 'INFO' self . setup_logging ( ) shutit_global . shutit_global_object . setup_panes ( action = args . action ) # This mode is a bit special - it's the only one with different arguments if self . action [ 'skeleton' ] : self . handle_skeleton ( args ) shutit_global . shutit_global_object . handle_exit ( ) elif self . action [ 'run' ] : self . handle_run ( args ) sys . exit ( 0 ) elif self . action [ 'build' ] or self . action [ 'list_configs' ] or self . action [ 'list_modules' ] : self . handle_build ( args ) else : self . fail ( 'Should not get here: action was: ' + str ( self . action ) ) self . nocolor = args . nocolor | Process the args we have . args is always a ShutItInit object . | 482 | 15 |
240,299 | def check_deps ( self ) : shutit_global . shutit_global_object . yield_to_draw ( ) cfg = self . cfg self . log ( 'PHASE: dependencies' , level = logging . DEBUG ) self . pause_point ( '\nNow checking for dependencies between modules' , print_input = False , level = 3 ) # Get modules we're going to build to_build = [ self . shutit_map [ module_id ] for module_id in self . shutit_map if module_id in cfg and cfg [ module_id ] [ 'shutit.core.module.build' ] ] # Add any deps we may need by extending to_build and altering cfg for module in to_build : self . resolve_dependencies ( to_build , module ) # Dep checking def err_checker ( errs , triples ) : """Collate error information. """ new_triples = [ ] for err , triple in zip ( errs , triples ) : if not err : new_triples . append ( triple ) continue found_errs . append ( err ) return new_triples found_errs = [ ] triples = [ ] for depender in to_build : for dependee_id in depender . depends_on : triples . append ( ( depender , self . shutit_map . get ( dependee_id ) , dependee_id ) ) triples = err_checker ( [ self . check_dependee_exists ( depender , dependee , dependee_id ) for depender , dependee , dependee_id in triples ] , triples ) triples = err_checker ( [ self . check_dependee_build ( depender , dependee , dependee_id ) for depender , dependee , dependee_id in triples ] , triples ) triples = err_checker ( [ check_dependee_order ( depender , dependee , dependee_id ) for depender , dependee , dependee_id in triples ] , triples ) if found_errs : return [ ( err , ) for err in found_errs ] self . log ( 'Modules configured to be built (in order) are: ' , level = logging . DEBUG ) for module_id in self . module_ids ( ) : module = self . shutit_map [ module_id ] if cfg [ module_id ] [ 'shutit.core.module.build' ] : self . log ( module_id + ' ' + str ( module . run_order ) , level = logging . DEBUG ) self . log ( '\n' , level = logging . DEBUG ) return [ ] | Dependency checking phase is performed in this method . | 593 | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.