idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
52,300
def Robbins ( L , G , rhol , rhog , mul , H = 1.0 , Fpd = 24.0 ) : r L = L * 737.33812 G = G * 737.33812 rhol = rhol * 0.062427961 rhog = rhog * 0.062427961 mul = mul * 1000.0 C3 = 7.4E-8 C4 = 2.7E-5 Fpd_root_term = ( .05 * Fpd ) ** 0.5 Lf = L * ( 62.4 / rhol ) * Fpd_root_term * mul ** 0.1 Gf = G * ( 0.075 / rhog ) ** 0.5 * Fpd_root_term Gf2 = Gf * Gf C4LF_10_GF2_C3 = C3 * Gf2 * 10.0 ** ( C4 * Lf ) C4LF_10_GF2_C3_2 = C4LF_10_GF2_C3 * C4LF_10_GF2_C3 dP = C4LF_10_GF2_C3 + 0.4 * ( 5e-5 * Lf ) ** 0.1 * ( C4LF_10_GF2_C3_2 * C4LF_10_GF2_C3_2 ) return dP * 817.22083 * H
r Calculates pressure drop across a packed column using the Robbins equation .
52,301
def dP_packed_bed ( dp , voidage , vs , rho , mu , L = 1 , Dt = None , sphericity = None , Method = None , AvailableMethods = False ) : r def list_methods ( ) : methods = [ ] if all ( ( dp , voidage , vs , rho , mu , L ) ) : for key , values in packed_beds_correlations . items ( ) : if Dt or not values [ 1 ] : methods . append ( key ) if 'Harrison, Brunner & Hecker' in methods : methods . remove ( 'Harrison, Brunner & Hecker' ) methods . insert ( 0 , 'Harrison, Brunner & Hecker' ) elif 'Erdim, Akgiray & Demir' in methods : methods . remove ( 'Erdim, Akgiray & Demir' ) methods . insert ( 0 , 'Erdim, Akgiray & Demir' ) return methods if AvailableMethods : return list_methods ( ) if not Method : Method = list_methods ( ) [ 0 ] if dp and sphericity : dp = dp * sphericity if Method in packed_beds_correlations : if packed_beds_correlations [ Method ] [ 1 ] : return packed_beds_correlations [ Method ] [ 0 ] ( dp = dp , voidage = voidage , vs = vs , rho = rho , mu = mu , L = L , Dt = Dt ) else : return packed_beds_correlations [ Method ] [ 0 ] ( dp = dp , voidage = voidage , vs = vs , rho = rho , mu = mu , L = L ) else : raise Exception ( 'Failure in in function' )
r This function handles choosing which pressure drop in a packed bed correlation is used . Automatically select which correlation to use if none is provided . Returns None if insufficient information is provided .
52,302
def Friedel ( m , x , rhol , rhog , mul , mug , sigma , D , roughness = 0 , L = 1 ) : r v_lo = m / rhol / ( pi / 4 * D ** 2 ) Re_lo = Reynolds ( V = v_lo , rho = rhol , mu = mul , D = D ) fd_lo = friction_factor ( Re = Re_lo , eD = roughness / D ) dP_lo = fd_lo * L / D * ( 0.5 * rhol * v_lo ** 2 ) v_go = m / rhog / ( pi / 4 * D ** 2 ) Re_go = Reynolds ( V = v_go , rho = rhog , mu = mug , D = D ) fd_go = friction_factor ( Re = Re_go , eD = roughness / D ) F = x ** 0.78 * ( 1 - x ) ** 0.224 H = ( rhol / rhog ) ** 0.91 * ( mug / mul ) ** 0.19 * ( 1 - mug / mul ) ** 0.7 E = ( 1 - x ) ** 2 + x ** 2 * ( rhol * fd_go / ( rhog * fd_lo ) ) voidage_h = homogeneous ( x , rhol , rhog ) rho_h = rhol * ( 1 - voidage_h ) + rhog * voidage_h Q_h = m / rho_h v_h = Q_h / ( pi / 4 * D ** 2 ) Fr = Froude ( V = v_h , L = D , squared = True ) We = Weber ( V = v_h , L = D , rho = rho_h , sigma = sigma ) phi_lo2 = E + 3.24 * F * H / ( Fr ** 0.0454 * We ** 0.035 ) return phi_lo2 * dP_lo
r Calculates two - phase pressure drop with the Friedel correlation .
52,303
def airmass ( func , angle , H_max = 86400.0 , R_planet = 6.371229E6 , RI = 1.000276 ) : r delta0 = RI - 1.0 rho0 = func ( 0.0 ) angle_term = cos ( radians ( angle ) ) def to_int ( Z ) : rho = func ( Z ) t1 = ( 1.0 + 2.0 * delta0 * ( 1.0 - rho / rho0 ) ) t2 = ( angle_term / ( 1.0 + Z / R_planet ) ) ** 2 t3 = ( 1.0 - t1 * t2 ) ** - 0.5 return rho * t3 from scipy . integrate import quad return float ( quad ( to_int , 0 , 86400.0 ) [ 0 ] )
r Calculates mass of air per square meter in the atmosphere using a provided atmospheric model . The lowest air mass is calculated straight up ; as the angle is lowered to nearer and nearer the horizon the air mass increases and can approach 40x or more the minimum airmass .
52,304
def _get_ind_from_H ( H ) : r if H <= 0 : return 0 for ind , Hi in enumerate ( H_std ) : if Hi >= H : return ind - 1 return 7
r Method defined in the US Standard Atmosphere 1976 for determining the index of the layer a specified elevation is above . Levels are 0 11E3 20E3 32E3 47E3 51E3 71E3 84852 meters respectively .
52,305
def gauge_from_t ( t , SI = True , schedule = 'BWG' ) : r tol = 0.1 if SI : t_inch = round ( t / inch , 9 ) else : t_inch = t try : sch_integers , sch_inch , sch_SI , decreasing = wire_schedules [ schedule ] except : raise ValueError ( 'Wire gauge schedule not found' ) sch_max , sch_min = sch_inch [ 0 ] , sch_inch [ - 1 ] if t_inch > sch_max : raise ValueError ( 'Input thickness is above the largest in the selected schedule' ) if t_inch in sch_inch : gauge = sch_integers [ sch_inch . index ( t_inch ) ] else : for i in range ( len ( sch_inch ) ) : if sch_inch [ i ] >= t_inch : larger = sch_inch [ i ] else : break if larger == sch_min : gauge = sch_min else : smaller = sch_inch [ i ] if ( t_inch - smaller ) <= tol * ( larger - smaller ) : gauge = sch_integers [ i ] else : gauge = sch_integers [ i - 1 ] return gauge
r Looks up the gauge of a given wire thickness of given schedule . Values are all non - linear and tabulated internally .
52,306
def t_from_gauge ( gauge , SI = True , schedule = 'BWG' ) : r try : sch_integers , sch_inch , sch_SI , decreasing = wire_schedules [ schedule ] except : raise ValueError ( "Wire gauge schedule not found; supported gauges are \'BWG', 'AWG', 'SWG', 'MWG', 'BSWG', and 'SSWG'." ) try : i = sch_integers . index ( gauge ) except : raise ValueError ( 'Input gauge not found in selected schedule' ) if SI : return sch_SI [ i ] else : return sch_inch [ i ]
r Looks up the thickness of a given wire gauge of given schedule . Values are all non - linear and tabulated internally .
52,307
def API520_F2 ( k , P1 , P2 ) : r r = P2 / P1 return ( k / ( k - 1 ) * r ** ( 2. / k ) * ( ( 1 - r ** ( ( k - 1. ) / k ) ) / ( 1. - r ) ) ) ** 0.5
r Calculates coefficient F2 for subcritical flow for use in API 520 subcritical flow relief valve sizing .
52,308
def API520_SH ( T1 , P1 ) : r if P1 > 20780325.0 : raise Exception ( 'For P above 20679 kPag, use the critical flow model' ) if T1 > 922.15 : raise Exception ( 'Superheat cannot be above 649 degrees Celcius' ) if T1 < 422.15 : return 1. return float ( bisplev ( T1 , P1 , API520_KSH_tck ) )
r Calculates correction due to steam superheat for steam flow for use in API 520 relief valve sizing . 2D interpolation among a table with 28 pressures and 10 temperatures is performed .
52,309
def API520_W ( Pset , Pback ) : r gauge_backpressure = ( Pback - atm ) / ( Pset - atm ) * 100.0 if gauge_backpressure < 15.0 : return 1.0 return interp ( gauge_backpressure , Kw_x , Kw_y )
r Calculates capacity correction due to backpressure on balanced spring - loaded PRVs in liquid service . For pilot operated valves this is always 1 . Applicable up to 50% of the percent gauge backpressure For use in API 520 relief valve sizing . 1D interpolation among a table with 53 backpressures is performed .
52,310
def API520_B ( Pset , Pback , overpressure = 0.1 ) : r gauge_backpressure = ( Pback - atm ) / ( Pset - atm ) * 100 if overpressure not in [ 0.1 , 0.16 , 0.21 ] : raise Exception ( 'Only overpressure of 10%, 16%, or 21% are permitted' ) if ( overpressure == 0.1 and gauge_backpressure < 30 ) or ( overpressure == 0.16 and gauge_backpressure < 38 ) or ( overpressure == 0.21 and gauge_backpressure < 50 ) : return 1 elif gauge_backpressure > 50 : raise Exception ( 'Gauge pressure must be < 50%' ) if overpressure == 0.16 : Kb = interp ( gauge_backpressure , Kb_16_over_x , Kb_16_over_y ) elif overpressure == 0.1 : Kb = interp ( gauge_backpressure , Kb_10_over_x , Kb_10_over_y ) return Kb
r Calculates capacity correction due to backpressure on balanced spring - loaded PRVs in vapor service . For pilot operated valves this is always 1 . Applicable up to 50% of the percent gauge backpressure For use in API 520 relief valve sizing . 1D interpolation among a table with 53 backpressures is performed .
52,311
def API520_A_g ( m , T , Z , MW , k , P1 , P2 = 101325 , Kd = 0.975 , Kb = 1 , Kc = 1 ) : r P1 , P2 = P1 / 1000. , P2 / 1000. m = m * 3600. if is_critical_flow ( P1 , P2 , k ) : C = API520_C ( k ) A = m / ( C * Kd * Kb * Kc * P1 ) * ( T * Z / MW ) ** 0.5 else : F2 = API520_F2 ( k , P1 , P2 ) A = 17.9 * m / ( F2 * Kd * Kc ) * ( T * Z / ( MW * P1 * ( P1 - P2 ) ) ) ** 0.5 return A * 0.001 ** 2
r Calculates required relief valve area for an API 520 valve passing a gas or a vapor at either critical or sub - critical flow .
52,312
def API520_A_steam ( m , T , P1 , Kd = 0.975 , Kb = 1 , Kc = 1 ) : r KN = API520_N ( P1 ) KSH = API520_SH ( T , P1 ) P1 = P1 / 1000. m = m * 3600. A = 190.5 * m / ( P1 * Kd * Kb * Kc * KN * KSH ) return A * 0.001 ** 2
r Calculates required relief valve area for an API 520 valve passing a steam at either saturation or superheat but not partially condensed .
52,313
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,314
def getFontName ( self , names , default = "helvetica" ) : 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
52,315
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" : 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
52,316
def pisaParser ( src , context , default_css = "" , xhtml = False , encoding = None , xml_output = None ) : global CSSAttrCache CSSAttrCache = { } if xhtml : parser = html5lib . XHTMLParser ( tree = treebuilders . getTreeBuilder ( "dom" ) ) else : parser = html5lib . HTMLParser ( tree = treebuilders . getTreeBuilder ( "dom" ) ) if isinstance ( src , six . text_type ) : if not encoding : encoding = "utf-8" src = src . encode ( encoding ) src = pisaTempFile ( src , capacity = context . capacity ) document = parser . parse ( src , ) 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 ) context . parseCSS ( ) 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
52,317
def doLayout ( self , width ) : 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 ) y = ( self . lineHeight - self . fontSize ) for frag in self : frag [ "y" ] = y return self . height
Align words in previous line .
52,318
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 if not splitted : x = style [ "textIndent" ] lenText = len ( self ) pos = 0 while pos < lenText : posBegin = pos line = Line ( style ) for box in copy . copy ( boxStack ) : box [ "x" ] = 0 line . append ( BoxBegin ( box ) ) while pos < lenText : frag = self [ pos ] fragWidth = frag [ "width" ] frag [ "x" ] = x pos += 1 if isinstance ( frag , BoxBegin ) : boxStack . append ( frag ) elif isinstance ( frag , BoxEnd ) : boxStack . pop ( ) if frag . isSoft : if frag . isLF : line . append ( frag ) break if x == 0 : continue elif fragWidth + x > maxWidth : break x += fragWidth line . append ( frag ) while line and line [ - 1 ] . name in ( "space" , "br" ) : line . pop ( ) line . dumpFragments ( ) self . height += line . doLayout ( self . width ) self . lines . append ( line ) if self . height > maxHeight : return posBegin x = 0 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
52,319
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
52,320
def wrap ( self , availWidth , availHeight ) : 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 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 .
52,321
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 .
52,322
def draw ( self ) : logger . debug ( "*** draw" ) if not self . text : return canvas = self . canv style = self . style canvas . saveState ( ) 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 : if hasattr ( frag , "draw" ) : frag . draw ( canvas , dy - y ) 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" ] ) 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 .
52,323
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
52,324
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 .
52,325
def parse ( self , src ) : self . cssBuilder . beginStylesheet ( ) try : 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 .
52,326
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 .
52,327
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 .
52,328
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 .
52,329
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
52,330
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
52,331
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 .
52,332
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
52,333
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
52,334
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 ) : r , g , b = [ int ( x ) for x in rgb_re . search ( value ) . groups ( ) ] value = "#%02x%02x%02x" % ( r , g , b ) else : pass return toColor ( value , default )
Convert to color value . This returns a Color object instance from a text bit .
52,335
def getCoords ( x , y , w , h , 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
52,336
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
52,337
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
52,338
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
52,339
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
52,340
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 ) 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
52,341
def setMimeTypeByName ( self , name ) : " Guess the mime type " mimetype = mimetypes . guess_type ( name ) [ 0 ] if mimetype is not None : self . mimetype = mimetypes . guess_type ( name ) [ 0 ] . split ( ";" ) [ 0 ]
Guess the mime type
52,342
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
52,343
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 ( ) 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 ) 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
52,344
def splitLines0 ( frags , widths ) : lineNum = 0 maxW = widths [ lineNum ] i = - 1 l = len ( frags ) lim = start = 0 text = frags [ 0 ] while 1 : 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 if start == lim : break 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 while g . text [ lim ] == ' ' : lim -= 1 nSpaces -= 1 break if j < 0 : j = lim if g [ 0 ] is f : g [ 2 ] = j else : g = ( f , start , j ) line . append ( g ) if j == lim : i += 1
given a list of ParaFrags we return a list of ParaLines
52,345
def cjkFragSplit ( frags , maxWidths , calcBounds , encoding = 'utf8' ) : from reportlab . rl_config import _FUZZ U = [ ] 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 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 ] lineStartPos = i widthUsed = w i -= 1 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
52,346
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
52,347
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 _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 ) : 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 ) 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 .
52,348
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 .
52,349
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 .
52,350
def link_callback ( uri , rel ) : sUrl = settings . STATIC_URL sRoot = settings . STATIC_ROOT mUrl = settings . MEDIA_URL mRoot = settings . MEDIA_ROOT 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 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
52,351
def start ( ) : setupdir = dirname ( dirname ( __file__ ) ) curdir = os . getcwd ( ) 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 .
52,352
def mergeStyles ( self , styles ) : " XXX Bugfix for use in PISA " 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
52,353
def atPage ( self , page , pseudopage , declarations ) : return self . ruleset ( [ self . selector ( '*' ) ] , declarations )
This is overriden by xhtml2pdf . context . pisaCSSBuilder
52,354
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' ] 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 ) ) : c = PTCycle ( ) for ptn in pt : 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" ) 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
52,355
def getRGBData ( self ) : "Return byte array of RGB data as string" if self . _data is None : self . _dataA = None if sys . platform [ 0 : 4 ] == 'java' : import jarray 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 ( ) 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 : self . _data = im . tostring ( ) return self . _data
Return byte array of RGB data as string
52,356
def wrap ( self , availWidth , availHeight ) : " This can be called more than once! Do not overwrite important data like drawWidth " availHeight = self . setMaxHeight ( availHeight ) 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 return self . dWidth , self . dHeight
This can be called more than once! Do not overwrite important data like drawWidth
52,357
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
52,358
def wrap ( self , availWidth , availHeight ) : widths = ( availWidth - self . rightColumnWidth , self . rightColumnWidth ) 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 : tableStyle . append ( ( 'TOPPADDING' , ( 0 , i ) , ( - 1 , i ) , max ( lastMargin , leftColStyle . spaceBefore ) ) ) lastMargin = leftColStyle . spaceAfter 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 .
52,359
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 ) 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
52,360
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 : if self . _check_blocked ( sendspec ) and sendspec . ignore_background != True : shutit . log ( 'sendline: blocked' , level = logging . DEBUG ) return False if sendspec . run_in_background : shutit . log ( 'sendline: run_in_background' , level = logging . DEBUG ) shutit_background_command_object = self . login_stack . get_current_login_item ( ) . append_background_send ( sendspec ) sendspec . check_exit = False if sendspec . nonewline != True : sendspec . send += '\n' sendspec . nonewline = True if sendspec . run_in_background : shutit_background_command_object . run_background_command ( ) return True 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 .
52,361
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 : 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 : break elif res_str in ( 'S' , 'N' ) : 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 ) time . sleep ( cadence ) shutit . log ( 'Wait complete.' , level = logging . DEBUG ) return True
Does not return until all background commands are completed .
52,362
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 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 ) 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
52,363
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 ) 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 ( + shutit . build [ 'conn_module' ] ) container_id = shutit . target [ 'container_id' ] conn_module . destroy_container ( shutit , 'host_child' , 'target_child' , container_id ) 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 ) 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 .
52,364
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 .
52,365
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 ) ] 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 : 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 : 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 ) else : return False return True
Internal function to check the exit value of the shell . Do not use .
52,366
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 .
52,367
def is_user_id_available ( self , user_id , note = None , loglevel = logging . DEBUG ) : shutit = self . shutit shutit . handle_note ( note ) 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 .
52,368
def lsb_release ( self , loglevel = logging . DEBUG ) : 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 .
52,369
def user_exists ( self , user , note = None , loglevel = logging . DEBUG ) : shutit = self . shutit shutit . handle_note ( note ) exists = False if user == '' : return exists 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 self . expect ( self . default_expect ) shutit . handle_note_after ( note = note ) return exists
Returns true if the specified username exists .
52,370
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 .
52,371
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 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' ) + + fname + + random_id + + curr_str + + 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 .
52,372
def check_dependee_order ( depender , dependee , dependee_id ) : 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 .
52,373
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
52,374
def get_config_set ( self , section , option ) : values = set ( ) for cp , filename , fp in self . layers : filename = filename fp = fp 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 .
52,375
def reload ( self ) : oldlayers = self . layers self . layers = [ ] for cp , filename , fp in oldlayers : cp = cp 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 .
52,376
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' ) 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
52,377
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 .
52,378
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 .
52,379
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 .
52,380
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 .
52,381
def fail ( self , msg , shutit_pexpect_child = None , throw_exception = False ) : shutit_global . shutit_global_object . yield_to_draw ( ) 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 : 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 .
52,382
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
52,383
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 .
52,384
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' ) 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' ) 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' ) else : self . fail ( 'CTRL-C hit and could not recover' ) self . fail ( 'Should not get here (expect_allow_interrupt)' ) return True
This function allows you to interrupt the run at more or less any point by breaking up the timeout into interactive chunks .
52,385
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 ( ) 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 ) : 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 ) self . handle_note_after ( note = note ) return True
Send file from host machine to given path
52,386
def send_host_dir ( self , path , hostfilepath , expect = None , shutit_pexpect_child = None , note = None , user = None , group = None , loglevel = logging . DEBUG ) : 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 host directory: ' + hostfilepath + ' to target path: ' + path ) self . log ( 'Sending host directory: ' + hostfilepath + ' to: ' + path , level = logging . INFO ) shutit_pexpect_session . send ( ShutItSendSpec ( shutit_pexpect_session , send = ' command mkdir -p ' + path , echo = False , loglevel = loglevel ) ) if user is None : user = shutit_pexpect_session . whoami ( ) if group is None : group = self . whoarewe ( ) if shutit_pexpect_session . command_available ( 'tar' ) : gzipfname = '/tmp/shutit_tar_tmp.tar.gz' with tarfile . open ( gzipfname , 'w:gz' ) as tar : tar . add ( hostfilepath , arcname = os . path . basename ( hostfilepath ) ) shutit_pexpect_session . send_file ( gzipfname , codecs . open ( gzipfname , mode = 'rb' , encoding = 'iso-8859-1' ) . read ( ) , user = user , group = group , loglevel = loglevel , encoding = 'iso-8859-1' ) shutit_pexpect_session . send ( ShutItSendSpec ( shutit_pexpect_session , send = ' command mkdir -p ' + path + ' && command tar -C ' + path + ' -zxf ' + gzipfname ) ) else : for root , subfolders , files in os . walk ( hostfilepath ) : subfolders . sort ( ) files . sort ( ) for subfolder in subfolders : shutit_pexpect_session . send ( ShutItSendSpec ( shutit_pexpect_session , send = ' command mkdir -p ' + path + '/' + subfolder , echo = False , loglevel = loglevel ) ) self . log ( 'send_host_dir recursing to: ' + hostfilepath + '/' + subfolder , level = logging . DEBUG ) self . send_host_dir ( path + '/' + subfolder , hostfilepath + '/' + subfolder , expect = expect , shutit_pexpect_child = shutit_pexpect_child , loglevel = loglevel ) for fname in files : hostfullfname = os . path . join ( root , fname ) targetfname = os . path . join ( path , fname ) self . log ( 'send_host_dir sending file ' + hostfullfname + ' to ' + 'target file: ' + targetfname , level = logging . DEBUG ) shutit_pexpect_session . send_file ( targetfname , codecs . open ( hostfullfname , mode = 'rb' , encoding = 'iso-8859-1' ) . read ( ) , user = user , group = group , loglevel = loglevel , encoding = 'iso-8859-1' ) self . handle_note_after ( note = note ) return True
Send directory and all contents recursively from host machine to given path . It will automatically make directories on the target .
52,387
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 .
52,388
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 ) if self . build [ 'delivery' ] != 'docker' : return False 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
52,389
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 ) 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 ) for subcp , filename , _ in reversed ( config_parser . layers ) : if filename == whereset : self . fail ( cfgstr + ' is being set in ' + filename + ', unable to override on a user config level' , throw_exception = False ) elif filename == usercfg : break else : 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 ( ) ) 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 : 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 .
52,390
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 .
52,391
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 .
52,392
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 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 ) 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 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 .
52,393
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 .
52,394
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 .
52,395
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 .
52,396
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
52,397
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 ) 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 .
52,398
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 .
52,399
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 ) : if c and c [ 0 ] != ' ' : s += c + '\n' return s
Gets command that have been run and have not been redacted .