repository_name stringclasses 316 values | func_path_in_repository stringlengths 6 223 | func_name stringlengths 1 134 | language stringclasses 1 value | func_code_string stringlengths 57 65.5k | func_documentation_string stringlengths 1 46.3k | split_name stringclasses 1 value | func_code_url stringlengths 91 315 | called_functions listlengths 1 156 ⌀ | enclosing_scope stringlengths 2 1.48M |
|---|---|---|---|---|---|---|---|---|---|
pokerregion/poker | poker/room/pokerstars.py | Notes.labels | python | def labels(self):
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label')) | Tuple of labels. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L340-L343 | null | class Notes(object):
"""Class for parsing pokerstars XML notes."""
_color_re = re.compile('^[0-9A-F]{6}$')
def __init__(self, notes):
# notes need to be a unicode object
self.raw = notes
parser = etree.XMLParser(recover=True, resolve_entities=False)
self.root = etree.XML(notes.encode('utf-8'), parser)
def __unicode__(self):
return str(self).decode('utf-8')
def __str__(self):
return etree.tostring(self.root, xml_declaration=True, encoding='UTF-8', pretty_print=True)
@classmethod
def from_file(cls, filename):
"""Make an instance from a XML file."""
return cls(Path(filename).open().read())
@property
def players(self):
"""Tuple of player names."""
return tuple(note.get('player') for note in self.root.iter('note'))
@property
def label_names(self):
"""Tuple of label names."""
return tuple(label.text for label in self.root.iter('label'))
@property
def notes(self):
"""Tuple of notes.."""
return tuple(self._get_note_data(note) for note in self.root.iter('note'))
@property
def get_note_text(self, player):
"""Return note text for the player."""
note = self._find_note(player)
return note.text
def get_note(self, player):
"""Return :class:`_Note` tuple for the player."""
return self._get_note_data(self._find_note(player))
def add_note(self, player, text, label=None, update=None):
"""Add a note to the xml. If update param is None, it will be the current time."""
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
update = datetime.utcnow()
# converted to timestamp, rounded to ones
update = update.strftime('%s')
label_id = self._get_label_id(label)
new_note = etree.Element('note', player=player, label=label_id, update=update)
new_note.text = text
self.root.append(new_note)
def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text
def prepend_note(self, player, text):
"""Prepend text to an already existing note."""
note = self._find_note(player)
note.text = text + note.text
def replace_note(self, player, text):
"""Replace note text with text. (Overwrites previous note!)"""
note = self._find_note(player)
note.text = text
def change_note_label(self, player, label):
label_id = self._get_label_id(label)
note = self._find_note(player)
note.attrib['label'] = label_id
def del_note(self, player):
"""Delete a note by player name."""
self.root.remove(self._find_note(player))
def _find_note(self, player):
# if player name contains a double quote, the search phrase would be invalid.
# " entitiy is searched with ", e.g. "bootei" is searched with '"bootei"'
quote = "'" if '"' in player else '"'
note = self.root.find('note[@player={0}{1}{0}]'.format(quote, player))
if note is None:
raise NoteNotFoundError(player)
return note
def _get_note_data(self, note):
labels = {label.get('id'): label.text for label in self.root.iter('label')}
label = note.get('label')
label = labels[label] if label != "-1" else None
timestamp = note.get('update')
if timestamp:
timestamp = int(timestamp)
update = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC)
else:
update = None
return _Note(note.get('player'), label, update, note.text)
def get_label(self, name):
"""Find the label by name."""
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text)
def add_label(self, name, color):
"""Add a new label. It's id will automatically be calculated."""
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels_tag[-1].get('id'))
new_id = str(last_id + 1)
new_label = etree.Element('label', id=new_id, color=color_upper)
new_label.text = name
labels_tag.append(new_label)
def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name))
def _find_label(self, name):
labels_tag = self.root[0]
try:
return labels_tag.xpath('label[text()="%s"]' % name)[0]
except IndexError:
raise LabelNotFoundError(name)
def _get_label_id(self, name):
return self._find_label(name).get('id') if name else '-1'
def save(self, filename):
"""Save the note XML to a file."""
with open(filename, 'w') as fp:
fp.write(str(self))
|
pokerregion/poker | poker/room/pokerstars.py | Notes.add_note | python | def add_note(self, player, text, label=None, update=None):
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
update = datetime.utcnow()
# converted to timestamp, rounded to ones
update = update.strftime('%s')
label_id = self._get_label_id(label)
new_note = etree.Element('note', player=player, label=label_id, update=update)
new_note.text = text
self.root.append(new_note) | Add a note to the xml. If update param is None, it will be the current time. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L354-L365 | [
"def _get_label_id(self, name):\n return self._find_label(name).get('id') if name else '-1'\n"
] | class Notes(object):
"""Class for parsing pokerstars XML notes."""
_color_re = re.compile('^[0-9A-F]{6}$')
def __init__(self, notes):
# notes need to be a unicode object
self.raw = notes
parser = etree.XMLParser(recover=True, resolve_entities=False)
self.root = etree.XML(notes.encode('utf-8'), parser)
def __unicode__(self):
return str(self).decode('utf-8')
def __str__(self):
return etree.tostring(self.root, xml_declaration=True, encoding='UTF-8', pretty_print=True)
@classmethod
def from_file(cls, filename):
"""Make an instance from a XML file."""
return cls(Path(filename).open().read())
@property
def players(self):
"""Tuple of player names."""
return tuple(note.get('player') for note in self.root.iter('note'))
@property
def label_names(self):
"""Tuple of label names."""
return tuple(label.text for label in self.root.iter('label'))
@property
def notes(self):
"""Tuple of notes.."""
return tuple(self._get_note_data(note) for note in self.root.iter('note'))
@property
def labels(self):
"""Tuple of labels."""
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label'))
def get_note_text(self, player):
"""Return note text for the player."""
note = self._find_note(player)
return note.text
def get_note(self, player):
"""Return :class:`_Note` tuple for the player."""
return self._get_note_data(self._find_note(player))
def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text
def prepend_note(self, player, text):
"""Prepend text to an already existing note."""
note = self._find_note(player)
note.text = text + note.text
def replace_note(self, player, text):
"""Replace note text with text. (Overwrites previous note!)"""
note = self._find_note(player)
note.text = text
def change_note_label(self, player, label):
label_id = self._get_label_id(label)
note = self._find_note(player)
note.attrib['label'] = label_id
def del_note(self, player):
"""Delete a note by player name."""
self.root.remove(self._find_note(player))
def _find_note(self, player):
# if player name contains a double quote, the search phrase would be invalid.
# " entitiy is searched with ", e.g. "bootei" is searched with '"bootei"'
quote = "'" if '"' in player else '"'
note = self.root.find('note[@player={0}{1}{0}]'.format(quote, player))
if note is None:
raise NoteNotFoundError(player)
return note
def _get_note_data(self, note):
labels = {label.get('id'): label.text for label in self.root.iter('label')}
label = note.get('label')
label = labels[label] if label != "-1" else None
timestamp = note.get('update')
if timestamp:
timestamp = int(timestamp)
update = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC)
else:
update = None
return _Note(note.get('player'), label, update, note.text)
def get_label(self, name):
"""Find the label by name."""
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text)
def add_label(self, name, color):
"""Add a new label. It's id will automatically be calculated."""
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels_tag[-1].get('id'))
new_id = str(last_id + 1)
new_label = etree.Element('label', id=new_id, color=color_upper)
new_label.text = name
labels_tag.append(new_label)
def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name))
def _find_label(self, name):
labels_tag = self.root[0]
try:
return labels_tag.xpath('label[text()="%s"]' % name)[0]
except IndexError:
raise LabelNotFoundError(name)
def _get_label_id(self, name):
return self._find_label(name).get('id') if name else '-1'
def save(self, filename):
"""Save the note XML to a file."""
with open(filename, 'w') as fp:
fp.write(str(self))
|
pokerregion/poker | poker/room/pokerstars.py | Notes.append_note | python | def append_note(self, player, text):
note = self._find_note(player)
note.text += text | Append text to an already existing note. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L367-L370 | [
"def _find_note(self, player):\n # if player name contains a double quote, the search phrase would be invalid.\n # " entitiy is searched with \", e.g. "bootei" is searched with '\"bootei\"'\n quote = \"'\" if '\"' in player else '\"'\n note = self.root.find('note[@player={0}{1}{0}]'.forma... | class Notes(object):
"""Class for parsing pokerstars XML notes."""
_color_re = re.compile('^[0-9A-F]{6}$')
def __init__(self, notes):
# notes need to be a unicode object
self.raw = notes
parser = etree.XMLParser(recover=True, resolve_entities=False)
self.root = etree.XML(notes.encode('utf-8'), parser)
def __unicode__(self):
return str(self).decode('utf-8')
def __str__(self):
return etree.tostring(self.root, xml_declaration=True, encoding='UTF-8', pretty_print=True)
@classmethod
def from_file(cls, filename):
"""Make an instance from a XML file."""
return cls(Path(filename).open().read())
@property
def players(self):
"""Tuple of player names."""
return tuple(note.get('player') for note in self.root.iter('note'))
@property
def label_names(self):
"""Tuple of label names."""
return tuple(label.text for label in self.root.iter('label'))
@property
def notes(self):
"""Tuple of notes.."""
return tuple(self._get_note_data(note) for note in self.root.iter('note'))
@property
def labels(self):
"""Tuple of labels."""
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label'))
def get_note_text(self, player):
"""Return note text for the player."""
note = self._find_note(player)
return note.text
def get_note(self, player):
"""Return :class:`_Note` tuple for the player."""
return self._get_note_data(self._find_note(player))
def add_note(self, player, text, label=None, update=None):
"""Add a note to the xml. If update param is None, it will be the current time."""
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
update = datetime.utcnow()
# converted to timestamp, rounded to ones
update = update.strftime('%s')
label_id = self._get_label_id(label)
new_note = etree.Element('note', player=player, label=label_id, update=update)
new_note.text = text
self.root.append(new_note)
def prepend_note(self, player, text):
"""Prepend text to an already existing note."""
note = self._find_note(player)
note.text = text + note.text
def replace_note(self, player, text):
"""Replace note text with text. (Overwrites previous note!)"""
note = self._find_note(player)
note.text = text
def change_note_label(self, player, label):
label_id = self._get_label_id(label)
note = self._find_note(player)
note.attrib['label'] = label_id
def del_note(self, player):
"""Delete a note by player name."""
self.root.remove(self._find_note(player))
def _find_note(self, player):
# if player name contains a double quote, the search phrase would be invalid.
# " entitiy is searched with ", e.g. "bootei" is searched with '"bootei"'
quote = "'" if '"' in player else '"'
note = self.root.find('note[@player={0}{1}{0}]'.format(quote, player))
if note is None:
raise NoteNotFoundError(player)
return note
def _get_note_data(self, note):
labels = {label.get('id'): label.text for label in self.root.iter('label')}
label = note.get('label')
label = labels[label] if label != "-1" else None
timestamp = note.get('update')
if timestamp:
timestamp = int(timestamp)
update = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC)
else:
update = None
return _Note(note.get('player'), label, update, note.text)
def get_label(self, name):
"""Find the label by name."""
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text)
def add_label(self, name, color):
"""Add a new label. It's id will automatically be calculated."""
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels_tag[-1].get('id'))
new_id = str(last_id + 1)
new_label = etree.Element('label', id=new_id, color=color_upper)
new_label.text = name
labels_tag.append(new_label)
def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name))
def _find_label(self, name):
labels_tag = self.root[0]
try:
return labels_tag.xpath('label[text()="%s"]' % name)[0]
except IndexError:
raise LabelNotFoundError(name)
def _get_label_id(self, name):
return self._find_label(name).get('id') if name else '-1'
def save(self, filename):
"""Save the note XML to a file."""
with open(filename, 'w') as fp:
fp.write(str(self))
|
pokerregion/poker | poker/room/pokerstars.py | Notes.prepend_note | python | def prepend_note(self, player, text):
note = self._find_note(player)
note.text = text + note.text | Prepend text to an already existing note. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L372-L375 | [
"def _find_note(self, player):\n # if player name contains a double quote, the search phrase would be invalid.\n # " entitiy is searched with \", e.g. "bootei" is searched with '\"bootei\"'\n quote = \"'\" if '\"' in player else '\"'\n note = self.root.find('note[@player={0}{1}{0}]'.forma... | class Notes(object):
"""Class for parsing pokerstars XML notes."""
_color_re = re.compile('^[0-9A-F]{6}$')
def __init__(self, notes):
# notes need to be a unicode object
self.raw = notes
parser = etree.XMLParser(recover=True, resolve_entities=False)
self.root = etree.XML(notes.encode('utf-8'), parser)
def __unicode__(self):
return str(self).decode('utf-8')
def __str__(self):
return etree.tostring(self.root, xml_declaration=True, encoding='UTF-8', pretty_print=True)
@classmethod
def from_file(cls, filename):
"""Make an instance from a XML file."""
return cls(Path(filename).open().read())
@property
def players(self):
"""Tuple of player names."""
return tuple(note.get('player') for note in self.root.iter('note'))
@property
def label_names(self):
"""Tuple of label names."""
return tuple(label.text for label in self.root.iter('label'))
@property
def notes(self):
"""Tuple of notes.."""
return tuple(self._get_note_data(note) for note in self.root.iter('note'))
@property
def labels(self):
"""Tuple of labels."""
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label'))
def get_note_text(self, player):
"""Return note text for the player."""
note = self._find_note(player)
return note.text
def get_note(self, player):
"""Return :class:`_Note` tuple for the player."""
return self._get_note_data(self._find_note(player))
def add_note(self, player, text, label=None, update=None):
"""Add a note to the xml. If update param is None, it will be the current time."""
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
update = datetime.utcnow()
# converted to timestamp, rounded to ones
update = update.strftime('%s')
label_id = self._get_label_id(label)
new_note = etree.Element('note', player=player, label=label_id, update=update)
new_note.text = text
self.root.append(new_note)
def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text
def replace_note(self, player, text):
"""Replace note text with text. (Overwrites previous note!)"""
note = self._find_note(player)
note.text = text
def change_note_label(self, player, label):
label_id = self._get_label_id(label)
note = self._find_note(player)
note.attrib['label'] = label_id
def del_note(self, player):
"""Delete a note by player name."""
self.root.remove(self._find_note(player))
def _find_note(self, player):
# if player name contains a double quote, the search phrase would be invalid.
# " entitiy is searched with ", e.g. "bootei" is searched with '"bootei"'
quote = "'" if '"' in player else '"'
note = self.root.find('note[@player={0}{1}{0}]'.format(quote, player))
if note is None:
raise NoteNotFoundError(player)
return note
def _get_note_data(self, note):
labels = {label.get('id'): label.text for label in self.root.iter('label')}
label = note.get('label')
label = labels[label] if label != "-1" else None
timestamp = note.get('update')
if timestamp:
timestamp = int(timestamp)
update = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC)
else:
update = None
return _Note(note.get('player'), label, update, note.text)
def get_label(self, name):
"""Find the label by name."""
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text)
def add_label(self, name, color):
"""Add a new label. It's id will automatically be calculated."""
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels_tag[-1].get('id'))
new_id = str(last_id + 1)
new_label = etree.Element('label', id=new_id, color=color_upper)
new_label.text = name
labels_tag.append(new_label)
def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name))
def _find_label(self, name):
labels_tag = self.root[0]
try:
return labels_tag.xpath('label[text()="%s"]' % name)[0]
except IndexError:
raise LabelNotFoundError(name)
def _get_label_id(self, name):
return self._find_label(name).get('id') if name else '-1'
def save(self, filename):
"""Save the note XML to a file."""
with open(filename, 'w') as fp:
fp.write(str(self))
|
pokerregion/poker | poker/room/pokerstars.py | Notes.replace_note | python | def replace_note(self, player, text):
note = self._find_note(player)
note.text = text | Replace note text with text. (Overwrites previous note!) | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L377-L380 | [
"def _find_note(self, player):\n # if player name contains a double quote, the search phrase would be invalid.\n # " entitiy is searched with \", e.g. "bootei" is searched with '\"bootei\"'\n quote = \"'\" if '\"' in player else '\"'\n note = self.root.find('note[@player={0}{1}{0}]'.forma... | class Notes(object):
"""Class for parsing pokerstars XML notes."""
_color_re = re.compile('^[0-9A-F]{6}$')
def __init__(self, notes):
# notes need to be a unicode object
self.raw = notes
parser = etree.XMLParser(recover=True, resolve_entities=False)
self.root = etree.XML(notes.encode('utf-8'), parser)
def __unicode__(self):
return str(self).decode('utf-8')
def __str__(self):
return etree.tostring(self.root, xml_declaration=True, encoding='UTF-8', pretty_print=True)
@classmethod
def from_file(cls, filename):
"""Make an instance from a XML file."""
return cls(Path(filename).open().read())
@property
def players(self):
"""Tuple of player names."""
return tuple(note.get('player') for note in self.root.iter('note'))
@property
def label_names(self):
"""Tuple of label names."""
return tuple(label.text for label in self.root.iter('label'))
@property
def notes(self):
"""Tuple of notes.."""
return tuple(self._get_note_data(note) for note in self.root.iter('note'))
@property
def labels(self):
"""Tuple of labels."""
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label'))
def get_note_text(self, player):
"""Return note text for the player."""
note = self._find_note(player)
return note.text
def get_note(self, player):
"""Return :class:`_Note` tuple for the player."""
return self._get_note_data(self._find_note(player))
def add_note(self, player, text, label=None, update=None):
"""Add a note to the xml. If update param is None, it will be the current time."""
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
update = datetime.utcnow()
# converted to timestamp, rounded to ones
update = update.strftime('%s')
label_id = self._get_label_id(label)
new_note = etree.Element('note', player=player, label=label_id, update=update)
new_note.text = text
self.root.append(new_note)
def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text
def prepend_note(self, player, text):
"""Prepend text to an already existing note."""
note = self._find_note(player)
note.text = text + note.text
def change_note_label(self, player, label):
label_id = self._get_label_id(label)
note = self._find_note(player)
note.attrib['label'] = label_id
def del_note(self, player):
"""Delete a note by player name."""
self.root.remove(self._find_note(player))
def _find_note(self, player):
# if player name contains a double quote, the search phrase would be invalid.
# " entitiy is searched with ", e.g. "bootei" is searched with '"bootei"'
quote = "'" if '"' in player else '"'
note = self.root.find('note[@player={0}{1}{0}]'.format(quote, player))
if note is None:
raise NoteNotFoundError(player)
return note
def _get_note_data(self, note):
labels = {label.get('id'): label.text for label in self.root.iter('label')}
label = note.get('label')
label = labels[label] if label != "-1" else None
timestamp = note.get('update')
if timestamp:
timestamp = int(timestamp)
update = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC)
else:
update = None
return _Note(note.get('player'), label, update, note.text)
def get_label(self, name):
"""Find the label by name."""
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text)
def add_label(self, name, color):
"""Add a new label. It's id will automatically be calculated."""
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels_tag[-1].get('id'))
new_id = str(last_id + 1)
new_label = etree.Element('label', id=new_id, color=color_upper)
new_label.text = name
labels_tag.append(new_label)
def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name))
def _find_label(self, name):
labels_tag = self.root[0]
try:
return labels_tag.xpath('label[text()="%s"]' % name)[0]
except IndexError:
raise LabelNotFoundError(name)
def _get_label_id(self, name):
return self._find_label(name).get('id') if name else '-1'
def save(self, filename):
"""Save the note XML to a file."""
with open(filename, 'w') as fp:
fp.write(str(self))
|
pokerregion/poker | poker/room/pokerstars.py | Notes.get_label | python | def get_label(self, name):
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text) | Find the label by name. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L412-L415 | [
"def _find_label(self, name):\n labels_tag = self.root[0]\n try:\n return labels_tag.xpath('label[text()=\"%s\"]' % name)[0]\n except IndexError:\n raise LabelNotFoundError(name)\n"
] | class Notes(object):
"""Class for parsing pokerstars XML notes."""
_color_re = re.compile('^[0-9A-F]{6}$')
def __init__(self, notes):
# notes need to be a unicode object
self.raw = notes
parser = etree.XMLParser(recover=True, resolve_entities=False)
self.root = etree.XML(notes.encode('utf-8'), parser)
def __unicode__(self):
return str(self).decode('utf-8')
def __str__(self):
return etree.tostring(self.root, xml_declaration=True, encoding='UTF-8', pretty_print=True)
@classmethod
def from_file(cls, filename):
"""Make an instance from a XML file."""
return cls(Path(filename).open().read())
@property
def players(self):
"""Tuple of player names."""
return tuple(note.get('player') for note in self.root.iter('note'))
@property
def label_names(self):
"""Tuple of label names."""
return tuple(label.text for label in self.root.iter('label'))
@property
def notes(self):
"""Tuple of notes.."""
return tuple(self._get_note_data(note) for note in self.root.iter('note'))
@property
def labels(self):
"""Tuple of labels."""
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label'))
def get_note_text(self, player):
"""Return note text for the player."""
note = self._find_note(player)
return note.text
def get_note(self, player):
"""Return :class:`_Note` tuple for the player."""
return self._get_note_data(self._find_note(player))
def add_note(self, player, text, label=None, update=None):
"""Add a note to the xml. If update param is None, it will be the current time."""
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
update = datetime.utcnow()
# converted to timestamp, rounded to ones
update = update.strftime('%s')
label_id = self._get_label_id(label)
new_note = etree.Element('note', player=player, label=label_id, update=update)
new_note.text = text
self.root.append(new_note)
def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text
def prepend_note(self, player, text):
"""Prepend text to an already existing note."""
note = self._find_note(player)
note.text = text + note.text
def replace_note(self, player, text):
"""Replace note text with text. (Overwrites previous note!)"""
note = self._find_note(player)
note.text = text
def change_note_label(self, player, label):
label_id = self._get_label_id(label)
note = self._find_note(player)
note.attrib['label'] = label_id
def del_note(self, player):
"""Delete a note by player name."""
self.root.remove(self._find_note(player))
def _find_note(self, player):
# if player name contains a double quote, the search phrase would be invalid.
# " entitiy is searched with ", e.g. "bootei" is searched with '"bootei"'
quote = "'" if '"' in player else '"'
note = self.root.find('note[@player={0}{1}{0}]'.format(quote, player))
if note is None:
raise NoteNotFoundError(player)
return note
def _get_note_data(self, note):
labels = {label.get('id'): label.text for label in self.root.iter('label')}
label = note.get('label')
label = labels[label] if label != "-1" else None
timestamp = note.get('update')
if timestamp:
timestamp = int(timestamp)
update = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC)
else:
update = None
return _Note(note.get('player'), label, update, note.text)
def add_label(self, name, color):
"""Add a new label. It's id will automatically be calculated."""
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels_tag[-1].get('id'))
new_id = str(last_id + 1)
new_label = etree.Element('label', id=new_id, color=color_upper)
new_label.text = name
labels_tag.append(new_label)
def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name))
def _find_label(self, name):
labels_tag = self.root[0]
try:
return labels_tag.xpath('label[text()="%s"]' % name)[0]
except IndexError:
raise LabelNotFoundError(name)
def _get_label_id(self, name):
return self._find_label(name).get('id') if name else '-1'
def save(self, filename):
"""Save the note XML to a file."""
with open(filename, 'w') as fp:
fp.write(str(self))
|
pokerregion/poker | poker/room/pokerstars.py | Notes.add_label | python | def add_label(self, name, color):
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels_tag[-1].get('id'))
new_id = str(last_id + 1)
new_label = etree.Element('label', id=new_id, color=color_upper)
new_label.text = name
labels_tag.append(new_label) | Add a new label. It's id will automatically be calculated. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L417-L430 | null | class Notes(object):
"""Class for parsing pokerstars XML notes."""
_color_re = re.compile('^[0-9A-F]{6}$')
def __init__(self, notes):
# notes need to be a unicode object
self.raw = notes
parser = etree.XMLParser(recover=True, resolve_entities=False)
self.root = etree.XML(notes.encode('utf-8'), parser)
def __unicode__(self):
return str(self).decode('utf-8')
def __str__(self):
return etree.tostring(self.root, xml_declaration=True, encoding='UTF-8', pretty_print=True)
@classmethod
def from_file(cls, filename):
"""Make an instance from a XML file."""
return cls(Path(filename).open().read())
@property
def players(self):
"""Tuple of player names."""
return tuple(note.get('player') for note in self.root.iter('note'))
@property
def label_names(self):
"""Tuple of label names."""
return tuple(label.text for label in self.root.iter('label'))
@property
def notes(self):
"""Tuple of notes.."""
return tuple(self._get_note_data(note) for note in self.root.iter('note'))
@property
def labels(self):
"""Tuple of labels."""
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label'))
def get_note_text(self, player):
"""Return note text for the player."""
note = self._find_note(player)
return note.text
def get_note(self, player):
"""Return :class:`_Note` tuple for the player."""
return self._get_note_data(self._find_note(player))
def add_note(self, player, text, label=None, update=None):
"""Add a note to the xml. If update param is None, it will be the current time."""
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
update = datetime.utcnow()
# converted to timestamp, rounded to ones
update = update.strftime('%s')
label_id = self._get_label_id(label)
new_note = etree.Element('note', player=player, label=label_id, update=update)
new_note.text = text
self.root.append(new_note)
def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text
def prepend_note(self, player, text):
"""Prepend text to an already existing note."""
note = self._find_note(player)
note.text = text + note.text
def replace_note(self, player, text):
"""Replace note text with text. (Overwrites previous note!)"""
note = self._find_note(player)
note.text = text
def change_note_label(self, player, label):
label_id = self._get_label_id(label)
note = self._find_note(player)
note.attrib['label'] = label_id
def del_note(self, player):
"""Delete a note by player name."""
self.root.remove(self._find_note(player))
def _find_note(self, player):
# if player name contains a double quote, the search phrase would be invalid.
# " entitiy is searched with ", e.g. "bootei" is searched with '"bootei"'
quote = "'" if '"' in player else '"'
note = self.root.find('note[@player={0}{1}{0}]'.format(quote, player))
if note is None:
raise NoteNotFoundError(player)
return note
def _get_note_data(self, note):
labels = {label.get('id'): label.text for label in self.root.iter('label')}
label = note.get('label')
label = labels[label] if label != "-1" else None
timestamp = note.get('update')
if timestamp:
timestamp = int(timestamp)
update = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC)
else:
update = None
return _Note(note.get('player'), label, update, note.text)
def get_label(self, name):
"""Find the label by name."""
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text)
def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name))
def _find_label(self, name):
labels_tag = self.root[0]
try:
return labels_tag.xpath('label[text()="%s"]' % name)[0]
except IndexError:
raise LabelNotFoundError(name)
def _get_label_id(self, name):
return self._find_label(name).get('id') if name else '-1'
def save(self, filename):
"""Save the note XML to a file."""
with open(filename, 'w') as fp:
fp.write(str(self))
|
pokerregion/poker | poker/room/pokerstars.py | Notes.del_label | python | def del_label(self, name):
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name)) | Delete a label by name. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L432-L435 | [
"def _find_label(self, name):\n labels_tag = self.root[0]\n try:\n return labels_tag.xpath('label[text()=\"%s\"]' % name)[0]\n except IndexError:\n raise LabelNotFoundError(name)\n"
] | class Notes(object):
"""Class for parsing pokerstars XML notes."""
_color_re = re.compile('^[0-9A-F]{6}$')
def __init__(self, notes):
# notes need to be a unicode object
self.raw = notes
parser = etree.XMLParser(recover=True, resolve_entities=False)
self.root = etree.XML(notes.encode('utf-8'), parser)
def __unicode__(self):
return str(self).decode('utf-8')
def __str__(self):
return etree.tostring(self.root, xml_declaration=True, encoding='UTF-8', pretty_print=True)
@classmethod
def from_file(cls, filename):
"""Make an instance from a XML file."""
return cls(Path(filename).open().read())
@property
def players(self):
"""Tuple of player names."""
return tuple(note.get('player') for note in self.root.iter('note'))
@property
def label_names(self):
"""Tuple of label names."""
return tuple(label.text for label in self.root.iter('label'))
@property
def notes(self):
"""Tuple of notes.."""
return tuple(self._get_note_data(note) for note in self.root.iter('note'))
@property
def labels(self):
"""Tuple of labels."""
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label'))
def get_note_text(self, player):
"""Return note text for the player."""
note = self._find_note(player)
return note.text
def get_note(self, player):
"""Return :class:`_Note` tuple for the player."""
return self._get_note_data(self._find_note(player))
def add_note(self, player, text, label=None, update=None):
"""Add a note to the xml. If update param is None, it will be the current time."""
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
update = datetime.utcnow()
# converted to timestamp, rounded to ones
update = update.strftime('%s')
label_id = self._get_label_id(label)
new_note = etree.Element('note', player=player, label=label_id, update=update)
new_note.text = text
self.root.append(new_note)
def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text
def prepend_note(self, player, text):
"""Prepend text to an already existing note."""
note = self._find_note(player)
note.text = text + note.text
def replace_note(self, player, text):
"""Replace note text with text. (Overwrites previous note!)"""
note = self._find_note(player)
note.text = text
def change_note_label(self, player, label):
label_id = self._get_label_id(label)
note = self._find_note(player)
note.attrib['label'] = label_id
def del_note(self, player):
"""Delete a note by player name."""
self.root.remove(self._find_note(player))
def _find_note(self, player):
# if player name contains a double quote, the search phrase would be invalid.
# " entitiy is searched with ", e.g. "bootei" is searched with '"bootei"'
quote = "'" if '"' in player else '"'
note = self.root.find('note[@player={0}{1}{0}]'.format(quote, player))
if note is None:
raise NoteNotFoundError(player)
return note
def _get_note_data(self, note):
labels = {label.get('id'): label.text for label in self.root.iter('label')}
label = note.get('label')
label = labels[label] if label != "-1" else None
timestamp = note.get('update')
if timestamp:
timestamp = int(timestamp)
update = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC)
else:
update = None
return _Note(note.get('player'), label, update, note.text)
def get_label(self, name):
"""Find the label by name."""
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text)
def add_label(self, name, color):
"""Add a new label. It's id will automatically be calculated."""
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels_tag[-1].get('id'))
new_id = str(last_id + 1)
new_label = etree.Element('label', id=new_id, color=color_upper)
new_label.text = name
labels_tag.append(new_label)
def _find_label(self, name):
labels_tag = self.root[0]
try:
return labels_tag.xpath('label[text()="%s"]' % name)[0]
except IndexError:
raise LabelNotFoundError(name)
def _get_label_id(self, name):
return self._find_label(name).get('id') if name else '-1'
def save(self, filename):
"""Save the note XML to a file."""
with open(filename, 'w') as fp:
fp.write(str(self))
|
pokerregion/poker | poker/room/pokerstars.py | Notes.save | python | def save(self, filename):
with open(filename, 'w') as fp:
fp.write(str(self)) | Save the note XML to a file. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/room/pokerstars.py#L447-L450 | null | class Notes(object):
"""Class for parsing pokerstars XML notes."""
_color_re = re.compile('^[0-9A-F]{6}$')
def __init__(self, notes):
# notes need to be a unicode object
self.raw = notes
parser = etree.XMLParser(recover=True, resolve_entities=False)
self.root = etree.XML(notes.encode('utf-8'), parser)
def __unicode__(self):
return str(self).decode('utf-8')
def __str__(self):
return etree.tostring(self.root, xml_declaration=True, encoding='UTF-8', pretty_print=True)
@classmethod
def from_file(cls, filename):
"""Make an instance from a XML file."""
return cls(Path(filename).open().read())
@property
def players(self):
"""Tuple of player names."""
return tuple(note.get('player') for note in self.root.iter('note'))
@property
def label_names(self):
"""Tuple of label names."""
return tuple(label.text for label in self.root.iter('label'))
@property
def notes(self):
"""Tuple of notes.."""
return tuple(self._get_note_data(note) for note in self.root.iter('note'))
@property
def labels(self):
"""Tuple of labels."""
return tuple(_Label(label.get('id'), label.get('color'), label.text) for label
in self.root.iter('label'))
def get_note_text(self, player):
"""Return note text for the player."""
note = self._find_note(player)
return note.text
def get_note(self, player):
"""Return :class:`_Note` tuple for the player."""
return self._get_note_data(self._find_note(player))
def add_note(self, player, text, label=None, update=None):
"""Add a note to the xml. If update param is None, it will be the current time."""
if label is not None and (label not in self.label_names):
raise LabelNotFoundError('Invalid label: {}'.format(label))
if update is None:
update = datetime.utcnow()
# converted to timestamp, rounded to ones
update = update.strftime('%s')
label_id = self._get_label_id(label)
new_note = etree.Element('note', player=player, label=label_id, update=update)
new_note.text = text
self.root.append(new_note)
def append_note(self, player, text):
"""Append text to an already existing note."""
note = self._find_note(player)
note.text += text
def prepend_note(self, player, text):
"""Prepend text to an already existing note."""
note = self._find_note(player)
note.text = text + note.text
def replace_note(self, player, text):
"""Replace note text with text. (Overwrites previous note!)"""
note = self._find_note(player)
note.text = text
def change_note_label(self, player, label):
label_id = self._get_label_id(label)
note = self._find_note(player)
note.attrib['label'] = label_id
def del_note(self, player):
"""Delete a note by player name."""
self.root.remove(self._find_note(player))
def _find_note(self, player):
# if player name contains a double quote, the search phrase would be invalid.
# " entitiy is searched with ", e.g. "bootei" is searched with '"bootei"'
quote = "'" if '"' in player else '"'
note = self.root.find('note[@player={0}{1}{0}]'.format(quote, player))
if note is None:
raise NoteNotFoundError(player)
return note
def _get_note_data(self, note):
labels = {label.get('id'): label.text for label in self.root.iter('label')}
label = note.get('label')
label = labels[label] if label != "-1" else None
timestamp = note.get('update')
if timestamp:
timestamp = int(timestamp)
update = datetime.utcfromtimestamp(timestamp).replace(tzinfo=pytz.UTC)
else:
update = None
return _Note(note.get('player'), label, update, note.text)
def get_label(self, name):
"""Find the label by name."""
label_tag = self._find_label(name)
return _Label(label_tag.get('id'), label_tag.get('color'), label_tag.text)
def add_label(self, name, color):
"""Add a new label. It's id will automatically be calculated."""
color_upper = color.upper()
if not self._color_re.match(color_upper):
raise ValueError('Invalid color: {}'.format(color))
labels_tag = self.root[0]
last_id = int(labels_tag[-1].get('id'))
new_id = str(last_id + 1)
new_label = etree.Element('label', id=new_id, color=color_upper)
new_label.text = name
labels_tag.append(new_label)
def del_label(self, name):
"""Delete a label by name."""
labels_tag = self.root[0]
labels_tag.remove(self._find_label(name))
def _find_label(self, name):
labels_tag = self.root[0]
try:
return labels_tag.xpath('label[text()="%s"]' % name)[0]
except IndexError:
raise LabelNotFoundError(name)
def _get_label_id(self, name):
return self._find_label(name).get('id') if name else '-1'
|
pokerregion/poker | poker/handhistory.py | _BaseHandHistory.board | python | def board(self):
board = []
if self.flop:
board.extend(self.flop.cards)
if self.turn:
board.append(self.turn)
if self.river:
board.append(self.river)
return tuple(board) if board else None | Calculates board from flop, turn and river. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/handhistory.py#L167-L176 | null | class _BaseHandHistory(object):
"""Abstract base class for *all* kinds of parser."""
def __init__(self, hand_text):
"""Save raw hand history."""
self.raw = hand_text.strip()
self.header_parsed = False
self.parsed = False
@classmethod
def from_file(cls, filename):
with io.open(filename, 'rt', encoding='utf-8-sig') as f:
return cls(f.read())
def __unicode__(self):
return "<{}: #{}>" .format(self.__class__.__name__, self.ident)
def __str__(self):
return unicode(self).decode('utf-8')
@property
def _parse_date(self, date_string):
"""Parse the date_string and return a datetime object as UTC."""
date = datetime.strptime(date_string, self._DATE_FORMAT)
self.date = self._TZ.localize(date).astimezone(pytz.UTC)
def _init_seats(self, player_num):
players = []
for seat in range(1, player_num + 1):
players.append(_Player(name='Empty Seat %s' % seat, stack=0, seat=seat, combo=None))
return players
def _get_hero_from_players(self, hero_name):
player_names = [p.name for p in self.players]
hero_index = player_names.index(hero_name)
return self.players[hero_index], hero_index
|
pokerregion/poker | poker/handhistory.py | _BaseHandHistory._parse_date | python | def _parse_date(self, date_string):
date = datetime.strptime(date_string, self._DATE_FORMAT)
self.date = self._TZ.localize(date).astimezone(pytz.UTC) | Parse the date_string and return a datetime object as UTC. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/handhistory.py#L178-L181 | null | class _BaseHandHistory(object):
"""Abstract base class for *all* kinds of parser."""
def __init__(self, hand_text):
"""Save raw hand history."""
self.raw = hand_text.strip()
self.header_parsed = False
self.parsed = False
@classmethod
def from_file(cls, filename):
with io.open(filename, 'rt', encoding='utf-8-sig') as f:
return cls(f.read())
def __unicode__(self):
return "<{}: #{}>" .format(self.__class__.__name__, self.ident)
def __str__(self):
return unicode(self).decode('utf-8')
@property
def board(self):
"""Calculates board from flop, turn and river."""
board = []
if self.flop:
board.extend(self.flop.cards)
if self.turn:
board.append(self.turn)
if self.river:
board.append(self.river)
return tuple(board) if board else None
def _init_seats(self, player_num):
players = []
for seat in range(1, player_num + 1):
players.append(_Player(name='Empty Seat %s' % seat, stack=0, seat=seat, combo=None))
return players
def _get_hero_from_players(self, hero_name):
player_names = [p.name for p in self.players]
hero_index = player_names.index(hero_name)
return self.players[hero_index], hero_index
|
pokerregion/poker | poker/handhistory.py | _SplittableHandHistoryMixin._split_raw | python | def _split_raw(self):
self._splitted = self._split_re.split(self.raw)
# search split locations (basically empty strings)
self._sections = [ind for ind, elem in enumerate(self._splitted) if not elem] | Split hand history by sections. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/handhistory.py#L201-L206 | null | class _SplittableHandHistoryMixin(object):
"""Class for PokerStars and FullTiltPoker type hand histories, where you can split the hand
history into sections.
"""
def _del_split_vars(self):
del self._splitted, self._sections
|
pokerregion/poker | poker/website/twoplustwo.py | ForumMember._get_timezone | python | def _get_timezone(self, root):
tz_str = root.xpath('//div[@class="smallfont" and @align="center"]')[0].text
hours = int(self._tz_re.search(tz_str).group(1))
return tzoffset(tz_str, hours * 60) | Find timezone informatation on bottom of the page. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/website/twoplustwo.py#L125-L129 | null | class ForumMember(object):
"""Download and store a member data from the Two Plus Two forum."""
_tz_re = re.compile('GMT (.*?)\.')
_attributes = (
('username', '//td[@id="username_box"]/h1/text()', unicode),
('rank', '//td[@id="username_box"]/h2/text()', unicode),
('profile_picture', '//td[@id="profilepic_cell"]/img/@src', unicode),
('location', '//div[@id="collapseobj_aboutme"]/div/ul/li/dl/dd[1]/text()', unicode),
('total_posts', '//div[@id="collapseobj_stats"]/div/fieldset[1]/ul/li[1]/text()', _make_int), # noqa
('posts_per_day', '//div[@id="collapseobj_stats"]/div/fieldset[1]/ul/li[2]/text()', float),
('public_usergroups', '//ul[@id="public_usergroup_list"]/li/text()', tuple),
('avatar', '//img[@id="user_avatar"]/@src', unicode),
)
def __init__(self, username):
self.id = search_userid(username)
self._download_and_parse()
def __repr__(self):
return '<{}: {}>'.format(self.__class__.__name__, self.username).encode('utf-8')
@classmethod
def from_userid(cls, userid):
self = super(ForumMember, cls).__new__(cls)
# we need unicode for consistency
self.id = userid.decode('utf-8')
self._download_and_parse()
return self
def _download_and_parse(self):
root = self._download_page()
self._parse_attributes(root)
tz = self._get_timezone(root)
self._parse_last_activity(root, tz)
self._parse_join_date(root)
@property
def profile_url(self):
return '{}/{}/'.format(FORUM_MEMBER_URL, self.id)
def _download_page(self):
stats_page = requests.get(self.profile_url)
self.download_date = datetime.now(UTC)
return etree.HTML(stats_page.text)
def _parse_attributes(self, root):
for attname, xpath, type_ in self._attributes:
if type_ != tuple:
try:
setattr(self, attname, type_(root.xpath(xpath)[0]))
except IndexError:
setattr(self, attname, None)
else:
setattr(self, attname, type_(root.xpath(xpath)))
def _parse_last_activity(self, root, tz):
try:
li = root.xpath('//div[@id="collapseobj_stats"]/div/fieldset[2]/ul/li[1]')[0]
date_str = li[0].tail.strip()
time_str = li[1].text.strip()
self.last_activity = self._parse_date(date_str + ' ' + time_str, tz)
except IndexError:
self.last_activity = None
def _parse_join_date(self, root):
ul = root.xpath('//div[@id="collapseobj_stats"]/div/fieldset[2]/ul')[0]
try:
join_date = ul.xpath('li[2]/text()')[0]
except IndexError:
# not everybody has a last activity field.
# in this case, it's the first li element, not the second
join_date = ul.xpath('li[1]/text()')[0]
join_date = join_date.strip()
self.join_date = datetime.strptime(join_date, '%m-%d-%Y').date()
@staticmethod
def _parse_date(date_str, tz):
try:
dt = datetime.strptime(date_str.strip(), '%m-%d-%Y %I:%M %p')
return dt.replace(tzinfo=tz).astimezone(UTC)
except ValueError:
# in case like "Yesterday 3:30 PM" or dates like that.
# calculates based on sourceTime. tz is 2p2 forum timezone
source = datetime.now(UTC).astimezone(tz)
dt, pt = parsedatetime.Calendar().parseDT(date_str, tzinfo=tz, sourceTime=source)
# parsed as a C{datetime}, means that parsing was successful
if pt == 3:
return dt.astimezone(UTC)
raise ValueError('Could not parse date: {}'.format(date_str))
|
pokerregion/poker | poker/website/pokerstars.py | get_current_tournaments | python | def get_current_tournaments():
schedule_page = requests.get(TOURNAMENTS_XML_URL)
root = etree.XML(schedule_page.content)
for tour in root.iter('{*}tournament'):
yield _Tournament(
start_date=tour.findtext('{*}start_date'),
name=tour.findtext('{*}name'),
game=tour.findtext('{*}game'),
buyin=tour.findtext('{*}buy_in_fee'),
players=tour.get('players')
) | Get the next 200 tournaments from pokerstars. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/website/pokerstars.py#L29-L42 | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division, print_function
import attr
from dateutil.parser import parse as parse_date
import requests
from lxml import etree
__all__ = ['get_current_tournaments', 'get_status', 'WEBSITE_URL', 'TOURNAMENTS_XML_URL',
'STATUS_URL']
WEBSITE_URL = 'http://www.pokerstars.eu'
TOURNAMENTS_XML_URL = WEBSITE_URL + '/datafeed_global/tournaments/all.xml'
STATUS_URL = 'http://www.psimg.com/datafeed/dyn_banners/summary.json.js'
@attr.s(slots=True)
class _Tournament(object):
"""Upcoming pokerstars tournament."""
start_date = attr.ib(convert=parse_date)
name = attr.ib()
game = attr.ib()
buyin = attr.ib()
players = attr.ib(convert=int)
@attr.s(slots=True)
class _Status(object):
"""PokerStars status."""
updated = attr.ib(convert=parse_date)
tables = attr.ib()
next_update = attr.ib()
players = attr.ib()
clubs = attr.ib()
active_tournaments = attr.ib()
total_tournaments = attr.ib()
sites = attr.ib() # list of sites, including Play Money
club_members = attr.ib()
@attr.s(slots=True)
class _SiteStatus(object):
"""PokerStars status on different subsites like FR, ES IT or Play Money."""
id = attr.ib() # ".FR", ".ES", ".IT" or 'Play Money'
tables = attr.ib()
players = attr.ib()
active_tournaments = attr.ib()
def get_status():
"""Get pokerstars status: players online, number of tables, etc."""
res = requests.get(STATUS_URL)
status = res.json()['tournaments']['summary']
# move all sites under sites attribute, including play money
sites = status.pop('site')
play_money = status.pop('play_money')
play_money['id'] = 'Play Money'
sites.append(play_money)
sites = tuple(_SiteStatus(**site) for site in sites)
return _Status(sites=sites, updated=status.pop('updated'), **status)
|
pokerregion/poker | poker/website/pokerstars.py | get_status | python | def get_status():
res = requests.get(STATUS_URL)
status = res.json()['tournaments']['summary']
# move all sites under sites attribute, including play money
sites = status.pop('site')
play_money = status.pop('play_money')
play_money['id'] = 'Play Money'
sites.append(play_money)
sites = tuple(_SiteStatus(**site) for site in sites)
return _Status(sites=sites, updated=status.pop('updated'), **status) | Get pokerstars status: players online, number of tables, etc. | train | https://github.com/pokerregion/poker/blob/2d8cf208fdf2b26bdc935972dcbe7a983a9e9768/poker/website/pokerstars.py#L68-L81 | null | # -*- coding: utf-8 -*-
from __future__ import unicode_literals, absolute_import, division, print_function
import attr
from dateutil.parser import parse as parse_date
import requests
from lxml import etree
__all__ = ['get_current_tournaments', 'get_status', 'WEBSITE_URL', 'TOURNAMENTS_XML_URL',
'STATUS_URL']
WEBSITE_URL = 'http://www.pokerstars.eu'
TOURNAMENTS_XML_URL = WEBSITE_URL + '/datafeed_global/tournaments/all.xml'
STATUS_URL = 'http://www.psimg.com/datafeed/dyn_banners/summary.json.js'
@attr.s(slots=True)
class _Tournament(object):
"""Upcoming pokerstars tournament."""
start_date = attr.ib(convert=parse_date)
name = attr.ib()
game = attr.ib()
buyin = attr.ib()
players = attr.ib(convert=int)
def get_current_tournaments():
"""Get the next 200 tournaments from pokerstars."""
schedule_page = requests.get(TOURNAMENTS_XML_URL)
root = etree.XML(schedule_page.content)
for tour in root.iter('{*}tournament'):
yield _Tournament(
start_date=tour.findtext('{*}start_date'),
name=tour.findtext('{*}name'),
game=tour.findtext('{*}game'),
buyin=tour.findtext('{*}buy_in_fee'),
players=tour.get('players')
)
@attr.s(slots=True)
class _Status(object):
"""PokerStars status."""
updated = attr.ib(convert=parse_date)
tables = attr.ib()
next_update = attr.ib()
players = attr.ib()
clubs = attr.ib()
active_tournaments = attr.ib()
total_tournaments = attr.ib()
sites = attr.ib() # list of sites, including Play Money
club_members = attr.ib()
@attr.s(slots=True)
class _SiteStatus(object):
"""PokerStars status on different subsites like FR, ES IT or Play Money."""
id = attr.ib() # ".FR", ".ES", ".IT" or 'Play Money'
tables = attr.ib()
players = attr.ib()
active_tournaments = attr.ib()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection._pack | python | def _pack(self, msg_type, payload):
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb | Packs the given message type and payload. Turns the resulting
message into a byte string. | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L401-L408 | null | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection._unpack | python | def _unpack(self, data):
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace') | Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer". | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L410-L419 | null | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection._unpack_header | python | def _unpack_header(self, data):
return struct.unpack(self._struct_header,
data[:self._struct_header_size]) | Unpacks the header of given byte string. | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L421-L426 | null | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection._recv_robust | python | def _recv_robust(self, sock, size):
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise | Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability) | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L428-L438 | null | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection._ipc_send | python | def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data | Send and receive a message from the ipc.
NOTE: this is not thread safe | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L453-L460 | [
"def _pack(self, msg_type, payload):\n \"\"\"\n Packs the given message type and payload. Turns the resulting\n message into a byte string.\n \"\"\"\n pb = payload.encode('utf-8')\n s = struct.pack('=II', len(pb), msg_type.value)\n return self.MAGIC.encode('utf-8') + s + pb\n",
"def _ipc_recv... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection.command | python | def command(self, payload):
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None | Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply. | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L490-L506 | [
"def message(self, message_type, payload):\n try:\n self.cmd_lock.acquire()\n return self._ipc_send(self.cmd_socket, message_type, payload)\n except BrokenPipeError as e:\n if not self.auto_reconnect:\n raise (e)\n\n if not self._wait_for_socket():\n raise (e)... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection.get_version | python | def get_version(self):
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply) | Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L508-L532 | [
"def message(self, message_type, payload):\n try:\n self.cmd_lock.acquire()\n return self._ipc_send(self.cmd_socket, message_type, payload)\n except BrokenPipeError as e:\n if not self.auto_reconnect:\n raise (e)\n\n if not self._wait_for_socket():\n raise (e)... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection.get_bar_config | python | def get_bar_config(self, bar_id=None):
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply) | Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L534-L549 | [
"def message(self, message_type, payload):\n try:\n self.cmd_lock.acquire()\n return self._ipc_send(self.cmd_socket, message_type, payload)\n except BrokenPipeError as e:\n if not self.auto_reconnect:\n raise (e)\n\n if not self._wait_for_socket():\n raise (e)... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection.get_bar_config_list | python | def get_bar_config_list(self):
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data) | Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`. | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L551-L559 | [
"def message(self, message_type, payload):\n try:\n self.cmd_lock.acquire()\n return self._ipc_send(self.cmd_socket, message_type, payload)\n except BrokenPipeError as e:\n if not self.auto_reconnect:\n raise (e)\n\n if not self._wait_for_socket():\n raise (e)... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection.get_outputs | python | def get_outputs(self):
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply) | Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}] | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L561-L584 | [
"def message(self, message_type, payload):\n try:\n self.cmd_lock.acquire()\n return self._ipc_send(self.cmd_socket, message_type, payload)\n except BrokenPipeError as e:\n if not self.auto_reconnect:\n raise (e)\n\n if not self._wait_for_socket():\n raise (e)... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection.get_workspaces | python | def get_workspaces(self):
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply) | Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`. | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L586-L597 | [
"def message(self, message_type, payload):\n try:\n self.cmd_lock.acquire()\n return self._ipc_send(self.cmd_socket, message_type, payload)\n except BrokenPipeError as e:\n if not self.auto_reconnect:\n raise (e)\n\n if not self._wait_for_socket():\n raise (e)... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection.get_tree | python | def get_tree(self):
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self) | Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L599-L607 | [
"def message(self, message_type, payload):\n try:\n self.cmd_lock.acquire()\n return self._ipc_send(self.cmd_socket, message_type, payload)\n except BrokenPipeError as e:\n if not self.auto_reconnect:\n raise (e)\n\n if not self._wait_for_socket():\n raise (e)... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection.get_marks | python | def get_marks(self):
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data) | Get a list of the names of all currently set marks.
:rtype: list | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L609-L616 | [
"def message(self, message_type, payload):\n try:\n self.cmd_lock.acquire()\n return self._ipc_send(self.cmd_socket, message_type, payload)\n except BrokenPipeError as e:\n if not self.auto_reconnect:\n raise (e)\n\n if not self._wait_for_socket():\n raise (e)... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection.get_binding_modes | python | def get_binding_modes(self):
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data) | Returns all currently configured binding modes.
:rtype: list | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L618-L625 | [
"def message(self, message_type, payload):\n try:\n self.cmd_lock.acquire()\n return self._ipc_send(self.cmd_socket, message_type, payload)\n except BrokenPipeError as e:\n if not self.auto_reconnect:\n raise (e)\n\n if not self._wait_for_socket():\n raise (e)... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection.get_config | python | def get_config(self):
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply) | Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L627-L635 | [
"def message(self, message_type, payload):\n try:\n self.cmd_lock.acquire()\n return self._ipc_send(self.cmd_socket, message_type, payload)\n except BrokenPipeError as e:\n if not self.auto_reconnect:\n raise (e)\n\n if not self._wait_for_socket():\n raise (e)... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def send_tick(self, payload=""):
"""
Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply
"""
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Connection.send_tick | python | def send_tick(self, payload=""):
data = self.message(MessageType.SEND_TICK, payload)
return json.loads(data, object_hook=TickReply) | Sends a tick event with the specified payload. After the reply was
received, the tick event has been written to all IPC connections which
subscribe to tick events.
:rtype: TickReply | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L637-L646 | [
"def message(self, message_type, payload):\n try:\n self.cmd_lock.acquire()\n return self._ipc_send(self.cmd_socket, message_type, payload)\n except BrokenPipeError as e:\n if not self.auto_reconnect:\n raise (e)\n\n if not self._wait_for_socket():\n raise (e)... | class Connection(object):
"""
This class controls a connection to the i3 ipc socket. It is capable of
executing commands, subscribing to window manager events, and querying the
window manager for information about the current state of windows,
workspaces, outputs, and the i3bar. For more information, see the `ipc
documentation <http://i3wm.org/docs/ipc.html>`_
:param str socket_path: The path for the socket to the current i3 session.
In most situations, you will not have to supply this yourself. Guessing
first happens by the environment variable :envvar:`I3SOCK`, and, if this is
empty, by executing :command:`i3 --get-socketpath`.
:raises Exception: If the connection to ``i3`` cannot be established, or when
the connection terminates.
"""
MAGIC = 'i3-ipc' # safety string for i3-ipc
_chunk_size = 1024 # in bytes
_timeout = 0.5 # in seconds
_struct_header = '=%dsII' % len(MAGIC.encode('utf-8'))
_struct_header_size = struct.calcsize(_struct_header)
def __init__(self, socket_path=None, auto_reconnect=False):
if not socket_path and os.environ.get("_I3IPC_TEST") is None:
socket_path = os.environ.get("I3SOCK")
if not socket_path:
socket_path = os.environ.get("SWAYSOCK")
if not socket_path:
try:
socket_path = subprocess.check_output(
['i3', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
try:
socket_path = subprocess.check_output(
['sway', '--get-socketpath'],
close_fds=True,
universal_newlines=True).strip()
except Exception:
pass
if not socket_path:
raise Exception(
'Failed to retrieve the i3 or sway IPC socket path')
if auto_reconnect:
self.subscriptions = Event.SHUTDOWN
else:
self.subscriptions = 0
self._pubsub = _PubSub(self)
self.props = _PropsObject(self)
self.socket_path = socket_path
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
self.cmd_lock = Lock()
self.sub_socket = None
self.sub_lock = Lock()
self.auto_reconnect = auto_reconnect
self._restarting = False
self._quitting = False
def _pack(self, msg_type, payload):
"""
Packs the given message type and payload. Turns the resulting
message into a byte string.
"""
pb = payload.encode('utf-8')
s = struct.pack('=II', len(pb), msg_type.value)
return self.MAGIC.encode('utf-8') + s + pb
def _unpack(self, data):
"""
Unpacks the given byte string and parses the result from JSON.
Returns None on failure and saves data into "self.buffer".
"""
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
# XXX: Message shouldn't be any longer than the data
payload = data[self._struct_header_size:msg_size]
return payload.decode('utf-8', 'replace')
def _unpack_header(self, data):
"""
Unpacks the header of given byte string.
"""
return struct.unpack(self._struct_header,
data[:self._struct_header_size])
def _recv_robust(self, sock, size):
"""
Receive size from sock, and retry if the recv() call was interrupted.
(this is only required for python2 compatability)
"""
while True:
try:
return sock.recv(size)
except socket.error as e:
if e.errno != errno.EINTR:
raise
def _ipc_recv(self, sock):
data = self._recv_robust(sock, 14)
if len(data) == 0:
# EOF
return '', 0
msg_magic, msg_length, msg_type = self._unpack_header(data)
msg_size = self._struct_header_size + msg_length
while len(data) < msg_size:
data += self._recv_robust(sock, msg_length)
return self._unpack(data), msg_type
def _ipc_send(self, sock, message_type, payload):
'''
Send and receive a message from the ipc.
NOTE: this is not thread safe
'''
sock.sendall(self._pack(message_type, payload))
data, msg_type = self._ipc_recv(sock)
return data
def _wait_for_socket(self):
# for the auto_reconnect feature only
socket_path_exists = False
for tries in range(0, 500):
socket_path_exists = os.path.exists(self.socket_path)
if socket_path_exists:
break
time.sleep(0.001)
return socket_path_exists
def message(self, message_type, payload):
try:
self.cmd_lock.acquire()
return self._ipc_send(self.cmd_socket, message_type, payload)
except BrokenPipeError as e:
if not self.auto_reconnect:
raise (e)
if not self._wait_for_socket():
raise (e)
self.cmd_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.cmd_socket.connect(self.socket_path)
return self._ipc_send(self.cmd_socket, message_type, payload)
finally:
self.cmd_lock.release()
def command(self, payload):
"""
Send a command to i3. See the `list of commands
<http://i3wm.org/docs/userguide.html#_list_of_commands>`_ in the user
guide for available commands. Pass the text of the command to execute
as the first arguments. This is essentially the same as using
``i3-msg`` or an ``exec`` block in your i3 config to control the
window manager.
:rtype: List of :class:`CommandReply` or None if the command causes i3
to restart or exit and does not give a reply.
"""
data = self.message(MessageType.COMMAND, payload)
if data:
return json.loads(data, object_hook=CommandReply)
else:
return None
def get_version(self):
"""
Get json encoded information about the running i3 instance. The
equivalent of :command:`i3-msg -t get_version`. The return
object exposes the following attributes :attr:`~VersionReply.major`,
:attr:`~VersionReply.minor`, :attr:`~VersionReply.patch`,
:attr:`~VersionReply.human_readable`, and
:attr:`~VersionReply.loaded_config_file_name`.
Example output:
.. code:: json
{'patch': 0,
'human_readable': '4.12 (2016-03-06, branch "4.12")',
'major': 4,
'minor': 12,
'loaded_config_file_name': '/home/joep/.config/i3/config'}
:rtype: VersionReply
"""
data = self.message(MessageType.GET_VERSION, '')
return json.loads(data, object_hook=VersionReply)
def get_bar_config(self, bar_id=None):
"""
Get the configuration of a single bar. Defaults to the first if none is
specified. Use :meth:`get_bar_config_list` to obtain a list of valid
IDs.
:rtype: BarConfigReply
"""
if not bar_id:
bar_config_list = self.get_bar_config_list()
if not bar_config_list:
return None
bar_id = bar_config_list[0]
data = self.message(MessageType.GET_BAR_CONFIG, bar_id)
return json.loads(data, object_hook=BarConfigReply)
def get_bar_config_list(self):
"""
Get list of bar IDs as active in the connected i3 session.
:rtype: List of strings that can be fed as ``bar_id`` into
:meth:`get_bar_config`.
"""
data = self.message(MessageType.GET_BAR_CONFIG, '')
return json.loads(data)
def get_outputs(self):
"""
Get a list of outputs. The equivalent of :command:`i3-msg -t get_outputs`.
:rtype: List of :class:`OutputReply`.
Example output:
.. code:: python
>>> i3ipc.Connection().get_outputs()
[{'name': 'eDP1',
'primary': True,
'active': True,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': '2'},
{'name': 'xroot-0',
'primary': False,
'active': False,
'rect': {'width': 1920, 'height': 1080, 'y': 0, 'x': 0},
'current_workspace': None}]
"""
data = self.message(MessageType.GET_OUTPUTS, '')
return json.loads(data, object_hook=OutputReply)
def get_workspaces(self):
"""
Get a list of workspaces. Returns JSON-like data, not a Con instance.
You might want to try the :meth:`Con.workspaces` instead if the info
contained here is too little.
:rtype: List of :class:`WorkspaceReply`.
"""
data = self.message(MessageType.GET_WORKSPACES, '')
return json.loads(data, object_hook=WorkspaceReply)
def get_tree(self):
"""
Returns a :class:`Con` instance with all kinds of methods and selectors.
Start here with exploration. Read up on the :class:`Con` stuffs.
:rtype: Con
"""
data = self.message(MessageType.GET_TREE, '')
return Con(json.loads(data), None, self)
def get_marks(self):
"""
Get a list of the names of all currently set marks.
:rtype: list
"""
data = self.message(MessageType.GET_MARKS, '')
return json.loads(data)
def get_binding_modes(self):
"""
Returns all currently configured binding modes.
:rtype: list
"""
data = self.message(MessageType.GET_BINDING_MODES, '')
return json.loads(data)
def get_config(self):
"""
Currently only contains the "config" member, which is a string
containing the config file as loaded by i3 most recently.
:rtype: ConfigReply
"""
data = self.message(MessageType.GET_CONFIG, '')
return json.loads(data, object_hook=ConfigReply)
def subscribe(self, events):
events_obj = []
if events & Event.WORKSPACE:
events_obj.append("workspace")
if events & Event.OUTPUT:
events_obj.append("output")
if events & Event.MODE:
events_obj.append("mode")
if events & Event.WINDOW:
events_obj.append("window")
if events & Event.BARCONFIG_UPDATE:
events_obj.append("barconfig_update")
if events & Event.BINDING:
events_obj.append("binding")
if events & Event.SHUTDOWN:
events_obj.append("shutdown")
if events & Event.TICK:
events_obj.append("tick")
try:
self.sub_lock.acquire()
data = self._ipc_send(self.sub_socket, MessageType.SUBSCRIBE,
json.dumps(events_obj))
finally:
self.sub_lock.release()
result = json.loads(data, object_hook=CommandReply)
self.subscriptions |= events
return result
def off(self, handler):
self._pubsub.unsubscribe(handler)
def on(self, detailed_event, handler):
event = detailed_event.replace('-', '_')
if detailed_event.count('::') > 0:
[event, __] = detailed_event.split('::')
# special case: ipc-shutdown is not in the protocol
if event == 'ipc_shutdown':
# TODO deprecate this
self._pubsub.subscribe(event, handler)
return
event_type = 0
if event == "workspace":
event_type = Event.WORKSPACE
elif event == "output":
event_type = Event.OUTPUT
elif event == "mode":
event_type = Event.MODE
elif event == "window":
event_type = Event.WINDOW
elif event == "barconfig_update":
event_type = Event.BARCONFIG_UPDATE
elif event == "binding":
event_type = Event.BINDING
elif event == "shutdown":
event_type = Event.SHUTDOWN
elif event == "tick":
event_type = Event.TICK
if not event_type:
raise Exception('event not implemented')
self.subscriptions |= event_type
self._pubsub.subscribe(detailed_event, handler)
def event_socket_setup(self):
self.sub_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.sub_socket.connect(self.socket_path)
self.subscribe(self.subscriptions)
def event_socket_teardown(self):
if self.sub_socket:
self.sub_socket.shutdown(socket.SHUT_RDWR)
self.sub_socket = None
def event_socket_poll(self):
if self.sub_socket is None:
return True
data, msg_type = self._ipc_recv(self.sub_socket)
if len(data) == 0:
# EOF
self._pubsub.emit('ipc_shutdown', None)
return True
data = json.loads(data)
msg_type = 1 << (msg_type & 0x7f)
event_name = ''
event = None
if msg_type == Event.WORKSPACE:
event_name = 'workspace'
event = WorkspaceEvent(data, self)
elif msg_type == Event.OUTPUT:
event_name = 'output'
event = GenericEvent(data)
elif msg_type == Event.MODE:
event_name = 'mode'
event = GenericEvent(data)
elif msg_type == Event.WINDOW:
event_name = 'window'
event = WindowEvent(data, self)
elif msg_type == Event.BARCONFIG_UPDATE:
event_name = 'barconfig_update'
event = BarconfigUpdateEvent(data)
elif msg_type == Event.BINDING:
event_name = 'binding'
event = BindingEvent(data)
elif msg_type == Event.SHUTDOWN:
event_name = 'shutdown'
event = GenericEvent(data)
if event.change == 'restart':
self._restarting = True
elif msg_type == Event.TICK:
event_name = 'tick'
event = TickEvent(data)
else:
# we have not implemented this event
return
self._pubsub.emit(event_name, event)
def main(self, timeout=0):
self._quitting = False
while True:
try:
self.event_socket_setup()
timer = None
if timeout:
timer = Timer(timeout, self.main_quit)
timer.start()
while not self.event_socket_poll():
pass
if timer:
timer.cancel()
finally:
self.event_socket_teardown()
if self._quitting or not self._restarting or not self.auto_reconnect:
return
self._restarting = False
# The ipc told us it's restarting and the user wants to survive
# restarts. Wait for the socket path to reappear and reconnect
# to it.
if not self._wait_for_socket():
break
def main_quit(self):
self._quitting = True
self.event_socket_teardown()
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Con.root | python | def root(self):
if not self.parent:
return self
con = self.parent
while con.parent:
con = con.parent
return con | Retrieves the root container.
:rtype: :class:`Con`. | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L1074-L1089 | null | class Con(object):
"""
The container class. Has all internal information about the windows,
outputs, workspaces and containers that :command:`i3` manages.
.. attribute:: id
The internal ID (actually a C pointer value within i3) of the container.
You can use it to (re-)identify and address containers when talking to
i3.
.. attribute:: name
The internal name of the container. ``None`` for containers which
are not leaves. The string `_NET_WM_NAME <://specifications.freedesktop.org/wm-spec/1.3/ar01s05.html#idm140238712347280>`_
for windows. Read-only value.
.. attribute:: type
The type of the container. Can be one of ``root``, ``output``, ``con``,
``floating_con``, ``workspace`` or ``dockarea``.
.. attribute:: window_title
The window title.
.. attribute:: window_class
The window class.
.. attribute:: instance
The instance name of the window class.
.. attribute:: gaps
The inner and outer gaps devation from default values.
.. attribute:: border
The type of border style for the selected container. Can be either
``normal``, ``none`` or ``1pixel``.
.. attribute:: current_border_width
Returns amount of pixels for the border. Readonly value. See `i3's user
manual <https://i3wm.org/docs/userguide.html#_border_style_for_new_windows>_
for more info.
.. attribute:: layout
Can be either ``splith``, ``splitv``, ``stacked``, ``tabbed``, ``dockarea`` or
``output``.
:rtype: string
.. attribute:: percent
The percentage which this container takes in its parent. A value of
null means that the percent property does not make sense for this
container, for example for the root container.
:rtype: float
.. attribute:: rect
The absolute display coordinates for this container. Display
coordinates means that when you have two 1600x1200 monitors on a single
X11 Display (the standard way), the coordinates of the first window on
the second monitor are ``{ "x": 1600, "y": 0, "width": 1600, "height":
1200 }``.
.. attribute:: window_rect
The coordinates of the *actual client window* inside the container,
without the window decorations that may also occupy space.
.. attribute:: deco_rect
The coordinates of the window decorations within a container. The
coordinates are relative to the container and do not include the client
window.
.. attribute:: geometry
The original geometry the window specified when i3 mapped it. Used when
switching a window to floating mode, for example.
.. attribute:: window
The X11 window ID of the client window.
.. attribute:: focus
A list of container ids describing the focus situation within the current
container. The first element refers to the container with (in)active focus.
.. attribute:: focused
Whether or not the current container is focused. There is only
one focused container.
.. attribute:: visible
Whether or not the current container is visible.
.. attribute:: num
Optional attribute that only makes sense for workspaces. This allows
for arbitrary and changeable names, even though the keyboard
shortcuts remain the same. See `the i3wm docs <https://i3wm.org/docs/userguide.html#_named_workspaces>`_
for more information
.. attribute:: urgent
Whether the window or workspace has the `urgent` state.
:returns: :bool:`True` or :bool:`False`.
.. attribute:: floating
Whether the container is floating or not. Possible values are
"auto_on", "auto_off", "user_on" and "user_off"
.. attribute:: pid
The id of the process who owns the client window
sway only, version >= 1.0-alpha.6
..
command <-- method
command_children <-- method
deco_rect IPC
descendents
find_by_id
find_by_role
find_by_window
find_classed
find_focused
find_fullscreen
find_marked
find_named
find_titled
floating
floating_nodes
fullscreen_mode
gaps
leaves
marks
nodes
orientation
parent
props
root
scratchpad
scratchpad_state
window_class
window_instance
window_rect
window_role
workspace
workspaces
"""
def __init__(self, data, parent, conn):
self.props = _PropsObject(self)
self._conn = conn
self.parent = parent
# set simple properties
ipc_properties = [
'border', 'current_border_width', 'floating', 'focus', 'focused',
'fullscreen_mode', 'id', 'layout', 'marks', 'name', 'num',
'orientation', 'percent', 'scratchpad_state', 'sticky', 'type',
'urgent', 'window', 'pid'
]
for attr in ipc_properties:
if attr in data:
setattr(self, attr, data[attr])
else:
setattr(self, attr, None)
# XXX in 4.12, marks is an array (old property was a string "mark")
if not self.marks:
self.marks = []
if 'mark' in data and data['mark']:
self.marks.append(data['mark'])
# XXX this is for compatability with 4.8
if isinstance(self.type, int):
if self.type == 0:
self.type = "root"
elif self.type == 1:
self.type = "output"
elif self.type == 2 or self.type == 3:
self.type = "con"
elif self.type == 4:
self.type = "workspace"
elif self.type == 5:
self.type = "dockarea"
# set complex properties
self.nodes = []
if 'nodes' in data:
for n in data['nodes']:
self.nodes.append(Con(n, self, conn))
self.floating_nodes = []
if 'floating_nodes' in data:
for n in data['floating_nodes']:
self.floating_nodes.append(Con(n, self, conn))
self.window_class = None
self.window_instance = None
self.window_role = None
self.window_title = None
if 'window_properties' in data:
if 'class' in data['window_properties']:
self.window_class = data['window_properties']['class']
if 'instance' in data['window_properties']:
self.window_instance = data['window_properties']['instance']
if 'window_role' in data['window_properties']:
self.window_role = data['window_properties']['window_role']
if 'title' in data['window_properties']:
self.window_title = data['window_properties']['title']
self.rect = Rect(data['rect'])
if 'window_rect' in data:
self.window_rect = Rect(data['window_rect'])
if 'deco_rect' in data:
self.deco_rect = Rect(data['deco_rect'])
self.gaps = None
if 'gaps' in data:
self.gaps = Gaps(data['gaps'])
def __iter__(self):
"""
Iterate through the descendents of this node (breadth-first tree traversal)
"""
queue = deque(self.nodes)
queue.extend(self.floating_nodes)
while queue:
con = queue.popleft()
yield con
queue.extend(con.nodes)
queue.extend(con.floating_nodes)
def descendents(self):
"""
Retrieve a list of all containers that delineate from the currently
selected container. Includes any kind of container.
:rtype: List of :class:`Con`.
"""
return [c for c in self]
def leaves(self):
"""
Retrieve a list of windows that delineate from the currently
selected container. Only lists client windows, no intermediate
containers.
:rtype: List of :class:`Con`.
"""
leaves = []
for c in self:
if not c.nodes and c.type == "con" and c.parent.type != "dockarea":
leaves.append(c)
return leaves
def command(self, command):
"""
Run a command on the currently active container.
:rtype: CommandReply
"""
return self._conn.command('[con_id="{}"] {}'.format(self.id, command))
def command_children(self, command):
"""
Run a command on the direct children of the currently selected
container.
:rtype: List of CommandReply????
"""
if not len(self.nodes):
return
commands = []
for c in self.nodes:
commands.append('[con_id="{}"] {};'.format(c.id, command))
self._conn.command(' '.join(commands))
def workspaces(self):
"""
Retrieve a list of currently active workspaces.
:rtype: List of :class:`Con`.
"""
workspaces = []
def collect_workspaces(con):
if con.type == "workspace" and not con.name.startswith('__'):
workspaces.append(con)
return
for c in con.nodes:
collect_workspaces(c)
collect_workspaces(self.root())
return workspaces
def find_focused(self):
"""
Finds the focused container.
:rtype class Con:
"""
try:
return next(c for c in self if c.focused)
except StopIteration:
return None
def find_by_id(self, id):
try:
return next(c for c in self if c.id == id)
except StopIteration:
return None
def find_by_window(self, window):
try:
return next(c for c in self if c.window == window)
except StopIteration:
return None
def find_by_role(self, pattern):
return [
c for c in self
if c.window_role and re.search(pattern, c.window_role)
]
def find_named(self, pattern):
return [c for c in self if c.name and re.search(pattern, c.name)]
def find_titled(self, pattern):
return [c for c in self if c.window_title and re.search(pattern, c.window_title)]
def find_classed(self, pattern):
return [
c for c in self
if c.window_class and re.search(pattern, c.window_class)
]
def find_instanced(self, pattern):
return [
c for c in self
if c.window_instance and re.search(pattern, c.window_instance)
]
def find_marked(self, pattern=".*"):
pattern = re.compile(pattern)
return [
c for c in self if any(pattern.search(mark) for mark in c.marks)
]
def find_fullscreen(self):
return [c for c in self if c.type == 'con' and c.fullscreen_mode]
def workspace(self):
if self.type == 'workspace':
return self
ret = self.parent
while ret:
if ret.type == 'workspace':
break
ret = ret.parent
return ret
def scratchpad(self):
root = self.root()
i3con = None
for c in root.nodes:
if c.name == "__i3":
i3con = c
break
if not i3con:
return None
i3con_content = None
for c in i3con.nodes:
if c.name == "content":
i3con_content = c
break
if not i3con_content:
return None
scratch = None
for c in i3con_content.nodes:
if c.name == "__i3_scratch":
scratch = c
break
return scratch
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Con.leaves | python | def leaves(self):
leaves = []
for c in self:
if not c.nodes and c.type == "con" and c.parent.type != "dockarea":
leaves.append(c)
return leaves | Retrieve a list of windows that delineate from the currently
selected container. Only lists client windows, no intermediate
containers.
:rtype: List of :class:`Con`. | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L1100-L1114 | null | class Con(object):
"""
The container class. Has all internal information about the windows,
outputs, workspaces and containers that :command:`i3` manages.
.. attribute:: id
The internal ID (actually a C pointer value within i3) of the container.
You can use it to (re-)identify and address containers when talking to
i3.
.. attribute:: name
The internal name of the container. ``None`` for containers which
are not leaves. The string `_NET_WM_NAME <://specifications.freedesktop.org/wm-spec/1.3/ar01s05.html#idm140238712347280>`_
for windows. Read-only value.
.. attribute:: type
The type of the container. Can be one of ``root``, ``output``, ``con``,
``floating_con``, ``workspace`` or ``dockarea``.
.. attribute:: window_title
The window title.
.. attribute:: window_class
The window class.
.. attribute:: instance
The instance name of the window class.
.. attribute:: gaps
The inner and outer gaps devation from default values.
.. attribute:: border
The type of border style for the selected container. Can be either
``normal``, ``none`` or ``1pixel``.
.. attribute:: current_border_width
Returns amount of pixels for the border. Readonly value. See `i3's user
manual <https://i3wm.org/docs/userguide.html#_border_style_for_new_windows>_
for more info.
.. attribute:: layout
Can be either ``splith``, ``splitv``, ``stacked``, ``tabbed``, ``dockarea`` or
``output``.
:rtype: string
.. attribute:: percent
The percentage which this container takes in its parent. A value of
null means that the percent property does not make sense for this
container, for example for the root container.
:rtype: float
.. attribute:: rect
The absolute display coordinates for this container. Display
coordinates means that when you have two 1600x1200 monitors on a single
X11 Display (the standard way), the coordinates of the first window on
the second monitor are ``{ "x": 1600, "y": 0, "width": 1600, "height":
1200 }``.
.. attribute:: window_rect
The coordinates of the *actual client window* inside the container,
without the window decorations that may also occupy space.
.. attribute:: deco_rect
The coordinates of the window decorations within a container. The
coordinates are relative to the container and do not include the client
window.
.. attribute:: geometry
The original geometry the window specified when i3 mapped it. Used when
switching a window to floating mode, for example.
.. attribute:: window
The X11 window ID of the client window.
.. attribute:: focus
A list of container ids describing the focus situation within the current
container. The first element refers to the container with (in)active focus.
.. attribute:: focused
Whether or not the current container is focused. There is only
one focused container.
.. attribute:: visible
Whether or not the current container is visible.
.. attribute:: num
Optional attribute that only makes sense for workspaces. This allows
for arbitrary and changeable names, even though the keyboard
shortcuts remain the same. See `the i3wm docs <https://i3wm.org/docs/userguide.html#_named_workspaces>`_
for more information
.. attribute:: urgent
Whether the window or workspace has the `urgent` state.
:returns: :bool:`True` or :bool:`False`.
.. attribute:: floating
Whether the container is floating or not. Possible values are
"auto_on", "auto_off", "user_on" and "user_off"
.. attribute:: pid
The id of the process who owns the client window
sway only, version >= 1.0-alpha.6
..
command <-- method
command_children <-- method
deco_rect IPC
descendents
find_by_id
find_by_role
find_by_window
find_classed
find_focused
find_fullscreen
find_marked
find_named
find_titled
floating
floating_nodes
fullscreen_mode
gaps
leaves
marks
nodes
orientation
parent
props
root
scratchpad
scratchpad_state
window_class
window_instance
window_rect
window_role
workspace
workspaces
"""
def __init__(self, data, parent, conn):
self.props = _PropsObject(self)
self._conn = conn
self.parent = parent
# set simple properties
ipc_properties = [
'border', 'current_border_width', 'floating', 'focus', 'focused',
'fullscreen_mode', 'id', 'layout', 'marks', 'name', 'num',
'orientation', 'percent', 'scratchpad_state', 'sticky', 'type',
'urgent', 'window', 'pid'
]
for attr in ipc_properties:
if attr in data:
setattr(self, attr, data[attr])
else:
setattr(self, attr, None)
# XXX in 4.12, marks is an array (old property was a string "mark")
if not self.marks:
self.marks = []
if 'mark' in data and data['mark']:
self.marks.append(data['mark'])
# XXX this is for compatability with 4.8
if isinstance(self.type, int):
if self.type == 0:
self.type = "root"
elif self.type == 1:
self.type = "output"
elif self.type == 2 or self.type == 3:
self.type = "con"
elif self.type == 4:
self.type = "workspace"
elif self.type == 5:
self.type = "dockarea"
# set complex properties
self.nodes = []
if 'nodes' in data:
for n in data['nodes']:
self.nodes.append(Con(n, self, conn))
self.floating_nodes = []
if 'floating_nodes' in data:
for n in data['floating_nodes']:
self.floating_nodes.append(Con(n, self, conn))
self.window_class = None
self.window_instance = None
self.window_role = None
self.window_title = None
if 'window_properties' in data:
if 'class' in data['window_properties']:
self.window_class = data['window_properties']['class']
if 'instance' in data['window_properties']:
self.window_instance = data['window_properties']['instance']
if 'window_role' in data['window_properties']:
self.window_role = data['window_properties']['window_role']
if 'title' in data['window_properties']:
self.window_title = data['window_properties']['title']
self.rect = Rect(data['rect'])
if 'window_rect' in data:
self.window_rect = Rect(data['window_rect'])
if 'deco_rect' in data:
self.deco_rect = Rect(data['deco_rect'])
self.gaps = None
if 'gaps' in data:
self.gaps = Gaps(data['gaps'])
def __iter__(self):
"""
Iterate through the descendents of this node (breadth-first tree traversal)
"""
queue = deque(self.nodes)
queue.extend(self.floating_nodes)
while queue:
con = queue.popleft()
yield con
queue.extend(con.nodes)
queue.extend(con.floating_nodes)
def root(self):
"""
Retrieves the root container.
:rtype: :class:`Con`.
"""
if not self.parent:
return self
con = self.parent
while con.parent:
con = con.parent
return con
def descendents(self):
"""
Retrieve a list of all containers that delineate from the currently
selected container. Includes any kind of container.
:rtype: List of :class:`Con`.
"""
return [c for c in self]
def command(self, command):
"""
Run a command on the currently active container.
:rtype: CommandReply
"""
return self._conn.command('[con_id="{}"] {}'.format(self.id, command))
def command_children(self, command):
"""
Run a command on the direct children of the currently selected
container.
:rtype: List of CommandReply????
"""
if not len(self.nodes):
return
commands = []
for c in self.nodes:
commands.append('[con_id="{}"] {};'.format(c.id, command))
self._conn.command(' '.join(commands))
def workspaces(self):
"""
Retrieve a list of currently active workspaces.
:rtype: List of :class:`Con`.
"""
workspaces = []
def collect_workspaces(con):
if con.type == "workspace" and not con.name.startswith('__'):
workspaces.append(con)
return
for c in con.nodes:
collect_workspaces(c)
collect_workspaces(self.root())
return workspaces
def find_focused(self):
"""
Finds the focused container.
:rtype class Con:
"""
try:
return next(c for c in self if c.focused)
except StopIteration:
return None
def find_by_id(self, id):
try:
return next(c for c in self if c.id == id)
except StopIteration:
return None
def find_by_window(self, window):
try:
return next(c for c in self if c.window == window)
except StopIteration:
return None
def find_by_role(self, pattern):
return [
c for c in self
if c.window_role and re.search(pattern, c.window_role)
]
def find_named(self, pattern):
return [c for c in self if c.name and re.search(pattern, c.name)]
def find_titled(self, pattern):
return [c for c in self if c.window_title and re.search(pattern, c.window_title)]
def find_classed(self, pattern):
return [
c for c in self
if c.window_class and re.search(pattern, c.window_class)
]
def find_instanced(self, pattern):
return [
c for c in self
if c.window_instance and re.search(pattern, c.window_instance)
]
def find_marked(self, pattern=".*"):
pattern = re.compile(pattern)
return [
c for c in self if any(pattern.search(mark) for mark in c.marks)
]
def find_fullscreen(self):
return [c for c in self if c.type == 'con' and c.fullscreen_mode]
def workspace(self):
if self.type == 'workspace':
return self
ret = self.parent
while ret:
if ret.type == 'workspace':
break
ret = ret.parent
return ret
def scratchpad(self):
root = self.root()
i3con = None
for c in root.nodes:
if c.name == "__i3":
i3con = c
break
if not i3con:
return None
i3con_content = None
for c in i3con.nodes:
if c.name == "content":
i3con_content = c
break
if not i3con_content:
return None
scratch = None
for c in i3con_content.nodes:
if c.name == "__i3_scratch":
scratch = c
break
return scratch
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Con.command | python | def command(self, command):
return self._conn.command('[con_id="{}"] {}'.format(self.id, command)) | Run a command on the currently active container.
:rtype: CommandReply | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L1116-L1122 | null | class Con(object):
"""
The container class. Has all internal information about the windows,
outputs, workspaces and containers that :command:`i3` manages.
.. attribute:: id
The internal ID (actually a C pointer value within i3) of the container.
You can use it to (re-)identify and address containers when talking to
i3.
.. attribute:: name
The internal name of the container. ``None`` for containers which
are not leaves. The string `_NET_WM_NAME <://specifications.freedesktop.org/wm-spec/1.3/ar01s05.html#idm140238712347280>`_
for windows. Read-only value.
.. attribute:: type
The type of the container. Can be one of ``root``, ``output``, ``con``,
``floating_con``, ``workspace`` or ``dockarea``.
.. attribute:: window_title
The window title.
.. attribute:: window_class
The window class.
.. attribute:: instance
The instance name of the window class.
.. attribute:: gaps
The inner and outer gaps devation from default values.
.. attribute:: border
The type of border style for the selected container. Can be either
``normal``, ``none`` or ``1pixel``.
.. attribute:: current_border_width
Returns amount of pixels for the border. Readonly value. See `i3's user
manual <https://i3wm.org/docs/userguide.html#_border_style_for_new_windows>_
for more info.
.. attribute:: layout
Can be either ``splith``, ``splitv``, ``stacked``, ``tabbed``, ``dockarea`` or
``output``.
:rtype: string
.. attribute:: percent
The percentage which this container takes in its parent. A value of
null means that the percent property does not make sense for this
container, for example for the root container.
:rtype: float
.. attribute:: rect
The absolute display coordinates for this container. Display
coordinates means that when you have two 1600x1200 monitors on a single
X11 Display (the standard way), the coordinates of the first window on
the second monitor are ``{ "x": 1600, "y": 0, "width": 1600, "height":
1200 }``.
.. attribute:: window_rect
The coordinates of the *actual client window* inside the container,
without the window decorations that may also occupy space.
.. attribute:: deco_rect
The coordinates of the window decorations within a container. The
coordinates are relative to the container and do not include the client
window.
.. attribute:: geometry
The original geometry the window specified when i3 mapped it. Used when
switching a window to floating mode, for example.
.. attribute:: window
The X11 window ID of the client window.
.. attribute:: focus
A list of container ids describing the focus situation within the current
container. The first element refers to the container with (in)active focus.
.. attribute:: focused
Whether or not the current container is focused. There is only
one focused container.
.. attribute:: visible
Whether or not the current container is visible.
.. attribute:: num
Optional attribute that only makes sense for workspaces. This allows
for arbitrary and changeable names, even though the keyboard
shortcuts remain the same. See `the i3wm docs <https://i3wm.org/docs/userguide.html#_named_workspaces>`_
for more information
.. attribute:: urgent
Whether the window or workspace has the `urgent` state.
:returns: :bool:`True` or :bool:`False`.
.. attribute:: floating
Whether the container is floating or not. Possible values are
"auto_on", "auto_off", "user_on" and "user_off"
.. attribute:: pid
The id of the process who owns the client window
sway only, version >= 1.0-alpha.6
..
command <-- method
command_children <-- method
deco_rect IPC
descendents
find_by_id
find_by_role
find_by_window
find_classed
find_focused
find_fullscreen
find_marked
find_named
find_titled
floating
floating_nodes
fullscreen_mode
gaps
leaves
marks
nodes
orientation
parent
props
root
scratchpad
scratchpad_state
window_class
window_instance
window_rect
window_role
workspace
workspaces
"""
def __init__(self, data, parent, conn):
self.props = _PropsObject(self)
self._conn = conn
self.parent = parent
# set simple properties
ipc_properties = [
'border', 'current_border_width', 'floating', 'focus', 'focused',
'fullscreen_mode', 'id', 'layout', 'marks', 'name', 'num',
'orientation', 'percent', 'scratchpad_state', 'sticky', 'type',
'urgent', 'window', 'pid'
]
for attr in ipc_properties:
if attr in data:
setattr(self, attr, data[attr])
else:
setattr(self, attr, None)
# XXX in 4.12, marks is an array (old property was a string "mark")
if not self.marks:
self.marks = []
if 'mark' in data and data['mark']:
self.marks.append(data['mark'])
# XXX this is for compatability with 4.8
if isinstance(self.type, int):
if self.type == 0:
self.type = "root"
elif self.type == 1:
self.type = "output"
elif self.type == 2 or self.type == 3:
self.type = "con"
elif self.type == 4:
self.type = "workspace"
elif self.type == 5:
self.type = "dockarea"
# set complex properties
self.nodes = []
if 'nodes' in data:
for n in data['nodes']:
self.nodes.append(Con(n, self, conn))
self.floating_nodes = []
if 'floating_nodes' in data:
for n in data['floating_nodes']:
self.floating_nodes.append(Con(n, self, conn))
self.window_class = None
self.window_instance = None
self.window_role = None
self.window_title = None
if 'window_properties' in data:
if 'class' in data['window_properties']:
self.window_class = data['window_properties']['class']
if 'instance' in data['window_properties']:
self.window_instance = data['window_properties']['instance']
if 'window_role' in data['window_properties']:
self.window_role = data['window_properties']['window_role']
if 'title' in data['window_properties']:
self.window_title = data['window_properties']['title']
self.rect = Rect(data['rect'])
if 'window_rect' in data:
self.window_rect = Rect(data['window_rect'])
if 'deco_rect' in data:
self.deco_rect = Rect(data['deco_rect'])
self.gaps = None
if 'gaps' in data:
self.gaps = Gaps(data['gaps'])
def __iter__(self):
"""
Iterate through the descendents of this node (breadth-first tree traversal)
"""
queue = deque(self.nodes)
queue.extend(self.floating_nodes)
while queue:
con = queue.popleft()
yield con
queue.extend(con.nodes)
queue.extend(con.floating_nodes)
def root(self):
"""
Retrieves the root container.
:rtype: :class:`Con`.
"""
if not self.parent:
return self
con = self.parent
while con.parent:
con = con.parent
return con
def descendents(self):
"""
Retrieve a list of all containers that delineate from the currently
selected container. Includes any kind of container.
:rtype: List of :class:`Con`.
"""
return [c for c in self]
def leaves(self):
"""
Retrieve a list of windows that delineate from the currently
selected container. Only lists client windows, no intermediate
containers.
:rtype: List of :class:`Con`.
"""
leaves = []
for c in self:
if not c.nodes and c.type == "con" and c.parent.type != "dockarea":
leaves.append(c)
return leaves
def command_children(self, command):
"""
Run a command on the direct children of the currently selected
container.
:rtype: List of CommandReply????
"""
if not len(self.nodes):
return
commands = []
for c in self.nodes:
commands.append('[con_id="{}"] {};'.format(c.id, command))
self._conn.command(' '.join(commands))
def workspaces(self):
"""
Retrieve a list of currently active workspaces.
:rtype: List of :class:`Con`.
"""
workspaces = []
def collect_workspaces(con):
if con.type == "workspace" and not con.name.startswith('__'):
workspaces.append(con)
return
for c in con.nodes:
collect_workspaces(c)
collect_workspaces(self.root())
return workspaces
def find_focused(self):
"""
Finds the focused container.
:rtype class Con:
"""
try:
return next(c for c in self if c.focused)
except StopIteration:
return None
def find_by_id(self, id):
try:
return next(c for c in self if c.id == id)
except StopIteration:
return None
def find_by_window(self, window):
try:
return next(c for c in self if c.window == window)
except StopIteration:
return None
def find_by_role(self, pattern):
return [
c for c in self
if c.window_role and re.search(pattern, c.window_role)
]
def find_named(self, pattern):
return [c for c in self if c.name and re.search(pattern, c.name)]
def find_titled(self, pattern):
return [c for c in self if c.window_title and re.search(pattern, c.window_title)]
def find_classed(self, pattern):
return [
c for c in self
if c.window_class and re.search(pattern, c.window_class)
]
def find_instanced(self, pattern):
return [
c for c in self
if c.window_instance and re.search(pattern, c.window_instance)
]
def find_marked(self, pattern=".*"):
pattern = re.compile(pattern)
return [
c for c in self if any(pattern.search(mark) for mark in c.marks)
]
def find_fullscreen(self):
return [c for c in self if c.type == 'con' and c.fullscreen_mode]
def workspace(self):
if self.type == 'workspace':
return self
ret = self.parent
while ret:
if ret.type == 'workspace':
break
ret = ret.parent
return ret
def scratchpad(self):
root = self.root()
i3con = None
for c in root.nodes:
if c.name == "__i3":
i3con = c
break
if not i3con:
return None
i3con_content = None
for c in i3con.nodes:
if c.name == "content":
i3con_content = c
break
if not i3con_content:
return None
scratch = None
for c in i3con_content.nodes:
if c.name == "__i3_scratch":
scratch = c
break
return scratch
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Con.command_children | python | def command_children(self, command):
if not len(self.nodes):
return
commands = []
for c in self.nodes:
commands.append('[con_id="{}"] {};'.format(c.id, command))
self._conn.command(' '.join(commands)) | Run a command on the direct children of the currently selected
container.
:rtype: List of CommandReply???? | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L1124-L1138 | null | class Con(object):
"""
The container class. Has all internal information about the windows,
outputs, workspaces and containers that :command:`i3` manages.
.. attribute:: id
The internal ID (actually a C pointer value within i3) of the container.
You can use it to (re-)identify and address containers when talking to
i3.
.. attribute:: name
The internal name of the container. ``None`` for containers which
are not leaves. The string `_NET_WM_NAME <://specifications.freedesktop.org/wm-spec/1.3/ar01s05.html#idm140238712347280>`_
for windows. Read-only value.
.. attribute:: type
The type of the container. Can be one of ``root``, ``output``, ``con``,
``floating_con``, ``workspace`` or ``dockarea``.
.. attribute:: window_title
The window title.
.. attribute:: window_class
The window class.
.. attribute:: instance
The instance name of the window class.
.. attribute:: gaps
The inner and outer gaps devation from default values.
.. attribute:: border
The type of border style for the selected container. Can be either
``normal``, ``none`` or ``1pixel``.
.. attribute:: current_border_width
Returns amount of pixels for the border. Readonly value. See `i3's user
manual <https://i3wm.org/docs/userguide.html#_border_style_for_new_windows>_
for more info.
.. attribute:: layout
Can be either ``splith``, ``splitv``, ``stacked``, ``tabbed``, ``dockarea`` or
``output``.
:rtype: string
.. attribute:: percent
The percentage which this container takes in its parent. A value of
null means that the percent property does not make sense for this
container, for example for the root container.
:rtype: float
.. attribute:: rect
The absolute display coordinates for this container. Display
coordinates means that when you have two 1600x1200 monitors on a single
X11 Display (the standard way), the coordinates of the first window on
the second monitor are ``{ "x": 1600, "y": 0, "width": 1600, "height":
1200 }``.
.. attribute:: window_rect
The coordinates of the *actual client window* inside the container,
without the window decorations that may also occupy space.
.. attribute:: deco_rect
The coordinates of the window decorations within a container. The
coordinates are relative to the container and do not include the client
window.
.. attribute:: geometry
The original geometry the window specified when i3 mapped it. Used when
switching a window to floating mode, for example.
.. attribute:: window
The X11 window ID of the client window.
.. attribute:: focus
A list of container ids describing the focus situation within the current
container. The first element refers to the container with (in)active focus.
.. attribute:: focused
Whether or not the current container is focused. There is only
one focused container.
.. attribute:: visible
Whether or not the current container is visible.
.. attribute:: num
Optional attribute that only makes sense for workspaces. This allows
for arbitrary and changeable names, even though the keyboard
shortcuts remain the same. See `the i3wm docs <https://i3wm.org/docs/userguide.html#_named_workspaces>`_
for more information
.. attribute:: urgent
Whether the window or workspace has the `urgent` state.
:returns: :bool:`True` or :bool:`False`.
.. attribute:: floating
Whether the container is floating or not. Possible values are
"auto_on", "auto_off", "user_on" and "user_off"
.. attribute:: pid
The id of the process who owns the client window
sway only, version >= 1.0-alpha.6
..
command <-- method
command_children <-- method
deco_rect IPC
descendents
find_by_id
find_by_role
find_by_window
find_classed
find_focused
find_fullscreen
find_marked
find_named
find_titled
floating
floating_nodes
fullscreen_mode
gaps
leaves
marks
nodes
orientation
parent
props
root
scratchpad
scratchpad_state
window_class
window_instance
window_rect
window_role
workspace
workspaces
"""
def __init__(self, data, parent, conn):
self.props = _PropsObject(self)
self._conn = conn
self.parent = parent
# set simple properties
ipc_properties = [
'border', 'current_border_width', 'floating', 'focus', 'focused',
'fullscreen_mode', 'id', 'layout', 'marks', 'name', 'num',
'orientation', 'percent', 'scratchpad_state', 'sticky', 'type',
'urgent', 'window', 'pid'
]
for attr in ipc_properties:
if attr in data:
setattr(self, attr, data[attr])
else:
setattr(self, attr, None)
# XXX in 4.12, marks is an array (old property was a string "mark")
if not self.marks:
self.marks = []
if 'mark' in data and data['mark']:
self.marks.append(data['mark'])
# XXX this is for compatability with 4.8
if isinstance(self.type, int):
if self.type == 0:
self.type = "root"
elif self.type == 1:
self.type = "output"
elif self.type == 2 or self.type == 3:
self.type = "con"
elif self.type == 4:
self.type = "workspace"
elif self.type == 5:
self.type = "dockarea"
# set complex properties
self.nodes = []
if 'nodes' in data:
for n in data['nodes']:
self.nodes.append(Con(n, self, conn))
self.floating_nodes = []
if 'floating_nodes' in data:
for n in data['floating_nodes']:
self.floating_nodes.append(Con(n, self, conn))
self.window_class = None
self.window_instance = None
self.window_role = None
self.window_title = None
if 'window_properties' in data:
if 'class' in data['window_properties']:
self.window_class = data['window_properties']['class']
if 'instance' in data['window_properties']:
self.window_instance = data['window_properties']['instance']
if 'window_role' in data['window_properties']:
self.window_role = data['window_properties']['window_role']
if 'title' in data['window_properties']:
self.window_title = data['window_properties']['title']
self.rect = Rect(data['rect'])
if 'window_rect' in data:
self.window_rect = Rect(data['window_rect'])
if 'deco_rect' in data:
self.deco_rect = Rect(data['deco_rect'])
self.gaps = None
if 'gaps' in data:
self.gaps = Gaps(data['gaps'])
def __iter__(self):
"""
Iterate through the descendents of this node (breadth-first tree traversal)
"""
queue = deque(self.nodes)
queue.extend(self.floating_nodes)
while queue:
con = queue.popleft()
yield con
queue.extend(con.nodes)
queue.extend(con.floating_nodes)
def root(self):
"""
Retrieves the root container.
:rtype: :class:`Con`.
"""
if not self.parent:
return self
con = self.parent
while con.parent:
con = con.parent
return con
def descendents(self):
"""
Retrieve a list of all containers that delineate from the currently
selected container. Includes any kind of container.
:rtype: List of :class:`Con`.
"""
return [c for c in self]
def leaves(self):
"""
Retrieve a list of windows that delineate from the currently
selected container. Only lists client windows, no intermediate
containers.
:rtype: List of :class:`Con`.
"""
leaves = []
for c in self:
if not c.nodes and c.type == "con" and c.parent.type != "dockarea":
leaves.append(c)
return leaves
def command(self, command):
"""
Run a command on the currently active container.
:rtype: CommandReply
"""
return self._conn.command('[con_id="{}"] {}'.format(self.id, command))
def workspaces(self):
"""
Retrieve a list of currently active workspaces.
:rtype: List of :class:`Con`.
"""
workspaces = []
def collect_workspaces(con):
if con.type == "workspace" and not con.name.startswith('__'):
workspaces.append(con)
return
for c in con.nodes:
collect_workspaces(c)
collect_workspaces(self.root())
return workspaces
def find_focused(self):
"""
Finds the focused container.
:rtype class Con:
"""
try:
return next(c for c in self if c.focused)
except StopIteration:
return None
def find_by_id(self, id):
try:
return next(c for c in self if c.id == id)
except StopIteration:
return None
def find_by_window(self, window):
try:
return next(c for c in self if c.window == window)
except StopIteration:
return None
def find_by_role(self, pattern):
return [
c for c in self
if c.window_role and re.search(pattern, c.window_role)
]
def find_named(self, pattern):
return [c for c in self if c.name and re.search(pattern, c.name)]
def find_titled(self, pattern):
return [c for c in self if c.window_title and re.search(pattern, c.window_title)]
def find_classed(self, pattern):
return [
c for c in self
if c.window_class and re.search(pattern, c.window_class)
]
def find_instanced(self, pattern):
return [
c for c in self
if c.window_instance and re.search(pattern, c.window_instance)
]
def find_marked(self, pattern=".*"):
pattern = re.compile(pattern)
return [
c for c in self if any(pattern.search(mark) for mark in c.marks)
]
def find_fullscreen(self):
return [c for c in self if c.type == 'con' and c.fullscreen_mode]
def workspace(self):
if self.type == 'workspace':
return self
ret = self.parent
while ret:
if ret.type == 'workspace':
break
ret = ret.parent
return ret
def scratchpad(self):
root = self.root()
i3con = None
for c in root.nodes:
if c.name == "__i3":
i3con = c
break
if not i3con:
return None
i3con_content = None
for c in i3con.nodes:
if c.name == "content":
i3con_content = c
break
if not i3con_content:
return None
scratch = None
for c in i3con_content.nodes:
if c.name == "__i3_scratch":
scratch = c
break
return scratch
|
acrisci/i3ipc-python | i3ipc/i3ipc.py | Con.workspaces | python | def workspaces(self):
workspaces = []
def collect_workspaces(con):
if con.type == "workspace" and not con.name.startswith('__'):
workspaces.append(con)
return
for c in con.nodes:
collect_workspaces(c)
collect_workspaces(self.root())
return workspaces | Retrieve a list of currently active workspaces.
:rtype: List of :class:`Con`. | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/i3ipc/i3ipc.py#L1140-L1157 | [
"def root(self):\n \"\"\"\n Retrieves the root container.\n\n :rtype: :class:`Con`.\n \"\"\"\n\n if not self.parent:\n return self\n\n con = self.parent\n\n while con.parent:\n con = con.parent\n\n return con\n",
"def collect_workspaces(con):\n if con.type == \"workspace\"... | class Con(object):
"""
The container class. Has all internal information about the windows,
outputs, workspaces and containers that :command:`i3` manages.
.. attribute:: id
The internal ID (actually a C pointer value within i3) of the container.
You can use it to (re-)identify and address containers when talking to
i3.
.. attribute:: name
The internal name of the container. ``None`` for containers which
are not leaves. The string `_NET_WM_NAME <://specifications.freedesktop.org/wm-spec/1.3/ar01s05.html#idm140238712347280>`_
for windows. Read-only value.
.. attribute:: type
The type of the container. Can be one of ``root``, ``output``, ``con``,
``floating_con``, ``workspace`` or ``dockarea``.
.. attribute:: window_title
The window title.
.. attribute:: window_class
The window class.
.. attribute:: instance
The instance name of the window class.
.. attribute:: gaps
The inner and outer gaps devation from default values.
.. attribute:: border
The type of border style for the selected container. Can be either
``normal``, ``none`` or ``1pixel``.
.. attribute:: current_border_width
Returns amount of pixels for the border. Readonly value. See `i3's user
manual <https://i3wm.org/docs/userguide.html#_border_style_for_new_windows>_
for more info.
.. attribute:: layout
Can be either ``splith``, ``splitv``, ``stacked``, ``tabbed``, ``dockarea`` or
``output``.
:rtype: string
.. attribute:: percent
The percentage which this container takes in its parent. A value of
null means that the percent property does not make sense for this
container, for example for the root container.
:rtype: float
.. attribute:: rect
The absolute display coordinates for this container. Display
coordinates means that when you have two 1600x1200 monitors on a single
X11 Display (the standard way), the coordinates of the first window on
the second monitor are ``{ "x": 1600, "y": 0, "width": 1600, "height":
1200 }``.
.. attribute:: window_rect
The coordinates of the *actual client window* inside the container,
without the window decorations that may also occupy space.
.. attribute:: deco_rect
The coordinates of the window decorations within a container. The
coordinates are relative to the container and do not include the client
window.
.. attribute:: geometry
The original geometry the window specified when i3 mapped it. Used when
switching a window to floating mode, for example.
.. attribute:: window
The X11 window ID of the client window.
.. attribute:: focus
A list of container ids describing the focus situation within the current
container. The first element refers to the container with (in)active focus.
.. attribute:: focused
Whether or not the current container is focused. There is only
one focused container.
.. attribute:: visible
Whether or not the current container is visible.
.. attribute:: num
Optional attribute that only makes sense for workspaces. This allows
for arbitrary and changeable names, even though the keyboard
shortcuts remain the same. See `the i3wm docs <https://i3wm.org/docs/userguide.html#_named_workspaces>`_
for more information
.. attribute:: urgent
Whether the window or workspace has the `urgent` state.
:returns: :bool:`True` or :bool:`False`.
.. attribute:: floating
Whether the container is floating or not. Possible values are
"auto_on", "auto_off", "user_on" and "user_off"
.. attribute:: pid
The id of the process who owns the client window
sway only, version >= 1.0-alpha.6
..
command <-- method
command_children <-- method
deco_rect IPC
descendents
find_by_id
find_by_role
find_by_window
find_classed
find_focused
find_fullscreen
find_marked
find_named
find_titled
floating
floating_nodes
fullscreen_mode
gaps
leaves
marks
nodes
orientation
parent
props
root
scratchpad
scratchpad_state
window_class
window_instance
window_rect
window_role
workspace
workspaces
"""
def __init__(self, data, parent, conn):
self.props = _PropsObject(self)
self._conn = conn
self.parent = parent
# set simple properties
ipc_properties = [
'border', 'current_border_width', 'floating', 'focus', 'focused',
'fullscreen_mode', 'id', 'layout', 'marks', 'name', 'num',
'orientation', 'percent', 'scratchpad_state', 'sticky', 'type',
'urgent', 'window', 'pid'
]
for attr in ipc_properties:
if attr in data:
setattr(self, attr, data[attr])
else:
setattr(self, attr, None)
# XXX in 4.12, marks is an array (old property was a string "mark")
if not self.marks:
self.marks = []
if 'mark' in data and data['mark']:
self.marks.append(data['mark'])
# XXX this is for compatability with 4.8
if isinstance(self.type, int):
if self.type == 0:
self.type = "root"
elif self.type == 1:
self.type = "output"
elif self.type == 2 or self.type == 3:
self.type = "con"
elif self.type == 4:
self.type = "workspace"
elif self.type == 5:
self.type = "dockarea"
# set complex properties
self.nodes = []
if 'nodes' in data:
for n in data['nodes']:
self.nodes.append(Con(n, self, conn))
self.floating_nodes = []
if 'floating_nodes' in data:
for n in data['floating_nodes']:
self.floating_nodes.append(Con(n, self, conn))
self.window_class = None
self.window_instance = None
self.window_role = None
self.window_title = None
if 'window_properties' in data:
if 'class' in data['window_properties']:
self.window_class = data['window_properties']['class']
if 'instance' in data['window_properties']:
self.window_instance = data['window_properties']['instance']
if 'window_role' in data['window_properties']:
self.window_role = data['window_properties']['window_role']
if 'title' in data['window_properties']:
self.window_title = data['window_properties']['title']
self.rect = Rect(data['rect'])
if 'window_rect' in data:
self.window_rect = Rect(data['window_rect'])
if 'deco_rect' in data:
self.deco_rect = Rect(data['deco_rect'])
self.gaps = None
if 'gaps' in data:
self.gaps = Gaps(data['gaps'])
def __iter__(self):
"""
Iterate through the descendents of this node (breadth-first tree traversal)
"""
queue = deque(self.nodes)
queue.extend(self.floating_nodes)
while queue:
con = queue.popleft()
yield con
queue.extend(con.nodes)
queue.extend(con.floating_nodes)
def root(self):
"""
Retrieves the root container.
:rtype: :class:`Con`.
"""
if not self.parent:
return self
con = self.parent
while con.parent:
con = con.parent
return con
def descendents(self):
"""
Retrieve a list of all containers that delineate from the currently
selected container. Includes any kind of container.
:rtype: List of :class:`Con`.
"""
return [c for c in self]
def leaves(self):
"""
Retrieve a list of windows that delineate from the currently
selected container. Only lists client windows, no intermediate
containers.
:rtype: List of :class:`Con`.
"""
leaves = []
for c in self:
if not c.nodes and c.type == "con" and c.parent.type != "dockarea":
leaves.append(c)
return leaves
def command(self, command):
"""
Run a command on the currently active container.
:rtype: CommandReply
"""
return self._conn.command('[con_id="{}"] {}'.format(self.id, command))
def command_children(self, command):
"""
Run a command on the direct children of the currently selected
container.
:rtype: List of CommandReply????
"""
if not len(self.nodes):
return
commands = []
for c in self.nodes:
commands.append('[con_id="{}"] {};'.format(c.id, command))
self._conn.command(' '.join(commands))
def find_focused(self):
"""
Finds the focused container.
:rtype class Con:
"""
try:
return next(c for c in self if c.focused)
except StopIteration:
return None
def find_by_id(self, id):
try:
return next(c for c in self if c.id == id)
except StopIteration:
return None
def find_by_window(self, window):
try:
return next(c for c in self if c.window == window)
except StopIteration:
return None
def find_by_role(self, pattern):
return [
c for c in self
if c.window_role and re.search(pattern, c.window_role)
]
def find_named(self, pattern):
return [c for c in self if c.name and re.search(pattern, c.name)]
def find_titled(self, pattern):
return [c for c in self if c.window_title and re.search(pattern, c.window_title)]
def find_classed(self, pattern):
return [
c for c in self
if c.window_class and re.search(pattern, c.window_class)
]
def find_instanced(self, pattern):
return [
c for c in self
if c.window_instance and re.search(pattern, c.window_instance)
]
def find_marked(self, pattern=".*"):
pattern = re.compile(pattern)
return [
c for c in self if any(pattern.search(mark) for mark in c.marks)
]
def find_fullscreen(self):
return [c for c in self if c.type == 'con' and c.fullscreen_mode]
def workspace(self):
if self.type == 'workspace':
return self
ret = self.parent
while ret:
if ret.type == 'workspace':
break
ret = ret.parent
return ret
def scratchpad(self):
root = self.root()
i3con = None
for c in root.nodes:
if c.name == "__i3":
i3con = c
break
if not i3con:
return None
i3con_content = None
for c in i3con.nodes:
if c.name == "content":
i3con_content = c
break
if not i3con_content:
return None
scratch = None
for c in i3con_content.nodes:
if c.name == "__i3_scratch":
scratch = c
break
return scratch
|
acrisci/i3ipc-python | examples/stop-application-on-unfocus.py | FocusMonitor.stop_cont | python | def stop_cont(self, cont=True):
for proc in psutil.process_iter():
if proc.name() == self.process_name:
sig = psutil.signal.SIGCONT if cont else psutil.signal.SIGSTOP
proc.send_signal(sig)
if self.debug:
sig = 'CONT' if cont else 'STOP'
print("Sent SIG%s to process %d" % (sig, proc.pid)) | Send SIGSTOP/SIGCONT to processes called <name> | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/examples/stop-application-on-unfocus.py#L31-L40 | null | class FocusMonitor(object):
def __init__(self, args):
self.had_focus = False
self.class_name = args.class_name
self.process_name = args.process_name
self.debug = args.debug
self.conn = i3ipc.Connection()
self.conn.on('window::focus', self.focus_change)
atexit.register(self.continue_at_exit)
def focus_change(self, i3conn, event):
"""Detect focus change on a process with class class_name.
On change, stop/continue the process called process_name
"""
has_focus_now = (event.container.window_class == self.class_name)
if self.had_focus ^ has_focus_now:
# The monitored application changed focus state
self.had_focus = has_focus_now
self.stop_cont(has_focus_now)
def continue_at_exit(self):
"""Send SIGCONT on script termination"""
self.stop_cont(True)
def run(self):
try:
self.conn.main()
except KeyboardInterrupt:
print('Exiting on keyboard interrupt')
|
acrisci/i3ipc-python | examples/stop-application-on-unfocus.py | FocusMonitor.focus_change | python | def focus_change(self, i3conn, event):
has_focus_now = (event.container.window_class == self.class_name)
if self.had_focus ^ has_focus_now:
# The monitored application changed focus state
self.had_focus = has_focus_now
self.stop_cont(has_focus_now) | Detect focus change on a process with class class_name.
On change, stop/continue the process called process_name | train | https://github.com/acrisci/i3ipc-python/blob/243d353434cdd2a93a9ca917c6bbf07b865c39af/examples/stop-application-on-unfocus.py#L42-L50 | [
"def stop_cont(self, cont=True):\n \"\"\"Send SIGSTOP/SIGCONT to processes called <name>\n \"\"\"\n for proc in psutil.process_iter():\n if proc.name() == self.process_name:\n sig = psutil.signal.SIGCONT if cont else psutil.signal.SIGSTOP\n proc.send_signal(sig)\n if... | class FocusMonitor(object):
def __init__(self, args):
self.had_focus = False
self.class_name = args.class_name
self.process_name = args.process_name
self.debug = args.debug
self.conn = i3ipc.Connection()
self.conn.on('window::focus', self.focus_change)
atexit.register(self.continue_at_exit)
def stop_cont(self, cont=True):
"""Send SIGSTOP/SIGCONT to processes called <name>
"""
for proc in psutil.process_iter():
if proc.name() == self.process_name:
sig = psutil.signal.SIGCONT if cont else psutil.signal.SIGSTOP
proc.send_signal(sig)
if self.debug:
sig = 'CONT' if cont else 'STOP'
print("Sent SIG%s to process %d" % (sig, proc.pid))
def continue_at_exit(self):
"""Send SIGCONT on script termination"""
self.stop_cont(True)
def run(self):
try:
self.conn.main()
except KeyboardInterrupt:
print('Exiting on keyboard interrupt')
|
micahhausler/container-transform | container_transform/ecs.py | ECSTransformer._read_stream | python | def _read_stream(self, stream):
contents = json.load(stream)
family, containers, volumes = '', contents, []
if isinstance(contents, dict) and 'containerDefinitions' in contents.keys():
family = contents.get('family', None)
containers = contents.get('containerDefinitions', [])
volumes = self.ingest_volumes_param(contents.get('volumes', []))
return family, containers, volumes | We override the return signature of
``super(BaseTransformer, self)._read_stream()`` to return extra volume
data. This is intentional.
:param stream: A file like object
:returns: Return the family name, containers, and volumes. If there are
no volumes or family name, a tuple of ('', dict, []) is
returned
:rtype: tuple of (str, list of dict, list of dict) | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/ecs.py#L42-L64 | [
"def ingest_volumes_param(self, volumes):\n \"\"\"\n This is for ingesting the \"volumes\" of a task description\n \"\"\"\n data = {}\n\n for volume in volumes:\n if volume.get('host', {}).get('sourcePath'):\n data[volume.get('name')] = {\n 'path': volume.get('host', ... | class ECSTransformer(BaseTransformer):
"""
A transformer for ECS Tasks
To use this class:
.. code-block:: python
transformer = ECSTransformer('./task.json')
output = transformer.ingest_containers()
print(json.dumps(output, indent=4))
"""
input_type = TransformationTypes.COMPOSE.value
def __init__(self, filename=None):
"""
We override ``.__init__()`` on purpose, we need to get the volume data.
:param filename: The file to be loaded
:type filename: str
"""
family, stream, volumes_in = '', None, []
if filename:
self._filename = filename
family, stream, volumes_in = self._read_file(filename)
self.family = family
self.stream = stream
self.volumes_in = volumes_in
self.volumes = []
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
return containers
def add_volume(self, volume):
"""
Add a volume to self.volumes if it isn't already present
"""
for old_vol in self.volumes:
if volume == old_vol:
return
self.volumes.append(volume)
def emit_containers(self, containers, verbose=True):
"""
Emits the task definition and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
task_definition = {
'family': self.family,
'containerDefinitions': containers,
'volumes': self.volumes or []
}
if verbose:
return json.dumps(task_definition, indent=4, sort_keys=True)
else:
return json.dumps(task_definition)
@staticmethod
def validate(container):
container['essential'] = True
container_name = container.get('name')
if not container_name:
container_name = str(uuid.uuid4())
container['name'] = container_name
return container
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'tcp')
}
host_port = mapping.get('hostPort')
if host_port:
output['host_port'] = host_port
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the ECS mappings to base schema mappings
:param port_mappings: The ECS port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
@staticmethod
def _emit_mapping(mapping):
output = {}
if 'host_port' not in mapping:
output.update({
'containerPort': int(mapping.get('container_port')),
})
else:
output.update({
'hostPort': int(mapping['host_port']),
'containerPort': int(mapping['container_port']),
})
if mapping.get('protocol') == 'udp':
output['protocol'] = 'udp'
return output
def emit_port_mappings(self, port_mappings):
return [self._emit_mapping(mapping) for mapping in port_mappings]
def ingest_memory(self, memory):
return memory << 20
def emit_memory(self, memory):
mem_in_mb = memory >> 20
if 4 > mem_in_mb:
return 4
return mem_in_mb
def ingest_cpu(self, cpu):
return cpu
def emit_cpu(self, cpu):
return cpu
def ingest_privileged(self, privileged):
return privileged
def emit_privileged(self, privileged):
return privileged
def ingest_environment(self, environment):
output = {}
for kv in environment:
output[kv['name']] = kv['value']
return output
def emit_environment(self, environment):
output = []
for k, v in environment.items():
output.append({'name': k, 'value': v})
return output
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
def ingest_volumes_from(self, volumes_from):
return [vol['sourceContainer'] for vol in volumes_from]
def emit_volumes_from(self, volumes_from):
emitted = []
volumes_from = copy(volumes_from)
for vol in volumes_from:
emit = {}
if vol.get('read_only'):
emit['readOnly'] = vol['read_only']
emit['sourceContainer'] = vol['source_container']
emitted.append(emit)
return emitted
def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a task description
"""
data = {}
for volume in volumes:
if volume.get('host', {}).get('sourcePath'):
data[volume.get('name')] = {
'path': volume.get('host', {}).get('sourcePath'),
'readonly': volume.get('readOnly', False)
}
else:
data[volume.get('name')] = {
'path': '/tmp/{}'.format(uuid.uuid4().hex[:8]),
'readonly': volume.get('readOnly', False)
}
return data
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('sourceVolume')).get('path'),
'container': volume.get('containerPath'),
'readonly': self.volumes_in.get(volume.get('sourceVolume')).get('readonly')
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
@staticmethod
def path_to_name(path):
return path.replace('/', ' ').title().replace(' ', '').replace('.', '_')
def _build_volume(self, volume):
host_path = volume.get('host')
return {
'name': self.path_to_name(host_path),
'host': {
'sourcePath': host_path
}
}
def _build_mountpoint(self, volume):
"""
Given a generic volume definition, create the mountPoints element
"""
self.add_volume(self._build_volume(volume))
return {
'sourceVolume': self.path_to_name(volume.get('host')),
'containerPath': volume.get('container')
}
def emit_volumes(self, volumes):
return [
self._build_mountpoint(volume)
for volume
in volumes
if self._build_mountpoint(volume) is not None
]
def ingest_labels(self, labels):
return labels
def emit_labels(self, labels):
return labels
def ingest_logging(self, logging):
data = logging
if data.get('logDriver'): # pragma: no cover
data['driver'] = data.get('logDriver')
del data['logDriver']
return logging
def emit_logging(self, logging):
data = logging
if data.get('driver'): # pragma: no cover
data['logDriver'] = data.get('driver')
del data['driver']
return logging
|
micahhausler/container-transform | container_transform/ecs.py | ECSTransformer.add_volume | python | def add_volume(self, volume):
for old_vol in self.volumes:
if volume == old_vol:
return
self.volumes.append(volume) | Add a volume to self.volumes if it isn't already present | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/ecs.py#L70-L77 | null | class ECSTransformer(BaseTransformer):
"""
A transformer for ECS Tasks
To use this class:
.. code-block:: python
transformer = ECSTransformer('./task.json')
output = transformer.ingest_containers()
print(json.dumps(output, indent=4))
"""
input_type = TransformationTypes.COMPOSE.value
def __init__(self, filename=None):
"""
We override ``.__init__()`` on purpose, we need to get the volume data.
:param filename: The file to be loaded
:type filename: str
"""
family, stream, volumes_in = '', None, []
if filename:
self._filename = filename
family, stream, volumes_in = self._read_file(filename)
self.family = family
self.stream = stream
self.volumes_in = volumes_in
self.volumes = []
def _read_stream(self, stream):
"""
We override the return signature of
``super(BaseTransformer, self)._read_stream()`` to return extra volume
data. This is intentional.
:param stream: A file like object
:returns: Return the family name, containers, and volumes. If there are
no volumes or family name, a tuple of ('', dict, []) is
returned
:rtype: tuple of (str, list of dict, list of dict)
"""
contents = json.load(stream)
family, containers, volumes = '', contents, []
if isinstance(contents, dict) and 'containerDefinitions' in contents.keys():
family = contents.get('family', None)
containers = contents.get('containerDefinitions', [])
volumes = self.ingest_volumes_param(contents.get('volumes', []))
return family, containers, volumes
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
return containers
def emit_containers(self, containers, verbose=True):
"""
Emits the task definition and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
task_definition = {
'family': self.family,
'containerDefinitions': containers,
'volumes': self.volumes or []
}
if verbose:
return json.dumps(task_definition, indent=4, sort_keys=True)
else:
return json.dumps(task_definition)
@staticmethod
def validate(container):
container['essential'] = True
container_name = container.get('name')
if not container_name:
container_name = str(uuid.uuid4())
container['name'] = container_name
return container
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'tcp')
}
host_port = mapping.get('hostPort')
if host_port:
output['host_port'] = host_port
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the ECS mappings to base schema mappings
:param port_mappings: The ECS port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
@staticmethod
def _emit_mapping(mapping):
output = {}
if 'host_port' not in mapping:
output.update({
'containerPort': int(mapping.get('container_port')),
})
else:
output.update({
'hostPort': int(mapping['host_port']),
'containerPort': int(mapping['container_port']),
})
if mapping.get('protocol') == 'udp':
output['protocol'] = 'udp'
return output
def emit_port_mappings(self, port_mappings):
return [self._emit_mapping(mapping) for mapping in port_mappings]
def ingest_memory(self, memory):
return memory << 20
def emit_memory(self, memory):
mem_in_mb = memory >> 20
if 4 > mem_in_mb:
return 4
return mem_in_mb
def ingest_cpu(self, cpu):
return cpu
def emit_cpu(self, cpu):
return cpu
def ingest_privileged(self, privileged):
return privileged
def emit_privileged(self, privileged):
return privileged
def ingest_environment(self, environment):
output = {}
for kv in environment:
output[kv['name']] = kv['value']
return output
def emit_environment(self, environment):
output = []
for k, v in environment.items():
output.append({'name': k, 'value': v})
return output
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
def ingest_volumes_from(self, volumes_from):
return [vol['sourceContainer'] for vol in volumes_from]
def emit_volumes_from(self, volumes_from):
emitted = []
volumes_from = copy(volumes_from)
for vol in volumes_from:
emit = {}
if vol.get('read_only'):
emit['readOnly'] = vol['read_only']
emit['sourceContainer'] = vol['source_container']
emitted.append(emit)
return emitted
def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a task description
"""
data = {}
for volume in volumes:
if volume.get('host', {}).get('sourcePath'):
data[volume.get('name')] = {
'path': volume.get('host', {}).get('sourcePath'),
'readonly': volume.get('readOnly', False)
}
else:
data[volume.get('name')] = {
'path': '/tmp/{}'.format(uuid.uuid4().hex[:8]),
'readonly': volume.get('readOnly', False)
}
return data
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('sourceVolume')).get('path'),
'container': volume.get('containerPath'),
'readonly': self.volumes_in.get(volume.get('sourceVolume')).get('readonly')
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
@staticmethod
def path_to_name(path):
return path.replace('/', ' ').title().replace(' ', '').replace('.', '_')
def _build_volume(self, volume):
host_path = volume.get('host')
return {
'name': self.path_to_name(host_path),
'host': {
'sourcePath': host_path
}
}
def _build_mountpoint(self, volume):
"""
Given a generic volume definition, create the mountPoints element
"""
self.add_volume(self._build_volume(volume))
return {
'sourceVolume': self.path_to_name(volume.get('host')),
'containerPath': volume.get('container')
}
def emit_volumes(self, volumes):
return [
self._build_mountpoint(volume)
for volume
in volumes
if self._build_mountpoint(volume) is not None
]
def ingest_labels(self, labels):
return labels
def emit_labels(self, labels):
return labels
def ingest_logging(self, logging):
data = logging
if data.get('logDriver'): # pragma: no cover
data['driver'] = data.get('logDriver')
del data['logDriver']
return logging
def emit_logging(self, logging):
data = logging
if data.get('driver'): # pragma: no cover
data['logDriver'] = data.get('driver')
del data['driver']
return logging
|
micahhausler/container-transform | container_transform/ecs.py | ECSTransformer.emit_containers | python | def emit_containers(self, containers, verbose=True):
containers = sorted(containers, key=lambda c: c.get('name'))
task_definition = {
'family': self.family,
'containerDefinitions': containers,
'volumes': self.volumes or []
}
if verbose:
return json.dumps(task_definition, indent=4, sort_keys=True)
else:
return json.dumps(task_definition) | Emits the task definition and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/ecs.py#L79-L101 | null | class ECSTransformer(BaseTransformer):
"""
A transformer for ECS Tasks
To use this class:
.. code-block:: python
transformer = ECSTransformer('./task.json')
output = transformer.ingest_containers()
print(json.dumps(output, indent=4))
"""
input_type = TransformationTypes.COMPOSE.value
def __init__(self, filename=None):
"""
We override ``.__init__()`` on purpose, we need to get the volume data.
:param filename: The file to be loaded
:type filename: str
"""
family, stream, volumes_in = '', None, []
if filename:
self._filename = filename
family, stream, volumes_in = self._read_file(filename)
self.family = family
self.stream = stream
self.volumes_in = volumes_in
self.volumes = []
def _read_stream(self, stream):
"""
We override the return signature of
``super(BaseTransformer, self)._read_stream()`` to return extra volume
data. This is intentional.
:param stream: A file like object
:returns: Return the family name, containers, and volumes. If there are
no volumes or family name, a tuple of ('', dict, []) is
returned
:rtype: tuple of (str, list of dict, list of dict)
"""
contents = json.load(stream)
family, containers, volumes = '', contents, []
if isinstance(contents, dict) and 'containerDefinitions' in contents.keys():
family = contents.get('family', None)
containers = contents.get('containerDefinitions', [])
volumes = self.ingest_volumes_param(contents.get('volumes', []))
return family, containers, volumes
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
return containers
def add_volume(self, volume):
"""
Add a volume to self.volumes if it isn't already present
"""
for old_vol in self.volumes:
if volume == old_vol:
return
self.volumes.append(volume)
@staticmethod
def validate(container):
container['essential'] = True
container_name = container.get('name')
if not container_name:
container_name = str(uuid.uuid4())
container['name'] = container_name
return container
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'tcp')
}
host_port = mapping.get('hostPort')
if host_port:
output['host_port'] = host_port
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the ECS mappings to base schema mappings
:param port_mappings: The ECS port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
@staticmethod
def _emit_mapping(mapping):
output = {}
if 'host_port' not in mapping:
output.update({
'containerPort': int(mapping.get('container_port')),
})
else:
output.update({
'hostPort': int(mapping['host_port']),
'containerPort': int(mapping['container_port']),
})
if mapping.get('protocol') == 'udp':
output['protocol'] = 'udp'
return output
def emit_port_mappings(self, port_mappings):
return [self._emit_mapping(mapping) for mapping in port_mappings]
def ingest_memory(self, memory):
return memory << 20
def emit_memory(self, memory):
mem_in_mb = memory >> 20
if 4 > mem_in_mb:
return 4
return mem_in_mb
def ingest_cpu(self, cpu):
return cpu
def emit_cpu(self, cpu):
return cpu
def ingest_privileged(self, privileged):
return privileged
def emit_privileged(self, privileged):
return privileged
def ingest_environment(self, environment):
output = {}
for kv in environment:
output[kv['name']] = kv['value']
return output
def emit_environment(self, environment):
output = []
for k, v in environment.items():
output.append({'name': k, 'value': v})
return output
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
def ingest_volumes_from(self, volumes_from):
return [vol['sourceContainer'] for vol in volumes_from]
def emit_volumes_from(self, volumes_from):
emitted = []
volumes_from = copy(volumes_from)
for vol in volumes_from:
emit = {}
if vol.get('read_only'):
emit['readOnly'] = vol['read_only']
emit['sourceContainer'] = vol['source_container']
emitted.append(emit)
return emitted
def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a task description
"""
data = {}
for volume in volumes:
if volume.get('host', {}).get('sourcePath'):
data[volume.get('name')] = {
'path': volume.get('host', {}).get('sourcePath'),
'readonly': volume.get('readOnly', False)
}
else:
data[volume.get('name')] = {
'path': '/tmp/{}'.format(uuid.uuid4().hex[:8]),
'readonly': volume.get('readOnly', False)
}
return data
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('sourceVolume')).get('path'),
'container': volume.get('containerPath'),
'readonly': self.volumes_in.get(volume.get('sourceVolume')).get('readonly')
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
@staticmethod
def path_to_name(path):
return path.replace('/', ' ').title().replace(' ', '').replace('.', '_')
def _build_volume(self, volume):
host_path = volume.get('host')
return {
'name': self.path_to_name(host_path),
'host': {
'sourcePath': host_path
}
}
def _build_mountpoint(self, volume):
"""
Given a generic volume definition, create the mountPoints element
"""
self.add_volume(self._build_volume(volume))
return {
'sourceVolume': self.path_to_name(volume.get('host')),
'containerPath': volume.get('container')
}
def emit_volumes(self, volumes):
return [
self._build_mountpoint(volume)
for volume
in volumes
if self._build_mountpoint(volume) is not None
]
def ingest_labels(self, labels):
return labels
def emit_labels(self, labels):
return labels
def ingest_logging(self, logging):
data = logging
if data.get('logDriver'): # pragma: no cover
data['driver'] = data.get('logDriver')
del data['logDriver']
return logging
def emit_logging(self, logging):
data = logging
if data.get('driver'): # pragma: no cover
data['logDriver'] = data.get('driver')
del data['driver']
return logging
|
micahhausler/container-transform | container_transform/ecs.py | ECSTransformer.ingest_volumes_param | python | def ingest_volumes_param(self, volumes):
data = {}
for volume in volumes:
if volume.get('host', {}).get('sourcePath'):
data[volume.get('name')] = {
'path': volume.get('host', {}).get('sourcePath'),
'readonly': volume.get('readOnly', False)
}
else:
data[volume.get('name')] = {
'path': '/tmp/{}'.format(uuid.uuid4().hex[:8]),
'readonly': volume.get('readOnly', False)
}
return data | This is for ingesting the "volumes" of a task description | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/ecs.py#L216-L233 | null | class ECSTransformer(BaseTransformer):
"""
A transformer for ECS Tasks
To use this class:
.. code-block:: python
transformer = ECSTransformer('./task.json')
output = transformer.ingest_containers()
print(json.dumps(output, indent=4))
"""
input_type = TransformationTypes.COMPOSE.value
def __init__(self, filename=None):
"""
We override ``.__init__()`` on purpose, we need to get the volume data.
:param filename: The file to be loaded
:type filename: str
"""
family, stream, volumes_in = '', None, []
if filename:
self._filename = filename
family, stream, volumes_in = self._read_file(filename)
self.family = family
self.stream = stream
self.volumes_in = volumes_in
self.volumes = []
def _read_stream(self, stream):
"""
We override the return signature of
``super(BaseTransformer, self)._read_stream()`` to return extra volume
data. This is intentional.
:param stream: A file like object
:returns: Return the family name, containers, and volumes. If there are
no volumes or family name, a tuple of ('', dict, []) is
returned
:rtype: tuple of (str, list of dict, list of dict)
"""
contents = json.load(stream)
family, containers, volumes = '', contents, []
if isinstance(contents, dict) and 'containerDefinitions' in contents.keys():
family = contents.get('family', None)
containers = contents.get('containerDefinitions', [])
volumes = self.ingest_volumes_param(contents.get('volumes', []))
return family, containers, volumes
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
return containers
def add_volume(self, volume):
"""
Add a volume to self.volumes if it isn't already present
"""
for old_vol in self.volumes:
if volume == old_vol:
return
self.volumes.append(volume)
def emit_containers(self, containers, verbose=True):
"""
Emits the task definition and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
task_definition = {
'family': self.family,
'containerDefinitions': containers,
'volumes': self.volumes or []
}
if verbose:
return json.dumps(task_definition, indent=4, sort_keys=True)
else:
return json.dumps(task_definition)
@staticmethod
def validate(container):
container['essential'] = True
container_name = container.get('name')
if not container_name:
container_name = str(uuid.uuid4())
container['name'] = container_name
return container
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'tcp')
}
host_port = mapping.get('hostPort')
if host_port:
output['host_port'] = host_port
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the ECS mappings to base schema mappings
:param port_mappings: The ECS port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
@staticmethod
def _emit_mapping(mapping):
output = {}
if 'host_port' not in mapping:
output.update({
'containerPort': int(mapping.get('container_port')),
})
else:
output.update({
'hostPort': int(mapping['host_port']),
'containerPort': int(mapping['container_port']),
})
if mapping.get('protocol') == 'udp':
output['protocol'] = 'udp'
return output
def emit_port_mappings(self, port_mappings):
return [self._emit_mapping(mapping) for mapping in port_mappings]
def ingest_memory(self, memory):
return memory << 20
def emit_memory(self, memory):
mem_in_mb = memory >> 20
if 4 > mem_in_mb:
return 4
return mem_in_mb
def ingest_cpu(self, cpu):
return cpu
def emit_cpu(self, cpu):
return cpu
def ingest_privileged(self, privileged):
return privileged
def emit_privileged(self, privileged):
return privileged
def ingest_environment(self, environment):
output = {}
for kv in environment:
output[kv['name']] = kv['value']
return output
def emit_environment(self, environment):
output = []
for k, v in environment.items():
output.append({'name': k, 'value': v})
return output
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
def ingest_volumes_from(self, volumes_from):
return [vol['sourceContainer'] for vol in volumes_from]
def emit_volumes_from(self, volumes_from):
emitted = []
volumes_from = copy(volumes_from)
for vol in volumes_from:
emit = {}
if vol.get('read_only'):
emit['readOnly'] = vol['read_only']
emit['sourceContainer'] = vol['source_container']
emitted.append(emit)
return emitted
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('sourceVolume')).get('path'),
'container': volume.get('containerPath'),
'readonly': self.volumes_in.get(volume.get('sourceVolume')).get('readonly')
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
@staticmethod
def path_to_name(path):
return path.replace('/', ' ').title().replace(' ', '').replace('.', '_')
def _build_volume(self, volume):
host_path = volume.get('host')
return {
'name': self.path_to_name(host_path),
'host': {
'sourcePath': host_path
}
}
def _build_mountpoint(self, volume):
"""
Given a generic volume definition, create the mountPoints element
"""
self.add_volume(self._build_volume(volume))
return {
'sourceVolume': self.path_to_name(volume.get('host')),
'containerPath': volume.get('container')
}
def emit_volumes(self, volumes):
return [
self._build_mountpoint(volume)
for volume
in volumes
if self._build_mountpoint(volume) is not None
]
def ingest_labels(self, labels):
return labels
def emit_labels(self, labels):
return labels
def ingest_logging(self, logging):
data = logging
if data.get('logDriver'): # pragma: no cover
data['driver'] = data.get('logDriver')
del data['logDriver']
return logging
def emit_logging(self, logging):
data = logging
if data.get('driver'): # pragma: no cover
data['logDriver'] = data.get('driver')
del data['driver']
return logging
|
micahhausler/container-transform | container_transform/ecs.py | ECSTransformer._build_mountpoint | python | def _build_mountpoint(self, volume):
self.add_volume(self._build_volume(volume))
return {
'sourceVolume': self.path_to_name(volume.get('host')),
'containerPath': volume.get('container')
} | Given a generic volume definition, create the mountPoints element | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/ecs.py#L259-L267 | null | class ECSTransformer(BaseTransformer):
"""
A transformer for ECS Tasks
To use this class:
.. code-block:: python
transformer = ECSTransformer('./task.json')
output = transformer.ingest_containers()
print(json.dumps(output, indent=4))
"""
input_type = TransformationTypes.COMPOSE.value
def __init__(self, filename=None):
"""
We override ``.__init__()`` on purpose, we need to get the volume data.
:param filename: The file to be loaded
:type filename: str
"""
family, stream, volumes_in = '', None, []
if filename:
self._filename = filename
family, stream, volumes_in = self._read_file(filename)
self.family = family
self.stream = stream
self.volumes_in = volumes_in
self.volumes = []
def _read_stream(self, stream):
"""
We override the return signature of
``super(BaseTransformer, self)._read_stream()`` to return extra volume
data. This is intentional.
:param stream: A file like object
:returns: Return the family name, containers, and volumes. If there are
no volumes or family name, a tuple of ('', dict, []) is
returned
:rtype: tuple of (str, list of dict, list of dict)
"""
contents = json.load(stream)
family, containers, volumes = '', contents, []
if isinstance(contents, dict) and 'containerDefinitions' in contents.keys():
family = contents.get('family', None)
containers = contents.get('containerDefinitions', [])
volumes = self.ingest_volumes_param(contents.get('volumes', []))
return family, containers, volumes
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
return containers
def add_volume(self, volume):
"""
Add a volume to self.volumes if it isn't already present
"""
for old_vol in self.volumes:
if volume == old_vol:
return
self.volumes.append(volume)
def emit_containers(self, containers, verbose=True):
"""
Emits the task definition and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
task_definition = {
'family': self.family,
'containerDefinitions': containers,
'volumes': self.volumes or []
}
if verbose:
return json.dumps(task_definition, indent=4, sort_keys=True)
else:
return json.dumps(task_definition)
@staticmethod
def validate(container):
container['essential'] = True
container_name = container.get('name')
if not container_name:
container_name = str(uuid.uuid4())
container['name'] = container_name
return container
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'tcp')
}
host_port = mapping.get('hostPort')
if host_port:
output['host_port'] = host_port
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the ECS mappings to base schema mappings
:param port_mappings: The ECS port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
@staticmethod
def _emit_mapping(mapping):
output = {}
if 'host_port' not in mapping:
output.update({
'containerPort': int(mapping.get('container_port')),
})
else:
output.update({
'hostPort': int(mapping['host_port']),
'containerPort': int(mapping['container_port']),
})
if mapping.get('protocol') == 'udp':
output['protocol'] = 'udp'
return output
def emit_port_mappings(self, port_mappings):
return [self._emit_mapping(mapping) for mapping in port_mappings]
def ingest_memory(self, memory):
return memory << 20
def emit_memory(self, memory):
mem_in_mb = memory >> 20
if 4 > mem_in_mb:
return 4
return mem_in_mb
def ingest_cpu(self, cpu):
return cpu
def emit_cpu(self, cpu):
return cpu
def ingest_privileged(self, privileged):
return privileged
def emit_privileged(self, privileged):
return privileged
def ingest_environment(self, environment):
output = {}
for kv in environment:
output[kv['name']] = kv['value']
return output
def emit_environment(self, environment):
output = []
for k, v in environment.items():
output.append({'name': k, 'value': v})
return output
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
def ingest_volumes_from(self, volumes_from):
return [vol['sourceContainer'] for vol in volumes_from]
def emit_volumes_from(self, volumes_from):
emitted = []
volumes_from = copy(volumes_from)
for vol in volumes_from:
emit = {}
if vol.get('read_only'):
emit['readOnly'] = vol['read_only']
emit['sourceContainer'] = vol['source_container']
emitted.append(emit)
return emitted
def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a task description
"""
data = {}
for volume in volumes:
if volume.get('host', {}).get('sourcePath'):
data[volume.get('name')] = {
'path': volume.get('host', {}).get('sourcePath'),
'readonly': volume.get('readOnly', False)
}
else:
data[volume.get('name')] = {
'path': '/tmp/{}'.format(uuid.uuid4().hex[:8]),
'readonly': volume.get('readOnly', False)
}
return data
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('sourceVolume')).get('path'),
'container': volume.get('containerPath'),
'readonly': self.volumes_in.get(volume.get('sourceVolume')).get('readonly')
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
@staticmethod
def path_to_name(path):
return path.replace('/', ' ').title().replace(' ', '').replace('.', '_')
def _build_volume(self, volume):
host_path = volume.get('host')
return {
'name': self.path_to_name(host_path),
'host': {
'sourcePath': host_path
}
}
def emit_volumes(self, volumes):
return [
self._build_mountpoint(volume)
for volume
in volumes
if self._build_mountpoint(volume) is not None
]
def ingest_labels(self, labels):
return labels
def emit_labels(self, labels):
return labels
def ingest_logging(self, logging):
data = logging
if data.get('logDriver'): # pragma: no cover
data['driver'] = data.get('logDriver')
del data['logDriver']
return logging
def emit_logging(self, logging):
data = logging
if data.get('driver'): # pragma: no cover
data['logDriver'] = data.get('driver')
del data['driver']
return logging
|
micahhausler/container-transform | container_transform/marathon.py | MarathonTransformer._lookup_parameter | python | def _lookup_parameter(self, container, key, common_type=None):
if not container.get('container', {}).get('docker', {}).get('parameters'):
return
params = container['container']['docker']['parameters']
# Super hacky - log-opt is a sub option of the logging directive of everything else
if key == 'log-driver':
return [
p
for p
in params
if p['key'] in ['log-opt', 'log-driver']]
matching_params = [
p['value']
for p
in params
if p['key'] == key]
if matching_params:
if common_type == list:
return matching_params
else:
return matching_params[0] | Lookup the `docker run` keyword from the 'container.docker.parameters' list
:param container: The container in question
:param key: The key name we're looking up
:param is_list: if the response is a list of items | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/marathon.py#L77-L106 | null | class MarathonTransformer(BaseTransformer):
"""
A transformer for Marathon Apps
When consuming Marathon input, the transformer supports:
* A single Marathon application
* Content from the Marathon Group API
* A JSON array of Marathon application objects
When emitting Marathon output, the transformer will emit a list of
applications if there is more than one. Otherwise, it will emit a single
application.
To use this class:
.. code-block:: python
transformer = MarathonTransformer('./app.json')
output = transformer.ingest_container()
print(json.dumps(output, indent=4))
"""
input_type = TransformationTypes.COMPOSE.value
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
if filename:
self._filename = filename
stream = self._read_file(filename)
self.stream = stream
else:
self.stream = None
def _read_stream(self, stream):
"""
Read in the json stream
"""
return json.load(stream)
def flatten_container(self, container):
"""
Accepts a marathon container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.MARATHON.value]['name'] and \
'.' in names[TransformationTypes.MARATHON.value]['name']:
marathon_dotted_name = names[TransformationTypes.MARATHON.value]['name']
parts = marathon_dotted_name.split('.')
if parts[-2] == 'parameters':
# Special lookup for docker parameters
common_type = names[TransformationTypes.MARATHON.value].get('type')
result = self._lookup_parameter(container, parts[-1], common_type)
if result:
container[marathon_dotted_name] = result
else:
result = lookup_nested_dict(container, *parts)
if result:
container[marathon_dotted_name] = result
return container
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept groups api output
if 'apps' in containers:
containers = containers['apps']
elif isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def emit_containers(self, containers, verbose=True):
"""
Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('id'))
if len(containers) == 1 and isinstance(containers, list):
containers = containers[0]
if verbose:
return json.dumps(containers, indent=4, sort_keys=True)
else:
return json.dumps(containers)
def validate(self, container):
# Ensure container name
container_name = container.get('id', str(uuid.uuid4()))
container['id'] = container_name
container_data = defaultdict(lambda: defaultdict(dict)) # pragma: no coverage
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key.startswith('container.'):
parts = key.split('.')
if parts[-2] == 'parameters':
# Parameters are inserted below
parts = parts[:-1]
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
else:
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
# Sort the parameters in a deterministic way
if container_data['container']['docker'].get('parameters'):
old_params = container_data['container']['docker']['parameters']
sorted_values = sorted(
old_params, key=lambda p: str(p.get('value'))
)
sorted_keys = sorted(
sorted_values, key=lambda p: p.get('key')
)
container_data['container']['docker']['parameters'] = sorted_keys
# Set requirePorts if any hostPorts are specified.
if container_data['container']['docker'].get('portMappings'):
host_ports = set([
p.get('hostPort', 0)
for p
in container_data['container']['docker']['portMappings']])
container_data['requirePorts'] = bool(host_ports.difference({0}))
# Assume the network mode is BRIDGE if unspecified
if container_data.get('container', {}).get('docker', {}).get('network') == 'HOST':
if container_data['container']['docker'].get('portMappings'):
container_data['ports'] = [
p.get('containerPort') or p.get('hostPort')
for p
in container_data['container']['docker']['portMappings']]
# del container_data['container']['docker']['portMappings']
container_data['requirePorts'] = True
else:
container_data['container']['docker']['network'] = 'BRIDGE'
container_data['container']['docker']['forcePullImage'] = True
container_data['container']['type'] = 'DOCKER'
container_data['acceptedResourceRoles'] = []
if container_data.get('container', {}).get('docker', {}).get('portMappings'):
container_data["healthChecks"] = [
{
"protocol": "HTTP",
"path": "/",
"portIndex": 0,
"gracePeriodSeconds": 300,
"intervalSeconds": 60,
"timeoutSeconds": 20,
"maxConsecutiveFailures": 3
}
]
container_data['cpus'] = container_data.get('cpus', float(1))
container_data['mem'] = container_data.get('mem', 128)
container_data['fetch'] = []
container_data['instances'] = 1
return container_data
def ingest_name(self, name):
return name.split('/')[-1]
def emit_links(self, links):
return ['/{0}'.format(link) for link in links]
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'tcp')
}
if 'hostPort' in mapping:
output['host_port'] = int(mapping.get('hostPort'))
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def emit_port_mappings(self, port_mappings):
return [
{
'containerPort': mapping['container_port'],
'hostPort': mapping.get('host_port', 0),
'protocol': mapping.get('protocol', 'tcp')
}
for mapping
in port_mappings]
def ingest_memory(self, memory):
return memory << 20
def emit_memory(self, memory):
mem_in_mb = memory >> 20
if 4 > mem_in_mb:
return 4
return mem_in_mb
def ingest_cpu(self, cpu):
return float(cpu * 1024)
def emit_cpu(self, cpu):
return float(cpu/1024)
def ingest_environment(self, environment):
return environment
def emit_environment(self, environment):
return environment
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return entrypoint
def emit_entrypoint(self, entrypoint):
return [{'key': 'entrypoint', 'value': entrypoint}]
def ingest_volumes_from(self, volumes_from):
return volumes_from
def emit_volumes_from(self, volumes_from):
_emitted = []
for vol in volumes_from:
_emitted.append({'key': 'volumes-from', 'value': vol['source_container']})
return _emitted
def _convert_volume(self, volume):
"""
This is for ingesting the "volumes" of a app description
"""
data = {
'host': volume.get('hostPath'),
'container': volume.get('containerPath'),
'readonly': volume.get('mode') == 'RO',
}
return data
def ingest_volumes(self, volumes):
return [self._convert_volume(volume) for volume in volumes]
@staticmethod
def _build_volume(volume):
"""
Given a generic volume definition, create the volumes element
"""
return {
'hostPath': volume.get('host'),
'containerPath': volume.get('container'),
'mode': 'RO' if volume.get('readonly') else 'RW'
}
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
def ingest_logging(self, logging):
# Super hacky continued - in self._lookup_parameter() we flatten the logging options
data = {
'driver': [p['value'] for p in logging if p['key'] == 'log-driver'][0],
'options': dict([p['value'].split('=') for p in logging if p['key'] == 'log-opt'])
}
return data
def emit_logging(self, logging):
output = [{
'key': 'log-driver',
'value': logging.get('driver')
}]
if logging.get('options') and isinstance(logging.get('options'), dict):
for k, v in logging.get('options').items():
output.append({
'key': 'log-opt',
'value': '{k}={v}'.format(k=k, v=v)
})
return output
def emit_dns(self, dns):
return [{'key': 'dns', 'value': serv} for serv in dns]
def emit_domain(self, domain):
return [{'key': 'dns-search', 'value': d} for d in domain]
def emit_work_dir(self, work_dir):
return [{'key': 'workdir', 'value': work_dir}]
def emit_network(self, network):
return [{'key': 'net', 'value': net} for net in network]
def ingest_net_mode(self, net_mode):
return net_mode.lower()
def emit_net_mode(self, net_mode):
return net_mode.upper()
def emit_user(self, user):
return [{'key': 'user', 'value': user}]
def emit_pid(self, pid):
return [{'key': 'pid', 'value': pid}]
def emit_env_file(self, env_file):
return [{'key': 'env-file', 'value': ef} for ef in env_file]
def emit_expose(self, expose):
return [{'key': 'expose', 'value': port} for port in expose]
|
micahhausler/container-transform | container_transform/marathon.py | MarathonTransformer.flatten_container | python | def flatten_container(self, container):
for names in ARG_MAP.values():
if names[TransformationTypes.MARATHON.value]['name'] and \
'.' in names[TransformationTypes.MARATHON.value]['name']:
marathon_dotted_name = names[TransformationTypes.MARATHON.value]['name']
parts = marathon_dotted_name.split('.')
if parts[-2] == 'parameters':
# Special lookup for docker parameters
common_type = names[TransformationTypes.MARATHON.value].get('type')
result = self._lookup_parameter(container, parts[-1], common_type)
if result:
container[marathon_dotted_name] = result
else:
result = lookup_nested_dict(container, *parts)
if result:
container[marathon_dotted_name] = result
return container | Accepts a marathon container and pulls out the nested values into the top level | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/marathon.py#L108-L129 | [
"def lookup_nested_dict(dic, key, *keys):\n if keys:\n return lookup_nested_dict(dic.get(key, None), *keys)\n return dic.get(key)\n",
"def _lookup_parameter(self, container, key, common_type=None):\n \"\"\"\n Lookup the `docker run` keyword from the 'container.docker.parameters' list\n :para... | class MarathonTransformer(BaseTransformer):
"""
A transformer for Marathon Apps
When consuming Marathon input, the transformer supports:
* A single Marathon application
* Content from the Marathon Group API
* A JSON array of Marathon application objects
When emitting Marathon output, the transformer will emit a list of
applications if there is more than one. Otherwise, it will emit a single
application.
To use this class:
.. code-block:: python
transformer = MarathonTransformer('./app.json')
output = transformer.ingest_container()
print(json.dumps(output, indent=4))
"""
input_type = TransformationTypes.COMPOSE.value
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
if filename:
self._filename = filename
stream = self._read_file(filename)
self.stream = stream
else:
self.stream = None
def _read_stream(self, stream):
"""
Read in the json stream
"""
return json.load(stream)
def _lookup_parameter(self, container, key, common_type=None):
"""
Lookup the `docker run` keyword from the 'container.docker.parameters' list
:param container: The container in question
:param key: The key name we're looking up
:param is_list: if the response is a list of items
"""
if not container.get('container', {}).get('docker', {}).get('parameters'):
return
params = container['container']['docker']['parameters']
# Super hacky - log-opt is a sub option of the logging directive of everything else
if key == 'log-driver':
return [
p
for p
in params
if p['key'] in ['log-opt', 'log-driver']]
matching_params = [
p['value']
for p
in params
if p['key'] == key]
if matching_params:
if common_type == list:
return matching_params
else:
return matching_params[0]
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept groups api output
if 'apps' in containers:
containers = containers['apps']
elif isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def emit_containers(self, containers, verbose=True):
"""
Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('id'))
if len(containers) == 1 and isinstance(containers, list):
containers = containers[0]
if verbose:
return json.dumps(containers, indent=4, sort_keys=True)
else:
return json.dumps(containers)
def validate(self, container):
# Ensure container name
container_name = container.get('id', str(uuid.uuid4()))
container['id'] = container_name
container_data = defaultdict(lambda: defaultdict(dict)) # pragma: no coverage
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key.startswith('container.'):
parts = key.split('.')
if parts[-2] == 'parameters':
# Parameters are inserted below
parts = parts[:-1]
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
else:
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
# Sort the parameters in a deterministic way
if container_data['container']['docker'].get('parameters'):
old_params = container_data['container']['docker']['parameters']
sorted_values = sorted(
old_params, key=lambda p: str(p.get('value'))
)
sorted_keys = sorted(
sorted_values, key=lambda p: p.get('key')
)
container_data['container']['docker']['parameters'] = sorted_keys
# Set requirePorts if any hostPorts are specified.
if container_data['container']['docker'].get('portMappings'):
host_ports = set([
p.get('hostPort', 0)
for p
in container_data['container']['docker']['portMappings']])
container_data['requirePorts'] = bool(host_ports.difference({0}))
# Assume the network mode is BRIDGE if unspecified
if container_data.get('container', {}).get('docker', {}).get('network') == 'HOST':
if container_data['container']['docker'].get('portMappings'):
container_data['ports'] = [
p.get('containerPort') or p.get('hostPort')
for p
in container_data['container']['docker']['portMappings']]
# del container_data['container']['docker']['portMappings']
container_data['requirePorts'] = True
else:
container_data['container']['docker']['network'] = 'BRIDGE'
container_data['container']['docker']['forcePullImage'] = True
container_data['container']['type'] = 'DOCKER'
container_data['acceptedResourceRoles'] = []
if container_data.get('container', {}).get('docker', {}).get('portMappings'):
container_data["healthChecks"] = [
{
"protocol": "HTTP",
"path": "/",
"portIndex": 0,
"gracePeriodSeconds": 300,
"intervalSeconds": 60,
"timeoutSeconds": 20,
"maxConsecutiveFailures": 3
}
]
container_data['cpus'] = container_data.get('cpus', float(1))
container_data['mem'] = container_data.get('mem', 128)
container_data['fetch'] = []
container_data['instances'] = 1
return container_data
def ingest_name(self, name):
return name.split('/')[-1]
def emit_links(self, links):
return ['/{0}'.format(link) for link in links]
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'tcp')
}
if 'hostPort' in mapping:
output['host_port'] = int(mapping.get('hostPort'))
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def emit_port_mappings(self, port_mappings):
return [
{
'containerPort': mapping['container_port'],
'hostPort': mapping.get('host_port', 0),
'protocol': mapping.get('protocol', 'tcp')
}
for mapping
in port_mappings]
def ingest_memory(self, memory):
return memory << 20
def emit_memory(self, memory):
mem_in_mb = memory >> 20
if 4 > mem_in_mb:
return 4
return mem_in_mb
def ingest_cpu(self, cpu):
return float(cpu * 1024)
def emit_cpu(self, cpu):
return float(cpu/1024)
def ingest_environment(self, environment):
return environment
def emit_environment(self, environment):
return environment
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return entrypoint
def emit_entrypoint(self, entrypoint):
return [{'key': 'entrypoint', 'value': entrypoint}]
def ingest_volumes_from(self, volumes_from):
return volumes_from
def emit_volumes_from(self, volumes_from):
_emitted = []
for vol in volumes_from:
_emitted.append({'key': 'volumes-from', 'value': vol['source_container']})
return _emitted
def _convert_volume(self, volume):
"""
This is for ingesting the "volumes" of a app description
"""
data = {
'host': volume.get('hostPath'),
'container': volume.get('containerPath'),
'readonly': volume.get('mode') == 'RO',
}
return data
def ingest_volumes(self, volumes):
return [self._convert_volume(volume) for volume in volumes]
@staticmethod
def _build_volume(volume):
"""
Given a generic volume definition, create the volumes element
"""
return {
'hostPath': volume.get('host'),
'containerPath': volume.get('container'),
'mode': 'RO' if volume.get('readonly') else 'RW'
}
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
def ingest_logging(self, logging):
# Super hacky continued - in self._lookup_parameter() we flatten the logging options
data = {
'driver': [p['value'] for p in logging if p['key'] == 'log-driver'][0],
'options': dict([p['value'].split('=') for p in logging if p['key'] == 'log-opt'])
}
return data
def emit_logging(self, logging):
output = [{
'key': 'log-driver',
'value': logging.get('driver')
}]
if logging.get('options') and isinstance(logging.get('options'), dict):
for k, v in logging.get('options').items():
output.append({
'key': 'log-opt',
'value': '{k}={v}'.format(k=k, v=v)
})
return output
def emit_dns(self, dns):
return [{'key': 'dns', 'value': serv} for serv in dns]
def emit_domain(self, domain):
return [{'key': 'dns-search', 'value': d} for d in domain]
def emit_work_dir(self, work_dir):
return [{'key': 'workdir', 'value': work_dir}]
def emit_network(self, network):
return [{'key': 'net', 'value': net} for net in network]
def ingest_net_mode(self, net_mode):
return net_mode.lower()
def emit_net_mode(self, net_mode):
return net_mode.upper()
def emit_user(self, user):
return [{'key': 'user', 'value': user}]
def emit_pid(self, pid):
return [{'key': 'pid', 'value': pid}]
def emit_env_file(self, env_file):
return [{'key': 'env-file', 'value': ef} for ef in env_file]
def emit_expose(self, expose):
return [{'key': 'expose', 'value': port} for port in expose]
|
micahhausler/container-transform | container_transform/marathon.py | MarathonTransformer.emit_containers | python | def emit_containers(self, containers, verbose=True):
containers = sorted(containers, key=lambda c: c.get('id'))
if len(containers) == 1 and isinstance(containers, list):
containers = containers[0]
if verbose:
return json.dumps(containers, indent=4, sort_keys=True)
else:
return json.dumps(containers) | Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/marathon.py#L143-L164 | null | class MarathonTransformer(BaseTransformer):
"""
A transformer for Marathon Apps
When consuming Marathon input, the transformer supports:
* A single Marathon application
* Content from the Marathon Group API
* A JSON array of Marathon application objects
When emitting Marathon output, the transformer will emit a list of
applications if there is more than one. Otherwise, it will emit a single
application.
To use this class:
.. code-block:: python
transformer = MarathonTransformer('./app.json')
output = transformer.ingest_container()
print(json.dumps(output, indent=4))
"""
input_type = TransformationTypes.COMPOSE.value
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
if filename:
self._filename = filename
stream = self._read_file(filename)
self.stream = stream
else:
self.stream = None
def _read_stream(self, stream):
"""
Read in the json stream
"""
return json.load(stream)
def _lookup_parameter(self, container, key, common_type=None):
"""
Lookup the `docker run` keyword from the 'container.docker.parameters' list
:param container: The container in question
:param key: The key name we're looking up
:param is_list: if the response is a list of items
"""
if not container.get('container', {}).get('docker', {}).get('parameters'):
return
params = container['container']['docker']['parameters']
# Super hacky - log-opt is a sub option of the logging directive of everything else
if key == 'log-driver':
return [
p
for p
in params
if p['key'] in ['log-opt', 'log-driver']]
matching_params = [
p['value']
for p
in params
if p['key'] == key]
if matching_params:
if common_type == list:
return matching_params
else:
return matching_params[0]
def flatten_container(self, container):
"""
Accepts a marathon container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.MARATHON.value]['name'] and \
'.' in names[TransformationTypes.MARATHON.value]['name']:
marathon_dotted_name = names[TransformationTypes.MARATHON.value]['name']
parts = marathon_dotted_name.split('.')
if parts[-2] == 'parameters':
# Special lookup for docker parameters
common_type = names[TransformationTypes.MARATHON.value].get('type')
result = self._lookup_parameter(container, parts[-1], common_type)
if result:
container[marathon_dotted_name] = result
else:
result = lookup_nested_dict(container, *parts)
if result:
container[marathon_dotted_name] = result
return container
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept groups api output
if 'apps' in containers:
containers = containers['apps']
elif isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def validate(self, container):
# Ensure container name
container_name = container.get('id', str(uuid.uuid4()))
container['id'] = container_name
container_data = defaultdict(lambda: defaultdict(dict)) # pragma: no coverage
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key.startswith('container.'):
parts = key.split('.')
if parts[-2] == 'parameters':
# Parameters are inserted below
parts = parts[:-1]
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
else:
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
# Sort the parameters in a deterministic way
if container_data['container']['docker'].get('parameters'):
old_params = container_data['container']['docker']['parameters']
sorted_values = sorted(
old_params, key=lambda p: str(p.get('value'))
)
sorted_keys = sorted(
sorted_values, key=lambda p: p.get('key')
)
container_data['container']['docker']['parameters'] = sorted_keys
# Set requirePorts if any hostPorts are specified.
if container_data['container']['docker'].get('portMappings'):
host_ports = set([
p.get('hostPort', 0)
for p
in container_data['container']['docker']['portMappings']])
container_data['requirePorts'] = bool(host_ports.difference({0}))
# Assume the network mode is BRIDGE if unspecified
if container_data.get('container', {}).get('docker', {}).get('network') == 'HOST':
if container_data['container']['docker'].get('portMappings'):
container_data['ports'] = [
p.get('containerPort') or p.get('hostPort')
for p
in container_data['container']['docker']['portMappings']]
# del container_data['container']['docker']['portMappings']
container_data['requirePorts'] = True
else:
container_data['container']['docker']['network'] = 'BRIDGE'
container_data['container']['docker']['forcePullImage'] = True
container_data['container']['type'] = 'DOCKER'
container_data['acceptedResourceRoles'] = []
if container_data.get('container', {}).get('docker', {}).get('portMappings'):
container_data["healthChecks"] = [
{
"protocol": "HTTP",
"path": "/",
"portIndex": 0,
"gracePeriodSeconds": 300,
"intervalSeconds": 60,
"timeoutSeconds": 20,
"maxConsecutiveFailures": 3
}
]
container_data['cpus'] = container_data.get('cpus', float(1))
container_data['mem'] = container_data.get('mem', 128)
container_data['fetch'] = []
container_data['instances'] = 1
return container_data
def ingest_name(self, name):
return name.split('/')[-1]
def emit_links(self, links):
return ['/{0}'.format(link) for link in links]
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'tcp')
}
if 'hostPort' in mapping:
output['host_port'] = int(mapping.get('hostPort'))
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def emit_port_mappings(self, port_mappings):
return [
{
'containerPort': mapping['container_port'],
'hostPort': mapping.get('host_port', 0),
'protocol': mapping.get('protocol', 'tcp')
}
for mapping
in port_mappings]
def ingest_memory(self, memory):
return memory << 20
def emit_memory(self, memory):
mem_in_mb = memory >> 20
if 4 > mem_in_mb:
return 4
return mem_in_mb
def ingest_cpu(self, cpu):
return float(cpu * 1024)
def emit_cpu(self, cpu):
return float(cpu/1024)
def ingest_environment(self, environment):
return environment
def emit_environment(self, environment):
return environment
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return entrypoint
def emit_entrypoint(self, entrypoint):
return [{'key': 'entrypoint', 'value': entrypoint}]
def ingest_volumes_from(self, volumes_from):
return volumes_from
def emit_volumes_from(self, volumes_from):
_emitted = []
for vol in volumes_from:
_emitted.append({'key': 'volumes-from', 'value': vol['source_container']})
return _emitted
def _convert_volume(self, volume):
"""
This is for ingesting the "volumes" of a app description
"""
data = {
'host': volume.get('hostPath'),
'container': volume.get('containerPath'),
'readonly': volume.get('mode') == 'RO',
}
return data
def ingest_volumes(self, volumes):
return [self._convert_volume(volume) for volume in volumes]
@staticmethod
def _build_volume(volume):
"""
Given a generic volume definition, create the volumes element
"""
return {
'hostPath': volume.get('host'),
'containerPath': volume.get('container'),
'mode': 'RO' if volume.get('readonly') else 'RW'
}
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
def ingest_logging(self, logging):
# Super hacky continued - in self._lookup_parameter() we flatten the logging options
data = {
'driver': [p['value'] for p in logging if p['key'] == 'log-driver'][0],
'options': dict([p['value'].split('=') for p in logging if p['key'] == 'log-opt'])
}
return data
def emit_logging(self, logging):
output = [{
'key': 'log-driver',
'value': logging.get('driver')
}]
if logging.get('options') and isinstance(logging.get('options'), dict):
for k, v in logging.get('options').items():
output.append({
'key': 'log-opt',
'value': '{k}={v}'.format(k=k, v=v)
})
return output
def emit_dns(self, dns):
return [{'key': 'dns', 'value': serv} for serv in dns]
def emit_domain(self, domain):
return [{'key': 'dns-search', 'value': d} for d in domain]
def emit_work_dir(self, work_dir):
return [{'key': 'workdir', 'value': work_dir}]
def emit_network(self, network):
return [{'key': 'net', 'value': net} for net in network]
def ingest_net_mode(self, net_mode):
return net_mode.lower()
def emit_net_mode(self, net_mode):
return net_mode.upper()
def emit_user(self, user):
return [{'key': 'user', 'value': user}]
def emit_pid(self, pid):
return [{'key': 'pid', 'value': pid}]
def emit_env_file(self, env_file):
return [{'key': 'env-file', 'value': ef} for ef in env_file]
def emit_expose(self, expose):
return [{'key': 'expose', 'value': port} for port in expose]
|
micahhausler/container-transform | container_transform/marathon.py | MarathonTransformer._convert_volume | python | def _convert_volume(self, volume):
data = {
'host': volume.get('hostPath'),
'container': volume.get('containerPath'),
'readonly': volume.get('mode') == 'RO',
}
return data | This is for ingesting the "volumes" of a app description | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/marathon.py#L323-L332 | null | class MarathonTransformer(BaseTransformer):
"""
A transformer for Marathon Apps
When consuming Marathon input, the transformer supports:
* A single Marathon application
* Content from the Marathon Group API
* A JSON array of Marathon application objects
When emitting Marathon output, the transformer will emit a list of
applications if there is more than one. Otherwise, it will emit a single
application.
To use this class:
.. code-block:: python
transformer = MarathonTransformer('./app.json')
output = transformer.ingest_container()
print(json.dumps(output, indent=4))
"""
input_type = TransformationTypes.COMPOSE.value
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
if filename:
self._filename = filename
stream = self._read_file(filename)
self.stream = stream
else:
self.stream = None
def _read_stream(self, stream):
"""
Read in the json stream
"""
return json.load(stream)
def _lookup_parameter(self, container, key, common_type=None):
"""
Lookup the `docker run` keyword from the 'container.docker.parameters' list
:param container: The container in question
:param key: The key name we're looking up
:param is_list: if the response is a list of items
"""
if not container.get('container', {}).get('docker', {}).get('parameters'):
return
params = container['container']['docker']['parameters']
# Super hacky - log-opt is a sub option of the logging directive of everything else
if key == 'log-driver':
return [
p
for p
in params
if p['key'] in ['log-opt', 'log-driver']]
matching_params = [
p['value']
for p
in params
if p['key'] == key]
if matching_params:
if common_type == list:
return matching_params
else:
return matching_params[0]
def flatten_container(self, container):
"""
Accepts a marathon container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.MARATHON.value]['name'] and \
'.' in names[TransformationTypes.MARATHON.value]['name']:
marathon_dotted_name = names[TransformationTypes.MARATHON.value]['name']
parts = marathon_dotted_name.split('.')
if parts[-2] == 'parameters':
# Special lookup for docker parameters
common_type = names[TransformationTypes.MARATHON.value].get('type')
result = self._lookup_parameter(container, parts[-1], common_type)
if result:
container[marathon_dotted_name] = result
else:
result = lookup_nested_dict(container, *parts)
if result:
container[marathon_dotted_name] = result
return container
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept groups api output
if 'apps' in containers:
containers = containers['apps']
elif isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def emit_containers(self, containers, verbose=True):
"""
Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('id'))
if len(containers) == 1 and isinstance(containers, list):
containers = containers[0]
if verbose:
return json.dumps(containers, indent=4, sort_keys=True)
else:
return json.dumps(containers)
def validate(self, container):
# Ensure container name
container_name = container.get('id', str(uuid.uuid4()))
container['id'] = container_name
container_data = defaultdict(lambda: defaultdict(dict)) # pragma: no coverage
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key.startswith('container.'):
parts = key.split('.')
if parts[-2] == 'parameters':
# Parameters are inserted below
parts = parts[:-1]
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
else:
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
# Sort the parameters in a deterministic way
if container_data['container']['docker'].get('parameters'):
old_params = container_data['container']['docker']['parameters']
sorted_values = sorted(
old_params, key=lambda p: str(p.get('value'))
)
sorted_keys = sorted(
sorted_values, key=lambda p: p.get('key')
)
container_data['container']['docker']['parameters'] = sorted_keys
# Set requirePorts if any hostPorts are specified.
if container_data['container']['docker'].get('portMappings'):
host_ports = set([
p.get('hostPort', 0)
for p
in container_data['container']['docker']['portMappings']])
container_data['requirePorts'] = bool(host_ports.difference({0}))
# Assume the network mode is BRIDGE if unspecified
if container_data.get('container', {}).get('docker', {}).get('network') == 'HOST':
if container_data['container']['docker'].get('portMappings'):
container_data['ports'] = [
p.get('containerPort') or p.get('hostPort')
for p
in container_data['container']['docker']['portMappings']]
# del container_data['container']['docker']['portMappings']
container_data['requirePorts'] = True
else:
container_data['container']['docker']['network'] = 'BRIDGE'
container_data['container']['docker']['forcePullImage'] = True
container_data['container']['type'] = 'DOCKER'
container_data['acceptedResourceRoles'] = []
if container_data.get('container', {}).get('docker', {}).get('portMappings'):
container_data["healthChecks"] = [
{
"protocol": "HTTP",
"path": "/",
"portIndex": 0,
"gracePeriodSeconds": 300,
"intervalSeconds": 60,
"timeoutSeconds": 20,
"maxConsecutiveFailures": 3
}
]
container_data['cpus'] = container_data.get('cpus', float(1))
container_data['mem'] = container_data.get('mem', 128)
container_data['fetch'] = []
container_data['instances'] = 1
return container_data
def ingest_name(self, name):
return name.split('/')[-1]
def emit_links(self, links):
return ['/{0}'.format(link) for link in links]
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'tcp')
}
if 'hostPort' in mapping:
output['host_port'] = int(mapping.get('hostPort'))
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def emit_port_mappings(self, port_mappings):
return [
{
'containerPort': mapping['container_port'],
'hostPort': mapping.get('host_port', 0),
'protocol': mapping.get('protocol', 'tcp')
}
for mapping
in port_mappings]
def ingest_memory(self, memory):
return memory << 20
def emit_memory(self, memory):
mem_in_mb = memory >> 20
if 4 > mem_in_mb:
return 4
return mem_in_mb
def ingest_cpu(self, cpu):
return float(cpu * 1024)
def emit_cpu(self, cpu):
return float(cpu/1024)
def ingest_environment(self, environment):
return environment
def emit_environment(self, environment):
return environment
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return entrypoint
def emit_entrypoint(self, entrypoint):
return [{'key': 'entrypoint', 'value': entrypoint}]
def ingest_volumes_from(self, volumes_from):
return volumes_from
def emit_volumes_from(self, volumes_from):
_emitted = []
for vol in volumes_from:
_emitted.append({'key': 'volumes-from', 'value': vol['source_container']})
return _emitted
def ingest_volumes(self, volumes):
return [self._convert_volume(volume) for volume in volumes]
@staticmethod
def _build_volume(volume):
"""
Given a generic volume definition, create the volumes element
"""
return {
'hostPath': volume.get('host'),
'containerPath': volume.get('container'),
'mode': 'RO' if volume.get('readonly') else 'RW'
}
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
def ingest_logging(self, logging):
# Super hacky continued - in self._lookup_parameter() we flatten the logging options
data = {
'driver': [p['value'] for p in logging if p['key'] == 'log-driver'][0],
'options': dict([p['value'].split('=') for p in logging if p['key'] == 'log-opt'])
}
return data
def emit_logging(self, logging):
output = [{
'key': 'log-driver',
'value': logging.get('driver')
}]
if logging.get('options') and isinstance(logging.get('options'), dict):
for k, v in logging.get('options').items():
output.append({
'key': 'log-opt',
'value': '{k}={v}'.format(k=k, v=v)
})
return output
def emit_dns(self, dns):
return [{'key': 'dns', 'value': serv} for serv in dns]
def emit_domain(self, domain):
return [{'key': 'dns-search', 'value': d} for d in domain]
def emit_work_dir(self, work_dir):
return [{'key': 'workdir', 'value': work_dir}]
def emit_network(self, network):
return [{'key': 'net', 'value': net} for net in network]
def ingest_net_mode(self, net_mode):
return net_mode.lower()
def emit_net_mode(self, net_mode):
return net_mode.upper()
def emit_user(self, user):
return [{'key': 'user', 'value': user}]
def emit_pid(self, pid):
return [{'key': 'pid', 'value': pid}]
def emit_env_file(self, env_file):
return [{'key': 'env-file', 'value': ef} for ef in env_file]
def emit_expose(self, expose):
return [{'key': 'expose', 'value': port} for port in expose]
|
micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer._find_convertable_object | python | def _find_convertable_object(self, data):
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
if len(convertable_object_idxs) < 1:
raise Exception("Kubernetes config didn't contain any of {}".format(
', '.join(self.pod_types.keys())
))
return list(data)[convertable_object_idxs[0]] | Get the first instance of a `self.pod_types` | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L70-L85 | null | class KubernetesTransformer(BaseTransformer):
"""
A transformer for Kubernetes Pods
TODO: look at http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_pod
"""
input_type = TransformationTypes.COMPOSE.value
pod_types = {
'ReplicaSet': lambda x: x.get('spec').get('template').get('spec'),
'Deployment': lambda x: x.get('spec').get('template').get('spec'),
'DaemonSet': lambda x: x.get('spec').get('template').get('spec'),
'Pod': lambda x: x.get('spec'),
'ReplicationController': lambda x: x.get('spec').get('template').get('spec')
}
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
obj, stream, volumes_in = {}, None, []
if filename:
self._filename = filename
obj, stream, volumes_in = self._read_file(filename)
self.obj = obj
self.stream = stream
self.volumes_in = volumes_in
self.volumes = {}
def _read_stream(self, stream):
"""
Read in the pod stream
"""
data = yaml.safe_load_all(stream=stream)
obj = self._find_convertable_object(data)
pod = self.pod_types[obj['kind']](obj)
return obj, pod.get('containers'), self.ingest_volumes_param(pod.get('volumes', []))
def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a pod spec
"""
data = {}
for volume in volumes:
if volume.get('hostPath', {}).get('path'):
data[volume.get('name')] = {
'path': volume.get('hostPath', {}).get('path'),
}
elif volume.get('emptyDir'):
data[volume.get('name')] = {}
else:
data[volume.get('name')] = {}
# TODO Support other k8s volume types?
return data
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('name')).get('path', ''),
'container': volume.get('mountPath', ''),
'readonly': bool(volume.get('readOnly')),
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
def flatten_container(self, container):
"""
Accepts a kubernetes container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.KUBERNETES.value]['name'] and \
'.' in names[TransformationTypes.KUBERNETES.value]['name']:
kubernetes_dotted_name = names[TransformationTypes.KUBERNETES.value]['name']
parts = kubernetes_dotted_name.split('.')
result = lookup_nested_dict(container, *parts)
if result:
container[kubernetes_dotted_name] = result
return container
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept groups api output
if isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def emit_containers(self, containers, verbose=True):
"""
Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
output = {
'kind': 'Deployment',
'apiVersion': 'extensions/v1beta1',
'metadata': {
'name': None,
'namespace': 'default',
'labels': {
'app': None,
'version': 'latest',
},
},
'spec': {
'replicas': 1,
'selector': {
'matchLabels': {
'app': None,
'version': 'latest'
}
},
'template': {
'metadata': {
'labels': {
'app': None,
'version': 'latest'
}
},
'spec': {
'containers': json.loads(json.dumps(containers))
}
}
}
}
if self.volumes:
volumes = sorted(self.volumes.values(), key=lambda x: x.get('name'))
output['spec']['template']['spec']['volumes'] = volumes
noalias_dumper = yaml.dumper.SafeDumper
noalias_dumper.ignore_aliases = lambda self, data: True
return yaml.dump(
output,
default_flow_style=False,
Dumper=noalias_dumper
)
def validate(self, container):
# Ensure container name
# container_name = container.get('name', str(uuid.uuid4()))
# container['name'] = container_name
container_data = defaultdict(lambda: defaultdict(dict))
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key and '.' in key:
parts = key.split('.')
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
return container_data
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'TCP').lower(),
}
if 'hostPort' in mapping:
output['host_port'] = int(mapping.get('hostPort'))
if 'name' in mapping:
output['name'] = mapping.get('name')
if 'hostIP' in mapping:
output['host_ip'] = mapping.get('hostIP')
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def emit_port_mappings(self, port_mappings):
output = []
for mapping in port_mappings:
data = {
'containerPort': mapping['container_port'],
'protocol': mapping.get('protocol', 'tcp').upper()
}
if mapping.get('host_port'):
data['hostPort'] = mapping['host_port']
if mapping.get('host_ip'):
data['hostIP'] = mapping['host_ip']
if mapping.get('name'):
data['name'] = mapping['name']
output.append(data)
return output
def ingest_memory(self, memory):
"""
Transform the memory into bytes
:param memory: Compose memory definition. (1g, 24k)
:type memory: memory string or integer
:return: The memory in bytes
:rtype: int
"""
def lshift(num, shift):
return num << shift
def k(num, thousands):
return num * thousands
# if isinstance(memory, int):
# # Memory was specified as an integer, meaning it is in bytes
memory = str(memory)
bit_shift = {
'E': {'func': k, 'shift': 10e17},
'P': {'func': k, 'shift': 10e14},
'T': {'func': k, 'shift': 10e11},
'G': {'func': k, 'shift': 10e8},
'M': {'func': k, 'shift': 10e5},
'K': {'func': k, 'shift': 10e2},
'Ei': {'func': lshift, 'shift': 60},
'Pi': {'func': lshift, 'shift': 50},
'Ti': {'func': lshift, 'shift': 40},
'Gi': {'func': lshift, 'shift': 30},
'Mi': {'func': lshift, 'shift': 20},
'Ki': {'func': lshift, 'shift': 10},
}
if len(memory) > 2 and memory[-2:] in bit_shift.keys():
unit = memory[-2:]
number = int(memory[:-2])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
elif len(memory) > 1 and memory[-1:] in bit_shift.keys():
unit = memory[-1]
number = int(memory[:-1])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
# Cast to a float to properly consume scientific notation
return int(float(memory))
def emit_memory(self, memory):
# return '{mem}Mi'.format(mem=int(memory) >> 20)
if int(memory) >> 20 > 0:
return '{mem}Mi'.format(mem=int(memory) >> 20)
return int(memory)
def ingest_cpu(self, cpu):
cpu = str(cpu)
if cpu[-1] == 'm':
cpu = float(int(cpu[:-1]) / 1000)
return float(cpu * 1024)
def emit_cpu(self, cpu):
value = float(cpu / 1024)
if value < 1.0:
value = '{}m'.format(value * 1000)
return value
def ingest_environment(self, environment):
return dict([(ev['name'], ev.get('value', '')) for ev in environment])
def emit_environment(self, environment):
return [{'name': k, 'value': v} for k, v in environment.items()]
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
@staticmethod
def _build_volume_name(hostpath):
return hostpath.replace('/', '-').strip('-')
def _build_volume(self, volume):
"""
Given a generic volume definition, create the volumes element
"""
self.volumes[self._build_volume_name(volume.get('host'))] = {
'name': self._build_volume_name(volume.get('host')),
'hostPath': {
'path': volume.get('host')
}
}
response = {
'name': self._build_volume_name(volume.get('host')),
'mountPath': volume.get('container'),
}
if volume.get('readonly', False):
response['readOnly'] = bool(volume.get('readonly', False))
return response
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
|
micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer._read_stream | python | def _read_stream(self, stream):
data = yaml.safe_load_all(stream=stream)
obj = self._find_convertable_object(data)
pod = self.pod_types[obj['kind']](obj)
return obj, pod.get('containers'), self.ingest_volumes_param(pod.get('volumes', [])) | Read in the pod stream | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L87-L94 | [
"def _find_convertable_object(self, data):\n \"\"\"\n Get the first instance of a `self.pod_types`\n \"\"\"\n data = list(data)\n convertable_object_idxs = [\n idx\n for idx, obj\n in enumerate(data)\n if obj.get('kind') in self.pod_types.keys()\n ]\n if len(converta... | class KubernetesTransformer(BaseTransformer):
"""
A transformer for Kubernetes Pods
TODO: look at http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_pod
"""
input_type = TransformationTypes.COMPOSE.value
pod_types = {
'ReplicaSet': lambda x: x.get('spec').get('template').get('spec'),
'Deployment': lambda x: x.get('spec').get('template').get('spec'),
'DaemonSet': lambda x: x.get('spec').get('template').get('spec'),
'Pod': lambda x: x.get('spec'),
'ReplicationController': lambda x: x.get('spec').get('template').get('spec')
}
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
obj, stream, volumes_in = {}, None, []
if filename:
self._filename = filename
obj, stream, volumes_in = self._read_file(filename)
self.obj = obj
self.stream = stream
self.volumes_in = volumes_in
self.volumes = {}
def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
if len(convertable_object_idxs) < 1:
raise Exception("Kubernetes config didn't contain any of {}".format(
', '.join(self.pod_types.keys())
))
return list(data)[convertable_object_idxs[0]]
def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a pod spec
"""
data = {}
for volume in volumes:
if volume.get('hostPath', {}).get('path'):
data[volume.get('name')] = {
'path': volume.get('hostPath', {}).get('path'),
}
elif volume.get('emptyDir'):
data[volume.get('name')] = {}
else:
data[volume.get('name')] = {}
# TODO Support other k8s volume types?
return data
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('name')).get('path', ''),
'container': volume.get('mountPath', ''),
'readonly': bool(volume.get('readOnly')),
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
def flatten_container(self, container):
"""
Accepts a kubernetes container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.KUBERNETES.value]['name'] and \
'.' in names[TransformationTypes.KUBERNETES.value]['name']:
kubernetes_dotted_name = names[TransformationTypes.KUBERNETES.value]['name']
parts = kubernetes_dotted_name.split('.')
result = lookup_nested_dict(container, *parts)
if result:
container[kubernetes_dotted_name] = result
return container
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept groups api output
if isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def emit_containers(self, containers, verbose=True):
"""
Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
output = {
'kind': 'Deployment',
'apiVersion': 'extensions/v1beta1',
'metadata': {
'name': None,
'namespace': 'default',
'labels': {
'app': None,
'version': 'latest',
},
},
'spec': {
'replicas': 1,
'selector': {
'matchLabels': {
'app': None,
'version': 'latest'
}
},
'template': {
'metadata': {
'labels': {
'app': None,
'version': 'latest'
}
},
'spec': {
'containers': json.loads(json.dumps(containers))
}
}
}
}
if self.volumes:
volumes = sorted(self.volumes.values(), key=lambda x: x.get('name'))
output['spec']['template']['spec']['volumes'] = volumes
noalias_dumper = yaml.dumper.SafeDumper
noalias_dumper.ignore_aliases = lambda self, data: True
return yaml.dump(
output,
default_flow_style=False,
Dumper=noalias_dumper
)
def validate(self, container):
# Ensure container name
# container_name = container.get('name', str(uuid.uuid4()))
# container['name'] = container_name
container_data = defaultdict(lambda: defaultdict(dict))
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key and '.' in key:
parts = key.split('.')
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
return container_data
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'TCP').lower(),
}
if 'hostPort' in mapping:
output['host_port'] = int(mapping.get('hostPort'))
if 'name' in mapping:
output['name'] = mapping.get('name')
if 'hostIP' in mapping:
output['host_ip'] = mapping.get('hostIP')
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def emit_port_mappings(self, port_mappings):
output = []
for mapping in port_mappings:
data = {
'containerPort': mapping['container_port'],
'protocol': mapping.get('protocol', 'tcp').upper()
}
if mapping.get('host_port'):
data['hostPort'] = mapping['host_port']
if mapping.get('host_ip'):
data['hostIP'] = mapping['host_ip']
if mapping.get('name'):
data['name'] = mapping['name']
output.append(data)
return output
def ingest_memory(self, memory):
"""
Transform the memory into bytes
:param memory: Compose memory definition. (1g, 24k)
:type memory: memory string or integer
:return: The memory in bytes
:rtype: int
"""
def lshift(num, shift):
return num << shift
def k(num, thousands):
return num * thousands
# if isinstance(memory, int):
# # Memory was specified as an integer, meaning it is in bytes
memory = str(memory)
bit_shift = {
'E': {'func': k, 'shift': 10e17},
'P': {'func': k, 'shift': 10e14},
'T': {'func': k, 'shift': 10e11},
'G': {'func': k, 'shift': 10e8},
'M': {'func': k, 'shift': 10e5},
'K': {'func': k, 'shift': 10e2},
'Ei': {'func': lshift, 'shift': 60},
'Pi': {'func': lshift, 'shift': 50},
'Ti': {'func': lshift, 'shift': 40},
'Gi': {'func': lshift, 'shift': 30},
'Mi': {'func': lshift, 'shift': 20},
'Ki': {'func': lshift, 'shift': 10},
}
if len(memory) > 2 and memory[-2:] in bit_shift.keys():
unit = memory[-2:]
number = int(memory[:-2])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
elif len(memory) > 1 and memory[-1:] in bit_shift.keys():
unit = memory[-1]
number = int(memory[:-1])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
# Cast to a float to properly consume scientific notation
return int(float(memory))
def emit_memory(self, memory):
# return '{mem}Mi'.format(mem=int(memory) >> 20)
if int(memory) >> 20 > 0:
return '{mem}Mi'.format(mem=int(memory) >> 20)
return int(memory)
def ingest_cpu(self, cpu):
cpu = str(cpu)
if cpu[-1] == 'm':
cpu = float(int(cpu[:-1]) / 1000)
return float(cpu * 1024)
def emit_cpu(self, cpu):
value = float(cpu / 1024)
if value < 1.0:
value = '{}m'.format(value * 1000)
return value
def ingest_environment(self, environment):
return dict([(ev['name'], ev.get('value', '')) for ev in environment])
def emit_environment(self, environment):
return [{'name': k, 'value': v} for k, v in environment.items()]
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
@staticmethod
def _build_volume_name(hostpath):
return hostpath.replace('/', '-').strip('-')
def _build_volume(self, volume):
"""
Given a generic volume definition, create the volumes element
"""
self.volumes[self._build_volume_name(volume.get('host'))] = {
'name': self._build_volume_name(volume.get('host')),
'hostPath': {
'path': volume.get('host')
}
}
response = {
'name': self._build_volume_name(volume.get('host')),
'mountPath': volume.get('container'),
}
if volume.get('readonly', False):
response['readOnly'] = bool(volume.get('readonly', False))
return response
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
|
micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer.ingest_volumes_param | python | def ingest_volumes_param(self, volumes):
data = {}
for volume in volumes:
if volume.get('hostPath', {}).get('path'):
data[volume.get('name')] = {
'path': volume.get('hostPath', {}).get('path'),
}
elif volume.get('emptyDir'):
data[volume.get('name')] = {}
else:
data[volume.get('name')] = {}
# TODO Support other k8s volume types?
return data | This is for ingesting the "volumes" of a pod spec | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L96-L111 | null | class KubernetesTransformer(BaseTransformer):
"""
A transformer for Kubernetes Pods
TODO: look at http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_pod
"""
input_type = TransformationTypes.COMPOSE.value
pod_types = {
'ReplicaSet': lambda x: x.get('spec').get('template').get('spec'),
'Deployment': lambda x: x.get('spec').get('template').get('spec'),
'DaemonSet': lambda x: x.get('spec').get('template').get('spec'),
'Pod': lambda x: x.get('spec'),
'ReplicationController': lambda x: x.get('spec').get('template').get('spec')
}
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
obj, stream, volumes_in = {}, None, []
if filename:
self._filename = filename
obj, stream, volumes_in = self._read_file(filename)
self.obj = obj
self.stream = stream
self.volumes_in = volumes_in
self.volumes = {}
def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
if len(convertable_object_idxs) < 1:
raise Exception("Kubernetes config didn't contain any of {}".format(
', '.join(self.pod_types.keys())
))
return list(data)[convertable_object_idxs[0]]
def _read_stream(self, stream):
"""
Read in the pod stream
"""
data = yaml.safe_load_all(stream=stream)
obj = self._find_convertable_object(data)
pod = self.pod_types[obj['kind']](obj)
return obj, pod.get('containers'), self.ingest_volumes_param(pod.get('volumes', []))
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('name')).get('path', ''),
'container': volume.get('mountPath', ''),
'readonly': bool(volume.get('readOnly')),
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
def flatten_container(self, container):
"""
Accepts a kubernetes container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.KUBERNETES.value]['name'] and \
'.' in names[TransformationTypes.KUBERNETES.value]['name']:
kubernetes_dotted_name = names[TransformationTypes.KUBERNETES.value]['name']
parts = kubernetes_dotted_name.split('.')
result = lookup_nested_dict(container, *parts)
if result:
container[kubernetes_dotted_name] = result
return container
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept groups api output
if isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def emit_containers(self, containers, verbose=True):
"""
Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
output = {
'kind': 'Deployment',
'apiVersion': 'extensions/v1beta1',
'metadata': {
'name': None,
'namespace': 'default',
'labels': {
'app': None,
'version': 'latest',
},
},
'spec': {
'replicas': 1,
'selector': {
'matchLabels': {
'app': None,
'version': 'latest'
}
},
'template': {
'metadata': {
'labels': {
'app': None,
'version': 'latest'
}
},
'spec': {
'containers': json.loads(json.dumps(containers))
}
}
}
}
if self.volumes:
volumes = sorted(self.volumes.values(), key=lambda x: x.get('name'))
output['spec']['template']['spec']['volumes'] = volumes
noalias_dumper = yaml.dumper.SafeDumper
noalias_dumper.ignore_aliases = lambda self, data: True
return yaml.dump(
output,
default_flow_style=False,
Dumper=noalias_dumper
)
def validate(self, container):
# Ensure container name
# container_name = container.get('name', str(uuid.uuid4()))
# container['name'] = container_name
container_data = defaultdict(lambda: defaultdict(dict))
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key and '.' in key:
parts = key.split('.')
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
return container_data
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'TCP').lower(),
}
if 'hostPort' in mapping:
output['host_port'] = int(mapping.get('hostPort'))
if 'name' in mapping:
output['name'] = mapping.get('name')
if 'hostIP' in mapping:
output['host_ip'] = mapping.get('hostIP')
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def emit_port_mappings(self, port_mappings):
output = []
for mapping in port_mappings:
data = {
'containerPort': mapping['container_port'],
'protocol': mapping.get('protocol', 'tcp').upper()
}
if mapping.get('host_port'):
data['hostPort'] = mapping['host_port']
if mapping.get('host_ip'):
data['hostIP'] = mapping['host_ip']
if mapping.get('name'):
data['name'] = mapping['name']
output.append(data)
return output
def ingest_memory(self, memory):
"""
Transform the memory into bytes
:param memory: Compose memory definition. (1g, 24k)
:type memory: memory string or integer
:return: The memory in bytes
:rtype: int
"""
def lshift(num, shift):
return num << shift
def k(num, thousands):
return num * thousands
# if isinstance(memory, int):
# # Memory was specified as an integer, meaning it is in bytes
memory = str(memory)
bit_shift = {
'E': {'func': k, 'shift': 10e17},
'P': {'func': k, 'shift': 10e14},
'T': {'func': k, 'shift': 10e11},
'G': {'func': k, 'shift': 10e8},
'M': {'func': k, 'shift': 10e5},
'K': {'func': k, 'shift': 10e2},
'Ei': {'func': lshift, 'shift': 60},
'Pi': {'func': lshift, 'shift': 50},
'Ti': {'func': lshift, 'shift': 40},
'Gi': {'func': lshift, 'shift': 30},
'Mi': {'func': lshift, 'shift': 20},
'Ki': {'func': lshift, 'shift': 10},
}
if len(memory) > 2 and memory[-2:] in bit_shift.keys():
unit = memory[-2:]
number = int(memory[:-2])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
elif len(memory) > 1 and memory[-1:] in bit_shift.keys():
unit = memory[-1]
number = int(memory[:-1])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
# Cast to a float to properly consume scientific notation
return int(float(memory))
def emit_memory(self, memory):
# return '{mem}Mi'.format(mem=int(memory) >> 20)
if int(memory) >> 20 > 0:
return '{mem}Mi'.format(mem=int(memory) >> 20)
return int(memory)
def ingest_cpu(self, cpu):
cpu = str(cpu)
if cpu[-1] == 'm':
cpu = float(int(cpu[:-1]) / 1000)
return float(cpu * 1024)
def emit_cpu(self, cpu):
value = float(cpu / 1024)
if value < 1.0:
value = '{}m'.format(value * 1000)
return value
def ingest_environment(self, environment):
return dict([(ev['name'], ev.get('value', '')) for ev in environment])
def emit_environment(self, environment):
return [{'name': k, 'value': v} for k, v in environment.items()]
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
@staticmethod
def _build_volume_name(hostpath):
return hostpath.replace('/', '-').strip('-')
def _build_volume(self, volume):
"""
Given a generic volume definition, create the volumes element
"""
self.volumes[self._build_volume_name(volume.get('host'))] = {
'name': self._build_volume_name(volume.get('host')),
'hostPath': {
'path': volume.get('host')
}
}
response = {
'name': self._build_volume_name(volume.get('host')),
'mountPath': volume.get('container'),
}
if volume.get('readonly', False):
response['readOnly'] = bool(volume.get('readonly', False))
return response
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
|
micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer.flatten_container | python | def flatten_container(self, container):
for names in ARG_MAP.values():
if names[TransformationTypes.KUBERNETES.value]['name'] and \
'.' in names[TransformationTypes.KUBERNETES.value]['name']:
kubernetes_dotted_name = names[TransformationTypes.KUBERNETES.value]['name']
parts = kubernetes_dotted_name.split('.')
result = lookup_nested_dict(container, *parts)
if result:
container[kubernetes_dotted_name] = result
return container | Accepts a kubernetes container and pulls out the nested values into the top level | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L124-L136 | [
"def lookup_nested_dict(dic, key, *keys):\n if keys and dic:\n return lookup_nested_dict(dic.get(key, None), *keys)\n if dic:\n return dic.get(key)\n else:\n return None\n"
] | class KubernetesTransformer(BaseTransformer):
"""
A transformer for Kubernetes Pods
TODO: look at http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_pod
"""
input_type = TransformationTypes.COMPOSE.value
pod_types = {
'ReplicaSet': lambda x: x.get('spec').get('template').get('spec'),
'Deployment': lambda x: x.get('spec').get('template').get('spec'),
'DaemonSet': lambda x: x.get('spec').get('template').get('spec'),
'Pod': lambda x: x.get('spec'),
'ReplicationController': lambda x: x.get('spec').get('template').get('spec')
}
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
obj, stream, volumes_in = {}, None, []
if filename:
self._filename = filename
obj, stream, volumes_in = self._read_file(filename)
self.obj = obj
self.stream = stream
self.volumes_in = volumes_in
self.volumes = {}
def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
if len(convertable_object_idxs) < 1:
raise Exception("Kubernetes config didn't contain any of {}".format(
', '.join(self.pod_types.keys())
))
return list(data)[convertable_object_idxs[0]]
def _read_stream(self, stream):
"""
Read in the pod stream
"""
data = yaml.safe_load_all(stream=stream)
obj = self._find_convertable_object(data)
pod = self.pod_types[obj['kind']](obj)
return obj, pod.get('containers'), self.ingest_volumes_param(pod.get('volumes', []))
def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a pod spec
"""
data = {}
for volume in volumes:
if volume.get('hostPath', {}).get('path'):
data[volume.get('name')] = {
'path': volume.get('hostPath', {}).get('path'),
}
elif volume.get('emptyDir'):
data[volume.get('name')] = {}
else:
data[volume.get('name')] = {}
# TODO Support other k8s volume types?
return data
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('name')).get('path', ''),
'container': volume.get('mountPath', ''),
'readonly': bool(volume.get('readOnly')),
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept groups api output
if isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def emit_containers(self, containers, verbose=True):
"""
Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
output = {
'kind': 'Deployment',
'apiVersion': 'extensions/v1beta1',
'metadata': {
'name': None,
'namespace': 'default',
'labels': {
'app': None,
'version': 'latest',
},
},
'spec': {
'replicas': 1,
'selector': {
'matchLabels': {
'app': None,
'version': 'latest'
}
},
'template': {
'metadata': {
'labels': {
'app': None,
'version': 'latest'
}
},
'spec': {
'containers': json.loads(json.dumps(containers))
}
}
}
}
if self.volumes:
volumes = sorted(self.volumes.values(), key=lambda x: x.get('name'))
output['spec']['template']['spec']['volumes'] = volumes
noalias_dumper = yaml.dumper.SafeDumper
noalias_dumper.ignore_aliases = lambda self, data: True
return yaml.dump(
output,
default_flow_style=False,
Dumper=noalias_dumper
)
def validate(self, container):
# Ensure container name
# container_name = container.get('name', str(uuid.uuid4()))
# container['name'] = container_name
container_data = defaultdict(lambda: defaultdict(dict))
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key and '.' in key:
parts = key.split('.')
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
return container_data
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'TCP').lower(),
}
if 'hostPort' in mapping:
output['host_port'] = int(mapping.get('hostPort'))
if 'name' in mapping:
output['name'] = mapping.get('name')
if 'hostIP' in mapping:
output['host_ip'] = mapping.get('hostIP')
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def emit_port_mappings(self, port_mappings):
output = []
for mapping in port_mappings:
data = {
'containerPort': mapping['container_port'],
'protocol': mapping.get('protocol', 'tcp').upper()
}
if mapping.get('host_port'):
data['hostPort'] = mapping['host_port']
if mapping.get('host_ip'):
data['hostIP'] = mapping['host_ip']
if mapping.get('name'):
data['name'] = mapping['name']
output.append(data)
return output
def ingest_memory(self, memory):
"""
Transform the memory into bytes
:param memory: Compose memory definition. (1g, 24k)
:type memory: memory string or integer
:return: The memory in bytes
:rtype: int
"""
def lshift(num, shift):
return num << shift
def k(num, thousands):
return num * thousands
# if isinstance(memory, int):
# # Memory was specified as an integer, meaning it is in bytes
memory = str(memory)
bit_shift = {
'E': {'func': k, 'shift': 10e17},
'P': {'func': k, 'shift': 10e14},
'T': {'func': k, 'shift': 10e11},
'G': {'func': k, 'shift': 10e8},
'M': {'func': k, 'shift': 10e5},
'K': {'func': k, 'shift': 10e2},
'Ei': {'func': lshift, 'shift': 60},
'Pi': {'func': lshift, 'shift': 50},
'Ti': {'func': lshift, 'shift': 40},
'Gi': {'func': lshift, 'shift': 30},
'Mi': {'func': lshift, 'shift': 20},
'Ki': {'func': lshift, 'shift': 10},
}
if len(memory) > 2 and memory[-2:] in bit_shift.keys():
unit = memory[-2:]
number = int(memory[:-2])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
elif len(memory) > 1 and memory[-1:] in bit_shift.keys():
unit = memory[-1]
number = int(memory[:-1])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
# Cast to a float to properly consume scientific notation
return int(float(memory))
def emit_memory(self, memory):
# return '{mem}Mi'.format(mem=int(memory) >> 20)
if int(memory) >> 20 > 0:
return '{mem}Mi'.format(mem=int(memory) >> 20)
return int(memory)
def ingest_cpu(self, cpu):
cpu = str(cpu)
if cpu[-1] == 'm':
cpu = float(int(cpu[:-1]) / 1000)
return float(cpu * 1024)
def emit_cpu(self, cpu):
value = float(cpu / 1024)
if value < 1.0:
value = '{}m'.format(value * 1000)
return value
def ingest_environment(self, environment):
return dict([(ev['name'], ev.get('value', '')) for ev in environment])
def emit_environment(self, environment):
return [{'name': k, 'value': v} for k, v in environment.items()]
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
@staticmethod
def _build_volume_name(hostpath):
return hostpath.replace('/', '-').strip('-')
def _build_volume(self, volume):
"""
Given a generic volume definition, create the volumes element
"""
self.volumes[self._build_volume_name(volume.get('host'))] = {
'name': self._build_volume_name(volume.get('host')),
'hostPath': {
'path': volume.get('host')
}
}
response = {
'name': self._build_volume_name(volume.get('host')),
'mountPath': volume.get('container'),
}
if volume.get('readonly', False):
response['readOnly'] = bool(volume.get('readonly', False))
return response
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
|
micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer.emit_containers | python | def emit_containers(self, containers, verbose=True):
containers = sorted(containers, key=lambda c: c.get('name'))
output = {
'kind': 'Deployment',
'apiVersion': 'extensions/v1beta1',
'metadata': {
'name': None,
'namespace': 'default',
'labels': {
'app': None,
'version': 'latest',
},
},
'spec': {
'replicas': 1,
'selector': {
'matchLabels': {
'app': None,
'version': 'latest'
}
},
'template': {
'metadata': {
'labels': {
'app': None,
'version': 'latest'
}
},
'spec': {
'containers': json.loads(json.dumps(containers))
}
}
}
}
if self.volumes:
volumes = sorted(self.volumes.values(), key=lambda x: x.get('name'))
output['spec']['template']['spec']['volumes'] = volumes
noalias_dumper = yaml.dumper.SafeDumper
noalias_dumper.ignore_aliases = lambda self, data: True
return yaml.dump(
output,
default_flow_style=False,
Dumper=noalias_dumper
) | Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L148-L205 | null | class KubernetesTransformer(BaseTransformer):
"""
A transformer for Kubernetes Pods
TODO: look at http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_pod
"""
input_type = TransformationTypes.COMPOSE.value
pod_types = {
'ReplicaSet': lambda x: x.get('spec').get('template').get('spec'),
'Deployment': lambda x: x.get('spec').get('template').get('spec'),
'DaemonSet': lambda x: x.get('spec').get('template').get('spec'),
'Pod': lambda x: x.get('spec'),
'ReplicationController': lambda x: x.get('spec').get('template').get('spec')
}
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
obj, stream, volumes_in = {}, None, []
if filename:
self._filename = filename
obj, stream, volumes_in = self._read_file(filename)
self.obj = obj
self.stream = stream
self.volumes_in = volumes_in
self.volumes = {}
def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
if len(convertable_object_idxs) < 1:
raise Exception("Kubernetes config didn't contain any of {}".format(
', '.join(self.pod_types.keys())
))
return list(data)[convertable_object_idxs[0]]
def _read_stream(self, stream):
"""
Read in the pod stream
"""
data = yaml.safe_load_all(stream=stream)
obj = self._find_convertable_object(data)
pod = self.pod_types[obj['kind']](obj)
return obj, pod.get('containers'), self.ingest_volumes_param(pod.get('volumes', []))
def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a pod spec
"""
data = {}
for volume in volumes:
if volume.get('hostPath', {}).get('path'):
data[volume.get('name')] = {
'path': volume.get('hostPath', {}).get('path'),
}
elif volume.get('emptyDir'):
data[volume.get('name')] = {}
else:
data[volume.get('name')] = {}
# TODO Support other k8s volume types?
return data
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('name')).get('path', ''),
'container': volume.get('mountPath', ''),
'readonly': bool(volume.get('readOnly')),
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
def flatten_container(self, container):
"""
Accepts a kubernetes container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.KUBERNETES.value]['name'] and \
'.' in names[TransformationTypes.KUBERNETES.value]['name']:
kubernetes_dotted_name = names[TransformationTypes.KUBERNETES.value]['name']
parts = kubernetes_dotted_name.split('.')
result = lookup_nested_dict(container, *parts)
if result:
container[kubernetes_dotted_name] = result
return container
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept groups api output
if isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def validate(self, container):
# Ensure container name
# container_name = container.get('name', str(uuid.uuid4()))
# container['name'] = container_name
container_data = defaultdict(lambda: defaultdict(dict))
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key and '.' in key:
parts = key.split('.')
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
return container_data
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'TCP').lower(),
}
if 'hostPort' in mapping:
output['host_port'] = int(mapping.get('hostPort'))
if 'name' in mapping:
output['name'] = mapping.get('name')
if 'hostIP' in mapping:
output['host_ip'] = mapping.get('hostIP')
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def emit_port_mappings(self, port_mappings):
output = []
for mapping in port_mappings:
data = {
'containerPort': mapping['container_port'],
'protocol': mapping.get('protocol', 'tcp').upper()
}
if mapping.get('host_port'):
data['hostPort'] = mapping['host_port']
if mapping.get('host_ip'):
data['hostIP'] = mapping['host_ip']
if mapping.get('name'):
data['name'] = mapping['name']
output.append(data)
return output
def ingest_memory(self, memory):
"""
Transform the memory into bytes
:param memory: Compose memory definition. (1g, 24k)
:type memory: memory string or integer
:return: The memory in bytes
:rtype: int
"""
def lshift(num, shift):
return num << shift
def k(num, thousands):
return num * thousands
# if isinstance(memory, int):
# # Memory was specified as an integer, meaning it is in bytes
memory = str(memory)
bit_shift = {
'E': {'func': k, 'shift': 10e17},
'P': {'func': k, 'shift': 10e14},
'T': {'func': k, 'shift': 10e11},
'G': {'func': k, 'shift': 10e8},
'M': {'func': k, 'shift': 10e5},
'K': {'func': k, 'shift': 10e2},
'Ei': {'func': lshift, 'shift': 60},
'Pi': {'func': lshift, 'shift': 50},
'Ti': {'func': lshift, 'shift': 40},
'Gi': {'func': lshift, 'shift': 30},
'Mi': {'func': lshift, 'shift': 20},
'Ki': {'func': lshift, 'shift': 10},
}
if len(memory) > 2 and memory[-2:] in bit_shift.keys():
unit = memory[-2:]
number = int(memory[:-2])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
elif len(memory) > 1 and memory[-1:] in bit_shift.keys():
unit = memory[-1]
number = int(memory[:-1])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
# Cast to a float to properly consume scientific notation
return int(float(memory))
def emit_memory(self, memory):
# return '{mem}Mi'.format(mem=int(memory) >> 20)
if int(memory) >> 20 > 0:
return '{mem}Mi'.format(mem=int(memory) >> 20)
return int(memory)
def ingest_cpu(self, cpu):
cpu = str(cpu)
if cpu[-1] == 'm':
cpu = float(int(cpu[:-1]) / 1000)
return float(cpu * 1024)
def emit_cpu(self, cpu):
value = float(cpu / 1024)
if value < 1.0:
value = '{}m'.format(value * 1000)
return value
def ingest_environment(self, environment):
return dict([(ev['name'], ev.get('value', '')) for ev in environment])
def emit_environment(self, environment):
return [{'name': k, 'value': v} for k, v in environment.items()]
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
@staticmethod
def _build_volume_name(hostpath):
return hostpath.replace('/', '-').strip('-')
def _build_volume(self, volume):
"""
Given a generic volume definition, create the volumes element
"""
self.volumes[self._build_volume_name(volume.get('host'))] = {
'name': self._build_volume_name(volume.get('host')),
'hostPath': {
'path': volume.get('host')
}
}
response = {
'name': self._build_volume_name(volume.get('host')),
'mountPath': volume.get('container'),
}
if volume.get('readonly', False):
response['readOnly'] = bool(volume.get('readonly', False))
return response
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
|
micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer.ingest_memory | python | def ingest_memory(self, memory):
def lshift(num, shift):
return num << shift
def k(num, thousands):
return num * thousands
# if isinstance(memory, int):
# # Memory was specified as an integer, meaning it is in bytes
memory = str(memory)
bit_shift = {
'E': {'func': k, 'shift': 10e17},
'P': {'func': k, 'shift': 10e14},
'T': {'func': k, 'shift': 10e11},
'G': {'func': k, 'shift': 10e8},
'M': {'func': k, 'shift': 10e5},
'K': {'func': k, 'shift': 10e2},
'Ei': {'func': lshift, 'shift': 60},
'Pi': {'func': lshift, 'shift': 50},
'Ti': {'func': lshift, 'shift': 40},
'Gi': {'func': lshift, 'shift': 30},
'Mi': {'func': lshift, 'shift': 20},
'Ki': {'func': lshift, 'shift': 10},
}
if len(memory) > 2 and memory[-2:] in bit_shift.keys():
unit = memory[-2:]
number = int(memory[:-2])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
elif len(memory) > 1 and memory[-1:] in bit_shift.keys():
unit = memory[-1]
number = int(memory[:-1])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
# Cast to a float to properly consume scientific notation
return int(float(memory)) | Transform the memory into bytes
:param memory: Compose memory definition. (1g, 24k)
:type memory: memory string or integer
:return: The memory in bytes
:rtype: int | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L267-L310 | null | class KubernetesTransformer(BaseTransformer):
"""
A transformer for Kubernetes Pods
TODO: look at http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_pod
"""
input_type = TransformationTypes.COMPOSE.value
pod_types = {
'ReplicaSet': lambda x: x.get('spec').get('template').get('spec'),
'Deployment': lambda x: x.get('spec').get('template').get('spec'),
'DaemonSet': lambda x: x.get('spec').get('template').get('spec'),
'Pod': lambda x: x.get('spec'),
'ReplicationController': lambda x: x.get('spec').get('template').get('spec')
}
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
obj, stream, volumes_in = {}, None, []
if filename:
self._filename = filename
obj, stream, volumes_in = self._read_file(filename)
self.obj = obj
self.stream = stream
self.volumes_in = volumes_in
self.volumes = {}
def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
if len(convertable_object_idxs) < 1:
raise Exception("Kubernetes config didn't contain any of {}".format(
', '.join(self.pod_types.keys())
))
return list(data)[convertable_object_idxs[0]]
def _read_stream(self, stream):
"""
Read in the pod stream
"""
data = yaml.safe_load_all(stream=stream)
obj = self._find_convertable_object(data)
pod = self.pod_types[obj['kind']](obj)
return obj, pod.get('containers'), self.ingest_volumes_param(pod.get('volumes', []))
def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a pod spec
"""
data = {}
for volume in volumes:
if volume.get('hostPath', {}).get('path'):
data[volume.get('name')] = {
'path': volume.get('hostPath', {}).get('path'),
}
elif volume.get('emptyDir'):
data[volume.get('name')] = {}
else:
data[volume.get('name')] = {}
# TODO Support other k8s volume types?
return data
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('name')).get('path', ''),
'container': volume.get('mountPath', ''),
'readonly': bool(volume.get('readOnly')),
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
def flatten_container(self, container):
"""
Accepts a kubernetes container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.KUBERNETES.value]['name'] and \
'.' in names[TransformationTypes.KUBERNETES.value]['name']:
kubernetes_dotted_name = names[TransformationTypes.KUBERNETES.value]['name']
parts = kubernetes_dotted_name.split('.')
result = lookup_nested_dict(container, *parts)
if result:
container[kubernetes_dotted_name] = result
return container
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept groups api output
if isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def emit_containers(self, containers, verbose=True):
"""
Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
output = {
'kind': 'Deployment',
'apiVersion': 'extensions/v1beta1',
'metadata': {
'name': None,
'namespace': 'default',
'labels': {
'app': None,
'version': 'latest',
},
},
'spec': {
'replicas': 1,
'selector': {
'matchLabels': {
'app': None,
'version': 'latest'
}
},
'template': {
'metadata': {
'labels': {
'app': None,
'version': 'latest'
}
},
'spec': {
'containers': json.loads(json.dumps(containers))
}
}
}
}
if self.volumes:
volumes = sorted(self.volumes.values(), key=lambda x: x.get('name'))
output['spec']['template']['spec']['volumes'] = volumes
noalias_dumper = yaml.dumper.SafeDumper
noalias_dumper.ignore_aliases = lambda self, data: True
return yaml.dump(
output,
default_flow_style=False,
Dumper=noalias_dumper
)
def validate(self, container):
# Ensure container name
# container_name = container.get('name', str(uuid.uuid4()))
# container['name'] = container_name
container_data = defaultdict(lambda: defaultdict(dict))
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key and '.' in key:
parts = key.split('.')
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
return container_data
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'TCP').lower(),
}
if 'hostPort' in mapping:
output['host_port'] = int(mapping.get('hostPort'))
if 'name' in mapping:
output['name'] = mapping.get('name')
if 'hostIP' in mapping:
output['host_ip'] = mapping.get('hostIP')
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def emit_port_mappings(self, port_mappings):
output = []
for mapping in port_mappings:
data = {
'containerPort': mapping['container_port'],
'protocol': mapping.get('protocol', 'tcp').upper()
}
if mapping.get('host_port'):
data['hostPort'] = mapping['host_port']
if mapping.get('host_ip'):
data['hostIP'] = mapping['host_ip']
if mapping.get('name'):
data['name'] = mapping['name']
output.append(data)
return output
def emit_memory(self, memory):
# return '{mem}Mi'.format(mem=int(memory) >> 20)
if int(memory) >> 20 > 0:
return '{mem}Mi'.format(mem=int(memory) >> 20)
return int(memory)
def ingest_cpu(self, cpu):
cpu = str(cpu)
if cpu[-1] == 'm':
cpu = float(int(cpu[:-1]) / 1000)
return float(cpu * 1024)
def emit_cpu(self, cpu):
value = float(cpu / 1024)
if value < 1.0:
value = '{}m'.format(value * 1000)
return value
def ingest_environment(self, environment):
return dict([(ev['name'], ev.get('value', '')) for ev in environment])
def emit_environment(self, environment):
return [{'name': k, 'value': v} for k, v in environment.items()]
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
@staticmethod
def _build_volume_name(hostpath):
return hostpath.replace('/', '-').strip('-')
def _build_volume(self, volume):
"""
Given a generic volume definition, create the volumes element
"""
self.volumes[self._build_volume_name(volume.get('host'))] = {
'name': self._build_volume_name(volume.get('host')),
'hostPath': {
'path': volume.get('host')
}
}
response = {
'name': self._build_volume_name(volume.get('host')),
'mountPath': volume.get('container'),
}
if volume.get('readonly', False):
response['readOnly'] = bool(volume.get('readonly', False))
return response
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
|
micahhausler/container-transform | container_transform/kubernetes.py | KubernetesTransformer._build_volume | python | def _build_volume(self, volume):
self.volumes[self._build_volume_name(volume.get('host'))] = {
'name': self._build_volume_name(volume.get('host')),
'hostPath': {
'path': volume.get('host')
}
}
response = {
'name': self._build_volume_name(volume.get('host')),
'mountPath': volume.get('container'),
}
if volume.get('readonly', False):
response['readOnly'] = bool(volume.get('readonly', False))
return response | Given a generic volume definition, create the volumes element | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/kubernetes.py#L352-L369 | null | class KubernetesTransformer(BaseTransformer):
"""
A transformer for Kubernetes Pods
TODO: look at http://kubernetes.io/docs/api-reference/v1/definitions/#_v1_pod
"""
input_type = TransformationTypes.COMPOSE.value
pod_types = {
'ReplicaSet': lambda x: x.get('spec').get('template').get('spec'),
'Deployment': lambda x: x.get('spec').get('template').get('spec'),
'DaemonSet': lambda x: x.get('spec').get('template').get('spec'),
'Pod': lambda x: x.get('spec'),
'ReplicationController': lambda x: x.get('spec').get('template').get('spec')
}
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
obj, stream, volumes_in = {}, None, []
if filename:
self._filename = filename
obj, stream, volumes_in = self._read_file(filename)
self.obj = obj
self.stream = stream
self.volumes_in = volumes_in
self.volumes = {}
def _find_convertable_object(self, data):
"""
Get the first instance of a `self.pod_types`
"""
data = list(data)
convertable_object_idxs = [
idx
for idx, obj
in enumerate(data)
if obj.get('kind') in self.pod_types.keys()
]
if len(convertable_object_idxs) < 1:
raise Exception("Kubernetes config didn't contain any of {}".format(
', '.join(self.pod_types.keys())
))
return list(data)[convertable_object_idxs[0]]
def _read_stream(self, stream):
"""
Read in the pod stream
"""
data = yaml.safe_load_all(stream=stream)
obj = self._find_convertable_object(data)
pod = self.pod_types[obj['kind']](obj)
return obj, pod.get('containers'), self.ingest_volumes_param(pod.get('volumes', []))
def ingest_volumes_param(self, volumes):
"""
This is for ingesting the "volumes" of a pod spec
"""
data = {}
for volume in volumes:
if volume.get('hostPath', {}).get('path'):
data[volume.get('name')] = {
'path': volume.get('hostPath', {}).get('path'),
}
elif volume.get('emptyDir'):
data[volume.get('name')] = {}
else:
data[volume.get('name')] = {}
# TODO Support other k8s volume types?
return data
def _ingest_volume(self, volume):
data = {
'host': self.volumes_in.get(volume.get('name')).get('path', ''),
'container': volume.get('mountPath', ''),
'readonly': bool(volume.get('readOnly')),
}
return data
def ingest_volumes(self, volumes):
return [self._ingest_volume(volume) for volume in volumes]
def flatten_container(self, container):
"""
Accepts a kubernetes container and pulls out the nested values into the top level
"""
for names in ARG_MAP.values():
if names[TransformationTypes.KUBERNETES.value]['name'] and \
'.' in names[TransformationTypes.KUBERNETES.value]['name']:
kubernetes_dotted_name = names[TransformationTypes.KUBERNETES.value]['name']
parts = kubernetes_dotted_name.split('.')
result = lookup_nested_dict(container, *parts)
if result:
container[kubernetes_dotted_name] = result
return container
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept groups api output
if isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def emit_containers(self, containers, verbose=True):
"""
Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
output = {
'kind': 'Deployment',
'apiVersion': 'extensions/v1beta1',
'metadata': {
'name': None,
'namespace': 'default',
'labels': {
'app': None,
'version': 'latest',
},
},
'spec': {
'replicas': 1,
'selector': {
'matchLabels': {
'app': None,
'version': 'latest'
}
},
'template': {
'metadata': {
'labels': {
'app': None,
'version': 'latest'
}
},
'spec': {
'containers': json.loads(json.dumps(containers))
}
}
}
}
if self.volumes:
volumes = sorted(self.volumes.values(), key=lambda x: x.get('name'))
output['spec']['template']['spec']['volumes'] = volumes
noalias_dumper = yaml.dumper.SafeDumper
noalias_dumper.ignore_aliases = lambda self, data: True
return yaml.dump(
output,
default_flow_style=False,
Dumper=noalias_dumper
)
def validate(self, container):
# Ensure container name
# container_name = container.get('name', str(uuid.uuid4()))
# container['name'] = container_name
container_data = defaultdict(lambda: defaultdict(dict))
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key and '.' in key:
parts = key.split('.')
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
return container_data
@staticmethod
def _parse_port_mapping(mapping):
output = {
'container_port': int(mapping['containerPort']),
'protocol': mapping.get('protocol', 'TCP').lower(),
}
if 'hostPort' in mapping:
output['host_port'] = int(mapping.get('hostPort'))
if 'name' in mapping:
output['name'] = mapping.get('name')
if 'hostIP' in mapping:
output['host_ip'] = mapping.get('hostIP')
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def emit_port_mappings(self, port_mappings):
output = []
for mapping in port_mappings:
data = {
'containerPort': mapping['container_port'],
'protocol': mapping.get('protocol', 'tcp').upper()
}
if mapping.get('host_port'):
data['hostPort'] = mapping['host_port']
if mapping.get('host_ip'):
data['hostIP'] = mapping['host_ip']
if mapping.get('name'):
data['name'] = mapping['name']
output.append(data)
return output
def ingest_memory(self, memory):
"""
Transform the memory into bytes
:param memory: Compose memory definition. (1g, 24k)
:type memory: memory string or integer
:return: The memory in bytes
:rtype: int
"""
def lshift(num, shift):
return num << shift
def k(num, thousands):
return num * thousands
# if isinstance(memory, int):
# # Memory was specified as an integer, meaning it is in bytes
memory = str(memory)
bit_shift = {
'E': {'func': k, 'shift': 10e17},
'P': {'func': k, 'shift': 10e14},
'T': {'func': k, 'shift': 10e11},
'G': {'func': k, 'shift': 10e8},
'M': {'func': k, 'shift': 10e5},
'K': {'func': k, 'shift': 10e2},
'Ei': {'func': lshift, 'shift': 60},
'Pi': {'func': lshift, 'shift': 50},
'Ti': {'func': lshift, 'shift': 40},
'Gi': {'func': lshift, 'shift': 30},
'Mi': {'func': lshift, 'shift': 20},
'Ki': {'func': lshift, 'shift': 10},
}
if len(memory) > 2 and memory[-2:] in bit_shift.keys():
unit = memory[-2:]
number = int(memory[:-2])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
elif len(memory) > 1 and memory[-1:] in bit_shift.keys():
unit = memory[-1]
number = int(memory[:-1])
memory = bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
# Cast to a float to properly consume scientific notation
return int(float(memory))
def emit_memory(self, memory):
# return '{mem}Mi'.format(mem=int(memory) >> 20)
if int(memory) >> 20 > 0:
return '{mem}Mi'.format(mem=int(memory) >> 20)
return int(memory)
def ingest_cpu(self, cpu):
cpu = str(cpu)
if cpu[-1] == 'm':
cpu = float(int(cpu[:-1]) / 1000)
return float(cpu * 1024)
def emit_cpu(self, cpu):
value = float(cpu / 1024)
if value < 1.0:
value = '{}m'.format(value * 1000)
return value
def ingest_environment(self, environment):
return dict([(ev['name'], ev.get('value', '')) for ev in environment])
def emit_environment(self, environment):
return [{'name': k, 'value': v} for k, v in environment.items()]
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return self._list2cmdline(entrypoint)
def emit_entrypoint(self, entrypoint):
return shlex.split(entrypoint)
@staticmethod
def _build_volume_name(hostpath):
return hostpath.replace('/', '-').strip('-')
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
|
micahhausler/container-transform | container_transform/converter.py | Converter.convert | python | def convert(self, verbose=True):
input_transformer = self._input_class(self._filename)
output_transformer = self._output_class()
containers = input_transformer.ingest_containers()
output_containers = []
for container in containers:
converted_container = self._convert_container(
container,
input_transformer,
output_transformer
)
validated = output_transformer.validate(converted_container)
output_containers.append(validated)
return output_transformer.emit_containers(output_containers, verbose) | :rtype: tuple
:returns: Output containers, messages | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/converter.py#L41-L64 | [
"def _convert_container(self, container, input_transformer, output_transformer):\n \"\"\"\n Converts a given dictionary to an output container definition\n\n :type container: dict\n :param container: The container definitions as a dictionary\n\n :rtype: dict\n :return: A output_type container defi... | class Converter(object):
def __init__(self, filename, input_type, output_type):
"""
:param filename: The file to be loaded
:type filename: str
:param input_type: The output class for the transformer
:type input_type: str
:param output_type: The output class for the transformer
:type output_type: str
"""
self._filename = filename
self.input_type = input_type
self._input_class = TRANSFORMER_CLASSES.get(input_type)
self.output_type = output_type
self._output_class = TRANSFORMER_CLASSES.get(output_type)
self.messages = set()
def _convert_container(self, container, input_transformer, output_transformer):
"""
Converts a given dictionary to an output container definition
:type container: dict
:param container: The container definitions as a dictionary
:rtype: dict
:return: A output_type container definition
"""
output = {}
for parameter, options in ARG_MAP.items():
output_name = options.get(self.output_type, {}).get('name')
output_required = options.get(self.output_type, {}).get('required')
input_name = options.get(self.input_type, {}).get('name')
if container.get(input_name) and \
hasattr(input_transformer, 'ingest_{}'.format(parameter)) and \
output_name and hasattr(output_transformer, 'emit_{}'.format(parameter)):
# call transform_{}
ingest_func = getattr(input_transformer, 'ingest_{}'.format(parameter))
emit_func = getattr(output_transformer, 'emit_{}'.format(parameter))
output[output_name] = emit_func(ingest_func(container.get(input_name)))
if not container.get(input_name) and output_required:
msg_template = 'Container {name} is missing required parameter "{output_name}".'
self.messages.add(
msg_template.format(
output_name=output_name,
output_type=self.output_type,
name=container.get('name', container)
)
)
return output
|
micahhausler/container-transform | container_transform/converter.py | Converter._convert_container | python | def _convert_container(self, container, input_transformer, output_transformer):
output = {}
for parameter, options in ARG_MAP.items():
output_name = options.get(self.output_type, {}).get('name')
output_required = options.get(self.output_type, {}).get('required')
input_name = options.get(self.input_type, {}).get('name')
if container.get(input_name) and \
hasattr(input_transformer, 'ingest_{}'.format(parameter)) and \
output_name and hasattr(output_transformer, 'emit_{}'.format(parameter)):
# call transform_{}
ingest_func = getattr(input_transformer, 'ingest_{}'.format(parameter))
emit_func = getattr(output_transformer, 'emit_{}'.format(parameter))
output[output_name] = emit_func(ingest_func(container.get(input_name)))
if not container.get(input_name) and output_required:
msg_template = 'Container {name} is missing required parameter "{output_name}".'
self.messages.add(
msg_template.format(
output_name=output_name,
output_type=self.output_type,
name=container.get('name', container)
)
)
return output | Converts a given dictionary to an output container definition
:type container: dict
:param container: The container definitions as a dictionary
:rtype: dict
:return: A output_type container definition | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/converter.py#L66-L102 | null | class Converter(object):
def __init__(self, filename, input_type, output_type):
"""
:param filename: The file to be loaded
:type filename: str
:param input_type: The output class for the transformer
:type input_type: str
:param output_type: The output class for the transformer
:type output_type: str
"""
self._filename = filename
self.input_type = input_type
self._input_class = TRANSFORMER_CLASSES.get(input_type)
self.output_type = output_type
self._output_class = TRANSFORMER_CLASSES.get(output_type)
self.messages = set()
def convert(self, verbose=True):
"""
:rtype: tuple
:returns: Output containers, messages
"""
input_transformer = self._input_class(self._filename)
output_transformer = self._output_class()
containers = input_transformer.ingest_containers()
output_containers = []
for container in containers:
converted_container = self._convert_container(
container,
input_transformer,
output_transformer
)
validated = output_transformer.validate(converted_container)
output_containers.append(validated)
return output_transformer.emit_containers(output_containers, verbose)
|
micahhausler/container-transform | container_transform/client.py | transform | python | def transform(input_file, input_type, output_type, verbose, quiet):
converter = Converter(input_file, input_type, output_type)
output = converter.convert(verbose)
click.echo(click.style(output, fg='green'))
if not quiet:
for message in converter.messages:
click.echo(click.style(message, fg='red', bold=True), err=True) | container-transform is a small utility to transform various docker
container formats to one another.
Default input type is compose, default output type is ECS
Default is to read from STDIN if no INPUT_FILE is provided
All options may be set by environment variables with the prefix "CT_"
followed by the full argument name. | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/client.py#L51-L70 | [
"def convert(self, verbose=True):\n \"\"\"\n :rtype: tuple\n :returns: Output containers, messages\n \"\"\"\n input_transformer = self._input_class(self._filename)\n output_transformer = self._output_class()\n\n containers = input_transformer.ingest_containers()\n\n output_containers = []\n\... | import click
from .converter import Converter
from .schema import InputTransformationTypes, OutputTransformationTypes
from .version import __version__
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument(
'input_file',
envvar='CT_INPUT_FILE',
default='/dev/stdin',
type=click.Path(exists=False, file_okay=True, dir_okay=False),
)
@click.option(
'-i',
'--input-type',
'input_type',
envvar='CT_INPUT_TYPE',
type=click.Choice([v.value.lower() for v in list(InputTransformationTypes)]),
default=InputTransformationTypes.COMPOSE.value,
)
@click.option(
'-o',
'--output-type',
'output_type',
envvar='CT_OUTPUT_TYPE',
type=click.Choice([v.value.lower() for v in list(OutputTransformationTypes)]),
default=OutputTransformationTypes.ECS.value,
)
@click.option(
'-v/--no-verbose',
'--verbose',
'verbose',
envvar='CT_VERBOSE',
default=True,
help='Expand/minify json output'
)
@click.option(
'-q',
'--quiet',
envvar='CT_QUIET',
default=False,
is_flag=True,
help='Silence error messages'
)
@click.version_option(__version__)
|
micahhausler/container-transform | container_transform/chronos.py | ChronosTransformer.flatten_container | python | def flatten_container(self, container):
for names in ARG_MAP.values():
if names[TransformationTypes.CHRONOS.value]['name'] and \
'.' in names[TransformationTypes.CHRONOS.value]['name']:
chronos_dotted_name = names[TransformationTypes.CHRONOS.value]['name']
parts = chronos_dotted_name.split('.')
if parts[-2] == 'parameters':
# Special lookup for docker parameters
common_type = names[TransformationTypes.CHRONOS.value].get('type')
result = self._lookup_parameter(container, parts[-1], common_type)
if result:
container[chronos_dotted_name] = result
else:
result = lookup_nested_dict(container, *parts)
if result:
container[chronos_dotted_name] = result
return container | Accepts a chronos container and pulls out the nested values into the top level | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/chronos.py#L106-L126 | [
"def lookup_nested_dict(dic, key, *keys):\n if keys:\n return lookup_nested_dict(dic.get(key, None), *keys)\n return dic.get(key)\n",
"def _lookup_parameter(self, container, key, common_type=None):\n \"\"\"\n Lookup the `docker run` keyword from the 'container.docker.parameters' list\n :para... | class ChronosTransformer(BaseTransformer):
"""
A transformer for Chronos Jobs
When consuming Chronos input, the transformer supports:
When emitting Chronos output, the transformer will emit a list of
applications if there is more than one. Otherwise, it will emit a single
application.
To use this class:
.. code-block:: python
transformer = ChronosTransformer('./task.json')
output = transformer.ingest_container()
print(json.dumps(output, indent=4))
"""
input_type = TransformationTypes.COMPOSE.value
def __init__(self, filename=None):
"""
:param filename: The file to be loaded
:type filename: str
"""
if filename:
self._filename = filename
stream = self._read_file(filename)
self.stream = stream
else:
self.stream = None
def _read_stream(self, stream):
"""
Read in the json stream
"""
return json.load(stream)
def _lookup_parameter(self, container, key, common_type=None):
"""
Lookup the `docker run` keyword from the 'container.docker.parameters' list
:param container: The container in question
:param key: The key name we're looking up
:param is_list: if the response is a list of items
"""
if not container.get('container', {}).get('parameters'):
return
params = container['container']['parameters']
# Super hacky - log-opt is a sub option of the logging directive of everything else
if key == 'log-driver':
return [
p
for p
in params
if p['key'] in ['log-opt', 'log-driver']]
matching_params = [
p['value']
for p
in params
if p['key'] == key]
if matching_params:
if common_type == list:
return matching_params
else:
return matching_params[0]
def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
# Accept lists of tasks for convenience
if isinstance(containers, dict):
containers = [containers]
return [
self.flatten_container(container)
for container
in containers]
def emit_containers(self, containers, verbose=True):
"""
Emits the applications and sorts containers by name
:param containers: List of the container definitions
:type containers: list of dict
:param verbose: Print out newlines and indented JSON
:type verbose: bool
:returns: The text output
:rtype: str
"""
containers = sorted(containers, key=lambda c: c.get('name'))
if len(containers) == 1 and isinstance(containers, list):
containers = containers[0]
if verbose:
return json.dumps(containers, indent=4, sort_keys=True)
else:
return json.dumps(containers)
def validate(self, container):
# Ensure container name
container_name = container.get('name', str(uuid.uuid4()))
container['name'] = container_name
container_data = defaultdict(lambda: defaultdict(dict))
container_data.update(container)
# Find keys with periods in the name, these are keys that we delete and
# create the corresponding entry for
for key, value in deepcopy(container_data).items():
if key.startswith('container.'):
parts = key.split('.')
if parts[-2] == 'parameters':
# Parameters are inserted below
parts = parts[:-1]
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
else:
data = reduce(lambda x, y: {y: x}, reversed(parts + [value]))
update_nested_dict(container_data, data)
del container_data[key]
# Sort the parameters in a deterministic way
if container_data['container'].get('parameters'):
old_params = container_data['container']['parameters']
sorted_values = sorted(
old_params, key=lambda p: str(p.get('value'))
)
sorted_keys = sorted(
sorted_values, key=lambda p: p.get('key')
)
container_data['container']['parameters'] = sorted_keys
# Assume the network mode is BRIDGE if unspecified
if container_data['container'].get('network') != 'HOST':
container_data['container']['network'] = 'BRIDGE'
container_data['container']['forcePullImage'] = True
container_data['container']['type'] = 'DOCKER'
container_data['uris'] = []
container_data['schedule'] = 'R/{now}/PT1H'.format(now=datetime.utcnow().isoformat())
container_data['disabled'] = False
container_data['shell'] = False
container_data['owner'] = None
container_data['ownerName'] = None
container_data['description'] = ""
return container_data
def ingest_name(self, name):
return name.split('/')[-1]
def emit_links(self, links):
return [
{'key': 'link', 'value': link}
for link
in links
]
@staticmethod
def _parse_port_mapping(mapping):
protocol = 'udp' if 'udp' in str(mapping) else 'tcp'
output = {
'protocol': protocol
}
mapping = str(mapping).rstrip('/udp')
parts = str(mapping).split(':')
if len(parts) == 1:
output.update({
'container_port': int(parts[0])
})
else:
output.update({
'host_port': int(parts[0]),
'container_port': int(parts[1]),
})
return output
def ingest_port_mappings(self, port_mappings):
"""
Transform the port mappings to base schema mappings
:param port_mappings: The port mappings
:type port_mappings: list of dict
:return: The base schema mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
def _construct_port_mapping(self, mapping):
output = str(mapping['container_port'])
if 'host_port' in mapping:
output = str(mapping['host_port']) + ':' + output
if mapping.get('protocol') == 'udp':
output += '/udp'
return output
def emit_port_mappings(self, port_mappings):
return [
{
'key': 'publish',
'value': self._construct_port_mapping(mapping),
}
for mapping
in port_mappings]
def ingest_memory(self, memory):
return memory << 20
def emit_memory(self, memory):
mem_in_mb = memory >> 20
if 4 > mem_in_mb:
return 4
return mem_in_mb
def ingest_cpu(self, cpu):
return float(cpu * 1024)
def emit_cpu(self, cpu):
return float(cpu/1024)
def ingest_environment(self, environment):
return dict([(var['name'], var['value']) for var in environment])
def emit_environment(self, environment):
environ = [
{'name': name, 'value': value}
for name, value
in environment.items()
]
# Sort the parameters in a deterministic way
sorted_by_value = sorted(environ, key=lambda p: p.get('value'))
return sorted(sorted_by_value, key=lambda p: p.get('name'))
def ingest_command(self, command):
return self._list2cmdline(command)
def emit_command(self, command):
return shlex.split(command)
def ingest_entrypoint(self, entrypoint):
return entrypoint
def emit_entrypoint(self, entrypoint):
return [{'key': 'entrypoint', 'value': entrypoint}]
def ingest_volumes_from(self, volumes_from):
return volumes_from
def emit_volumes_from(self, volumes_from):
return [{'key': 'volumes-from', 'value': vol} for vol in volumes_from]
def _convert_volume(self, volume):
"""
This is for ingesting the "volumes" of a app description
"""
data = {
'host': volume.get('hostPath'),
'container': volume.get('containerPath'),
'readonly': volume.get('mode') == 'RO',
}
return data
def ingest_volumes(self, volumes):
return [self._convert_volume(volume) for volume in volumes]
@staticmethod
def _build_volume(volume):
"""
Given a generic volume definition, create the volumes element
"""
return {
'hostPath': volume.get('host'),
'containerPath': volume.get('container'),
'mode': 'RO' if volume.get('readonly') else 'RW'
}
def emit_volumes(self, volumes):
return [
self._build_volume(volume)
for volume
in volumes
]
def ingest_logging(self, logging):
# Super hacky continued - in self._lookup_parameter() we flatten the logging options
data = {
'driver': [p['value'] for p in logging if p['key'] == 'log-driver'][0],
'options': dict([p['value'].split('=') for p in logging if p['key'] == 'log-opt'])
}
return data
def emit_logging(self, logging):
output = [{
'key': 'log-driver',
'value': logging.get('driver')
}]
if logging.get('options') and isinstance(logging.get('options'), dict):
for k, v in logging.get('options').items():
output.append({
'key': 'log-opt',
'value': '{k}={v}'.format(k=k, v=v)
})
return output
def emit_dns(self, dns):
return [{'key': 'dns', 'value': serv} for serv in dns]
def emit_domain(self, domain):
return [{'key': 'dns-search', 'value': d} for d in domain]
def emit_work_dir(self, work_dir):
return [{'key': 'workdir', 'value': work_dir}]
def emit_network(self, network):
return [{'key': 'net', 'value': net} for net in network]
def ingest_net_mode(self, net_mode):
return net_mode.lower()
def emit_net_mode(self, net_mode):
return net_mode.upper()
def emit_user(self, user):
return [{'key': 'user', 'value': user}]
def emit_pid(self, pid):
return [{'key': 'pid', 'value': pid}]
def emit_env_file(self, env_file):
return [{'key': 'env-file', 'value': ef} for ef in env_file]
def emit_expose(self, expose):
return [{'key': 'expose', 'value': port} for port in expose]
def emit_labels(self, labels):
return [{'key': 'label', 'value': label} for label in labels]
def emit_privileged(self, privileged):
return [{'key': 'privileged', 'value': privileged}]
def ingest_fetch(self, fetch):
return [{'uri': uri} for uri in fetch]
def emit_fetch(self, fetch):
return [uri.get('uri') for uri in fetch]
|
micahhausler/container-transform | container_transform/transformer.py | BaseTransformer._read_file | python | def _read_file(self, filename):
with open(filename, 'r') as stream:
return self._read_stream(stream=stream) | :param filename: The location of the file to read
:type filename: str | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/transformer.py#L66-L72 | [
"def _read_stream(self, stream):\n \"\"\"\n Read in the json stream\n \"\"\"\n return json.load(stream)\n",
"def _read_stream(self, stream):\n return yaml.safe_load(stream=stream)\n",
"def _read_stream(self, stream):\n \"\"\"\n We override the return signature of\n ``super(BaseTransforme... | class BaseTransformer(object, metaclass=ABCMeta):
"""
The base class for Transformer classes to inherit from.
Basic usage should look like
.. code-block:: python
transformer = MyTransformer('./my-file.txt')
normalized_keys = transformer.ingest_containers()
"""
@staticmethod
def _list2cmdline(commands):
def quote(cmd):
"""
Make sure that each cmd in command list will be treated as a single token
:param cmd: str
:return:
"""
if len(shlex.split(cmd)) == 1:
# Already a single token, do nothing
return cmd
else:
return shlex.quote(cmd)
return ' '.join(quote(cmd) for cmd in commands)
@abstractmethod
def _read_stream(self, stream):
"""
Override this method and parse the stream to be passed to
``self.transform()``
:param stream: A file-like object
:type stream: file
"""
raise NotImplementedError
@abstractmethod
def ingest_containers(self, containers=None):
"""
Ingest self.stream and return a list of un-converted container
definitions dictionaries.
This is to normalize `where` all the container information is.
For example, Compose v1 places the container name outside the rest of the
container definition. We need to have a 'name' key in the container
definition.
:rtype: list of dict
"""
raise NotImplementedError
@abstractmethod
def emit_containers(self, containers, verbose=True):
raise NotImplementedError
@staticmethod
@abstractmethod
def validate(container):
"""
Validate that the container has all essential parameters and add any if
possible
:param container: The converted container
:type container: dict
:return: The container with all valid parameters
:rtype: dict
"""
raise NotImplementedError
def ingest_name(self, name):
return name
def emit_name(self, name):
return name
def ingest_image(self, image):
return image
def emit_image(self, image):
return image
def ingest_links(self, image):
return image
def emit_links(self, image):
return image
def ingest_user(self, user):
return user
def emit_user(self, user):
return user
def ingest_net_mode(self, net_mode):
return net_mode
def emit_net_mode(self, net_mode):
return net_mode
def ingest_network(self, network):
if not isinstance(network, list) and network is not None:
network = [network]
return network
def emit_network(self, network):
return network
def ingest_domain(self, domain):
if not isinstance(domain, list) and domain is not None:
domain = [domain]
return domain
def emit_domain(self, domain):
return domain
def ingest_dns(self, dns):
if not isinstance(dns, list) and dns is not None:
dns = [dns]
return dns
def emit_dns(self, dns):
return dns
def ingest_work_dir(self, work_dir):
return work_dir
def emit_work_dir(self, work_dir):
return work_dir
def ingest_labels(self, labels):
return labels
def emit_labels(self, labels):
return labels
def ingest_pid(self, pid):
return pid
def emit_pid(self, pid):
return pid
def ingest_env_file(self, env_file):
if not isinstance(env_file, list) and env_file is not None:
env_file = [env_file]
return env_file
def emit_env_file(self, env_file):
return env_file
def ingest_expose(self, expose):
if not isinstance(expose, list) and expose is not None:
expose = [expose]
return expose
def emit_expose(self, expose):
return expose
def ingest_privileged(self, privileged):
return privileged
def emit_privileged(self, privileged):
return privileged
def ingest_fetch(self, fetch):
return fetch
def emit_fetch(self, fetch):
return fetch
@abstractmethod
def ingest_port_mappings(self, port_mappings):
raise NotImplementedError
@abstractmethod
def emit_port_mappings(self, port_mappings):
raise NotImplementedError
@abstractmethod
def ingest_cpu(self, cpu):
raise NotImplementedError
@abstractmethod
def emit_cpu(self, cpu):
raise NotImplementedError
@abstractmethod
def ingest_memory(self, memory):
raise NotImplementedError
@abstractmethod
def emit_memory(self, memory):
raise NotImplementedError
@abstractmethod
def ingest_environment(self, environment):
raise NotImplementedError
@abstractmethod
def emit_environment(self, environment):
raise NotImplementedError
@abstractmethod
def ingest_command(self, command):
raise NotImplementedError
@abstractmethod
def emit_command(self, command):
raise NotImplementedError
@abstractmethod
def ingest_entrypoint(self, entrypoint):
raise NotImplementedError
@abstractmethod
def emit_entrypoint(self, entrypoint):
raise NotImplementedError
@abstractmethod
def ingest_volumes(self, volumes):
raise NotImplementedError
@abstractmethod
def emit_volumes(self, volumes):
raise NotImplementedError
|
micahhausler/container-transform | container_transform/compose.py | ComposeTransformer.ingest_containers | python | def ingest_containers(self, containers=None):
containers = containers or self.stream or {}
output_containers = []
for container_name, definition in containers.items():
container = definition.copy()
container['name'] = container_name
output_containers.append(container)
return output_containers | Transform the YAML into a dict with normalized keys | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/compose.py#L46-L59 | null | class ComposeTransformer(BaseTransformer):
"""
A transformer for docker-compose v1 and v2
To use this class:
.. code-block:: python
transformer = ComposeTransformer('./docker-compose.yml')
normalized_keys = transformer.ingest_containers()
"""
def __init__(self, filename=None):
"""
We override ``.__init__()`` on purpose, we need to get the volume,
version, network, and possibly other data.
:param filename: The file to be loaded
:type filename: str
"""
if filename:
self._filename = filename
stream = self._read_file(filename)
self.stream_version = float(stream.get('version', '1'))
if self.stream_version > 1:
self.stream = stream.get('services')
self.volumes = stream.get('volumes', None)
self.networks = stream.get('networks', None)
else:
self.stream = stream
else:
self.stream = None
def _read_stream(self, stream):
return yaml.safe_load(stream=stream)
def emit_containers(self, containers, verbose=True):
services = {}
for container in containers:
name_in_container = container.get('name')
if not name_in_container:
name = str(uuid.uuid4())
else:
name = container.pop('name')
services[name] = container
output = {
'services': services,
'version': '2',
}
noalias_dumper = yaml.dumper.SafeDumper
noalias_dumper.ignore_aliases = lambda self, data: True
return yaml.dump(
output,
default_flow_style=False,
Dumper=noalias_dumper
)
@staticmethod
def validate(container):
return container
@staticmethod
def _parse_port_mapping(mapping):
protocol = 'udp' if 'udp' in str(mapping) else 'tcp'
output = {
'protocol': protocol
}
mapping = str(mapping).rstrip('/udp')
parts = str(mapping).split(':')
if len(parts) == 1:
output.update({
'container_port': int(parts[0])
})
elif len(parts) == 2 and '.' not in mapping:
output.update({
'host_port': int(parts[0]),
'container_port': int(parts[1]),
})
elif len(parts) == 3:
if '.' in parts[0]:
output.update({
'host_ip': parts[0],
'host_port': int(parts[1]),
'container_port': int(parts[2]),
})
else:
output.update({
'host_port': int(parts[0]),
'container_ip': parts[1],
'container_port': int(parts[2]),
})
elif len(parts) == 4:
output.update({
'host_ip': parts[0],
'host_port': int(parts[1]),
'container_ip': parts[2],
'container_port': int(parts[3]),
})
return output if len(output) >= 2 else None
def ingest_port_mappings(self, port_mappings):
"""
Transform the docker-compose port mappings to base schema port_mappings
:param port_mappings: The compose port mappings
:type port_mappings: list
:return: the base schema port_mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
@staticmethod
def _emit_mapping(mapping):
parts = []
if mapping.get('host_ip'):
parts.append(str(mapping['host_ip']))
if mapping.get('host_port'):
parts.append(str(mapping['host_port']))
if mapping.get('container_ip'):
parts.append(str(mapping['container_ip']))
if mapping.get('container_port'):
parts.append(str(mapping['container_port']))
output = ':'.join(parts)
if mapping.get('protocol') == 'udp':
output += '/udp'
return output
def emit_port_mappings(self, port_mappings):
"""
:param port_mappings: the base schema port_mappings
:type port_mappings: list of dict
:return:
:rtype: list of str
"""
return [str(self._emit_mapping(mapping)) for mapping in port_mappings]
def ingest_memory(self, memory):
"""
Transform the memory into bytes
:param memory: Compose memory definition. (1g, 24k)
:type memory: memory string or integer
:return: The memory in bytes
:rtype: int
"""
def lshift(num, shift):
return num << shift
def rshift(num, shift):
return num >> shift
if isinstance(memory, int):
# Memory was specified as an integer, meaning it is in bytes
memory = '{}b'.format(memory)
bit_shift = {
'g': {'func': lshift, 'shift': 30},
'm': {'func': lshift, 'shift': 20},
'k': {'func': lshift, 'shift': 10},
'b': {'func': rshift, 'shift': 0}
}
unit = memory[-1]
number = int(memory[:-1])
return bit_shift[unit]['func'](number, bit_shift[unit]['shift'])
def emit_memory(self, memory):
return '{}b'.format(memory)
def ingest_cpu(self, cpu):
return cpu
def emit_cpu(self, cpu):
return cpu
def ingest_environment(self, environment):
output = {}
if type(environment) is list:
for kv in environment:
index = kv.find('=')
output[str(kv[:index])] = str(kv[index + 1:]).replace('$$', '$')
if type(environment) is dict:
for key, value in environment.items():
output[str(key)] = str(value).replace('$$', '$')
return output
def emit_environment(self, environment):
# Use double-dollar and avoid vairable substitution. Reference,
# https://docs.docker.com/compose/compose-file/compose-file-v2
for key, value in environment.items():
environment[key] = str(value).replace('$', '$$')
return environment
def ingest_command(self, command):
if isinstance(command, list):
return self._list2cmdline(command)
return command
def emit_command(self, command):
return command
def ingest_entrypoint(self, entrypoint):
if isinstance(entrypoint, list):
return self._list2cmdline(entrypoint)
return entrypoint
def emit_entrypoint(self, entrypoint):
return entrypoint
def ingest_volumes_from(self, volumes_from):
ingested_volumes_from = []
for vol in volumes_from:
ingested = {}
parts = vol.split(':')
rwo_value = None
assert len(parts) <= 3, \
"Volume string '{}' has too many colons".format(vol)
if len(parts) == 3:
# Is form 'service:name:ro' or 'container:name:ro'
# in new compose v2 format.
source_container, rwo_value = parts[1:]
elif len(parts) == 2:
# Is form 'name:ro' or 'service:name' (for >= v2)
if self.stream_version > 1 and parts[0] == 'service':
source_container = parts[1]
else:
assert(parts[1] in ['ro', 'rw'])
source_container = parts[0]
rwo_value = parts[1]
else:
source_container = parts[0]
if rwo_value == 'ro':
ingested['read_only'] = True
ingested['source_container'] = source_container
ingested_volumes_from.append(ingested)
return ingested_volumes_from
def emit_volumes_from(self, volumes_from):
return volumes_from
@staticmethod
def _ingest_volume(volume):
parts = volume.split(':')
if len(parts) == 1:
return {
'host': parts[0],
'container': parts[0]
}
if len(parts) == 2 and parts[1] != 'ro':
return {
'host': parts[0],
'container': parts[1]
}
if len(parts) == 2 and parts[1] == 'ro':
return {
'host': parts[0],
'container': parts[0],
'readonly': True
}
if len(parts) == 3 and parts[-1] == 'ro':
return {
'host': parts[0],
'container': parts[1],
'readonly': True
}
if len(parts) == 3 and parts[-1] == 'rw':
return {
'host': parts[0],
'container': parts[1],
}
def ingest_volumes(self, volumes):
return [
self._ingest_volume(volume)
for volume
in volumes
if self._ingest_volume(volume) is not None
]
@staticmethod
def _emit_volume(volume):
volume_str = '{0}:{1}'.format(volume.get('host'), volume.get('container', ':'))
volume_str = volume_str.strip(':')
if volume.get('readonly') and len(volume_str):
volume_str += ':ro'
return volume_str
def emit_volumes(self, volumes):
return [
self._emit_volume(volume)
for volume
in volumes
if len(self._emit_volume(volume))
]
@staticmethod
def _parse_label_string(label):
eq = label.find('=')
if eq == -1:
return {label: None}
else:
return {label[:eq]: label[eq+1:]}
def ingest_labels(self, labels):
if isinstance(labels, list):
return reduce(
lambda a, b: a.update(b) or a,
map(self._parse_label_string, labels),
{}
)
return labels
def emit_labels(self, labels):
return labels
def ingest_logging(self, logging):
return logging
def emit_logging(self, logging):
return logging
def ingest_privileged(self, privileged):
return privileged
def emit_privileged(self, privileged):
return privileged
|
micahhausler/container-transform | container_transform/compose.py | ComposeTransformer.ingest_memory | python | def ingest_memory(self, memory):
def lshift(num, shift):
return num << shift
def rshift(num, shift):
return num >> shift
if isinstance(memory, int):
# Memory was specified as an integer, meaning it is in bytes
memory = '{}b'.format(memory)
bit_shift = {
'g': {'func': lshift, 'shift': 30},
'm': {'func': lshift, 'shift': 20},
'k': {'func': lshift, 'shift': 10},
'b': {'func': rshift, 'shift': 0}
}
unit = memory[-1]
number = int(memory[:-1])
return bit_shift[unit]['func'](number, bit_shift[unit]['shift']) | Transform the memory into bytes
:param memory: Compose memory definition. (1g, 24k)
:type memory: memory string or integer
:return: The memory in bytes
:rtype: int | train | https://github.com/micahhausler/container-transform/blob/68223fae98f30b8bb2ce0f02ba9e58afbc80f196/container_transform/compose.py#L165-L192 | null | class ComposeTransformer(BaseTransformer):
"""
A transformer for docker-compose v1 and v2
To use this class:
.. code-block:: python
transformer = ComposeTransformer('./docker-compose.yml')
normalized_keys = transformer.ingest_containers()
"""
def __init__(self, filename=None):
"""
We override ``.__init__()`` on purpose, we need to get the volume,
version, network, and possibly other data.
:param filename: The file to be loaded
:type filename: str
"""
if filename:
self._filename = filename
stream = self._read_file(filename)
self.stream_version = float(stream.get('version', '1'))
if self.stream_version > 1:
self.stream = stream.get('services')
self.volumes = stream.get('volumes', None)
self.networks = stream.get('networks', None)
else:
self.stream = stream
else:
self.stream = None
def _read_stream(self, stream):
return yaml.safe_load(stream=stream)
def ingest_containers(self, containers=None):
"""
Transform the YAML into a dict with normalized keys
"""
containers = containers or self.stream or {}
output_containers = []
for container_name, definition in containers.items():
container = definition.copy()
container['name'] = container_name
output_containers.append(container)
return output_containers
def emit_containers(self, containers, verbose=True):
services = {}
for container in containers:
name_in_container = container.get('name')
if not name_in_container:
name = str(uuid.uuid4())
else:
name = container.pop('name')
services[name] = container
output = {
'services': services,
'version': '2',
}
noalias_dumper = yaml.dumper.SafeDumper
noalias_dumper.ignore_aliases = lambda self, data: True
return yaml.dump(
output,
default_flow_style=False,
Dumper=noalias_dumper
)
@staticmethod
def validate(container):
return container
@staticmethod
def _parse_port_mapping(mapping):
protocol = 'udp' if 'udp' in str(mapping) else 'tcp'
output = {
'protocol': protocol
}
mapping = str(mapping).rstrip('/udp')
parts = str(mapping).split(':')
if len(parts) == 1:
output.update({
'container_port': int(parts[0])
})
elif len(parts) == 2 and '.' not in mapping:
output.update({
'host_port': int(parts[0]),
'container_port': int(parts[1]),
})
elif len(parts) == 3:
if '.' in parts[0]:
output.update({
'host_ip': parts[0],
'host_port': int(parts[1]),
'container_port': int(parts[2]),
})
else:
output.update({
'host_port': int(parts[0]),
'container_ip': parts[1],
'container_port': int(parts[2]),
})
elif len(parts) == 4:
output.update({
'host_ip': parts[0],
'host_port': int(parts[1]),
'container_ip': parts[2],
'container_port': int(parts[3]),
})
return output if len(output) >= 2 else None
def ingest_port_mappings(self, port_mappings):
"""
Transform the docker-compose port mappings to base schema port_mappings
:param port_mappings: The compose port mappings
:type port_mappings: list
:return: the base schema port_mappings
:rtype: list of dict
"""
return [self._parse_port_mapping(mapping) for mapping in port_mappings]
@staticmethod
def _emit_mapping(mapping):
parts = []
if mapping.get('host_ip'):
parts.append(str(mapping['host_ip']))
if mapping.get('host_port'):
parts.append(str(mapping['host_port']))
if mapping.get('container_ip'):
parts.append(str(mapping['container_ip']))
if mapping.get('container_port'):
parts.append(str(mapping['container_port']))
output = ':'.join(parts)
if mapping.get('protocol') == 'udp':
output += '/udp'
return output
def emit_port_mappings(self, port_mappings):
"""
:param port_mappings: the base schema port_mappings
:type port_mappings: list of dict
:return:
:rtype: list of str
"""
return [str(self._emit_mapping(mapping)) for mapping in port_mappings]
def emit_memory(self, memory):
return '{}b'.format(memory)
def ingest_cpu(self, cpu):
return cpu
def emit_cpu(self, cpu):
return cpu
def ingest_environment(self, environment):
output = {}
if type(environment) is list:
for kv in environment:
index = kv.find('=')
output[str(kv[:index])] = str(kv[index + 1:]).replace('$$', '$')
if type(environment) is dict:
for key, value in environment.items():
output[str(key)] = str(value).replace('$$', '$')
return output
def emit_environment(self, environment):
# Use double-dollar and avoid vairable substitution. Reference,
# https://docs.docker.com/compose/compose-file/compose-file-v2
for key, value in environment.items():
environment[key] = str(value).replace('$', '$$')
return environment
def ingest_command(self, command):
if isinstance(command, list):
return self._list2cmdline(command)
return command
def emit_command(self, command):
return command
def ingest_entrypoint(self, entrypoint):
if isinstance(entrypoint, list):
return self._list2cmdline(entrypoint)
return entrypoint
def emit_entrypoint(self, entrypoint):
return entrypoint
def ingest_volumes_from(self, volumes_from):
ingested_volumes_from = []
for vol in volumes_from:
ingested = {}
parts = vol.split(':')
rwo_value = None
assert len(parts) <= 3, \
"Volume string '{}' has too many colons".format(vol)
if len(parts) == 3:
# Is form 'service:name:ro' or 'container:name:ro'
# in new compose v2 format.
source_container, rwo_value = parts[1:]
elif len(parts) == 2:
# Is form 'name:ro' or 'service:name' (for >= v2)
if self.stream_version > 1 and parts[0] == 'service':
source_container = parts[1]
else:
assert(parts[1] in ['ro', 'rw'])
source_container = parts[0]
rwo_value = parts[1]
else:
source_container = parts[0]
if rwo_value == 'ro':
ingested['read_only'] = True
ingested['source_container'] = source_container
ingested_volumes_from.append(ingested)
return ingested_volumes_from
def emit_volumes_from(self, volumes_from):
return volumes_from
@staticmethod
def _ingest_volume(volume):
parts = volume.split(':')
if len(parts) == 1:
return {
'host': parts[0],
'container': parts[0]
}
if len(parts) == 2 and parts[1] != 'ro':
return {
'host': parts[0],
'container': parts[1]
}
if len(parts) == 2 and parts[1] == 'ro':
return {
'host': parts[0],
'container': parts[0],
'readonly': True
}
if len(parts) == 3 and parts[-1] == 'ro':
return {
'host': parts[0],
'container': parts[1],
'readonly': True
}
if len(parts) == 3 and parts[-1] == 'rw':
return {
'host': parts[0],
'container': parts[1],
}
def ingest_volumes(self, volumes):
return [
self._ingest_volume(volume)
for volume
in volumes
if self._ingest_volume(volume) is not None
]
@staticmethod
def _emit_volume(volume):
volume_str = '{0}:{1}'.format(volume.get('host'), volume.get('container', ':'))
volume_str = volume_str.strip(':')
if volume.get('readonly') and len(volume_str):
volume_str += ':ro'
return volume_str
def emit_volumes(self, volumes):
return [
self._emit_volume(volume)
for volume
in volumes
if len(self._emit_volume(volume))
]
@staticmethod
def _parse_label_string(label):
eq = label.find('=')
if eq == -1:
return {label: None}
else:
return {label[:eq]: label[eq+1:]}
def ingest_labels(self, labels):
if isinstance(labels, list):
return reduce(
lambda a, b: a.update(b) or a,
map(self._parse_label_string, labels),
{}
)
return labels
def emit_labels(self, labels):
return labels
def ingest_logging(self, logging):
return logging
def emit_logging(self, logging):
return logging
def ingest_privileged(self, privileged):
return privileged
def emit_privileged(self, privileged):
return privileged
|
openatx/facebook-wda | wda/__init__.py | urljoin | python | def urljoin(*urls):
return reduce(_urljoin, [u.strip('/')+'/' for u in urls if u.strip('/')], '').rstrip('/') | The default urlparse.urljoin behavior look strange
Standard urlparse.urljoin('http://a.com/foo', '/bar')
Expect: http://a.com/foo/bar
Actually: http://a.com/bar
This function fix that. | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L45-L54 | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
import base64
import copy
import functools
import json
import os
import re
import io
import time
from collections import namedtuple
import requests
import six
from . import xcui_element_types
if six.PY3:
from urllib.parse import urljoin as _urljoin
from functools import reduce
else:
from urlparse import urljoin as _urljoin
DEBUG = False
HTTP_TIMEOUT = 60.0 # unit second
LANDSCAPE = 'LANDSCAPE'
PORTRAIT = 'PORTRAIT'
LANDSCAPE_RIGHT = 'UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT'
PORTRAIT_UPSIDEDOWN = 'UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN'
alert_callback = None
def convert(dictionary):
"""
Convert dict to namedtuple
"""
return namedtuple('GenericDict', list(dictionary.keys()))(**dictionary)
def roundint(i):
return int(round(i, 0))
def httpdo(url, method='GET', data=None):
"""
Do HTTP Request
"""
start = time.time()
if isinstance(data, dict):
data = json.dumps(data)
if DEBUG:
print("Shell: curl -X {method} -d '{data}' '{url}'".format(method=method.upper(), data=data or '', url=url))
try:
response = requests.request(method, url, data=data, timeout=HTTP_TIMEOUT)
except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout):
# retry again
# print('retry to connect, error: {}'.format(e))
time.sleep(1.0)
response = requests.request(method, url, data=data, timeout=HTTP_TIMEOUT)
if DEBUG:
ms = (time.time() - start) * 1000
print('Return ({:.0f}ms): {}'.format(ms, response.text))
try:
retjson = response.json()
except ValueError as e:
# show why json.loads error
raise ValueError(e, response.text)
r = convert(retjson)
if r.status != 0:
raise WDAError(r.status, r.value)
return r
class HTTPClient(object):
def __init__(self, address, alert_callback=None):
"""
Args:
address (string): url address eg: http://localhost:8100
alert_callback (func): function to call when alert popup
"""
self.address = address
self.alert_callback = alert_callback
def new_client(self, path):
return HTTPClient(self.address.rstrip('/') + '/' + path.lstrip('/'), self.alert_callback)
def fetch(self, method, url, data=None):
return self._fetch_no_alert(method, url, data)
# return httpdo(urljoin(self.address, url), method, data)
def _fetch_no_alert(self, method, url, data=None, depth=0):
target_url = urljoin(self.address, url)
try:
return httpdo(target_url, method, data)
except WDAError as err:
if depth >= 10:
raise
if err.status != 26:
raise
if not callable(self.alert_callback):
raise
self.alert_callback()
return self._fetch_no_alert(method, url, data, depth=depth+1)
def __getattr__(self, key):
""" Handle GET,POST,DELETE, etc ... """
return functools.partial(self.fetch, key)
class WDAError(Exception):
def __init__(self, status, value):
self.status = status
self.value = value
def __str__(self):
return 'WDAError(status=%d, value=%s)' % (self.status, self.value)
class WDAElementNotFoundError(Exception):
pass
class WDAElementNotDisappearError(Exception):
pass
class Rect(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def __str__(self):
return 'Rect(x={x}, y={y}, width={w}, height={h})'.format(
x=self.x, y=self.y, w=self.width, h=self.height)
def __repr__(self):
return str(self)
@property
def center(self):
return namedtuple('Point', ['x', 'y'])(self.x+self.width/2, self.y+self.height/2)
@property
def origin(self):
return namedtuple('Point', ['x', 'y'])(self.x, self.y)
@property
def left(self):
return self.x
@property
def top(self):
return self.y
@property
def right(self):
return self.x+self.width
@property
def bottom(self):
return self.y+self.height
class Client(object):
def __init__(self, url=None):
"""
Args:
target (string): the device url
If target is None, device url will set to env-var "DEVICE_URL" if defined else set to "http://localhost:8100"
"""
if url is None:
url = os.environ.get('DEVICE_URL', 'http://localhost:8100')
self.http = HTTPClient(url)
def wait_ready(self, timeout=120):
"""
wait until WDA back to normal
Returns:
bool (if wda works)
"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
self.status()
return True
except:
time.sleep(2)
return False
def status(self):
res = self.http.get('status')
sid = res.sessionId
res.value['sessionId'] = sid
return res.value
def home(self):
"""Press home button"""
return self.http.post('/wda/homescreen')
def healthcheck(self):
"""Hit healthcheck"""
return self.http.get('/wda/healthcheck')
def source(self, format='xml', accessible=False):
"""
Args:
format (str): only 'xml' and 'json' source types are supported
accessible (bool): when set to true, format is always 'json'
"""
if accessible:
return self.http.get('/wda/accessibleSource').value
return self.http.get('source?format='+format).value
def session(self, bundle_id=None, arguments=None, environment=None):
"""
Args:
- bundle_id (str): the app bundle id
- arguments (list): ['-u', 'https://www.google.com/ncr']
- enviroment (dict): {"KEY": "VAL"}
WDA Return json like
{
"value": {
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"capabilities": {
"device": "iphone",
"browserName": "部落冲突",
"sdkVersion": "9.3.2",
"CFBundleIdentifier": "com.supercell.magic"
}
},
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"status": 0
}
To create a new session, send json data like
{
"desiredCapabilities": {
"bundleId": "your-bundle-id",
"app": "your-app-path"
"shouldUseCompactResponses": (bool),
"shouldUseTestManagerForVisibilityDetection": (bool),
"maxTypingFrequency": (integer),
"arguments": (list(str)),
"environment": (dict: str->str)
},
}
"""
if bundle_id is None:
sid = self.status()['sessionId']
if not sid:
raise RuntimeError("no session created ever")
http = self.http.new_client('session/'+sid)
return Session(http, sid)
if arguments and type(arguments) is not list:
raise TypeError('arguments must be a list')
if environment and type(environment) is not dict:
raise TypeError('environment must be a dict')
capabilities = {
'bundleId': bundle_id,
'arguments': arguments,
'environment': environment,
'shouldWaitForQuiescence': True,
}
# Remove empty value to prevent WDAError
for k in list(capabilities.keys()):
if capabilities[k] is None:
capabilities.pop(k)
data = json.dumps({
'desiredCapabilities': capabilities
})
res = self.http.post('session', data)
httpclient = self.http.new_client('session/'+res.sessionId)
return Session(httpclient, res.sessionId)
def screenshot(self, png_filename=None, format='raw'):
"""
Screenshot with PNG format
Args:
png_filename(string): optional, save file name
format(string): return format, pillow or raw(default)
Returns:
raw data or PIL.Image
Raises:
WDAError
"""
value = self.http.get('screenshot').value
raw_value = base64.b64decode(value)
png_header = b"\x89PNG\r\n\x1a\n"
if not raw_value.startswith(png_header) and png_filename:
raise WDAError(-1, "screenshot png format error")
if png_filename:
with open(png_filename, 'wb') as f:
f.write(raw_value)
if format == 'raw':
return raw_value
elif format == 'pillow':
from PIL import Image
buff = io.BytesIO(raw_value)
return Image.open(buff)
else:
raise ValueError("unknown format")
class Session(object):
def __init__(self, httpclient, session_id):
"""
Args:
- target(string): for example, http://127.0.0.1:8100
- session_id(string): wda session id
"""
self.http = httpclient
self._target = None
# self._sid = session_id
# Example session value
# "capabilities": {
# "CFBundleIdentifier": "com.netease.aabbcc",
# "browserName": "?????",
# "device": "iphone",
# "sdkVersion": "10.2"
# }
v = self.http.get('/').value
self.capabilities = v['capabilities']
self._sid = v['sessionId']
self.__scale = None
def __str__(self):
return 'wda.Session (id=%s)' % self._sid
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
@property
def id(self):
return self._sid
@property
def scale(self):
"""
UIKit scale factor
Refs:
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html
"""
if self.__scale:
return self.__scale
v = max(self.screenshot().size) / max(self.window_size())
self.__scale = round(v)
return self.__scale
@property
def bundle_id(self):
""" the session matched bundle id """
return self.capabilities.get('CFBundleIdentifier')
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callable):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None
def open_url(self, url):
"""
TODO: Never successed using before.
https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Commands/FBSessionCommands.m#L43
Args:
url (str): url
Raises:
WDAError
"""
return self.http.post('url', {'url': url})
def deactivate(self, duration):
"""Put app into background and than put it back
Args:
- duration (float): deactivate time, seconds
"""
return self.http.post('/wda/deactivateApp', dict(duration=duration))
def tap(self, x, y):
return self.http.post('/wda/tap/0', dict(x=x, y=y))
def _percent2pos(self, px, py):
w, h = self.window_size()
x = int(px*w) if isinstance(px, float) else px
y = int(py*h) if isinstance(py, float) else py
assert w >= x >= 0
assert h >= y >= 0
return (x, y)
def click(self, x, y):
"""
x, y can be float(percent) or int
"""
if isinstance(x, float) or isinstance(y, float):
x, y = self._percent2pos(x, y)
return self.tap(x, y)
def double_tap(self, x, y):
return self.http.post('/wda/doubleTap', dict(x=x, y=y))
def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
data = {'x': x, 'y': y, 'duration': duration}
return self.http.post('/wda/touchAndHold', data=data)
def screenshot(self):
"""
Take screenshot with session check
Returns:
PIL.Image
"""
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(buff)
def swipe(self, x1, y1, x2, y2, duration=0):
"""
Args:
duration (float): start coordinate press duration (seconds)
[[FBRoute POST:@"/wda/dragfromtoforduration"] respondWithTarget:self action:@selector(handleDragCoordinate:)],
"""
data = dict(fromX=x1, fromY=y1, toX=x2, toY=y2, duration=duration)
return self.http.post('/wda/dragfromtoforduration', data=data)
def swipe_left(self):
w, h = self.window_size()
return self.swipe(w, h/2, 0, h/2)
def swipe_right(self):
w, h = self.window_size()
return self.swipe(0, h/2, w, h/2)
def swipe_up(self):
w, h = self.window_size()
return self.swipe(w/2, h, w/2, 0)
def swipe_down(self):
w, h = self.window_size()
return self.swipe(w/2, 0, w/2, h)
@property
def orientation(self):
"""
Return string
One of <PORTRAIT | LANDSCAPE>
"""
return self.http.get('orientation').value
@orientation.setter
def orientation(self, value):
"""
Args:
- orientation(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT |
UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN
"""
return self.http.post('orientation', data={'orientation': value})
def window_size(self):
"""
Returns:
namedtuple: eg
Size(width=320, height=568)
"""
value = self.http.get('/window/size').value
w = roundint(value['width'])
h = roundint(value['height'])
return namedtuple('Size', ['width', 'height'])(w, h)
def send_keys(self, value):
"""
send keys, yet I know not, todo function
"""
if isinstance(value, six.string_types):
value = list(value)
return self.http.post('/wda/keys', data={'value': value})
def keyboard_dismiss(self):
"""
Not working for now
"""
raise RuntimeError("not pass tests, this method is not allowed to use")
self.http.post('/wda/keyboard/dismiss')
@property
def alert(self):
return Alert(self)
def close(self):
return self.http.delete('/')
def __call__(self, *args, **kwargs):
httpclient = self.http.new_client('')
return Selector(httpclient, self, *args, **kwargs)
class Alert(object):
def __init__(self, session):
self._s = session
self.http = session.http
@property
def exists(self):
try:
self.text
except WDAError as e:
if e.status != 27:
raise
return False
return True
@property
def text(self):
return self.http.get('/alert/text').value
def wait(self, timeout=20.0):
start_time = time.time()
while time.time() - start_time < timeout:
if self.exists:
return True
time.sleep(0.2)
return False
def accept(self):
return self.http.post('/alert/accept')
def dismiss(self):
return self.http.post('/alert/dismiss')
def buttons(self):
return self.http.get('/wda/alert/buttons').value
def click(self, button_name):
"""
Args:
- button_name: the name of the button
"""
# Actually, It has no difference POST to accept or dismiss
return self.http.post('/alert/accept', data={"name": button_name})
class Selector(object):
def __init__(self, httpclient, session,
predicate=None,
id=None,
className=None, type=None,
name=None, nameContains=None, nameMatches=None,
text=None, textContains=None, textMatches=None,
value=None, valueContains=None,
label=None, labelContains=None,
visible=None, enabled=None,
classChain=None,
xpath=None,
parent_class_chains=[],
timeout=10.0,
index=0):
'''
Args:
predicate (str): predicate string
id (str): raw identifier
className (str): attr of className
type (str): alias of className
name (str): attr for name
nameContains (str): attr of name contains
nameMatches (str): regex string
text (str): alias of name
textContains (str): alias of nameContains
textMatches (str): alias of nameMatches
value (str): attr of value, not used in most times
valueContains (str): attr of value contains
label (str): attr for label
labelContains (str): attr for label contains
visible (bool): is visible
enabled (bool): is enabled
classChain (str): string of ios chain query, eg: **/XCUIElementTypeOther[`value BEGINSWITH 'blabla'`]
xpath (str): xpath string, a little slow, but works fine
timeout (float): maxium wait element time, default 10.0s
index (int): index of founded elements
WDA use two key to find elements "using", "value"
Examples:
"using" can be on of
"partial link text", "link text"
"name", "id", "accessibility id"
"class name", "class chain", "xpath", "predicate string"
predicate string support many keys
UID,
accessibilityContainer,
accessible,
enabled,
frame,
label,
name,
rect,
type,
value,
visible,
wdAccessibilityContainer,
wdAccessible,
wdEnabled,
wdFrame,
wdLabel,
wdName,
wdRect,
wdType,
wdUID,
wdValue,
wdVisible
'''
self.http = httpclient
self.session = session
self.predicate = predicate
self.id = id
self.class_name = className or type
self.name = self._add_escape_character_for_quote_prime_character(name or text)
self.name_part = nameContains or textContains
self.name_regex = nameMatches or textMatches
self.value = value
self.value_part = valueContains
self.label = label
self.label_part = labelContains
self.enabled = enabled
self.visible = visible
self.index = index
self.xpath = self._fix_xcui_type(xpath)
self.class_chain = self._fix_xcui_type(classChain)
self.timeout = timeout
# some fixtures
if self.class_name and not self.class_name.startswith('XCUIElementType'):
self.class_name = 'XCUIElementType'+self.class_name
if self.name_regex:
if not self.name_regex.startswith('^') and not self.name_regex.startswith('.*'):
self.name_regex = '.*' + self.name_regex
if not self.name_regex.endswith('$') and not self.name_regex.endswith('.*'):
self.name_regex = self.name_regex + '.*'
self.parent_class_chains = parent_class_chains
def _fix_xcui_type(self, s):
if s is None:
return
re_element = '|'.join(xcui_element_types.ELEMENTS)
return re.sub(r'/('+re_element+')', '/XCUIElementType\g<1>', s)
def _add_escape_character_for_quote_prime_character(self, text):
"""
Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text
"""
if text is not None:
if "'" in text:
return text.replace("'","\\'")
elif '"' in text:
return text.replace('"','\\"')
else:
return text
else:
return text
def _wdasearch(self, using, value):
"""
Returns:
element_ids (list(string)): example ['id1', 'id2']
HTTP example response:
[
{"ELEMENT": "E2FF5B2A-DBDF-4E67-9179-91609480D80A"},
{"ELEMENT": "597B1A1E-70B9-4CBE-ACAD-40943B0A6034"}
]
"""
element_ids = []
for v in self.http.post('/elements', {'using': using, 'value': value}).value:
element_ids.append(v['ELEMENT'])
return element_ids
def _gen_class_chain(self):
# just return if aleady exists predicate
if self.predicate:
return '/XCUIElementTypeAny[`' + self.predicate + '`]'
qs = []
if self.name:
qs.append("name == '%s'" % self.name)
if self.name_part:
qs.append("name CONTAINS '%s'" % self.name_part)
if self.name_regex:
qs.append("name MATCHES '%s'" % self.name_regex.encode('unicode_escape'))
if self.label:
qs.append("label == '%s'" % self.label)
if self.label_part:
qs.append("label CONTAINS '%s'" % self.label_part)
if self.value:
qs.append("value == '%s'" % self.value)
if self.value_part:
qs.append("value CONTAINS ’%s'" % self.value_part)
if self.visible is not None:
qs.append("visible == %s" % 'true' if self.visible else 'false')
if self.enabled is not None:
qs.append("enabled == %s" % 'true' if self.enabled else 'false')
predicate = ' AND '.join(qs)
chain = '/' + (self.class_name or 'XCUIElementTypeAny')
if predicate:
chain = chain + '[`' + predicate + '`]'
if self.index:
chain = chain + '[%d]' % self.index
return chain
def find_element_ids(self):
elems = []
if self.id:
return self._wdasearch('id', self.id)
if self.predicate:
return self._wdasearch('predicate string', self.predicate)
if self.xpath:
return self._wdasearch('xpath', self.xpath)
if self.class_chain:
return self._wdasearch('class chain', self.class_chain)
chain = '**' + ''.join(self.parent_class_chains) + self._gen_class_chain()
if DEBUG:
print('CHAIN:', chain)
return self._wdasearch('class chain', chain)
def find_elements(self):
"""
Returns:
Element (list): all the elements
"""
es = []
for element_id in self.find_element_ids():
e = Element(self.http.new_client(''), element_id)
es.append(e)
return es
def count(self):
return len(self.find_element_ids())
def get(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None
"""
start_time = time.time()
if timeout is None:
timeout = self.timeout
while True:
elems = self.find_elements()
if len(elems) > 0:
return elems[0]
if start_time + timeout < time.time():
break
time.sleep(0.01)
# check alert again
if self.session.alert.exists and self.http.alert_callback:
self.http.alert_callback()
return self.get(timeout, raise_error)
if raise_error:
raise WDAElementNotFoundError("element not found")
def __getattr__(self, oper):
return getattr(self.get(), oper)
def set_timeout(self, s):
"""
Set element wait timeout
"""
self.timeout = s
return self
def __getitem__(self, index):
self.index = index
return self
def child(self, *args, **kwargs):
chain = self._gen_class_chain()
kwargs['parent_class_chains'] = self.parent_class_chains + [chain]
return Selector(self.http, self.session, *args, **kwargs)
@property
def exists(self):
return len(self.find_element_ids()) > self.index
def click_exists(self, timeout=0):
"""
Wait element and perform click
Args:
timeout (float): timeout for wait
Returns:
bool: if successfully clicked
"""
e = self.get(timeout=timeout, raise_error=False)
if e is None:
return False
e.click()
return True
def wait(self, timeout=None, raise_error=True):
""" alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError
"""
return self.get(timeout=timeout, raise_error=raise_error)
def wait_gone(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): default timeout
raise_error (bool): return bool or raise error
Returns:
bool: works when raise_error is False
Raises:
WDAElementNotDisappearError
"""
start_time = time.time()
if timeout is None or timeout <= 0:
timeout = self.timeout
while start_time + timeout > time.time():
if not self.exists:
return True
if not raise_error:
return False
raise WDAElementNotDisappearError("element not gone")
# todo
# pinch
# touchAndHold
# dragfromtoforduration
# twoFingerTap
# todo
# handleGetIsAccessibilityContainer
# [[FBRoute GET:@"/wda/element/:uuid/accessibilityContainer"] respondWithTarget:self action:@selector(handleGetIsAccessibilityContainer:)],
class Element(object):
def __init__(self, httpclient, id):
"""
base_url eg: http://localhost:8100/session/$SESSION_ID
"""
self.http = httpclient
self._id = id
def __repr__(self):
return '<wda.Element(id="{}")>'.format(self.id)
def _req(self, method, url, data=None):
return self.http.fetch(method, '/element/'+self.id+url, data)
def _wda_req(self, method, url, data=None):
return self.http.fetch(method, '/wda/element/'+self.id+url, data)
def _prop(self, key):
return self._req('get', '/'+key.lstrip('/')).value
def _wda_prop(self, key):
ret = self._request('GET', 'wda/element/%s/%s' %(self._id, key)).value
return ret
@property
def id(self):
return self._id
@property
def label(self):
return self._prop('attribute/label')
@property
def className(self):
return self._prop('attribute/type')
@property
def text(self):
return self._prop('text')
@property
def name(self):
return self._prop('name')
@property
def displayed(self):
return self._prop("displayed")
@property
def enabled(self):
return self._prop('enabled')
@property
def accessible(self):
return self._wda_prop("accessible")
@property
def accessibility_container(self):
return self._wda_prop('accessibilityContainer')
@property
def value(self):
return self._prop('attribute/value')
@property
def enabled(self):
return self._prop('enabled')
@property
def visible(self):
return self._prop('attribute/visible')
@property
def bounds(self):
value = self._prop('rect')
x, y = value['x'], value['y']
w, h = value['width'], value['height']
return Rect(x, y, w, h)
# operations
def tap(self):
return self._req('post', '/click')
def click(self):
""" Alias of tap """
return self.tap()
def tap_hold(self, duration=1.0):
"""
Tap and hold for a moment
Args:
duration (float): seconds of hold time
[[FBRoute POST:@"/wda/element/:uuid/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHold:)],
"""
return self._wda_req('post', '/touchAndHold', {'duration': duration})
def scroll(self, direction='visible', distance=1.0):
"""
Args:
direction (str): one of "visible", "up", "down", "left", "right"
distance (float): swipe distance, only works when direction is not "visible"
Raises:
ValueError
distance=1.0 means, element (width or height) multiply 1.0
"""
if direction == 'visible':
self._wda_req('post', '/scroll', {'toVisible': True})
elif direction in ['up', 'down', 'left', 'right']:
self._wda_req('post', '/scroll', {'direction': direction, 'distance': distance})
else:
raise ValueError("Invalid direction")
return self
def pinch(self, scale, velocity):
"""
Args:
scale (float): scale must > 0
velocity (float): velocity must be less than zero when scale is less than 1
Example:
pinchIn -> scale:0.5, velocity: -1
pinchOut -> scale:2.0, velocity: 1
"""
data = {'scale': scale, 'velocity': velocity}
return self._wda_req('post', '/pinch', data)
def set_text(self, value):
return self._req('post', '/value', {'value': value})
def clear_text(self):
return self._req('post', '/clear')
# def child(self, **kwargs):
# return Selector(self.__base_url, self._id, **kwargs)
# todo lot of other operations
# tap_hold
|
openatx/facebook-wda | wda/__init__.py | httpdo | python | def httpdo(url, method='GET', data=None):
start = time.time()
if isinstance(data, dict):
data = json.dumps(data)
if DEBUG:
print("Shell: curl -X {method} -d '{data}' '{url}'".format(method=method.upper(), data=data or '', url=url))
try:
response = requests.request(method, url, data=data, timeout=HTTP_TIMEOUT)
except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout):
# retry again
# print('retry to connect, error: {}'.format(e))
time.sleep(1.0)
response = requests.request(method, url, data=data, timeout=HTTP_TIMEOUT)
if DEBUG:
ms = (time.time() - start) * 1000
print('Return ({:.0f}ms): {}'.format(ms, response.text))
try:
retjson = response.json()
except ValueError as e:
# show why json.loads error
raise ValueError(e, response.text)
r = convert(retjson)
if r.status != 0:
raise WDAError(r.status, r.value)
return r | Do HTTP Request | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L60-L91 | [
"def convert(dictionary):\n \"\"\"\n Convert dict to namedtuple\n \"\"\"\n return namedtuple('GenericDict', list(dictionary.keys()))(**dictionary)\n"
] | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
import base64
import copy
import functools
import json
import os
import re
import io
import time
from collections import namedtuple
import requests
import six
from . import xcui_element_types
if six.PY3:
from urllib.parse import urljoin as _urljoin
from functools import reduce
else:
from urlparse import urljoin as _urljoin
DEBUG = False
HTTP_TIMEOUT = 60.0 # unit second
LANDSCAPE = 'LANDSCAPE'
PORTRAIT = 'PORTRAIT'
LANDSCAPE_RIGHT = 'UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT'
PORTRAIT_UPSIDEDOWN = 'UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN'
alert_callback = None
def convert(dictionary):
"""
Convert dict to namedtuple
"""
return namedtuple('GenericDict', list(dictionary.keys()))(**dictionary)
def urljoin(*urls):
"""
The default urlparse.urljoin behavior look strange
Standard urlparse.urljoin('http://a.com/foo', '/bar')
Expect: http://a.com/foo/bar
Actually: http://a.com/bar
This function fix that.
"""
return reduce(_urljoin, [u.strip('/')+'/' for u in urls if u.strip('/')], '').rstrip('/')
def roundint(i):
return int(round(i, 0))
def httpdo(url, method='GET', data=None):
"""
Do HTTP Request
"""
start = time.time()
if isinstance(data, dict):
data = json.dumps(data)
if DEBUG:
print("Shell: curl -X {method} -d '{data}' '{url}'".format(method=method.upper(), data=data or '', url=url))
try:
response = requests.request(method, url, data=data, timeout=HTTP_TIMEOUT)
except (requests.exceptions.ConnectionError, requests.exceptions.ReadTimeout):
# retry again
# print('retry to connect, error: {}'.format(e))
time.sleep(1.0)
response = requests.request(method, url, data=data, timeout=HTTP_TIMEOUT)
if DEBUG:
ms = (time.time() - start) * 1000
print('Return ({:.0f}ms): {}'.format(ms, response.text))
try:
retjson = response.json()
except ValueError as e:
# show why json.loads error
raise ValueError(e, response.text)
r = convert(retjson)
if r.status != 0:
raise WDAError(r.status, r.value)
return r
class HTTPClient(object):
def __init__(self, address, alert_callback=None):
"""
Args:
address (string): url address eg: http://localhost:8100
alert_callback (func): function to call when alert popup
"""
self.address = address
self.alert_callback = alert_callback
def new_client(self, path):
return HTTPClient(self.address.rstrip('/') + '/' + path.lstrip('/'), self.alert_callback)
def fetch(self, method, url, data=None):
return self._fetch_no_alert(method, url, data)
# return httpdo(urljoin(self.address, url), method, data)
def _fetch_no_alert(self, method, url, data=None, depth=0):
target_url = urljoin(self.address, url)
try:
return httpdo(target_url, method, data)
except WDAError as err:
if depth >= 10:
raise
if err.status != 26:
raise
if not callable(self.alert_callback):
raise
self.alert_callback()
return self._fetch_no_alert(method, url, data, depth=depth+1)
def __getattr__(self, key):
""" Handle GET,POST,DELETE, etc ... """
return functools.partial(self.fetch, key)
class WDAError(Exception):
def __init__(self, status, value):
self.status = status
self.value = value
def __str__(self):
return 'WDAError(status=%d, value=%s)' % (self.status, self.value)
class WDAElementNotFoundError(Exception):
pass
class WDAElementNotDisappearError(Exception):
pass
class Rect(object):
def __init__(self, x, y, width, height):
self.x = x
self.y = y
self.width = width
self.height = height
def __str__(self):
return 'Rect(x={x}, y={y}, width={w}, height={h})'.format(
x=self.x, y=self.y, w=self.width, h=self.height)
def __repr__(self):
return str(self)
@property
def center(self):
return namedtuple('Point', ['x', 'y'])(self.x+self.width/2, self.y+self.height/2)
@property
def origin(self):
return namedtuple('Point', ['x', 'y'])(self.x, self.y)
@property
def left(self):
return self.x
@property
def top(self):
return self.y
@property
def right(self):
return self.x+self.width
@property
def bottom(self):
return self.y+self.height
class Client(object):
def __init__(self, url=None):
"""
Args:
target (string): the device url
If target is None, device url will set to env-var "DEVICE_URL" if defined else set to "http://localhost:8100"
"""
if url is None:
url = os.environ.get('DEVICE_URL', 'http://localhost:8100')
self.http = HTTPClient(url)
def wait_ready(self, timeout=120):
"""
wait until WDA back to normal
Returns:
bool (if wda works)
"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
self.status()
return True
except:
time.sleep(2)
return False
def status(self):
res = self.http.get('status')
sid = res.sessionId
res.value['sessionId'] = sid
return res.value
def home(self):
"""Press home button"""
return self.http.post('/wda/homescreen')
def healthcheck(self):
"""Hit healthcheck"""
return self.http.get('/wda/healthcheck')
def source(self, format='xml', accessible=False):
"""
Args:
format (str): only 'xml' and 'json' source types are supported
accessible (bool): when set to true, format is always 'json'
"""
if accessible:
return self.http.get('/wda/accessibleSource').value
return self.http.get('source?format='+format).value
def session(self, bundle_id=None, arguments=None, environment=None):
"""
Args:
- bundle_id (str): the app bundle id
- arguments (list): ['-u', 'https://www.google.com/ncr']
- enviroment (dict): {"KEY": "VAL"}
WDA Return json like
{
"value": {
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"capabilities": {
"device": "iphone",
"browserName": "部落冲突",
"sdkVersion": "9.3.2",
"CFBundleIdentifier": "com.supercell.magic"
}
},
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"status": 0
}
To create a new session, send json data like
{
"desiredCapabilities": {
"bundleId": "your-bundle-id",
"app": "your-app-path"
"shouldUseCompactResponses": (bool),
"shouldUseTestManagerForVisibilityDetection": (bool),
"maxTypingFrequency": (integer),
"arguments": (list(str)),
"environment": (dict: str->str)
},
}
"""
if bundle_id is None:
sid = self.status()['sessionId']
if not sid:
raise RuntimeError("no session created ever")
http = self.http.new_client('session/'+sid)
return Session(http, sid)
if arguments and type(arguments) is not list:
raise TypeError('arguments must be a list')
if environment and type(environment) is not dict:
raise TypeError('environment must be a dict')
capabilities = {
'bundleId': bundle_id,
'arguments': arguments,
'environment': environment,
'shouldWaitForQuiescence': True,
}
# Remove empty value to prevent WDAError
for k in list(capabilities.keys()):
if capabilities[k] is None:
capabilities.pop(k)
data = json.dumps({
'desiredCapabilities': capabilities
})
res = self.http.post('session', data)
httpclient = self.http.new_client('session/'+res.sessionId)
return Session(httpclient, res.sessionId)
def screenshot(self, png_filename=None, format='raw'):
"""
Screenshot with PNG format
Args:
png_filename(string): optional, save file name
format(string): return format, pillow or raw(default)
Returns:
raw data or PIL.Image
Raises:
WDAError
"""
value = self.http.get('screenshot').value
raw_value = base64.b64decode(value)
png_header = b"\x89PNG\r\n\x1a\n"
if not raw_value.startswith(png_header) and png_filename:
raise WDAError(-1, "screenshot png format error")
if png_filename:
with open(png_filename, 'wb') as f:
f.write(raw_value)
if format == 'raw':
return raw_value
elif format == 'pillow':
from PIL import Image
buff = io.BytesIO(raw_value)
return Image.open(buff)
else:
raise ValueError("unknown format")
class Session(object):
def __init__(self, httpclient, session_id):
"""
Args:
- target(string): for example, http://127.0.0.1:8100
- session_id(string): wda session id
"""
self.http = httpclient
self._target = None
# self._sid = session_id
# Example session value
# "capabilities": {
# "CFBundleIdentifier": "com.netease.aabbcc",
# "browserName": "?????",
# "device": "iphone",
# "sdkVersion": "10.2"
# }
v = self.http.get('/').value
self.capabilities = v['capabilities']
self._sid = v['sessionId']
self.__scale = None
def __str__(self):
return 'wda.Session (id=%s)' % self._sid
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
@property
def id(self):
return self._sid
@property
def scale(self):
"""
UIKit scale factor
Refs:
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html
"""
if self.__scale:
return self.__scale
v = max(self.screenshot().size) / max(self.window_size())
self.__scale = round(v)
return self.__scale
@property
def bundle_id(self):
""" the session matched bundle id """
return self.capabilities.get('CFBundleIdentifier')
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callable):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None
def open_url(self, url):
"""
TODO: Never successed using before.
https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Commands/FBSessionCommands.m#L43
Args:
url (str): url
Raises:
WDAError
"""
return self.http.post('url', {'url': url})
def deactivate(self, duration):
"""Put app into background and than put it back
Args:
- duration (float): deactivate time, seconds
"""
return self.http.post('/wda/deactivateApp', dict(duration=duration))
def tap(self, x, y):
return self.http.post('/wda/tap/0', dict(x=x, y=y))
def _percent2pos(self, px, py):
w, h = self.window_size()
x = int(px*w) if isinstance(px, float) else px
y = int(py*h) if isinstance(py, float) else py
assert w >= x >= 0
assert h >= y >= 0
return (x, y)
def click(self, x, y):
"""
x, y can be float(percent) or int
"""
if isinstance(x, float) or isinstance(y, float):
x, y = self._percent2pos(x, y)
return self.tap(x, y)
def double_tap(self, x, y):
return self.http.post('/wda/doubleTap', dict(x=x, y=y))
def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
data = {'x': x, 'y': y, 'duration': duration}
return self.http.post('/wda/touchAndHold', data=data)
def screenshot(self):
"""
Take screenshot with session check
Returns:
PIL.Image
"""
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(buff)
def swipe(self, x1, y1, x2, y2, duration=0):
"""
Args:
duration (float): start coordinate press duration (seconds)
[[FBRoute POST:@"/wda/dragfromtoforduration"] respondWithTarget:self action:@selector(handleDragCoordinate:)],
"""
data = dict(fromX=x1, fromY=y1, toX=x2, toY=y2, duration=duration)
return self.http.post('/wda/dragfromtoforduration', data=data)
def swipe_left(self):
w, h = self.window_size()
return self.swipe(w, h/2, 0, h/2)
def swipe_right(self):
w, h = self.window_size()
return self.swipe(0, h/2, w, h/2)
def swipe_up(self):
w, h = self.window_size()
return self.swipe(w/2, h, w/2, 0)
def swipe_down(self):
w, h = self.window_size()
return self.swipe(w/2, 0, w/2, h)
@property
def orientation(self):
"""
Return string
One of <PORTRAIT | LANDSCAPE>
"""
return self.http.get('orientation').value
@orientation.setter
def orientation(self, value):
"""
Args:
- orientation(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT |
UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN
"""
return self.http.post('orientation', data={'orientation': value})
def window_size(self):
"""
Returns:
namedtuple: eg
Size(width=320, height=568)
"""
value = self.http.get('/window/size').value
w = roundint(value['width'])
h = roundint(value['height'])
return namedtuple('Size', ['width', 'height'])(w, h)
def send_keys(self, value):
"""
send keys, yet I know not, todo function
"""
if isinstance(value, six.string_types):
value = list(value)
return self.http.post('/wda/keys', data={'value': value})
def keyboard_dismiss(self):
"""
Not working for now
"""
raise RuntimeError("not pass tests, this method is not allowed to use")
self.http.post('/wda/keyboard/dismiss')
@property
def alert(self):
return Alert(self)
def close(self):
return self.http.delete('/')
def __call__(self, *args, **kwargs):
httpclient = self.http.new_client('')
return Selector(httpclient, self, *args, **kwargs)
class Alert(object):
def __init__(self, session):
self._s = session
self.http = session.http
@property
def exists(self):
try:
self.text
except WDAError as e:
if e.status != 27:
raise
return False
return True
@property
def text(self):
return self.http.get('/alert/text').value
def wait(self, timeout=20.0):
start_time = time.time()
while time.time() - start_time < timeout:
if self.exists:
return True
time.sleep(0.2)
return False
def accept(self):
return self.http.post('/alert/accept')
def dismiss(self):
return self.http.post('/alert/dismiss')
def buttons(self):
return self.http.get('/wda/alert/buttons').value
def click(self, button_name):
"""
Args:
- button_name: the name of the button
"""
# Actually, It has no difference POST to accept or dismiss
return self.http.post('/alert/accept', data={"name": button_name})
class Selector(object):
def __init__(self, httpclient, session,
predicate=None,
id=None,
className=None, type=None,
name=None, nameContains=None, nameMatches=None,
text=None, textContains=None, textMatches=None,
value=None, valueContains=None,
label=None, labelContains=None,
visible=None, enabled=None,
classChain=None,
xpath=None,
parent_class_chains=[],
timeout=10.0,
index=0):
'''
Args:
predicate (str): predicate string
id (str): raw identifier
className (str): attr of className
type (str): alias of className
name (str): attr for name
nameContains (str): attr of name contains
nameMatches (str): regex string
text (str): alias of name
textContains (str): alias of nameContains
textMatches (str): alias of nameMatches
value (str): attr of value, not used in most times
valueContains (str): attr of value contains
label (str): attr for label
labelContains (str): attr for label contains
visible (bool): is visible
enabled (bool): is enabled
classChain (str): string of ios chain query, eg: **/XCUIElementTypeOther[`value BEGINSWITH 'blabla'`]
xpath (str): xpath string, a little slow, but works fine
timeout (float): maxium wait element time, default 10.0s
index (int): index of founded elements
WDA use two key to find elements "using", "value"
Examples:
"using" can be on of
"partial link text", "link text"
"name", "id", "accessibility id"
"class name", "class chain", "xpath", "predicate string"
predicate string support many keys
UID,
accessibilityContainer,
accessible,
enabled,
frame,
label,
name,
rect,
type,
value,
visible,
wdAccessibilityContainer,
wdAccessible,
wdEnabled,
wdFrame,
wdLabel,
wdName,
wdRect,
wdType,
wdUID,
wdValue,
wdVisible
'''
self.http = httpclient
self.session = session
self.predicate = predicate
self.id = id
self.class_name = className or type
self.name = self._add_escape_character_for_quote_prime_character(name or text)
self.name_part = nameContains or textContains
self.name_regex = nameMatches or textMatches
self.value = value
self.value_part = valueContains
self.label = label
self.label_part = labelContains
self.enabled = enabled
self.visible = visible
self.index = index
self.xpath = self._fix_xcui_type(xpath)
self.class_chain = self._fix_xcui_type(classChain)
self.timeout = timeout
# some fixtures
if self.class_name and not self.class_name.startswith('XCUIElementType'):
self.class_name = 'XCUIElementType'+self.class_name
if self.name_regex:
if not self.name_regex.startswith('^') and not self.name_regex.startswith('.*'):
self.name_regex = '.*' + self.name_regex
if not self.name_regex.endswith('$') and not self.name_regex.endswith('.*'):
self.name_regex = self.name_regex + '.*'
self.parent_class_chains = parent_class_chains
def _fix_xcui_type(self, s):
if s is None:
return
re_element = '|'.join(xcui_element_types.ELEMENTS)
return re.sub(r'/('+re_element+')', '/XCUIElementType\g<1>', s)
def _add_escape_character_for_quote_prime_character(self, text):
"""
Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text
"""
if text is not None:
if "'" in text:
return text.replace("'","\\'")
elif '"' in text:
return text.replace('"','\\"')
else:
return text
else:
return text
def _wdasearch(self, using, value):
"""
Returns:
element_ids (list(string)): example ['id1', 'id2']
HTTP example response:
[
{"ELEMENT": "E2FF5B2A-DBDF-4E67-9179-91609480D80A"},
{"ELEMENT": "597B1A1E-70B9-4CBE-ACAD-40943B0A6034"}
]
"""
element_ids = []
for v in self.http.post('/elements', {'using': using, 'value': value}).value:
element_ids.append(v['ELEMENT'])
return element_ids
def _gen_class_chain(self):
# just return if aleady exists predicate
if self.predicate:
return '/XCUIElementTypeAny[`' + self.predicate + '`]'
qs = []
if self.name:
qs.append("name == '%s'" % self.name)
if self.name_part:
qs.append("name CONTAINS '%s'" % self.name_part)
if self.name_regex:
qs.append("name MATCHES '%s'" % self.name_regex.encode('unicode_escape'))
if self.label:
qs.append("label == '%s'" % self.label)
if self.label_part:
qs.append("label CONTAINS '%s'" % self.label_part)
if self.value:
qs.append("value == '%s'" % self.value)
if self.value_part:
qs.append("value CONTAINS ’%s'" % self.value_part)
if self.visible is not None:
qs.append("visible == %s" % 'true' if self.visible else 'false')
if self.enabled is not None:
qs.append("enabled == %s" % 'true' if self.enabled else 'false')
predicate = ' AND '.join(qs)
chain = '/' + (self.class_name or 'XCUIElementTypeAny')
if predicate:
chain = chain + '[`' + predicate + '`]'
if self.index:
chain = chain + '[%d]' % self.index
return chain
def find_element_ids(self):
elems = []
if self.id:
return self._wdasearch('id', self.id)
if self.predicate:
return self._wdasearch('predicate string', self.predicate)
if self.xpath:
return self._wdasearch('xpath', self.xpath)
if self.class_chain:
return self._wdasearch('class chain', self.class_chain)
chain = '**' + ''.join(self.parent_class_chains) + self._gen_class_chain()
if DEBUG:
print('CHAIN:', chain)
return self._wdasearch('class chain', chain)
def find_elements(self):
"""
Returns:
Element (list): all the elements
"""
es = []
for element_id in self.find_element_ids():
e = Element(self.http.new_client(''), element_id)
es.append(e)
return es
def count(self):
return len(self.find_element_ids())
def get(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None
"""
start_time = time.time()
if timeout is None:
timeout = self.timeout
while True:
elems = self.find_elements()
if len(elems) > 0:
return elems[0]
if start_time + timeout < time.time():
break
time.sleep(0.01)
# check alert again
if self.session.alert.exists and self.http.alert_callback:
self.http.alert_callback()
return self.get(timeout, raise_error)
if raise_error:
raise WDAElementNotFoundError("element not found")
def __getattr__(self, oper):
return getattr(self.get(), oper)
def set_timeout(self, s):
"""
Set element wait timeout
"""
self.timeout = s
return self
def __getitem__(self, index):
self.index = index
return self
def child(self, *args, **kwargs):
chain = self._gen_class_chain()
kwargs['parent_class_chains'] = self.parent_class_chains + [chain]
return Selector(self.http, self.session, *args, **kwargs)
@property
def exists(self):
return len(self.find_element_ids()) > self.index
def click_exists(self, timeout=0):
"""
Wait element and perform click
Args:
timeout (float): timeout for wait
Returns:
bool: if successfully clicked
"""
e = self.get(timeout=timeout, raise_error=False)
if e is None:
return False
e.click()
return True
def wait(self, timeout=None, raise_error=True):
""" alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError
"""
return self.get(timeout=timeout, raise_error=raise_error)
def wait_gone(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): default timeout
raise_error (bool): return bool or raise error
Returns:
bool: works when raise_error is False
Raises:
WDAElementNotDisappearError
"""
start_time = time.time()
if timeout is None or timeout <= 0:
timeout = self.timeout
while start_time + timeout > time.time():
if not self.exists:
return True
if not raise_error:
return False
raise WDAElementNotDisappearError("element not gone")
# todo
# pinch
# touchAndHold
# dragfromtoforduration
# twoFingerTap
# todo
# handleGetIsAccessibilityContainer
# [[FBRoute GET:@"/wda/element/:uuid/accessibilityContainer"] respondWithTarget:self action:@selector(handleGetIsAccessibilityContainer:)],
class Element(object):
def __init__(self, httpclient, id):
"""
base_url eg: http://localhost:8100/session/$SESSION_ID
"""
self.http = httpclient
self._id = id
def __repr__(self):
return '<wda.Element(id="{}")>'.format(self.id)
def _req(self, method, url, data=None):
return self.http.fetch(method, '/element/'+self.id+url, data)
def _wda_req(self, method, url, data=None):
return self.http.fetch(method, '/wda/element/'+self.id+url, data)
def _prop(self, key):
return self._req('get', '/'+key.lstrip('/')).value
def _wda_prop(self, key):
ret = self._request('GET', 'wda/element/%s/%s' %(self._id, key)).value
return ret
@property
def id(self):
return self._id
@property
def label(self):
return self._prop('attribute/label')
@property
def className(self):
return self._prop('attribute/type')
@property
def text(self):
return self._prop('text')
@property
def name(self):
return self._prop('name')
@property
def displayed(self):
return self._prop("displayed")
@property
def enabled(self):
return self._prop('enabled')
@property
def accessible(self):
return self._wda_prop("accessible")
@property
def accessibility_container(self):
return self._wda_prop('accessibilityContainer')
@property
def value(self):
return self._prop('attribute/value')
@property
def enabled(self):
return self._prop('enabled')
@property
def visible(self):
return self._prop('attribute/visible')
@property
def bounds(self):
value = self._prop('rect')
x, y = value['x'], value['y']
w, h = value['width'], value['height']
return Rect(x, y, w, h)
# operations
def tap(self):
return self._req('post', '/click')
def click(self):
""" Alias of tap """
return self.tap()
def tap_hold(self, duration=1.0):
"""
Tap and hold for a moment
Args:
duration (float): seconds of hold time
[[FBRoute POST:@"/wda/element/:uuid/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHold:)],
"""
return self._wda_req('post', '/touchAndHold', {'duration': duration})
def scroll(self, direction='visible', distance=1.0):
"""
Args:
direction (str): one of "visible", "up", "down", "left", "right"
distance (float): swipe distance, only works when direction is not "visible"
Raises:
ValueError
distance=1.0 means, element (width or height) multiply 1.0
"""
if direction == 'visible':
self._wda_req('post', '/scroll', {'toVisible': True})
elif direction in ['up', 'down', 'left', 'right']:
self._wda_req('post', '/scroll', {'direction': direction, 'distance': distance})
else:
raise ValueError("Invalid direction")
return self
def pinch(self, scale, velocity):
"""
Args:
scale (float): scale must > 0
velocity (float): velocity must be less than zero when scale is less than 1
Example:
pinchIn -> scale:0.5, velocity: -1
pinchOut -> scale:2.0, velocity: 1
"""
data = {'scale': scale, 'velocity': velocity}
return self._wda_req('post', '/pinch', data)
def set_text(self, value):
return self._req('post', '/value', {'value': value})
def clear_text(self):
return self._req('post', '/clear')
# def child(self, **kwargs):
# return Selector(self.__base_url, self._id, **kwargs)
# todo lot of other operations
# tap_hold
|
openatx/facebook-wda | wda/__init__.py | Client.wait_ready | python | def wait_ready(self, timeout=120):
deadline = time.time() + timeout
while time.time() < deadline:
try:
self.status()
return True
except:
time.sleep(2)
return False | wait until WDA back to normal
Returns:
bool (if wda works) | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L197-L211 | [
"def status(self):\n res = self.http.get('status')\n sid = res.sessionId\n res.value['sessionId'] = sid\n return res.value\n"
] | class Client(object):
def __init__(self, url=None):
"""
Args:
target (string): the device url
If target is None, device url will set to env-var "DEVICE_URL" if defined else set to "http://localhost:8100"
"""
if url is None:
url = os.environ.get('DEVICE_URL', 'http://localhost:8100')
self.http = HTTPClient(url)
def status(self):
res = self.http.get('status')
sid = res.sessionId
res.value['sessionId'] = sid
return res.value
def home(self):
"""Press home button"""
return self.http.post('/wda/homescreen')
def healthcheck(self):
"""Hit healthcheck"""
return self.http.get('/wda/healthcheck')
def source(self, format='xml', accessible=False):
"""
Args:
format (str): only 'xml' and 'json' source types are supported
accessible (bool): when set to true, format is always 'json'
"""
if accessible:
return self.http.get('/wda/accessibleSource').value
return self.http.get('source?format='+format).value
def session(self, bundle_id=None, arguments=None, environment=None):
"""
Args:
- bundle_id (str): the app bundle id
- arguments (list): ['-u', 'https://www.google.com/ncr']
- enviroment (dict): {"KEY": "VAL"}
WDA Return json like
{
"value": {
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"capabilities": {
"device": "iphone",
"browserName": "部落冲突",
"sdkVersion": "9.3.2",
"CFBundleIdentifier": "com.supercell.magic"
}
},
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"status": 0
}
To create a new session, send json data like
{
"desiredCapabilities": {
"bundleId": "your-bundle-id",
"app": "your-app-path"
"shouldUseCompactResponses": (bool),
"shouldUseTestManagerForVisibilityDetection": (bool),
"maxTypingFrequency": (integer),
"arguments": (list(str)),
"environment": (dict: str->str)
},
}
"""
if bundle_id is None:
sid = self.status()['sessionId']
if not sid:
raise RuntimeError("no session created ever")
http = self.http.new_client('session/'+sid)
return Session(http, sid)
if arguments and type(arguments) is not list:
raise TypeError('arguments must be a list')
if environment and type(environment) is not dict:
raise TypeError('environment must be a dict')
capabilities = {
'bundleId': bundle_id,
'arguments': arguments,
'environment': environment,
'shouldWaitForQuiescence': True,
}
# Remove empty value to prevent WDAError
for k in list(capabilities.keys()):
if capabilities[k] is None:
capabilities.pop(k)
data = json.dumps({
'desiredCapabilities': capabilities
})
res = self.http.post('session', data)
httpclient = self.http.new_client('session/'+res.sessionId)
return Session(httpclient, res.sessionId)
def screenshot(self, png_filename=None, format='raw'):
"""
Screenshot with PNG format
Args:
png_filename(string): optional, save file name
format(string): return format, pillow or raw(default)
Returns:
raw data or PIL.Image
Raises:
WDAError
"""
value = self.http.get('screenshot').value
raw_value = base64.b64decode(value)
png_header = b"\x89PNG\r\n\x1a\n"
if not raw_value.startswith(png_header) and png_filename:
raise WDAError(-1, "screenshot png format error")
if png_filename:
with open(png_filename, 'wb') as f:
f.write(raw_value)
if format == 'raw':
return raw_value
elif format == 'pillow':
from PIL import Image
buff = io.BytesIO(raw_value)
return Image.open(buff)
else:
raise ValueError("unknown format")
|
openatx/facebook-wda | wda/__init__.py | Client.source | python | def source(self, format='xml', accessible=False):
if accessible:
return self.http.get('/wda/accessibleSource').value
return self.http.get('source?format='+format).value | Args:
format (str): only 'xml' and 'json' source types are supported
accessible (bool): when set to true, format is always 'json' | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L229-L237 | null | class Client(object):
def __init__(self, url=None):
"""
Args:
target (string): the device url
If target is None, device url will set to env-var "DEVICE_URL" if defined else set to "http://localhost:8100"
"""
if url is None:
url = os.environ.get('DEVICE_URL', 'http://localhost:8100')
self.http = HTTPClient(url)
def wait_ready(self, timeout=120):
"""
wait until WDA back to normal
Returns:
bool (if wda works)
"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
self.status()
return True
except:
time.sleep(2)
return False
def status(self):
res = self.http.get('status')
sid = res.sessionId
res.value['sessionId'] = sid
return res.value
def home(self):
"""Press home button"""
return self.http.post('/wda/homescreen')
def healthcheck(self):
"""Hit healthcheck"""
return self.http.get('/wda/healthcheck')
def session(self, bundle_id=None, arguments=None, environment=None):
"""
Args:
- bundle_id (str): the app bundle id
- arguments (list): ['-u', 'https://www.google.com/ncr']
- enviroment (dict): {"KEY": "VAL"}
WDA Return json like
{
"value": {
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"capabilities": {
"device": "iphone",
"browserName": "部落冲突",
"sdkVersion": "9.3.2",
"CFBundleIdentifier": "com.supercell.magic"
}
},
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"status": 0
}
To create a new session, send json data like
{
"desiredCapabilities": {
"bundleId": "your-bundle-id",
"app": "your-app-path"
"shouldUseCompactResponses": (bool),
"shouldUseTestManagerForVisibilityDetection": (bool),
"maxTypingFrequency": (integer),
"arguments": (list(str)),
"environment": (dict: str->str)
},
}
"""
if bundle_id is None:
sid = self.status()['sessionId']
if not sid:
raise RuntimeError("no session created ever")
http = self.http.new_client('session/'+sid)
return Session(http, sid)
if arguments and type(arguments) is not list:
raise TypeError('arguments must be a list')
if environment and type(environment) is not dict:
raise TypeError('environment must be a dict')
capabilities = {
'bundleId': bundle_id,
'arguments': arguments,
'environment': environment,
'shouldWaitForQuiescence': True,
}
# Remove empty value to prevent WDAError
for k in list(capabilities.keys()):
if capabilities[k] is None:
capabilities.pop(k)
data = json.dumps({
'desiredCapabilities': capabilities
})
res = self.http.post('session', data)
httpclient = self.http.new_client('session/'+res.sessionId)
return Session(httpclient, res.sessionId)
def screenshot(self, png_filename=None, format='raw'):
"""
Screenshot with PNG format
Args:
png_filename(string): optional, save file name
format(string): return format, pillow or raw(default)
Returns:
raw data or PIL.Image
Raises:
WDAError
"""
value = self.http.get('screenshot').value
raw_value = base64.b64decode(value)
png_header = b"\x89PNG\r\n\x1a\n"
if not raw_value.startswith(png_header) and png_filename:
raise WDAError(-1, "screenshot png format error")
if png_filename:
with open(png_filename, 'wb') as f:
f.write(raw_value)
if format == 'raw':
return raw_value
elif format == 'pillow':
from PIL import Image
buff = io.BytesIO(raw_value)
return Image.open(buff)
else:
raise ValueError("unknown format")
|
openatx/facebook-wda | wda/__init__.py | Client.session | python | def session(self, bundle_id=None, arguments=None, environment=None):
if bundle_id is None:
sid = self.status()['sessionId']
if not sid:
raise RuntimeError("no session created ever")
http = self.http.new_client('session/'+sid)
return Session(http, sid)
if arguments and type(arguments) is not list:
raise TypeError('arguments must be a list')
if environment and type(environment) is not dict:
raise TypeError('environment must be a dict')
capabilities = {
'bundleId': bundle_id,
'arguments': arguments,
'environment': environment,
'shouldWaitForQuiescence': True,
}
# Remove empty value to prevent WDAError
for k in list(capabilities.keys()):
if capabilities[k] is None:
capabilities.pop(k)
data = json.dumps({
'desiredCapabilities': capabilities
})
res = self.http.post('session', data)
httpclient = self.http.new_client('session/'+res.sessionId)
return Session(httpclient, res.sessionId) | Args:
- bundle_id (str): the app bundle id
- arguments (list): ['-u', 'https://www.google.com/ncr']
- enviroment (dict): {"KEY": "VAL"}
WDA Return json like
{
"value": {
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"capabilities": {
"device": "iphone",
"browserName": "部落冲突",
"sdkVersion": "9.3.2",
"CFBundleIdentifier": "com.supercell.magic"
}
},
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"status": 0
}
To create a new session, send json data like
{
"desiredCapabilities": {
"bundleId": "your-bundle-id",
"app": "your-app-path"
"shouldUseCompactResponses": (bool),
"shouldUseTestManagerForVisibilityDetection": (bool),
"maxTypingFrequency": (integer),
"arguments": (list(str)),
"environment": (dict: str->str)
},
} | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L239-L305 | [
"def new_client(self, path):\n return HTTPClient(self.address.rstrip('/') + '/' + path.lstrip('/'), self.alert_callback)\n",
"def status(self):\n res = self.http.get('status')\n sid = res.sessionId\n res.value['sessionId'] = sid\n return res.value\n"
] | class Client(object):
def __init__(self, url=None):
"""
Args:
target (string): the device url
If target is None, device url will set to env-var "DEVICE_URL" if defined else set to "http://localhost:8100"
"""
if url is None:
url = os.environ.get('DEVICE_URL', 'http://localhost:8100')
self.http = HTTPClient(url)
def wait_ready(self, timeout=120):
"""
wait until WDA back to normal
Returns:
bool (if wda works)
"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
self.status()
return True
except:
time.sleep(2)
return False
def status(self):
res = self.http.get('status')
sid = res.sessionId
res.value['sessionId'] = sid
return res.value
def home(self):
"""Press home button"""
return self.http.post('/wda/homescreen')
def healthcheck(self):
"""Hit healthcheck"""
return self.http.get('/wda/healthcheck')
def source(self, format='xml', accessible=False):
"""
Args:
format (str): only 'xml' and 'json' source types are supported
accessible (bool): when set to true, format is always 'json'
"""
if accessible:
return self.http.get('/wda/accessibleSource').value
return self.http.get('source?format='+format).value
def screenshot(self, png_filename=None, format='raw'):
"""
Screenshot with PNG format
Args:
png_filename(string): optional, save file name
format(string): return format, pillow or raw(default)
Returns:
raw data or PIL.Image
Raises:
WDAError
"""
value = self.http.get('screenshot').value
raw_value = base64.b64decode(value)
png_header = b"\x89PNG\r\n\x1a\n"
if not raw_value.startswith(png_header) and png_filename:
raise WDAError(-1, "screenshot png format error")
if png_filename:
with open(png_filename, 'wb') as f:
f.write(raw_value)
if format == 'raw':
return raw_value
elif format == 'pillow':
from PIL import Image
buff = io.BytesIO(raw_value)
return Image.open(buff)
else:
raise ValueError("unknown format")
|
openatx/facebook-wda | wda/__init__.py | Client.screenshot | python | def screenshot(self, png_filename=None, format='raw'):
value = self.http.get('screenshot').value
raw_value = base64.b64decode(value)
png_header = b"\x89PNG\r\n\x1a\n"
if not raw_value.startswith(png_header) and png_filename:
raise WDAError(-1, "screenshot png format error")
if png_filename:
with open(png_filename, 'wb') as f:
f.write(raw_value)
if format == 'raw':
return raw_value
elif format == 'pillow':
from PIL import Image
buff = io.BytesIO(raw_value)
return Image.open(buff)
else:
raise ValueError("unknown format") | Screenshot with PNG format
Args:
png_filename(string): optional, save file name
format(string): return format, pillow or raw(default)
Returns:
raw data or PIL.Image
Raises:
WDAError | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L307-L337 | null | class Client(object):
def __init__(self, url=None):
"""
Args:
target (string): the device url
If target is None, device url will set to env-var "DEVICE_URL" if defined else set to "http://localhost:8100"
"""
if url is None:
url = os.environ.get('DEVICE_URL', 'http://localhost:8100')
self.http = HTTPClient(url)
def wait_ready(self, timeout=120):
"""
wait until WDA back to normal
Returns:
bool (if wda works)
"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
self.status()
return True
except:
time.sleep(2)
return False
def status(self):
res = self.http.get('status')
sid = res.sessionId
res.value['sessionId'] = sid
return res.value
def home(self):
"""Press home button"""
return self.http.post('/wda/homescreen')
def healthcheck(self):
"""Hit healthcheck"""
return self.http.get('/wda/healthcheck')
def source(self, format='xml', accessible=False):
"""
Args:
format (str): only 'xml' and 'json' source types are supported
accessible (bool): when set to true, format is always 'json'
"""
if accessible:
return self.http.get('/wda/accessibleSource').value
return self.http.get('source?format='+format).value
def session(self, bundle_id=None, arguments=None, environment=None):
"""
Args:
- bundle_id (str): the app bundle id
- arguments (list): ['-u', 'https://www.google.com/ncr']
- enviroment (dict): {"KEY": "VAL"}
WDA Return json like
{
"value": {
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"capabilities": {
"device": "iphone",
"browserName": "部落冲突",
"sdkVersion": "9.3.2",
"CFBundleIdentifier": "com.supercell.magic"
}
},
"sessionId": "69E6FDBA-8D59-4349-B7DE-A9CA41A97814",
"status": 0
}
To create a new session, send json data like
{
"desiredCapabilities": {
"bundleId": "your-bundle-id",
"app": "your-app-path"
"shouldUseCompactResponses": (bool),
"shouldUseTestManagerForVisibilityDetection": (bool),
"maxTypingFrequency": (integer),
"arguments": (list(str)),
"environment": (dict: str->str)
},
}
"""
if bundle_id is None:
sid = self.status()['sessionId']
if not sid:
raise RuntimeError("no session created ever")
http = self.http.new_client('session/'+sid)
return Session(http, sid)
if arguments and type(arguments) is not list:
raise TypeError('arguments must be a list')
if environment and type(environment) is not dict:
raise TypeError('environment must be a dict')
capabilities = {
'bundleId': bundle_id,
'arguments': arguments,
'environment': environment,
'shouldWaitForQuiescence': True,
}
# Remove empty value to prevent WDAError
for k in list(capabilities.keys()):
if capabilities[k] is None:
capabilities.pop(k)
data = json.dumps({
'desiredCapabilities': capabilities
})
res = self.http.post('session', data)
httpclient = self.http.new_client('session/'+res.sessionId)
return Session(httpclient, res.sessionId)
def screenshot(self, png_filename=None, format='raw'):
"""
Screenshot with PNG format
Args:
png_filename(string): optional, save file name
format(string): return format, pillow or raw(default)
Returns:
raw data or PIL.Image
Raises:
WDAError
"""
value = self.http.get('screenshot').value
raw_value = base64.b64decode(value)
png_header = b"\x89PNG\r\n\x1a\n"
if not raw_value.startswith(png_header) and png_filename:
raise WDAError(-1, "screenshot png format error")
if png_filename:
with open(png_filename, 'wb') as f:
f.write(raw_value)
if format == 'raw':
return raw_value
elif format == 'pillow':
from PIL import Image
buff = io.BytesIO(raw_value)
return Image.open(buff)
else:
raise ValueError("unknown format")
|
openatx/facebook-wda | wda/__init__.py | Session.scale | python | def scale(self):
if self.__scale:
return self.__scale
v = max(self.screenshot().size) / max(self.window_size())
self.__scale = round(v)
return self.__scale | UIKit scale factor
Refs:
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L376-L387 | [
"def screenshot(self):\n \"\"\"\n Take screenshot with session check\n\n Returns:\n PIL.Image\n \"\"\"\n b64data = self.http.get('/screenshot').value\n raw_data = base64.b64decode(b64data)\n from PIL import Image\n buff = io.BytesIO(raw_data)\n return Image.open(buff)\n",
"def wi... | class Session(object):
def __init__(self, httpclient, session_id):
"""
Args:
- target(string): for example, http://127.0.0.1:8100
- session_id(string): wda session id
"""
self.http = httpclient
self._target = None
# self._sid = session_id
# Example session value
# "capabilities": {
# "CFBundleIdentifier": "com.netease.aabbcc",
# "browserName": "?????",
# "device": "iphone",
# "sdkVersion": "10.2"
# }
v = self.http.get('/').value
self.capabilities = v['capabilities']
self._sid = v['sessionId']
self.__scale = None
def __str__(self):
return 'wda.Session (id=%s)' % self._sid
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
@property
def id(self):
return self._sid
@property
def scale(self):
"""
UIKit scale factor
Refs:
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html
"""
if self.__scale:
return self.__scale
v = max(self.screenshot().size) / max(self.window_size())
self.__scale = round(v)
return self.__scale
@property
def bundle_id(self):
""" the session matched bundle id """
return self.capabilities.get('CFBundleIdentifier')
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callable):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None
def open_url(self, url):
"""
TODO: Never successed using before.
https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Commands/FBSessionCommands.m#L43
Args:
url (str): url
Raises:
WDAError
"""
return self.http.post('url', {'url': url})
def deactivate(self, duration):
"""Put app into background and than put it back
Args:
- duration (float): deactivate time, seconds
"""
return self.http.post('/wda/deactivateApp', dict(duration=duration))
def tap(self, x, y):
return self.http.post('/wda/tap/0', dict(x=x, y=y))
def _percent2pos(self, px, py):
w, h = self.window_size()
x = int(px*w) if isinstance(px, float) else px
y = int(py*h) if isinstance(py, float) else py
assert w >= x >= 0
assert h >= y >= 0
return (x, y)
def click(self, x, y):
"""
x, y can be float(percent) or int
"""
if isinstance(x, float) or isinstance(y, float):
x, y = self._percent2pos(x, y)
return self.tap(x, y)
def double_tap(self, x, y):
return self.http.post('/wda/doubleTap', dict(x=x, y=y))
def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
data = {'x': x, 'y': y, 'duration': duration}
return self.http.post('/wda/touchAndHold', data=data)
def screenshot(self):
"""
Take screenshot with session check
Returns:
PIL.Image
"""
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(buff)
def swipe(self, x1, y1, x2, y2, duration=0):
"""
Args:
duration (float): start coordinate press duration (seconds)
[[FBRoute POST:@"/wda/dragfromtoforduration"] respondWithTarget:self action:@selector(handleDragCoordinate:)],
"""
data = dict(fromX=x1, fromY=y1, toX=x2, toY=y2, duration=duration)
return self.http.post('/wda/dragfromtoforduration', data=data)
def swipe_left(self):
w, h = self.window_size()
return self.swipe(w, h/2, 0, h/2)
def swipe_right(self):
w, h = self.window_size()
return self.swipe(0, h/2, w, h/2)
def swipe_up(self):
w, h = self.window_size()
return self.swipe(w/2, h, w/2, 0)
def swipe_down(self):
w, h = self.window_size()
return self.swipe(w/2, 0, w/2, h)
@property
def orientation(self):
"""
Return string
One of <PORTRAIT | LANDSCAPE>
"""
return self.http.get('orientation').value
@orientation.setter
def orientation(self, value):
"""
Args:
- orientation(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT |
UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN
"""
return self.http.post('orientation', data={'orientation': value})
def window_size(self):
"""
Returns:
namedtuple: eg
Size(width=320, height=568)
"""
value = self.http.get('/window/size').value
w = roundint(value['width'])
h = roundint(value['height'])
return namedtuple('Size', ['width', 'height'])(w, h)
def send_keys(self, value):
"""
send keys, yet I know not, todo function
"""
if isinstance(value, six.string_types):
value = list(value)
return self.http.post('/wda/keys', data={'value': value})
def keyboard_dismiss(self):
"""
Not working for now
"""
raise RuntimeError("not pass tests, this method is not allowed to use")
self.http.post('/wda/keyboard/dismiss')
@property
def alert(self):
return Alert(self)
def close(self):
return self.http.delete('/')
def __call__(self, *args, **kwargs):
httpclient = self.http.new_client('')
return Selector(httpclient, self, *args, **kwargs)
|
openatx/facebook-wda | wda/__init__.py | Session.set_alert_callback | python | def set_alert_callback(self, callback):
if callable(callable):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None | Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept() | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L394-L407 | null | class Session(object):
def __init__(self, httpclient, session_id):
"""
Args:
- target(string): for example, http://127.0.0.1:8100
- session_id(string): wda session id
"""
self.http = httpclient
self._target = None
# self._sid = session_id
# Example session value
# "capabilities": {
# "CFBundleIdentifier": "com.netease.aabbcc",
# "browserName": "?????",
# "device": "iphone",
# "sdkVersion": "10.2"
# }
v = self.http.get('/').value
self.capabilities = v['capabilities']
self._sid = v['sessionId']
self.__scale = None
def __str__(self):
return 'wda.Session (id=%s)' % self._sid
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
@property
def id(self):
return self._sid
@property
def scale(self):
"""
UIKit scale factor
Refs:
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html
"""
if self.__scale:
return self.__scale
v = max(self.screenshot().size) / max(self.window_size())
self.__scale = round(v)
return self.__scale
@property
def bundle_id(self):
""" the session matched bundle id """
return self.capabilities.get('CFBundleIdentifier')
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callable):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None
def open_url(self, url):
"""
TODO: Never successed using before.
https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Commands/FBSessionCommands.m#L43
Args:
url (str): url
Raises:
WDAError
"""
return self.http.post('url', {'url': url})
def deactivate(self, duration):
"""Put app into background and than put it back
Args:
- duration (float): deactivate time, seconds
"""
return self.http.post('/wda/deactivateApp', dict(duration=duration))
def tap(self, x, y):
return self.http.post('/wda/tap/0', dict(x=x, y=y))
def _percent2pos(self, px, py):
w, h = self.window_size()
x = int(px*w) if isinstance(px, float) else px
y = int(py*h) if isinstance(py, float) else py
assert w >= x >= 0
assert h >= y >= 0
return (x, y)
def click(self, x, y):
"""
x, y can be float(percent) or int
"""
if isinstance(x, float) or isinstance(y, float):
x, y = self._percent2pos(x, y)
return self.tap(x, y)
def double_tap(self, x, y):
return self.http.post('/wda/doubleTap', dict(x=x, y=y))
def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
data = {'x': x, 'y': y, 'duration': duration}
return self.http.post('/wda/touchAndHold', data=data)
def screenshot(self):
"""
Take screenshot with session check
Returns:
PIL.Image
"""
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(buff)
def swipe(self, x1, y1, x2, y2, duration=0):
"""
Args:
duration (float): start coordinate press duration (seconds)
[[FBRoute POST:@"/wda/dragfromtoforduration"] respondWithTarget:self action:@selector(handleDragCoordinate:)],
"""
data = dict(fromX=x1, fromY=y1, toX=x2, toY=y2, duration=duration)
return self.http.post('/wda/dragfromtoforduration', data=data)
def swipe_left(self):
w, h = self.window_size()
return self.swipe(w, h/2, 0, h/2)
def swipe_right(self):
w, h = self.window_size()
return self.swipe(0, h/2, w, h/2)
def swipe_up(self):
w, h = self.window_size()
return self.swipe(w/2, h, w/2, 0)
def swipe_down(self):
w, h = self.window_size()
return self.swipe(w/2, 0, w/2, h)
@property
def orientation(self):
"""
Return string
One of <PORTRAIT | LANDSCAPE>
"""
return self.http.get('orientation').value
@orientation.setter
def orientation(self, value):
"""
Args:
- orientation(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT |
UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN
"""
return self.http.post('orientation', data={'orientation': value})
def window_size(self):
"""
Returns:
namedtuple: eg
Size(width=320, height=568)
"""
value = self.http.get('/window/size').value
w = roundint(value['width'])
h = roundint(value['height'])
return namedtuple('Size', ['width', 'height'])(w, h)
def send_keys(self, value):
"""
send keys, yet I know not, todo function
"""
if isinstance(value, six.string_types):
value = list(value)
return self.http.post('/wda/keys', data={'value': value})
def keyboard_dismiss(self):
"""
Not working for now
"""
raise RuntimeError("not pass tests, this method is not allowed to use")
self.http.post('/wda/keyboard/dismiss')
@property
def alert(self):
return Alert(self)
def close(self):
return self.http.delete('/')
def __call__(self, *args, **kwargs):
httpclient = self.http.new_client('')
return Selector(httpclient, self, *args, **kwargs)
|
openatx/facebook-wda | wda/__init__.py | Session.click | python | def click(self, x, y):
if isinstance(x, float) or isinstance(y, float):
x, y = self._percent2pos(x, y)
return self.tap(x, y) | x, y can be float(percent) or int | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L439-L445 | [
"def tap(self, x, y):\n return self.http.post('/wda/tap/0', dict(x=x, y=y))\n",
"def _percent2pos(self, px, py):\n w, h = self.window_size()\n x = int(px*w) if isinstance(px, float) else px\n y = int(py*h) if isinstance(py, float) else py\n assert w >= x >= 0\n assert h >= y >= 0\n return (x,... | class Session(object):
def __init__(self, httpclient, session_id):
"""
Args:
- target(string): for example, http://127.0.0.1:8100
- session_id(string): wda session id
"""
self.http = httpclient
self._target = None
# self._sid = session_id
# Example session value
# "capabilities": {
# "CFBundleIdentifier": "com.netease.aabbcc",
# "browserName": "?????",
# "device": "iphone",
# "sdkVersion": "10.2"
# }
v = self.http.get('/').value
self.capabilities = v['capabilities']
self._sid = v['sessionId']
self.__scale = None
def __str__(self):
return 'wda.Session (id=%s)' % self._sid
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
@property
def id(self):
return self._sid
@property
def scale(self):
"""
UIKit scale factor
Refs:
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html
"""
if self.__scale:
return self.__scale
v = max(self.screenshot().size) / max(self.window_size())
self.__scale = round(v)
return self.__scale
@property
def bundle_id(self):
""" the session matched bundle id """
return self.capabilities.get('CFBundleIdentifier')
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callable):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None
def open_url(self, url):
"""
TODO: Never successed using before.
https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Commands/FBSessionCommands.m#L43
Args:
url (str): url
Raises:
WDAError
"""
return self.http.post('url', {'url': url})
def deactivate(self, duration):
"""Put app into background and than put it back
Args:
- duration (float): deactivate time, seconds
"""
return self.http.post('/wda/deactivateApp', dict(duration=duration))
def tap(self, x, y):
return self.http.post('/wda/tap/0', dict(x=x, y=y))
def _percent2pos(self, px, py):
w, h = self.window_size()
x = int(px*w) if isinstance(px, float) else px
y = int(py*h) if isinstance(py, float) else py
assert w >= x >= 0
assert h >= y >= 0
return (x, y)
def double_tap(self, x, y):
return self.http.post('/wda/doubleTap', dict(x=x, y=y))
def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
data = {'x': x, 'y': y, 'duration': duration}
return self.http.post('/wda/touchAndHold', data=data)
def screenshot(self):
"""
Take screenshot with session check
Returns:
PIL.Image
"""
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(buff)
def swipe(self, x1, y1, x2, y2, duration=0):
"""
Args:
duration (float): start coordinate press duration (seconds)
[[FBRoute POST:@"/wda/dragfromtoforduration"] respondWithTarget:self action:@selector(handleDragCoordinate:)],
"""
data = dict(fromX=x1, fromY=y1, toX=x2, toY=y2, duration=duration)
return self.http.post('/wda/dragfromtoforduration', data=data)
def swipe_left(self):
w, h = self.window_size()
return self.swipe(w, h/2, 0, h/2)
def swipe_right(self):
w, h = self.window_size()
return self.swipe(0, h/2, w, h/2)
def swipe_up(self):
w, h = self.window_size()
return self.swipe(w/2, h, w/2, 0)
def swipe_down(self):
w, h = self.window_size()
return self.swipe(w/2, 0, w/2, h)
@property
def orientation(self):
"""
Return string
One of <PORTRAIT | LANDSCAPE>
"""
return self.http.get('orientation').value
@orientation.setter
def orientation(self, value):
"""
Args:
- orientation(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT |
UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN
"""
return self.http.post('orientation', data={'orientation': value})
def window_size(self):
"""
Returns:
namedtuple: eg
Size(width=320, height=568)
"""
value = self.http.get('/window/size').value
w = roundint(value['width'])
h = roundint(value['height'])
return namedtuple('Size', ['width', 'height'])(w, h)
def send_keys(self, value):
"""
send keys, yet I know not, todo function
"""
if isinstance(value, six.string_types):
value = list(value)
return self.http.post('/wda/keys', data={'value': value})
def keyboard_dismiss(self):
"""
Not working for now
"""
raise RuntimeError("not pass tests, this method is not allowed to use")
self.http.post('/wda/keyboard/dismiss')
@property
def alert(self):
return Alert(self)
def close(self):
return self.http.delete('/')
def __call__(self, *args, **kwargs):
httpclient = self.http.new_client('')
return Selector(httpclient, self, *args, **kwargs)
|
openatx/facebook-wda | wda/__init__.py | Session.tap_hold | python | def tap_hold(self, x, y, duration=1.0):
data = {'x': x, 'y': y, 'duration': duration}
return self.http.post('/wda/touchAndHold', data=data) | Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)], | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L450-L461 | null | class Session(object):
def __init__(self, httpclient, session_id):
"""
Args:
- target(string): for example, http://127.0.0.1:8100
- session_id(string): wda session id
"""
self.http = httpclient
self._target = None
# self._sid = session_id
# Example session value
# "capabilities": {
# "CFBundleIdentifier": "com.netease.aabbcc",
# "browserName": "?????",
# "device": "iphone",
# "sdkVersion": "10.2"
# }
v = self.http.get('/').value
self.capabilities = v['capabilities']
self._sid = v['sessionId']
self.__scale = None
def __str__(self):
return 'wda.Session (id=%s)' % self._sid
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
@property
def id(self):
return self._sid
@property
def scale(self):
"""
UIKit scale factor
Refs:
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html
"""
if self.__scale:
return self.__scale
v = max(self.screenshot().size) / max(self.window_size())
self.__scale = round(v)
return self.__scale
@property
def bundle_id(self):
""" the session matched bundle id """
return self.capabilities.get('CFBundleIdentifier')
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callable):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None
def open_url(self, url):
"""
TODO: Never successed using before.
https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Commands/FBSessionCommands.m#L43
Args:
url (str): url
Raises:
WDAError
"""
return self.http.post('url', {'url': url})
def deactivate(self, duration):
"""Put app into background and than put it back
Args:
- duration (float): deactivate time, seconds
"""
return self.http.post('/wda/deactivateApp', dict(duration=duration))
def tap(self, x, y):
return self.http.post('/wda/tap/0', dict(x=x, y=y))
def _percent2pos(self, px, py):
w, h = self.window_size()
x = int(px*w) if isinstance(px, float) else px
y = int(py*h) if isinstance(py, float) else py
assert w >= x >= 0
assert h >= y >= 0
return (x, y)
def click(self, x, y):
"""
x, y can be float(percent) or int
"""
if isinstance(x, float) or isinstance(y, float):
x, y = self._percent2pos(x, y)
return self.tap(x, y)
def double_tap(self, x, y):
return self.http.post('/wda/doubleTap', dict(x=x, y=y))
def screenshot(self):
"""
Take screenshot with session check
Returns:
PIL.Image
"""
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(buff)
def swipe(self, x1, y1, x2, y2, duration=0):
"""
Args:
duration (float): start coordinate press duration (seconds)
[[FBRoute POST:@"/wda/dragfromtoforduration"] respondWithTarget:self action:@selector(handleDragCoordinate:)],
"""
data = dict(fromX=x1, fromY=y1, toX=x2, toY=y2, duration=duration)
return self.http.post('/wda/dragfromtoforduration', data=data)
def swipe_left(self):
w, h = self.window_size()
return self.swipe(w, h/2, 0, h/2)
def swipe_right(self):
w, h = self.window_size()
return self.swipe(0, h/2, w, h/2)
def swipe_up(self):
w, h = self.window_size()
return self.swipe(w/2, h, w/2, 0)
def swipe_down(self):
w, h = self.window_size()
return self.swipe(w/2, 0, w/2, h)
@property
def orientation(self):
"""
Return string
One of <PORTRAIT | LANDSCAPE>
"""
return self.http.get('orientation').value
@orientation.setter
def orientation(self, value):
"""
Args:
- orientation(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT |
UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN
"""
return self.http.post('orientation', data={'orientation': value})
def window_size(self):
"""
Returns:
namedtuple: eg
Size(width=320, height=568)
"""
value = self.http.get('/window/size').value
w = roundint(value['width'])
h = roundint(value['height'])
return namedtuple('Size', ['width', 'height'])(w, h)
def send_keys(self, value):
"""
send keys, yet I know not, todo function
"""
if isinstance(value, six.string_types):
value = list(value)
return self.http.post('/wda/keys', data={'value': value})
def keyboard_dismiss(self):
"""
Not working for now
"""
raise RuntimeError("not pass tests, this method is not allowed to use")
self.http.post('/wda/keyboard/dismiss')
@property
def alert(self):
return Alert(self)
def close(self):
return self.http.delete('/')
def __call__(self, *args, **kwargs):
httpclient = self.http.new_client('')
return Selector(httpclient, self, *args, **kwargs)
|
openatx/facebook-wda | wda/__init__.py | Session.screenshot | python | def screenshot(self):
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(buff) | Take screenshot with session check
Returns:
PIL.Image | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L463-L474 | null | class Session(object):
def __init__(self, httpclient, session_id):
"""
Args:
- target(string): for example, http://127.0.0.1:8100
- session_id(string): wda session id
"""
self.http = httpclient
self._target = None
# self._sid = session_id
# Example session value
# "capabilities": {
# "CFBundleIdentifier": "com.netease.aabbcc",
# "browserName": "?????",
# "device": "iphone",
# "sdkVersion": "10.2"
# }
v = self.http.get('/').value
self.capabilities = v['capabilities']
self._sid = v['sessionId']
self.__scale = None
def __str__(self):
return 'wda.Session (id=%s)' % self._sid
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
@property
def id(self):
return self._sid
@property
def scale(self):
"""
UIKit scale factor
Refs:
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html
"""
if self.__scale:
return self.__scale
v = max(self.screenshot().size) / max(self.window_size())
self.__scale = round(v)
return self.__scale
@property
def bundle_id(self):
""" the session matched bundle id """
return self.capabilities.get('CFBundleIdentifier')
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callable):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None
def open_url(self, url):
"""
TODO: Never successed using before.
https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Commands/FBSessionCommands.m#L43
Args:
url (str): url
Raises:
WDAError
"""
return self.http.post('url', {'url': url})
def deactivate(self, duration):
"""Put app into background and than put it back
Args:
- duration (float): deactivate time, seconds
"""
return self.http.post('/wda/deactivateApp', dict(duration=duration))
def tap(self, x, y):
return self.http.post('/wda/tap/0', dict(x=x, y=y))
def _percent2pos(self, px, py):
w, h = self.window_size()
x = int(px*w) if isinstance(px, float) else px
y = int(py*h) if isinstance(py, float) else py
assert w >= x >= 0
assert h >= y >= 0
return (x, y)
def click(self, x, y):
"""
x, y can be float(percent) or int
"""
if isinstance(x, float) or isinstance(y, float):
x, y = self._percent2pos(x, y)
return self.tap(x, y)
def double_tap(self, x, y):
return self.http.post('/wda/doubleTap', dict(x=x, y=y))
def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
data = {'x': x, 'y': y, 'duration': duration}
return self.http.post('/wda/touchAndHold', data=data)
def swipe(self, x1, y1, x2, y2, duration=0):
"""
Args:
duration (float): start coordinate press duration (seconds)
[[FBRoute POST:@"/wda/dragfromtoforduration"] respondWithTarget:self action:@selector(handleDragCoordinate:)],
"""
data = dict(fromX=x1, fromY=y1, toX=x2, toY=y2, duration=duration)
return self.http.post('/wda/dragfromtoforduration', data=data)
def swipe_left(self):
w, h = self.window_size()
return self.swipe(w, h/2, 0, h/2)
def swipe_right(self):
w, h = self.window_size()
return self.swipe(0, h/2, w, h/2)
def swipe_up(self):
w, h = self.window_size()
return self.swipe(w/2, h, w/2, 0)
def swipe_down(self):
w, h = self.window_size()
return self.swipe(w/2, 0, w/2, h)
@property
def orientation(self):
"""
Return string
One of <PORTRAIT | LANDSCAPE>
"""
return self.http.get('orientation').value
@orientation.setter
def orientation(self, value):
"""
Args:
- orientation(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT |
UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN
"""
return self.http.post('orientation', data={'orientation': value})
def window_size(self):
"""
Returns:
namedtuple: eg
Size(width=320, height=568)
"""
value = self.http.get('/window/size').value
w = roundint(value['width'])
h = roundint(value['height'])
return namedtuple('Size', ['width', 'height'])(w, h)
def send_keys(self, value):
"""
send keys, yet I know not, todo function
"""
if isinstance(value, six.string_types):
value = list(value)
return self.http.post('/wda/keys', data={'value': value})
def keyboard_dismiss(self):
"""
Not working for now
"""
raise RuntimeError("not pass tests, this method is not allowed to use")
self.http.post('/wda/keyboard/dismiss')
@property
def alert(self):
return Alert(self)
def close(self):
return self.http.delete('/')
def __call__(self, *args, **kwargs):
httpclient = self.http.new_client('')
return Selector(httpclient, self, *args, **kwargs)
|
openatx/facebook-wda | wda/__init__.py | Session.swipe | python | def swipe(self, x1, y1, x2, y2, duration=0):
data = dict(fromX=x1, fromY=y1, toX=x2, toY=y2, duration=duration)
return self.http.post('/wda/dragfromtoforduration', data=data) | Args:
duration (float): start coordinate press duration (seconds)
[[FBRoute POST:@"/wda/dragfromtoforduration"] respondWithTarget:self action:@selector(handleDragCoordinate:)], | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L476-L484 | null | class Session(object):
def __init__(self, httpclient, session_id):
"""
Args:
- target(string): for example, http://127.0.0.1:8100
- session_id(string): wda session id
"""
self.http = httpclient
self._target = None
# self._sid = session_id
# Example session value
# "capabilities": {
# "CFBundleIdentifier": "com.netease.aabbcc",
# "browserName": "?????",
# "device": "iphone",
# "sdkVersion": "10.2"
# }
v = self.http.get('/').value
self.capabilities = v['capabilities']
self._sid = v['sessionId']
self.__scale = None
def __str__(self):
return 'wda.Session (id=%s)' % self._sid
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
@property
def id(self):
return self._sid
@property
def scale(self):
"""
UIKit scale factor
Refs:
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html
"""
if self.__scale:
return self.__scale
v = max(self.screenshot().size) / max(self.window_size())
self.__scale = round(v)
return self.__scale
@property
def bundle_id(self):
""" the session matched bundle id """
return self.capabilities.get('CFBundleIdentifier')
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callable):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None
def open_url(self, url):
"""
TODO: Never successed using before.
https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Commands/FBSessionCommands.m#L43
Args:
url (str): url
Raises:
WDAError
"""
return self.http.post('url', {'url': url})
def deactivate(self, duration):
"""Put app into background and than put it back
Args:
- duration (float): deactivate time, seconds
"""
return self.http.post('/wda/deactivateApp', dict(duration=duration))
def tap(self, x, y):
return self.http.post('/wda/tap/0', dict(x=x, y=y))
def _percent2pos(self, px, py):
w, h = self.window_size()
x = int(px*w) if isinstance(px, float) else px
y = int(py*h) if isinstance(py, float) else py
assert w >= x >= 0
assert h >= y >= 0
return (x, y)
def click(self, x, y):
"""
x, y can be float(percent) or int
"""
if isinstance(x, float) or isinstance(y, float):
x, y = self._percent2pos(x, y)
return self.tap(x, y)
def double_tap(self, x, y):
return self.http.post('/wda/doubleTap', dict(x=x, y=y))
def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
data = {'x': x, 'y': y, 'duration': duration}
return self.http.post('/wda/touchAndHold', data=data)
def screenshot(self):
"""
Take screenshot with session check
Returns:
PIL.Image
"""
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(buff)
def swipe_left(self):
w, h = self.window_size()
return self.swipe(w, h/2, 0, h/2)
def swipe_right(self):
w, h = self.window_size()
return self.swipe(0, h/2, w, h/2)
def swipe_up(self):
w, h = self.window_size()
return self.swipe(w/2, h, w/2, 0)
def swipe_down(self):
w, h = self.window_size()
return self.swipe(w/2, 0, w/2, h)
@property
def orientation(self):
"""
Return string
One of <PORTRAIT | LANDSCAPE>
"""
return self.http.get('orientation').value
@orientation.setter
def orientation(self, value):
"""
Args:
- orientation(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT |
UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN
"""
return self.http.post('orientation', data={'orientation': value})
def window_size(self):
"""
Returns:
namedtuple: eg
Size(width=320, height=568)
"""
value = self.http.get('/window/size').value
w = roundint(value['width'])
h = roundint(value['height'])
return namedtuple('Size', ['width', 'height'])(w, h)
def send_keys(self, value):
"""
send keys, yet I know not, todo function
"""
if isinstance(value, six.string_types):
value = list(value)
return self.http.post('/wda/keys', data={'value': value})
def keyboard_dismiss(self):
"""
Not working for now
"""
raise RuntimeError("not pass tests, this method is not allowed to use")
self.http.post('/wda/keyboard/dismiss')
@property
def alert(self):
return Alert(self)
def close(self):
return self.http.delete('/')
def __call__(self, *args, **kwargs):
httpclient = self.http.new_client('')
return Selector(httpclient, self, *args, **kwargs)
|
openatx/facebook-wda | wda/__init__.py | Session.window_size | python | def window_size(self):
value = self.http.get('/window/size').value
w = roundint(value['width'])
h = roundint(value['height'])
return namedtuple('Size', ['width', 'height'])(w, h) | Returns:
namedtuple: eg
Size(width=320, height=568) | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L519-L528 | [
"def roundint(i):\n return int(round(i, 0))\n"
] | class Session(object):
def __init__(self, httpclient, session_id):
"""
Args:
- target(string): for example, http://127.0.0.1:8100
- session_id(string): wda session id
"""
self.http = httpclient
self._target = None
# self._sid = session_id
# Example session value
# "capabilities": {
# "CFBundleIdentifier": "com.netease.aabbcc",
# "browserName": "?????",
# "device": "iphone",
# "sdkVersion": "10.2"
# }
v = self.http.get('/').value
self.capabilities = v['capabilities']
self._sid = v['sessionId']
self.__scale = None
def __str__(self):
return 'wda.Session (id=%s)' % self._sid
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
@property
def id(self):
return self._sid
@property
def scale(self):
"""
UIKit scale factor
Refs:
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html
"""
if self.__scale:
return self.__scale
v = max(self.screenshot().size) / max(self.window_size())
self.__scale = round(v)
return self.__scale
@property
def bundle_id(self):
""" the session matched bundle id """
return self.capabilities.get('CFBundleIdentifier')
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callable):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None
def open_url(self, url):
"""
TODO: Never successed using before.
https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Commands/FBSessionCommands.m#L43
Args:
url (str): url
Raises:
WDAError
"""
return self.http.post('url', {'url': url})
def deactivate(self, duration):
"""Put app into background and than put it back
Args:
- duration (float): deactivate time, seconds
"""
return self.http.post('/wda/deactivateApp', dict(duration=duration))
def tap(self, x, y):
return self.http.post('/wda/tap/0', dict(x=x, y=y))
def _percent2pos(self, px, py):
w, h = self.window_size()
x = int(px*w) if isinstance(px, float) else px
y = int(py*h) if isinstance(py, float) else py
assert w >= x >= 0
assert h >= y >= 0
return (x, y)
def click(self, x, y):
"""
x, y can be float(percent) or int
"""
if isinstance(x, float) or isinstance(y, float):
x, y = self._percent2pos(x, y)
return self.tap(x, y)
def double_tap(self, x, y):
return self.http.post('/wda/doubleTap', dict(x=x, y=y))
def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
data = {'x': x, 'y': y, 'duration': duration}
return self.http.post('/wda/touchAndHold', data=data)
def screenshot(self):
"""
Take screenshot with session check
Returns:
PIL.Image
"""
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(buff)
def swipe(self, x1, y1, x2, y2, duration=0):
"""
Args:
duration (float): start coordinate press duration (seconds)
[[FBRoute POST:@"/wda/dragfromtoforduration"] respondWithTarget:self action:@selector(handleDragCoordinate:)],
"""
data = dict(fromX=x1, fromY=y1, toX=x2, toY=y2, duration=duration)
return self.http.post('/wda/dragfromtoforduration', data=data)
def swipe_left(self):
w, h = self.window_size()
return self.swipe(w, h/2, 0, h/2)
def swipe_right(self):
w, h = self.window_size()
return self.swipe(0, h/2, w, h/2)
def swipe_up(self):
w, h = self.window_size()
return self.swipe(w/2, h, w/2, 0)
def swipe_down(self):
w, h = self.window_size()
return self.swipe(w/2, 0, w/2, h)
@property
def orientation(self):
"""
Return string
One of <PORTRAIT | LANDSCAPE>
"""
return self.http.get('orientation').value
@orientation.setter
def orientation(self, value):
"""
Args:
- orientation(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT |
UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN
"""
return self.http.post('orientation', data={'orientation': value})
def send_keys(self, value):
"""
send keys, yet I know not, todo function
"""
if isinstance(value, six.string_types):
value = list(value)
return self.http.post('/wda/keys', data={'value': value})
def keyboard_dismiss(self):
"""
Not working for now
"""
raise RuntimeError("not pass tests, this method is not allowed to use")
self.http.post('/wda/keyboard/dismiss')
@property
def alert(self):
return Alert(self)
def close(self):
return self.http.delete('/')
def __call__(self, *args, **kwargs):
httpclient = self.http.new_client('')
return Selector(httpclient, self, *args, **kwargs)
|
openatx/facebook-wda | wda/__init__.py | Session.send_keys | python | def send_keys(self, value):
if isinstance(value, six.string_types):
value = list(value)
return self.http.post('/wda/keys', data={'value': value}) | send keys, yet I know not, todo function | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L530-L536 | null | class Session(object):
def __init__(self, httpclient, session_id):
"""
Args:
- target(string): for example, http://127.0.0.1:8100
- session_id(string): wda session id
"""
self.http = httpclient
self._target = None
# self._sid = session_id
# Example session value
# "capabilities": {
# "CFBundleIdentifier": "com.netease.aabbcc",
# "browserName": "?????",
# "device": "iphone",
# "sdkVersion": "10.2"
# }
v = self.http.get('/').value
self.capabilities = v['capabilities']
self._sid = v['sessionId']
self.__scale = None
def __str__(self):
return 'wda.Session (id=%s)' % self._sid
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self.close()
@property
def id(self):
return self._sid
@property
def scale(self):
"""
UIKit scale factor
Refs:
https://developer.apple.com/library/archive/documentation/DeviceInformation/Reference/iOSDeviceCompatibility/Displays/Displays.html
"""
if self.__scale:
return self.__scale
v = max(self.screenshot().size) / max(self.window_size())
self.__scale = round(v)
return self.__scale
@property
def bundle_id(self):
""" the session matched bundle id """
return self.capabilities.get('CFBundleIdentifier')
def set_alert_callback(self, callback):
"""
Args:
callback (func): called when alert popup
Example of callback:
def callback(session):
session.alert.accept()
"""
if callable(callable):
self.http.alert_callback = functools.partial(callback, self)
else:
self.http.alert_callback = None
def open_url(self, url):
"""
TODO: Never successed using before.
https://github.com/facebook/WebDriverAgent/blob/master/WebDriverAgentLib/Commands/FBSessionCommands.m#L43
Args:
url (str): url
Raises:
WDAError
"""
return self.http.post('url', {'url': url})
def deactivate(self, duration):
"""Put app into background and than put it back
Args:
- duration (float): deactivate time, seconds
"""
return self.http.post('/wda/deactivateApp', dict(duration=duration))
def tap(self, x, y):
return self.http.post('/wda/tap/0', dict(x=x, y=y))
def _percent2pos(self, px, py):
w, h = self.window_size()
x = int(px*w) if isinstance(px, float) else px
y = int(py*h) if isinstance(py, float) else py
assert w >= x >= 0
assert h >= y >= 0
return (x, y)
def click(self, x, y):
"""
x, y can be float(percent) or int
"""
if isinstance(x, float) or isinstance(y, float):
x, y = self._percent2pos(x, y)
return self.tap(x, y)
def double_tap(self, x, y):
return self.http.post('/wda/doubleTap', dict(x=x, y=y))
def tap_hold(self, x, y, duration=1.0):
"""
Tap and hold for a moment
Args:
- x, y(int): position
- duration(float): seconds of hold time
[[FBRoute POST:@"/wda/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHoldCoordinate:)],
"""
data = {'x': x, 'y': y, 'duration': duration}
return self.http.post('/wda/touchAndHold', data=data)
def screenshot(self):
"""
Take screenshot with session check
Returns:
PIL.Image
"""
b64data = self.http.get('/screenshot').value
raw_data = base64.b64decode(b64data)
from PIL import Image
buff = io.BytesIO(raw_data)
return Image.open(buff)
def swipe(self, x1, y1, x2, y2, duration=0):
"""
Args:
duration (float): start coordinate press duration (seconds)
[[FBRoute POST:@"/wda/dragfromtoforduration"] respondWithTarget:self action:@selector(handleDragCoordinate:)],
"""
data = dict(fromX=x1, fromY=y1, toX=x2, toY=y2, duration=duration)
return self.http.post('/wda/dragfromtoforduration', data=data)
def swipe_left(self):
w, h = self.window_size()
return self.swipe(w, h/2, 0, h/2)
def swipe_right(self):
w, h = self.window_size()
return self.swipe(0, h/2, w, h/2)
def swipe_up(self):
w, h = self.window_size()
return self.swipe(w/2, h, w/2, 0)
def swipe_down(self):
w, h = self.window_size()
return self.swipe(w/2, 0, w/2, h)
@property
def orientation(self):
"""
Return string
One of <PORTRAIT | LANDSCAPE>
"""
return self.http.get('orientation').value
@orientation.setter
def orientation(self, value):
"""
Args:
- orientation(string): LANDSCAPE | PORTRAIT | UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT |
UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN
"""
return self.http.post('orientation', data={'orientation': value})
def window_size(self):
"""
Returns:
namedtuple: eg
Size(width=320, height=568)
"""
value = self.http.get('/window/size').value
w = roundint(value['width'])
h = roundint(value['height'])
return namedtuple('Size', ['width', 'height'])(w, h)
def keyboard_dismiss(self):
"""
Not working for now
"""
raise RuntimeError("not pass tests, this method is not allowed to use")
self.http.post('/wda/keyboard/dismiss')
@property
def alert(self):
return Alert(self)
def close(self):
return self.http.delete('/')
def __call__(self, *args, **kwargs):
httpclient = self.http.new_client('')
return Selector(httpclient, self, *args, **kwargs)
|
openatx/facebook-wda | wda/__init__.py | Selector._add_escape_character_for_quote_prime_character | python | def _add_escape_character_for_quote_prime_character(self, text):
if text is not None:
if "'" in text:
return text.replace("'","\\'")
elif '"' in text:
return text.replace('"','\\"')
else:
return text
else:
return text | Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L707-L721 | null | class Selector(object):
def __init__(self, httpclient, session,
predicate=None,
id=None,
className=None, type=None,
name=None, nameContains=None, nameMatches=None,
text=None, textContains=None, textMatches=None,
value=None, valueContains=None,
label=None, labelContains=None,
visible=None, enabled=None,
classChain=None,
xpath=None,
parent_class_chains=[],
timeout=10.0,
index=0):
'''
Args:
predicate (str): predicate string
id (str): raw identifier
className (str): attr of className
type (str): alias of className
name (str): attr for name
nameContains (str): attr of name contains
nameMatches (str): regex string
text (str): alias of name
textContains (str): alias of nameContains
textMatches (str): alias of nameMatches
value (str): attr of value, not used in most times
valueContains (str): attr of value contains
label (str): attr for label
labelContains (str): attr for label contains
visible (bool): is visible
enabled (bool): is enabled
classChain (str): string of ios chain query, eg: **/XCUIElementTypeOther[`value BEGINSWITH 'blabla'`]
xpath (str): xpath string, a little slow, but works fine
timeout (float): maxium wait element time, default 10.0s
index (int): index of founded elements
WDA use two key to find elements "using", "value"
Examples:
"using" can be on of
"partial link text", "link text"
"name", "id", "accessibility id"
"class name", "class chain", "xpath", "predicate string"
predicate string support many keys
UID,
accessibilityContainer,
accessible,
enabled,
frame,
label,
name,
rect,
type,
value,
visible,
wdAccessibilityContainer,
wdAccessible,
wdEnabled,
wdFrame,
wdLabel,
wdName,
wdRect,
wdType,
wdUID,
wdValue,
wdVisible
'''
self.http = httpclient
self.session = session
self.predicate = predicate
self.id = id
self.class_name = className or type
self.name = self._add_escape_character_for_quote_prime_character(name or text)
self.name_part = nameContains or textContains
self.name_regex = nameMatches or textMatches
self.value = value
self.value_part = valueContains
self.label = label
self.label_part = labelContains
self.enabled = enabled
self.visible = visible
self.index = index
self.xpath = self._fix_xcui_type(xpath)
self.class_chain = self._fix_xcui_type(classChain)
self.timeout = timeout
# some fixtures
if self.class_name and not self.class_name.startswith('XCUIElementType'):
self.class_name = 'XCUIElementType'+self.class_name
if self.name_regex:
if not self.name_regex.startswith('^') and not self.name_regex.startswith('.*'):
self.name_regex = '.*' + self.name_regex
if not self.name_regex.endswith('$') and not self.name_regex.endswith('.*'):
self.name_regex = self.name_regex + '.*'
self.parent_class_chains = parent_class_chains
def _fix_xcui_type(self, s):
if s is None:
return
re_element = '|'.join(xcui_element_types.ELEMENTS)
return re.sub(r'/('+re_element+')', '/XCUIElementType\g<1>', s)
def _wdasearch(self, using, value):
"""
Returns:
element_ids (list(string)): example ['id1', 'id2']
HTTP example response:
[
{"ELEMENT": "E2FF5B2A-DBDF-4E67-9179-91609480D80A"},
{"ELEMENT": "597B1A1E-70B9-4CBE-ACAD-40943B0A6034"}
]
"""
element_ids = []
for v in self.http.post('/elements', {'using': using, 'value': value}).value:
element_ids.append(v['ELEMENT'])
return element_ids
def _gen_class_chain(self):
# just return if aleady exists predicate
if self.predicate:
return '/XCUIElementTypeAny[`' + self.predicate + '`]'
qs = []
if self.name:
qs.append("name == '%s'" % self.name)
if self.name_part:
qs.append("name CONTAINS '%s'" % self.name_part)
if self.name_regex:
qs.append("name MATCHES '%s'" % self.name_regex.encode('unicode_escape'))
if self.label:
qs.append("label == '%s'" % self.label)
if self.label_part:
qs.append("label CONTAINS '%s'" % self.label_part)
if self.value:
qs.append("value == '%s'" % self.value)
if self.value_part:
qs.append("value CONTAINS ’%s'" % self.value_part)
if self.visible is not None:
qs.append("visible == %s" % 'true' if self.visible else 'false')
if self.enabled is not None:
qs.append("enabled == %s" % 'true' if self.enabled else 'false')
predicate = ' AND '.join(qs)
chain = '/' + (self.class_name or 'XCUIElementTypeAny')
if predicate:
chain = chain + '[`' + predicate + '`]'
if self.index:
chain = chain + '[%d]' % self.index
return chain
def find_element_ids(self):
elems = []
if self.id:
return self._wdasearch('id', self.id)
if self.predicate:
return self._wdasearch('predicate string', self.predicate)
if self.xpath:
return self._wdasearch('xpath', self.xpath)
if self.class_chain:
return self._wdasearch('class chain', self.class_chain)
chain = '**' + ''.join(self.parent_class_chains) + self._gen_class_chain()
if DEBUG:
print('CHAIN:', chain)
return self._wdasearch('class chain', chain)
def find_elements(self):
"""
Returns:
Element (list): all the elements
"""
es = []
for element_id in self.find_element_ids():
e = Element(self.http.new_client(''), element_id)
es.append(e)
return es
def count(self):
return len(self.find_element_ids())
def get(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None
"""
start_time = time.time()
if timeout is None:
timeout = self.timeout
while True:
elems = self.find_elements()
if len(elems) > 0:
return elems[0]
if start_time + timeout < time.time():
break
time.sleep(0.01)
# check alert again
if self.session.alert.exists and self.http.alert_callback:
self.http.alert_callback()
return self.get(timeout, raise_error)
if raise_error:
raise WDAElementNotFoundError("element not found")
def __getattr__(self, oper):
return getattr(self.get(), oper)
def set_timeout(self, s):
"""
Set element wait timeout
"""
self.timeout = s
return self
def __getitem__(self, index):
self.index = index
return self
def child(self, *args, **kwargs):
chain = self._gen_class_chain()
kwargs['parent_class_chains'] = self.parent_class_chains + [chain]
return Selector(self.http, self.session, *args, **kwargs)
@property
def exists(self):
return len(self.find_element_ids()) > self.index
def click_exists(self, timeout=0):
"""
Wait element and perform click
Args:
timeout (float): timeout for wait
Returns:
bool: if successfully clicked
"""
e = self.get(timeout=timeout, raise_error=False)
if e is None:
return False
e.click()
return True
def wait(self, timeout=None, raise_error=True):
""" alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError
"""
return self.get(timeout=timeout, raise_error=raise_error)
def wait_gone(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): default timeout
raise_error (bool): return bool or raise error
Returns:
bool: works when raise_error is False
Raises:
WDAElementNotDisappearError
"""
start_time = time.time()
if timeout is None or timeout <= 0:
timeout = self.timeout
while start_time + timeout > time.time():
if not self.exists:
return True
if not raise_error:
return False
raise WDAElementNotDisappearError("element not gone")
|
openatx/facebook-wda | wda/__init__.py | Selector._wdasearch | python | def _wdasearch(self, using, value):
element_ids = []
for v in self.http.post('/elements', {'using': using, 'value': value}).value:
element_ids.append(v['ELEMENT'])
return element_ids | Returns:
element_ids (list(string)): example ['id1', 'id2']
HTTP example response:
[
{"ELEMENT": "E2FF5B2A-DBDF-4E67-9179-91609480D80A"},
{"ELEMENT": "597B1A1E-70B9-4CBE-ACAD-40943B0A6034"}
] | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L723-L737 | null | class Selector(object):
def __init__(self, httpclient, session,
predicate=None,
id=None,
className=None, type=None,
name=None, nameContains=None, nameMatches=None,
text=None, textContains=None, textMatches=None,
value=None, valueContains=None,
label=None, labelContains=None,
visible=None, enabled=None,
classChain=None,
xpath=None,
parent_class_chains=[],
timeout=10.0,
index=0):
'''
Args:
predicate (str): predicate string
id (str): raw identifier
className (str): attr of className
type (str): alias of className
name (str): attr for name
nameContains (str): attr of name contains
nameMatches (str): regex string
text (str): alias of name
textContains (str): alias of nameContains
textMatches (str): alias of nameMatches
value (str): attr of value, not used in most times
valueContains (str): attr of value contains
label (str): attr for label
labelContains (str): attr for label contains
visible (bool): is visible
enabled (bool): is enabled
classChain (str): string of ios chain query, eg: **/XCUIElementTypeOther[`value BEGINSWITH 'blabla'`]
xpath (str): xpath string, a little slow, but works fine
timeout (float): maxium wait element time, default 10.0s
index (int): index of founded elements
WDA use two key to find elements "using", "value"
Examples:
"using" can be on of
"partial link text", "link text"
"name", "id", "accessibility id"
"class name", "class chain", "xpath", "predicate string"
predicate string support many keys
UID,
accessibilityContainer,
accessible,
enabled,
frame,
label,
name,
rect,
type,
value,
visible,
wdAccessibilityContainer,
wdAccessible,
wdEnabled,
wdFrame,
wdLabel,
wdName,
wdRect,
wdType,
wdUID,
wdValue,
wdVisible
'''
self.http = httpclient
self.session = session
self.predicate = predicate
self.id = id
self.class_name = className or type
self.name = self._add_escape_character_for_quote_prime_character(name or text)
self.name_part = nameContains or textContains
self.name_regex = nameMatches or textMatches
self.value = value
self.value_part = valueContains
self.label = label
self.label_part = labelContains
self.enabled = enabled
self.visible = visible
self.index = index
self.xpath = self._fix_xcui_type(xpath)
self.class_chain = self._fix_xcui_type(classChain)
self.timeout = timeout
# some fixtures
if self.class_name and not self.class_name.startswith('XCUIElementType'):
self.class_name = 'XCUIElementType'+self.class_name
if self.name_regex:
if not self.name_regex.startswith('^') and not self.name_regex.startswith('.*'):
self.name_regex = '.*' + self.name_regex
if not self.name_regex.endswith('$') and not self.name_regex.endswith('.*'):
self.name_regex = self.name_regex + '.*'
self.parent_class_chains = parent_class_chains
def _fix_xcui_type(self, s):
if s is None:
return
re_element = '|'.join(xcui_element_types.ELEMENTS)
return re.sub(r'/('+re_element+')', '/XCUIElementType\g<1>', s)
def _add_escape_character_for_quote_prime_character(self, text):
"""
Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text
"""
if text is not None:
if "'" in text:
return text.replace("'","\\'")
elif '"' in text:
return text.replace('"','\\"')
else:
return text
else:
return text
def _wdasearch(self, using, value):
"""
Returns:
element_ids (list(string)): example ['id1', 'id2']
HTTP example response:
[
{"ELEMENT": "E2FF5B2A-DBDF-4E67-9179-91609480D80A"},
{"ELEMENT": "597B1A1E-70B9-4CBE-ACAD-40943B0A6034"}
]
"""
element_ids = []
for v in self.http.post('/elements', {'using': using, 'value': value}).value:
element_ids.append(v['ELEMENT'])
return element_ids
def _gen_class_chain(self):
# just return if aleady exists predicate
if self.predicate:
return '/XCUIElementTypeAny[`' + self.predicate + '`]'
qs = []
if self.name:
qs.append("name == '%s'" % self.name)
if self.name_part:
qs.append("name CONTAINS '%s'" % self.name_part)
if self.name_regex:
qs.append("name MATCHES '%s'" % self.name_regex.encode('unicode_escape'))
if self.label:
qs.append("label == '%s'" % self.label)
if self.label_part:
qs.append("label CONTAINS '%s'" % self.label_part)
if self.value:
qs.append("value == '%s'" % self.value)
if self.value_part:
qs.append("value CONTAINS ’%s'" % self.value_part)
if self.visible is not None:
qs.append("visible == %s" % 'true' if self.visible else 'false')
if self.enabled is not None:
qs.append("enabled == %s" % 'true' if self.enabled else 'false')
predicate = ' AND '.join(qs)
chain = '/' + (self.class_name or 'XCUIElementTypeAny')
if predicate:
chain = chain + '[`' + predicate + '`]'
if self.index:
chain = chain + '[%d]' % self.index
return chain
def find_element_ids(self):
elems = []
if self.id:
return self._wdasearch('id', self.id)
if self.predicate:
return self._wdasearch('predicate string', self.predicate)
if self.xpath:
return self._wdasearch('xpath', self.xpath)
if self.class_chain:
return self._wdasearch('class chain', self.class_chain)
chain = '**' + ''.join(self.parent_class_chains) + self._gen_class_chain()
if DEBUG:
print('CHAIN:', chain)
return self._wdasearch('class chain', chain)
def find_elements(self):
"""
Returns:
Element (list): all the elements
"""
es = []
for element_id in self.find_element_ids():
e = Element(self.http.new_client(''), element_id)
es.append(e)
return es
def count(self):
return len(self.find_element_ids())
def get(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None
"""
start_time = time.time()
if timeout is None:
timeout = self.timeout
while True:
elems = self.find_elements()
if len(elems) > 0:
return elems[0]
if start_time + timeout < time.time():
break
time.sleep(0.01)
# check alert again
if self.session.alert.exists and self.http.alert_callback:
self.http.alert_callback()
return self.get(timeout, raise_error)
if raise_error:
raise WDAElementNotFoundError("element not found")
def __getattr__(self, oper):
return getattr(self.get(), oper)
def set_timeout(self, s):
"""
Set element wait timeout
"""
self.timeout = s
return self
def __getitem__(self, index):
self.index = index
return self
def child(self, *args, **kwargs):
chain = self._gen_class_chain()
kwargs['parent_class_chains'] = self.parent_class_chains + [chain]
return Selector(self.http, self.session, *args, **kwargs)
@property
def exists(self):
return len(self.find_element_ids()) > self.index
def click_exists(self, timeout=0):
"""
Wait element and perform click
Args:
timeout (float): timeout for wait
Returns:
bool: if successfully clicked
"""
e = self.get(timeout=timeout, raise_error=False)
if e is None:
return False
e.click()
return True
def wait(self, timeout=None, raise_error=True):
""" alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError
"""
return self.get(timeout=timeout, raise_error=raise_error)
def wait_gone(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): default timeout
raise_error (bool): return bool or raise error
Returns:
bool: works when raise_error is False
Raises:
WDAElementNotDisappearError
"""
start_time = time.time()
if timeout is None or timeout <= 0:
timeout = self.timeout
while start_time + timeout > time.time():
if not self.exists:
return True
if not raise_error:
return False
raise WDAElementNotDisappearError("element not gone")
|
openatx/facebook-wda | wda/__init__.py | Selector.find_elements | python | def find_elements(self):
es = []
for element_id in self.find_element_ids():
e = Element(self.http.new_client(''), element_id)
es.append(e)
return es | Returns:
Element (list): all the elements | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L786-L795 | [
"def find_element_ids(self):\n elems = []\n if self.id:\n return self._wdasearch('id', self.id)\n if self.predicate:\n return self._wdasearch('predicate string', self.predicate)\n if self.xpath:\n return self._wdasearch('xpath', self.xpath)\n if self.class_chain:\n return ... | class Selector(object):
def __init__(self, httpclient, session,
predicate=None,
id=None,
className=None, type=None,
name=None, nameContains=None, nameMatches=None,
text=None, textContains=None, textMatches=None,
value=None, valueContains=None,
label=None, labelContains=None,
visible=None, enabled=None,
classChain=None,
xpath=None,
parent_class_chains=[],
timeout=10.0,
index=0):
'''
Args:
predicate (str): predicate string
id (str): raw identifier
className (str): attr of className
type (str): alias of className
name (str): attr for name
nameContains (str): attr of name contains
nameMatches (str): regex string
text (str): alias of name
textContains (str): alias of nameContains
textMatches (str): alias of nameMatches
value (str): attr of value, not used in most times
valueContains (str): attr of value contains
label (str): attr for label
labelContains (str): attr for label contains
visible (bool): is visible
enabled (bool): is enabled
classChain (str): string of ios chain query, eg: **/XCUIElementTypeOther[`value BEGINSWITH 'blabla'`]
xpath (str): xpath string, a little slow, but works fine
timeout (float): maxium wait element time, default 10.0s
index (int): index of founded elements
WDA use two key to find elements "using", "value"
Examples:
"using" can be on of
"partial link text", "link text"
"name", "id", "accessibility id"
"class name", "class chain", "xpath", "predicate string"
predicate string support many keys
UID,
accessibilityContainer,
accessible,
enabled,
frame,
label,
name,
rect,
type,
value,
visible,
wdAccessibilityContainer,
wdAccessible,
wdEnabled,
wdFrame,
wdLabel,
wdName,
wdRect,
wdType,
wdUID,
wdValue,
wdVisible
'''
self.http = httpclient
self.session = session
self.predicate = predicate
self.id = id
self.class_name = className or type
self.name = self._add_escape_character_for_quote_prime_character(name or text)
self.name_part = nameContains or textContains
self.name_regex = nameMatches or textMatches
self.value = value
self.value_part = valueContains
self.label = label
self.label_part = labelContains
self.enabled = enabled
self.visible = visible
self.index = index
self.xpath = self._fix_xcui_type(xpath)
self.class_chain = self._fix_xcui_type(classChain)
self.timeout = timeout
# some fixtures
if self.class_name and not self.class_name.startswith('XCUIElementType'):
self.class_name = 'XCUIElementType'+self.class_name
if self.name_regex:
if not self.name_regex.startswith('^') and not self.name_regex.startswith('.*'):
self.name_regex = '.*' + self.name_regex
if not self.name_regex.endswith('$') and not self.name_regex.endswith('.*'):
self.name_regex = self.name_regex + '.*'
self.parent_class_chains = parent_class_chains
def _fix_xcui_type(self, s):
if s is None:
return
re_element = '|'.join(xcui_element_types.ELEMENTS)
return re.sub(r'/('+re_element+')', '/XCUIElementType\g<1>', s)
def _add_escape_character_for_quote_prime_character(self, text):
"""
Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text
"""
if text is not None:
if "'" in text:
return text.replace("'","\\'")
elif '"' in text:
return text.replace('"','\\"')
else:
return text
else:
return text
def _wdasearch(self, using, value):
"""
Returns:
element_ids (list(string)): example ['id1', 'id2']
HTTP example response:
[
{"ELEMENT": "E2FF5B2A-DBDF-4E67-9179-91609480D80A"},
{"ELEMENT": "597B1A1E-70B9-4CBE-ACAD-40943B0A6034"}
]
"""
element_ids = []
for v in self.http.post('/elements', {'using': using, 'value': value}).value:
element_ids.append(v['ELEMENT'])
return element_ids
def _gen_class_chain(self):
# just return if aleady exists predicate
if self.predicate:
return '/XCUIElementTypeAny[`' + self.predicate + '`]'
qs = []
if self.name:
qs.append("name == '%s'" % self.name)
if self.name_part:
qs.append("name CONTAINS '%s'" % self.name_part)
if self.name_regex:
qs.append("name MATCHES '%s'" % self.name_regex.encode('unicode_escape'))
if self.label:
qs.append("label == '%s'" % self.label)
if self.label_part:
qs.append("label CONTAINS '%s'" % self.label_part)
if self.value:
qs.append("value == '%s'" % self.value)
if self.value_part:
qs.append("value CONTAINS ’%s'" % self.value_part)
if self.visible is not None:
qs.append("visible == %s" % 'true' if self.visible else 'false')
if self.enabled is not None:
qs.append("enabled == %s" % 'true' if self.enabled else 'false')
predicate = ' AND '.join(qs)
chain = '/' + (self.class_name or 'XCUIElementTypeAny')
if predicate:
chain = chain + '[`' + predicate + '`]'
if self.index:
chain = chain + '[%d]' % self.index
return chain
def find_element_ids(self):
elems = []
if self.id:
return self._wdasearch('id', self.id)
if self.predicate:
return self._wdasearch('predicate string', self.predicate)
if self.xpath:
return self._wdasearch('xpath', self.xpath)
if self.class_chain:
return self._wdasearch('class chain', self.class_chain)
chain = '**' + ''.join(self.parent_class_chains) + self._gen_class_chain()
if DEBUG:
print('CHAIN:', chain)
return self._wdasearch('class chain', chain)
def count(self):
return len(self.find_element_ids())
def get(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None
"""
start_time = time.time()
if timeout is None:
timeout = self.timeout
while True:
elems = self.find_elements()
if len(elems) > 0:
return elems[0]
if start_time + timeout < time.time():
break
time.sleep(0.01)
# check alert again
if self.session.alert.exists and self.http.alert_callback:
self.http.alert_callback()
return self.get(timeout, raise_error)
if raise_error:
raise WDAElementNotFoundError("element not found")
def __getattr__(self, oper):
return getattr(self.get(), oper)
def set_timeout(self, s):
"""
Set element wait timeout
"""
self.timeout = s
return self
def __getitem__(self, index):
self.index = index
return self
def child(self, *args, **kwargs):
chain = self._gen_class_chain()
kwargs['parent_class_chains'] = self.parent_class_chains + [chain]
return Selector(self.http, self.session, *args, **kwargs)
@property
def exists(self):
return len(self.find_element_ids()) > self.index
def click_exists(self, timeout=0):
"""
Wait element and perform click
Args:
timeout (float): timeout for wait
Returns:
bool: if successfully clicked
"""
e = self.get(timeout=timeout, raise_error=False)
if e is None:
return False
e.click()
return True
def wait(self, timeout=None, raise_error=True):
""" alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError
"""
return self.get(timeout=timeout, raise_error=raise_error)
def wait_gone(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): default timeout
raise_error (bool): return bool or raise error
Returns:
bool: works when raise_error is False
Raises:
WDAElementNotDisappearError
"""
start_time = time.time()
if timeout is None or timeout <= 0:
timeout = self.timeout
while start_time + timeout > time.time():
if not self.exists:
return True
if not raise_error:
return False
raise WDAElementNotDisappearError("element not gone")
|
openatx/facebook-wda | wda/__init__.py | Selector.get | python | def get(self, timeout=None, raise_error=True):
start_time = time.time()
if timeout is None:
timeout = self.timeout
while True:
elems = self.find_elements()
if len(elems) > 0:
return elems[0]
if start_time + timeout < time.time():
break
time.sleep(0.01)
# check alert again
if self.session.alert.exists and self.http.alert_callback:
self.http.alert_callback()
return self.get(timeout, raise_error)
if raise_error:
raise WDAElementNotFoundError("element not found") | Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L800-L830 | [
"def find_elements(self):\n \"\"\"\n Returns:\n Element (list): all the elements\n \"\"\"\n es = []\n for element_id in self.find_element_ids():\n e = Element(self.http.new_client(''), element_id)\n es.append(e)\n return es\n",
"def get(self, timeout=None, raise_error=True):... | class Selector(object):
def __init__(self, httpclient, session,
predicate=None,
id=None,
className=None, type=None,
name=None, nameContains=None, nameMatches=None,
text=None, textContains=None, textMatches=None,
value=None, valueContains=None,
label=None, labelContains=None,
visible=None, enabled=None,
classChain=None,
xpath=None,
parent_class_chains=[],
timeout=10.0,
index=0):
'''
Args:
predicate (str): predicate string
id (str): raw identifier
className (str): attr of className
type (str): alias of className
name (str): attr for name
nameContains (str): attr of name contains
nameMatches (str): regex string
text (str): alias of name
textContains (str): alias of nameContains
textMatches (str): alias of nameMatches
value (str): attr of value, not used in most times
valueContains (str): attr of value contains
label (str): attr for label
labelContains (str): attr for label contains
visible (bool): is visible
enabled (bool): is enabled
classChain (str): string of ios chain query, eg: **/XCUIElementTypeOther[`value BEGINSWITH 'blabla'`]
xpath (str): xpath string, a little slow, but works fine
timeout (float): maxium wait element time, default 10.0s
index (int): index of founded elements
WDA use two key to find elements "using", "value"
Examples:
"using" can be on of
"partial link text", "link text"
"name", "id", "accessibility id"
"class name", "class chain", "xpath", "predicate string"
predicate string support many keys
UID,
accessibilityContainer,
accessible,
enabled,
frame,
label,
name,
rect,
type,
value,
visible,
wdAccessibilityContainer,
wdAccessible,
wdEnabled,
wdFrame,
wdLabel,
wdName,
wdRect,
wdType,
wdUID,
wdValue,
wdVisible
'''
self.http = httpclient
self.session = session
self.predicate = predicate
self.id = id
self.class_name = className or type
self.name = self._add_escape_character_for_quote_prime_character(name or text)
self.name_part = nameContains or textContains
self.name_regex = nameMatches or textMatches
self.value = value
self.value_part = valueContains
self.label = label
self.label_part = labelContains
self.enabled = enabled
self.visible = visible
self.index = index
self.xpath = self._fix_xcui_type(xpath)
self.class_chain = self._fix_xcui_type(classChain)
self.timeout = timeout
# some fixtures
if self.class_name and not self.class_name.startswith('XCUIElementType'):
self.class_name = 'XCUIElementType'+self.class_name
if self.name_regex:
if not self.name_regex.startswith('^') and not self.name_regex.startswith('.*'):
self.name_regex = '.*' + self.name_regex
if not self.name_regex.endswith('$') and not self.name_regex.endswith('.*'):
self.name_regex = self.name_regex + '.*'
self.parent_class_chains = parent_class_chains
def _fix_xcui_type(self, s):
if s is None:
return
re_element = '|'.join(xcui_element_types.ELEMENTS)
return re.sub(r'/('+re_element+')', '/XCUIElementType\g<1>', s)
def _add_escape_character_for_quote_prime_character(self, text):
"""
Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text
"""
if text is not None:
if "'" in text:
return text.replace("'","\\'")
elif '"' in text:
return text.replace('"','\\"')
else:
return text
else:
return text
def _wdasearch(self, using, value):
"""
Returns:
element_ids (list(string)): example ['id1', 'id2']
HTTP example response:
[
{"ELEMENT": "E2FF5B2A-DBDF-4E67-9179-91609480D80A"},
{"ELEMENT": "597B1A1E-70B9-4CBE-ACAD-40943B0A6034"}
]
"""
element_ids = []
for v in self.http.post('/elements', {'using': using, 'value': value}).value:
element_ids.append(v['ELEMENT'])
return element_ids
def _gen_class_chain(self):
# just return if aleady exists predicate
if self.predicate:
return '/XCUIElementTypeAny[`' + self.predicate + '`]'
qs = []
if self.name:
qs.append("name == '%s'" % self.name)
if self.name_part:
qs.append("name CONTAINS '%s'" % self.name_part)
if self.name_regex:
qs.append("name MATCHES '%s'" % self.name_regex.encode('unicode_escape'))
if self.label:
qs.append("label == '%s'" % self.label)
if self.label_part:
qs.append("label CONTAINS '%s'" % self.label_part)
if self.value:
qs.append("value == '%s'" % self.value)
if self.value_part:
qs.append("value CONTAINS ’%s'" % self.value_part)
if self.visible is not None:
qs.append("visible == %s" % 'true' if self.visible else 'false')
if self.enabled is not None:
qs.append("enabled == %s" % 'true' if self.enabled else 'false')
predicate = ' AND '.join(qs)
chain = '/' + (self.class_name or 'XCUIElementTypeAny')
if predicate:
chain = chain + '[`' + predicate + '`]'
if self.index:
chain = chain + '[%d]' % self.index
return chain
def find_element_ids(self):
elems = []
if self.id:
return self._wdasearch('id', self.id)
if self.predicate:
return self._wdasearch('predicate string', self.predicate)
if self.xpath:
return self._wdasearch('xpath', self.xpath)
if self.class_chain:
return self._wdasearch('class chain', self.class_chain)
chain = '**' + ''.join(self.parent_class_chains) + self._gen_class_chain()
if DEBUG:
print('CHAIN:', chain)
return self._wdasearch('class chain', chain)
def find_elements(self):
"""
Returns:
Element (list): all the elements
"""
es = []
for element_id in self.find_element_ids():
e = Element(self.http.new_client(''), element_id)
es.append(e)
return es
def count(self):
return len(self.find_element_ids())
def get(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None
"""
start_time = time.time()
if timeout is None:
timeout = self.timeout
while True:
elems = self.find_elements()
if len(elems) > 0:
return elems[0]
if start_time + timeout < time.time():
break
time.sleep(0.01)
# check alert again
if self.session.alert.exists and self.http.alert_callback:
self.http.alert_callback()
return self.get(timeout, raise_error)
if raise_error:
raise WDAElementNotFoundError("element not found")
def __getattr__(self, oper):
return getattr(self.get(), oper)
def set_timeout(self, s):
"""
Set element wait timeout
"""
self.timeout = s
return self
def __getitem__(self, index):
self.index = index
return self
def child(self, *args, **kwargs):
chain = self._gen_class_chain()
kwargs['parent_class_chains'] = self.parent_class_chains + [chain]
return Selector(self.http, self.session, *args, **kwargs)
@property
def exists(self):
return len(self.find_element_ids()) > self.index
def click_exists(self, timeout=0):
"""
Wait element and perform click
Args:
timeout (float): timeout for wait
Returns:
bool: if successfully clicked
"""
e = self.get(timeout=timeout, raise_error=False)
if e is None:
return False
e.click()
return True
def wait(self, timeout=None, raise_error=True):
""" alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError
"""
return self.get(timeout=timeout, raise_error=raise_error)
def wait_gone(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): default timeout
raise_error (bool): return bool or raise error
Returns:
bool: works when raise_error is False
Raises:
WDAElementNotDisappearError
"""
start_time = time.time()
if timeout is None or timeout <= 0:
timeout = self.timeout
while start_time + timeout > time.time():
if not self.exists:
return True
if not raise_error:
return False
raise WDAElementNotDisappearError("element not gone")
|
openatx/facebook-wda | wda/__init__.py | Selector.click_exists | python | def click_exists(self, timeout=0):
e = self.get(timeout=timeout, raise_error=False)
if e is None:
return False
e.click()
return True | Wait element and perform click
Args:
timeout (float): timeout for wait
Returns:
bool: if successfully clicked | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L855-L869 | [
"def get(self, timeout=None, raise_error=True):\n \"\"\"\n Args:\n timeout (float): timeout for query element, unit seconds\n Default 10s\n raise_error (bool): whether to raise error if element not found\n\n Returns:\n Element: UI Element\n\n Raises:\n WDAElementNo... | class Selector(object):
def __init__(self, httpclient, session,
predicate=None,
id=None,
className=None, type=None,
name=None, nameContains=None, nameMatches=None,
text=None, textContains=None, textMatches=None,
value=None, valueContains=None,
label=None, labelContains=None,
visible=None, enabled=None,
classChain=None,
xpath=None,
parent_class_chains=[],
timeout=10.0,
index=0):
'''
Args:
predicate (str): predicate string
id (str): raw identifier
className (str): attr of className
type (str): alias of className
name (str): attr for name
nameContains (str): attr of name contains
nameMatches (str): regex string
text (str): alias of name
textContains (str): alias of nameContains
textMatches (str): alias of nameMatches
value (str): attr of value, not used in most times
valueContains (str): attr of value contains
label (str): attr for label
labelContains (str): attr for label contains
visible (bool): is visible
enabled (bool): is enabled
classChain (str): string of ios chain query, eg: **/XCUIElementTypeOther[`value BEGINSWITH 'blabla'`]
xpath (str): xpath string, a little slow, but works fine
timeout (float): maxium wait element time, default 10.0s
index (int): index of founded elements
WDA use two key to find elements "using", "value"
Examples:
"using" can be on of
"partial link text", "link text"
"name", "id", "accessibility id"
"class name", "class chain", "xpath", "predicate string"
predicate string support many keys
UID,
accessibilityContainer,
accessible,
enabled,
frame,
label,
name,
rect,
type,
value,
visible,
wdAccessibilityContainer,
wdAccessible,
wdEnabled,
wdFrame,
wdLabel,
wdName,
wdRect,
wdType,
wdUID,
wdValue,
wdVisible
'''
self.http = httpclient
self.session = session
self.predicate = predicate
self.id = id
self.class_name = className or type
self.name = self._add_escape_character_for_quote_prime_character(name or text)
self.name_part = nameContains or textContains
self.name_regex = nameMatches or textMatches
self.value = value
self.value_part = valueContains
self.label = label
self.label_part = labelContains
self.enabled = enabled
self.visible = visible
self.index = index
self.xpath = self._fix_xcui_type(xpath)
self.class_chain = self._fix_xcui_type(classChain)
self.timeout = timeout
# some fixtures
if self.class_name and not self.class_name.startswith('XCUIElementType'):
self.class_name = 'XCUIElementType'+self.class_name
if self.name_regex:
if not self.name_regex.startswith('^') and not self.name_regex.startswith('.*'):
self.name_regex = '.*' + self.name_regex
if not self.name_regex.endswith('$') and not self.name_regex.endswith('.*'):
self.name_regex = self.name_regex + '.*'
self.parent_class_chains = parent_class_chains
def _fix_xcui_type(self, s):
if s is None:
return
re_element = '|'.join(xcui_element_types.ELEMENTS)
return re.sub(r'/('+re_element+')', '/XCUIElementType\g<1>', s)
def _add_escape_character_for_quote_prime_character(self, text):
"""
Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text
"""
if text is not None:
if "'" in text:
return text.replace("'","\\'")
elif '"' in text:
return text.replace('"','\\"')
else:
return text
else:
return text
def _wdasearch(self, using, value):
"""
Returns:
element_ids (list(string)): example ['id1', 'id2']
HTTP example response:
[
{"ELEMENT": "E2FF5B2A-DBDF-4E67-9179-91609480D80A"},
{"ELEMENT": "597B1A1E-70B9-4CBE-ACAD-40943B0A6034"}
]
"""
element_ids = []
for v in self.http.post('/elements', {'using': using, 'value': value}).value:
element_ids.append(v['ELEMENT'])
return element_ids
def _gen_class_chain(self):
# just return if aleady exists predicate
if self.predicate:
return '/XCUIElementTypeAny[`' + self.predicate + '`]'
qs = []
if self.name:
qs.append("name == '%s'" % self.name)
if self.name_part:
qs.append("name CONTAINS '%s'" % self.name_part)
if self.name_regex:
qs.append("name MATCHES '%s'" % self.name_regex.encode('unicode_escape'))
if self.label:
qs.append("label == '%s'" % self.label)
if self.label_part:
qs.append("label CONTAINS '%s'" % self.label_part)
if self.value:
qs.append("value == '%s'" % self.value)
if self.value_part:
qs.append("value CONTAINS ’%s'" % self.value_part)
if self.visible is not None:
qs.append("visible == %s" % 'true' if self.visible else 'false')
if self.enabled is not None:
qs.append("enabled == %s" % 'true' if self.enabled else 'false')
predicate = ' AND '.join(qs)
chain = '/' + (self.class_name or 'XCUIElementTypeAny')
if predicate:
chain = chain + '[`' + predicate + '`]'
if self.index:
chain = chain + '[%d]' % self.index
return chain
def find_element_ids(self):
elems = []
if self.id:
return self._wdasearch('id', self.id)
if self.predicate:
return self._wdasearch('predicate string', self.predicate)
if self.xpath:
return self._wdasearch('xpath', self.xpath)
if self.class_chain:
return self._wdasearch('class chain', self.class_chain)
chain = '**' + ''.join(self.parent_class_chains) + self._gen_class_chain()
if DEBUG:
print('CHAIN:', chain)
return self._wdasearch('class chain', chain)
def find_elements(self):
"""
Returns:
Element (list): all the elements
"""
es = []
for element_id in self.find_element_ids():
e = Element(self.http.new_client(''), element_id)
es.append(e)
return es
def count(self):
return len(self.find_element_ids())
def get(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None
"""
start_time = time.time()
if timeout is None:
timeout = self.timeout
while True:
elems = self.find_elements()
if len(elems) > 0:
return elems[0]
if start_time + timeout < time.time():
break
time.sleep(0.01)
# check alert again
if self.session.alert.exists and self.http.alert_callback:
self.http.alert_callback()
return self.get(timeout, raise_error)
if raise_error:
raise WDAElementNotFoundError("element not found")
def __getattr__(self, oper):
return getattr(self.get(), oper)
def set_timeout(self, s):
"""
Set element wait timeout
"""
self.timeout = s
return self
def __getitem__(self, index):
self.index = index
return self
def child(self, *args, **kwargs):
chain = self._gen_class_chain()
kwargs['parent_class_chains'] = self.parent_class_chains + [chain]
return Selector(self.http, self.session, *args, **kwargs)
@property
def exists(self):
return len(self.find_element_ids()) > self.index
def click_exists(self, timeout=0):
"""
Wait element and perform click
Args:
timeout (float): timeout for wait
Returns:
bool: if successfully clicked
"""
e = self.get(timeout=timeout, raise_error=False)
if e is None:
return False
e.click()
return True
def wait(self, timeout=None, raise_error=True):
""" alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError
"""
return self.get(timeout=timeout, raise_error=raise_error)
def wait_gone(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): default timeout
raise_error (bool): return bool or raise error
Returns:
bool: works when raise_error is False
Raises:
WDAElementNotDisappearError
"""
start_time = time.time()
if timeout is None or timeout <= 0:
timeout = self.timeout
while start_time + timeout > time.time():
if not self.exists:
return True
if not raise_error:
return False
raise WDAElementNotDisappearError("element not gone")
|
openatx/facebook-wda | wda/__init__.py | Selector.wait | python | def wait(self, timeout=None, raise_error=True):
return self.get(timeout=timeout, raise_error=raise_error) | alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L871-L880 | [
"def get(self, timeout=None, raise_error=True):\n \"\"\"\n Args:\n timeout (float): timeout for query element, unit seconds\n Default 10s\n raise_error (bool): whether to raise error if element not found\n\n Returns:\n Element: UI Element\n\n Raises:\n WDAElementNo... | class Selector(object):
def __init__(self, httpclient, session,
predicate=None,
id=None,
className=None, type=None,
name=None, nameContains=None, nameMatches=None,
text=None, textContains=None, textMatches=None,
value=None, valueContains=None,
label=None, labelContains=None,
visible=None, enabled=None,
classChain=None,
xpath=None,
parent_class_chains=[],
timeout=10.0,
index=0):
'''
Args:
predicate (str): predicate string
id (str): raw identifier
className (str): attr of className
type (str): alias of className
name (str): attr for name
nameContains (str): attr of name contains
nameMatches (str): regex string
text (str): alias of name
textContains (str): alias of nameContains
textMatches (str): alias of nameMatches
value (str): attr of value, not used in most times
valueContains (str): attr of value contains
label (str): attr for label
labelContains (str): attr for label contains
visible (bool): is visible
enabled (bool): is enabled
classChain (str): string of ios chain query, eg: **/XCUIElementTypeOther[`value BEGINSWITH 'blabla'`]
xpath (str): xpath string, a little slow, but works fine
timeout (float): maxium wait element time, default 10.0s
index (int): index of founded elements
WDA use two key to find elements "using", "value"
Examples:
"using" can be on of
"partial link text", "link text"
"name", "id", "accessibility id"
"class name", "class chain", "xpath", "predicate string"
predicate string support many keys
UID,
accessibilityContainer,
accessible,
enabled,
frame,
label,
name,
rect,
type,
value,
visible,
wdAccessibilityContainer,
wdAccessible,
wdEnabled,
wdFrame,
wdLabel,
wdName,
wdRect,
wdType,
wdUID,
wdValue,
wdVisible
'''
self.http = httpclient
self.session = session
self.predicate = predicate
self.id = id
self.class_name = className or type
self.name = self._add_escape_character_for_quote_prime_character(name or text)
self.name_part = nameContains or textContains
self.name_regex = nameMatches or textMatches
self.value = value
self.value_part = valueContains
self.label = label
self.label_part = labelContains
self.enabled = enabled
self.visible = visible
self.index = index
self.xpath = self._fix_xcui_type(xpath)
self.class_chain = self._fix_xcui_type(classChain)
self.timeout = timeout
# some fixtures
if self.class_name and not self.class_name.startswith('XCUIElementType'):
self.class_name = 'XCUIElementType'+self.class_name
if self.name_regex:
if not self.name_regex.startswith('^') and not self.name_regex.startswith('.*'):
self.name_regex = '.*' + self.name_regex
if not self.name_regex.endswith('$') and not self.name_regex.endswith('.*'):
self.name_regex = self.name_regex + '.*'
self.parent_class_chains = parent_class_chains
def _fix_xcui_type(self, s):
if s is None:
return
re_element = '|'.join(xcui_element_types.ELEMENTS)
return re.sub(r'/('+re_element+')', '/XCUIElementType\g<1>', s)
def _add_escape_character_for_quote_prime_character(self, text):
"""
Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text
"""
if text is not None:
if "'" in text:
return text.replace("'","\\'")
elif '"' in text:
return text.replace('"','\\"')
else:
return text
else:
return text
def _wdasearch(self, using, value):
"""
Returns:
element_ids (list(string)): example ['id1', 'id2']
HTTP example response:
[
{"ELEMENT": "E2FF5B2A-DBDF-4E67-9179-91609480D80A"},
{"ELEMENT": "597B1A1E-70B9-4CBE-ACAD-40943B0A6034"}
]
"""
element_ids = []
for v in self.http.post('/elements', {'using': using, 'value': value}).value:
element_ids.append(v['ELEMENT'])
return element_ids
def _gen_class_chain(self):
# just return if aleady exists predicate
if self.predicate:
return '/XCUIElementTypeAny[`' + self.predicate + '`]'
qs = []
if self.name:
qs.append("name == '%s'" % self.name)
if self.name_part:
qs.append("name CONTAINS '%s'" % self.name_part)
if self.name_regex:
qs.append("name MATCHES '%s'" % self.name_regex.encode('unicode_escape'))
if self.label:
qs.append("label == '%s'" % self.label)
if self.label_part:
qs.append("label CONTAINS '%s'" % self.label_part)
if self.value:
qs.append("value == '%s'" % self.value)
if self.value_part:
qs.append("value CONTAINS ’%s'" % self.value_part)
if self.visible is not None:
qs.append("visible == %s" % 'true' if self.visible else 'false')
if self.enabled is not None:
qs.append("enabled == %s" % 'true' if self.enabled else 'false')
predicate = ' AND '.join(qs)
chain = '/' + (self.class_name or 'XCUIElementTypeAny')
if predicate:
chain = chain + '[`' + predicate + '`]'
if self.index:
chain = chain + '[%d]' % self.index
return chain
def find_element_ids(self):
elems = []
if self.id:
return self._wdasearch('id', self.id)
if self.predicate:
return self._wdasearch('predicate string', self.predicate)
if self.xpath:
return self._wdasearch('xpath', self.xpath)
if self.class_chain:
return self._wdasearch('class chain', self.class_chain)
chain = '**' + ''.join(self.parent_class_chains) + self._gen_class_chain()
if DEBUG:
print('CHAIN:', chain)
return self._wdasearch('class chain', chain)
def find_elements(self):
"""
Returns:
Element (list): all the elements
"""
es = []
for element_id in self.find_element_ids():
e = Element(self.http.new_client(''), element_id)
es.append(e)
return es
def count(self):
return len(self.find_element_ids())
def get(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None
"""
start_time = time.time()
if timeout is None:
timeout = self.timeout
while True:
elems = self.find_elements()
if len(elems) > 0:
return elems[0]
if start_time + timeout < time.time():
break
time.sleep(0.01)
# check alert again
if self.session.alert.exists and self.http.alert_callback:
self.http.alert_callback()
return self.get(timeout, raise_error)
if raise_error:
raise WDAElementNotFoundError("element not found")
def __getattr__(self, oper):
return getattr(self.get(), oper)
def set_timeout(self, s):
"""
Set element wait timeout
"""
self.timeout = s
return self
def __getitem__(self, index):
self.index = index
return self
def child(self, *args, **kwargs):
chain = self._gen_class_chain()
kwargs['parent_class_chains'] = self.parent_class_chains + [chain]
return Selector(self.http, self.session, *args, **kwargs)
@property
def exists(self):
return len(self.find_element_ids()) > self.index
def click_exists(self, timeout=0):
"""
Wait element and perform click
Args:
timeout (float): timeout for wait
Returns:
bool: if successfully clicked
"""
e = self.get(timeout=timeout, raise_error=False)
if e is None:
return False
e.click()
return True
def wait(self, timeout=None, raise_error=True):
""" alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError
"""
return self.get(timeout=timeout, raise_error=raise_error)
def wait_gone(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): default timeout
raise_error (bool): return bool or raise error
Returns:
bool: works when raise_error is False
Raises:
WDAElementNotDisappearError
"""
start_time = time.time()
if timeout is None or timeout <= 0:
timeout = self.timeout
while start_time + timeout > time.time():
if not self.exists:
return True
if not raise_error:
return False
raise WDAElementNotDisappearError("element not gone")
|
openatx/facebook-wda | wda/__init__.py | Selector.wait_gone | python | def wait_gone(self, timeout=None, raise_error=True):
start_time = time.time()
if timeout is None or timeout <= 0:
timeout = self.timeout
while start_time + timeout > time.time():
if not self.exists:
return True
if not raise_error:
return False
raise WDAElementNotDisappearError("element not gone") | Args:
timeout (float): default timeout
raise_error (bool): return bool or raise error
Returns:
bool: works when raise_error is False
Raises:
WDAElementNotDisappearError | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L882-L902 | null | class Selector(object):
def __init__(self, httpclient, session,
predicate=None,
id=None,
className=None, type=None,
name=None, nameContains=None, nameMatches=None,
text=None, textContains=None, textMatches=None,
value=None, valueContains=None,
label=None, labelContains=None,
visible=None, enabled=None,
classChain=None,
xpath=None,
parent_class_chains=[],
timeout=10.0,
index=0):
'''
Args:
predicate (str): predicate string
id (str): raw identifier
className (str): attr of className
type (str): alias of className
name (str): attr for name
nameContains (str): attr of name contains
nameMatches (str): regex string
text (str): alias of name
textContains (str): alias of nameContains
textMatches (str): alias of nameMatches
value (str): attr of value, not used in most times
valueContains (str): attr of value contains
label (str): attr for label
labelContains (str): attr for label contains
visible (bool): is visible
enabled (bool): is enabled
classChain (str): string of ios chain query, eg: **/XCUIElementTypeOther[`value BEGINSWITH 'blabla'`]
xpath (str): xpath string, a little slow, but works fine
timeout (float): maxium wait element time, default 10.0s
index (int): index of founded elements
WDA use two key to find elements "using", "value"
Examples:
"using" can be on of
"partial link text", "link text"
"name", "id", "accessibility id"
"class name", "class chain", "xpath", "predicate string"
predicate string support many keys
UID,
accessibilityContainer,
accessible,
enabled,
frame,
label,
name,
rect,
type,
value,
visible,
wdAccessibilityContainer,
wdAccessible,
wdEnabled,
wdFrame,
wdLabel,
wdName,
wdRect,
wdType,
wdUID,
wdValue,
wdVisible
'''
self.http = httpclient
self.session = session
self.predicate = predicate
self.id = id
self.class_name = className or type
self.name = self._add_escape_character_for_quote_prime_character(name or text)
self.name_part = nameContains or textContains
self.name_regex = nameMatches or textMatches
self.value = value
self.value_part = valueContains
self.label = label
self.label_part = labelContains
self.enabled = enabled
self.visible = visible
self.index = index
self.xpath = self._fix_xcui_type(xpath)
self.class_chain = self._fix_xcui_type(classChain)
self.timeout = timeout
# some fixtures
if self.class_name and not self.class_name.startswith('XCUIElementType'):
self.class_name = 'XCUIElementType'+self.class_name
if self.name_regex:
if not self.name_regex.startswith('^') and not self.name_regex.startswith('.*'):
self.name_regex = '.*' + self.name_regex
if not self.name_regex.endswith('$') and not self.name_regex.endswith('.*'):
self.name_regex = self.name_regex + '.*'
self.parent_class_chains = parent_class_chains
def _fix_xcui_type(self, s):
if s is None:
return
re_element = '|'.join(xcui_element_types.ELEMENTS)
return re.sub(r'/('+re_element+')', '/XCUIElementType\g<1>', s)
def _add_escape_character_for_quote_prime_character(self, text):
"""
Fix for https://github.com/openatx/facebook-wda/issues/33
Returns:
string with properly formated quotes, or non changed text
"""
if text is not None:
if "'" in text:
return text.replace("'","\\'")
elif '"' in text:
return text.replace('"','\\"')
else:
return text
else:
return text
def _wdasearch(self, using, value):
"""
Returns:
element_ids (list(string)): example ['id1', 'id2']
HTTP example response:
[
{"ELEMENT": "E2FF5B2A-DBDF-4E67-9179-91609480D80A"},
{"ELEMENT": "597B1A1E-70B9-4CBE-ACAD-40943B0A6034"}
]
"""
element_ids = []
for v in self.http.post('/elements', {'using': using, 'value': value}).value:
element_ids.append(v['ELEMENT'])
return element_ids
def _gen_class_chain(self):
# just return if aleady exists predicate
if self.predicate:
return '/XCUIElementTypeAny[`' + self.predicate + '`]'
qs = []
if self.name:
qs.append("name == '%s'" % self.name)
if self.name_part:
qs.append("name CONTAINS '%s'" % self.name_part)
if self.name_regex:
qs.append("name MATCHES '%s'" % self.name_regex.encode('unicode_escape'))
if self.label:
qs.append("label == '%s'" % self.label)
if self.label_part:
qs.append("label CONTAINS '%s'" % self.label_part)
if self.value:
qs.append("value == '%s'" % self.value)
if self.value_part:
qs.append("value CONTAINS ’%s'" % self.value_part)
if self.visible is not None:
qs.append("visible == %s" % 'true' if self.visible else 'false')
if self.enabled is not None:
qs.append("enabled == %s" % 'true' if self.enabled else 'false')
predicate = ' AND '.join(qs)
chain = '/' + (self.class_name or 'XCUIElementTypeAny')
if predicate:
chain = chain + '[`' + predicate + '`]'
if self.index:
chain = chain + '[%d]' % self.index
return chain
def find_element_ids(self):
elems = []
if self.id:
return self._wdasearch('id', self.id)
if self.predicate:
return self._wdasearch('predicate string', self.predicate)
if self.xpath:
return self._wdasearch('xpath', self.xpath)
if self.class_chain:
return self._wdasearch('class chain', self.class_chain)
chain = '**' + ''.join(self.parent_class_chains) + self._gen_class_chain()
if DEBUG:
print('CHAIN:', chain)
return self._wdasearch('class chain', chain)
def find_elements(self):
"""
Returns:
Element (list): all the elements
"""
es = []
for element_id in self.find_element_ids():
e = Element(self.http.new_client(''), element_id)
es.append(e)
return es
def count(self):
return len(self.find_element_ids())
def get(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): timeout for query element, unit seconds
Default 10s
raise_error (bool): whether to raise error if element not found
Returns:
Element: UI Element
Raises:
WDAElementNotFoundError if raise_error is True else None
"""
start_time = time.time()
if timeout is None:
timeout = self.timeout
while True:
elems = self.find_elements()
if len(elems) > 0:
return elems[0]
if start_time + timeout < time.time():
break
time.sleep(0.01)
# check alert again
if self.session.alert.exists and self.http.alert_callback:
self.http.alert_callback()
return self.get(timeout, raise_error)
if raise_error:
raise WDAElementNotFoundError("element not found")
def __getattr__(self, oper):
return getattr(self.get(), oper)
def set_timeout(self, s):
"""
Set element wait timeout
"""
self.timeout = s
return self
def __getitem__(self, index):
self.index = index
return self
def child(self, *args, **kwargs):
chain = self._gen_class_chain()
kwargs['parent_class_chains'] = self.parent_class_chains + [chain]
return Selector(self.http, self.session, *args, **kwargs)
@property
def exists(self):
return len(self.find_element_ids()) > self.index
def click_exists(self, timeout=0):
"""
Wait element and perform click
Args:
timeout (float): timeout for wait
Returns:
bool: if successfully clicked
"""
e = self.get(timeout=timeout, raise_error=False)
if e is None:
return False
e.click()
return True
def wait(self, timeout=None, raise_error=True):
""" alias of get
Args:
timeout (float): timeout seconds
raise_error (bool): default true, whether to raise error if element not found
Raises:
WDAElementNotFoundError
"""
return self.get(timeout=timeout, raise_error=raise_error)
def wait_gone(self, timeout=None, raise_error=True):
"""
Args:
timeout (float): default timeout
raise_error (bool): return bool or raise error
Returns:
bool: works when raise_error is False
Raises:
WDAElementNotDisappearError
"""
start_time = time.time()
if timeout is None or timeout <= 0:
timeout = self.timeout
while start_time + timeout > time.time():
if not self.exists:
return True
if not raise_error:
return False
raise WDAElementNotDisappearError("element not gone")
|
openatx/facebook-wda | wda/__init__.py | Element.scroll | python | def scroll(self, direction='visible', distance=1.0):
if direction == 'visible':
self._wda_req('post', '/scroll', {'toVisible': True})
elif direction in ['up', 'down', 'left', 'right']:
self._wda_req('post', '/scroll', {'direction': direction, 'distance': distance})
else:
raise ValueError("Invalid direction")
return self | Args:
direction (str): one of "visible", "up", "down", "left", "right"
distance (float): swipe distance, only works when direction is not "visible"
Raises:
ValueError
distance=1.0 means, element (width or height) multiply 1.0 | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L1013-L1030 | [
"def _wda_req(self, method, url, data=None):\n return self.http.fetch(method, '/wda/element/'+self.id+url, data)\n"
] | class Element(object):
def __init__(self, httpclient, id):
"""
base_url eg: http://localhost:8100/session/$SESSION_ID
"""
self.http = httpclient
self._id = id
def __repr__(self):
return '<wda.Element(id="{}")>'.format(self.id)
def _req(self, method, url, data=None):
return self.http.fetch(method, '/element/'+self.id+url, data)
def _wda_req(self, method, url, data=None):
return self.http.fetch(method, '/wda/element/'+self.id+url, data)
def _prop(self, key):
return self._req('get', '/'+key.lstrip('/')).value
def _wda_prop(self, key):
ret = self._request('GET', 'wda/element/%s/%s' %(self._id, key)).value
return ret
@property
def id(self):
return self._id
@property
def label(self):
return self._prop('attribute/label')
@property
def className(self):
return self._prop('attribute/type')
@property
def text(self):
return self._prop('text')
@property
def name(self):
return self._prop('name')
@property
def displayed(self):
return self._prop("displayed")
@property
def enabled(self):
return self._prop('enabled')
@property
def accessible(self):
return self._wda_prop("accessible")
@property
def accessibility_container(self):
return self._wda_prop('accessibilityContainer')
@property
def value(self):
return self._prop('attribute/value')
@property
def enabled(self):
return self._prop('enabled')
@property
def visible(self):
return self._prop('attribute/visible')
@property
def bounds(self):
value = self._prop('rect')
x, y = value['x'], value['y']
w, h = value['width'], value['height']
return Rect(x, y, w, h)
# operations
def tap(self):
return self._req('post', '/click')
def click(self):
""" Alias of tap """
return self.tap()
def tap_hold(self, duration=1.0):
"""
Tap and hold for a moment
Args:
duration (float): seconds of hold time
[[FBRoute POST:@"/wda/element/:uuid/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHold:)],
"""
return self._wda_req('post', '/touchAndHold', {'duration': duration})
def scroll(self, direction='visible', distance=1.0):
"""
Args:
direction (str): one of "visible", "up", "down", "left", "right"
distance (float): swipe distance, only works when direction is not "visible"
Raises:
ValueError
distance=1.0 means, element (width or height) multiply 1.0
"""
if direction == 'visible':
self._wda_req('post', '/scroll', {'toVisible': True})
elif direction in ['up', 'down', 'left', 'right']:
self._wda_req('post', '/scroll', {'direction': direction, 'distance': distance})
else:
raise ValueError("Invalid direction")
return self
def pinch(self, scale, velocity):
"""
Args:
scale (float): scale must > 0
velocity (float): velocity must be less than zero when scale is less than 1
Example:
pinchIn -> scale:0.5, velocity: -1
pinchOut -> scale:2.0, velocity: 1
"""
data = {'scale': scale, 'velocity': velocity}
return self._wda_req('post', '/pinch', data)
def set_text(self, value):
return self._req('post', '/value', {'value': value})
def clear_text(self):
return self._req('post', '/clear')
|
openatx/facebook-wda | wda/__init__.py | Element.pinch | python | def pinch(self, scale, velocity):
data = {'scale': scale, 'velocity': velocity}
return self._wda_req('post', '/pinch', data) | Args:
scale (float): scale must > 0
velocity (float): velocity must be less than zero when scale is less than 1
Example:
pinchIn -> scale:0.5, velocity: -1
pinchOut -> scale:2.0, velocity: 1 | train | https://github.com/openatx/facebook-wda/blob/aa644204620c6d5c7705a9c7452d8c0cc39330d5/wda/__init__.py#L1032-L1043 | [
"def _wda_req(self, method, url, data=None):\n return self.http.fetch(method, '/wda/element/'+self.id+url, data)\n"
] | class Element(object):
def __init__(self, httpclient, id):
"""
base_url eg: http://localhost:8100/session/$SESSION_ID
"""
self.http = httpclient
self._id = id
def __repr__(self):
return '<wda.Element(id="{}")>'.format(self.id)
def _req(self, method, url, data=None):
return self.http.fetch(method, '/element/'+self.id+url, data)
def _wda_req(self, method, url, data=None):
return self.http.fetch(method, '/wda/element/'+self.id+url, data)
def _prop(self, key):
return self._req('get', '/'+key.lstrip('/')).value
def _wda_prop(self, key):
ret = self._request('GET', 'wda/element/%s/%s' %(self._id, key)).value
return ret
@property
def id(self):
return self._id
@property
def label(self):
return self._prop('attribute/label')
@property
def className(self):
return self._prop('attribute/type')
@property
def text(self):
return self._prop('text')
@property
def name(self):
return self._prop('name')
@property
def displayed(self):
return self._prop("displayed")
@property
def enabled(self):
return self._prop('enabled')
@property
def accessible(self):
return self._wda_prop("accessible")
@property
def accessibility_container(self):
return self._wda_prop('accessibilityContainer')
@property
def value(self):
return self._prop('attribute/value')
@property
def enabled(self):
return self._prop('enabled')
@property
def visible(self):
return self._prop('attribute/visible')
@property
def bounds(self):
value = self._prop('rect')
x, y = value['x'], value['y']
w, h = value['width'], value['height']
return Rect(x, y, w, h)
# operations
def tap(self):
return self._req('post', '/click')
def click(self):
""" Alias of tap """
return self.tap()
def tap_hold(self, duration=1.0):
"""
Tap and hold for a moment
Args:
duration (float): seconds of hold time
[[FBRoute POST:@"/wda/element/:uuid/touchAndHold"] respondWithTarget:self action:@selector(handleTouchAndHold:)],
"""
return self._wda_req('post', '/touchAndHold', {'duration': duration})
def scroll(self, direction='visible', distance=1.0):
"""
Args:
direction (str): one of "visible", "up", "down", "left", "right"
distance (float): swipe distance, only works when direction is not "visible"
Raises:
ValueError
distance=1.0 means, element (width or height) multiply 1.0
"""
if direction == 'visible':
self._wda_req('post', '/scroll', {'toVisible': True})
elif direction in ['up', 'down', 'left', 'right']:
self._wda_req('post', '/scroll', {'direction': direction, 'distance': distance})
else:
raise ValueError("Invalid direction")
return self
def pinch(self, scale, velocity):
"""
Args:
scale (float): scale must > 0
velocity (float): velocity must be less than zero when scale is less than 1
Example:
pinchIn -> scale:0.5, velocity: -1
pinchOut -> scale:2.0, velocity: 1
"""
data = {'scale': scale, 'velocity': velocity}
return self._wda_req('post', '/pinch', data)
def set_text(self, value):
return self._req('post', '/value', {'value': value})
def clear_text(self):
return self._req('post', '/clear')
|
ets-labs/python-dependency-injector | examples/containers/dynamic_runtime_creation.py | import_cls | python | def import_cls(cls_name):
path_components = cls_name.split('.')
module = __import__('.'.join(path_components[:-1]),
locals(),
globals(),
fromlist=path_components[-1:])
return getattr(module, path_components[-1]) | Import class by its fully qualified name.
In terms of current example it is just a small helper function. Please,
don't use it in production approaches. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/containers/dynamic_runtime_creation.py#L13-L24 | null | """Creation of dynamic container based on some configuration example."""
import collections
import dependency_injector.containers as containers
# Defining several example services:
UsersService = collections.namedtuple('UsersService', [])
AuthService = collections.namedtuple('AuthService', [])
# "Parsing" some configuration:
config = {
'services': {
'users': {
'class': '__main__.UsersService',
'provider_class': 'dependency_injector.providers.Factory',
},
'auth': {
'class': '__main__.AuthService',
'provider_class': 'dependency_injector.providers.Factory',
}
}
}
# Creating empty container of service providers:
services = containers.DynamicContainer()
# Filling dynamic container with service providers using configuration:
for service_name, service_info in config['services'].iteritems():
# Runtime importing of service and service provider classes:
service_cls = import_cls(service_info['class'])
service_provider_cls = import_cls(service_info['provider_class'])
# Binding service provider to the dynamic service providers catalog:
setattr(services, service_name, service_provider_cls(service_cls))
# Creating some objects:
users_service = services.users()
auth_service = services.auth()
# Making some asserts:
assert isinstance(users_service, UsersService)
assert isinstance(auth_service, AuthService)
|
ets-labs/python-dependency-injector | examples/miniapps/services_v1/example/main.py | main | python | def main(uid, password, photo, users_service, auth_service, photos_service):
user = users_service.get_user_by_id(uid)
auth_service.authenticate(user, password)
photos_service.upload_photo(user['uid'], photo) | Authenticate user and upload photo. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/services_v1/example/main.py#L4-L8 | null | """Example main module."""
|
ets-labs/python-dependency-injector | examples/miniapps/use_cases/example/use_cases.py | SignupUseCase.execute | python | def execute(self, email):
print('Sign up user {0}'.format(email))
self.email_sender.send(email, 'Welcome, "{}"'.format(email)) | Execute use case handling. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/use_cases/example/use_cases.py#L19-L22 | null | class SignupUseCase(object):
"""Sign up use cases registers users."""
def __init__(self, email_sender):
"""Initializer."""
self.email_sender = email_sender
|
ets-labs/python-dependency-injector | examples/speech/inject.py | main | python | def main(car_factory, extra_engine):
car1 = car_factory(serial_number=1)
car2 = car_factory(serial_number=2, engine=extra_engine)
assert car1.serial_number == 1 and car2.serial_number == 2
assert car1.engine is not car2.engine
assert car2.engine is extra_engine | Run application. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/speech/inject.py#L10-L17 | null | """@inject decorator example."""
from container import Container
from dependency_injector.injections import inject
@inject(car_factory=Container.car_factory.delegate())
@inject(extra_engine=Container.engine_factory)
if __name__ == '__main__':
main()
|
ets-labs/python-dependency-injector | examples/miniapps/movie_lister/movies/finders.py | CsvMovieFinder.find_all | python | def find_all(self):
with open(self._csv_file_path) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=self._delimiter)
return [self._movie_model(*row) for row in csv_reader] | Return all found movies.
:rtype: list[movies.models.Movie]
:return: List of movie instances. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/movie_lister/movies/finders.py#L52-L60 | null | class CsvMovieFinder(MovieFinder):
"""Movie finder that fetches movies data from csv file."""
def __init__(self, movie_model, csv_file_path, delimiter):
"""Initializer.
:param movie_model: Movie model's factory
:type movie_model: movies.models.Movie
:param csv_file_path: Path to csv file with movies data
:type csv_file_path: str
:param delimiter: Csv file's delimiter
:type delimiter: str
"""
self._csv_file_path = csv_file_path
self._delimiter = delimiter
super(CsvMovieFinder, self).__init__(movie_model)
|
ets-labs/python-dependency-injector | examples/miniapps/movie_lister/movies/finders.py | SqliteMovieFinder.find_all | python | def find_all(self):
with self._database:
rows = self._database.execute('SELECT name, year, director '
'FROM movies')
return [self._movie_model(*row) for row in rows] | Return all found movies.
:rtype: list[movies.models.Movie]
:return: List of movie instances. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/movie_lister/movies/finders.py#L78-L87 | null | class SqliteMovieFinder(MovieFinder):
"""Movie finder that fetches movies data from sqlite database."""
def __init__(self, movie_model, database):
"""Initializer.
:param movie_model: Movie model's factory
:type movie_model: (object) -> movies.models.Movie
:param database: Connection to sqlite database with movies data
:type database: sqlite3.Connection
"""
self._database = database
super(SqliteMovieFinder, self).__init__(movie_model)
|
ets-labs/python-dependency-injector | examples/providers/overriding_users_model.py | UsersService.get_by_id | python | def get_by_id(self, id):
return self.user_cls(id=id, password='secret' + str(id)) | Find user by his id and return user model. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/providers/overriding_users_model.py#L24-L26 | null | class UsersService(object):
"""Example class UsersService."""
def __init__(self, user_cls):
"""Initializer."""
self.user_cls = user_cls
super(UsersService, self).__init__()
|
ets-labs/python-dependency-injector | examples/providers/overriding_users_model.py | ExtendedUsersService.get_by_id | python | def get_by_id(self, id):
user = super(ExtendedUsersService, self).get_by_id(id)
user.first_name = 'John' + str(id)
user.last_name = 'Smith' + str(id)
user.gender = 'male'
return user | Find user by his id and return user model. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/providers/overriding_users_model.py#L65-L71 | null | class ExtendedUsersService(UsersService):
"""Example class ExtendedUsersService."""
|
ets-labs/python-dependency-injector | examples/miniapps/services_v1/example/services.py | UsersService.get_user_by_id | python | def get_user_by_id(self, uid):
self.logger.debug('User %s has been found in database', uid)
return dict(uid=uid, password_hash='secret_hash') | Return user's data by identifier. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/services_v1/example/services.py#L16-L19 | null | class UsersService(BaseService):
"""Users service."""
def __init__(self, logger, db):
"""Initializer."""
self.logger = logger
self.db = db
|
ets-labs/python-dependency-injector | examples/miniapps/services_v1/example/services.py | AuthService.authenticate | python | def authenticate(self, user, password):
assert user['password_hash'] == '_'.join((password, 'hash'))
self.logger.debug('User %s has been successfully authenticated',
user['uid']) | Authenticate user. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/services_v1/example/services.py#L31-L35 | null | class AuthService(BaseService):
"""Authentication service."""
def __init__(self, logger, db, token_ttl):
"""Initializer."""
self.logger = logger
self.db = db
self.token_ttl = token_ttl
|
ets-labs/python-dependency-injector | examples/miniapps/mail_service/example.py | MailService.send | python | def send(self, email, body):
print('Connecting server {0}:{1} with {2}:{3}'.format(
self._host, self._port, self._login, self._password))
print('Sending "{0}" to "{1}"'.format(body, email)) | Send email. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/mail_service/example.py#L22-L26 | null | class MailService(AbstractMailService):
"""Mail service."""
def __init__(self, host, port, login, password):
"""Initializer."""
self._host = host
self._port = port
self._login = login
self._password = password
|
ets-labs/python-dependency-injector | examples/providers/factory_delegation.py | User.main_photo | python | def main_photo(self):
if not self._main_photo:
self._main_photo = self.photos_factory()
return self._main_photo | Return user's main photo. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/providers/factory_delegation.py#L20-L24 | null | class User(object):
"""Example user model."""
def __init__(self, photos_factory):
"""Initializer."""
self.photos_factory = photos_factory
self._main_photo = None
@property
|
ets-labs/python-dependency-injector | examples/miniapps/movie_lister/example/main.py | main | python | def main(movie_lister):
print(movie_lister.movies_directed_by('Francis Lawrence'))
print(movie_lister.movies_directed_by('Patricia Riggen'))
print(movie_lister.movies_directed_by('JJ Abrams'))
print(movie_lister.movies_released_in(2015)) | Run application.
This program prints info about all movies that were directed by different
persons and then prints all movies that were released in 2015.
:param movie_lister: Movie lister instance
:type movie_lister: movies.listers.MovieLister | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/movie_lister/example/main.py#L4-L17 | null | """Example main module."""
|
ets-labs/python-dependency-injector | examples/miniapps/movie_lister/example/db.py | init_sqlite | python | def init_sqlite(movies_data, database):
with database:
database.execute('CREATE TABLE IF NOT EXISTS movies '
'(name text, year int, director text)')
database.execute('DELETE FROM movies')
database.executemany('INSERT INTO movies VALUES (?,?,?)', movies_data) | Initialize sqlite3 movies database.
:param movies_data: Data about movies
:type movies_data: tuple[tuple]
:param database: Connection to sqlite database with movies data
:type database: sqlite3.Connection | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/movie_lister/example/db.py#L6-L19 | null | """Example database module."""
import csv
def init_csv(movies_data, csv_file_path, delimiter):
"""Initialize csv movies database.
:param movies_data: Data about movies
:type movies_data: tuple[tuple]
:param csv_file_path: Path to csv file with movies data
:type csv_file_path: str
:param delimiter: Csv file's delimiter
:type delimiter: str
"""
with open(csv_file_path, 'w') as csv_file:
csv.writer(csv_file, delimiter=delimiter).writerows(movies_data)
|
ets-labs/python-dependency-injector | examples/miniapps/movie_lister/example/db.py | init_csv | python | def init_csv(movies_data, csv_file_path, delimiter):
with open(csv_file_path, 'w') as csv_file:
csv.writer(csv_file, delimiter=delimiter).writerows(movies_data) | Initialize csv movies database.
:param movies_data: Data about movies
:type movies_data: tuple[tuple]
:param csv_file_path: Path to csv file with movies data
:type csv_file_path: str
:param delimiter: Csv file's delimiter
:type delimiter: str | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/miniapps/movie_lister/example/db.py#L22-L35 | null | """Example database module."""
import csv
def init_sqlite(movies_data, database):
"""Initialize sqlite3 movies database.
:param movies_data: Data about movies
:type movies_data: tuple[tuple]
:param database: Connection to sqlite database with movies data
:type database: sqlite3.Connection
"""
with database:
database.execute('CREATE TABLE IF NOT EXISTS movies '
'(name text, year int, director text)')
database.execute('DELETE FROM movies')
database.executemany('INSERT INTO movies VALUES (?,?,?)', movies_data)
|
ets-labs/python-dependency-injector | examples/providers/factory_aggregate/games.py | Game.play | python | def play(self):
print('{0} and {1} are playing {2}'.format(
self.player1, self.player2, self.__class__.__name__.lower())) | Play game. | train | https://github.com/ets-labs/python-dependency-injector/blob/d04fe41eb17f667da38b97525e2d16c8f2d272fe/examples/providers/factory_aggregate/games.py#L12-L15 | null | class Game(object):
"""Base game class."""
def __init__(self, player1, player2):
"""Initializer."""
self.player1 = player1
self.player2 = player2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.