repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
getCoords
def getCoords(x, y, w, h, pagesize): """ 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 """ #~ 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)
python
def getCoords(x, y, w, h, pagesize): """ 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 """ #~ 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)
[ "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
[ "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" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L336-L354
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
getFrameDimensions
def getFrameDimensions(data, page_width, page_height): """Calculate dimensions of a frame Returns left, top, width and height of the frame in points. """ 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
python
def getFrameDimensions(data, page_width, page_height): """Calculate dimensions of a frame Returns left, top, width and height of the frame in points. """ 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
[ "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 Returns left, top, width and height of the frame in points.
[ "Calculate", "dimensions", "of", "a", "frame" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L372-L407
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
getPos
def getPos(position, pagesize): """ Pair of coordinates """ 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)
python
def getPos(position, pagesize): """ Pair of coordinates """ 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)
[ "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
[ "Pair", "of", "coordinates" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L411-L419
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
pisaTempFile.makeTempFile
def makeTempFile(self): """ Switch to next startegy. If an error occured, stay with the first strategy """ 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
python
def makeTempFile(self): """ Switch to next startegy. If an error occured, stay with the first strategy """ 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
[ "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
[ "Switch", "to", "next", "startegy", ".", "If", "an", "error", "occured", "stay", "with", "the", "first", "strategy" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L497-L511
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
pisaTempFile.getvalue
def getvalue(self): """ Get value of file. Work around for second strategy. Always returns bytes """ 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
python
def getvalue(self): """ Get value of file. Work around for second strategy. Always returns bytes """ 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
[ "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
[ "Get", "value", "of", "file", ".", "Work", "around", "for", "second", "strategy", ".", "Always", "returns", "bytes" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L529-L542
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
pisaTempFile.write
def write(self, value): """ If capacity != -1 and length of file > capacity it is time to switch """ if self.capacity > 0 and self.strategy == 0: len_value = len(value) if len_value >= self.capacity: needs_new_strategy = True else: self.seek(0, 2) # find end of file needs_new_strategy = \ (self.tell() + len_value) >= self.capacity if needs_new_strategy: self.makeTempFile() if not isinstance(value, six.binary_type): value = value.encode('utf-8') self._delegate.write(value)
python
def write(self, value): """ If capacity != -1 and length of file > capacity it is time to switch """ if self.capacity > 0 and self.strategy == 0: len_value = len(value) if len_value >= self.capacity: needs_new_strategy = True else: self.seek(0, 2) # find end of file needs_new_strategy = \ (self.tell() + len_value) >= self.capacity if needs_new_strategy: self.makeTempFile() if not isinstance(value, six.binary_type): value = value.encode('utf-8') self._delegate.write(value)
[ "def", "write", "(", "self", ",", "value", ")", ":", "if", "self", ".", "capacity", ">", "0", "and", "self", ".", "strategy", "==", "0", ":", "len_value", "=", "len", "(", "value", ")", "if", "len_value", ">=", "self", ".", "capacity", ":", "needs_new_strategy", "=", "True", "else", ":", "self", ".", "seek", "(", "0", ",", "2", ")", "# find end of file", "needs_new_strategy", "=", "(", "self", ".", "tell", "(", ")", "+", "len_value", ")", ">=", "self", ".", "capacity", "if", "needs_new_strategy", ":", "self", ".", "makeTempFile", "(", ")", "if", "not", "isinstance", "(", "value", ",", "six", ".", "binary_type", ")", ":", "value", "=", "value", ".", "encode", "(", "'utf-8'", ")", "self", ".", "_delegate", ".", "write", "(", "value", ")" ]
If capacity != -1 and length of file > capacity it is time to switch
[ "If", "capacity", "!", "=", "-", "1", "and", "length", "of", "file", ">", "capacity", "it", "is", "time", "to", "switch" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L544-L563
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/util.py
pisaFileObject.setMimeTypeByName
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]
python
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]
[ "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
[ "Guess", "the", "mime", "type" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/util.py#L732-L736
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
_sameFrag
def _sameFrag(f, g): """ returns 1 if two ParaFrags map out the same """ 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
python
def _sameFrag(f, g): """ returns 1 if two ParaFrags map out the same """ 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
[ "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
[ "returns", "1", "if", "two", "ParaFrags", "map", "out", "the", "same" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L417-L426
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
_drawBullet
def _drawBullet(canvas, offset, cur_y, bulletText, style): """ draw a bullet text could be a simple string or a frag list """ tx2 = canvas.beginText(style.bulletIndent, cur_y + getattr(style, "bulletOffsetY", 0)) tx2.setFont(style.bulletFontName, style.bulletFontSize) tx2.setFillColor(hasattr(style, 'bulletColor') and style.bulletColor or style.textColor) if isinstance(bulletText, basestring): tx2.textOut(bulletText) else: for f in bulletText: if hasattr(f, "image"): image = f.image width = image.drawWidth height = image.drawHeight gap = style.bulletFontSize * 0.25 img = image.getImage() # print style.bulletIndent, offset, width canvas.drawImage( img, style.leftIndent - width - gap, cur_y + getattr(style, "bulletOffsetY", 0), width, height) else: tx2.setFont(f.fontName, f.fontSize) tx2.setFillColor(f.textColor) tx2.textOut(f.text) canvas.drawText(tx2) #AR making definition lists a bit less ugly #bulletEnd = tx2.getX() bulletEnd = tx2.getX() + style.bulletFontSize * 0.6 offset = max(offset, bulletEnd - style.leftIndent) return offset
python
def _drawBullet(canvas, offset, cur_y, bulletText, style): """ draw a bullet text could be a simple string or a frag list """ tx2 = canvas.beginText(style.bulletIndent, cur_y + getattr(style, "bulletOffsetY", 0)) tx2.setFont(style.bulletFontName, style.bulletFontSize) tx2.setFillColor(hasattr(style, 'bulletColor') and style.bulletColor or style.textColor) if isinstance(bulletText, basestring): tx2.textOut(bulletText) else: for f in bulletText: if hasattr(f, "image"): image = f.image width = image.drawWidth height = image.drawHeight gap = style.bulletFontSize * 0.25 img = image.getImage() # print style.bulletIndent, offset, width canvas.drawImage( img, style.leftIndent - width - gap, cur_y + getattr(style, "bulletOffsetY", 0), width, height) else: tx2.setFont(f.fontName, f.fontSize) tx2.setFillColor(f.textColor) tx2.textOut(f.text) canvas.drawText(tx2) #AR making definition lists a bit less ugly #bulletEnd = tx2.getX() bulletEnd = tx2.getX() + style.bulletFontSize * 0.6 offset = max(offset, bulletEnd - style.leftIndent) return offset
[ "def", "_drawBullet", "(", "canvas", ",", "offset", ",", "cur_y", ",", "bulletText", ",", "style", ")", ":", "tx2", "=", "canvas", ".", "beginText", "(", "style", ".", "bulletIndent", ",", "cur_y", "+", "getattr", "(", "style", ",", "\"bulletOffsetY\"", ",", "0", ")", ")", "tx2", ".", "setFont", "(", "style", ".", "bulletFontName", ",", "style", ".", "bulletFontSize", ")", "tx2", ".", "setFillColor", "(", "hasattr", "(", "style", ",", "'bulletColor'", ")", "and", "style", ".", "bulletColor", "or", "style", ".", "textColor", ")", "if", "isinstance", "(", "bulletText", ",", "basestring", ")", ":", "tx2", ".", "textOut", "(", "bulletText", ")", "else", ":", "for", "f", "in", "bulletText", ":", "if", "hasattr", "(", "f", ",", "\"image\"", ")", ":", "image", "=", "f", ".", "image", "width", "=", "image", ".", "drawWidth", "height", "=", "image", ".", "drawHeight", "gap", "=", "style", ".", "bulletFontSize", "*", "0.25", "img", "=", "image", ".", "getImage", "(", ")", "# print style.bulletIndent, offset, width", "canvas", ".", "drawImage", "(", "img", ",", "style", ".", "leftIndent", "-", "width", "-", "gap", ",", "cur_y", "+", "getattr", "(", "style", ",", "\"bulletOffsetY\"", ",", "0", ")", ",", "width", ",", "height", ")", "else", ":", "tx2", ".", "setFont", "(", "f", ".", "fontName", ",", "f", ".", "fontSize", ")", "tx2", ".", "setFillColor", "(", "f", ".", "textColor", ")", "tx2", ".", "textOut", "(", "f", ".", "text", ")", "canvas", ".", "drawText", "(", "tx2", ")", "#AR making definition lists a bit less ugly", "#bulletEnd = tx2.getX()", "bulletEnd", "=", "tx2", ".", "getX", "(", ")", "+", "style", ".", "bulletFontSize", "*", "0.6", "offset", "=", "max", "(", "offset", ",", "bulletEnd", "-", "style", ".", "leftIndent", ")", "return", "offset" ]
draw a bullet text could be a simple string or a frag list
[ "draw", "a", "bullet", "text", "could", "be", "a", "simple", "string", "or", "a", "frag", "list" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L536-L570
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
splitLines0
def splitLines0(frags, widths): """ given a list of ParaFrags we return a list of ParaLines each ParaLine has 1) ExtraSpace 2) blankCount 3) [textDefns....] each text definition is a (ParaFrag, start, limit) triplet """ #initialise the algorithm lineNum = 0 maxW = widths[lineNum] i = -1 l = len(frags) lim = start = 0 text = frags[0] while 1: #find a non whitespace character while i < l: while start < lim and text[start] == ' ': start += 1 if start == lim: i += 1 if i == l: break start = 0 f = frags[i] text = f.text lim = len(text) else: break # we found one if start == lim: break # if we didn't find one we are done #start of a line g = (None, None, None) line = [] cLen = 0 nSpaces = 0 while cLen < maxW: j = text.find(' ', start) if j < 0: j == lim w = stringWidth(text[start:j], f.fontName, f.fontSize) cLen += w if cLen > maxW and line != []: cLen = cLen - w #this is the end of the line while g.text[lim] == ' ': lim -= 1 nSpaces -= 1 break if j < 0: j = lim if g[0] is f: g[2] = j #extend else: g = (f, start, j) line.append(g) if j == lim: i += 1
python
def splitLines0(frags, widths): """ given a list of ParaFrags we return a list of ParaLines each ParaLine has 1) ExtraSpace 2) blankCount 3) [textDefns....] each text definition is a (ParaFrag, start, limit) triplet """ #initialise the algorithm lineNum = 0 maxW = widths[lineNum] i = -1 l = len(frags) lim = start = 0 text = frags[0] while 1: #find a non whitespace character while i < l: while start < lim and text[start] == ' ': start += 1 if start == lim: i += 1 if i == l: break start = 0 f = frags[i] text = f.text lim = len(text) else: break # we found one if start == lim: break # if we didn't find one we are done #start of a line g = (None, None, None) line = [] cLen = 0 nSpaces = 0 while cLen < maxW: j = text.find(' ', start) if j < 0: j == lim w = stringWidth(text[start:j], f.fontName, f.fontSize) cLen += w if cLen > maxW and line != []: cLen = cLen - w #this is the end of the line while g.text[lim] == ' ': lim -= 1 nSpaces -= 1 break if j < 0: j = lim if g[0] is f: g[2] = j #extend else: g = (f, start, j) line.append(g) if j == lim: i += 1
[ "def", "splitLines0", "(", "frags", ",", "widths", ")", ":", "#initialise the algorithm", "lineNum", "=", "0", "maxW", "=", "widths", "[", "lineNum", "]", "i", "=", "-", "1", "l", "=", "len", "(", "frags", ")", "lim", "=", "start", "=", "0", "text", "=", "frags", "[", "0", "]", "while", "1", ":", "#find a non whitespace character", "while", "i", "<", "l", ":", "while", "start", "<", "lim", "and", "text", "[", "start", "]", "==", "' '", ":", "start", "+=", "1", "if", "start", "==", "lim", ":", "i", "+=", "1", "if", "i", "==", "l", ":", "break", "start", "=", "0", "f", "=", "frags", "[", "i", "]", "text", "=", "f", ".", "text", "lim", "=", "len", "(", "text", ")", "else", ":", "break", "# we found one", "if", "start", "==", "lim", ":", "break", "# if we didn't find one we are done", "#start of a line", "g", "=", "(", "None", ",", "None", ",", "None", ")", "line", "=", "[", "]", "cLen", "=", "0", "nSpaces", "=", "0", "while", "cLen", "<", "maxW", ":", "j", "=", "text", ".", "find", "(", "' '", ",", "start", ")", "if", "j", "<", "0", ":", "j", "==", "lim", "w", "=", "stringWidth", "(", "text", "[", "start", ":", "j", "]", ",", "f", ".", "fontName", ",", "f", ".", "fontSize", ")", "cLen", "+=", "w", "if", "cLen", ">", "maxW", "and", "line", "!=", "[", "]", ":", "cLen", "=", "cLen", "-", "w", "#this is the end of the line", "while", "g", ".", "text", "[", "lim", "]", "==", "' '", ":", "lim", "-=", "1", "nSpaces", "-=", "1", "break", "if", "j", "<", "0", ":", "j", "=", "lim", "if", "g", "[", "0", "]", "is", "f", ":", "g", "[", "2", "]", "=", "j", "#extend", "else", ":", "g", "=", "(", "f", ",", "start", ",", "j", ")", "line", ".", "append", "(", "g", ")", "if", "j", "==", "lim", ":", "i", "+=", "1" ]
given a list of ParaFrags we return a list of ParaLines each ParaLine has 1) ExtraSpace 2) blankCount 3) [textDefns....] each text definition is a (ParaFrag, start, limit) triplet
[ "given", "a", "list", "of", "ParaFrags", "we", "return", "a", "list", "of", "ParaLines" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L592-L652
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
cjkFragSplit
def cjkFragSplit(frags, maxWidths, calcBounds, encoding='utf8'): """ This attempts to be wordSplit for frags using the dumb algorithm """ from reportlab.rl_config import _FUZZ U = [] # get a list of single glyphs with their widths etc etc for f in frags: text = f.text if not isinstance(text, unicode): text = text.decode(encoding) if text: U.extend([cjkU(t, f, encoding) for t in text]) else: U.append(cjkU(text, f, encoding)) lines = [] widthUsed = lineStartPos = 0 maxWidth = maxWidths[0] for i, u in enumerate(U): w = u.width widthUsed += w lineBreak = hasattr(u.frag, 'lineBreak') endLine = (widthUsed > maxWidth + _FUZZ and widthUsed > 0) or lineBreak if endLine: if lineBreak: continue extraSpace = maxWidth - widthUsed + w #This is the most important of the Japanese typography rules. #if next character cannot start a line, wrap it up to this line so it hangs #in the right margin. We won't do two or more though - that's unlikely and #would result in growing ugliness. nextChar = U[i] if nextChar in ALL_CANNOT_START: extraSpace -= w i += 1 lines.append(makeCJKParaLine(U[lineStartPos:i], extraSpace, calcBounds)) try: maxWidth = maxWidths[len(lines)] except IndexError: maxWidth = maxWidths[-1] # use the last one lineStartPos = i widthUsed = w i -= 1 #any characters left? if widthUsed > 0: lines.append(makeCJKParaLine(U[lineStartPos:], maxWidth - widthUsed, calcBounds)) return ParaLines(kind=1, lines=lines)
python
def cjkFragSplit(frags, maxWidths, calcBounds, encoding='utf8'): """ This attempts to be wordSplit for frags using the dumb algorithm """ from reportlab.rl_config import _FUZZ U = [] # get a list of single glyphs with their widths etc etc for f in frags: text = f.text if not isinstance(text, unicode): text = text.decode(encoding) if text: U.extend([cjkU(t, f, encoding) for t in text]) else: U.append(cjkU(text, f, encoding)) lines = [] widthUsed = lineStartPos = 0 maxWidth = maxWidths[0] for i, u in enumerate(U): w = u.width widthUsed += w lineBreak = hasattr(u.frag, 'lineBreak') endLine = (widthUsed > maxWidth + _FUZZ and widthUsed > 0) or lineBreak if endLine: if lineBreak: continue extraSpace = maxWidth - widthUsed + w #This is the most important of the Japanese typography rules. #if next character cannot start a line, wrap it up to this line so it hangs #in the right margin. We won't do two or more though - that's unlikely and #would result in growing ugliness. nextChar = U[i] if nextChar in ALL_CANNOT_START: extraSpace -= w i += 1 lines.append(makeCJKParaLine(U[lineStartPos:i], extraSpace, calcBounds)) try: maxWidth = maxWidths[len(lines)] except IndexError: maxWidth = maxWidths[-1] # use the last one lineStartPos = i widthUsed = w i -= 1 #any characters left? if widthUsed > 0: lines.append(makeCJKParaLine(U[lineStartPos:], maxWidth - widthUsed, calcBounds)) return ParaLines(kind=1, lines=lines)
[ "def", "cjkFragSplit", "(", "frags", ",", "maxWidths", ",", "calcBounds", ",", "encoding", "=", "'utf8'", ")", ":", "from", "reportlab", ".", "rl_config", "import", "_FUZZ", "U", "=", "[", "]", "# get a list of single glyphs with their widths etc etc", "for", "f", "in", "frags", ":", "text", "=", "f", ".", "text", "if", "not", "isinstance", "(", "text", ",", "unicode", ")", ":", "text", "=", "text", ".", "decode", "(", "encoding", ")", "if", "text", ":", "U", ".", "extend", "(", "[", "cjkU", "(", "t", ",", "f", ",", "encoding", ")", "for", "t", "in", "text", "]", ")", "else", ":", "U", ".", "append", "(", "cjkU", "(", "text", ",", "f", ",", "encoding", ")", ")", "lines", "=", "[", "]", "widthUsed", "=", "lineStartPos", "=", "0", "maxWidth", "=", "maxWidths", "[", "0", "]", "for", "i", ",", "u", "in", "enumerate", "(", "U", ")", ":", "w", "=", "u", ".", "width", "widthUsed", "+=", "w", "lineBreak", "=", "hasattr", "(", "u", ".", "frag", ",", "'lineBreak'", ")", "endLine", "=", "(", "widthUsed", ">", "maxWidth", "+", "_FUZZ", "and", "widthUsed", ">", "0", ")", "or", "lineBreak", "if", "endLine", ":", "if", "lineBreak", ":", "continue", "extraSpace", "=", "maxWidth", "-", "widthUsed", "+", "w", "#This is the most important of the Japanese typography rules.", "#if next character cannot start a line, wrap it up to this line so it hangs", "#in the right margin. We won't do two or more though - that's unlikely and", "#would result in growing ugliness.", "nextChar", "=", "U", "[", "i", "]", "if", "nextChar", "in", "ALL_CANNOT_START", ":", "extraSpace", "-=", "w", "i", "+=", "1", "lines", ".", "append", "(", "makeCJKParaLine", "(", "U", "[", "lineStartPos", ":", "i", "]", ",", "extraSpace", ",", "calcBounds", ")", ")", "try", ":", "maxWidth", "=", "maxWidths", "[", "len", "(", "lines", ")", "]", "except", "IndexError", ":", "maxWidth", "=", "maxWidths", "[", "-", "1", "]", "# use the last one", "lineStartPos", "=", "i", "widthUsed", "=", "w", "i", "-=", "1", "#any characters left?", "if", "widthUsed", ">", "0", ":", "lines", ".", "append", "(", "makeCJKParaLine", "(", "U", "[", "lineStartPos", ":", "]", ",", "maxWidth", "-", "widthUsed", ",", "calcBounds", ")", ")", "return", "ParaLines", "(", "kind", "=", "1", ",", "lines", "=", "lines", ")" ]
This attempts to be wordSplit for frags using the dumb algorithm
[ "This", "attempts", "to", "be", "wordSplit", "for", "frags", "using", "the", "dumb", "algorithm" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L854-L904
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
Paragraph.minWidth
def minWidth(self): """ Attempt to determine a minimum sensible width """ 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))
python
def minWidth(self): """ Attempt to determine a minimum sensible width """ 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))
[ "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
[ "Attempt", "to", "determine", "a", "minimum", "sensible", "width" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L1043-L1060
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
Paragraph.breakLinesCJK
def breakLinesCJK(self, width): """Initially, the dumbest possible wrapping algorithm. Cannot handle font variations.""" if self.debug: print (id(self), "breakLinesCJK") if not isinstance(width, (list, tuple)): maxWidths = [width] else: maxWidths = width style = self.style #for bullets, work out width and ensure we wrap the right amount onto line one _handleBulletWidth(self.bulletText, style, maxWidths) if len(self.frags) > 1: autoLeading = getattr(self, 'autoLeading', getattr(style, 'autoLeading', '')) calcBounds = autoLeading not in ('', 'off') return cjkFragSplit(self.frags, maxWidths, calcBounds, self.encoding) elif not len(self.frags): return ParaLines(kind=0, fontSize=style.fontSize, fontName=style.fontName, textColor=style.textColor, lines=[], ascent=style.fontSize, descent=-0.2 * style.fontSize) f = self.frags[0] if 1 and hasattr(self, 'blPara') and getattr(self, '_splitpara', 0): #NB this is an utter hack that awaits the proper information #preserving splitting algorithm return f.clone(kind=0, lines=self.blPara.lines) lines = [] self.height = 0 f = self.frags[0] if hasattr(f, 'text'): text = f.text else: text = ''.join(getattr(f, 'words', [])) from reportlab.lib.textsplit import wordSplit lines = wordSplit(text, maxWidths[0], f.fontName, f.fontSize) #the paragraph drawing routine assumes multiple frags per line, so we need an #extra list like this # [space, [text]] # wrappedLines = [(sp, [line]) for (sp, line) in lines] return f.clone(kind=0, lines=wrappedLines, ascent=f.fontSize, descent=-0.2 * f.fontSize)
python
def breakLinesCJK(self, width): """Initially, the dumbest possible wrapping algorithm. Cannot handle font variations.""" if self.debug: print (id(self), "breakLinesCJK") if not isinstance(width, (list, tuple)): maxWidths = [width] else: maxWidths = width style = self.style #for bullets, work out width and ensure we wrap the right amount onto line one _handleBulletWidth(self.bulletText, style, maxWidths) if len(self.frags) > 1: autoLeading = getattr(self, 'autoLeading', getattr(style, 'autoLeading', '')) calcBounds = autoLeading not in ('', 'off') return cjkFragSplit(self.frags, maxWidths, calcBounds, self.encoding) elif not len(self.frags): return ParaLines(kind=0, fontSize=style.fontSize, fontName=style.fontName, textColor=style.textColor, lines=[], ascent=style.fontSize, descent=-0.2 * style.fontSize) f = self.frags[0] if 1 and hasattr(self, 'blPara') and getattr(self, '_splitpara', 0): #NB this is an utter hack that awaits the proper information #preserving splitting algorithm return f.clone(kind=0, lines=self.blPara.lines) lines = [] self.height = 0 f = self.frags[0] if hasattr(f, 'text'): text = f.text else: text = ''.join(getattr(f, 'words', [])) from reportlab.lib.textsplit import wordSplit lines = wordSplit(text, maxWidths[0], f.fontName, f.fontSize) #the paragraph drawing routine assumes multiple frags per line, so we need an #extra list like this # [space, [text]] # wrappedLines = [(sp, [line]) for (sp, line) in lines] return f.clone(kind=0, lines=wrappedLines, ascent=f.fontSize, descent=-0.2 * f.fontSize)
[ "def", "breakLinesCJK", "(", "self", ",", "width", ")", ":", "if", "self", ".", "debug", ":", "print", "(", "id", "(", "self", ")", ",", "\"breakLinesCJK\"", ")", "if", "not", "isinstance", "(", "width", ",", "(", "list", ",", "tuple", ")", ")", ":", "maxWidths", "=", "[", "width", "]", "else", ":", "maxWidths", "=", "width", "style", "=", "self", ".", "style", "#for bullets, work out width and ensure we wrap the right amount onto line one", "_handleBulletWidth", "(", "self", ".", "bulletText", ",", "style", ",", "maxWidths", ")", "if", "len", "(", "self", ".", "frags", ")", ">", "1", ":", "autoLeading", "=", "getattr", "(", "self", ",", "'autoLeading'", ",", "getattr", "(", "style", ",", "'autoLeading'", ",", "''", ")", ")", "calcBounds", "=", "autoLeading", "not", "in", "(", "''", ",", "'off'", ")", "return", "cjkFragSplit", "(", "self", ".", "frags", ",", "maxWidths", ",", "calcBounds", ",", "self", ".", "encoding", ")", "elif", "not", "len", "(", "self", ".", "frags", ")", ":", "return", "ParaLines", "(", "kind", "=", "0", ",", "fontSize", "=", "style", ".", "fontSize", ",", "fontName", "=", "style", ".", "fontName", ",", "textColor", "=", "style", ".", "textColor", ",", "lines", "=", "[", "]", ",", "ascent", "=", "style", ".", "fontSize", ",", "descent", "=", "-", "0.2", "*", "style", ".", "fontSize", ")", "f", "=", "self", ".", "frags", "[", "0", "]", "if", "1", "and", "hasattr", "(", "self", ",", "'blPara'", ")", "and", "getattr", "(", "self", ",", "'_splitpara'", ",", "0", ")", ":", "#NB this is an utter hack that awaits the proper information", "#preserving splitting algorithm", "return", "f", ".", "clone", "(", "kind", "=", "0", ",", "lines", "=", "self", ".", "blPara", ".", "lines", ")", "lines", "=", "[", "]", "self", ".", "height", "=", "0", "f", "=", "self", ".", "frags", "[", "0", "]", "if", "hasattr", "(", "f", ",", "'text'", ")", ":", "text", "=", "f", ".", "text", "else", ":", "text", "=", "''", ".", "join", "(", "getattr", "(", "f", ",", "'words'", ",", "[", "]", ")", ")", "from", "reportlab", ".", "lib", ".", "textsplit", "import", "wordSplit", "lines", "=", "wordSplit", "(", "text", ",", "maxWidths", "[", "0", "]", ",", "f", ".", "fontName", ",", "f", ".", "fontSize", ")", "#the paragraph drawing routine assumes multiple frags per line, so we need an", "#extra list like this", "# [space, [text]]", "#", "wrappedLines", "=", "[", "(", "sp", ",", "[", "line", "]", ")", "for", "(", "sp", ",", "line", ")", "in", "lines", "]", "return", "f", ".", "clone", "(", "kind", "=", "0", ",", "lines", "=", "wrappedLines", ",", "ascent", "=", "f", ".", "fontSize", ",", "descent", "=", "-", "0.2", "*", "f", ".", "fontSize", ")" ]
Initially, the dumbest possible wrapping algorithm. Cannot handle font variations.
[ "Initially", "the", "dumbest", "possible", "wrapping", "algorithm", ".", "Cannot", "handle", "font", "variations", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L1409-L1456
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
Paragraph.getPlainText
def getPlainText(self, identify=None): """ Convenience function for templates which want access to the raw text, without XML tags. """ 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 ''
python
def getPlainText(self, identify=None): """ Convenience function for templates which want access to the raw text, without XML tags. """ 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 ''
[ "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.
[ "Convenience", "function", "for", "templates", "which", "want", "access", "to", "the", "raw", "text", "without", "XML", "tags", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L1657-L1675
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/reportlab_paragraph.py
Paragraph.getActualLineWidths0
def getActualLineWidths0(self): """ 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. """ 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)
python
def getActualLineWidths0(self): """ 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. """ 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)
[ "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.
[ "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", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/reportlab_paragraph.py#L1677-L1690
train
xhtml2pdf/xhtml2pdf
demo/djangoproject/views.py
link_callback
def link_callback(uri, rel): """ Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources """ # use short variable names sUrl = settings.STATIC_URL # Typically /static/ sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/ mUrl = settings.MEDIA_URL # Typically /static/media/ # Typically /home/userX/project_static/media/ mRoot = settings.MEDIA_ROOT # convert URIs to absolute system paths if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) else: return uri # handle absolute uri (ie: http://some.tld/foo.png) # make sure that file exists if not os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl) ) return path
python
def link_callback(uri, rel): """ Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources """ # use short variable names sUrl = settings.STATIC_URL # Typically /static/ sRoot = settings.STATIC_ROOT # Typically /home/userX/project_static/ mUrl = settings.MEDIA_URL # Typically /static/media/ # Typically /home/userX/project_static/media/ mRoot = settings.MEDIA_ROOT # convert URIs to absolute system paths if uri.startswith(mUrl): path = os.path.join(mRoot, uri.replace(mUrl, "")) elif uri.startswith(sUrl): path = os.path.join(sRoot, uri.replace(sUrl, "")) else: return uri # handle absolute uri (ie: http://some.tld/foo.png) # make sure that file exists if not os.path.isfile(path): raise Exception( 'media URI must start with %s or %s' % (sUrl, mUrl) ) return path
[ "def", "link_callback", "(", "uri", ",", "rel", ")", ":", "# use short variable names", "sUrl", "=", "settings", ".", "STATIC_URL", "# Typically /static/", "sRoot", "=", "settings", ".", "STATIC_ROOT", "# Typically /home/userX/project_static/", "mUrl", "=", "settings", ".", "MEDIA_URL", "# Typically /static/media/", "# Typically /home/userX/project_static/media/", "mRoot", "=", "settings", ".", "MEDIA_ROOT", "# convert URIs to absolute system paths", "if", "uri", ".", "startswith", "(", "mUrl", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "mRoot", ",", "uri", ".", "replace", "(", "mUrl", ",", "\"\"", ")", ")", "elif", "uri", ".", "startswith", "(", "sUrl", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "sRoot", ",", "uri", ".", "replace", "(", "sUrl", ",", "\"\"", ")", ")", "else", ":", "return", "uri", "# handle absolute uri (ie: http://some.tld/foo.png)", "# make sure that file exists", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "raise", "Exception", "(", "'media URI must start with %s or %s'", "%", "(", "sUrl", ",", "mUrl", ")", ")", "return", "path" ]
Convert HTML URIs to absolute system paths so xhtml2pdf can access those resources
[ "Convert", "HTML", "URIs", "to", "absolute", "system", "paths", "so", "xhtml2pdf", "can", "access", "those", "resources" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/demo/djangoproject/views.py#L23-L48
train
xhtml2pdf/xhtml2pdf
demo/tgpisa/tgpisa/commands.py
start
def start(): """Start the CherryPy application server.""" setupdir = dirname(dirname(__file__)) curdir = os.getcwd() # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration # from a file called 'dev.cfg'. If it's not there, the project # is probably installed and we'll look first for a file called # 'prod.cfg' in the current directory and then for a default # config file called 'default.cfg' packaged in the egg. if len(sys.argv) > 1: configfile = sys.argv[1] elif exists(join(setupdir, "setup.py")): configfile = join(setupdir, "dev.cfg") elif exists(join(curdir, "prod.cfg")): configfile = join(curdir, "prod.cfg") else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("tgpisa"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile=configfile, modulename="tgpisa.config") from tgpisa.controllers import Root turbogears.start_server(Root())
python
def start(): """Start the CherryPy application server.""" setupdir = dirname(dirname(__file__)) curdir = os.getcwd() # First look on the command line for a desired config file, # if it's not on the command line, then look for 'setup.py' # in the current directory. If there, load configuration # from a file called 'dev.cfg'. If it's not there, the project # is probably installed and we'll look first for a file called # 'prod.cfg' in the current directory and then for a default # config file called 'default.cfg' packaged in the egg. if len(sys.argv) > 1: configfile = sys.argv[1] elif exists(join(setupdir, "setup.py")): configfile = join(setupdir, "dev.cfg") elif exists(join(curdir, "prod.cfg")): configfile = join(curdir, "prod.cfg") else: try: configfile = pkg_resources.resource_filename( pkg_resources.Requirement.parse("tgpisa"), "config/default.cfg") except pkg_resources.DistributionNotFound: raise ConfigurationError("Could not find default configuration.") turbogears.update_config(configfile=configfile, modulename="tgpisa.config") from tgpisa.controllers import Root turbogears.start_server(Root())
[ "def", "start", "(", ")", ":", "setupdir", "=", "dirname", "(", "dirname", "(", "__file__", ")", ")", "curdir", "=", "os", ".", "getcwd", "(", ")", "# First look on the command line for a desired config file,", "# if it's not on the command line, then look for 'setup.py'", "# in the current directory. If there, load configuration", "# from a file called 'dev.cfg'. If it's not there, the project", "# is probably installed and we'll look first for a file called", "# 'prod.cfg' in the current directory and then for a default", "# config file called 'default.cfg' packaged in the egg.", "if", "len", "(", "sys", ".", "argv", ")", ">", "1", ":", "configfile", "=", "sys", ".", "argv", "[", "1", "]", "elif", "exists", "(", "join", "(", "setupdir", ",", "\"setup.py\"", ")", ")", ":", "configfile", "=", "join", "(", "setupdir", ",", "\"dev.cfg\"", ")", "elif", "exists", "(", "join", "(", "curdir", ",", "\"prod.cfg\"", ")", ")", ":", "configfile", "=", "join", "(", "curdir", ",", "\"prod.cfg\"", ")", "else", ":", "try", ":", "configfile", "=", "pkg_resources", ".", "resource_filename", "(", "pkg_resources", ".", "Requirement", ".", "parse", "(", "\"tgpisa\"", ")", ",", "\"config/default.cfg\"", ")", "except", "pkg_resources", ".", "DistributionNotFound", ":", "raise", "ConfigurationError", "(", "\"Could not find default configuration.\"", ")", "turbogears", ".", "update_config", "(", "configfile", "=", "configfile", ",", "modulename", "=", "\"tgpisa.config\"", ")", "from", "tgpisa", ".", "controllers", "import", "Root", "turbogears", ".", "start_server", "(", "Root", "(", ")", ")" ]
Start the CherryPy application server.
[ "Start", "the", "CherryPy", "application", "server", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/demo/tgpisa/tgpisa/commands.py#L20-L52
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/w3c/css.py
CSSRuleset.mergeStyles
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
python
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
[ "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
[ "XXX", "Bugfix", "for", "use", "in", "PISA" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/css.py#L697-L704
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/w3c/css.py
CSSBuilder.atPage
def atPage(self, page, pseudopage, declarations): """ This is overriden by xhtml2pdf.context.pisaCSSBuilder """ return self.ruleset([self.selector('*')], declarations)
python
def atPage(self, page, pseudopage, declarations): """ This is overriden by xhtml2pdf.context.pisaCSSBuilder """ return self.ruleset([self.selector('*')], declarations)
[ "def", "atPage", "(", "self", ",", "page", ",", "pseudopage", ",", "declarations", ")", ":", "return", "self", ".", "ruleset", "(", "[", "self", ".", "selector", "(", "'*'", ")", "]", ",", "declarations", ")" ]
This is overriden by xhtml2pdf.context.pisaCSSBuilder
[ "This", "is", "overriden", "by", "xhtml2pdf", ".", "context", ".", "pisaCSSBuilder" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/w3c/css.py#L905-L909
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/xhtml2pdf_reportlab.py
PmlBaseDoc.handle_nextPageTemplate
def handle_nextPageTemplate(self, pt): ''' if pt has also templates for even and odd page convert it to list ''' has_left_template = self._has_template_for_name(pt + '_left') has_right_template = self._has_template_for_name(pt + '_right') if has_left_template and has_right_template: pt = [pt + '_left', pt + '_right'] '''On endPage change to the page template with name or index pt''' if isinstance(pt, str): if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle for t in self.pageTemplates: if t.id == pt: self._nextPageTemplateIndex = self.pageTemplates.index(t) return raise ValueError("can't find template('%s')" % pt) elif isinstance(pt, int): if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle self._nextPageTemplateIndex = pt elif isinstance(pt, (list, tuple)): #used for alternating left/right pages #collect the refs to the template objects, complain if any are bad c = PTCycle() for ptn in pt: #special case name used to short circuit the iteration if ptn == '*': c._restart = len(c) continue for t in self.pageTemplates: if t.id == ptn.strip(): c.append(t) break if not c: raise ValueError("No valid page templates in cycle") elif c._restart > len(c): raise ValueError("Invalid cycle restart position") #ensure we start on the first one$ self._nextPageTemplateCycle = c.cyclicIterator() else: raise TypeError("Argument pt should be string or integer or list")
python
def handle_nextPageTemplate(self, pt): ''' if pt has also templates for even and odd page convert it to list ''' has_left_template = self._has_template_for_name(pt + '_left') has_right_template = self._has_template_for_name(pt + '_right') if has_left_template and has_right_template: pt = [pt + '_left', pt + '_right'] '''On endPage change to the page template with name or index pt''' if isinstance(pt, str): if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle for t in self.pageTemplates: if t.id == pt: self._nextPageTemplateIndex = self.pageTemplates.index(t) return raise ValueError("can't find template('%s')" % pt) elif isinstance(pt, int): if hasattr(self, '_nextPageTemplateCycle'): del self._nextPageTemplateCycle self._nextPageTemplateIndex = pt elif isinstance(pt, (list, tuple)): #used for alternating left/right pages #collect the refs to the template objects, complain if any are bad c = PTCycle() for ptn in pt: #special case name used to short circuit the iteration if ptn == '*': c._restart = len(c) continue for t in self.pageTemplates: if t.id == ptn.strip(): c.append(t) break if not c: raise ValueError("No valid page templates in cycle") elif c._restart > len(c): raise ValueError("Invalid cycle restart position") #ensure we start on the first one$ self._nextPageTemplateCycle = c.cyclicIterator() else: raise TypeError("Argument pt should be string or integer or list")
[ "def", "handle_nextPageTemplate", "(", "self", ",", "pt", ")", ":", "has_left_template", "=", "self", ".", "_has_template_for_name", "(", "pt", "+", "'_left'", ")", "has_right_template", "=", "self", ".", "_has_template_for_name", "(", "pt", "+", "'_right'", ")", "if", "has_left_template", "and", "has_right_template", ":", "pt", "=", "[", "pt", "+", "'_left'", ",", "pt", "+", "'_right'", "]", "'''On endPage change to the page template with name or index pt'''", "if", "isinstance", "(", "pt", ",", "str", ")", ":", "if", "hasattr", "(", "self", ",", "'_nextPageTemplateCycle'", ")", ":", "del", "self", ".", "_nextPageTemplateCycle", "for", "t", "in", "self", ".", "pageTemplates", ":", "if", "t", ".", "id", "==", "pt", ":", "self", ".", "_nextPageTemplateIndex", "=", "self", ".", "pageTemplates", ".", "index", "(", "t", ")", "return", "raise", "ValueError", "(", "\"can't find template('%s')\"", "%", "pt", ")", "elif", "isinstance", "(", "pt", ",", "int", ")", ":", "if", "hasattr", "(", "self", ",", "'_nextPageTemplateCycle'", ")", ":", "del", "self", ".", "_nextPageTemplateCycle", "self", ".", "_nextPageTemplateIndex", "=", "pt", "elif", "isinstance", "(", "pt", ",", "(", "list", ",", "tuple", ")", ")", ":", "#used for alternating left/right pages", "#collect the refs to the template objects, complain if any are bad", "c", "=", "PTCycle", "(", ")", "for", "ptn", "in", "pt", ":", "#special case name used to short circuit the iteration", "if", "ptn", "==", "'*'", ":", "c", ".", "_restart", "=", "len", "(", "c", ")", "continue", "for", "t", "in", "self", ".", "pageTemplates", ":", "if", "t", ".", "id", "==", "ptn", ".", "strip", "(", ")", ":", "c", ".", "append", "(", "t", ")", "break", "if", "not", "c", ":", "raise", "ValueError", "(", "\"No valid page templates in cycle\"", ")", "elif", "c", ".", "_restart", ">", "len", "(", "c", ")", ":", "raise", "ValueError", "(", "\"Invalid cycle restart position\"", ")", "#ensure we start on the first one$", "self", ".", "_nextPageTemplateCycle", "=", "c", ".", "cyclicIterator", "(", ")", "else", ":", "raise", "TypeError", "(", "\"Argument pt should be string or integer or list\"", ")" ]
if pt has also templates for even and odd page convert it to list
[ "if", "pt", "has", "also", "templates", "for", "even", "and", "odd", "page", "convert", "it", "to", "list" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/xhtml2pdf_reportlab.py#L125-L169
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/xhtml2pdf_reportlab.py
PmlImageReader.getRGBData
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 # TODO: Move to top. from java.awt.image import PixelGrabber width, height = self.getSize() buffer = jarray.zeros(width * height, 'i') pg = PixelGrabber(self._image, 0, 0, width, height, buffer, 0, width) pg.grabPixels() # there must be a way to do this with a cast not a byte-level loop, # I just haven't found it yet... pixels = [] a = pixels.append for rgb in buffer: a(chr((rgb >> 16) & 0xff)) a(chr((rgb >> 8) & 0xff)) a(chr(rgb & 0xff)) self._data = ''.join(pixels) self.mode = 'RGB' else: im = self._image mode = self.mode = im.mode if mode == 'RGBA': im.load() self._dataA = PmlImageReader(im.split()[3]) im = im.convert('RGB') self.mode = 'RGB' elif mode not in ('L', 'RGB', 'CMYK'): im = im.convert('RGB') self.mode = 'RGB' if hasattr(im, 'tobytes'): self._data = im.tobytes() else: # PIL compatibility self._data = im.tostring() return self._data
python
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 # TODO: Move to top. from java.awt.image import PixelGrabber width, height = self.getSize() buffer = jarray.zeros(width * height, 'i') pg = PixelGrabber(self._image, 0, 0, width, height, buffer, 0, width) pg.grabPixels() # there must be a way to do this with a cast not a byte-level loop, # I just haven't found it yet... pixels = [] a = pixels.append for rgb in buffer: a(chr((rgb >> 16) & 0xff)) a(chr((rgb >> 8) & 0xff)) a(chr(rgb & 0xff)) self._data = ''.join(pixels) self.mode = 'RGB' else: im = self._image mode = self.mode = im.mode if mode == 'RGBA': im.load() self._dataA = PmlImageReader(im.split()[3]) im = im.convert('RGB') self.mode = 'RGB' elif mode not in ('L', 'RGB', 'CMYK'): im = im.convert('RGB') self.mode = 'RGB' if hasattr(im, 'tobytes'): self._data = im.tobytes() else: # PIL compatibility self._data = im.tostring() return self._data
[ "def", "getRGBData", "(", "self", ")", ":", "if", "self", ".", "_data", "is", "None", ":", "self", ".", "_dataA", "=", "None", "if", "sys", ".", "platform", "[", "0", ":", "4", "]", "==", "'java'", ":", "import", "jarray", "# TODO: Move to top.", "from", "java", ".", "awt", ".", "image", "import", "PixelGrabber", "width", ",", "height", "=", "self", ".", "getSize", "(", ")", "buffer", "=", "jarray", ".", "zeros", "(", "width", "*", "height", ",", "'i'", ")", "pg", "=", "PixelGrabber", "(", "self", ".", "_image", ",", "0", ",", "0", ",", "width", ",", "height", ",", "buffer", ",", "0", ",", "width", ")", "pg", ".", "grabPixels", "(", ")", "# there must be a way to do this with a cast not a byte-level loop,", "# I just haven't found it yet...", "pixels", "=", "[", "]", "a", "=", "pixels", ".", "append", "for", "rgb", "in", "buffer", ":", "a", "(", "chr", "(", "(", "rgb", ">>", "16", ")", "&", "0xff", ")", ")", "a", "(", "chr", "(", "(", "rgb", ">>", "8", ")", "&", "0xff", ")", ")", "a", "(", "chr", "(", "rgb", "&", "0xff", ")", ")", "self", ".", "_data", "=", "''", ".", "join", "(", "pixels", ")", "self", ".", "mode", "=", "'RGB'", "else", ":", "im", "=", "self", ".", "_image", "mode", "=", "self", ".", "mode", "=", "im", ".", "mode", "if", "mode", "==", "'RGBA'", ":", "im", ".", "load", "(", ")", "self", ".", "_dataA", "=", "PmlImageReader", "(", "im", ".", "split", "(", ")", "[", "3", "]", ")", "im", "=", "im", ".", "convert", "(", "'RGB'", ")", "self", ".", "mode", "=", "'RGB'", "elif", "mode", "not", "in", "(", "'L'", ",", "'RGB'", ",", "'CMYK'", ")", ":", "im", "=", "im", ".", "convert", "(", "'RGB'", ")", "self", ".", "mode", "=", "'RGB'", "if", "hasattr", "(", "im", ",", "'tobytes'", ")", ":", "self", ".", "_data", "=", "im", ".", "tobytes", "(", ")", "else", ":", "# PIL compatibility", "self", ".", "_data", "=", "im", ".", "tostring", "(", ")", "return", "self", ".", "_data" ]
Return byte array of RGB data as string
[ "Return", "byte", "array", "of", "RGB", "data", "as", "string" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/xhtml2pdf_reportlab.py#L396-L434
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/xhtml2pdf_reportlab.py
PmlImage.wrap
def wrap(self, availWidth, availHeight): " This can be called more than once! Do not overwrite important data like drawWidth " availHeight = self.setMaxHeight(availHeight) # print "image wrap", id(self), availWidth, availHeight, self.drawWidth, self.drawHeight width = min(self.drawWidth, availWidth) wfactor = float(width) / self.drawWidth height = min(self.drawHeight, availHeight * MAX_IMAGE_RATIO) hfactor = float(height) / self.drawHeight factor = min(wfactor, hfactor) self.dWidth = self.drawWidth * factor self.dHeight = self.drawHeight * factor # print "imgage result", factor, self.dWidth, self.dHeight return self.dWidth, self.dHeight
python
def wrap(self, availWidth, availHeight): " This can be called more than once! Do not overwrite important data like drawWidth " availHeight = self.setMaxHeight(availHeight) # print "image wrap", id(self), availWidth, availHeight, self.drawWidth, self.drawHeight width = min(self.drawWidth, availWidth) wfactor = float(width) / self.drawWidth height = min(self.drawHeight, availHeight * MAX_IMAGE_RATIO) hfactor = float(height) / self.drawHeight factor = min(wfactor, hfactor) self.dWidth = self.drawWidth * factor self.dHeight = self.drawHeight * factor # print "imgage result", factor, self.dWidth, self.dHeight return self.dWidth, self.dHeight
[ "def", "wrap", "(", "self", ",", "availWidth", ",", "availHeight", ")", ":", "availHeight", "=", "self", ".", "setMaxHeight", "(", "availHeight", ")", "# print \"image wrap\", id(self), availWidth, availHeight, self.drawWidth, self.drawHeight", "width", "=", "min", "(", "self", ".", "drawWidth", ",", "availWidth", ")", "wfactor", "=", "float", "(", "width", ")", "/", "self", ".", "drawWidth", "height", "=", "min", "(", "self", ".", "drawHeight", ",", "availHeight", "*", "MAX_IMAGE_RATIO", ")", "hfactor", "=", "float", "(", "height", ")", "/", "self", ".", "drawHeight", "factor", "=", "min", "(", "wfactor", ",", "hfactor", ")", "self", ".", "dWidth", "=", "self", ".", "drawWidth", "*", "factor", "self", ".", "dHeight", "=", "self", ".", "drawHeight", "*", "factor", "# print \"imgage result\", factor, self.dWidth, self.dHeight", "return", "self", ".", "dWidth", ",", "self", ".", "dHeight" ]
This can be called more than once! Do not overwrite important data like drawWidth
[ "This", "can", "be", "called", "more", "than", "once!", "Do", "not", "overwrite", "important", "data", "like", "drawWidth" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/xhtml2pdf_reportlab.py#L490-L502
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/xhtml2pdf_reportlab.py
PmlTable._normWidth
def _normWidth(self, w, maxw): """ Helper for calculating percentages """ if type(w) == type(""): w = ((maxw / 100.0) * float(w[: - 1])) elif (w is None) or (w == "*"): w = maxw return min(w, maxw)
python
def _normWidth(self, w, maxw): """ Helper for calculating percentages """ if type(w) == type(""): w = ((maxw / 100.0) * float(w[: - 1])) elif (w is None) or (w == "*"): w = maxw return min(w, maxw)
[ "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
[ "Helper", "for", "calculating", "percentages" ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/xhtml2pdf_reportlab.py#L707-L715
train
xhtml2pdf/xhtml2pdf
xhtml2pdf/xhtml2pdf_reportlab.py
PmlTableOfContents.wrap
def wrap(self, availWidth, availHeight): """ All table properties should be known by now. """ widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth) # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len(self._lastEntries) == 0: _tempEntries = [(0, 'Placeholder for table of contents', 0)] else: _tempEntries = self._lastEntries lastMargin = 0 tableData = [] tableStyle = [ ('VALIGN', (0, 0), (- 1, - 1), 'TOP'), ('LEFTPADDING', (0, 0), (- 1, - 1), 0), ('RIGHTPADDING', (0, 0), (- 1, - 1), 0), ('TOPPADDING', (0, 0), (- 1, - 1), 0), ('BOTTOMPADDING', (0, 0), (- 1, - 1), 0), ] for i, entry in enumerate(_tempEntries): level, text, pageNum = entry[:3] leftColStyle = self.levelStyles[level] if i: # Not for first element tableStyle.append(( 'TOPPADDING', (0, i), (- 1, i), max(lastMargin, leftColStyle.spaceBefore))) # print leftColStyle.leftIndent lastMargin = leftColStyle.spaceAfter #right col style is right aligned rightColStyle = ParagraphStyle(name='leftColLevel%d' % level, parent=leftColStyle, leftIndent=0, alignment=TA_RIGHT) leftPara = Paragraph(text, leftColStyle) rightPara = Paragraph(str(pageNum), rightColStyle) tableData.append([leftPara, rightPara]) self._table = Table( tableData, colWidths=widths, style=TableStyle(tableStyle)) self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight) return self.width, self.height
python
def wrap(self, availWidth, availHeight): """ All table properties should be known by now. """ widths = (availWidth - self.rightColumnWidth, self.rightColumnWidth) # makes an internal table which does all the work. # we draw the LAST RUN's entries! If there are # none, we make some dummy data to keep the table # from complaining if len(self._lastEntries) == 0: _tempEntries = [(0, 'Placeholder for table of contents', 0)] else: _tempEntries = self._lastEntries lastMargin = 0 tableData = [] tableStyle = [ ('VALIGN', (0, 0), (- 1, - 1), 'TOP'), ('LEFTPADDING', (0, 0), (- 1, - 1), 0), ('RIGHTPADDING', (0, 0), (- 1, - 1), 0), ('TOPPADDING', (0, 0), (- 1, - 1), 0), ('BOTTOMPADDING', (0, 0), (- 1, - 1), 0), ] for i, entry in enumerate(_tempEntries): level, text, pageNum = entry[:3] leftColStyle = self.levelStyles[level] if i: # Not for first element tableStyle.append(( 'TOPPADDING', (0, i), (- 1, i), max(lastMargin, leftColStyle.spaceBefore))) # print leftColStyle.leftIndent lastMargin = leftColStyle.spaceAfter #right col style is right aligned rightColStyle = ParagraphStyle(name='leftColLevel%d' % level, parent=leftColStyle, leftIndent=0, alignment=TA_RIGHT) leftPara = Paragraph(text, leftColStyle) rightPara = Paragraph(str(pageNum), rightColStyle) tableData.append([leftPara, rightPara]) self._table = Table( tableData, colWidths=widths, style=TableStyle(tableStyle)) self.width, self.height = self._table.wrapOn(self.canv, availWidth, availHeight) return self.width, self.height
[ "def", "wrap", "(", "self", ",", "availWidth", ",", "availHeight", ")", ":", "widths", "=", "(", "availWidth", "-", "self", ".", "rightColumnWidth", ",", "self", ".", "rightColumnWidth", ")", "# makes an internal table which does all the work.", "# we draw the LAST RUN's entries! If there are", "# none, we make some dummy data to keep the table", "# from complaining", "if", "len", "(", "self", ".", "_lastEntries", ")", "==", "0", ":", "_tempEntries", "=", "[", "(", "0", ",", "'Placeholder for table of contents'", ",", "0", ")", "]", "else", ":", "_tempEntries", "=", "self", ".", "_lastEntries", "lastMargin", "=", "0", "tableData", "=", "[", "]", "tableStyle", "=", "[", "(", "'VALIGN'", ",", "(", "0", ",", "0", ")", ",", "(", "-", "1", ",", "-", "1", ")", ",", "'TOP'", ")", ",", "(", "'LEFTPADDING'", ",", "(", "0", ",", "0", ")", ",", "(", "-", "1", ",", "-", "1", ")", ",", "0", ")", ",", "(", "'RIGHTPADDING'", ",", "(", "0", ",", "0", ")", ",", "(", "-", "1", ",", "-", "1", ")", ",", "0", ")", ",", "(", "'TOPPADDING'", ",", "(", "0", ",", "0", ")", ",", "(", "-", "1", ",", "-", "1", ")", ",", "0", ")", ",", "(", "'BOTTOMPADDING'", ",", "(", "0", ",", "0", ")", ",", "(", "-", "1", ",", "-", "1", ")", ",", "0", ")", ",", "]", "for", "i", ",", "entry", "in", "enumerate", "(", "_tempEntries", ")", ":", "level", ",", "text", ",", "pageNum", "=", "entry", "[", ":", "3", "]", "leftColStyle", "=", "self", ".", "levelStyles", "[", "level", "]", "if", "i", ":", "# Not for first element", "tableStyle", ".", "append", "(", "(", "'TOPPADDING'", ",", "(", "0", ",", "i", ")", ",", "(", "-", "1", ",", "i", ")", ",", "max", "(", "lastMargin", ",", "leftColStyle", ".", "spaceBefore", ")", ")", ")", "# print leftColStyle.leftIndent", "lastMargin", "=", "leftColStyle", ".", "spaceAfter", "#right col style is right aligned", "rightColStyle", "=", "ParagraphStyle", "(", "name", "=", "'leftColLevel%d'", "%", "level", ",", "parent", "=", "leftColStyle", ",", "leftIndent", "=", "0", ",", "alignment", "=", "TA_RIGHT", ")", "leftPara", "=", "Paragraph", "(", "text", ",", "leftColStyle", ")", "rightPara", "=", "Paragraph", "(", "str", "(", "pageNum", ")", ",", "rightColStyle", ")", "tableData", ".", "append", "(", "[", "leftPara", ",", "rightPara", "]", ")", "self", ".", "_table", "=", "Table", "(", "tableData", ",", "colWidths", "=", "widths", ",", "style", "=", "TableStyle", "(", "tableStyle", ")", ")", "self", ".", "width", ",", "self", ".", "height", "=", "self", ".", "_table", ".", "wrapOn", "(", "self", ".", "canv", ",", "availWidth", ",", "availHeight", ")", "return", "self", ".", "width", ",", "self", ".", "height" ]
All table properties should be known by now.
[ "All", "table", "properties", "should", "be", "known", "by", "now", "." ]
230357a392f48816532d3c2fa082a680b80ece48
https://github.com/xhtml2pdf/xhtml2pdf/blob/230357a392f48816532d3c2fa082a680b80ece48/xhtml2pdf/xhtml2pdf_reportlab.py#L788-L839
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession._spawn_child
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): """spawn a child, and manage the delaybefore send setting to 0 """ shutit = self.shutit args = args or [] pexpect_child = pexpect.spawn(command, args=args, timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize, env=env, ignore_sighup=ignore_sighup, echo=echo, preexec_fn=preexec_fn, encoding=encoding, codec_errors=codec_errors, dimensions=dimensions) # Set the winsize to the theoretical maximum to reduce risk of trouble from terminal line wraps. # Other things have been attempted, eg tput rmam/smam without success. pexpect_child.setwinsize(shutit_global.shutit_global_object.pexpect_window_size[0],shutit_global.shutit_global_object.pexpect_window_size[1]) pexpect_child.delaybeforesend=delaybeforesend shutit.log('sessions before: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG) shutit.shutit_pexpect_sessions.update({self.pexpect_session_id:self}) shutit.log('sessions after: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG) return pexpect_child
python
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): """spawn a child, and manage the delaybefore send setting to 0 """ shutit = self.shutit args = args or [] pexpect_child = pexpect.spawn(command, args=args, timeout=timeout, maxread=maxread, searchwindowsize=searchwindowsize, env=env, ignore_sighup=ignore_sighup, echo=echo, preexec_fn=preexec_fn, encoding=encoding, codec_errors=codec_errors, dimensions=dimensions) # Set the winsize to the theoretical maximum to reduce risk of trouble from terminal line wraps. # Other things have been attempted, eg tput rmam/smam without success. pexpect_child.setwinsize(shutit_global.shutit_global_object.pexpect_window_size[0],shutit_global.shutit_global_object.pexpect_window_size[1]) pexpect_child.delaybeforesend=delaybeforesend shutit.log('sessions before: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG) shutit.shutit_pexpect_sessions.update({self.pexpect_session_id:self}) shutit.log('sessions after: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG) return pexpect_child
[ "def", "_spawn_child", "(", "self", ",", "command", ",", "args", "=", "None", ",", "timeout", "=", "shutit_global", ".", "shutit_global_object", ".", "default_timeout", ",", "maxread", "=", "2000", ",", "searchwindowsize", "=", "None", ",", "env", "=", "None", ",", "ignore_sighup", "=", "False", ",", "echo", "=", "True", ",", "preexec_fn", "=", "None", ",", "encoding", "=", "None", ",", "codec_errors", "=", "'strict'", ",", "dimensions", "=", "None", ",", "delaybeforesend", "=", "shutit_global", ".", "shutit_global_object", ".", "delaybeforesend", ")", ":", "shutit", "=", "self", ".", "shutit", "args", "=", "args", "or", "[", "]", "pexpect_child", "=", "pexpect", ".", "spawn", "(", "command", ",", "args", "=", "args", ",", "timeout", "=", "timeout", ",", "maxread", "=", "maxread", ",", "searchwindowsize", "=", "searchwindowsize", ",", "env", "=", "env", ",", "ignore_sighup", "=", "ignore_sighup", ",", "echo", "=", "echo", ",", "preexec_fn", "=", "preexec_fn", ",", "encoding", "=", "encoding", ",", "codec_errors", "=", "codec_errors", ",", "dimensions", "=", "dimensions", ")", "# Set the winsize to the theoretical maximum to reduce risk of trouble from terminal line wraps.", "# Other things have been attempted, eg tput rmam/smam without success.", "pexpect_child", ".", "setwinsize", "(", "shutit_global", ".", "shutit_global_object", ".", "pexpect_window_size", "[", "0", "]", ",", "shutit_global", ".", "shutit_global_object", ".", "pexpect_window_size", "[", "1", "]", ")", "pexpect_child", ".", "delaybeforesend", "=", "delaybeforesend", "shutit", ".", "log", "(", "'sessions before: '", "+", "str", "(", "shutit", ".", "shutit_pexpect_sessions", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "shutit", ".", "shutit_pexpect_sessions", ".", "update", "(", "{", "self", ".", "pexpect_session_id", ":", "self", "}", ")", "shutit", ".", "log", "(", "'sessions after: '", "+", "str", "(", "shutit", ".", "shutit_pexpect_sessions", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "pexpect_child" ]
spawn a child, and manage the delaybefore send setting to 0
[ "spawn", "a", "child", "and", "manage", "the", "delaybefore", "send", "setting", "to", "0" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L149-L186
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.sendline
def sendline(self, sendspec): """Sends line, handling background and newline directives. True means: 'all handled here ok' False means: you'll need to 'expect' the right thing from here. """ assert not sendspec.started, shutit_util.print_debug() shutit = self.shutit shutit.log('Sending in pexpect session (' + str(id(self)) + '): ' + str(sendspec.send), level=logging.DEBUG) if sendspec.expect: shutit.log('Expecting: ' + str(sendspec.expect), level=logging.DEBUG) else: shutit.log('Not expecting anything', level=logging.DEBUG) try: # Check there are no background commands running that have block_other_commands set iff # this sendspec says if self._check_blocked(sendspec) and sendspec.ignore_background != True: shutit.log('sendline: blocked', level=logging.DEBUG) return False # If this is marked as in the background, create a background object and run in the background. if sendspec.run_in_background: shutit.log('sendline: run_in_background', level=logging.DEBUG) # If this is marked as in the background, create a background object and run in the background after newlines sorted. shutit_background_command_object = self.login_stack.get_current_login_item().append_background_send(sendspec) # Makes no sense to check exit for a background command. sendspec.check_exit = False if sendspec.nonewline != True: sendspec.send += '\n' # sendspec has newline added now, so no need to keep marker sendspec.nonewline = True if sendspec.run_in_background: shutit_background_command_object.run_background_command() return True #shutit.log('sendline: actually sending: ' + sendspec.send, level=logging.DEBUG) self.pexpect_child.send(sendspec.send) return False except OSError: self.shutit.fail('Caught failure to send, assuming user has exited from pause point.')
python
def sendline(self, sendspec): """Sends line, handling background and newline directives. True means: 'all handled here ok' False means: you'll need to 'expect' the right thing from here. """ assert not sendspec.started, shutit_util.print_debug() shutit = self.shutit shutit.log('Sending in pexpect session (' + str(id(self)) + '): ' + str(sendspec.send), level=logging.DEBUG) if sendspec.expect: shutit.log('Expecting: ' + str(sendspec.expect), level=logging.DEBUG) else: shutit.log('Not expecting anything', level=logging.DEBUG) try: # Check there are no background commands running that have block_other_commands set iff # this sendspec says if self._check_blocked(sendspec) and sendspec.ignore_background != True: shutit.log('sendline: blocked', level=logging.DEBUG) return False # If this is marked as in the background, create a background object and run in the background. if sendspec.run_in_background: shutit.log('sendline: run_in_background', level=logging.DEBUG) # If this is marked as in the background, create a background object and run in the background after newlines sorted. shutit_background_command_object = self.login_stack.get_current_login_item().append_background_send(sendspec) # Makes no sense to check exit for a background command. sendspec.check_exit = False if sendspec.nonewline != True: sendspec.send += '\n' # sendspec has newline added now, so no need to keep marker sendspec.nonewline = True if sendspec.run_in_background: shutit_background_command_object.run_background_command() return True #shutit.log('sendline: actually sending: ' + sendspec.send, level=logging.DEBUG) self.pexpect_child.send(sendspec.send) return False except OSError: self.shutit.fail('Caught failure to send, assuming user has exited from pause point.')
[ "def", "sendline", "(", "self", ",", "sendspec", ")", ":", "assert", "not", "sendspec", ".", "started", ",", "shutit_util", ".", "print_debug", "(", ")", "shutit", "=", "self", ".", "shutit", "shutit", ".", "log", "(", "'Sending in pexpect session ('", "+", "str", "(", "id", "(", "self", ")", ")", "+", "'): '", "+", "str", "(", "sendspec", ".", "send", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "sendspec", ".", "expect", ":", "shutit", ".", "log", "(", "'Expecting: '", "+", "str", "(", "sendspec", ".", "expect", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "else", ":", "shutit", ".", "log", "(", "'Not expecting anything'", ",", "level", "=", "logging", ".", "DEBUG", ")", "try", ":", "# Check there are no background commands running that have block_other_commands set iff", "# this sendspec says", "if", "self", ".", "_check_blocked", "(", "sendspec", ")", "and", "sendspec", ".", "ignore_background", "!=", "True", ":", "shutit", ".", "log", "(", "'sendline: blocked'", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "False", "# If this is marked as in the background, create a background object and run in the background.", "if", "sendspec", ".", "run_in_background", ":", "shutit", ".", "log", "(", "'sendline: run_in_background'", ",", "level", "=", "logging", ".", "DEBUG", ")", "# If this is marked as in the background, create a background object and run in the background after newlines sorted.", "shutit_background_command_object", "=", "self", ".", "login_stack", ".", "get_current_login_item", "(", ")", ".", "append_background_send", "(", "sendspec", ")", "# Makes no sense to check exit for a background command.", "sendspec", ".", "check_exit", "=", "False", "if", "sendspec", ".", "nonewline", "!=", "True", ":", "sendspec", ".", "send", "+=", "'\\n'", "# sendspec has newline added now, so no need to keep marker", "sendspec", ".", "nonewline", "=", "True", "if", "sendspec", ".", "run_in_background", ":", "shutit_background_command_object", ".", "run_background_command", "(", ")", "return", "True", "#shutit.log('sendline: actually sending: ' + sendspec.send, level=logging.DEBUG)", "self", ".", "pexpect_child", ".", "send", "(", "sendspec", ".", "send", ")", "return", "False", "except", "OSError", ":", "self", ".", "shutit", ".", "fail", "(", "'Caught failure to send, assuming user has exited from pause point.'", ")" ]
Sends line, handling background and newline directives. True means: 'all handled here ok' False means: you'll need to 'expect' the right thing from here.
[ "Sends", "line", "handling", "background", "and", "newline", "directives", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L189-L226
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.wait
def wait(self, cadence=2, sendspec=None): """Does not return until all background commands are completed. """ shutit = self.shutit shutit.log('In wait.', level=logging.DEBUG) if sendspec: cadence = sendspec.wait_cadence shutit.log('Login stack is:\n' + str(self.login_stack), level=logging.DEBUG) while True: # go through each background child checking whether they've finished res, res_str, background_object = self.login_stack.get_current_login_item().check_background_commands_complete() shutit.log('Checking: ' + str(background_object) + '\nres: ' + str(res) + '\nres_str' + str(res_str), level=logging.DEBUG) if res: # When all have completed, break return the background command objects. break elif res_str in ('S','N'): # Do nothing, this is an started or not-running task. pass elif res_str == 'F': assert background_object is not None, shutit_util.print_debug() assert isinstance(background_object, ShutItBackgroundCommand), shutit_util.print_debug() shutit.log('Failure in: ' + str(self.login_stack), level=logging.DEBUG) self.pause_point('Background task: ' + background_object.sendspec.original_send + ' :failed.') return False else: self.shutit.fail('Un-handled exit code: ' + res_str) # pragma: no cover time.sleep(cadence) shutit.log('Wait complete.', level=logging.DEBUG) return True
python
def wait(self, cadence=2, sendspec=None): """Does not return until all background commands are completed. """ shutit = self.shutit shutit.log('In wait.', level=logging.DEBUG) if sendspec: cadence = sendspec.wait_cadence shutit.log('Login stack is:\n' + str(self.login_stack), level=logging.DEBUG) while True: # go through each background child checking whether they've finished res, res_str, background_object = self.login_stack.get_current_login_item().check_background_commands_complete() shutit.log('Checking: ' + str(background_object) + '\nres: ' + str(res) + '\nres_str' + str(res_str), level=logging.DEBUG) if res: # When all have completed, break return the background command objects. break elif res_str in ('S','N'): # Do nothing, this is an started or not-running task. pass elif res_str == 'F': assert background_object is not None, shutit_util.print_debug() assert isinstance(background_object, ShutItBackgroundCommand), shutit_util.print_debug() shutit.log('Failure in: ' + str(self.login_stack), level=logging.DEBUG) self.pause_point('Background task: ' + background_object.sendspec.original_send + ' :failed.') return False else: self.shutit.fail('Un-handled exit code: ' + res_str) # pragma: no cover time.sleep(cadence) shutit.log('Wait complete.', level=logging.DEBUG) return True
[ "def", "wait", "(", "self", ",", "cadence", "=", "2", ",", "sendspec", "=", "None", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "log", "(", "'In wait.'", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "sendspec", ":", "cadence", "=", "sendspec", ".", "wait_cadence", "shutit", ".", "log", "(", "'Login stack is:\\n'", "+", "str", "(", "self", ".", "login_stack", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "while", "True", ":", "# go through each background child checking whether they've finished", "res", ",", "res_str", ",", "background_object", "=", "self", ".", "login_stack", ".", "get_current_login_item", "(", ")", ".", "check_background_commands_complete", "(", ")", "shutit", ".", "log", "(", "'Checking: '", "+", "str", "(", "background_object", ")", "+", "'\\nres: '", "+", "str", "(", "res", ")", "+", "'\\nres_str'", "+", "str", "(", "res_str", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "res", ":", "# When all have completed, break return the background command objects.", "break", "elif", "res_str", "in", "(", "'S'", ",", "'N'", ")", ":", "# Do nothing, this is an started or not-running task.", "pass", "elif", "res_str", "==", "'F'", ":", "assert", "background_object", "is", "not", "None", ",", "shutit_util", ".", "print_debug", "(", ")", "assert", "isinstance", "(", "background_object", ",", "ShutItBackgroundCommand", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "shutit", ".", "log", "(", "'Failure in: '", "+", "str", "(", "self", ".", "login_stack", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "pause_point", "(", "'Background task: '", "+", "background_object", ".", "sendspec", ".", "original_send", "+", "' :failed.'", ")", "return", "False", "else", ":", "self", ".", "shutit", ".", "fail", "(", "'Un-handled exit code: '", "+", "res_str", ")", "# pragma: no cover", "time", ".", "sleep", "(", "cadence", ")", "shutit", ".", "log", "(", "'Wait complete.'", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "True" ]
Does not return until all background commands are completed.
[ "Does", "not", "return", "until", "all", "background", "commands", "are", "completed", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L271-L299
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.expect
def expect(self, expect, searchwindowsize=None, maxread=None, timeout=None, iteration_n=1): """Handle child expects, with EOF and TIMEOUT handled iteration_n - Number of times this expect has been called for the send. If 1, (the default) then it gets added to the pane of output (if applicable to this run) """ if isinstance(expect, str): expect = [expect] if searchwindowsize != None: old_searchwindowsize = self.pexpect_child.searchwindowsize self.pexpect_child.searchwindowsize = searchwindowsize if maxread != None: old_maxread = self.pexpect_child.maxread self.pexpect_child.maxread = maxread res = self.pexpect_child.expect(expect + [pexpect.TIMEOUT] + [pexpect.EOF], timeout=timeout) if searchwindowsize != None: self.pexpect_child.searchwindowsize = old_searchwindowsize if maxread != None: self.pexpect_child.maxread = old_maxread # Add to session lines only if pane manager exists. if shutit_global.shutit_global_object.pane_manager and iteration_n == 1: time_seen = time.time() lines_to_add = [] if isinstance(self.pexpect_child.before, (str,unicode)): for line_str in self.pexpect_child.before.split('\n'): lines_to_add.append(line_str) if isinstance(self.pexpect_child.after, (str,unicode)): for line_str in self.pexpect_child.after.split('\n'): lines_to_add.append(line_str) # If first or last line is empty, remove it. #if len(lines_to_add) > 0 and lines_to_add[1] == '': # lines_to_add = lines_to_add[1:] #if len(lines_to_add) > 0 and lines_to_add[-1] == '': # lines_to_add = lines_to_add[:-1] for line in lines_to_add: self.session_output_lines.append(SessionPaneLine(line_str=line, time_seen=time_seen, line_type='output')) return res
python
def expect(self, expect, searchwindowsize=None, maxread=None, timeout=None, iteration_n=1): """Handle child expects, with EOF and TIMEOUT handled iteration_n - Number of times this expect has been called for the send. If 1, (the default) then it gets added to the pane of output (if applicable to this run) """ if isinstance(expect, str): expect = [expect] if searchwindowsize != None: old_searchwindowsize = self.pexpect_child.searchwindowsize self.pexpect_child.searchwindowsize = searchwindowsize if maxread != None: old_maxread = self.pexpect_child.maxread self.pexpect_child.maxread = maxread res = self.pexpect_child.expect(expect + [pexpect.TIMEOUT] + [pexpect.EOF], timeout=timeout) if searchwindowsize != None: self.pexpect_child.searchwindowsize = old_searchwindowsize if maxread != None: self.pexpect_child.maxread = old_maxread # Add to session lines only if pane manager exists. if shutit_global.shutit_global_object.pane_manager and iteration_n == 1: time_seen = time.time() lines_to_add = [] if isinstance(self.pexpect_child.before, (str,unicode)): for line_str in self.pexpect_child.before.split('\n'): lines_to_add.append(line_str) if isinstance(self.pexpect_child.after, (str,unicode)): for line_str in self.pexpect_child.after.split('\n'): lines_to_add.append(line_str) # If first or last line is empty, remove it. #if len(lines_to_add) > 0 and lines_to_add[1] == '': # lines_to_add = lines_to_add[1:] #if len(lines_to_add) > 0 and lines_to_add[-1] == '': # lines_to_add = lines_to_add[:-1] for line in lines_to_add: self.session_output_lines.append(SessionPaneLine(line_str=line, time_seen=time_seen, line_type='output')) return res
[ "def", "expect", "(", "self", ",", "expect", ",", "searchwindowsize", "=", "None", ",", "maxread", "=", "None", ",", "timeout", "=", "None", ",", "iteration_n", "=", "1", ")", ":", "if", "isinstance", "(", "expect", ",", "str", ")", ":", "expect", "=", "[", "expect", "]", "if", "searchwindowsize", "!=", "None", ":", "old_searchwindowsize", "=", "self", ".", "pexpect_child", ".", "searchwindowsize", "self", ".", "pexpect_child", ".", "searchwindowsize", "=", "searchwindowsize", "if", "maxread", "!=", "None", ":", "old_maxread", "=", "self", ".", "pexpect_child", ".", "maxread", "self", ".", "pexpect_child", ".", "maxread", "=", "maxread", "res", "=", "self", ".", "pexpect_child", ".", "expect", "(", "expect", "+", "[", "pexpect", ".", "TIMEOUT", "]", "+", "[", "pexpect", ".", "EOF", "]", ",", "timeout", "=", "timeout", ")", "if", "searchwindowsize", "!=", "None", ":", "self", ".", "pexpect_child", ".", "searchwindowsize", "=", "old_searchwindowsize", "if", "maxread", "!=", "None", ":", "self", ".", "pexpect_child", ".", "maxread", "=", "old_maxread", "# Add to session lines only if pane manager exists.", "if", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", "and", "iteration_n", "==", "1", ":", "time_seen", "=", "time", ".", "time", "(", ")", "lines_to_add", "=", "[", "]", "if", "isinstance", "(", "self", ".", "pexpect_child", ".", "before", ",", "(", "str", ",", "unicode", ")", ")", ":", "for", "line_str", "in", "self", ".", "pexpect_child", ".", "before", ".", "split", "(", "'\\n'", ")", ":", "lines_to_add", ".", "append", "(", "line_str", ")", "if", "isinstance", "(", "self", ".", "pexpect_child", ".", "after", ",", "(", "str", ",", "unicode", ")", ")", ":", "for", "line_str", "in", "self", ".", "pexpect_child", ".", "after", ".", "split", "(", "'\\n'", ")", ":", "lines_to_add", ".", "append", "(", "line_str", ")", "# If first or last line is empty, remove it.", "#if len(lines_to_add) > 0 and lines_to_add[1] == '':", "#\tlines_to_add = lines_to_add[1:]", "#if len(lines_to_add) > 0 and lines_to_add[-1] == '':", "#\tlines_to_add = lines_to_add[:-1]", "for", "line", "in", "lines_to_add", ":", "self", ".", "session_output_lines", ".", "append", "(", "SessionPaneLine", "(", "line_str", "=", "line", ",", "time_seen", "=", "time_seen", ",", "line_type", "=", "'output'", ")", ")", "return", "res" ]
Handle child expects, with EOF and TIMEOUT handled iteration_n - Number of times this expect has been called for the send. If 1, (the default) then it gets added to the pane of output (if applicable to this run)
[ "Handle", "child", "expects", "with", "EOF", "and", "TIMEOUT", "handled" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L585-L627
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.replace_container
def replace_container(self, new_target_image_name, go_home=None): """Replaces a container. Assumes we are in Docker context. """ shutit = self.shutit shutit.log('Replacing container with ' + new_target_image_name + ', please wait...', level=logging.DEBUG) shutit.log(shutit.print_session_state(), level=logging.DEBUG) # Destroy existing container. conn_module = None for mod in shutit.conn_modules: if mod.module_id == shutit.build['conn_module']: conn_module = mod break if conn_module is None: shutit.fail('''Couldn't find conn_module ''' + shutit.build['conn_module']) # pragma: no cover container_id = shutit.target['container_id'] conn_module.destroy_container(shutit, 'host_child', 'target_child', container_id) # Start up a new container. shutit.target['docker_image'] = new_target_image_name target_child = conn_module.start_container(shutit, self.pexpect_session_id) conn_module.setup_target_child(shutit, target_child) shutit.log('Container replaced', level=logging.DEBUG) shutit.log(shutit.print_session_state(), level=logging.DEBUG) # New session - log in. This makes the assumption that we are nested # the same level in in terms of shells (root shell + 1 new login shell). target_child = shutit.get_shutit_pexpect_session_from_id('target_child') if go_home != None: target_child.login(ShutItSendSpec(self, send=shutit_global.shutit_global_object.bash_startup_command, check_exit=False, echo=False, go_home=go_home)) else: target_child.login(ShutItSendSpec(self, send=shutit_global.shutit_global_object.bash_startup_command, check_exit=False, echo=False)) return True
python
def replace_container(self, new_target_image_name, go_home=None): """Replaces a container. Assumes we are in Docker context. """ shutit = self.shutit shutit.log('Replacing container with ' + new_target_image_name + ', please wait...', level=logging.DEBUG) shutit.log(shutit.print_session_state(), level=logging.DEBUG) # Destroy existing container. conn_module = None for mod in shutit.conn_modules: if mod.module_id == shutit.build['conn_module']: conn_module = mod break if conn_module is None: shutit.fail('''Couldn't find conn_module ''' + shutit.build['conn_module']) # pragma: no cover container_id = shutit.target['container_id'] conn_module.destroy_container(shutit, 'host_child', 'target_child', container_id) # Start up a new container. shutit.target['docker_image'] = new_target_image_name target_child = conn_module.start_container(shutit, self.pexpect_session_id) conn_module.setup_target_child(shutit, target_child) shutit.log('Container replaced', level=logging.DEBUG) shutit.log(shutit.print_session_state(), level=logging.DEBUG) # New session - log in. This makes the assumption that we are nested # the same level in in terms of shells (root shell + 1 new login shell). target_child = shutit.get_shutit_pexpect_session_from_id('target_child') if go_home != None: target_child.login(ShutItSendSpec(self, send=shutit_global.shutit_global_object.bash_startup_command, check_exit=False, echo=False, go_home=go_home)) else: target_child.login(ShutItSendSpec(self, send=shutit_global.shutit_global_object.bash_startup_command, check_exit=False, echo=False)) return True
[ "def", "replace_container", "(", "self", ",", "new_target_image_name", ",", "go_home", "=", "None", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "log", "(", "'Replacing container with '", "+", "new_target_image_name", "+", "', please wait...'", ",", "level", "=", "logging", ".", "DEBUG", ")", "shutit", ".", "log", "(", "shutit", ".", "print_session_state", "(", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "# Destroy existing container.", "conn_module", "=", "None", "for", "mod", "in", "shutit", ".", "conn_modules", ":", "if", "mod", ".", "module_id", "==", "shutit", ".", "build", "[", "'conn_module'", "]", ":", "conn_module", "=", "mod", "break", "if", "conn_module", "is", "None", ":", "shutit", ".", "fail", "(", "'''Couldn't find conn_module '''", "+", "shutit", ".", "build", "[", "'conn_module'", "]", ")", "# pragma: no cover", "container_id", "=", "shutit", ".", "target", "[", "'container_id'", "]", "conn_module", ".", "destroy_container", "(", "shutit", ",", "'host_child'", ",", "'target_child'", ",", "container_id", ")", "# Start up a new container.", "shutit", ".", "target", "[", "'docker_image'", "]", "=", "new_target_image_name", "target_child", "=", "conn_module", ".", "start_container", "(", "shutit", ",", "self", ".", "pexpect_session_id", ")", "conn_module", ".", "setup_target_child", "(", "shutit", ",", "target_child", ")", "shutit", ".", "log", "(", "'Container replaced'", ",", "level", "=", "logging", ".", "DEBUG", ")", "shutit", ".", "log", "(", "shutit", ".", "print_session_state", "(", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "# New session - log in. This makes the assumption that we are nested", "# the same level in in terms of shells (root shell + 1 new login shell).", "target_child", "=", "shutit", ".", "get_shutit_pexpect_session_from_id", "(", "'target_child'", ")", "if", "go_home", "!=", "None", ":", "target_child", ".", "login", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "shutit_global", ".", "shutit_global_object", ".", "bash_startup_command", ",", "check_exit", "=", "False", ",", "echo", "=", "False", ",", "go_home", "=", "go_home", ")", ")", "else", ":", "target_child", ".", "login", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "shutit_global", ".", "shutit_global_object", ".", "bash_startup_command", ",", "check_exit", "=", "False", ",", "echo", "=", "False", ")", ")", "return", "True" ]
Replaces a container. Assumes we are in Docker context.
[ "Replaces", "a", "container", ".", "Assumes", "we", "are", "in", "Docker", "context", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L630-L668
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.whoami
def whoami(self, note=None, loglevel=logging.DEBUG): """Returns the current user by executing "whoami". @param note: See send() @return: the output of "whoami" @rtype: string """ 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
python
def whoami(self, note=None, loglevel=logging.DEBUG): """Returns the current user by executing "whoami". @param note: See send() @return: the output of "whoami" @rtype: string """ 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
[ "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". @param note: See send() @return: the output of "whoami" @rtype: string
[ "Returns", "the", "current", "user", "by", "executing", "whoami", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L671-L691
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.check_last_exit_values
def check_last_exit_values(self, send, check_exit=True, expect=None, exit_values=None, retry=0, retbool=False): """Internal function to check the exit value of the shell. Do not use. """ shutit = self.shutit expect = expect or self.default_expect if not self.check_exit or not check_exit: shutit.log('check_exit configured off, returning', level=logging.DEBUG) return True if exit_values is None: exit_values = ['0'] if isinstance(exit_values, int): exit_values = [str(exit_values)] # Don't use send here (will mess up last_output)! # Space before "echo" here is sic - we don't need this to show up in bash history send_exit_code = ' echo EXIT_CODE:$?' shutit.log('Sending with sendline: ' + str(send_exit_code), level=logging.DEBUG) assert not self.sendline(ShutItSendSpec(self, send=send_exit_code, ignore_background=True)), shutit_util.print_debug() shutit.log('Expecting: ' + str(expect), level=logging.DEBUG) self.expect(expect,timeout=10) shutit.log('before: ' + str(self.pexpect_child.before), level=logging.DEBUG) res = shutit.match_string(str(self.pexpect_child.before), '^EXIT_CODE:([0-9][0-9]?[0-9]?)$') if res not in exit_values or res is None: # pragma: no cover res_str = res or str(res) shutit.log('shutit_pexpect_child.after: ' + str(self.pexpect_child.after), level=logging.DEBUG) shutit.log('Exit value from command: ' + str(send) + ' was:' + res_str, level=logging.DEBUG) msg = ('\nWARNING: command:\n' + send + '\nreturned unaccepted exit code: ' + res_str + '\nIf this is expected, pass in check_exit=False or an exit_values array into the send function call.') shutit.build['report'] += msg if retbool: return False elif retry == 1 and shutit_global.shutit_global_object.interactive >= 1: # This is a failure, so we pass in level=0 shutit.pause_point(msg + '\n\nInteractive, so not retrying.\nPause point on exit_code != 0 (' + res_str + '). CTRL-C to quit', shutit_pexpect_child=self.pexpect_child, level=0) elif retry == 1: shutit.fail('Exit value from command\n' + send + '\nwas:\n' + res_str, throw_exception=False) # pragma: no cover else: return False return True
python
def check_last_exit_values(self, send, check_exit=True, expect=None, exit_values=None, retry=0, retbool=False): """Internal function to check the exit value of the shell. Do not use. """ shutit = self.shutit expect = expect or self.default_expect if not self.check_exit or not check_exit: shutit.log('check_exit configured off, returning', level=logging.DEBUG) return True if exit_values is None: exit_values = ['0'] if isinstance(exit_values, int): exit_values = [str(exit_values)] # Don't use send here (will mess up last_output)! # Space before "echo" here is sic - we don't need this to show up in bash history send_exit_code = ' echo EXIT_CODE:$?' shutit.log('Sending with sendline: ' + str(send_exit_code), level=logging.DEBUG) assert not self.sendline(ShutItSendSpec(self, send=send_exit_code, ignore_background=True)), shutit_util.print_debug() shutit.log('Expecting: ' + str(expect), level=logging.DEBUG) self.expect(expect,timeout=10) shutit.log('before: ' + str(self.pexpect_child.before), level=logging.DEBUG) res = shutit.match_string(str(self.pexpect_child.before), '^EXIT_CODE:([0-9][0-9]?[0-9]?)$') if res not in exit_values or res is None: # pragma: no cover res_str = res or str(res) shutit.log('shutit_pexpect_child.after: ' + str(self.pexpect_child.after), level=logging.DEBUG) shutit.log('Exit value from command: ' + str(send) + ' was:' + res_str, level=logging.DEBUG) msg = ('\nWARNING: command:\n' + send + '\nreturned unaccepted exit code: ' + res_str + '\nIf this is expected, pass in check_exit=False or an exit_values array into the send function call.') shutit.build['report'] += msg if retbool: return False elif retry == 1 and shutit_global.shutit_global_object.interactive >= 1: # This is a failure, so we pass in level=0 shutit.pause_point(msg + '\n\nInteractive, so not retrying.\nPause point on exit_code != 0 (' + res_str + '). CTRL-C to quit', shutit_pexpect_child=self.pexpect_child, level=0) elif retry == 1: shutit.fail('Exit value from command\n' + send + '\nwas:\n' + res_str, throw_exception=False) # pragma: no cover else: return False return True
[ "def", "check_last_exit_values", "(", "self", ",", "send", ",", "check_exit", "=", "True", ",", "expect", "=", "None", ",", "exit_values", "=", "None", ",", "retry", "=", "0", ",", "retbool", "=", "False", ")", ":", "shutit", "=", "self", ".", "shutit", "expect", "=", "expect", "or", "self", ".", "default_expect", "if", "not", "self", ".", "check_exit", "or", "not", "check_exit", ":", "shutit", ".", "log", "(", "'check_exit configured off, returning'", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "True", "if", "exit_values", "is", "None", ":", "exit_values", "=", "[", "'0'", "]", "if", "isinstance", "(", "exit_values", ",", "int", ")", ":", "exit_values", "=", "[", "str", "(", "exit_values", ")", "]", "# Don't use send here (will mess up last_output)!", "# Space before \"echo\" here is sic - we don't need this to show up in bash history", "send_exit_code", "=", "' echo EXIT_CODE:$?'", "shutit", ".", "log", "(", "'Sending with sendline: '", "+", "str", "(", "send_exit_code", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "assert", "not", "self", ".", "sendline", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "send_exit_code", ",", "ignore_background", "=", "True", ")", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "shutit", ".", "log", "(", "'Expecting: '", "+", "str", "(", "expect", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "expect", "(", "expect", ",", "timeout", "=", "10", ")", "shutit", ".", "log", "(", "'before: '", "+", "str", "(", "self", ".", "pexpect_child", ".", "before", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "res", "=", "shutit", ".", "match_string", "(", "str", "(", "self", ".", "pexpect_child", ".", "before", ")", ",", "'^EXIT_CODE:([0-9][0-9]?[0-9]?)$'", ")", "if", "res", "not", "in", "exit_values", "or", "res", "is", "None", ":", "# pragma: no cover", "res_str", "=", "res", "or", "str", "(", "res", ")", "shutit", ".", "log", "(", "'shutit_pexpect_child.after: '", "+", "str", "(", "self", ".", "pexpect_child", ".", "after", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "shutit", ".", "log", "(", "'Exit value from command: '", "+", "str", "(", "send", ")", "+", "' was:'", "+", "res_str", ",", "level", "=", "logging", ".", "DEBUG", ")", "msg", "=", "(", "'\\nWARNING: command:\\n'", "+", "send", "+", "'\\nreturned unaccepted exit code: '", "+", "res_str", "+", "'\\nIf this is expected, pass in check_exit=False or an exit_values array into the send function call.'", ")", "shutit", ".", "build", "[", "'report'", "]", "+=", "msg", "if", "retbool", ":", "return", "False", "elif", "retry", "==", "1", "and", "shutit_global", ".", "shutit_global_object", ".", "interactive", ">=", "1", ":", "# This is a failure, so we pass in level=0", "shutit", ".", "pause_point", "(", "msg", "+", "'\\n\\nInteractive, so not retrying.\\nPause point on exit_code != 0 ('", "+", "res_str", "+", "'). CTRL-C to quit'", ",", "shutit_pexpect_child", "=", "self", ".", "pexpect_child", ",", "level", "=", "0", ")", "elif", "retry", "==", "1", ":", "shutit", ".", "fail", "(", "'Exit value from command\\n'", "+", "send", "+", "'\\nwas:\\n'", "+", "res_str", ",", "throw_exception", "=", "False", ")", "# pragma: no cover", "else", ":", "return", "False", "return", "True" ]
Internal function to check the exit value of the shell. Do not use.
[ "Internal", "function", "to", "check", "the", "exit", "value", "of", "the", "shell", ".", "Do", "not", "use", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L695-L739
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.get_file_perms
def get_file_perms(self, filename, note=None, loglevel=logging.DEBUG): """Returns the permissions of the file on the target as an octal string triplet. @param filename: Filename to get permissions of. @param note: See send() @type filename: string @rtype: string """ 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
python
def get_file_perms(self, filename, note=None, loglevel=logging.DEBUG): """Returns the permissions of the file on the target as an octal string triplet. @param filename: Filename to get permissions of. @param note: See send() @type filename: string @rtype: string """ 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
[ "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. @param filename: Filename to get permissions of. @param note: See send() @type filename: string @rtype: string
[ "Returns", "the", "permissions", "of", "the", "file", "on", "the", "target", "as", "an", "octal", "string", "triplet", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L956-L981
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.is_user_id_available
def is_user_id_available(self, user_id, note=None, loglevel=logging.DEBUG): """Determine whether the specified user_id available. @param user_id: User id to be checked. @param note: See send() @type user_id: integer @rtype: boolean @return: True is the specified user id is not used yet, False if it's already been assigned to a user. """ shutit = self.shutit shutit.handle_note(note) # v the space is intentional, to avoid polluting bash history. self.send(ShutItSendSpec(self, send=' command cut -d: -f3 /etc/paswd | grep -w ^' + user_id + '$ | wc -l', expect=self.default_expect, echo=False, loglevel=loglevel, ignore_background=True)) shutit.handle_note_after(note=note) if shutit.match_string(self.pexpect_child.before, '^([0-9]+)$') == '1': return False return True
python
def is_user_id_available(self, user_id, note=None, loglevel=logging.DEBUG): """Determine whether the specified user_id available. @param user_id: User id to be checked. @param note: See send() @type user_id: integer @rtype: boolean @return: True is the specified user id is not used yet, False if it's already been assigned to a user. """ shutit = self.shutit shutit.handle_note(note) # v the space is intentional, to avoid polluting bash history. self.send(ShutItSendSpec(self, send=' command cut -d: -f3 /etc/paswd | grep -w ^' + user_id + '$ | wc -l', expect=self.default_expect, echo=False, loglevel=loglevel, ignore_background=True)) shutit.handle_note_after(note=note) if shutit.match_string(self.pexpect_child.before, '^([0-9]+)$') == '1': return False return True
[ "def", "is_user_id_available", "(", "self", ",", "user_id", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "handle_note", "(", "note", ")", "# v the space is intentional, to avoid polluting bash history.", "self", ".", "send", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' command cut -d: -f3 /etc/paswd | grep -w ^'", "+", "user_id", "+", "'$ | wc -l'", ",", "expect", "=", "self", ".", "default_expect", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ",", "ignore_background", "=", "True", ")", ")", "shutit", ".", "handle_note_after", "(", "note", "=", "note", ")", "if", "shutit", ".", "match_string", "(", "self", ".", "pexpect_child", ".", "before", ",", "'^([0-9]+)$'", ")", "==", "'1'", ":", "return", "False", "return", "True" ]
Determine whether the specified user_id available. @param user_id: User id to be checked. @param note: See send() @type user_id: integer @rtype: boolean @return: True is the specified user id is not used yet, False if it's already been assigned to a user.
[ "Determine", "whether", "the", "specified", "user_id", "available", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L1011-L1037
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.lsb_release
def lsb_release(self, loglevel=logging.DEBUG): """Get distro information from lsb_release. """ # v the space is intentional, to avoid polluting bash history. shutit = self.shutit d = {} self.send(ShutItSendSpec(self, send=' command lsb_release -a', check_exit=False, echo=False, loglevel=loglevel, ignore_background=True)) res = shutit.match_string(self.pexpect_child.before, r'^Distributor[\s]*ID:[\s]*(.*)$') if isinstance(res, str): dist_string = res d['distro'] = dist_string.lower().strip() try: d['install_type'] = (package_map.INSTALL_TYPE_MAP[dist_string.lower()]) except KeyError: raise Exception("Distribution '%s' is not supported." % dist_string) else: return d res = shutit.match_string(self.pexpect_child.before, r'^Release:[\s*](.*)$') if isinstance(res, str): version_string = res d['distro_version'] = version_string return d
python
def lsb_release(self, loglevel=logging.DEBUG): """Get distro information from lsb_release. """ # v the space is intentional, to avoid polluting bash history. shutit = self.shutit d = {} self.send(ShutItSendSpec(self, send=' command lsb_release -a', check_exit=False, echo=False, loglevel=loglevel, ignore_background=True)) res = shutit.match_string(self.pexpect_child.before, r'^Distributor[\s]*ID:[\s]*(.*)$') if isinstance(res, str): dist_string = res d['distro'] = dist_string.lower().strip() try: d['install_type'] = (package_map.INSTALL_TYPE_MAP[dist_string.lower()]) except KeyError: raise Exception("Distribution '%s' is not supported." % dist_string) else: return d res = shutit.match_string(self.pexpect_child.before, r'^Release:[\s*](.*)$') if isinstance(res, str): version_string = res d['distro_version'] = version_string return d
[ "def", "lsb_release", "(", "self", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "# v the space is intentional, to avoid polluting bash history.", "shutit", "=", "self", ".", "shutit", "d", "=", "{", "}", "self", ".", "send", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' command lsb_release -a'", ",", "check_exit", "=", "False", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ",", "ignore_background", "=", "True", ")", ")", "res", "=", "shutit", ".", "match_string", "(", "self", ".", "pexpect_child", ".", "before", ",", "r'^Distributor[\\s]*ID:[\\s]*(.*)$'", ")", "if", "isinstance", "(", "res", ",", "str", ")", ":", "dist_string", "=", "res", "d", "[", "'distro'", "]", "=", "dist_string", ".", "lower", "(", ")", ".", "strip", "(", ")", "try", ":", "d", "[", "'install_type'", "]", "=", "(", "package_map", ".", "INSTALL_TYPE_MAP", "[", "dist_string", ".", "lower", "(", ")", "]", ")", "except", "KeyError", ":", "raise", "Exception", "(", "\"Distribution '%s' is not supported.\"", "%", "dist_string", ")", "else", ":", "return", "d", "res", "=", "shutit", ".", "match_string", "(", "self", ".", "pexpect_child", ".", "before", ",", "r'^Release:[\\s*](.*)$'", ")", "if", "isinstance", "(", "res", ",", "str", ")", ":", "version_string", "=", "res", "d", "[", "'distro_version'", "]", "=", "version_string", "return", "d" ]
Get distro information from lsb_release.
[ "Get", "distro", "information", "from", "lsb_release", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L1115-L1142
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.user_exists
def user_exists(self, user, note=None, loglevel=logging.DEBUG): """Returns true if the specified username exists. @param user: username to check for @param note: See send() @type user: string @rtype: boolean """ shutit = self.shutit shutit.handle_note(note) exists = False if user == '': return exists # v the space is intentional, to avoid polluting bash history. # The quotes before XIST are deliberate, to prevent the command from matching the expect. ret = self.send(ShutItSendSpec(self, send=' command id %s && echo E""XIST || echo N""XIST' % user, expect=['NXIST', 'EXIST'], echo=False, loglevel=loglevel, ignore_background=True)) if ret: exists = True # sync with the prompt self.expect(self.default_expect) shutit.handle_note_after(note=note) return exists
python
def user_exists(self, user, note=None, loglevel=logging.DEBUG): """Returns true if the specified username exists. @param user: username to check for @param note: See send() @type user: string @rtype: boolean """ shutit = self.shutit shutit.handle_note(note) exists = False if user == '': return exists # v the space is intentional, to avoid polluting bash history. # The quotes before XIST are deliberate, to prevent the command from matching the expect. ret = self.send(ShutItSendSpec(self, send=' command id %s && echo E""XIST || echo N""XIST' % user, expect=['NXIST', 'EXIST'], echo=False, loglevel=loglevel, ignore_background=True)) if ret: exists = True # sync with the prompt self.expect(self.default_expect) shutit.handle_note_after(note=note) return exists
[ "def", "user_exists", "(", "self", ",", "user", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit", "=", "self", ".", "shutit", "shutit", ".", "handle_note", "(", "note", ")", "exists", "=", "False", "if", "user", "==", "''", ":", "return", "exists", "# v the space is intentional, to avoid polluting bash history.", "# The quotes before XIST are deliberate, to prevent the command from matching the expect.", "ret", "=", "self", ".", "send", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' command id %s && echo E\"\"XIST || echo N\"\"XIST'", "%", "user", ",", "expect", "=", "[", "'NXIST'", ",", "'EXIST'", "]", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ",", "ignore_background", "=", "True", ")", ")", "if", "ret", ":", "exists", "=", "True", "# sync with the prompt", "self", ".", "expect", "(", "self", ".", "default_expect", ")", "shutit", ".", "handle_note_after", "(", "note", "=", "note", ")", "return", "exists" ]
Returns true if the specified username exists. @param user: username to check for @param note: See send() @type user: string @rtype: boolean
[ "Returns", "true", "if", "the", "specified", "username", "exists", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L1228-L1259
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession.quick_send
def quick_send(self, send, echo=None, loglevel=logging.INFO): """Quick and dirty send that ignores background tasks. Intended for internal use. """ 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)
python
def quick_send(self, send, echo=None, loglevel=logging.INFO): """Quick and dirty send that ignores background tasks. Intended for internal use. """ 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)
[ "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.
[ "Quick", "and", "dirty", "send", "that", "ignores", "background", "tasks", ".", "Intended", "for", "internal", "use", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L2938-L2951
train
ianmiell/shutit
shutit_pexpect.py
ShutItPexpectSession._create_command_file
def _create_command_file(self, expect, send): """Internal function. Do not use. Takes a long command, and puts it in an executable file ready to run. Returns the filename. """ shutit = self.shutit random_id = shutit_util.random_id() fname = shutit_global.shutit_global_object.shutit_state_dir + '/tmp_' + random_id working_str = send # truncate -s must be used as --size is not supported everywhere (eg busybox) assert not self.sendline(ShutItSendSpec(self, send=' truncate -s 0 '+ fname, ignore_background=True)), shutit_util.print_debug() self.expect(expect) size = shutit_global.shutit_global_object.line_limit while working_str: curr_str = working_str[:size] working_str = working_str[size:] assert not self.sendline(ShutItSendSpec(self, send=' ' + shutit.get_command('head') + ''' -c -1 >> ''' + fname + """ << 'END_""" + random_id + """'\n""" + curr_str + """\nEND_""" + random_id, ignore_background=True)), shutit_util.print_debug() self.expect(expect) assert not self.sendline(ShutItSendSpec(self, send=' chmod +x ' + fname, ignore_background=True)), shutit_util.print_debug() self.expect(expect) return fname
python
def _create_command_file(self, expect, send): """Internal function. Do not use. Takes a long command, and puts it in an executable file ready to run. Returns the filename. """ shutit = self.shutit random_id = shutit_util.random_id() fname = shutit_global.shutit_global_object.shutit_state_dir + '/tmp_' + random_id working_str = send # truncate -s must be used as --size is not supported everywhere (eg busybox) assert not self.sendline(ShutItSendSpec(self, send=' truncate -s 0 '+ fname, ignore_background=True)), shutit_util.print_debug() self.expect(expect) size = shutit_global.shutit_global_object.line_limit while working_str: curr_str = working_str[:size] working_str = working_str[size:] assert not self.sendline(ShutItSendSpec(self, send=' ' + shutit.get_command('head') + ''' -c -1 >> ''' + fname + """ << 'END_""" + random_id + """'\n""" + curr_str + """\nEND_""" + random_id, ignore_background=True)), shutit_util.print_debug() self.expect(expect) assert not self.sendline(ShutItSendSpec(self, send=' chmod +x ' + fname, ignore_background=True)), shutit_util.print_debug() self.expect(expect) return fname
[ "def", "_create_command_file", "(", "self", ",", "expect", ",", "send", ")", ":", "shutit", "=", "self", ".", "shutit", "random_id", "=", "shutit_util", ".", "random_id", "(", ")", "fname", "=", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir", "+", "'/tmp_'", "+", "random_id", "working_str", "=", "send", "# truncate -s must be used as --size is not supported everywhere (eg busybox)", "assert", "not", "self", ".", "sendline", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' truncate -s 0 '", "+", "fname", ",", "ignore_background", "=", "True", ")", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "self", ".", "expect", "(", "expect", ")", "size", "=", "shutit_global", ".", "shutit_global_object", ".", "line_limit", "while", "working_str", ":", "curr_str", "=", "working_str", "[", ":", "size", "]", "working_str", "=", "working_str", "[", "size", ":", "]", "assert", "not", "self", ".", "sendline", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' '", "+", "shutit", ".", "get_command", "(", "'head'", ")", "+", "''' -c -1 >> '''", "+", "fname", "+", "\"\"\" << 'END_\"\"\"", "+", "random_id", "+", "\"\"\"'\\n\"\"\"", "+", "curr_str", "+", "\"\"\"\\nEND_\"\"\"", "+", "random_id", ",", "ignore_background", "=", "True", ")", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "self", ".", "expect", "(", "expect", ")", "assert", "not", "self", ".", "sendline", "(", "ShutItSendSpec", "(", "self", ",", "send", "=", "' chmod +x '", "+", "fname", ",", "ignore_background", "=", "True", ")", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "self", ".", "expect", "(", "expect", ")", "return", "fname" ]
Internal function. Do not use. Takes a long command, and puts it in an executable file ready to run. Returns the filename.
[ "Internal", "function", ".", "Do", "not", "use", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_pexpect.py#L3535-L3561
train
ianmiell/shutit
shutit_class.py
check_dependee_order
def check_dependee_order(depender, dependee, dependee_id): """Checks whether run orders are in the appropriate order. """ # If it depends on a module id, then the module id should be higher up # in the run order. shutit_global.shutit_global_object.yield_to_draw() if dependee.run_order > depender.run_order: return 'depender module id:\n\n' + depender.module_id + '\n\n(run order: ' + str(depender.run_order) + ') ' + 'depends on dependee module_id:\n\n' + dependee_id + '\n\n(run order: ' + str(dependee.run_order) + ') ' + 'but the latter is configured to run after the former' return ''
python
def check_dependee_order(depender, dependee, dependee_id): """Checks whether run orders are in the appropriate order. """ # If it depends on a module id, then the module id should be higher up # in the run order. shutit_global.shutit_global_object.yield_to_draw() if dependee.run_order > depender.run_order: return 'depender module id:\n\n' + depender.module_id + '\n\n(run order: ' + str(depender.run_order) + ') ' + 'depends on dependee module_id:\n\n' + dependee_id + '\n\n(run order: ' + str(dependee.run_order) + ') ' + 'but the latter is configured to run after the former' return ''
[ "def", "check_dependee_order", "(", "depender", ",", "dependee", ",", "dependee_id", ")", ":", "# If it depends on a module id, then the module id should be higher up", "# in the run order.", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "dependee", ".", "run_order", ">", "depender", ".", "run_order", ":", "return", "'depender module id:\\n\\n'", "+", "depender", ".", "module_id", "+", "'\\n\\n(run order: '", "+", "str", "(", "depender", ".", "run_order", ")", "+", "') '", "+", "'depends on dependee module_id:\\n\\n'", "+", "dependee_id", "+", "'\\n\\n(run order: '", "+", "str", "(", "dependee", ".", "run_order", ")", "+", "') '", "+", "'but the latter is configured to run after the former'", "return", "''" ]
Checks whether run orders are in the appropriate order.
[ "Checks", "whether", "run", "orders", "are", "in", "the", "appropriate", "order", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4869-L4877
train
ianmiell/shutit
shutit_class.py
make_dep_graph
def make_dep_graph(depender): """Returns a digraph string fragment based on the passed-in module """ 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
python
def make_dep_graph(depender): """Returns a digraph string fragment based on the passed-in module """ 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
[ "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
[ "Returns", "a", "digraph", "string", "fragment", "based", "on", "the", "passed", "-", "in", "module" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4880-L4887
train
ianmiell/shutit
shutit_class.py
LayerConfigParser.get_config_set
def get_config_set(self, section, option): """Returns a set with each value per config file in it. """ 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
python
def get_config_set(self, section, option): """Returns a set with each value per config file in it. """ 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
[ "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.
[ "Returns", "a", "set", "with", "each", "value", "per", "config", "file", "in", "it", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L117-L126
train
ianmiell/shutit
shutit_class.py
LayerConfigParser.reload
def reload(self): """ 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. """ 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)
python
def reload(self): """ 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. """ 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)
[ "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.
[ "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", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L128-L141
train
ianmiell/shutit
shutit_class.py
ShutIt.get_shutit_pexpect_session_environment
def get_shutit_pexpect_session_environment(self, environment_id): """Returns the first shutit_pexpect_session object related to the given environment-id """ if not isinstance(environment_id, str): self.fail('Wrong argument type in get_shutit_pexpect_session_environment') # pragma: no cover for env in shutit_global.shutit_global_object.shutit_pexpect_session_environments: if env.environment_id == environment_id: return env return None
python
def get_shutit_pexpect_session_environment(self, environment_id): """Returns the first shutit_pexpect_session object related to the given environment-id """ if not isinstance(environment_id, str): self.fail('Wrong argument type in get_shutit_pexpect_session_environment') # pragma: no cover for env in shutit_global.shutit_global_object.shutit_pexpect_session_environments: if env.environment_id == environment_id: return env return None
[ "def", "get_shutit_pexpect_session_environment", "(", "self", ",", "environment_id", ")", ":", "if", "not", "isinstance", "(", "environment_id", ",", "str", ")", ":", "self", ".", "fail", "(", "'Wrong argument type in get_shutit_pexpect_session_environment'", ")", "# pragma: no cover", "for", "env", "in", "shutit_global", ".", "shutit_global_object", ".", "shutit_pexpect_session_environments", ":", "if", "env", ".", "environment_id", "==", "environment_id", ":", "return", "env", "return", "None" ]
Returns the first shutit_pexpect_session object related to the given environment-id
[ "Returns", "the", "first", "shutit_pexpect_session", "object", "related", "to", "the", "given", "environment", "-", "id" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L515-L524
train
ianmiell/shutit
shutit_class.py
ShutIt.get_current_shutit_pexpect_session_environment
def get_current_shutit_pexpect_session_environment(self, note=None): """Returns the current environment from the currently-set default pexpect child. """ 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
python
def get_current_shutit_pexpect_session_environment(self, note=None): """Returns the current environment from the currently-set default pexpect child. """ 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
[ "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.
[ "Returns", "the", "current", "environment", "from", "the", "currently", "-", "set", "default", "pexpect", "child", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L527-L538
train
ianmiell/shutit
shutit_class.py
ShutIt.get_current_shutit_pexpect_session
def get_current_shutit_pexpect_session(self, note=None): """Returns the currently-set default pexpect child. @return: default shutit pexpect child object """ self.handle_note(note) res = self.current_shutit_pexpect_session self.handle_note_after(note) return res
python
def get_current_shutit_pexpect_session(self, note=None): """Returns the currently-set default pexpect child. @return: default shutit pexpect child object """ self.handle_note(note) res = self.current_shutit_pexpect_session self.handle_note_after(note) return res
[ "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. @return: default shutit pexpect child object
[ "Returns", "the", "currently", "-", "set", "default", "pexpect", "child", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L541-L549
train
ianmiell/shutit
shutit_class.py
ShutIt.get_shutit_pexpect_sessions
def get_shutit_pexpect_sessions(self, note=None): """Returns all the shutit_pexpect_session keys for this object. @return: list of all shutit_pexpect_session keys (pexpect_session_ids) """ 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
python
def get_shutit_pexpect_sessions(self, note=None): """Returns all the shutit_pexpect_session keys for this object. @return: list of all shutit_pexpect_session keys (pexpect_session_ids) """ 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
[ "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. @return: list of all shutit_pexpect_session keys (pexpect_session_ids)
[ "Returns", "all", "the", "shutit_pexpect_session", "keys", "for", "this", "object", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L552-L562
train
ianmiell/shutit
shutit_class.py
ShutIt.set_default_shutit_pexpect_session
def set_default_shutit_pexpect_session(self, shutit_pexpect_session): """Sets the default pexpect child. @param shutit_pexpect_session: pexpect child to set as default """ assert isinstance(shutit_pexpect_session, ShutItPexpectSession), shutit_util.print_debug() self.current_shutit_pexpect_session = shutit_pexpect_session return True
python
def set_default_shutit_pexpect_session(self, shutit_pexpect_session): """Sets the default pexpect child. @param shutit_pexpect_session: pexpect child to set as default """ assert isinstance(shutit_pexpect_session, ShutItPexpectSession), shutit_util.print_debug() self.current_shutit_pexpect_session = shutit_pexpect_session return True
[ "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. @param shutit_pexpect_session: pexpect child to set as default
[ "Sets", "the", "default", "pexpect", "child", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L582-L589
train
ianmiell/shutit
shutit_class.py
ShutIt.fail
def fail(self, msg, shutit_pexpect_child=None, throw_exception=False): """Handles a failure, pausing if a pexpect child object is passed in. @param shutit_pexpect_child: pexpect child to work on @param throw_exception: Whether to throw an exception. @type throw_exception: boolean """ shutit_global.shutit_global_object.yield_to_draw() # Note: we must not default to a child here if shutit_pexpect_child is not None: shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) shutit_util.print_debug(sys.exc_info()) shutit_pexpect_session.pause_point('Pause point on fail: ' + msg, color='31') if throw_exception: sys.stderr.write('Error caught: ' + msg + '\n') sys.stderr.write('\n') shutit_util.print_debug(sys.exc_info()) raise ShutItFailException(msg) else: # This is an "OK" failure, ie we don't need to throw an exception. # However, it's still a "failure", so return 1 shutit_global.shutit_global_object.handle_exit(exit_code=1,msg=msg) shutit_global.shutit_global_object.yield_to_draw()
python
def fail(self, msg, shutit_pexpect_child=None, throw_exception=False): """Handles a failure, pausing if a pexpect child object is passed in. @param shutit_pexpect_child: pexpect child to work on @param throw_exception: Whether to throw an exception. @type throw_exception: boolean """ shutit_global.shutit_global_object.yield_to_draw() # Note: we must not default to a child here if shutit_pexpect_child is not None: shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) shutit_util.print_debug(sys.exc_info()) shutit_pexpect_session.pause_point('Pause point on fail: ' + msg, color='31') if throw_exception: sys.stderr.write('Error caught: ' + msg + '\n') sys.stderr.write('\n') shutit_util.print_debug(sys.exc_info()) raise ShutItFailException(msg) else: # This is an "OK" failure, ie we don't need to throw an exception. # However, it's still a "failure", so return 1 shutit_global.shutit_global_object.handle_exit(exit_code=1,msg=msg) shutit_global.shutit_global_object.yield_to_draw()
[ "def", "fail", "(", "self", ",", "msg", ",", "shutit_pexpect_child", "=", "None", ",", "throw_exception", "=", "False", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# Note: we must not default to a child here", "if", "shutit_pexpect_child", "is", "not", "None", ":", "shutit_pexpect_session", "=", "self", ".", "get_shutit_pexpect_session_from_child", "(", "shutit_pexpect_child", ")", "shutit_util", ".", "print_debug", "(", "sys", ".", "exc_info", "(", ")", ")", "shutit_pexpect_session", ".", "pause_point", "(", "'Pause point on fail: '", "+", "msg", ",", "color", "=", "'31'", ")", "if", "throw_exception", ":", "sys", ".", "stderr", ".", "write", "(", "'Error caught: '", "+", "msg", "+", "'\\n'", ")", "sys", ".", "stderr", ".", "write", "(", "'\\n'", ")", "shutit_util", ".", "print_debug", "(", "sys", ".", "exc_info", "(", ")", ")", "raise", "ShutItFailException", "(", "msg", ")", "else", ":", "# This is an \"OK\" failure, ie we don't need to throw an exception.", "# However, it's still a \"failure\", so return 1", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "1", ",", "msg", "=", "msg", ")", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")" ]
Handles a failure, pausing if a pexpect child object is passed in. @param shutit_pexpect_child: pexpect child to work on @param throw_exception: Whether to throw an exception. @type throw_exception: boolean
[ "Handles", "a", "failure", "pausing", "if", "a", "pexpect", "child", "object", "is", "passed", "in", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L607-L629
train
ianmiell/shutit
shutit_class.py
ShutIt.get_current_environment
def get_current_environment(self, note=None): """Returns the current environment id from the current shutit_pexpect_session """ 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
python
def get_current_environment(self, note=None): """Returns the current environment id from the current shutit_pexpect_session """ 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
[ "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
[ "Returns", "the", "current", "environment", "id", "from", "the", "current", "shutit_pexpect_session" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L632-L640
train
ianmiell/shutit
shutit_class.py
ShutIt.handle_note
def handle_note(self, note, command='', training_input=''): """Handle notes and walkthrough option. @param note: See send() """ 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
python
def handle_note(self, note, command='', training_input=''): """Handle notes and walkthrough option. @param note: See send() """ 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
[ "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. @param note: See send()
[ "Handle", "notes", "and", "walkthrough", "option", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L938-L964
train
ianmiell/shutit
shutit_class.py
ShutIt.expect_allow_interrupt
def expect_allow_interrupt(self, shutit_pexpect_child, expect, timeout, iteration_s=1): """This function allows you to interrupt the run at more or less any point by breaking up the timeout into interactive chunks. """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) accum_timeout = 0 if isinstance(expect, str): expect = [expect] if timeout < 1: timeout = 1 if iteration_s > timeout: iteration_s = timeout - 1 if iteration_s < 1: iteration_s = 1 timed_out = True iteration_n = 0 while accum_timeout < timeout: iteration_n+=1 res = shutit_pexpect_session.expect(expect, timeout=iteration_s, iteration_n=iteration_n) if res == len(expect): if self.build['ctrlc_stop']: timed_out = False self.build['ctrlc_stop'] = False break accum_timeout += iteration_s else: return res if timed_out and not shutit_global.shutit_global_object.determine_interactive(): self.log('Command timed out, trying to get terminal back for you', level=logging.DEBUG) self.fail('Timed out and could not recover') # pragma: no cover else: if shutit_global.shutit_global_object.determine_interactive(): shutit_pexpect_child.send('\x03') res = shutit_pexpect_session.expect(expect,timeout=1) if res == len(expect): shutit_pexpect_child.send('\x1a') res = shutit_pexpect_session.expect(expect,timeout=1) if res == len(expect): self.fail('CTRL-C sent by ShutIt following a timeout, and could not recover') # pragma: no cover shutit_pexpect_session.pause_point('CTRL-C sent by ShutIt following a timeout; the command has been cancelled') return res else: if timed_out: self.fail('Timed out and interactive, but could not recover') # pragma: no cover else: self.fail('CTRL-C hit and could not recover') # pragma: no cover self.fail('Should not get here (expect_allow_interrupt)') # pragma: no cover return True
python
def expect_allow_interrupt(self, shutit_pexpect_child, expect, timeout, iteration_s=1): """This function allows you to interrupt the run at more or less any point by breaking up the timeout into interactive chunks. """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) accum_timeout = 0 if isinstance(expect, str): expect = [expect] if timeout < 1: timeout = 1 if iteration_s > timeout: iteration_s = timeout - 1 if iteration_s < 1: iteration_s = 1 timed_out = True iteration_n = 0 while accum_timeout < timeout: iteration_n+=1 res = shutit_pexpect_session.expect(expect, timeout=iteration_s, iteration_n=iteration_n) if res == len(expect): if self.build['ctrlc_stop']: timed_out = False self.build['ctrlc_stop'] = False break accum_timeout += iteration_s else: return res if timed_out and not shutit_global.shutit_global_object.determine_interactive(): self.log('Command timed out, trying to get terminal back for you', level=logging.DEBUG) self.fail('Timed out and could not recover') # pragma: no cover else: if shutit_global.shutit_global_object.determine_interactive(): shutit_pexpect_child.send('\x03') res = shutit_pexpect_session.expect(expect,timeout=1) if res == len(expect): shutit_pexpect_child.send('\x1a') res = shutit_pexpect_session.expect(expect,timeout=1) if res == len(expect): self.fail('CTRL-C sent by ShutIt following a timeout, and could not recover') # pragma: no cover shutit_pexpect_session.pause_point('CTRL-C sent by ShutIt following a timeout; the command has been cancelled') return res else: if timed_out: self.fail('Timed out and interactive, but could not recover') # pragma: no cover else: self.fail('CTRL-C hit and could not recover') # pragma: no cover self.fail('Should not get here (expect_allow_interrupt)') # pragma: no cover return True
[ "def", "expect_allow_interrupt", "(", "self", ",", "shutit_pexpect_child", ",", "expect", ",", "timeout", ",", "iteration_s", "=", "1", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "shutit_pexpect_session", "=", "self", ".", "get_shutit_pexpect_session_from_child", "(", "shutit_pexpect_child", ")", "accum_timeout", "=", "0", "if", "isinstance", "(", "expect", ",", "str", ")", ":", "expect", "=", "[", "expect", "]", "if", "timeout", "<", "1", ":", "timeout", "=", "1", "if", "iteration_s", ">", "timeout", ":", "iteration_s", "=", "timeout", "-", "1", "if", "iteration_s", "<", "1", ":", "iteration_s", "=", "1", "timed_out", "=", "True", "iteration_n", "=", "0", "while", "accum_timeout", "<", "timeout", ":", "iteration_n", "+=", "1", "res", "=", "shutit_pexpect_session", ".", "expect", "(", "expect", ",", "timeout", "=", "iteration_s", ",", "iteration_n", "=", "iteration_n", ")", "if", "res", "==", "len", "(", "expect", ")", ":", "if", "self", ".", "build", "[", "'ctrlc_stop'", "]", ":", "timed_out", "=", "False", "self", ".", "build", "[", "'ctrlc_stop'", "]", "=", "False", "break", "accum_timeout", "+=", "iteration_s", "else", ":", "return", "res", "if", "timed_out", "and", "not", "shutit_global", ".", "shutit_global_object", ".", "determine_interactive", "(", ")", ":", "self", ".", "log", "(", "'Command timed out, trying to get terminal back for you'", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "fail", "(", "'Timed out and could not recover'", ")", "# pragma: no cover", "else", ":", "if", "shutit_global", ".", "shutit_global_object", ".", "determine_interactive", "(", ")", ":", "shutit_pexpect_child", ".", "send", "(", "'\\x03'", ")", "res", "=", "shutit_pexpect_session", ".", "expect", "(", "expect", ",", "timeout", "=", "1", ")", "if", "res", "==", "len", "(", "expect", ")", ":", "shutit_pexpect_child", ".", "send", "(", "'\\x1a'", ")", "res", "=", "shutit_pexpect_session", ".", "expect", "(", "expect", ",", "timeout", "=", "1", ")", "if", "res", "==", "len", "(", "expect", ")", ":", "self", ".", "fail", "(", "'CTRL-C sent by ShutIt following a timeout, and could not recover'", ")", "# pragma: no cover", "shutit_pexpect_session", ".", "pause_point", "(", "'CTRL-C sent by ShutIt following a timeout; the command has been cancelled'", ")", "return", "res", "else", ":", "if", "timed_out", ":", "self", ".", "fail", "(", "'Timed out and interactive, but could not recover'", ")", "# pragma: no cover", "else", ":", "self", ".", "fail", "(", "'CTRL-C hit and could not recover'", ")", "# pragma: no cover", "self", ".", "fail", "(", "'Should not get here (expect_allow_interrupt)'", ")", "# pragma: no cover", "return", "True" ]
This function allows you to interrupt the run at more or less any point by breaking up the timeout into interactive chunks.
[ "This", "function", "allows", "you", "to", "interrupt", "the", "run", "at", "more", "or", "less", "any", "point", "by", "breaking", "up", "the", "timeout", "into", "interactive", "chunks", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L978-L1030
train
ianmiell/shutit
shutit_class.py
ShutIt.send_host_file
def send_host_file(self, path, hostfilepath, expect=None, shutit_pexpect_child=None, note=None, user=None, group=None, loglevel=logging.INFO): """Send file from host machine to given path @param path: Path to send file to. @param hostfilepath: Path to file from host to send to target. @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child expect = expect or self.get_current_shutit_pexpect_session().default_expect shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) self.handle_note(note, 'Sending file from host: ' + hostfilepath + ' to target path: ' + path) self.log('Sending file from host: ' + hostfilepath + ' to: ' + path, level=loglevel) if user is None: user = shutit_pexpect_session.whoami() if group is None: group = self.whoarewe() # TODO: use gz for both if os.path.isfile(hostfilepath): shutit_pexpect_session.send_file(path, codecs.open(hostfilepath,mode='rb',encoding='iso-8859-1').read(), user=user, group=group, loglevel=loglevel, encoding='iso-8859-1') elif os.path.isdir(hostfilepath): # Need a binary type encoding for gzip(?) self.send_host_dir(path, hostfilepath, user=user, group=group, loglevel=loglevel) else: self.fail('send_host_file - file: ' + hostfilepath + ' does not exist as file or dir. cwd is: ' + os.getcwd(), shutit_pexpect_child=shutit_pexpect_child, throw_exception=False) # pragma: no cover self.handle_note_after(note=note) return True
python
def send_host_file(self, path, hostfilepath, expect=None, shutit_pexpect_child=None, note=None, user=None, group=None, loglevel=logging.INFO): """Send file from host machine to given path @param path: Path to send file to. @param hostfilepath: Path to file from host to send to target. @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string """ shutit_global.shutit_global_object.yield_to_draw() shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child expect = expect or self.get_current_shutit_pexpect_session().default_expect shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) self.handle_note(note, 'Sending file from host: ' + hostfilepath + ' to target path: ' + path) self.log('Sending file from host: ' + hostfilepath + ' to: ' + path, level=loglevel) if user is None: user = shutit_pexpect_session.whoami() if group is None: group = self.whoarewe() # TODO: use gz for both if os.path.isfile(hostfilepath): shutit_pexpect_session.send_file(path, codecs.open(hostfilepath,mode='rb',encoding='iso-8859-1').read(), user=user, group=group, loglevel=loglevel, encoding='iso-8859-1') elif os.path.isdir(hostfilepath): # Need a binary type encoding for gzip(?) self.send_host_dir(path, hostfilepath, user=user, group=group, loglevel=loglevel) else: self.fail('send_host_file - file: ' + hostfilepath + ' does not exist as file or dir. cwd is: ' + os.getcwd(), shutit_pexpect_child=shutit_pexpect_child, throw_exception=False) # pragma: no cover self.handle_note_after(note=note) return True
[ "def", "send_host_file", "(", "self", ",", "path", ",", "hostfilepath", ",", "expect", "=", "None", ",", "shutit_pexpect_child", "=", "None", ",", "note", "=", "None", ",", "user", "=", "None", ",", "group", "=", "None", ",", "loglevel", "=", "logging", ".", "INFO", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "shutit_pexpect_child", "=", "shutit_pexpect_child", "or", "self", ".", "get_current_shutit_pexpect_session", "(", ")", ".", "pexpect_child", "expect", "=", "expect", "or", "self", ".", "get_current_shutit_pexpect_session", "(", ")", ".", "default_expect", "shutit_pexpect_session", "=", "self", ".", "get_shutit_pexpect_session_from_child", "(", "shutit_pexpect_child", ")", "self", ".", "handle_note", "(", "note", ",", "'Sending file from host: '", "+", "hostfilepath", "+", "' to target path: '", "+", "path", ")", "self", ".", "log", "(", "'Sending file from host: '", "+", "hostfilepath", "+", "' to: '", "+", "path", ",", "level", "=", "loglevel", ")", "if", "user", "is", "None", ":", "user", "=", "shutit_pexpect_session", ".", "whoami", "(", ")", "if", "group", "is", "None", ":", "group", "=", "self", ".", "whoarewe", "(", ")", "# TODO: use gz for both", "if", "os", ".", "path", ".", "isfile", "(", "hostfilepath", ")", ":", "shutit_pexpect_session", ".", "send_file", "(", "path", ",", "codecs", ".", "open", "(", "hostfilepath", ",", "mode", "=", "'rb'", ",", "encoding", "=", "'iso-8859-1'", ")", ".", "read", "(", ")", ",", "user", "=", "user", ",", "group", "=", "group", ",", "loglevel", "=", "loglevel", ",", "encoding", "=", "'iso-8859-1'", ")", "elif", "os", ".", "path", ".", "isdir", "(", "hostfilepath", ")", ":", "# Need a binary type encoding for gzip(?)", "self", ".", "send_host_dir", "(", "path", ",", "hostfilepath", ",", "user", "=", "user", ",", "group", "=", "group", ",", "loglevel", "=", "loglevel", ")", "else", ":", "self", ".", "fail", "(", "'send_host_file - file: '", "+", "hostfilepath", "+", "' does not exist as file or dir. cwd is: '", "+", "os", ".", "getcwd", "(", ")", ",", "shutit_pexpect_child", "=", "shutit_pexpect_child", ",", "throw_exception", "=", "False", ")", "# pragma: no cover", "self", ".", "handle_note_after", "(", "note", "=", "note", ")", "return", "True" ]
Send file from host machine to given path @param path: Path to send file to. @param hostfilepath: Path to file from host to send to target. @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string
[ "Send", "file", "from", "host", "machine", "to", "given", "path" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1118-L1168
train
ianmiell/shutit
shutit_class.py
ShutIt.send_host_dir
def send_host_dir(self, path, hostfilepath, expect=None, shutit_pexpect_child=None, note=None, user=None, group=None, loglevel=logging.DEBUG): """Send directory and all contents recursively from host machine to given path. It will automatically make directories on the target. @param path: Path to send directory to (places hostfilepath inside path as a subfolder) @param hostfilepath: Path to file from host to send to target @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string """ 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() # Create gzip of folder #import pdb #pdb.set_trace() 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: # If no gunzip, fall back to old slow method. 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
python
def send_host_dir(self, path, hostfilepath, expect=None, shutit_pexpect_child=None, note=None, user=None, group=None, loglevel=logging.DEBUG): """Send directory and all contents recursively from host machine to given path. It will automatically make directories on the target. @param path: Path to send directory to (places hostfilepath inside path as a subfolder) @param hostfilepath: Path to file from host to send to target @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string """ 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() # Create gzip of folder #import pdb #pdb.set_trace() 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: # If no gunzip, fall back to old slow method. 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
[ "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", "(", ")", "# Create gzip of folder", "#import pdb", "#pdb.set_trace()", "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", ":", "# If no gunzip, fall back to old slow method.", "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. @param path: Path to send directory to (places hostfilepath inside path as a subfolder) @param hostfilepath: Path to file from host to send to target @param expect: See send() @param shutit_pexpect_child: See send() @param note: See send() @param user: Set ownership to this user (defaults to whoami) @param group: Set group to this user (defaults to first group in groups) @type path: string @type hostfilepath: string
[ "Send", "directory", "and", "all", "contents", "recursively", "from", "host", "machine", "to", "given", "path", ".", "It", "will", "automatically", "make", "directories", "on", "the", "target", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1171-L1250
train
ianmiell/shutit
shutit_class.py
ShutIt.delete_text
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): """Delete a chunk of text from a file. See insert_text. """ 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)
python
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): """Delete a chunk of text from a file. See insert_text. """ 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)
[ "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.
[ "Delete", "a", "chunk", "of", "text", "from", "a", "file", ".", "See", "insert_text", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1422-L1447
train
ianmiell/shutit
shutit_class.py
ShutIt.get_file
def get_file(self, target_path, host_path, note=None, loglevel=logging.DEBUG): """Copy a file from the target machine to the host machine @param target_path: path to file in the target @param host_path: path to file on the host machine (e.g. copy test) @param note: See send() @type target_path: string @type host_path: string @return: boolean @rtype: string """ shutit_global.shutit_global_object.yield_to_draw() self.handle_note(note) # Only handle for docker initially, return false in case we care if self.build['delivery'] != 'docker': return False # on the host, run: #Usage: docker cp [OPTIONS] CONTAINER:PATH LOCALPATH|- # Need: host env, container id, path from and path to shutit_pexpect_child = self.get_shutit_pexpect_session_from_id('host_child').pexpect_child expect = self.expect_prompts['ORIGIN_ENV'] self.send('docker cp ' + self.target['container_id'] + ':' + target_path + ' ' + host_path, shutit_pexpect_child=shutit_pexpect_child, expect=expect, check_exit=False, echo=False, loglevel=loglevel) self.handle_note_after(note=note) return True
python
def get_file(self, target_path, host_path, note=None, loglevel=logging.DEBUG): """Copy a file from the target machine to the host machine @param target_path: path to file in the target @param host_path: path to file on the host machine (e.g. copy test) @param note: See send() @type target_path: string @type host_path: string @return: boolean @rtype: string """ shutit_global.shutit_global_object.yield_to_draw() self.handle_note(note) # Only handle for docker initially, return false in case we care if self.build['delivery'] != 'docker': return False # on the host, run: #Usage: docker cp [OPTIONS] CONTAINER:PATH LOCALPATH|- # Need: host env, container id, path from and path to shutit_pexpect_child = self.get_shutit_pexpect_session_from_id('host_child').pexpect_child expect = self.expect_prompts['ORIGIN_ENV'] self.send('docker cp ' + self.target['container_id'] + ':' + target_path + ' ' + host_path, shutit_pexpect_child=shutit_pexpect_child, expect=expect, check_exit=False, echo=False, loglevel=loglevel) self.handle_note_after(note=note) return True
[ "def", "get_file", "(", "self", ",", "target_path", ",", "host_path", ",", "note", "=", "None", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "handle_note", "(", "note", ")", "# Only handle for docker initially, return false in case we care", "if", "self", ".", "build", "[", "'delivery'", "]", "!=", "'docker'", ":", "return", "False", "# on the host, run:", "#Usage: docker cp [OPTIONS] CONTAINER:PATH LOCALPATH|-", "# Need: host env, container id, path from and path to", "shutit_pexpect_child", "=", "self", ".", "get_shutit_pexpect_session_from_id", "(", "'host_child'", ")", ".", "pexpect_child", "expect", "=", "self", ".", "expect_prompts", "[", "'ORIGIN_ENV'", "]", "self", ".", "send", "(", "'docker cp '", "+", "self", ".", "target", "[", "'container_id'", "]", "+", "':'", "+", "target_path", "+", "' '", "+", "host_path", ",", "shutit_pexpect_child", "=", "shutit_pexpect_child", ",", "expect", "=", "expect", ",", "check_exit", "=", "False", ",", "echo", "=", "False", ",", "loglevel", "=", "loglevel", ")", "self", ".", "handle_note_after", "(", "note", "=", "note", ")", "return", "True" ]
Copy a file from the target machine to the host machine @param target_path: path to file in the target @param host_path: path to file on the host machine (e.g. copy test) @param note: See send() @type target_path: string @type host_path: string @return: boolean @rtype: string
[ "Copy", "a", "file", "from", "the", "target", "machine", "to", "the", "host", "machine" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1673-L1707
train
ianmiell/shutit
shutit_class.py
ShutIt.prompt_cfg
def prompt_cfg(self, msg, sec, name, ispass=False): """Prompt for a config value, optionally saving it to the user-level cfg. Only runs if we are in an interactive mode. @param msg: Message to display to user. @param sec: Section of config to add to. @param name: Config item name. @param ispass: If True, hide the input from the terminal. Default: False. @type msg: string @type sec: string @type name: string @type ispass: boolean @return: the value entered by the user @rtype: string """ shutit_global.shutit_global_object.yield_to_draw() cfgstr = '[%s]/%s' % (sec, name) config_parser = self.config_parser usercfg = os.path.join(self.host['shutit_path'], 'config') self.log('\nPROMPTING FOR CONFIG: %s' % (cfgstr,),transient=True,level=logging.INFO) self.log('\n' + msg + '\n',transient=True,level=logging.INFO) if not shutit_global.shutit_global_object.determine_interactive(): self.fail('ShutIt is not in a terminal so cannot prompt for values.', throw_exception=False) # pragma: no cover if config_parser.has_option(sec, name): whereset = config_parser.whereset(sec, name) if usercfg == whereset: self.fail(cfgstr + ' has already been set in the user config, edit ' + usercfg + ' directly to change it', throw_exception=False) # pragma: no cover for subcp, filename, _ in reversed(config_parser.layers): # Is the config file loaded after the user config file? if filename == whereset: self.fail(cfgstr + ' is being set in ' + filename + ', unable to override on a user config level', throw_exception=False) # pragma: no cover elif filename == usercfg: break else: # The item is not currently set so we're fine to do so pass if ispass: val = getpass.getpass('>> ') else: val = shutit_util.util_raw_input(prompt='>> ') is_excluded = ( config_parser.has_option('save_exclude', sec) and name in config_parser.get('save_exclude', sec).split() ) # TODO: ideally we would remember the prompted config item for this invocation of shutit if not is_excluded: usercp = [ subcp for subcp, filename, _ in config_parser.layers if filename == usercfg ][0] if shutit_util.util_raw_input(prompt=shutit_util.colorise('32', 'Do you want to save this to your user settings? y/n: '),default='y') == 'y': sec_toset, name_toset, val_toset = sec, name, val else: # Never save it if config_parser.has_option('save_exclude', sec): excluded = config_parser.get('save_exclude', sec).split() else: excluded = [] excluded.append(name) excluded = ' '.join(excluded) sec_toset, name_toset, val_toset = 'save_exclude', sec, excluded if not usercp.has_section(sec_toset): usercp.add_section(sec_toset) usercp.set(sec_toset, name_toset, val_toset) usercp.write(open(usercfg, 'w')) config_parser.reload() return val
python
def prompt_cfg(self, msg, sec, name, ispass=False): """Prompt for a config value, optionally saving it to the user-level cfg. Only runs if we are in an interactive mode. @param msg: Message to display to user. @param sec: Section of config to add to. @param name: Config item name. @param ispass: If True, hide the input from the terminal. Default: False. @type msg: string @type sec: string @type name: string @type ispass: boolean @return: the value entered by the user @rtype: string """ shutit_global.shutit_global_object.yield_to_draw() cfgstr = '[%s]/%s' % (sec, name) config_parser = self.config_parser usercfg = os.path.join(self.host['shutit_path'], 'config') self.log('\nPROMPTING FOR CONFIG: %s' % (cfgstr,),transient=True,level=logging.INFO) self.log('\n' + msg + '\n',transient=True,level=logging.INFO) if not shutit_global.shutit_global_object.determine_interactive(): self.fail('ShutIt is not in a terminal so cannot prompt for values.', throw_exception=False) # pragma: no cover if config_parser.has_option(sec, name): whereset = config_parser.whereset(sec, name) if usercfg == whereset: self.fail(cfgstr + ' has already been set in the user config, edit ' + usercfg + ' directly to change it', throw_exception=False) # pragma: no cover for subcp, filename, _ in reversed(config_parser.layers): # Is the config file loaded after the user config file? if filename == whereset: self.fail(cfgstr + ' is being set in ' + filename + ', unable to override on a user config level', throw_exception=False) # pragma: no cover elif filename == usercfg: break else: # The item is not currently set so we're fine to do so pass if ispass: val = getpass.getpass('>> ') else: val = shutit_util.util_raw_input(prompt='>> ') is_excluded = ( config_parser.has_option('save_exclude', sec) and name in config_parser.get('save_exclude', sec).split() ) # TODO: ideally we would remember the prompted config item for this invocation of shutit if not is_excluded: usercp = [ subcp for subcp, filename, _ in config_parser.layers if filename == usercfg ][0] if shutit_util.util_raw_input(prompt=shutit_util.colorise('32', 'Do you want to save this to your user settings? y/n: '),default='y') == 'y': sec_toset, name_toset, val_toset = sec, name, val else: # Never save it if config_parser.has_option('save_exclude', sec): excluded = config_parser.get('save_exclude', sec).split() else: excluded = [] excluded.append(name) excluded = ' '.join(excluded) sec_toset, name_toset, val_toset = 'save_exclude', sec, excluded if not usercp.has_section(sec_toset): usercp.add_section(sec_toset) usercp.set(sec_toset, name_toset, val_toset) usercp.write(open(usercfg, 'w')) config_parser.reload() return val
[ "def", "prompt_cfg", "(", "self", ",", "msg", ",", "sec", ",", "name", ",", "ispass", "=", "False", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfgstr", "=", "'[%s]/%s'", "%", "(", "sec", ",", "name", ")", "config_parser", "=", "self", ".", "config_parser", "usercfg", "=", "os", ".", "path", ".", "join", "(", "self", ".", "host", "[", "'shutit_path'", "]", ",", "'config'", ")", "self", ".", "log", "(", "'\\nPROMPTING FOR CONFIG: %s'", "%", "(", "cfgstr", ",", ")", ",", "transient", "=", "True", ",", "level", "=", "logging", ".", "INFO", ")", "self", ".", "log", "(", "'\\n'", "+", "msg", "+", "'\\n'", ",", "transient", "=", "True", ",", "level", "=", "logging", ".", "INFO", ")", "if", "not", "shutit_global", ".", "shutit_global_object", ".", "determine_interactive", "(", ")", ":", "self", ".", "fail", "(", "'ShutIt is not in a terminal so cannot prompt for values.'", ",", "throw_exception", "=", "False", ")", "# pragma: no cover", "if", "config_parser", ".", "has_option", "(", "sec", ",", "name", ")", ":", "whereset", "=", "config_parser", ".", "whereset", "(", "sec", ",", "name", ")", "if", "usercfg", "==", "whereset", ":", "self", ".", "fail", "(", "cfgstr", "+", "' has already been set in the user config, edit '", "+", "usercfg", "+", "' directly to change it'", ",", "throw_exception", "=", "False", ")", "# pragma: no cover", "for", "subcp", ",", "filename", ",", "_", "in", "reversed", "(", "config_parser", ".", "layers", ")", ":", "# Is the config file loaded after the user config file?", "if", "filename", "==", "whereset", ":", "self", ".", "fail", "(", "cfgstr", "+", "' is being set in '", "+", "filename", "+", "', unable to override on a user config level'", ",", "throw_exception", "=", "False", ")", "# pragma: no cover", "elif", "filename", "==", "usercfg", ":", "break", "else", ":", "# The item is not currently set so we're fine to do so", "pass", "if", "ispass", ":", "val", "=", "getpass", ".", "getpass", "(", "'>> '", ")", "else", ":", "val", "=", "shutit_util", ".", "util_raw_input", "(", "prompt", "=", "'>> '", ")", "is_excluded", "=", "(", "config_parser", ".", "has_option", "(", "'save_exclude'", ",", "sec", ")", "and", "name", "in", "config_parser", ".", "get", "(", "'save_exclude'", ",", "sec", ")", ".", "split", "(", ")", ")", "# TODO: ideally we would remember the prompted config item for this invocation of shutit", "if", "not", "is_excluded", ":", "usercp", "=", "[", "subcp", "for", "subcp", ",", "filename", ",", "_", "in", "config_parser", ".", "layers", "if", "filename", "==", "usercfg", "]", "[", "0", "]", "if", "shutit_util", ".", "util_raw_input", "(", "prompt", "=", "shutit_util", ".", "colorise", "(", "'32'", ",", "'Do you want to save this to your user settings? y/n: '", ")", ",", "default", "=", "'y'", ")", "==", "'y'", ":", "sec_toset", ",", "name_toset", ",", "val_toset", "=", "sec", ",", "name", ",", "val", "else", ":", "# Never save it", "if", "config_parser", ".", "has_option", "(", "'save_exclude'", ",", "sec", ")", ":", "excluded", "=", "config_parser", ".", "get", "(", "'save_exclude'", ",", "sec", ")", ".", "split", "(", ")", "else", ":", "excluded", "=", "[", "]", "excluded", ".", "append", "(", "name", ")", "excluded", "=", "' '", ".", "join", "(", "excluded", ")", "sec_toset", ",", "name_toset", ",", "val_toset", "=", "'save_exclude'", ",", "sec", ",", "excluded", "if", "not", "usercp", ".", "has_section", "(", "sec_toset", ")", ":", "usercp", ".", "add_section", "(", "sec_toset", ")", "usercp", ".", "set", "(", "sec_toset", ",", "name_toset", ",", "val_toset", ")", "usercp", ".", "write", "(", "open", "(", "usercfg", ",", "'w'", ")", ")", "config_parser", ".", "reload", "(", ")", "return", "val" ]
Prompt for a config value, optionally saving it to the user-level cfg. Only runs if we are in an interactive mode. @param msg: Message to display to user. @param sec: Section of config to add to. @param name: Config item name. @param ispass: If True, hide the input from the terminal. Default: False. @type msg: string @type sec: string @type name: string @type ispass: boolean @return: the value entered by the user @rtype: string
[ "Prompt", "for", "a", "config", "value", "optionally", "saving", "it", "to", "the", "user", "-", "level", "cfg", ".", "Only", "runs", "if", "we", "are", "in", "an", "interactive", "mode", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1710-L1782
train
ianmiell/shutit
shutit_class.py
ShutIt.step_through
def step_through(self, msg='', shutit_pexpect_child=None, level=1, print_input=True, value=True): """Implements a step-through function, using pause_point. """ 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
python
def step_through(self, msg='', shutit_pexpect_child=None, level=1, print_input=True, value=True): """Implements a step-through function, using pause_point. """ 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
[ "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.
[ "Implements", "a", "step", "-", "through", "function", "using", "pause_point", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1785-L1796
train
ianmiell/shutit
shutit_class.py
ShutIt.interact
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): """Same as pause_point, but sets up the terminal ready for unmediated interaction.""" 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)
python
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): """Same as pause_point, but sets up the terminal ready for unmediated interaction.""" 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)
[ "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.
[ "Same", "as", "pause_point", "but", "sets", "up", "the", "terminal", "ready", "for", "unmediated", "interaction", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1799-L1819
train
ianmiell/shutit
shutit_class.py
ShutIt.pause_point
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): """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. @param msg: Message to display to user on pause point. @param shutit_pexpect_child: See send() @param print_input: Whether to take input at this point (i.e. interact), or simply pause pending any input. Default: True @param level: Minimum level to invoke the pause_point at. Default: 1 @param resize: If True, try to resize terminal. Default: False @param color: Color to print message (typically 31 for red, 32 for green) @param default_msg: Whether to print the standard blurb @param wait: Wait a few seconds rather than for input @type msg: string @type print_input: boolean @type level: integer @type resize: boolean @type wait: decimal @return: True if pause point handled ok, else false """ shutit_global.shutit_global_object.yield_to_draw() if (not shutit_global.shutit_global_object.determine_interactive() or shutit_global.shutit_global_object.interactive < 1 or shutit_global.shutit_global_object.interactive < level): return True shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child # Don't log log traces while in interactive log_trace_when_idle_original_value = shutit_global.shutit_global_object.log_trace_when_idle shutit_global.shutit_global_object.log_trace_when_idle = False if shutit_pexpect_child: if shutit_global.shutit_global_object.pane_manager is not None: shutit_global.shutit_global_object.pane_manager.draw_screen(draw_type='clearscreen') shutit_global.shutit_global_object.pane_manager.do_render = False shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) # TODO: context added to pause point message shutit_pexpect_session.pause_point(msg=msg, print_input=print_input, resize=resize, color=color, default_msg=default_msg, wait=wait, interact=interact) else: self.log(msg,level=logging.DEBUG) self.log('Nothing to interact with, so quitting to presumably the original shell',level=logging.DEBUG) shutit_global.shutit_global_object.handle_exit(exit_code=1) if shutit_pexpect_child: if shutit_global.shutit_global_object.pane_manager is not None: shutit_global.shutit_global_object.pane_manager.do_render = True shutit_global.shutit_global_object.pane_manager.draw_screen(draw_type='clearscreen') self.build['ctrlc_stop'] = False # Revert value of log_trace_when_idle shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return True
python
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): """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. @param msg: Message to display to user on pause point. @param shutit_pexpect_child: See send() @param print_input: Whether to take input at this point (i.e. interact), or simply pause pending any input. Default: True @param level: Minimum level to invoke the pause_point at. Default: 1 @param resize: If True, try to resize terminal. Default: False @param color: Color to print message (typically 31 for red, 32 for green) @param default_msg: Whether to print the standard blurb @param wait: Wait a few seconds rather than for input @type msg: string @type print_input: boolean @type level: integer @type resize: boolean @type wait: decimal @return: True if pause point handled ok, else false """ shutit_global.shutit_global_object.yield_to_draw() if (not shutit_global.shutit_global_object.determine_interactive() or shutit_global.shutit_global_object.interactive < 1 or shutit_global.shutit_global_object.interactive < level): return True shutit_pexpect_child = shutit_pexpect_child or self.get_current_shutit_pexpect_session().pexpect_child # Don't log log traces while in interactive log_trace_when_idle_original_value = shutit_global.shutit_global_object.log_trace_when_idle shutit_global.shutit_global_object.log_trace_when_idle = False if shutit_pexpect_child: if shutit_global.shutit_global_object.pane_manager is not None: shutit_global.shutit_global_object.pane_manager.draw_screen(draw_type='clearscreen') shutit_global.shutit_global_object.pane_manager.do_render = False shutit_pexpect_session = self.get_shutit_pexpect_session_from_child(shutit_pexpect_child) # TODO: context added to pause point message shutit_pexpect_session.pause_point(msg=msg, print_input=print_input, resize=resize, color=color, default_msg=default_msg, wait=wait, interact=interact) else: self.log(msg,level=logging.DEBUG) self.log('Nothing to interact with, so quitting to presumably the original shell',level=logging.DEBUG) shutit_global.shutit_global_object.handle_exit(exit_code=1) if shutit_pexpect_child: if shutit_global.shutit_global_object.pane_manager is not None: shutit_global.shutit_global_object.pane_manager.do_render = True shutit_global.shutit_global_object.pane_manager.draw_screen(draw_type='clearscreen') self.build['ctrlc_stop'] = False # Revert value of log_trace_when_idle shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return True
[ "def", "pause_point", "(", "self", ",", "msg", "=", "'SHUTIT PAUSE POINT'", ",", "shutit_pexpect_child", "=", "None", ",", "print_input", "=", "True", ",", "level", "=", "1", ",", "resize", "=", "True", ",", "color", "=", "'32'", ",", "default_msg", "=", "None", ",", "interact", "=", "False", ",", "wait", "=", "-", "1", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "(", "not", "shutit_global", ".", "shutit_global_object", ".", "determine_interactive", "(", ")", "or", "shutit_global", ".", "shutit_global_object", ".", "interactive", "<", "1", "or", "shutit_global", ".", "shutit_global_object", ".", "interactive", "<", "level", ")", ":", "return", "True", "shutit_pexpect_child", "=", "shutit_pexpect_child", "or", "self", ".", "get_current_shutit_pexpect_session", "(", ")", ".", "pexpect_child", "# Don't log log traces while in interactive", "log_trace_when_idle_original_value", "=", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "False", "if", "shutit_pexpect_child", ":", "if", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", "is", "not", "None", ":", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", ".", "draw_screen", "(", "draw_type", "=", "'clearscreen'", ")", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", ".", "do_render", "=", "False", "shutit_pexpect_session", "=", "self", ".", "get_shutit_pexpect_session_from_child", "(", "shutit_pexpect_child", ")", "# TODO: context added to pause point message", "shutit_pexpect_session", ".", "pause_point", "(", "msg", "=", "msg", ",", "print_input", "=", "print_input", ",", "resize", "=", "resize", ",", "color", "=", "color", ",", "default_msg", "=", "default_msg", ",", "wait", "=", "wait", ",", "interact", "=", "interact", ")", "else", ":", "self", ".", "log", "(", "msg", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "log", "(", "'Nothing to interact with, so quitting to presumably the original shell'", ",", "level", "=", "logging", ".", "DEBUG", ")", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "1", ")", "if", "shutit_pexpect_child", ":", "if", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", "is", "not", "None", ":", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", ".", "do_render", "=", "True", "shutit_global", ".", "shutit_global_object", ".", "pane_manager", ".", "draw_screen", "(", "draw_type", "=", "'clearscreen'", ")", "self", ".", "build", "[", "'ctrlc_stop'", "]", "=", "False", "# Revert value of log_trace_when_idle", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "log_trace_when_idle_original_value", "return", "True" ]
Inserts a pause in the build session, which allows the user to try things out before continuing. Ignored if we are not in an interactive mode, or the interactive level is less than the passed-in one. Designed to help debug the build, or drop to on failure so the situation can be debugged. @param msg: Message to display to user on pause point. @param shutit_pexpect_child: See send() @param print_input: Whether to take input at this point (i.e. interact), or simply pause pending any input. Default: True @param level: Minimum level to invoke the pause_point at. Default: 1 @param resize: If True, try to resize terminal. Default: False @param color: Color to print message (typically 31 for red, 32 for green) @param default_msg: Whether to print the standard blurb @param wait: Wait a few seconds rather than for input @type msg: string @type print_input: boolean @type level: integer @type resize: boolean @type wait: decimal @return: True if pause point handled ok, else false
[ "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", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L1822-L1891
train
ianmiell/shutit
shutit_class.py
ShutIt.login
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): """Logs user in on default child. """ 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))
python
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): """Logs user in on default child. """ 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))
[ "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.
[ "Logs", "user", "in", "on", "default", "child", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2105-L2138
train
ianmiell/shutit
shutit_class.py
ShutIt.logout_all
def logout_all(self, command='exit', note=None, echo=None, timeout=shutit_global.shutit_global_object.default_timeout, nonewline=False, loglevel=logging.DEBUG): """Logs the user out of all pexpect sessions within this ShutIt object. @param command: Command to run to log out (default=exit) @param note: See send() """ 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
python
def logout_all(self, command='exit', note=None, echo=None, timeout=shutit_global.shutit_global_object.default_timeout, nonewline=False, loglevel=logging.DEBUG): """Logs the user out of all pexpect sessions within this ShutIt object. @param command: Command to run to log out (default=exit) @param note: See send() """ 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
[ "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. @param command: Command to run to log out (default=exit) @param note: See send()
[ "Logs", "the", "user", "out", "of", "all", "pexpect", "sessions", "within", "this", "ShutIt", "object", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2141-L2163
train
ianmiell/shutit
shutit_class.py
ShutIt.push_repository
def push_repository(self, repository, docker_executable='docker', shutit_pexpect_child=None, expect=None, note=None, loglevel=logging.INFO): """Pushes the repository. @param repository: Repository to push. @param docker_executable: Defaults to 'docker' @param expect: See send() @param shutit_pexpect_child: See send() @type repository: string @type docker_executable: string """ 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
python
def push_repository(self, repository, docker_executable='docker', shutit_pexpect_child=None, expect=None, note=None, loglevel=logging.INFO): """Pushes the repository. @param repository: Repository to push. @param docker_executable: Defaults to 'docker' @param expect: See send() @param shutit_pexpect_child: See send() @type repository: string @type docker_executable: string """ 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
[ "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. @param repository: Repository to push. @param docker_executable: Defaults to 'docker' @param expect: See send() @param shutit_pexpect_child: See send() @type repository: string @type docker_executable: string
[ "Pushes", "the", "repository", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2301-L2337
train
ianmiell/shutit
shutit_class.py
ShutIt.get_emailer
def get_emailer(self, cfg_section): """Sends an email using the mailer """ shutit_global.shutit_global_object.yield_to_draw() import emailer return emailer.Emailer(cfg_section, self)
python
def get_emailer(self, cfg_section): """Sends an email using the mailer """ shutit_global.shutit_global_object.yield_to_draw() import emailer return emailer.Emailer(cfg_section, self)
[ "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
[ "Sends", "an", "email", "using", "the", "mailer" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2617-L2622
train
ianmiell/shutit
shutit_class.py
ShutIt.get_shutit_pexpect_session_id
def get_shutit_pexpect_session_id(self, shutit_pexpect_child): """Given a pexpect child object, return the shutit_pexpect_session_id object. """ shutit_global.shutit_global_object.yield_to_draw() if not isinstance(shutit_pexpect_child, pexpect.pty_spawn.spawn): self.fail('Wrong type in get_shutit_pexpect_session_id',throw_exception=True) # pragma: no cover for key in self.shutit_pexpect_sessions: if self.shutit_pexpect_sessions[key].pexpect_child == shutit_pexpect_child: return key return self.fail('Should not get here in get_shutit_pexpect_session_id',throw_exception=True)
python
def get_shutit_pexpect_session_id(self, shutit_pexpect_child): """Given a pexpect child object, return the shutit_pexpect_session_id object. """ shutit_global.shutit_global_object.yield_to_draw() if not isinstance(shutit_pexpect_child, pexpect.pty_spawn.spawn): self.fail('Wrong type in get_shutit_pexpect_session_id',throw_exception=True) # pragma: no cover for key in self.shutit_pexpect_sessions: if self.shutit_pexpect_sessions[key].pexpect_child == shutit_pexpect_child: return key return self.fail('Should not get here in get_shutit_pexpect_session_id',throw_exception=True)
[ "def", "get_shutit_pexpect_session_id", "(", "self", ",", "shutit_pexpect_child", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "not", "isinstance", "(", "shutit_pexpect_child", ",", "pexpect", ".", "pty_spawn", ".", "spawn", ")", ":", "self", ".", "fail", "(", "'Wrong type in get_shutit_pexpect_session_id'", ",", "throw_exception", "=", "True", ")", "# pragma: no cover", "for", "key", "in", "self", ".", "shutit_pexpect_sessions", ":", "if", "self", ".", "shutit_pexpect_sessions", "[", "key", "]", ".", "pexpect_child", "==", "shutit_pexpect_child", ":", "return", "key", "return", "self", ".", "fail", "(", "'Should not get here in get_shutit_pexpect_session_id'", ",", "throw_exception", "=", "True", ")" ]
Given a pexpect child object, return the shutit_pexpect_session_id object.
[ "Given", "a", "pexpect", "child", "object", "return", "the", "shutit_pexpect_session_id", "object", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2645-L2654
train
ianmiell/shutit
shutit_class.py
ShutIt.get_shutit_pexpect_session_from_id
def get_shutit_pexpect_session_from_id(self, shutit_pexpect_id): """Get the pexpect session from the given identifier. """ 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)
python
def get_shutit_pexpect_session_from_id(self, shutit_pexpect_id): """Get the pexpect session from the given identifier. """ 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)
[ "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.
[ "Get", "the", "pexpect", "session", "from", "the", "given", "identifier", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2657-L2664
train
ianmiell/shutit
shutit_class.py
ShutIt.get_commands
def get_commands(self): """Gets command that have been run and have not been redacted. """ 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
python
def get_commands(self): """Gets command that have been run and have not been redacted. """ 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
[ "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.
[ "Gets", "command", "that", "have", "been", "run", "and", "have", "not", "been", "redacted", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2722-L2732
train
ianmiell/shutit
shutit_class.py
ShutIt.build_report
def build_report(self, msg=''): """Resposible for constructing a report to be output as part of the build. Returns report as a string. """ shutit_global.shutit_global_object.yield_to_draw() s = '\n' s += '################################################################################\n' s += '# COMMAND HISTORY BEGIN ' + shutit_global.shutit_global_object.build_id + '\n' s += self.get_commands() s += '# COMMAND HISTORY END ' + shutit_global.shutit_global_object.build_id + '\n' s += '################################################################################\n' s += '################################################################################\n' s += '# BUILD REPORT FOR BUILD BEGIN ' + shutit_global.shutit_global_object.build_id + '\n' s += '# ' + msg + '\n' if self.build['report'] != '': s += self.build['report'] + '\n' else: s += '# Nothing to report\n' if 'container_id' in self.target: s += '# CONTAINER_ID: ' + self.target['container_id'] + '\n' s += '# BUILD REPORT FOR BUILD END ' + shutit_global.shutit_global_object.build_id + '\n' s += '###############################################################################\n' s += '# INVOKING COMMAND WAS: ' + sys.executable for arg in sys.argv: s += ' ' + arg s += '\n' s += '###############################################################################\n' return s
python
def build_report(self, msg=''): """Resposible for constructing a report to be output as part of the build. Returns report as a string. """ shutit_global.shutit_global_object.yield_to_draw() s = '\n' s += '################################################################################\n' s += '# COMMAND HISTORY BEGIN ' + shutit_global.shutit_global_object.build_id + '\n' s += self.get_commands() s += '# COMMAND HISTORY END ' + shutit_global.shutit_global_object.build_id + '\n' s += '################################################################################\n' s += '################################################################################\n' s += '# BUILD REPORT FOR BUILD BEGIN ' + shutit_global.shutit_global_object.build_id + '\n' s += '# ' + msg + '\n' if self.build['report'] != '': s += self.build['report'] + '\n' else: s += '# Nothing to report\n' if 'container_id' in self.target: s += '# CONTAINER_ID: ' + self.target['container_id'] + '\n' s += '# BUILD REPORT FOR BUILD END ' + shutit_global.shutit_global_object.build_id + '\n' s += '###############################################################################\n' s += '# INVOKING COMMAND WAS: ' + sys.executable for arg in sys.argv: s += ' ' + arg s += '\n' s += '###############################################################################\n' return s
[ "def", "build_report", "(", "self", ",", "msg", "=", "''", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "s", "=", "'\\n'", "s", "+=", "'################################################################################\\n'", "s", "+=", "'# COMMAND HISTORY BEGIN '", "+", "shutit_global", ".", "shutit_global_object", ".", "build_id", "+", "'\\n'", "s", "+=", "self", ".", "get_commands", "(", ")", "s", "+=", "'# COMMAND HISTORY END '", "+", "shutit_global", ".", "shutit_global_object", ".", "build_id", "+", "'\\n'", "s", "+=", "'################################################################################\\n'", "s", "+=", "'################################################################################\\n'", "s", "+=", "'# BUILD REPORT FOR BUILD BEGIN '", "+", "shutit_global", ".", "shutit_global_object", ".", "build_id", "+", "'\\n'", "s", "+=", "'# '", "+", "msg", "+", "'\\n'", "if", "self", ".", "build", "[", "'report'", "]", "!=", "''", ":", "s", "+=", "self", ".", "build", "[", "'report'", "]", "+", "'\\n'", "else", ":", "s", "+=", "'# Nothing to report\\n'", "if", "'container_id'", "in", "self", ".", "target", ":", "s", "+=", "'# CONTAINER_ID: '", "+", "self", ".", "target", "[", "'container_id'", "]", "+", "'\\n'", "s", "+=", "'# BUILD REPORT FOR BUILD END '", "+", "shutit_global", ".", "shutit_global_object", ".", "build_id", "+", "'\\n'", "s", "+=", "'###############################################################################\\n'", "s", "+=", "'# INVOKING COMMAND WAS: '", "+", "sys", ".", "executable", "for", "arg", "in", "sys", ".", "argv", ":", "s", "+=", "' '", "+", "arg", "s", "+=", "'\\n'", "s", "+=", "'###############################################################################\\n'", "return", "s" ]
Resposible for constructing a report to be output as part of the build. Returns report as a string.
[ "Resposible", "for", "constructing", "a", "report", "to", "be", "output", "as", "part", "of", "the", "build", ".", "Returns", "report", "as", "a", "string", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2736-L2763
train
ianmiell/shutit
shutit_class.py
ShutIt.match_string
def match_string(self, string_to_match, regexp): """Get regular expression from the first of the lines passed in in string that matched. Handles first group of regexp as a return value. @param string_to_match: String to match on @param regexp: Regexp to check (per-line) against string @type string_to_match: string @type regexp: string Returns None if none of the lines matched. Returns True if there are no groups selected in the regexp. else returns matching group (ie non-None) """ shutit_global.shutit_global_object.yield_to_draw() if not isinstance(string_to_match, str): return None lines = string_to_match.split('\r\n') # sometimes they're separated by just a carriage return... new_lines = [] for line in lines: new_lines = new_lines + line.split('\r') # and sometimes they're separated by just a newline... for line in lines: new_lines = new_lines + line.split('\n') lines = new_lines if not shutit_util.check_regexp(regexp): self.fail('Illegal regexp found in match_string call: ' + regexp) # pragma: no cover for line in lines: match = re.match(regexp, line) if match is not None: if match.groups(): return match.group(1) return True return None
python
def match_string(self, string_to_match, regexp): """Get regular expression from the first of the lines passed in in string that matched. Handles first group of regexp as a return value. @param string_to_match: String to match on @param regexp: Regexp to check (per-line) against string @type string_to_match: string @type regexp: string Returns None if none of the lines matched. Returns True if there are no groups selected in the regexp. else returns matching group (ie non-None) """ shutit_global.shutit_global_object.yield_to_draw() if not isinstance(string_to_match, str): return None lines = string_to_match.split('\r\n') # sometimes they're separated by just a carriage return... new_lines = [] for line in lines: new_lines = new_lines + line.split('\r') # and sometimes they're separated by just a newline... for line in lines: new_lines = new_lines + line.split('\n') lines = new_lines if not shutit_util.check_regexp(regexp): self.fail('Illegal regexp found in match_string call: ' + regexp) # pragma: no cover for line in lines: match = re.match(regexp, line) if match is not None: if match.groups(): return match.group(1) return True return None
[ "def", "match_string", "(", "self", ",", "string_to_match", ",", "regexp", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "not", "isinstance", "(", "string_to_match", ",", "str", ")", ":", "return", "None", "lines", "=", "string_to_match", ".", "split", "(", "'\\r\\n'", ")", "# sometimes they're separated by just a carriage return...", "new_lines", "=", "[", "]", "for", "line", "in", "lines", ":", "new_lines", "=", "new_lines", "+", "line", ".", "split", "(", "'\\r'", ")", "# and sometimes they're separated by just a newline...", "for", "line", "in", "lines", ":", "new_lines", "=", "new_lines", "+", "line", ".", "split", "(", "'\\n'", ")", "lines", "=", "new_lines", "if", "not", "shutit_util", ".", "check_regexp", "(", "regexp", ")", ":", "self", ".", "fail", "(", "'Illegal regexp found in match_string call: '", "+", "regexp", ")", "# pragma: no cover", "for", "line", "in", "lines", ":", "match", "=", "re", ".", "match", "(", "regexp", ",", "line", ")", "if", "match", "is", "not", "None", ":", "if", "match", ".", "groups", "(", ")", ":", "return", "match", ".", "group", "(", "1", ")", "return", "True", "return", "None" ]
Get regular expression from the first of the lines passed in in string that matched. Handles first group of regexp as a return value. @param string_to_match: String to match on @param regexp: Regexp to check (per-line) against string @type string_to_match: string @type regexp: string Returns None if none of the lines matched. Returns True if there are no groups selected in the regexp. else returns matching group (ie non-None)
[ "Get", "regular", "expression", "from", "the", "first", "of", "the", "lines", "passed", "in", "in", "string", "that", "matched", ".", "Handles", "first", "group", "of", "regexp", "as", "a", "return", "value", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2766-L2802
train
ianmiell/shutit
shutit_class.py
ShutIt.is_to_be_built_or_is_installed
def is_to_be_built_or_is_installed(self, shutit_module_obj): """Returns true if this module is configured to be built, or if it is already installed. """ 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)
python
def is_to_be_built_or_is_installed(self, shutit_module_obj): """Returns true if this module is configured to be built, or if it is already installed. """ 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)
[ "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.
[ "Returns", "true", "if", "this", "module", "is", "configured", "to", "be", "built", "or", "if", "it", "is", "already", "installed", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2816-L2823
train
ianmiell/shutit
shutit_class.py
ShutIt.is_installed
def is_installed(self, shutit_module_obj): """Returns true if this module is installed. Uses cache where possible. """ shutit_global.shutit_global_object.yield_to_draw() # Cache first if shutit_module_obj.module_id in self.get_current_shutit_pexpect_session_environment().modules_installed: return True if shutit_module_obj.module_id in self.get_current_shutit_pexpect_session_environment().modules_not_installed: return False # Is it installed? if shutit_module_obj.is_installed(self): self.get_current_shutit_pexpect_session_environment().modules_installed.append(shutit_module_obj.module_id) return True # If not installed, and not in cache, add it. else: if shutit_module_obj.module_id not in self.get_current_shutit_pexpect_session_environment().modules_not_installed: self.get_current_shutit_pexpect_session_environment().modules_not_installed.append(shutit_module_obj.module_id) return False return False
python
def is_installed(self, shutit_module_obj): """Returns true if this module is installed. Uses cache where possible. """ shutit_global.shutit_global_object.yield_to_draw() # Cache first if shutit_module_obj.module_id in self.get_current_shutit_pexpect_session_environment().modules_installed: return True if shutit_module_obj.module_id in self.get_current_shutit_pexpect_session_environment().modules_not_installed: return False # Is it installed? if shutit_module_obj.is_installed(self): self.get_current_shutit_pexpect_session_environment().modules_installed.append(shutit_module_obj.module_id) return True # If not installed, and not in cache, add it. else: if shutit_module_obj.module_id not in self.get_current_shutit_pexpect_session_environment().modules_not_installed: self.get_current_shutit_pexpect_session_environment().modules_not_installed.append(shutit_module_obj.module_id) return False return False
[ "def", "is_installed", "(", "self", ",", "shutit_module_obj", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# Cache first", "if", "shutit_module_obj", ".", "module_id", "in", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_installed", ":", "return", "True", "if", "shutit_module_obj", ".", "module_id", "in", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_not_installed", ":", "return", "False", "# Is it installed?", "if", "shutit_module_obj", ".", "is_installed", "(", "self", ")", ":", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_installed", ".", "append", "(", "shutit_module_obj", ".", "module_id", ")", "return", "True", "# If not installed, and not in cache, add it.", "else", ":", "if", "shutit_module_obj", ".", "module_id", "not", "in", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_not_installed", ":", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_not_installed", ".", "append", "(", "shutit_module_obj", ".", "module_id", ")", "return", "False", "return", "False" ]
Returns true if this module is installed. Uses cache where possible.
[ "Returns", "true", "if", "this", "module", "is", "installed", ".", "Uses", "cache", "where", "possible", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2826-L2845
train
ianmiell/shutit
shutit_class.py
ShutIt.allowed_image
def allowed_image(self, module_id): """Given a module id, determine whether the image is allowed to be built. """ shutit_global.shutit_global_object.yield_to_draw() self.log("In allowed_image: " + module_id,level=logging.DEBUG) cfg = self.cfg if self.build['ignoreimage']: self.log("ignoreimage == true, returning true" + module_id,level=logging.DEBUG) return True self.log(str(cfg[module_id]['shutit.core.module.allowed_images']),level=logging.DEBUG) if cfg[module_id]['shutit.core.module.allowed_images']: # Try allowed images as regexps for regexp in cfg[module_id]['shutit.core.module.allowed_images']: if not shutit_util.check_regexp(regexp): self.fail('Illegal regexp found in allowed_images: ' + regexp) # pragma: no cover if re.match('^' + regexp + '$', self.target['docker_image']): return True return False
python
def allowed_image(self, module_id): """Given a module id, determine whether the image is allowed to be built. """ shutit_global.shutit_global_object.yield_to_draw() self.log("In allowed_image: " + module_id,level=logging.DEBUG) cfg = self.cfg if self.build['ignoreimage']: self.log("ignoreimage == true, returning true" + module_id,level=logging.DEBUG) return True self.log(str(cfg[module_id]['shutit.core.module.allowed_images']),level=logging.DEBUG) if cfg[module_id]['shutit.core.module.allowed_images']: # Try allowed images as regexps for regexp in cfg[module_id]['shutit.core.module.allowed_images']: if not shutit_util.check_regexp(regexp): self.fail('Illegal regexp found in allowed_images: ' + regexp) # pragma: no cover if re.match('^' + regexp + '$', self.target['docker_image']): return True return False
[ "def", "allowed_image", "(", "self", ",", "module_id", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "log", "(", "\"In allowed_image: \"", "+", "module_id", ",", "level", "=", "logging", ".", "DEBUG", ")", "cfg", "=", "self", ".", "cfg", "if", "self", ".", "build", "[", "'ignoreimage'", "]", ":", "self", ".", "log", "(", "\"ignoreimage == true, returning true\"", "+", "module_id", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "True", "self", ".", "log", "(", "str", "(", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.allowed_images'", "]", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.allowed_images'", "]", ":", "# Try allowed images as regexps", "for", "regexp", "in", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.allowed_images'", "]", ":", "if", "not", "shutit_util", ".", "check_regexp", "(", "regexp", ")", ":", "self", ".", "fail", "(", "'Illegal regexp found in allowed_images: '", "+", "regexp", ")", "# pragma: no cover", "if", "re", ".", "match", "(", "'^'", "+", "regexp", "+", "'$'", ",", "self", ".", "target", "[", "'docker_image'", "]", ")", ":", "return", "True", "return", "False" ]
Given a module id, determine whether the image is allowed to be built.
[ "Given", "a", "module", "id", "determine", "whether", "the", "image", "is", "allowed", "to", "be", "built", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2861-L2878
train
ianmiell/shutit
shutit_class.py
ShutIt.print_modules
def print_modules(self): """Returns a string table representing the modules in the ShutIt module map. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg module_string = '' module_string += 'Modules: \n' module_string += ' Run order Build Remove Module ID\n' for module_id in self.module_ids(): module_string += ' ' + str(self.shutit_map[module_id].run_order) + ' ' + str( cfg[module_id]['shutit.core.module.build']) + ' ' + str( cfg[module_id]['shutit.core.module.remove']) + ' ' + module_id + '\n' return module_string
python
def print_modules(self): """Returns a string table representing the modules in the ShutIt module map. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg module_string = '' module_string += 'Modules: \n' module_string += ' Run order Build Remove Module ID\n' for module_id in self.module_ids(): module_string += ' ' + str(self.shutit_map[module_id].run_order) + ' ' + str( cfg[module_id]['shutit.core.module.build']) + ' ' + str( cfg[module_id]['shutit.core.module.remove']) + ' ' + module_id + '\n' return module_string
[ "def", "print_modules", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "module_string", "=", "''", "module_string", "+=", "'Modules: \\n'", "module_string", "+=", "' Run order Build Remove Module ID\\n'", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "module_string", "+=", "' '", "+", "str", "(", "self", ".", "shutit_map", "[", "module_id", "]", ".", "run_order", ")", "+", "' '", "+", "str", "(", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", ")", "+", "' '", "+", "str", "(", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.remove'", "]", ")", "+", "' '", "+", "module_id", "+", "'\\n'", "return", "module_string" ]
Returns a string table representing the modules in the ShutIt module map.
[ "Returns", "a", "string", "table", "representing", "the", "modules", "in", "the", "ShutIt", "module", "map", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2881-L2893
train
ianmiell/shutit
shutit_class.py
ShutIt.load_shutit_modules
def load_shutit_modules(self): """Responsible for loading the shutit modules based on the configured module paths. """ shutit_global.shutit_global_object.yield_to_draw() if self.loglevel <= logging.DEBUG: self.log('ShutIt module paths now: ',level=logging.DEBUG) self.log(self.host['shutit_module_path'],level=logging.DEBUG) for shutit_module_path in self.host['shutit_module_path']: self.load_all_from_path(shutit_module_path)
python
def load_shutit_modules(self): """Responsible for loading the shutit modules based on the configured module paths. """ shutit_global.shutit_global_object.yield_to_draw() if self.loglevel <= logging.DEBUG: self.log('ShutIt module paths now: ',level=logging.DEBUG) self.log(self.host['shutit_module_path'],level=logging.DEBUG) for shutit_module_path in self.host['shutit_module_path']: self.load_all_from_path(shutit_module_path)
[ "def", "load_shutit_modules", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "self", ".", "loglevel", "<=", "logging", ".", "DEBUG", ":", "self", ".", "log", "(", "'ShutIt module paths now: '", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "log", "(", "self", ".", "host", "[", "'shutit_module_path'", "]", ",", "level", "=", "logging", ".", "DEBUG", ")", "for", "shutit_module_path", "in", "self", ".", "host", "[", "'shutit_module_path'", "]", ":", "self", ".", "load_all_from_path", "(", "shutit_module_path", ")" ]
Responsible for loading the shutit modules based on the configured module paths.
[ "Responsible", "for", "loading", "the", "shutit", "modules", "based", "on", "the", "configured", "module", "paths", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2896-L2905
train
ianmiell/shutit
shutit_class.py
ShutIt.get_command
def get_command(self, command): """Helper function for osx - return gnu utils rather than default for eg head and md5sum where possible and needed. """ 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
python
def get_command(self, command): """Helper function for osx - return gnu utils rather than default for eg head and md5sum where possible and needed. """ 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
[ "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.
[ "Helper", "function", "for", "osx", "-", "return", "gnu", "utils", "rather", "than", "default", "for", "eg", "head", "and", "md5sum", "where", "possible", "and", "needed", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2908-L2916
train
ianmiell/shutit
shutit_class.py
ShutIt.get_send_command
def get_send_command(self, send): """Internal helper function to get command that's really sent """ shutit_global.shutit_global_object.yield_to_draw() if send is None: return send cmd_arr = send.split() if cmd_arr and cmd_arr[0] in ('md5sum','sed','head'): newcmd = self.get_command(cmd_arr[0]) send = send.replace(cmd_arr[0],newcmd) return send
python
def get_send_command(self, send): """Internal helper function to get command that's really sent """ shutit_global.shutit_global_object.yield_to_draw() if send is None: return send cmd_arr = send.split() if cmd_arr and cmd_arr[0] in ('md5sum','sed','head'): newcmd = self.get_command(cmd_arr[0]) send = send.replace(cmd_arr[0],newcmd) return send
[ "def", "get_send_command", "(", "self", ",", "send", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "if", "send", "is", "None", ":", "return", "send", "cmd_arr", "=", "send", ".", "split", "(", ")", "if", "cmd_arr", "and", "cmd_arr", "[", "0", "]", "in", "(", "'md5sum'", ",", "'sed'", ",", "'head'", ")", ":", "newcmd", "=", "self", ".", "get_command", "(", "cmd_arr", "[", "0", "]", ")", "send", "=", "send", ".", "replace", "(", "cmd_arr", "[", "0", "]", ",", "newcmd", ")", "return", "send" ]
Internal helper function to get command that's really sent
[ "Internal", "helper", "function", "to", "get", "command", "that", "s", "really", "sent" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2919-L2929
train
ianmiell/shutit
shutit_class.py
ShutIt.load_configs
def load_configs(self): """Responsible for loading config files into ShutIt. Recurses down from configured shutit module paths. """ shutit_global.shutit_global_object.yield_to_draw() # Get root default config. # TODO: change default_cnf so it places whatever the values are at this stage of the build. configs = [('defaults', StringIO(default_cnf)), os.path.expanduser('~/.shutit/config'), os.path.join(self.host['shutit_path'], 'config'), 'configs/build.cnf'] # Add the shutit global host- and user-specific config file. # Add the local build.cnf # Get passed-in config(s) for config_file_name in self.build['extra_configs']: run_config_file = os.path.expanduser(config_file_name) if not os.path.isfile(run_config_file): shutit_global.shutit_global_object.shutit_print('Did not recognise ' + run_config_file + ' as a file - do you need to touch ' + run_config_file + '?') shutit_global.shutit_global_object.handle_exit(exit_code=0) configs.append(run_config_file) # Image to use to start off. The script should be idempotent, so running it # on an already built image should be ok, and is advised to reduce diff space required. if self.action['list_configs'] or self.loglevel <= logging.DEBUG: msg = '' for c in configs: if isinstance(c, tuple): c = c[0] msg = msg + ' \n' + c self.log(' ' + c,level=logging.DEBUG) # Interpret any config overrides, write to a file and add them to the # list of configs to be interpreted if self.build['config_overrides']: # We don't need layers, this is a temporary configparser override_cp = ConfigParser.RawConfigParser() for o_sec, o_key, o_val in self.build['config_overrides']: if not override_cp.has_section(o_sec): override_cp.add_section(o_sec) override_cp.set(o_sec, o_key, o_val) override_fd = StringIO() override_cp.write(override_fd) override_fd.seek(0) configs.append(('overrides', override_fd)) self.config_parser = self.get_configs(configs) self.get_base_config()
python
def load_configs(self): """Responsible for loading config files into ShutIt. Recurses down from configured shutit module paths. """ shutit_global.shutit_global_object.yield_to_draw() # Get root default config. # TODO: change default_cnf so it places whatever the values are at this stage of the build. configs = [('defaults', StringIO(default_cnf)), os.path.expanduser('~/.shutit/config'), os.path.join(self.host['shutit_path'], 'config'), 'configs/build.cnf'] # Add the shutit global host- and user-specific config file. # Add the local build.cnf # Get passed-in config(s) for config_file_name in self.build['extra_configs']: run_config_file = os.path.expanduser(config_file_name) if not os.path.isfile(run_config_file): shutit_global.shutit_global_object.shutit_print('Did not recognise ' + run_config_file + ' as a file - do you need to touch ' + run_config_file + '?') shutit_global.shutit_global_object.handle_exit(exit_code=0) configs.append(run_config_file) # Image to use to start off. The script should be idempotent, so running it # on an already built image should be ok, and is advised to reduce diff space required. if self.action['list_configs'] or self.loglevel <= logging.DEBUG: msg = '' for c in configs: if isinstance(c, tuple): c = c[0] msg = msg + ' \n' + c self.log(' ' + c,level=logging.DEBUG) # Interpret any config overrides, write to a file and add them to the # list of configs to be interpreted if self.build['config_overrides']: # We don't need layers, this is a temporary configparser override_cp = ConfigParser.RawConfigParser() for o_sec, o_key, o_val in self.build['config_overrides']: if not override_cp.has_section(o_sec): override_cp.add_section(o_sec) override_cp.set(o_sec, o_key, o_val) override_fd = StringIO() override_cp.write(override_fd) override_fd.seek(0) configs.append(('overrides', override_fd)) self.config_parser = self.get_configs(configs) self.get_base_config()
[ "def", "load_configs", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# Get root default config.", "# TODO: change default_cnf so it places whatever the values are at this stage of the build.", "configs", "=", "[", "(", "'defaults'", ",", "StringIO", "(", "default_cnf", ")", ")", ",", "os", ".", "path", ".", "expanduser", "(", "'~/.shutit/config'", ")", ",", "os", ".", "path", ".", "join", "(", "self", ".", "host", "[", "'shutit_path'", "]", ",", "'config'", ")", ",", "'configs/build.cnf'", "]", "# Add the shutit global host- and user-specific config file.", "# Add the local build.cnf", "# Get passed-in config(s)", "for", "config_file_name", "in", "self", ".", "build", "[", "'extra_configs'", "]", ":", "run_config_file", "=", "os", ".", "path", ".", "expanduser", "(", "config_file_name", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "run_config_file", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "'Did not recognise '", "+", "run_config_file", "+", "' as a file - do you need to touch '", "+", "run_config_file", "+", "'?'", ")", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "0", ")", "configs", ".", "append", "(", "run_config_file", ")", "# Image to use to start off. The script should be idempotent, so running it", "# on an already built image should be ok, and is advised to reduce diff space required.", "if", "self", ".", "action", "[", "'list_configs'", "]", "or", "self", ".", "loglevel", "<=", "logging", ".", "DEBUG", ":", "msg", "=", "''", "for", "c", "in", "configs", ":", "if", "isinstance", "(", "c", ",", "tuple", ")", ":", "c", "=", "c", "[", "0", "]", "msg", "=", "msg", "+", "' \\n'", "+", "c", "self", ".", "log", "(", "' '", "+", "c", ",", "level", "=", "logging", ".", "DEBUG", ")", "# Interpret any config overrides, write to a file and add them to the", "# list of configs to be interpreted", "if", "self", ".", "build", "[", "'config_overrides'", "]", ":", "# We don't need layers, this is a temporary configparser", "override_cp", "=", "ConfigParser", ".", "RawConfigParser", "(", ")", "for", "o_sec", ",", "o_key", ",", "o_val", "in", "self", ".", "build", "[", "'config_overrides'", "]", ":", "if", "not", "override_cp", ".", "has_section", "(", "o_sec", ")", ":", "override_cp", ".", "add_section", "(", "o_sec", ")", "override_cp", ".", "set", "(", "o_sec", ",", "o_key", ",", "o_val", ")", "override_fd", "=", "StringIO", "(", ")", "override_cp", ".", "write", "(", "override_fd", ")", "override_fd", ".", "seek", "(", "0", ")", "configs", ".", "append", "(", "(", "'overrides'", ",", "override_fd", ")", ")", "self", ".", "config_parser", "=", "self", ".", "get_configs", "(", "configs", ")", "self", ".", "get_base_config", "(", ")" ]
Responsible for loading config files into ShutIt. Recurses down from configured shutit module paths.
[ "Responsible", "for", "loading", "config", "files", "into", "ShutIt", ".", "Recurses", "down", "from", "configured", "shutit", "module", "paths", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L2932-L2974
train
ianmiell/shutit
shutit_class.py
ShutIt.config_collection
def config_collection(self): """Collect core config from config files for all seen modules. """ shutit_global.shutit_global_object.yield_to_draw() self.log('In config_collection',level=logging.DEBUG) cfg = self.cfg for module_id in self.module_ids(): # Default to None so we can interpret as ifneeded self.get_config(module_id, 'shutit.core.module.build', None, boolean=True, forcenone=True) self.get_config(module_id, 'shutit.core.module.remove', False, boolean=True) self.get_config(module_id, 'shutit.core.module.tag', False, boolean=True) # Default to allow any image self.get_config(module_id, 'shutit.core.module.allowed_images', [".*"]) module = self.shutit_map[module_id] cfg_file = os.path.dirname(get_module_file(self,module)) + '/configs/build.cnf' if os.path.isfile(cfg_file): # use self.get_config, forcing the passed-in default config_parser = ConfigParser.ConfigParser() config_parser.read(cfg_file) for section in config_parser.sections(): if section == module_id: for option in config_parser.options(section): if option == 'shutit.core.module.allowed_images': override = False for mod, opt, val in self.build['config_overrides']: val = val # pylint # skip overrides if mod == module_id and opt == option: override = True if override: continue value = config_parser.get(section,option) if option == 'shutit.core.module.allowed_images': value = json.loads(value) self.get_config(module_id, option, value, forceask=True) # ifneeded will (by default) only take effect if 'build' is not # specified. It can, however, be forced to a value, but this # should be unusual. if cfg[module_id]['shutit.core.module.build'] is None: self.get_config(module_id, 'shutit.core.module.build_ifneeded', True, boolean=True) cfg[module_id]['shutit.core.module.build'] = False else: self.get_config(module_id, 'shutit.core.module.build_ifneeded', False, boolean=True)
python
def config_collection(self): """Collect core config from config files for all seen modules. """ shutit_global.shutit_global_object.yield_to_draw() self.log('In config_collection',level=logging.DEBUG) cfg = self.cfg for module_id in self.module_ids(): # Default to None so we can interpret as ifneeded self.get_config(module_id, 'shutit.core.module.build', None, boolean=True, forcenone=True) self.get_config(module_id, 'shutit.core.module.remove', False, boolean=True) self.get_config(module_id, 'shutit.core.module.tag', False, boolean=True) # Default to allow any image self.get_config(module_id, 'shutit.core.module.allowed_images', [".*"]) module = self.shutit_map[module_id] cfg_file = os.path.dirname(get_module_file(self,module)) + '/configs/build.cnf' if os.path.isfile(cfg_file): # use self.get_config, forcing the passed-in default config_parser = ConfigParser.ConfigParser() config_parser.read(cfg_file) for section in config_parser.sections(): if section == module_id: for option in config_parser.options(section): if option == 'shutit.core.module.allowed_images': override = False for mod, opt, val in self.build['config_overrides']: val = val # pylint # skip overrides if mod == module_id and opt == option: override = True if override: continue value = config_parser.get(section,option) if option == 'shutit.core.module.allowed_images': value = json.loads(value) self.get_config(module_id, option, value, forceask=True) # ifneeded will (by default) only take effect if 'build' is not # specified. It can, however, be forced to a value, but this # should be unusual. if cfg[module_id]['shutit.core.module.build'] is None: self.get_config(module_id, 'shutit.core.module.build_ifneeded', True, boolean=True) cfg[module_id]['shutit.core.module.build'] = False else: self.get_config(module_id, 'shutit.core.module.build_ifneeded', False, boolean=True)
[ "def", "config_collection", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "log", "(", "'In config_collection'", ",", "level", "=", "logging", ".", "DEBUG", ")", "cfg", "=", "self", ".", "cfg", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "# Default to None so we can interpret as ifneeded", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.build'", ",", "None", ",", "boolean", "=", "True", ",", "forcenone", "=", "True", ")", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.remove'", ",", "False", ",", "boolean", "=", "True", ")", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.tag'", ",", "False", ",", "boolean", "=", "True", ")", "# Default to allow any image", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.allowed_images'", ",", "[", "\".*\"", "]", ")", "module", "=", "self", ".", "shutit_map", "[", "module_id", "]", "cfg_file", "=", "os", ".", "path", ".", "dirname", "(", "get_module_file", "(", "self", ",", "module", ")", ")", "+", "'/configs/build.cnf'", "if", "os", ".", "path", ".", "isfile", "(", "cfg_file", ")", ":", "# use self.get_config, forcing the passed-in default", "config_parser", "=", "ConfigParser", ".", "ConfigParser", "(", ")", "config_parser", ".", "read", "(", "cfg_file", ")", "for", "section", "in", "config_parser", ".", "sections", "(", ")", ":", "if", "section", "==", "module_id", ":", "for", "option", "in", "config_parser", ".", "options", "(", "section", ")", ":", "if", "option", "==", "'shutit.core.module.allowed_images'", ":", "override", "=", "False", "for", "mod", ",", "opt", ",", "val", "in", "self", ".", "build", "[", "'config_overrides'", "]", ":", "val", "=", "val", "# pylint", "# skip overrides", "if", "mod", "==", "module_id", "and", "opt", "==", "option", ":", "override", "=", "True", "if", "override", ":", "continue", "value", "=", "config_parser", ".", "get", "(", "section", ",", "option", ")", "if", "option", "==", "'shutit.core.module.allowed_images'", ":", "value", "=", "json", ".", "loads", "(", "value", ")", "self", ".", "get_config", "(", "module_id", ",", "option", ",", "value", ",", "forceask", "=", "True", ")", "# ifneeded will (by default) only take effect if 'build' is not", "# specified. It can, however, be forced to a value, but this", "# should be unusual.", "if", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", "is", "None", ":", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.build_ifneeded'", ",", "True", ",", "boolean", "=", "True", ")", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", "=", "False", "else", ":", "self", ".", "get_config", "(", "module_id", ",", "'shutit.core.module.build_ifneeded'", ",", "False", ",", "boolean", "=", "True", ")" ]
Collect core config from config files for all seen modules.
[ "Collect", "core", "config", "from", "config", "files", "for", "all", "seen", "modules", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L3195-L3237
train
ianmiell/shutit
shutit_class.py
ShutIt.print_config
def print_config(self, cfg, hide_password=True, history=False, module_id=None): """Returns a string representing the config of this ShutIt run. """ shutit_global.shutit_global_object.yield_to_draw() cp = self.config_parser s = '' keys1 = list(cfg.keys()) if keys1: keys1.sort() for k in keys1: if module_id is not None and k != module_id: continue if isinstance(k, str) and isinstance(cfg[k], dict): s += '\n[' + k + ']\n' keys2 = list(cfg[k].keys()) if keys2: keys2.sort() for k1 in keys2: line = '' line += k1 + ':' # If we want to hide passwords, we do so using a sha512 # done an aritrary number of times (27). if hide_password and (k1 == 'password' or k1 == 'passphrase'): p = hashlib.sha512(cfg[k][k1]).hexdigest() i = 27 while i > 0: i -= 1 p = hashlib.sha512(s).hexdigest() line += p else: if type(cfg[k][k1] == bool): line += str(cfg[k][k1]) elif type(cfg[k][k1] == str): line += cfg[k][k1] if history: try: line += (30-len(line)) * ' ' + ' # ' + cp.whereset(k, k1) except Exception: # Assume this is because it was never set by a config parser. line += (30-len(line)) * ' ' + ' # ' + "defaults in code" s += line + '\n' return s
python
def print_config(self, cfg, hide_password=True, history=False, module_id=None): """Returns a string representing the config of this ShutIt run. """ shutit_global.shutit_global_object.yield_to_draw() cp = self.config_parser s = '' keys1 = list(cfg.keys()) if keys1: keys1.sort() for k in keys1: if module_id is not None and k != module_id: continue if isinstance(k, str) and isinstance(cfg[k], dict): s += '\n[' + k + ']\n' keys2 = list(cfg[k].keys()) if keys2: keys2.sort() for k1 in keys2: line = '' line += k1 + ':' # If we want to hide passwords, we do so using a sha512 # done an aritrary number of times (27). if hide_password and (k1 == 'password' or k1 == 'passphrase'): p = hashlib.sha512(cfg[k][k1]).hexdigest() i = 27 while i > 0: i -= 1 p = hashlib.sha512(s).hexdigest() line += p else: if type(cfg[k][k1] == bool): line += str(cfg[k][k1]) elif type(cfg[k][k1] == str): line += cfg[k][k1] if history: try: line += (30-len(line)) * ' ' + ' # ' + cp.whereset(k, k1) except Exception: # Assume this is because it was never set by a config parser. line += (30-len(line)) * ' ' + ' # ' + "defaults in code" s += line + '\n' return s
[ "def", "print_config", "(", "self", ",", "cfg", ",", "hide_password", "=", "True", ",", "history", "=", "False", ",", "module_id", "=", "None", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cp", "=", "self", ".", "config_parser", "s", "=", "''", "keys1", "=", "list", "(", "cfg", ".", "keys", "(", ")", ")", "if", "keys1", ":", "keys1", ".", "sort", "(", ")", "for", "k", "in", "keys1", ":", "if", "module_id", "is", "not", "None", "and", "k", "!=", "module_id", ":", "continue", "if", "isinstance", "(", "k", ",", "str", ")", "and", "isinstance", "(", "cfg", "[", "k", "]", ",", "dict", ")", ":", "s", "+=", "'\\n['", "+", "k", "+", "']\\n'", "keys2", "=", "list", "(", "cfg", "[", "k", "]", ".", "keys", "(", ")", ")", "if", "keys2", ":", "keys2", ".", "sort", "(", ")", "for", "k1", "in", "keys2", ":", "line", "=", "''", "line", "+=", "k1", "+", "':'", "# If we want to hide passwords, we do so using a sha512", "# done an aritrary number of times (27).", "if", "hide_password", "and", "(", "k1", "==", "'password'", "or", "k1", "==", "'passphrase'", ")", ":", "p", "=", "hashlib", ".", "sha512", "(", "cfg", "[", "k", "]", "[", "k1", "]", ")", ".", "hexdigest", "(", ")", "i", "=", "27", "while", "i", ">", "0", ":", "i", "-=", "1", "p", "=", "hashlib", ".", "sha512", "(", "s", ")", ".", "hexdigest", "(", ")", "line", "+=", "p", "else", ":", "if", "type", "(", "cfg", "[", "k", "]", "[", "k1", "]", "==", "bool", ")", ":", "line", "+=", "str", "(", "cfg", "[", "k", "]", "[", "k1", "]", ")", "elif", "type", "(", "cfg", "[", "k", "]", "[", "k1", "]", "==", "str", ")", ":", "line", "+=", "cfg", "[", "k", "]", "[", "k1", "]", "if", "history", ":", "try", ":", "line", "+=", "(", "30", "-", "len", "(", "line", ")", ")", "*", "' '", "+", "' # '", "+", "cp", ".", "whereset", "(", "k", ",", "k1", ")", "except", "Exception", ":", "# Assume this is because it was never set by a config parser.", "line", "+=", "(", "30", "-", "len", "(", "line", ")", ")", "*", "' '", "+", "' # '", "+", "\"defaults in code\"", "s", "+=", "line", "+", "'\\n'", "return", "s" ]
Returns a string representing the config of this ShutIt run.
[ "Returns", "a", "string", "representing", "the", "config", "of", "this", "ShutIt", "run", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L3338-L3379
train
ianmiell/shutit
shutit_class.py
ShutIt.process_args
def process_args(self, args): """Process the args we have. 'args' is always a ShutItInit object. """ shutit_global.shutit_global_object.yield_to_draw() assert isinstance(args,ShutItInit), shutit_util.print_debug() if args.action == 'version': shutit_global.shutit_global_object.shutit_print('ShutIt version: ' + shutit.shutit_version) shutit_global.shutit_global_object.handle_exit(exit_code=0) # What are we asking shutit to do? self.action['list_configs'] = args.action == 'list_configs' self.action['list_modules'] = args.action == 'list_modules' self.action['list_deps'] = args.action == 'list_deps' self.action['skeleton'] = args.action == 'skeleton' self.action['build'] = args.action == 'build' self.action['run'] = args.action == 'run' # Logging if not self.logging_setup_done: self.logfile = args.logfile self.loglevel = args.loglevel if self.loglevel is None or self.loglevel == '': self.loglevel = 'INFO' self.setup_logging() shutit_global.shutit_global_object.setup_panes(action=args.action) # This mode is a bit special - it's the only one with different arguments if self.action['skeleton']: self.handle_skeleton(args) shutit_global.shutit_global_object.handle_exit() elif self.action['run']: self.handle_run(args) sys.exit(0) elif self.action['build'] or self.action['list_configs'] or self.action['list_modules']: self.handle_build(args) else: self.fail('Should not get here: action was: ' + str(self.action)) self.nocolor = args.nocolor
python
def process_args(self, args): """Process the args we have. 'args' is always a ShutItInit object. """ shutit_global.shutit_global_object.yield_to_draw() assert isinstance(args,ShutItInit), shutit_util.print_debug() if args.action == 'version': shutit_global.shutit_global_object.shutit_print('ShutIt version: ' + shutit.shutit_version) shutit_global.shutit_global_object.handle_exit(exit_code=0) # What are we asking shutit to do? self.action['list_configs'] = args.action == 'list_configs' self.action['list_modules'] = args.action == 'list_modules' self.action['list_deps'] = args.action == 'list_deps' self.action['skeleton'] = args.action == 'skeleton' self.action['build'] = args.action == 'build' self.action['run'] = args.action == 'run' # Logging if not self.logging_setup_done: self.logfile = args.logfile self.loglevel = args.loglevel if self.loglevel is None or self.loglevel == '': self.loglevel = 'INFO' self.setup_logging() shutit_global.shutit_global_object.setup_panes(action=args.action) # This mode is a bit special - it's the only one with different arguments if self.action['skeleton']: self.handle_skeleton(args) shutit_global.shutit_global_object.handle_exit() elif self.action['run']: self.handle_run(args) sys.exit(0) elif self.action['build'] or self.action['list_configs'] or self.action['list_modules']: self.handle_build(args) else: self.fail('Should not get here: action was: ' + str(self.action)) self.nocolor = args.nocolor
[ "def", "process_args", "(", "self", ",", "args", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "assert", "isinstance", "(", "args", ",", "ShutItInit", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "if", "args", ".", "action", "==", "'version'", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "'ShutIt version: '", "+", "shutit", ".", "shutit_version", ")", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "0", ")", "# What are we asking shutit to do?", "self", ".", "action", "[", "'list_configs'", "]", "=", "args", ".", "action", "==", "'list_configs'", "self", ".", "action", "[", "'list_modules'", "]", "=", "args", ".", "action", "==", "'list_modules'", "self", ".", "action", "[", "'list_deps'", "]", "=", "args", ".", "action", "==", "'list_deps'", "self", ".", "action", "[", "'skeleton'", "]", "=", "args", ".", "action", "==", "'skeleton'", "self", ".", "action", "[", "'build'", "]", "=", "args", ".", "action", "==", "'build'", "self", ".", "action", "[", "'run'", "]", "=", "args", ".", "action", "==", "'run'", "# Logging", "if", "not", "self", ".", "logging_setup_done", ":", "self", ".", "logfile", "=", "args", ".", "logfile", "self", ".", "loglevel", "=", "args", ".", "loglevel", "if", "self", ".", "loglevel", "is", "None", "or", "self", ".", "loglevel", "==", "''", ":", "self", ".", "loglevel", "=", "'INFO'", "self", ".", "setup_logging", "(", ")", "shutit_global", ".", "shutit_global_object", ".", "setup_panes", "(", "action", "=", "args", ".", "action", ")", "# This mode is a bit special - it's the only one with different arguments", "if", "self", ".", "action", "[", "'skeleton'", "]", ":", "self", ".", "handle_skeleton", "(", "args", ")", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", ")", "elif", "self", ".", "action", "[", "'run'", "]", ":", "self", ".", "handle_run", "(", "args", ")", "sys", ".", "exit", "(", "0", ")", "elif", "self", ".", "action", "[", "'build'", "]", "or", "self", ".", "action", "[", "'list_configs'", "]", "or", "self", ".", "action", "[", "'list_modules'", "]", ":", "self", ".", "handle_build", "(", "args", ")", "else", ":", "self", ".", "fail", "(", "'Should not get here: action was: '", "+", "str", "(", "self", ".", "action", ")", ")", "self", ".", "nocolor", "=", "args", ".", "nocolor" ]
Process the args we have. 'args' is always a ShutItInit object.
[ "Process", "the", "args", "we", "have", ".", "args", "is", "always", "a", "ShutItInit", "object", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L3382-L3420
train
ianmiell/shutit
shutit_class.py
ShutIt.check_deps
def check_deps(self): """Dependency checking phase is performed in this method. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg self.log('PHASE: dependencies', level=logging.DEBUG) self.pause_point('\nNow checking for dependencies between modules', print_input=False, level=3) # Get modules we're going to build to_build = [ self.shutit_map[module_id] for module_id in self.shutit_map if module_id in cfg and cfg[module_id]['shutit.core.module.build'] ] # Add any deps we may need by extending to_build and altering cfg for module in to_build: self.resolve_dependencies(to_build, module) # Dep checking def err_checker(errs, triples): """Collate error information. """ new_triples = [] for err, triple in zip(errs, triples): if not err: new_triples.append(triple) continue found_errs.append(err) return new_triples found_errs = [] triples = [] for depender in to_build: for dependee_id in depender.depends_on: triples.append((depender, self.shutit_map.get(dependee_id), dependee_id)) triples = err_checker([ self.check_dependee_exists(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) triples = err_checker([ self.check_dependee_build(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) triples = err_checker([ check_dependee_order(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) if found_errs: return [(err,) for err in found_errs] self.log('Modules configured to be built (in order) are: ', level=logging.DEBUG) for module_id in self.module_ids(): module = self.shutit_map[module_id] if cfg[module_id]['shutit.core.module.build']: self.log(module_id + ' ' + str(module.run_order), level=logging.DEBUG) self.log('\n', level=logging.DEBUG) return []
python
def check_deps(self): """Dependency checking phase is performed in this method. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg self.log('PHASE: dependencies', level=logging.DEBUG) self.pause_point('\nNow checking for dependencies between modules', print_input=False, level=3) # Get modules we're going to build to_build = [ self.shutit_map[module_id] for module_id in self.shutit_map if module_id in cfg and cfg[module_id]['shutit.core.module.build'] ] # Add any deps we may need by extending to_build and altering cfg for module in to_build: self.resolve_dependencies(to_build, module) # Dep checking def err_checker(errs, triples): """Collate error information. """ new_triples = [] for err, triple in zip(errs, triples): if not err: new_triples.append(triple) continue found_errs.append(err) return new_triples found_errs = [] triples = [] for depender in to_build: for dependee_id in depender.depends_on: triples.append((depender, self.shutit_map.get(dependee_id), dependee_id)) triples = err_checker([ self.check_dependee_exists(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) triples = err_checker([ self.check_dependee_build(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) triples = err_checker([ check_dependee_order(depender, dependee, dependee_id) for depender, dependee, dependee_id in triples ], triples) if found_errs: return [(err,) for err in found_errs] self.log('Modules configured to be built (in order) are: ', level=logging.DEBUG) for module_id in self.module_ids(): module = self.shutit_map[module_id] if cfg[module_id]['shutit.core.module.build']: self.log(module_id + ' ' + str(module.run_order), level=logging.DEBUG) self.log('\n', level=logging.DEBUG) return []
[ "def", "check_deps", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "self", ".", "log", "(", "'PHASE: dependencies'", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "pause_point", "(", "'\\nNow checking for dependencies between modules'", ",", "print_input", "=", "False", ",", "level", "=", "3", ")", "# Get modules we're going to build", "to_build", "=", "[", "self", ".", "shutit_map", "[", "module_id", "]", "for", "module_id", "in", "self", ".", "shutit_map", "if", "module_id", "in", "cfg", "and", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", "]", "# Add any deps we may need by extending to_build and altering cfg", "for", "module", "in", "to_build", ":", "self", ".", "resolve_dependencies", "(", "to_build", ",", "module", ")", "# Dep checking", "def", "err_checker", "(", "errs", ",", "triples", ")", ":", "\"\"\"Collate error information.\n\t\t\t\"\"\"", "new_triples", "=", "[", "]", "for", "err", ",", "triple", "in", "zip", "(", "errs", ",", "triples", ")", ":", "if", "not", "err", ":", "new_triples", ".", "append", "(", "triple", ")", "continue", "found_errs", ".", "append", "(", "err", ")", "return", "new_triples", "found_errs", "=", "[", "]", "triples", "=", "[", "]", "for", "depender", "in", "to_build", ":", "for", "dependee_id", "in", "depender", ".", "depends_on", ":", "triples", ".", "append", "(", "(", "depender", ",", "self", ".", "shutit_map", ".", "get", "(", "dependee_id", ")", ",", "dependee_id", ")", ")", "triples", "=", "err_checker", "(", "[", "self", ".", "check_dependee_exists", "(", "depender", ",", "dependee", ",", "dependee_id", ")", "for", "depender", ",", "dependee", ",", "dependee_id", "in", "triples", "]", ",", "triples", ")", "triples", "=", "err_checker", "(", "[", "self", ".", "check_dependee_build", "(", "depender", ",", "dependee", ",", "dependee_id", ")", "for", "depender", ",", "dependee", ",", "dependee_id", "in", "triples", "]", ",", "triples", ")", "triples", "=", "err_checker", "(", "[", "check_dependee_order", "(", "depender", ",", "dependee", ",", "dependee_id", ")", "for", "depender", ",", "dependee", ",", "dependee_id", "in", "triples", "]", ",", "triples", ")", "if", "found_errs", ":", "return", "[", "(", "err", ",", ")", "for", "err", "in", "found_errs", "]", "self", ".", "log", "(", "'Modules configured to be built (in order) are: '", ",", "level", "=", "logging", ".", "DEBUG", ")", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "module", "=", "self", ".", "shutit_map", "[", "module_id", "]", "if", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", ":", "self", ".", "log", "(", "module_id", "+", "' '", "+", "str", "(", "module", ".", "run_order", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "log", "(", "'\\n'", ",", "level", "=", "logging", ".", "DEBUG", ")", "return", "[", "]" ]
Dependency checking phase is performed in this method.
[ "Dependency", "checking", "phase", "is", "performed", "in", "this", "method", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4361-L4409
train
ianmiell/shutit
shutit_class.py
ShutIt.check_conflicts
def check_conflicts(self): """Checks for any conflicts between modules configured to be built. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # Now consider conflicts self.log('PHASE: conflicts', level=logging.DEBUG) errs = [] self.pause_point('\nNow checking for conflicts between modules', print_input=False, level=3) for module_id in self.module_ids(): if not cfg[module_id]['shutit.core.module.build']: continue conflicter = self.shutit_map[module_id] for conflictee in conflicter.conflicts_with: # If the module id isn't there, there's no problem. conflictee_obj = self.shutit_map.get(conflictee) if conflictee_obj is None: continue if ((cfg[conflicter.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(conflicter)) and (cfg[conflictee_obj.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(conflictee_obj))): errs.append(('conflicter module id: ' + conflicter.module_id + ' is configured to be built or is already built but conflicts with module_id: ' + conflictee_obj.module_id,)) return errs
python
def check_conflicts(self): """Checks for any conflicts between modules configured to be built. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # Now consider conflicts self.log('PHASE: conflicts', level=logging.DEBUG) errs = [] self.pause_point('\nNow checking for conflicts between modules', print_input=False, level=3) for module_id in self.module_ids(): if not cfg[module_id]['shutit.core.module.build']: continue conflicter = self.shutit_map[module_id] for conflictee in conflicter.conflicts_with: # If the module id isn't there, there's no problem. conflictee_obj = self.shutit_map.get(conflictee) if conflictee_obj is None: continue if ((cfg[conflicter.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(conflicter)) and (cfg[conflictee_obj.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(conflictee_obj))): errs.append(('conflicter module id: ' + conflicter.module_id + ' is configured to be built or is already built but conflicts with module_id: ' + conflictee_obj.module_id,)) return errs
[ "def", "check_conflicts", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "# Now consider conflicts", "self", ".", "log", "(", "'PHASE: conflicts'", ",", "level", "=", "logging", ".", "DEBUG", ")", "errs", "=", "[", "]", "self", ".", "pause_point", "(", "'\\nNow checking for conflicts between modules'", ",", "print_input", "=", "False", ",", "level", "=", "3", ")", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "if", "not", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.build'", "]", ":", "continue", "conflicter", "=", "self", ".", "shutit_map", "[", "module_id", "]", "for", "conflictee", "in", "conflicter", ".", "conflicts_with", ":", "# If the module id isn't there, there's no problem.", "conflictee_obj", "=", "self", ".", "shutit_map", ".", "get", "(", "conflictee", ")", "if", "conflictee_obj", "is", "None", ":", "continue", "if", "(", "(", "cfg", "[", "conflicter", ".", "module_id", "]", "[", "'shutit.core.module.build'", "]", "or", "self", ".", "is_to_be_built_or_is_installed", "(", "conflicter", ")", ")", "and", "(", "cfg", "[", "conflictee_obj", ".", "module_id", "]", "[", "'shutit.core.module.build'", "]", "or", "self", ".", "is_to_be_built_or_is_installed", "(", "conflictee_obj", ")", ")", ")", ":", "errs", ".", "append", "(", "(", "'conflicter module id: '", "+", "conflicter", ".", "module_id", "+", "' is configured to be built or is already built but conflicts with module_id: '", "+", "conflictee_obj", ".", "module_id", ",", ")", ")", "return", "errs" ]
Checks for any conflicts between modules configured to be built.
[ "Checks", "for", "any", "conflicts", "between", "modules", "configured", "to", "be", "built", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4412-L4435
train
ianmiell/shutit
shutit_class.py
ShutIt.do_remove
def do_remove(self, loglevel=logging.DEBUG): """Remove modules by calling remove method on those configured for removal. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # Now get the run_order keys in order and go. self.log('PHASE: remove', level=loglevel) self.pause_point('\nNow removing any modules that need removing', print_input=False, level=3) # Login at least once to get the exports. for module_id in self.module_ids(): module = self.shutit_map[module_id] self.log('considering whether to remove: ' + module_id, level=logging.DEBUG) if cfg[module_id]['shutit.core.module.remove']: self.log('removing: ' + module_id, level=logging.DEBUG) self.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False) if not module.remove(self): self.log(self.print_modules(), level=logging.DEBUG) self.fail(module_id + ' failed on remove', shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').pexpect_child) # pragma: no cover else: if self.build['delivery'] in ('docker','dockerfile'): # Create a directory and files to indicate this has been removed. self.send(' command mkdir -p ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + ' && command rm -f ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + '/built && command touch ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + '/removed', loglevel=loglevel, echo=False) # Remove from "installed" cache if module.module_id in self.get_current_shutit_pexpect_session_environment().modules_installed: self.get_current_shutit_pexpect_session_environment().modules_installed.remove(module.module_id) # Add to "not installed" cache self.get_current_shutit_pexpect_session_environment().modules_not_installed.append(module.module_id) self.logout(echo=False)
python
def do_remove(self, loglevel=logging.DEBUG): """Remove modules by calling remove method on those configured for removal. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # Now get the run_order keys in order and go. self.log('PHASE: remove', level=loglevel) self.pause_point('\nNow removing any modules that need removing', print_input=False, level=3) # Login at least once to get the exports. for module_id in self.module_ids(): module = self.shutit_map[module_id] self.log('considering whether to remove: ' + module_id, level=logging.DEBUG) if cfg[module_id]['shutit.core.module.remove']: self.log('removing: ' + module_id, level=logging.DEBUG) self.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False) if not module.remove(self): self.log(self.print_modules(), level=logging.DEBUG) self.fail(module_id + ' failed on remove', shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').pexpect_child) # pragma: no cover else: if self.build['delivery'] in ('docker','dockerfile'): # Create a directory and files to indicate this has been removed. self.send(' command mkdir -p ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + ' && command rm -f ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + '/built && command touch ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/module_record/' + module.module_id + '/removed', loglevel=loglevel, echo=False) # Remove from "installed" cache if module.module_id in self.get_current_shutit_pexpect_session_environment().modules_installed: self.get_current_shutit_pexpect_session_environment().modules_installed.remove(module.module_id) # Add to "not installed" cache self.get_current_shutit_pexpect_session_environment().modules_not_installed.append(module.module_id) self.logout(echo=False)
[ "def", "do_remove", "(", "self", ",", "loglevel", "=", "logging", ".", "DEBUG", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "# Now get the run_order keys in order and go.", "self", ".", "log", "(", "'PHASE: remove'", ",", "level", "=", "loglevel", ")", "self", ".", "pause_point", "(", "'\\nNow removing any modules that need removing'", ",", "print_input", "=", "False", ",", "level", "=", "3", ")", "# Login at least once to get the exports.", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "module", "=", "self", ".", "shutit_map", "[", "module_id", "]", "self", ".", "log", "(", "'considering whether to remove: '", "+", "module_id", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "cfg", "[", "module_id", "]", "[", "'shutit.core.module.remove'", "]", ":", "self", ".", "log", "(", "'removing: '", "+", "module_id", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "login", "(", "prompt_prefix", "=", "module_id", ",", "command", "=", "shutit_global", ".", "shutit_global_object", ".", "bash_startup_command", ",", "echo", "=", "False", ")", "if", "not", "module", ".", "remove", "(", "self", ")", ":", "self", ".", "log", "(", "self", ".", "print_modules", "(", ")", ",", "level", "=", "logging", ".", "DEBUG", ")", "self", ".", "fail", "(", "module_id", "+", "' failed on remove'", ",", "shutit_pexpect_child", "=", "self", ".", "get_shutit_pexpect_session_from_id", "(", "'target_child'", ")", ".", "pexpect_child", ")", "# pragma: no cover", "else", ":", "if", "self", ".", "build", "[", "'delivery'", "]", "in", "(", "'docker'", ",", "'dockerfile'", ")", ":", "# Create a directory and files to indicate this has been removed.", "self", ".", "send", "(", "' command mkdir -p '", "+", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir_build_db_dir", "+", "'/module_record/'", "+", "module", ".", "module_id", "+", "' && command rm -f '", "+", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir_build_db_dir", "+", "'/module_record/'", "+", "module", ".", "module_id", "+", "'/built && command touch '", "+", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir_build_db_dir", "+", "'/module_record/'", "+", "module", ".", "module_id", "+", "'/removed'", ",", "loglevel", "=", "loglevel", ",", "echo", "=", "False", ")", "# Remove from \"installed\" cache", "if", "module", ".", "module_id", "in", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_installed", ":", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_installed", ".", "remove", "(", "module", ".", "module_id", ")", "# Add to \"not installed\" cache", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "modules_not_installed", ".", "append", "(", "module", ".", "module_id", ")", "self", ".", "logout", "(", "echo", "=", "False", ")" ]
Remove modules by calling remove method on those configured for removal.
[ "Remove", "modules", "by", "calling", "remove", "method", "on", "those", "configured", "for", "removal", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4466-L4493
train
ianmiell/shutit
shutit_class.py
ShutIt.do_build
def do_build(self): """Runs build phase, building any modules that we've determined need building. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg self.log('PHASE: build, repository work', level=logging.DEBUG) module_id_list = self.module_ids() if self.build['deps_only']: module_id_list_build_only = filter(lambda x: cfg[x]['shutit.core.module.build'], module_id_list) for module_id in module_id_list: module = self.shutit_map[module_id] self.log('Considering whether to build: ' + module.module_id, level=logging.INFO) if cfg[module.module_id]['shutit.core.module.build']: if self.build['delivery'] not in module.ok_delivery_methods: self.fail('Module: ' + module.module_id + ' can only be built with one of these --delivery methods: ' + str(module.ok_delivery_methods) + '\nSee shutit build -h for more info, or try adding: --delivery <method> to your shutit invocation') # pragma: no cover if self.is_installed(module): self.build['report'] = (self.build['report'] + '\nBuilt already: ' + module.module_id + ' with run order: ' + str(module.run_order)) else: # We move to the module directory to perform the build, returning immediately afterwards. if self.build['deps_only'] and module_id == module_id_list_build_only[-1]: # If this is the last module, and we are only building deps, stop here. self.build['report'] = (self.build['report'] + '\nSkipping: ' + module.module_id + ' with run order: ' + str(module.run_order) + '\n\tas this is the final module and we are building dependencies only') else: revert_dir = os.getcwd() self.get_current_shutit_pexpect_session_environment().module_root_dir = os.path.dirname(self.shutit_file_map[module_id]) self.chdir(self.get_current_shutit_pexpect_session_environment().module_root_dir) self.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False) self.build_module(module) self.logout(echo=False) self.chdir(revert_dir) if self.is_installed(module): self.log('Starting module',level=logging.DEBUG) if not module.start(self): self.fail(module.module_id + ' failed on start', shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').pexpect_child)
python
def do_build(self): """Runs build phase, building any modules that we've determined need building. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg self.log('PHASE: build, repository work', level=logging.DEBUG) module_id_list = self.module_ids() if self.build['deps_only']: module_id_list_build_only = filter(lambda x: cfg[x]['shutit.core.module.build'], module_id_list) for module_id in module_id_list: module = self.shutit_map[module_id] self.log('Considering whether to build: ' + module.module_id, level=logging.INFO) if cfg[module.module_id]['shutit.core.module.build']: if self.build['delivery'] not in module.ok_delivery_methods: self.fail('Module: ' + module.module_id + ' can only be built with one of these --delivery methods: ' + str(module.ok_delivery_methods) + '\nSee shutit build -h for more info, or try adding: --delivery <method> to your shutit invocation') # pragma: no cover if self.is_installed(module): self.build['report'] = (self.build['report'] + '\nBuilt already: ' + module.module_id + ' with run order: ' + str(module.run_order)) else: # We move to the module directory to perform the build, returning immediately afterwards. if self.build['deps_only'] and module_id == module_id_list_build_only[-1]: # If this is the last module, and we are only building deps, stop here. self.build['report'] = (self.build['report'] + '\nSkipping: ' + module.module_id + ' with run order: ' + str(module.run_order) + '\n\tas this is the final module and we are building dependencies only') else: revert_dir = os.getcwd() self.get_current_shutit_pexpect_session_environment().module_root_dir = os.path.dirname(self.shutit_file_map[module_id]) self.chdir(self.get_current_shutit_pexpect_session_environment().module_root_dir) self.login(prompt_prefix=module_id,command=shutit_global.shutit_global_object.bash_startup_command,echo=False) self.build_module(module) self.logout(echo=False) self.chdir(revert_dir) if self.is_installed(module): self.log('Starting module',level=logging.DEBUG) if not module.start(self): self.fail(module.module_id + ' failed on start', shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').pexpect_child)
[ "def", "do_build", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "self", ".", "log", "(", "'PHASE: build, repository work'", ",", "level", "=", "logging", ".", "DEBUG", ")", "module_id_list", "=", "self", ".", "module_ids", "(", ")", "if", "self", ".", "build", "[", "'deps_only'", "]", ":", "module_id_list_build_only", "=", "filter", "(", "lambda", "x", ":", "cfg", "[", "x", "]", "[", "'shutit.core.module.build'", "]", ",", "module_id_list", ")", "for", "module_id", "in", "module_id_list", ":", "module", "=", "self", ".", "shutit_map", "[", "module_id", "]", "self", ".", "log", "(", "'Considering whether to build: '", "+", "module", ".", "module_id", ",", "level", "=", "logging", ".", "INFO", ")", "if", "cfg", "[", "module", ".", "module_id", "]", "[", "'shutit.core.module.build'", "]", ":", "if", "self", ".", "build", "[", "'delivery'", "]", "not", "in", "module", ".", "ok_delivery_methods", ":", "self", ".", "fail", "(", "'Module: '", "+", "module", ".", "module_id", "+", "' can only be built with one of these --delivery methods: '", "+", "str", "(", "module", ".", "ok_delivery_methods", ")", "+", "'\\nSee shutit build -h for more info, or try adding: --delivery <method> to your shutit invocation'", ")", "# pragma: no cover", "if", "self", ".", "is_installed", "(", "module", ")", ":", "self", ".", "build", "[", "'report'", "]", "=", "(", "self", ".", "build", "[", "'report'", "]", "+", "'\\nBuilt already: '", "+", "module", ".", "module_id", "+", "' with run order: '", "+", "str", "(", "module", ".", "run_order", ")", ")", "else", ":", "# We move to the module directory to perform the build, returning immediately afterwards.", "if", "self", ".", "build", "[", "'deps_only'", "]", "and", "module_id", "==", "module_id_list_build_only", "[", "-", "1", "]", ":", "# If this is the last module, and we are only building deps, stop here.", "self", ".", "build", "[", "'report'", "]", "=", "(", "self", ".", "build", "[", "'report'", "]", "+", "'\\nSkipping: '", "+", "module", ".", "module_id", "+", "' with run order: '", "+", "str", "(", "module", ".", "run_order", ")", "+", "'\\n\\tas this is the final module and we are building dependencies only'", ")", "else", ":", "revert_dir", "=", "os", ".", "getcwd", "(", ")", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "module_root_dir", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "shutit_file_map", "[", "module_id", "]", ")", "self", ".", "chdir", "(", "self", ".", "get_current_shutit_pexpect_session_environment", "(", ")", ".", "module_root_dir", ")", "self", ".", "login", "(", "prompt_prefix", "=", "module_id", ",", "command", "=", "shutit_global", ".", "shutit_global_object", ".", "bash_startup_command", ",", "echo", "=", "False", ")", "self", ".", "build_module", "(", "module", ")", "self", ".", "logout", "(", "echo", "=", "False", ")", "self", ".", "chdir", "(", "revert_dir", ")", "if", "self", ".", "is_installed", "(", "module", ")", ":", "self", ".", "log", "(", "'Starting module'", ",", "level", "=", "logging", ".", "DEBUG", ")", "if", "not", "module", ".", "start", "(", "self", ")", ":", "self", ".", "fail", "(", "module", ".", "module_id", "+", "' failed on start'", ",", "shutit_pexpect_child", "=", "self", ".", "get_shutit_pexpect_session_from_id", "(", "'target_child'", ")", ".", "pexpect_child", ")" ]
Runs build phase, building any modules that we've determined need building.
[ "Runs", "build", "phase", "building", "any", "modules", "that", "we", "ve", "determined", "need", "building", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4535-L4569
train
ianmiell/shutit
shutit_class.py
ShutIt.stop_all
def stop_all(self, run_order=-1): """Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc. """ shutit_global.shutit_global_object.yield_to_draw() # sort them so they're stopped in reverse order for module_id in self.module_ids(rev=True): shutit_module_obj = self.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if self.is_installed(shutit_module_obj): if not shutit_module_obj.stop(self): self.fail('failed to stop: ' + module_id, shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').shutit_pexpect_child)
python
def stop_all(self, run_order=-1): """Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc. """ shutit_global.shutit_global_object.yield_to_draw() # sort them so they're stopped in reverse order for module_id in self.module_ids(rev=True): shutit_module_obj = self.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if self.is_installed(shutit_module_obj): if not shutit_module_obj.stop(self): self.fail('failed to stop: ' + module_id, shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').shutit_pexpect_child)
[ "def", "stop_all", "(", "self", ",", "run_order", "=", "-", "1", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# sort them so they're stopped in reverse order", "for", "module_id", "in", "self", ".", "module_ids", "(", "rev", "=", "True", ")", ":", "shutit_module_obj", "=", "self", ".", "shutit_map", "[", "module_id", "]", "if", "run_order", "==", "-", "1", "or", "shutit_module_obj", ".", "run_order", "<=", "run_order", ":", "if", "self", ".", "is_installed", "(", "shutit_module_obj", ")", ":", "if", "not", "shutit_module_obj", ".", "stop", "(", "self", ")", ":", "self", ".", "fail", "(", "'failed to stop: '", "+", "module_id", ",", "shutit_pexpect_child", "=", "self", ".", "get_shutit_pexpect_session_from_id", "(", "'target_child'", ")", ".", "shutit_pexpect_child", ")" ]
Runs stop method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we clean up state before committing run files etc.
[ "Runs", "stop", "method", "on", "all", "modules", "less", "than", "the", "passed", "-", "in", "run_order", ".", "Used", "when", "target", "is", "exporting", "itself", "mid", "-", "build", "so", "we", "clean", "up", "state", "before", "committing", "run", "files", "etc", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4615-L4627
train
ianmiell/shutit
shutit_class.py
ShutIt.start_all
def start_all(self, run_order=-1): """Runs start method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we can export a clean target and still depended-on modules running if necessary. """ shutit_global.shutit_global_object.yield_to_draw() # sort them so they're started in order for module_id in self.module_ids(): shutit_module_obj = self.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if self.is_installed(shutit_module_obj): if not shutit_module_obj.start(self): self.fail('failed to start: ' + module_id, shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').shutit_pexpect_child)
python
def start_all(self, run_order=-1): """Runs start method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we can export a clean target and still depended-on modules running if necessary. """ shutit_global.shutit_global_object.yield_to_draw() # sort them so they're started in order for module_id in self.module_ids(): shutit_module_obj = self.shutit_map[module_id] if run_order == -1 or shutit_module_obj.run_order <= run_order: if self.is_installed(shutit_module_obj): if not shutit_module_obj.start(self): self.fail('failed to start: ' + module_id, shutit_pexpect_child=self.get_shutit_pexpect_session_from_id('target_child').shutit_pexpect_child)
[ "def", "start_all", "(", "self", ",", "run_order", "=", "-", "1", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# sort them so they're started in order", "for", "module_id", "in", "self", ".", "module_ids", "(", ")", ":", "shutit_module_obj", "=", "self", ".", "shutit_map", "[", "module_id", "]", "if", "run_order", "==", "-", "1", "or", "shutit_module_obj", ".", "run_order", "<=", "run_order", ":", "if", "self", ".", "is_installed", "(", "shutit_module_obj", ")", ":", "if", "not", "shutit_module_obj", ".", "start", "(", "self", ")", ":", "self", ".", "fail", "(", "'failed to start: '", "+", "module_id", ",", "shutit_pexpect_child", "=", "self", ".", "get_shutit_pexpect_session_from_id", "(", "'target_child'", ")", ".", "shutit_pexpect_child", ")" ]
Runs start method on all modules less than the passed-in run_order. Used when target is exporting itself mid-build, so we can export a clean target and still depended-on modules running if necessary.
[ "Runs", "start", "method", "on", "all", "modules", "less", "than", "the", "passed", "-", "in", "run_order", ".", "Used", "when", "target", "is", "exporting", "itself", "mid", "-", "build", "so", "we", "can", "export", "a", "clean", "target", "and", "still", "depended", "-", "on", "modules", "running", "if", "necessary", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4631-L4643
train
ianmiell/shutit
shutit_class.py
ShutIt.init_shutit_map
def init_shutit_map(self): """Initializes the module map of shutit based on the modules we have gathered. Checks we have core modules Checks for duplicate module details. Sets up common config. Sets up map of modules. """ shutit_global.shutit_global_object.yield_to_draw() modules = self.shutit_modules # Have we got anything to process outside of special modules? if len([mod for mod in modules if mod.run_order > 0]) < 1: self.log(modules,level=logging.DEBUG) path = ':'.join(self.host['shutit_module_path']) self.log('\nIf you are new to ShutIt, see:\n\n\thttp://ianmiell.github.io/shutit/\n\nor try running\n\n\tshutit skeleton\n\n',level=logging.INFO) if path == '': self.fail('No ShutIt modules aside from core ones found and no ShutIt module path given.\nDid you set --shutit_module_path/-m wrongly?\n') # pragma: no cover elif path == '.': self.fail('No modules aside from core ones found and no ShutIt module path given apart from default (.).\n\n- Did you set --shutit_module_path/-m?\n- Is there a STOP* file in your . dir?') # pragma: no cover else: self.fail('No modules aside from core ones found and no ShutIt modules in path:\n\n' + path + '\n\nor their subfolders. Check your --shutit_module_path/-m setting and check that there are ShutIt modules below without STOP* files in any relevant directories.') # pragma: no cover self.log('PHASE: base setup', level=logging.DEBUG) run_orders = {} has_core_module = False for module in modules: assert isinstance(module, ShutItModule), shutit_util.print_debug() if module.module_id in self.shutit_map: self.fail('Duplicated module id: ' + module.module_id + '\n\nYou may want to check your --shutit_module_path setting') # pragma: no cover if module.run_order in run_orders: self.fail('Duplicate run order: ' + str(module.run_order) + ' for ' + module.module_id + ' and ' + run_orders[module.run_order].module_id + '\n\nYou may want to check your --shutit_module_path setting') # pragma: no cover if module.run_order == 0: has_core_module = True self.shutit_map[module.module_id] = run_orders[module.run_order] = module self.shutit_file_map[module.module_id] = get_module_file(self, module) if not has_core_module: self.fail('No module with run_order=0 specified! This is required.')
python
def init_shutit_map(self): """Initializes the module map of shutit based on the modules we have gathered. Checks we have core modules Checks for duplicate module details. Sets up common config. Sets up map of modules. """ shutit_global.shutit_global_object.yield_to_draw() modules = self.shutit_modules # Have we got anything to process outside of special modules? if len([mod for mod in modules if mod.run_order > 0]) < 1: self.log(modules,level=logging.DEBUG) path = ':'.join(self.host['shutit_module_path']) self.log('\nIf you are new to ShutIt, see:\n\n\thttp://ianmiell.github.io/shutit/\n\nor try running\n\n\tshutit skeleton\n\n',level=logging.INFO) if path == '': self.fail('No ShutIt modules aside from core ones found and no ShutIt module path given.\nDid you set --shutit_module_path/-m wrongly?\n') # pragma: no cover elif path == '.': self.fail('No modules aside from core ones found and no ShutIt module path given apart from default (.).\n\n- Did you set --shutit_module_path/-m?\n- Is there a STOP* file in your . dir?') # pragma: no cover else: self.fail('No modules aside from core ones found and no ShutIt modules in path:\n\n' + path + '\n\nor their subfolders. Check your --shutit_module_path/-m setting and check that there are ShutIt modules below without STOP* files in any relevant directories.') # pragma: no cover self.log('PHASE: base setup', level=logging.DEBUG) run_orders = {} has_core_module = False for module in modules: assert isinstance(module, ShutItModule), shutit_util.print_debug() if module.module_id in self.shutit_map: self.fail('Duplicated module id: ' + module.module_id + '\n\nYou may want to check your --shutit_module_path setting') # pragma: no cover if module.run_order in run_orders: self.fail('Duplicate run order: ' + str(module.run_order) + ' for ' + module.module_id + ' and ' + run_orders[module.run_order].module_id + '\n\nYou may want to check your --shutit_module_path setting') # pragma: no cover if module.run_order == 0: has_core_module = True self.shutit_map[module.module_id] = run_orders[module.run_order] = module self.shutit_file_map[module.module_id] = get_module_file(self, module) if not has_core_module: self.fail('No module with run_order=0 specified! This is required.')
[ "def", "init_shutit_map", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "modules", "=", "self", ".", "shutit_modules", "# Have we got anything to process outside of special modules?", "if", "len", "(", "[", "mod", "for", "mod", "in", "modules", "if", "mod", ".", "run_order", ">", "0", "]", ")", "<", "1", ":", "self", ".", "log", "(", "modules", ",", "level", "=", "logging", ".", "DEBUG", ")", "path", "=", "':'", ".", "join", "(", "self", ".", "host", "[", "'shutit_module_path'", "]", ")", "self", ".", "log", "(", "'\\nIf you are new to ShutIt, see:\\n\\n\\thttp://ianmiell.github.io/shutit/\\n\\nor try running\\n\\n\\tshutit skeleton\\n\\n'", ",", "level", "=", "logging", ".", "INFO", ")", "if", "path", "==", "''", ":", "self", ".", "fail", "(", "'No ShutIt modules aside from core ones found and no ShutIt module path given.\\nDid you set --shutit_module_path/-m wrongly?\\n'", ")", "# pragma: no cover", "elif", "path", "==", "'.'", ":", "self", ".", "fail", "(", "'No modules aside from core ones found and no ShutIt module path given apart from default (.).\\n\\n- Did you set --shutit_module_path/-m?\\n- Is there a STOP* file in your . dir?'", ")", "# pragma: no cover", "else", ":", "self", ".", "fail", "(", "'No modules aside from core ones found and no ShutIt modules in path:\\n\\n'", "+", "path", "+", "'\\n\\nor their subfolders. Check your --shutit_module_path/-m setting and check that there are ShutIt modules below without STOP* files in any relevant directories.'", ")", "# pragma: no cover", "self", ".", "log", "(", "'PHASE: base setup'", ",", "level", "=", "logging", ".", "DEBUG", ")", "run_orders", "=", "{", "}", "has_core_module", "=", "False", "for", "module", "in", "modules", ":", "assert", "isinstance", "(", "module", ",", "ShutItModule", ")", ",", "shutit_util", ".", "print_debug", "(", ")", "if", "module", ".", "module_id", "in", "self", ".", "shutit_map", ":", "self", ".", "fail", "(", "'Duplicated module id: '", "+", "module", ".", "module_id", "+", "'\\n\\nYou may want to check your --shutit_module_path setting'", ")", "# pragma: no cover", "if", "module", ".", "run_order", "in", "run_orders", ":", "self", ".", "fail", "(", "'Duplicate run order: '", "+", "str", "(", "module", ".", "run_order", ")", "+", "' for '", "+", "module", ".", "module_id", "+", "' and '", "+", "run_orders", "[", "module", ".", "run_order", "]", ".", "module_id", "+", "'\\n\\nYou may want to check your --shutit_module_path setting'", ")", "# pragma: no cover", "if", "module", ".", "run_order", "==", "0", ":", "has_core_module", "=", "True", "self", ".", "shutit_map", "[", "module", ".", "module_id", "]", "=", "run_orders", "[", "module", ".", "run_order", "]", "=", "module", "self", ".", "shutit_file_map", "[", "module", ".", "module_id", "]", "=", "get_module_file", "(", "self", ",", "module", ")", "if", "not", "has_core_module", ":", "self", ".", "fail", "(", "'No module with run_order=0 specified! This is required.'", ")" ]
Initializes the module map of shutit based on the modules we have gathered. Checks we have core modules Checks for duplicate module details. Sets up common config. Sets up map of modules.
[ "Initializes", "the", "module", "map", "of", "shutit", "based", "on", "the", "modules", "we", "have", "gathered", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4661-L4700
train
ianmiell/shutit
shutit_class.py
ShutIt.conn_target
def conn_target(self): """Connect to the target. """ shutit_global.shutit_global_object.yield_to_draw() conn_module = None for mod in self.conn_modules: if mod.module_id == self.build['conn_module']: conn_module = mod break if conn_module is None: self.fail('Couldn\'t find conn_module ' + self.build['conn_module']) # pragma: no cover # Set up the target in pexpect. conn_module.get_config(self) conn_module.build(self)
python
def conn_target(self): """Connect to the target. """ shutit_global.shutit_global_object.yield_to_draw() conn_module = None for mod in self.conn_modules: if mod.module_id == self.build['conn_module']: conn_module = mod break if conn_module is None: self.fail('Couldn\'t find conn_module ' + self.build['conn_module']) # pragma: no cover # Set up the target in pexpect. conn_module.get_config(self) conn_module.build(self)
[ "def", "conn_target", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "conn_module", "=", "None", "for", "mod", "in", "self", ".", "conn_modules", ":", "if", "mod", ".", "module_id", "==", "self", ".", "build", "[", "'conn_module'", "]", ":", "conn_module", "=", "mod", "break", "if", "conn_module", "is", "None", ":", "self", ".", "fail", "(", "'Couldn\\'t find conn_module '", "+", "self", ".", "build", "[", "'conn_module'", "]", ")", "# pragma: no cover", "# Set up the target in pexpect.", "conn_module", ".", "get_config", "(", "self", ")", "conn_module", ".", "build", "(", "self", ")" ]
Connect to the target.
[ "Connect", "to", "the", "target", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4703-L4717
train
ianmiell/shutit
shutit_class.py
ShutIt.finalize_target
def finalize_target(self): """Finalize the target using the core finalize method. """ shutit_global.shutit_global_object.yield_to_draw() self.pause_point('\nFinalizing the target module (' + self.shutit_main_dir + '/shutit_setup.py)', print_input=False, level=3) # Can assume conn_module exists at this point for mod in self.conn_modules: if mod.module_id == self.build['conn_module']: conn_module = mod break conn_module.finalize(self)
python
def finalize_target(self): """Finalize the target using the core finalize method. """ shutit_global.shutit_global_object.yield_to_draw() self.pause_point('\nFinalizing the target module (' + self.shutit_main_dir + '/shutit_setup.py)', print_input=False, level=3) # Can assume conn_module exists at this point for mod in self.conn_modules: if mod.module_id == self.build['conn_module']: conn_module = mod break conn_module.finalize(self)
[ "def", "finalize_target", "(", "self", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "pause_point", "(", "'\\nFinalizing the target module ('", "+", "self", ".", "shutit_main_dir", "+", "'/shutit_setup.py)'", ",", "print_input", "=", "False", ",", "level", "=", "3", ")", "# Can assume conn_module exists at this point", "for", "mod", "in", "self", ".", "conn_modules", ":", "if", "mod", ".", "module_id", "==", "self", ".", "build", "[", "'conn_module'", "]", ":", "conn_module", "=", "mod", "break", "conn_module", ".", "finalize", "(", "self", ")" ]
Finalize the target using the core finalize method.
[ "Finalize", "the", "target", "using", "the", "core", "finalize", "method", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4720-L4730
train
ianmiell/shutit
shutit_class.py
ShutIt.resolve_dependencies
def resolve_dependencies(self, to_build, depender): """Add any required dependencies. """ shutit_global.shutit_global_object.yield_to_draw() self.log('In resolve_dependencies',level=logging.DEBUG) cfg = self.cfg for dependee_id in depender.depends_on: dependee = self.shutit_map.get(dependee_id) # Don't care if module doesn't exist, we check this later if (dependee and dependee not in to_build and cfg[dependee_id]['shutit.core.module.build_ifneeded']): to_build.append(dependee) cfg[dependee_id]['shutit.core.module.build'] = True return True
python
def resolve_dependencies(self, to_build, depender): """Add any required dependencies. """ shutit_global.shutit_global_object.yield_to_draw() self.log('In resolve_dependencies',level=logging.DEBUG) cfg = self.cfg for dependee_id in depender.depends_on: dependee = self.shutit_map.get(dependee_id) # Don't care if module doesn't exist, we check this later if (dependee and dependee not in to_build and cfg[dependee_id]['shutit.core.module.build_ifneeded']): to_build.append(dependee) cfg[dependee_id]['shutit.core.module.build'] = True return True
[ "def", "resolve_dependencies", "(", "self", ",", "to_build", ",", "depender", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "self", ".", "log", "(", "'In resolve_dependencies'", ",", "level", "=", "logging", ".", "DEBUG", ")", "cfg", "=", "self", ".", "cfg", "for", "dependee_id", "in", "depender", ".", "depends_on", ":", "dependee", "=", "self", ".", "shutit_map", ".", "get", "(", "dependee_id", ")", "# Don't care if module doesn't exist, we check this later", "if", "(", "dependee", "and", "dependee", "not", "in", "to_build", "and", "cfg", "[", "dependee_id", "]", "[", "'shutit.core.module.build_ifneeded'", "]", ")", ":", "to_build", ".", "append", "(", "dependee", ")", "cfg", "[", "dependee_id", "]", "[", "'shutit.core.module.build'", "]", "=", "True", "return", "True" ]
Add any required dependencies.
[ "Add", "any", "required", "dependencies", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4735-L4748
train
ianmiell/shutit
shutit_class.py
ShutIt.check_dependee_exists
def check_dependee_exists(self, depender, dependee, dependee_id): """Checks whether a depended-on module is available. """ shutit_global.shutit_global_object.yield_to_draw() # If the module id isn't there, there's a problem. if dependee is None: return 'module: \n\n' + dependee_id + '\n\nnot found in paths: ' + str(self.host['shutit_module_path']) + ' but needed for ' + depender.module_id + '\nCheck your --shutit_module_path setting and ensure that all modules configured to be built are in that path setting, eg "--shutit_module_path /path/to/other/module/:."\n\nAlso check that the module is configured to be built with the correct module id in that module\'s configs/build.cnf file.\n\nSee also help.' return ''
python
def check_dependee_exists(self, depender, dependee, dependee_id): """Checks whether a depended-on module is available. """ shutit_global.shutit_global_object.yield_to_draw() # If the module id isn't there, there's a problem. if dependee is None: return 'module: \n\n' + dependee_id + '\n\nnot found in paths: ' + str(self.host['shutit_module_path']) + ' but needed for ' + depender.module_id + '\nCheck your --shutit_module_path setting and ensure that all modules configured to be built are in that path setting, eg "--shutit_module_path /path/to/other/module/:."\n\nAlso check that the module is configured to be built with the correct module id in that module\'s configs/build.cnf file.\n\nSee also help.' return ''
[ "def", "check_dependee_exists", "(", "self", ",", "depender", ",", "dependee", ",", "dependee_id", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "# If the module id isn't there, there's a problem.", "if", "dependee", "is", "None", ":", "return", "'module: \\n\\n'", "+", "dependee_id", "+", "'\\n\\nnot found in paths: '", "+", "str", "(", "self", ".", "host", "[", "'shutit_module_path'", "]", ")", "+", "' but needed for '", "+", "depender", ".", "module_id", "+", "'\\nCheck your --shutit_module_path setting and ensure that all modules configured to be built are in that path setting, eg \"--shutit_module_path /path/to/other/module/:.\"\\n\\nAlso check that the module is configured to be built with the correct module id in that module\\'s configs/build.cnf file.\\n\\nSee also help.'", "return", "''" ]
Checks whether a depended-on module is available.
[ "Checks", "whether", "a", "depended", "-", "on", "module", "is", "available", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4751-L4758
train
ianmiell/shutit
shutit_class.py
ShutIt.check_dependee_build
def check_dependee_build(self, depender, dependee, dependee_id): """Checks whether a depended on module is configured to be built. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # If depender is installed or will be installed, so must the dependee if not (cfg[dependee.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(dependee)): return 'depender module id:\n\n[' + depender.module_id + ']\n\nis configured: "build:yes" or is already built but dependee module_id:\n\n[' + dependee_id + ']\n\n is not configured: "build:yes"' return ''
python
def check_dependee_build(self, depender, dependee, dependee_id): """Checks whether a depended on module is configured to be built. """ shutit_global.shutit_global_object.yield_to_draw() cfg = self.cfg # If depender is installed or will be installed, so must the dependee if not (cfg[dependee.module_id]['shutit.core.module.build'] or self.is_to_be_built_or_is_installed(dependee)): return 'depender module id:\n\n[' + depender.module_id + ']\n\nis configured: "build:yes" or is already built but dependee module_id:\n\n[' + dependee_id + ']\n\n is not configured: "build:yes"' return ''
[ "def", "check_dependee_build", "(", "self", ",", "depender", ",", "dependee", ",", "dependee_id", ")", ":", "shutit_global", ".", "shutit_global_object", ".", "yield_to_draw", "(", ")", "cfg", "=", "self", ".", "cfg", "# If depender is installed or will be installed, so must the dependee", "if", "not", "(", "cfg", "[", "dependee", ".", "module_id", "]", "[", "'shutit.core.module.build'", "]", "or", "self", ".", "is_to_be_built_or_is_installed", "(", "dependee", ")", ")", ":", "return", "'depender module id:\\n\\n['", "+", "depender", ".", "module_id", "+", "']\\n\\nis configured: \"build:yes\" or is already built but dependee module_id:\\n\\n['", "+", "dependee_id", "+", "']\\n\\n is not configured: \"build:yes\"'", "return", "''" ]
Checks whether a depended on module is configured to be built.
[ "Checks", "whether", "a", "depended", "on", "module", "is", "configured", "to", "be", "built", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4761-L4770
train
ianmiell/shutit
shutit_class.py
ShutIt.destroy
def destroy(self): """Finish up a session. """ if self.session_type == 'bash': # TODO: does this work/handle already being logged out/logged in deep OK? self.logout() elif self.session_type == 'vagrant': # TODO: does this work/handle already being logged out/logged in deep OK? self.logout()
python
def destroy(self): """Finish up a session. """ if self.session_type == 'bash': # TODO: does this work/handle already being logged out/logged in deep OK? self.logout() elif self.session_type == 'vagrant': # TODO: does this work/handle already being logged out/logged in deep OK? self.logout()
[ "def", "destroy", "(", "self", ")", ":", "if", "self", ".", "session_type", "==", "'bash'", ":", "# TODO: does this work/handle already being logged out/logged in deep OK?", "self", ".", "logout", "(", ")", "elif", "self", ".", "session_type", "==", "'vagrant'", ":", "# TODO: does this work/handle already being logged out/logged in deep OK?", "self", ".", "logout", "(", ")" ]
Finish up a session.
[ "Finish", "up", "a", "session", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_class.py#L4858-L4866
train
ianmiell/shutit
shutit_module.py
shutit_method_scope
def shutit_method_scope(func): """Notifies the ShutIt object whenever we call a shutit module method. This allows setting values for the 'scope' of a function. """ def wrapper(self, shutit): """Wrapper to call a shutit module method, notifying the ShutIt object. """ ret = func(self, shutit) return ret return wrapper
python
def shutit_method_scope(func): """Notifies the ShutIt object whenever we call a shutit module method. This allows setting values for the 'scope' of a function. """ def wrapper(self, shutit): """Wrapper to call a shutit module method, notifying the ShutIt object. """ ret = func(self, shutit) return ret return wrapper
[ "def", "shutit_method_scope", "(", "func", ")", ":", "def", "wrapper", "(", "self", ",", "shutit", ")", ":", "\"\"\"Wrapper to call a shutit module method, notifying the ShutIt object.\n\t\t\"\"\"", "ret", "=", "func", "(", "self", ",", "shutit", ")", "return", "ret", "return", "wrapper" ]
Notifies the ShutIt object whenever we call a shutit module method. This allows setting values for the 'scope' of a function.
[ "Notifies", "the", "ShutIt", "object", "whenever", "we", "call", "a", "shutit", "module", "method", ".", "This", "allows", "setting", "values", "for", "the", "scope", "of", "a", "function", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_module.py#L53-L62
train
ianmiell/shutit
shutit_threads.py
managing_thread_main_simple
def managing_thread_main_simple(): """Simpler thread to track whether main thread has been quiet for long enough that a thread dump should be printed. """ import shutit_global last_msg = '' while True: printed_anything = False if shutit_global.shutit_global_object.log_trace_when_idle and time.time() - shutit_global.shutit_global_object.last_log_time > 10: this_msg = '' this_header = '' for thread_id, stack in sys._current_frames().items(): # ignore own thread: if thread_id == threading.current_thread().ident: continue printed_thread_started = False for filename, lineno, name, line in traceback.extract_stack(stack): if not printed_anything: printed_anything = True this_header += '\n='*80 + '\n' this_header += 'STACK TRACES PRINTED ON IDLE: THREAD_ID: ' + str(thread_id) + ' at ' + time.strftime('%c') + '\n' this_header += '='*80 + '\n' if not printed_thread_started: printed_thread_started = True this_msg += '%s:%d:%s' % (filename, lineno, name) + '\n' if line: this_msg += ' %s' % (line,) + '\n' if printed_anything: this_msg += '='*80 + '\n' this_msg += 'STACK TRACES DONE\n' this_msg += '='*80 + '\n' if this_msg != last_msg: print(this_header + this_msg) last_msg = this_msg time.sleep(5)
python
def managing_thread_main_simple(): """Simpler thread to track whether main thread has been quiet for long enough that a thread dump should be printed. """ import shutit_global last_msg = '' while True: printed_anything = False if shutit_global.shutit_global_object.log_trace_when_idle and time.time() - shutit_global.shutit_global_object.last_log_time > 10: this_msg = '' this_header = '' for thread_id, stack in sys._current_frames().items(): # ignore own thread: if thread_id == threading.current_thread().ident: continue printed_thread_started = False for filename, lineno, name, line in traceback.extract_stack(stack): if not printed_anything: printed_anything = True this_header += '\n='*80 + '\n' this_header += 'STACK TRACES PRINTED ON IDLE: THREAD_ID: ' + str(thread_id) + ' at ' + time.strftime('%c') + '\n' this_header += '='*80 + '\n' if not printed_thread_started: printed_thread_started = True this_msg += '%s:%d:%s' % (filename, lineno, name) + '\n' if line: this_msg += ' %s' % (line,) + '\n' if printed_anything: this_msg += '='*80 + '\n' this_msg += 'STACK TRACES DONE\n' this_msg += '='*80 + '\n' if this_msg != last_msg: print(this_header + this_msg) last_msg = this_msg time.sleep(5)
[ "def", "managing_thread_main_simple", "(", ")", ":", "import", "shutit_global", "last_msg", "=", "''", "while", "True", ":", "printed_anything", "=", "False", "if", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "and", "time", ".", "time", "(", ")", "-", "shutit_global", ".", "shutit_global_object", ".", "last_log_time", ">", "10", ":", "this_msg", "=", "''", "this_header", "=", "''", "for", "thread_id", ",", "stack", "in", "sys", ".", "_current_frames", "(", ")", ".", "items", "(", ")", ":", "# ignore own thread:", "if", "thread_id", "==", "threading", ".", "current_thread", "(", ")", ".", "ident", ":", "continue", "printed_thread_started", "=", "False", "for", "filename", ",", "lineno", ",", "name", ",", "line", "in", "traceback", ".", "extract_stack", "(", "stack", ")", ":", "if", "not", "printed_anything", ":", "printed_anything", "=", "True", "this_header", "+=", "'\\n='", "*", "80", "+", "'\\n'", "this_header", "+=", "'STACK TRACES PRINTED ON IDLE: THREAD_ID: '", "+", "str", "(", "thread_id", ")", "+", "' at '", "+", "time", ".", "strftime", "(", "'%c'", ")", "+", "'\\n'", "this_header", "+=", "'='", "*", "80", "+", "'\\n'", "if", "not", "printed_thread_started", ":", "printed_thread_started", "=", "True", "this_msg", "+=", "'%s:%d:%s'", "%", "(", "filename", ",", "lineno", ",", "name", ")", "+", "'\\n'", "if", "line", ":", "this_msg", "+=", "' %s'", "%", "(", "line", ",", ")", "+", "'\\n'", "if", "printed_anything", ":", "this_msg", "+=", "'='", "*", "80", "+", "'\\n'", "this_msg", "+=", "'STACK TRACES DONE\\n'", "this_msg", "+=", "'='", "*", "80", "+", "'\\n'", "if", "this_msg", "!=", "last_msg", ":", "print", "(", "this_header", "+", "this_msg", ")", "last_msg", "=", "this_msg", "time", ".", "sleep", "(", "5", ")" ]
Simpler thread to track whether main thread has been quiet for long enough that a thread dump should be printed.
[ "Simpler", "thread", "to", "track", "whether", "main", "thread", "has", "been", "quiet", "for", "long", "enough", "that", "a", "thread", "dump", "should", "be", "printed", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_threads.py#L138-L172
train
ianmiell/shutit
package_map.py
map_package
def map_package(shutit_pexpect_session, package, install_type): """If package mapping exists, then return it, else return package. """ if package in PACKAGE_MAP.keys(): for itype in PACKAGE_MAP[package].keys(): if itype == install_type: ret = PACKAGE_MAP[package][install_type] if isinstance(ret,str): return ret if callable(ret): ret(shutit_pexpect_session) return '' # Otherwise, simply return package return package
python
def map_package(shutit_pexpect_session, package, install_type): """If package mapping exists, then return it, else return package. """ if package in PACKAGE_MAP.keys(): for itype in PACKAGE_MAP[package].keys(): if itype == install_type: ret = PACKAGE_MAP[package][install_type] if isinstance(ret,str): return ret if callable(ret): ret(shutit_pexpect_session) return '' # Otherwise, simply return package return package
[ "def", "map_package", "(", "shutit_pexpect_session", ",", "package", ",", "install_type", ")", ":", "if", "package", "in", "PACKAGE_MAP", ".", "keys", "(", ")", ":", "for", "itype", "in", "PACKAGE_MAP", "[", "package", "]", ".", "keys", "(", ")", ":", "if", "itype", "==", "install_type", ":", "ret", "=", "PACKAGE_MAP", "[", "package", "]", "[", "install_type", "]", "if", "isinstance", "(", "ret", ",", "str", ")", ":", "return", "ret", "if", "callable", "(", "ret", ")", ":", "ret", "(", "shutit_pexpect_session", ")", "return", "''", "# Otherwise, simply return package", "return", "package" ]
If package mapping exists, then return it, else return package.
[ "If", "package", "mapping", "exists", "then", "return", "it", "else", "return", "package", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/package_map.py#L135-L148
train
ianmiell/shutit
shutit_util.py
is_file_secure
def is_file_secure(file_name): """Returns false if file is considered insecure, true if secure. If file doesn't exist, it's considered secure! """ if not os.path.isfile(file_name): return True file_mode = os.stat(file_name).st_mode if file_mode & (stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH): return False return True
python
def is_file_secure(file_name): """Returns false if file is considered insecure, true if secure. If file doesn't exist, it's considered secure! """ if not os.path.isfile(file_name): return True file_mode = os.stat(file_name).st_mode if file_mode & (stat.S_IRGRP | stat.S_IWGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IWOTH | stat.S_IXOTH): return False return True
[ "def", "is_file_secure", "(", "file_name", ")", ":", "if", "not", "os", ".", "path", ".", "isfile", "(", "file_name", ")", ":", "return", "True", "file_mode", "=", "os", ".", "stat", "(", "file_name", ")", ".", "st_mode", "if", "file_mode", "&", "(", "stat", ".", "S_IRGRP", "|", "stat", ".", "S_IWGRP", "|", "stat", ".", "S_IXGRP", "|", "stat", ".", "S_IROTH", "|", "stat", ".", "S_IWOTH", "|", "stat", ".", "S_IXOTH", ")", ":", "return", "False", "return", "True" ]
Returns false if file is considered insecure, true if secure. If file doesn't exist, it's considered secure!
[ "Returns", "false", "if", "file", "is", "considered", "insecure", "true", "if", "secure", ".", "If", "file", "doesn", "t", "exist", "it", "s", "considered", "secure!" ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_util.py#L57-L66
train
ianmiell/shutit
shutit_util.py
random_id
def random_id(size=8, chars=string.ascii_letters + string.digits): """Generates a random string of given size from the given chars. @param size: The size of the random string. @param chars: Constituent pool of characters to draw random characters from. @type size: number @type chars: string @rtype: string @return: The string of random characters. """ return ''.join(random.choice(chars) for _ in range(size))
python
def random_id(size=8, chars=string.ascii_letters + string.digits): """Generates a random string of given size from the given chars. @param size: The size of the random string. @param chars: Constituent pool of characters to draw random characters from. @type size: number @type chars: string @rtype: string @return: The string of random characters. """ return ''.join(random.choice(chars) for _ in range(size))
[ "def", "random_id", "(", "size", "=", "8", ",", "chars", "=", "string", ".", "ascii_letters", "+", "string", ".", "digits", ")", ":", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "chars", ")", "for", "_", "in", "range", "(", "size", ")", ")" ]
Generates a random string of given size from the given chars. @param size: The size of the random string. @param chars: Constituent pool of characters to draw random characters from. @type size: number @type chars: string @rtype: string @return: The string of random characters.
[ "Generates", "a", "random", "string", "of", "given", "size", "from", "the", "given", "chars", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_util.py#L82-L92
train
ianmiell/shutit
shutit_util.py
random_word
def random_word(size=6): """Returns a random word in lower case. """ words = shutit_assets.get_words().splitlines() word = '' while len(word) != size or "'" in word: word = words[int(random.random() * (len(words) - 1))] return word.lower()
python
def random_word(size=6): """Returns a random word in lower case. """ words = shutit_assets.get_words().splitlines() word = '' while len(word) != size or "'" in word: word = words[int(random.random() * (len(words) - 1))] return word.lower()
[ "def", "random_word", "(", "size", "=", "6", ")", ":", "words", "=", "shutit_assets", ".", "get_words", "(", ")", ".", "splitlines", "(", ")", "word", "=", "''", "while", "len", "(", "word", ")", "!=", "size", "or", "\"'\"", "in", "word", ":", "word", "=", "words", "[", "int", "(", "random", ".", "random", "(", ")", "*", "(", "len", "(", "words", ")", "-", "1", ")", ")", "]", "return", "word", ".", "lower", "(", ")" ]
Returns a random word in lower case.
[ "Returns", "a", "random", "word", "in", "lower", "case", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_util.py#L95-L102
train
ianmiell/shutit
shutit_util.py
ctrl_c_signal_handler
def ctrl_c_signal_handler(_, frame): """CTRL-c signal handler - enters a pause point if it can. """ global ctrl_c_calls ctrl_c_calls += 1 if ctrl_c_calls > 10: shutit_global.shutit_global_object.handle_exit(exit_code=1) shutit_frame = get_shutit_frame(frame) if in_ctrlc: msg = 'CTRL-C hit twice, quitting' if shutit_frame: shutit_global.shutit_global_object.shutit_print('\n') shutit = shutit_frame.f_locals['shutit'] shutit.log(msg,level=logging.CRITICAL) else: shutit_global.shutit_global_object.shutit_print(msg) shutit_global.shutit_global_object.handle_exit(exit_code=1) if shutit_frame: shutit = shutit_frame.f_locals['shutit'] if shutit.build['ctrlc_passthrough']: shutit.self.get_current_shutit_pexpect_session().pexpect_child.sendline(r'') return shutit_global.shutit_global_object.shutit_print(colorise(31,"\r" + r"You may need to wait for a command to complete before a pause point is available. Alternatively, CTRL-\ to quit.")) shutit.build['ctrlc_stop'] = True t = threading.Thread(target=ctrlc_background) t.daemon = True t.start() # Reset the ctrl-c calls ctrl_c_calls = 0 return shutit_global.shutit_global_object.shutit_print(colorise(31,'\n' + '*' * 80)) shutit_global.shutit_global_object.shutit_print(colorise(31,"CTRL-c caught, CTRL-c twice to quit.")) shutit_global.shutit_global_object.shutit_print(colorise(31,'*' * 80)) t = threading.Thread(target=ctrlc_background) t.daemon = True t.start() # Reset the ctrl-c calls ctrl_c_calls = 0
python
def ctrl_c_signal_handler(_, frame): """CTRL-c signal handler - enters a pause point if it can. """ global ctrl_c_calls ctrl_c_calls += 1 if ctrl_c_calls > 10: shutit_global.shutit_global_object.handle_exit(exit_code=1) shutit_frame = get_shutit_frame(frame) if in_ctrlc: msg = 'CTRL-C hit twice, quitting' if shutit_frame: shutit_global.shutit_global_object.shutit_print('\n') shutit = shutit_frame.f_locals['shutit'] shutit.log(msg,level=logging.CRITICAL) else: shutit_global.shutit_global_object.shutit_print(msg) shutit_global.shutit_global_object.handle_exit(exit_code=1) if shutit_frame: shutit = shutit_frame.f_locals['shutit'] if shutit.build['ctrlc_passthrough']: shutit.self.get_current_shutit_pexpect_session().pexpect_child.sendline(r'') return shutit_global.shutit_global_object.shutit_print(colorise(31,"\r" + r"You may need to wait for a command to complete before a pause point is available. Alternatively, CTRL-\ to quit.")) shutit.build['ctrlc_stop'] = True t = threading.Thread(target=ctrlc_background) t.daemon = True t.start() # Reset the ctrl-c calls ctrl_c_calls = 0 return shutit_global.shutit_global_object.shutit_print(colorise(31,'\n' + '*' * 80)) shutit_global.shutit_global_object.shutit_print(colorise(31,"CTRL-c caught, CTRL-c twice to quit.")) shutit_global.shutit_global_object.shutit_print(colorise(31,'*' * 80)) t = threading.Thread(target=ctrlc_background) t.daemon = True t.start() # Reset the ctrl-c calls ctrl_c_calls = 0
[ "def", "ctrl_c_signal_handler", "(", "_", ",", "frame", ")", ":", "global", "ctrl_c_calls", "ctrl_c_calls", "+=", "1", "if", "ctrl_c_calls", ">", "10", ":", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "1", ")", "shutit_frame", "=", "get_shutit_frame", "(", "frame", ")", "if", "in_ctrlc", ":", "msg", "=", "'CTRL-C hit twice, quitting'", "if", "shutit_frame", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "'\\n'", ")", "shutit", "=", "shutit_frame", ".", "f_locals", "[", "'shutit'", "]", "shutit", ".", "log", "(", "msg", ",", "level", "=", "logging", ".", "CRITICAL", ")", "else", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "msg", ")", "shutit_global", ".", "shutit_global_object", ".", "handle_exit", "(", "exit_code", "=", "1", ")", "if", "shutit_frame", ":", "shutit", "=", "shutit_frame", ".", "f_locals", "[", "'shutit'", "]", "if", "shutit", ".", "build", "[", "'ctrlc_passthrough'", "]", ":", "shutit", ".", "self", ".", "get_current_shutit_pexpect_session", "(", ")", ".", "pexpect_child", ".", "sendline", "(", "r'\u0003'", ")", "return", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "colorise", "(", "31", ",", "\"\\r\"", "+", "r\"You may need to wait for a command to complete before a pause point is available. Alternatively, CTRL-\\ to quit.\"", ")", ")", "shutit", ".", "build", "[", "'ctrlc_stop'", "]", "=", "True", "t", "=", "threading", ".", "Thread", "(", "target", "=", "ctrlc_background", ")", "t", ".", "daemon", "=", "True", "t", ".", "start", "(", ")", "# Reset the ctrl-c calls", "ctrl_c_calls", "=", "0", "return", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "colorise", "(", "31", ",", "'\\n'", "+", "'*'", "*", "80", ")", ")", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "colorise", "(", "31", ",", "\"CTRL-c caught, CTRL-c twice to quit.\"", ")", ")", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "colorise", "(", "31", ",", "'*'", "*", "80", ")", ")", "t", "=", "threading", ".", "Thread", "(", "target", "=", "ctrlc_background", ")", "t", ".", "daemon", "=", "True", "t", ".", "start", "(", ")", "# Reset the ctrl-c calls", "ctrl_c_calls", "=", "0" ]
CTRL-c signal handler - enters a pause point if it can.
[ "CTRL", "-", "c", "signal", "handler", "-", "enters", "a", "pause", "point", "if", "it", "can", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_util.py#L145-L182
train
ianmiell/shutit
shutit_util.py
get_input
def get_input(msg, default='', valid=None, boolean=False, ispass=False, color=None): """Gets input from the user, and returns the answer. @param msg: message to send to user @param default: default value if nothing entered @param valid: valid input values (default == empty list == anything allowed) @param boolean: whether return value should be boolean @param ispass: True if this is a password (ie whether to not echo input) @param color: Color code to colorize with (eg 32 = green) """ # switch off log tracing when in get_input 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 boolean and valid is None: valid = ('yes','y','Y','1','true','no','n','N','0','false') if color: answer = util_raw_input(prompt=colorise(color,msg),ispass=ispass) else: answer = util_raw_input(msg,ispass=ispass) if boolean and answer in ('', None) and default != '': # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return default if valid is not None: while answer not in valid: shutit_global.shutit_global_object.shutit_print('Answer must be one of: ' + str(valid),transient=True) if color: answer = util_raw_input(prompt=colorise(color,msg),ispass=ispass) else: answer = util_raw_input(msg,ispass=ispass) if boolean: if answer.lower() in ('yes','y','1','true','t'): # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return True elif answer.lower() in ('no','n','0','false','f'): # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return False # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return answer or default
python
def get_input(msg, default='', valid=None, boolean=False, ispass=False, color=None): """Gets input from the user, and returns the answer. @param msg: message to send to user @param default: default value if nothing entered @param valid: valid input values (default == empty list == anything allowed) @param boolean: whether return value should be boolean @param ispass: True if this is a password (ie whether to not echo input) @param color: Color code to colorize with (eg 32 = green) """ # switch off log tracing when in get_input 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 boolean and valid is None: valid = ('yes','y','Y','1','true','no','n','N','0','false') if color: answer = util_raw_input(prompt=colorise(color,msg),ispass=ispass) else: answer = util_raw_input(msg,ispass=ispass) if boolean and answer in ('', None) and default != '': # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return default if valid is not None: while answer not in valid: shutit_global.shutit_global_object.shutit_print('Answer must be one of: ' + str(valid),transient=True) if color: answer = util_raw_input(prompt=colorise(color,msg),ispass=ispass) else: answer = util_raw_input(msg,ispass=ispass) if boolean: if answer.lower() in ('yes','y','1','true','t'): # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return True elif answer.lower() in ('no','n','0','false','f'): # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return False # Revert log trace value to original shutit_global.shutit_global_object.log_trace_when_idle = log_trace_when_idle_original_value return answer or default
[ "def", "get_input", "(", "msg", ",", "default", "=", "''", ",", "valid", "=", "None", ",", "boolean", "=", "False", ",", "ispass", "=", "False", ",", "color", "=", "None", ")", ":", "# switch off log tracing when in get_input", "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", "boolean", "and", "valid", "is", "None", ":", "valid", "=", "(", "'yes'", ",", "'y'", ",", "'Y'", ",", "'1'", ",", "'true'", ",", "'no'", ",", "'n'", ",", "'N'", ",", "'0'", ",", "'false'", ")", "if", "color", ":", "answer", "=", "util_raw_input", "(", "prompt", "=", "colorise", "(", "color", ",", "msg", ")", ",", "ispass", "=", "ispass", ")", "else", ":", "answer", "=", "util_raw_input", "(", "msg", ",", "ispass", "=", "ispass", ")", "if", "boolean", "and", "answer", "in", "(", "''", ",", "None", ")", "and", "default", "!=", "''", ":", "# Revert log trace value to original", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "log_trace_when_idle_original_value", "return", "default", "if", "valid", "is", "not", "None", ":", "while", "answer", "not", "in", "valid", ":", "shutit_global", ".", "shutit_global_object", ".", "shutit_print", "(", "'Answer must be one of: '", "+", "str", "(", "valid", ")", ",", "transient", "=", "True", ")", "if", "color", ":", "answer", "=", "util_raw_input", "(", "prompt", "=", "colorise", "(", "color", ",", "msg", ")", ",", "ispass", "=", "ispass", ")", "else", ":", "answer", "=", "util_raw_input", "(", "msg", ",", "ispass", "=", "ispass", ")", "if", "boolean", ":", "if", "answer", ".", "lower", "(", ")", "in", "(", "'yes'", ",", "'y'", ",", "'1'", ",", "'true'", ",", "'t'", ")", ":", "# Revert log trace value to original", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "log_trace_when_idle_original_value", "return", "True", "elif", "answer", ".", "lower", "(", ")", "in", "(", "'no'", ",", "'n'", ",", "'0'", ",", "'false'", ",", "'f'", ")", ":", "# Revert log trace value to original", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "log_trace_when_idle_original_value", "return", "False", "# Revert log trace value to original", "shutit_global", ".", "shutit_global_object", ".", "log_trace_when_idle", "=", "log_trace_when_idle_original_value", "return", "answer", "or", "default" ]
Gets input from the user, and returns the answer. @param msg: message to send to user @param default: default value if nothing entered @param valid: valid input values (default == empty list == anything allowed) @param boolean: whether return value should be boolean @param ispass: True if this is a password (ie whether to not echo input) @param color: Color code to colorize with (eg 32 = green)
[ "Gets", "input", "from", "the", "user", "and", "returns", "the", "answer", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_util.py#L281-L322
train
ianmiell/shutit
shutit_setup.py
ConnDocker.build
def build(self, shutit): """Sets up the target ready for building. """ target_child = self.start_container(shutit, 'target_child') self.setup_host_child(shutit) # TODO: on the host child, check that the image running has bash as its cmd/entrypoint. self.setup_target_child(shutit, target_child) shutit.send('chmod -R 777 ' + shutit_global.shutit_global_object.shutit_state_dir + ' && mkdir -p ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/' + shutit_global.shutit_global_object.build_id, shutit_pexpect_child=target_child, echo=False) return True
python
def build(self, shutit): """Sets up the target ready for building. """ target_child = self.start_container(shutit, 'target_child') self.setup_host_child(shutit) # TODO: on the host child, check that the image running has bash as its cmd/entrypoint. self.setup_target_child(shutit, target_child) shutit.send('chmod -R 777 ' + shutit_global.shutit_global_object.shutit_state_dir + ' && mkdir -p ' + shutit_global.shutit_global_object.shutit_state_dir_build_db_dir + '/' + shutit_global.shutit_global_object.build_id, shutit_pexpect_child=target_child, echo=False) return True
[ "def", "build", "(", "self", ",", "shutit", ")", ":", "target_child", "=", "self", ".", "start_container", "(", "shutit", ",", "'target_child'", ")", "self", ".", "setup_host_child", "(", "shutit", ")", "# TODO: on the host child, check that the image running has bash as its cmd/entrypoint.", "self", ".", "setup_target_child", "(", "shutit", ",", "target_child", ")", "shutit", ".", "send", "(", "'chmod -R 777 '", "+", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir", "+", "' && mkdir -p '", "+", "shutit_global", ".", "shutit_global_object", ".", "shutit_state_dir_build_db_dir", "+", "'/'", "+", "shutit_global", ".", "shutit_global_object", ".", "build_id", ",", "shutit_pexpect_child", "=", "target_child", ",", "echo", "=", "False", ")", "return", "True" ]
Sets up the target ready for building.
[ "Sets", "up", "the", "target", "ready", "for", "building", "." ]
19cd64cdfb23515b106b40213dccff4101617076
https://github.com/ianmiell/shutit/blob/19cd64cdfb23515b106b40213dccff4101617076/shutit_setup.py#L82-L90
train