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 ) f...
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 ) medi...
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 . HTMLPars...
- 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...
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 = l...
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 s...
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 = Pa...
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 . setLineWidt...
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 ( ) r...
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 ...
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 , proper...
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...
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 = "...
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 ( ...
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 . make...
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 , No...
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...
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 s...
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 , ...
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 = _get...
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 . b...
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 ) re...
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 # conve...
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 pro...
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 i...
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 ,...
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 , availHei...
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 )...
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_...
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 ....
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 che...
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 max...
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. c...
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 = ...
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...
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 ) )...
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' ...
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 = shut...
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 ...
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_back...
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 . send...
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 + ...
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 . environm...
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 ) shut...
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...
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 ]...
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 ( ) ....
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...
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:...
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 , )...
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_s...
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 , pri...
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_in...
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 . DEB...
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 ...
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...
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 sel...
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 . fai...
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 += '#...
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 = ...
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_ses...
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 ) retu...
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_orde...
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 [ '...
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 s...
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 . ...
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'...
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 i...
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_...
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 = [ se...
Dependency checking phase is performed in this method .
593
11