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
ttroy50/pyephember
pyephember/pyephember.py
EphEmber._request_token
python
def _request_token(self, force=False): if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True
Request a new auth token
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L41-L75
null
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber._login
python
def _login(self): headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False
Login using username / password and get the first auth token
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L77-L109
null
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.get_home
python
def get_home(self, home_id=None): now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home
Get the data about a home
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L121-L162
[ "def _do_auth(self):\n \"\"\"\n Do authentication to the system (if required)\n \"\"\"\n if self.login_data is None:\n return self._login()\n\n return self._request_token()\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.get_zones
python
def get_zones(self): home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones
Get all zones
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L164-L178
[ "def get_home(self, home_id=None):\n \"\"\"\n Get the data about a home\n \"\"\"\n now = datetime.datetime.utcnow()\n if self.home and now < self.home_refresh_at:\n return self.home\n\n if not self._do_auth():\n raise RuntimeError(\"Unable to login\")\n\n if home_id is None:\n home_id = self.home_id\n\n url = self.api_base_url + \"Home/GetHomeById\"\n\n params = {\n \"homeId\": home_id\n }\n\n headers = {\n \"Accept\": \"application/json\",\n 'Authorization':\n 'bearer ' + self.login_data['token']['accessToken']\n }\n\n response = requests.get(\n url, params=params, headers=headers, timeout=10)\n\n if response.status_code != 200:\n raise RuntimeError(\n \"{} response code when getting home\".format(\n response.status_code))\n\n home = response.json()\n\n if self.cache_home:\n self.home = home\n self.home_refresh_at = (datetime.datetime.utcnow()\n + datetime.timedelta(minutes=5))\n\n return home\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.get_zone_names
python
def get_zone_names(self): zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names
Get the name of all zones
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L180-L188
[ "def get_zones(self):\n \"\"\"\n Get all zones\n \"\"\"\n home_data = self.get_home()\n if not home_data['isSuccess']:\n return []\n\n zones = []\n\n for receiver in home_data['data']['receivers']:\n for zone in receiver['zones']:\n zones.append(zone)\n\n return zones\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.get_zone
python
def get_zone(self, zone_name): for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone")
Get the information about a particular zone
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L190-L198
[ "def get_zones(self):\n \"\"\"\n Get all zones\n \"\"\"\n home_data = self.get_home()\n if not home_data['isSuccess']:\n return []\n\n zones = []\n\n for receiver in home_data['data']['receivers']:\n for zone in receiver['zones']:\n zones.append(zone)\n\n return zones\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.is_zone_active
python
def is_zone_active(self, zone_name): zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive']
Check if a zone is active
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L200-L208
[ "def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.get_zone_temperature
python
def get_zone_temperature(self, zone_name): zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature']
Get the temperature for a zone
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L210-L219
[ "def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.is_boost_active
python
def is_boost_active(self, zone_name): zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive']
Check if a zone is active
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L221-L230
[ "def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.is_target_temperature_reached
python
def is_target_temperature_reached(self, zone_name): zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached']
Check if a zone is active
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L232-L241
[ "def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.set_target_temperature_by_id
python
def set_target_temperature_by_id(self, zone_id, target_temperature): if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False)
Set the target temperature for a zone by id
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L243-L272
[ "def _do_auth(self):\n \"\"\"\n Do authentication to the system (if required)\n \"\"\"\n if self.login_data is None:\n return self._login()\n\n return self._request_token()\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.set_target_temperture_by_name
python
def set_target_temperture_by_name(self, zone_name, target_temperature): zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature)
Set the target temperature for a zone by name
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L274-L284
[ "def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n", "def set_target_temperature_by_id(self, zone_id, target_temperature):\n \"\"\"\n Set the target temperature for a zone by id\n \"\"\"\n if not self._do_auth():\n raise RuntimeError(\"Unable to login\")\n\n data = {\n \"ZoneId\": zone_id,\n \"TargetTemperature\": target_temperature\n }\n\n headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n 'Authorization':\n 'Bearer ' + self.login_data['token']['accessToken']\n }\n\n url = self.api_base_url + \"Home/ZoneTargetTemperature\"\n\n response = requests.post(url, data=json.dumps(\n data), headers=headers, timeout=10)\n\n if response.status_code != 200:\n return False\n\n zone_change_data = response.json()\n\n return zone_change_data.get(\"isSuccess\", False)\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.activate_boost_by_id
python
def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False)
Activate boost for a zone based on the numeric id
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L286-L317
[ "def _do_auth(self):\n \"\"\"\n Do authentication to the system (if required)\n \"\"\"\n if self.login_data is None:\n return self._login()\n\n return self._request_token()\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.activate_boost_by_name
python
def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours)
Activate boost by the name of the zone
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L319-L332
[ "def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n", "def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1):\n \"\"\"\n Activate boost for a zone based on the numeric id\n \"\"\"\n if not self._do_auth():\n raise RuntimeError(\"Unable to login\")\n\n zones = [zone_id]\n data = {\n \"ZoneIds\": zones,\n \"NumberOfHours\": num_hours,\n \"TargetTemperature\": target_temperature\n }\n\n headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n 'Authorization':\n 'Bearer ' + self.login_data['token']['accessToken']\n }\n\n url = self.api_base_url + \"Home/ActivateZoneBoost\"\n\n response = requests.post(url, data=json.dumps(\n data), headers=headers, timeout=10)\n\n if response.status_code != 200:\n return False\n\n boost_data = response.json()\n\n return boost_data.get(\"isSuccess\", False)\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.deactivate_boost_by_name
python
def deactivate_boost_by_name(self, zone_name): zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"])
Deactivate boost by the name of the zone
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L362-L371
[ "def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n", "def deactivate_boost_by_id(self, zone_id):\n \"\"\"\n Deactivate boost for a zone based on the numeric id\n \"\"\"\n if not self._do_auth():\n raise RuntimeError(\"Unable to login\")\n\n zones = [zone_id]\n data = zones\n\n headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n 'Authorization':\n 'Bearer ' + self.login_data['token']['accessToken']\n }\n\n url = self.api_base_url + \"Home/DeActivateZoneBoost\"\n response = requests.post(url, data=json.dumps(\n data), headers=headers, timeout=10)\n\n if response.status_code != 200:\n return False\n\n boost_data = response.json()\n\n return boost_data.get(\"isSuccess\", False)\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.set_mode_by_id
python
def set_mode_by_id(self, zone_id, mode): if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False)
Set the mode by using the zone id Supported zones are available in the enum Mode
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L373-L402
[ "def _do_auth(self):\n \"\"\"\n Do authentication to the system (if required)\n \"\"\"\n if self.login_data is None:\n return self._login()\n\n return self._request_token()\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.set_mode_by_name
python
def set_mode_by_name(self, zone_name, mode): zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode)
Set the mode by using the name of the zone
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L404-L412
[ "def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n", "def set_mode_by_id(self, zone_id, mode):\n \"\"\"\n Set the mode by using the zone id\n Supported zones are available in the enum Mode\n \"\"\"\n if not self._do_auth():\n raise RuntimeError(\"Unable to login\")\n\n data = {\n \"ZoneId\": zone_id,\n \"mode\": mode.value\n }\n\n headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n 'Authorization':\n 'Bearer ' + self.login_data['token']['accessToken']\n }\n\n url = self.api_base_url + \"Home/SetZoneMode\"\n response = requests.post(url, data=json.dumps(\n data), headers=headers, timeout=10)\n\n if response.status_code != 200:\n return False\n\n mode_data = response.json()\n\n return mode_data.get(\"isSuccess\", False)\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def get_zone_mode(self, zone_name): """ Get the mode for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode']) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
ttroy50/pyephember
pyephember/pyephember.py
EphEmber.get_zone_mode
python
def get_zone_mode(self, zone_name): zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return ZoneMode(zone['mode'])
Get the mode for a zone
train
https://github.com/ttroy50/pyephember/blob/3ee159ee82b926b957dae8dcbc7a4bfb6807a9b4/pyephember/pyephember.py#L414-L423
[ "def get_zone(self, zone_name):\n \"\"\"\n Get the information about a particular zone\n \"\"\"\n for zone in self.get_zones():\n if zone_name == zone['name']:\n return zone\n\n raise RuntimeError(\"Unknown zone\")\n" ]
class EphEmber: """Interacts with a EphEmber thermostat via API. Example usage: t = EphEmber('me@somewhere.com', 'mypasswd') t.getZoneTemperature('myzone') # Get temperature """ # pylint: disable=too-many-instance-attributes def _requires_refresh_token(self): """ Check if a refresh of the token is needed """ expires_on = datetime.datetime.strptime( self.login_data['token']['expiresOn'], '%Y-%m-%dT%H:%M:%SZ') refresh = datetime.datetime.utcnow() + datetime.timedelta(seconds=30) return expires_on < refresh def _request_token(self, force=False): """ Request a new auth token """ if self.login_data is None: raise RuntimeError("Don't have a token to refresh") if not force: if not self._requires_refresh_token(): # no need to refresh as token is valid return True headers = { "Accept": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "account/RefreshToken" response = requests.get(url, headers=headers, timeout=10) if response.status_code != 200: return False refresh_data = response.json() if 'token' not in refresh_data: return False self.login_data['token']['accessToken'] = refresh_data['accessToken'] self.login_data['token']['issuedOn'] = refresh_data['issuedOn'] self.login_data['token']['expiresOn'] = refresh_data['expiresOn'] return True def _login(self): """ Login using username / password and get the first auth token """ headers = { "Content-Type": "application/x-www-form-urlencoded", "Accept": "application/json" } url = self.api_base_url + "account/directlogin" data = {'Email': self.username, 'Password': self.password, 'RememberMe': 'True'} response = requests.post(url, data=data, headers=headers, timeout=10) if response.status_code != 200: return False self.login_data = response.json() if not self.login_data['isSuccess']: self.login_data = None return False if ('token' in self.login_data and 'accessToken' in self.login_data['token']): self.home_id = self.login_data['token']['currentHomeId'] self.user_id = self.login_data['token']['userId'] return True self.login_data = None return False def _do_auth(self): """ Do authentication to the system (if required) """ if self.login_data is None: return self._login() return self._request_token() # Public interface def get_home(self, home_id=None): """ Get the data about a home """ now = datetime.datetime.utcnow() if self.home and now < self.home_refresh_at: return self.home if not self._do_auth(): raise RuntimeError("Unable to login") if home_id is None: home_id = self.home_id url = self.api_base_url + "Home/GetHomeById" params = { "homeId": home_id } headers = { "Accept": "application/json", 'Authorization': 'bearer ' + self.login_data['token']['accessToken'] } response = requests.get( url, params=params, headers=headers, timeout=10) if response.status_code != 200: raise RuntimeError( "{} response code when getting home".format( response.status_code)) home = response.json() if self.cache_home: self.home = home self.home_refresh_at = (datetime.datetime.utcnow() + datetime.timedelta(minutes=5)) return home def get_zones(self): """ Get all zones """ home_data = self.get_home() if not home_data['isSuccess']: return [] zones = [] for receiver in home_data['data']['receivers']: for zone in receiver['zones']: zones.append(zone) return zones def get_zone_names(self): """ Get the name of all zones """ zone_names = [] for zone in self.get_zones(): zone_names.append(zone['name']) return zone_names def get_zone(self, zone_name): """ Get the information about a particular zone """ for zone in self.get_zones(): if zone_name == zone['name']: return zone raise RuntimeError("Unknown zone") def is_zone_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unable to get zone") return zone['isCurrentlyActive'] def get_zone_temperature(self, zone_name): """ Get the temperature for a zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['currentTemperature'] def is_boost_active(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isBoostActive'] def is_target_temperature_reached(self, zone_name): """ Check if a zone is active """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return zone['isTargetTemperatureReached'] def set_target_temperature_by_id(self, zone_id, target_temperature): """ Set the target temperature for a zone by id """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ZoneTargetTemperature" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False zone_change_data = response.json() return zone_change_data.get("isSuccess", False) def set_target_temperture_by_name(self, zone_name, target_temperature): """ Set the target temperature for a zone by name """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_target_temperature_by_id(zone["zoneId"], target_temperature) def activate_boost_by_id(self, zone_id, target_temperature, num_hours=1): """ Activate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = { "ZoneIds": zones, "NumberOfHours": num_hours, "TargetTemperature": target_temperature } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/ActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def activate_boost_by_name(self, zone_name, target_temperature, num_hours=1): """ Activate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.activate_boost_by_id(zone["zoneId"], target_temperature, num_hours) def deactivate_boost_by_id(self, zone_id): """ Deactivate boost for a zone based on the numeric id """ if not self._do_auth(): raise RuntimeError("Unable to login") zones = [zone_id] data = zones headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/DeActivateZoneBoost" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False boost_data = response.json() return boost_data.get("isSuccess", False) def deactivate_boost_by_name(self, zone_name): """ Deactivate boost by the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.deactivate_boost_by_id(zone["zoneId"]) def set_mode_by_id(self, zone_id, mode): """ Set the mode by using the zone id Supported zones are available in the enum Mode """ if not self._do_auth(): raise RuntimeError("Unable to login") data = { "ZoneId": zone_id, "mode": mode.value } headers = { "Accept": "application/json", "Content-Type": "application/json", 'Authorization': 'Bearer ' + self.login_data['token']['accessToken'] } url = self.api_base_url + "Home/SetZoneMode" response = requests.post(url, data=json.dumps( data), headers=headers, timeout=10) if response.status_code != 200: return False mode_data = response.json() return mode_data.get("isSuccess", False) def set_mode_by_name(self, zone_name, mode): """ Set the mode by using the name of the zone """ zone = self.get_zone(zone_name) if zone is None: raise RuntimeError("Unknown zone") return self.set_mode_by_id(zone["zoneId"], mode) # Ctor def __init__(self, username, password, cache_home=False): """Performs login and save session cookie.""" # HTTPS Interface self.home_id = None self.user_id = None self.login_data = None self.username = username self.password = password self.cache_home = cache_home self.home = None self.home_refresh_at = None self.api_base_url = 'https://ember.ephcontrols.com/api/' if not self._login(): raise RuntimeError("Unable to login")
textbook/atmdb
atmdb/core.py
Service.url_builder
python
def url_builder(self, endpoint, *, root=None, params=None, url_params=None): if root is None: root = self.ROOT return ''.join([ root, endpoint, '?' + urlencode(url_params) if url_params else '', ]).format(**params or {})
Create a URL for the specified endpoint. Arguments: endpoint (:py:class:`str`): The API endpoint to access. root: (:py:class:`str`, optional): The root URL for the service API. params: (:py:class:`dict`, optional): The values for format into the created URL (defaults to ``None``). url_params: (:py:class:`dict`, optional): Parameters to add to the end of the URL (defaults to ``None``). Returns: :py:class:`str`: The resulting URL.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L40-L62
null
class Service(metaclass=ABCMeta): """Abstract base class for API wrapper services.""" REQUIRED = set() """:py:class:`set`: The service's required configuration keys.""" ROOT = '' """:py:class:`str`: The root URL for the API.""" @abstractmethod def __init__(self, *_, **kwargs): self.service_name = kwargs.get('name') @property def headers(self): """Get the headers for the service requests. Returns: :py:class:`dict`: The header mapping. """ return {} @staticmethod def calculate_timeout(http_date): """Extract request timeout from e.g. ``Retry-After`` header. Notes: Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can be either an integer number of seconds or an HTTP date. This function can handle either. Arguments: http_date (:py:class:`str`): The date to parse. Returns: :py:class:`int`: The timeout, in seconds. """ try: return int(http_date) except ValueError: date_after = parse(http_date) utc_now = datetime.now(tz=timezone.utc) return int((date_after - utc_now).total_seconds())
textbook/atmdb
atmdb/core.py
Service.calculate_timeout
python
def calculate_timeout(http_date): try: return int(http_date) except ValueError: date_after = parse(http_date) utc_now = datetime.now(tz=timezone.utc) return int((date_after - utc_now).total_seconds())
Extract request timeout from e.g. ``Retry-After`` header. Notes: Per :rfc:`2616#section-14.37`, the ``Retry-After`` header can be either an integer number of seconds or an HTTP date. This function can handle either. Arguments: http_date (:py:class:`str`): The date to parse. Returns: :py:class:`int`: The timeout, in seconds.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L65-L85
null
class Service(metaclass=ABCMeta): """Abstract base class for API wrapper services.""" REQUIRED = set() """:py:class:`set`: The service's required configuration keys.""" ROOT = '' """:py:class:`str`: The root URL for the API.""" @abstractmethod def __init__(self, *_, **kwargs): self.service_name = kwargs.get('name') @property def headers(self): """Get the headers for the service requests. Returns: :py:class:`dict`: The header mapping. """ return {} def url_builder(self, endpoint, *, root=None, params=None, url_params=None): """Create a URL for the specified endpoint. Arguments: endpoint (:py:class:`str`): The API endpoint to access. root: (:py:class:`str`, optional): The root URL for the service API. params: (:py:class:`dict`, optional): The values for format into the created URL (defaults to ``None``). url_params: (:py:class:`dict`, optional): Parameters to add to the end of the URL (defaults to ``None``). Returns: :py:class:`str`: The resulting URL. """ if root is None: root = self.ROOT return ''.join([ root, endpoint, '?' + urlencode(url_params) if url_params else '', ]).format(**params or {}) @staticmethod
textbook/atmdb
atmdb/core.py
TokenAuthMixin.from_env
python
def from_env(cls): token = getenv(cls.TOKEN_ENV_VAR) if token is None: msg = 'missing environment variable: {!r}'.format(cls.TOKEN_ENV_VAR) raise ValueError(msg) return cls(api_token=token)
Create a service instance from an environment variable.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L104-L110
null
class TokenAuthMixin: """Mix-in class for implementing token authentication. Arguments: api_token (:py:class:`str`): A valid API token. """ TOKEN_ENV_VAR = None """:py:class:`str`: The environment variable holding the token.""" def __init__(self, *, api_token, **kwargs): self.api_token = api_token super().__init__(**kwargs) @classmethod
textbook/atmdb
atmdb/core.py
UrlParamMixin.url_builder
python
def url_builder(self, endpoint, params=None, url_params=None): if url_params is None: url_params = OrderedDict() url_params[self.AUTH_PARAM] = self.api_token return super().url_builder( endpoint, params=params, url_params=url_params, )
Add authentication URL parameter.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/core.py#L119-L128
null
class UrlParamMixin(TokenAuthMixin): """Mix-in class for implementing URL parameter authentication.""" AUTH_PARAM = None """:py:class:`str`: The name of the URL parameter."""
textbook/atmdb
atmdb/models.py
BaseModel._create_image_url
python
def _create_image_url(self, file_path, type_, target_size): if self.image_config is None: logger.warning('no image configuration available') return return ''.join([ self.image_config['secure_base_url'], self._image_size(self.image_config, type_, target_size), file_path, ])
The the closest available size for specified image type. Arguments: file_path (:py:class:`str`): The image file path. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height).
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L65-L83
[ "def _image_size(image_config, type_, target_size):\n \"\"\"Find the closest available size for specified image type.\n\n Arguments:\n image_config (:py:class:`dict`): The image config data.\n type_ (:py:class:`str`): The type of image to create a URL\n for, (``'poster'`` or ``'profile'``).\n target_size (:py:class:`int`): The size of image to aim for (used\n as either width or height).\n\n \"\"\"\n return min(\n image_config['{}_sizes'.format(type_)],\n key=lambda size: (abs(target_size - int(size[1:]))\n if size.startswith('w') or size.startswith('h')\n else 999),\n )\n" ]
class BaseModel: """Base TMDb model functionality. Arguments: id_ (:py:class:`int`): The TMDb ID of the object. image_path (:py:class:`str`): The short path to the image. Attributes: image_url (:py:class:`str`): The fully-qualified image URL. """ CONTAINS = None """:py:class:`dict`: Rules for what the model contains.""" IMAGE_TYPE = None """:py:class:`str`: The type of image to use.""" JSON_MAPPING = dict(id_='id') """:py:class:`dict`: The mapping between JSON keys and attributes.""" image_config = None """:py:class:`dict`: The API image configuration.""" def __init__(self, *, id_, image_path=None, **_): self.id_ = id_ self.image_path = image_path def __contains__(self, item): if self.CONTAINS is None: return False attr = self.CONTAINS['attr'] subclasses = {obj.__name__: obj for obj in BaseModel.__subclasses__()} # pylint: disable=no-member cls = subclasses[self.CONTAINS['type']] return isinstance(item, cls) and item in getattr(self, attr) def __eq__(self, other): return isinstance(other, type(self)) and self.id_ == other.id_ def __hash__(self): return hash(self.id_) def __repr__(self): return '{}({})'.format( self.__class__.__name__, ', '.join(['{}={!r}'.format(attr, getattr(self, attr)) for attr in self.JSON_MAPPING]), ) @property def image_url(self): return self._create_image_url(self.image_path, self.IMAGE_TYPE, 200) @classmethod def from_json(cls, json, image_config=None): """Create a model instance Arguments: json (:py:class:`dict`): The parsed JSON data. image_config (:py:class:`dict`): The API image configuration data. Returns: :py:class:`BaseModel`: The model instance. """ cls.image_config = image_config return cls(**{ attr: json.get(attr if key is None else key) for attr, key in cls.JSON_MAPPING.items() }) @staticmethod def _image_size(image_config, type_, target_size): """Find the closest available size for specified image type. Arguments: image_config (:py:class:`dict`): The image config data. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height). """ return min( image_config['{}_sizes'.format(type_)], key=lambda size: (abs(target_size - int(size[1:])) if size.startswith('w') or size.startswith('h') else 999), )
textbook/atmdb
atmdb/models.py
BaseModel.from_json
python
def from_json(cls, json, image_config=None): cls.image_config = image_config return cls(**{ attr: json.get(attr if key is None else key) for attr, key in cls.JSON_MAPPING.items() })
Create a model instance Arguments: json (:py:class:`dict`): The parsed JSON data. image_config (:py:class:`dict`): The API image configuration data. Returns: :py:class:`BaseModel`: The model instance.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L86-L102
null
class BaseModel: """Base TMDb model functionality. Arguments: id_ (:py:class:`int`): The TMDb ID of the object. image_path (:py:class:`str`): The short path to the image. Attributes: image_url (:py:class:`str`): The fully-qualified image URL. """ CONTAINS = None """:py:class:`dict`: Rules for what the model contains.""" IMAGE_TYPE = None """:py:class:`str`: The type of image to use.""" JSON_MAPPING = dict(id_='id') """:py:class:`dict`: The mapping between JSON keys and attributes.""" image_config = None """:py:class:`dict`: The API image configuration.""" def __init__(self, *, id_, image_path=None, **_): self.id_ = id_ self.image_path = image_path def __contains__(self, item): if self.CONTAINS is None: return False attr = self.CONTAINS['attr'] subclasses = {obj.__name__: obj for obj in BaseModel.__subclasses__()} # pylint: disable=no-member cls = subclasses[self.CONTAINS['type']] return isinstance(item, cls) and item in getattr(self, attr) def __eq__(self, other): return isinstance(other, type(self)) and self.id_ == other.id_ def __hash__(self): return hash(self.id_) def __repr__(self): return '{}({})'.format( self.__class__.__name__, ', '.join(['{}={!r}'.format(attr, getattr(self, attr)) for attr in self.JSON_MAPPING]), ) @property def image_url(self): return self._create_image_url(self.image_path, self.IMAGE_TYPE, 200) def _create_image_url(self, file_path, type_, target_size): """The the closest available size for specified image type. Arguments: file_path (:py:class:`str`): The image file path. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height). """ if self.image_config is None: logger.warning('no image configuration available') return return ''.join([ self.image_config['secure_base_url'], self._image_size(self.image_config, type_, target_size), file_path, ]) @classmethod @staticmethod def _image_size(image_config, type_, target_size): """Find the closest available size for specified image type. Arguments: image_config (:py:class:`dict`): The image config data. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height). """ return min( image_config['{}_sizes'.format(type_)], key=lambda size: (abs(target_size - int(size[1:])) if size.startswith('w') or size.startswith('h') else 999), )
textbook/atmdb
atmdb/models.py
BaseModel._image_size
python
def _image_size(image_config, type_, target_size): return min( image_config['{}_sizes'.format(type_)], key=lambda size: (abs(target_size - int(size[1:])) if size.startswith('w') or size.startswith('h') else 999), )
Find the closest available size for specified image type. Arguments: image_config (:py:class:`dict`): The image config data. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height).
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/models.py#L105-L121
null
class BaseModel: """Base TMDb model functionality. Arguments: id_ (:py:class:`int`): The TMDb ID of the object. image_path (:py:class:`str`): The short path to the image. Attributes: image_url (:py:class:`str`): The fully-qualified image URL. """ CONTAINS = None """:py:class:`dict`: Rules for what the model contains.""" IMAGE_TYPE = None """:py:class:`str`: The type of image to use.""" JSON_MAPPING = dict(id_='id') """:py:class:`dict`: The mapping between JSON keys and attributes.""" image_config = None """:py:class:`dict`: The API image configuration.""" def __init__(self, *, id_, image_path=None, **_): self.id_ = id_ self.image_path = image_path def __contains__(self, item): if self.CONTAINS is None: return False attr = self.CONTAINS['attr'] subclasses = {obj.__name__: obj for obj in BaseModel.__subclasses__()} # pylint: disable=no-member cls = subclasses[self.CONTAINS['type']] return isinstance(item, cls) and item in getattr(self, attr) def __eq__(self, other): return isinstance(other, type(self)) and self.id_ == other.id_ def __hash__(self): return hash(self.id_) def __repr__(self): return '{}({})'.format( self.__class__.__name__, ', '.join(['{}={!r}'.format(attr, getattr(self, attr)) for attr in self.JSON_MAPPING]), ) @property def image_url(self): return self._create_image_url(self.image_path, self.IMAGE_TYPE, 200) def _create_image_url(self, file_path, type_, target_size): """The the closest available size for specified image type. Arguments: file_path (:py:class:`str`): The image file path. type_ (:py:class:`str`): The type of image to create a URL for, (``'poster'`` or ``'profile'``). target_size (:py:class:`int`): The size of image to aim for (used as either width or height). """ if self.image_config is None: logger.warning('no image configuration available') return return ''.join([ self.image_config['secure_base_url'], self._image_size(self.image_config, type_, target_size), file_path, ]) @classmethod def from_json(cls, json, image_config=None): """Create a model instance Arguments: json (:py:class:`dict`): The parsed JSON data. image_config (:py:class:`dict`): The API image configuration data. Returns: :py:class:`BaseModel`: The model instance. """ cls.image_config = image_config return cls(**{ attr: json.get(attr if key is None else key) for attr, key in cls.JSON_MAPPING.items() }) @staticmethod
textbook/atmdb
atmdb/client.py
TMDbClient._update_config
python
async def _update_config(self): if self.config['data'] is None or self.config_expired: data = await self.get_data(self.url_builder('configuration')) self.config = dict(data=data, last_update=datetime.now())
Update configuration data if required. Notes: Per `the documentation`_, this updates the API configuration data *"every few days"*. .. _the documentation: http://docs.themoviedb.apiary.io/#reference/configuration
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L44-L57
null
class TMDbClient(UrlParamMixin, Service): """Simple wrapper for the `TMDb`_ API. .. _TMDb: https://www.themoviedb.org/ """ AUTH_PARAM = 'api_key' ROOT = 'https://api.themoviedb.org/3/' TOKEN_ENV_VAR = 'TMDB_API_TOKEN' def __init__(self, *, api_token=None, **kwargs): super().__init__(api_token=api_token, **kwargs) self.config = dict(data=None, last_update=None) @property def headers(self): return dict(Accept='application/json', **super().headers) @property def config_expired(self): """Whether the configuration data has expired.""" return (self.config['last_update'] + timedelta(days=2)) < datetime.now() async def get_data(self, url): """Get data from the TMDb API via :py:func:`aiohttp.get`. Notes: Updates configuration (if required) on successful requests. Arguments: url (:py:class:`str`): The endpoint URL and params. Returns: :py:class:`dict`: The parsed JSON result. """ logger.debug('making request to %r', url) with aiohttp.ClientSession() as session: async with session.get(url, headers=self.headers) as response: body = json.loads((await response.read()).decode('utf-8')) if response.status == HTTPStatus.OK: if url != self.url_builder('configuration'): await self._update_config() return body elif response.status == HTTPStatus.TOO_MANY_REQUESTS: timeout = self.calculate_timeout( response.headers['Retry-After'], ) logger.warning( 'Request limit exceeded, waiting %s seconds', timeout, ) await asyncio.sleep(timeout) return await self.get_data(url) logger.warning( 'request failed %s: %r', response.status, body.get('status_message', '<no message>') ) async def find_movie(self, query): """Retrieve movie data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ params = OrderedDict([ ('query', query), ('include_adult', False), ]) url = self.url_builder('search/movie', {}, params) data = await self.get_data(url) if data is None: return return [ Movie.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def find_person(self, query): """Retrieve person data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ url = self.url_builder( 'search/person', dict(), url_params=OrderedDict([ ('query', query), ('include_adult', False) ]), ) data = await self.get_data(url) if data is None: return return [ Person.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def get_movie(self, id_): """Retrieve movie data by ID. Arguments: id_ (:py:class:`int`): The movie's TMDb ID. Returns: :py:class:`~.Movie`: The requested movie. """ url = self.url_builder( 'movie/{movie_id}', dict(movie_id=id_), url_params=OrderedDict(append_to_response='credits'), ) data = await self.get_data(url) if data is None: return return Movie.from_json(data, self.config['data'].get('images')) async def get_person(self, id_): """Retrieve person data by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. Returns: :py:class:`~.Person`: The requested person. """ data = await self._get_person_json( id_, OrderedDict(append_to_response='movie_credits') ) return Person.from_json(data, self.config['data'].get('images')) async def _get_person_json(self, id_, url_params=None): """Retrieve raw person JSON by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. url_params (:py:class:`dict`): Any additional URL parameters. Returns: :py:class:`dict`: The JSON data. """ url = self.url_builder( 'person/{person_id}', dict(person_id=id_), url_params=url_params or OrderedDict(), ) data = await self.get_data(url) return data async def get_random_popular_person(self, limit=500): """Randomly select a popular person. Notes: Requires at least two API calls. May require three API calls if the randomly-selected index isn't within the first page of required data. Arguments: limit (:py:class:`int`, optional): How many of the most popular people to make random choice from (defaults to top ``500``). Returns: :py:class:`~.Person`: A randomly-selected popular person. """ index = random.randrange(limit) data = await self._get_popular_people_page() if data is None: return if index >= len(data['results']): # result is not on first page page, index = self._calculate_page_index(index, data) data = await self._get_popular_people_page(page) if data is None: return json_data = data['results'][index] details = await self._get_person_json(json_data['id']) details.update(**json_data) return Person.from_json(details, self.config['data'].get('images')) async def _get_popular_people_page(self, page=1): """Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data. """ return await self.get_data(self.url_builder( 'person/popular', url_params=OrderedDict(page=page), )) @staticmethod def _calculate_page_index(index, data): """Determine the location of a given index in paged data. Arguments: index (:py:class:`int`): The overall index. data: (:py:class:`dict`) The first page of data. Returns: :py:class:`tuple`: The location of that index, in the format ``(page, index_in_page)``. """ if index > data['total_results']: raise ValueError('index not in paged data') page_length = len(data['results']) return (index // page_length) + 1, (index % page_length) - 1
textbook/atmdb
atmdb/client.py
TMDbClient.get_data
python
async def get_data(self, url): logger.debug('making request to %r', url) with aiohttp.ClientSession() as session: async with session.get(url, headers=self.headers) as response: body = json.loads((await response.read()).decode('utf-8')) if response.status == HTTPStatus.OK: if url != self.url_builder('configuration'): await self._update_config() return body elif response.status == HTTPStatus.TOO_MANY_REQUESTS: timeout = self.calculate_timeout( response.headers['Retry-After'], ) logger.warning( 'Request limit exceeded, waiting %s seconds', timeout, ) await asyncio.sleep(timeout) return await self.get_data(url) logger.warning( 'request failed %s: %r', response.status, body.get('status_message', '<no message>') )
Get data from the TMDb API via :py:func:`aiohttp.get`. Notes: Updates configuration (if required) on successful requests. Arguments: url (:py:class:`str`): The endpoint URL and params. Returns: :py:class:`dict`: The parsed JSON result.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L59-L94
null
class TMDbClient(UrlParamMixin, Service): """Simple wrapper for the `TMDb`_ API. .. _TMDb: https://www.themoviedb.org/ """ AUTH_PARAM = 'api_key' ROOT = 'https://api.themoviedb.org/3/' TOKEN_ENV_VAR = 'TMDB_API_TOKEN' def __init__(self, *, api_token=None, **kwargs): super().__init__(api_token=api_token, **kwargs) self.config = dict(data=None, last_update=None) @property def headers(self): return dict(Accept='application/json', **super().headers) @property def config_expired(self): """Whether the configuration data has expired.""" return (self.config['last_update'] + timedelta(days=2)) < datetime.now() async def _update_config(self): """Update configuration data if required. Notes: Per `the documentation`_, this updates the API configuration data *"every few days"*. .. _the documentation: http://docs.themoviedb.apiary.io/#reference/configuration """ if self.config['data'] is None or self.config_expired: data = await self.get_data(self.url_builder('configuration')) self.config = dict(data=data, last_update=datetime.now()) async def find_movie(self, query): """Retrieve movie data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ params = OrderedDict([ ('query', query), ('include_adult', False), ]) url = self.url_builder('search/movie', {}, params) data = await self.get_data(url) if data is None: return return [ Movie.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def find_person(self, query): """Retrieve person data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ url = self.url_builder( 'search/person', dict(), url_params=OrderedDict([ ('query', query), ('include_adult', False) ]), ) data = await self.get_data(url) if data is None: return return [ Person.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def get_movie(self, id_): """Retrieve movie data by ID. Arguments: id_ (:py:class:`int`): The movie's TMDb ID. Returns: :py:class:`~.Movie`: The requested movie. """ url = self.url_builder( 'movie/{movie_id}', dict(movie_id=id_), url_params=OrderedDict(append_to_response='credits'), ) data = await self.get_data(url) if data is None: return return Movie.from_json(data, self.config['data'].get('images')) async def get_person(self, id_): """Retrieve person data by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. Returns: :py:class:`~.Person`: The requested person. """ data = await self._get_person_json( id_, OrderedDict(append_to_response='movie_credits') ) return Person.from_json(data, self.config['data'].get('images')) async def _get_person_json(self, id_, url_params=None): """Retrieve raw person JSON by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. url_params (:py:class:`dict`): Any additional URL parameters. Returns: :py:class:`dict`: The JSON data. """ url = self.url_builder( 'person/{person_id}', dict(person_id=id_), url_params=url_params or OrderedDict(), ) data = await self.get_data(url) return data async def get_random_popular_person(self, limit=500): """Randomly select a popular person. Notes: Requires at least two API calls. May require three API calls if the randomly-selected index isn't within the first page of required data. Arguments: limit (:py:class:`int`, optional): How many of the most popular people to make random choice from (defaults to top ``500``). Returns: :py:class:`~.Person`: A randomly-selected popular person. """ index = random.randrange(limit) data = await self._get_popular_people_page() if data is None: return if index >= len(data['results']): # result is not on first page page, index = self._calculate_page_index(index, data) data = await self._get_popular_people_page(page) if data is None: return json_data = data['results'][index] details = await self._get_person_json(json_data['id']) details.update(**json_data) return Person.from_json(details, self.config['data'].get('images')) async def _get_popular_people_page(self, page=1): """Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data. """ return await self.get_data(self.url_builder( 'person/popular', url_params=OrderedDict(page=page), )) @staticmethod def _calculate_page_index(index, data): """Determine the location of a given index in paged data. Arguments: index (:py:class:`int`): The overall index. data: (:py:class:`dict`) The first page of data. Returns: :py:class:`tuple`: The location of that index, in the format ``(page, index_in_page)``. """ if index > data['total_results']: raise ValueError('index not in paged data') page_length = len(data['results']) return (index // page_length) + 1, (index % page_length) - 1
textbook/atmdb
atmdb/client.py
TMDbClient.find_movie
python
async def find_movie(self, query): params = OrderedDict([ ('query', query), ('include_adult', False), ]) url = self.url_builder('search/movie', {}, params) data = await self.get_data(url) if data is None: return return [ Movie.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ]
Retrieve movie data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L96-L116
[ "async def get_data(self, url):\n \"\"\"Get data from the TMDb API via :py:func:`aiohttp.get`.\n\n Notes:\n Updates configuration (if required) on successful requests.\n\n Arguments:\n url (:py:class:`str`): The endpoint URL and params.\n\n Returns:\n :py:class:`dict`: The parsed JSON result.\n\n \"\"\"\n logger.debug('making request to %r', url)\n with aiohttp.ClientSession() as session:\n async with session.get(url, headers=self.headers) as response:\n body = json.loads((await response.read()).decode('utf-8'))\n if response.status == HTTPStatus.OK:\n if url != self.url_builder('configuration'):\n await self._update_config()\n return body\n elif response.status == HTTPStatus.TOO_MANY_REQUESTS:\n timeout = self.calculate_timeout(\n response.headers['Retry-After'],\n )\n logger.warning(\n 'Request limit exceeded, waiting %s seconds',\n timeout,\n )\n await asyncio.sleep(timeout)\n return await self.get_data(url)\n logger.warning(\n 'request failed %s: %r',\n response.status,\n body.get('status_message', '<no message>')\n )\n", "def url_builder(self, endpoint, params=None, url_params=None):\n \"\"\"Add authentication URL parameter.\"\"\"\n if url_params is None:\n url_params = OrderedDict()\n url_params[self.AUTH_PARAM] = self.api_token\n return super().url_builder(\n endpoint,\n params=params,\n url_params=url_params,\n )\n" ]
class TMDbClient(UrlParamMixin, Service): """Simple wrapper for the `TMDb`_ API. .. _TMDb: https://www.themoviedb.org/ """ AUTH_PARAM = 'api_key' ROOT = 'https://api.themoviedb.org/3/' TOKEN_ENV_VAR = 'TMDB_API_TOKEN' def __init__(self, *, api_token=None, **kwargs): super().__init__(api_token=api_token, **kwargs) self.config = dict(data=None, last_update=None) @property def headers(self): return dict(Accept='application/json', **super().headers) @property def config_expired(self): """Whether the configuration data has expired.""" return (self.config['last_update'] + timedelta(days=2)) < datetime.now() async def _update_config(self): """Update configuration data if required. Notes: Per `the documentation`_, this updates the API configuration data *"every few days"*. .. _the documentation: http://docs.themoviedb.apiary.io/#reference/configuration """ if self.config['data'] is None or self.config_expired: data = await self.get_data(self.url_builder('configuration')) self.config = dict(data=data, last_update=datetime.now()) async def get_data(self, url): """Get data from the TMDb API via :py:func:`aiohttp.get`. Notes: Updates configuration (if required) on successful requests. Arguments: url (:py:class:`str`): The endpoint URL and params. Returns: :py:class:`dict`: The parsed JSON result. """ logger.debug('making request to %r', url) with aiohttp.ClientSession() as session: async with session.get(url, headers=self.headers) as response: body = json.loads((await response.read()).decode('utf-8')) if response.status == HTTPStatus.OK: if url != self.url_builder('configuration'): await self._update_config() return body elif response.status == HTTPStatus.TOO_MANY_REQUESTS: timeout = self.calculate_timeout( response.headers['Retry-After'], ) logger.warning( 'Request limit exceeded, waiting %s seconds', timeout, ) await asyncio.sleep(timeout) return await self.get_data(url) logger.warning( 'request failed %s: %r', response.status, body.get('status_message', '<no message>') ) async def find_person(self, query): """Retrieve person data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ url = self.url_builder( 'search/person', dict(), url_params=OrderedDict([ ('query', query), ('include_adult', False) ]), ) data = await self.get_data(url) if data is None: return return [ Person.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def get_movie(self, id_): """Retrieve movie data by ID. Arguments: id_ (:py:class:`int`): The movie's TMDb ID. Returns: :py:class:`~.Movie`: The requested movie. """ url = self.url_builder( 'movie/{movie_id}', dict(movie_id=id_), url_params=OrderedDict(append_to_response='credits'), ) data = await self.get_data(url) if data is None: return return Movie.from_json(data, self.config['data'].get('images')) async def get_person(self, id_): """Retrieve person data by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. Returns: :py:class:`~.Person`: The requested person. """ data = await self._get_person_json( id_, OrderedDict(append_to_response='movie_credits') ) return Person.from_json(data, self.config['data'].get('images')) async def _get_person_json(self, id_, url_params=None): """Retrieve raw person JSON by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. url_params (:py:class:`dict`): Any additional URL parameters. Returns: :py:class:`dict`: The JSON data. """ url = self.url_builder( 'person/{person_id}', dict(person_id=id_), url_params=url_params or OrderedDict(), ) data = await self.get_data(url) return data async def get_random_popular_person(self, limit=500): """Randomly select a popular person. Notes: Requires at least two API calls. May require three API calls if the randomly-selected index isn't within the first page of required data. Arguments: limit (:py:class:`int`, optional): How many of the most popular people to make random choice from (defaults to top ``500``). Returns: :py:class:`~.Person`: A randomly-selected popular person. """ index = random.randrange(limit) data = await self._get_popular_people_page() if data is None: return if index >= len(data['results']): # result is not on first page page, index = self._calculate_page_index(index, data) data = await self._get_popular_people_page(page) if data is None: return json_data = data['results'][index] details = await self._get_person_json(json_data['id']) details.update(**json_data) return Person.from_json(details, self.config['data'].get('images')) async def _get_popular_people_page(self, page=1): """Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data. """ return await self.get_data(self.url_builder( 'person/popular', url_params=OrderedDict(page=page), )) @staticmethod def _calculate_page_index(index, data): """Determine the location of a given index in paged data. Arguments: index (:py:class:`int`): The overall index. data: (:py:class:`dict`) The first page of data. Returns: :py:class:`tuple`: The location of that index, in the format ``(page, index_in_page)``. """ if index > data['total_results']: raise ValueError('index not in paged data') page_length = len(data['results']) return (index // page_length) + 1, (index % page_length) - 1
textbook/atmdb
atmdb/client.py
TMDbClient.find_person
python
async def find_person(self, query): url = self.url_builder( 'search/person', dict(), url_params=OrderedDict([ ('query', query), ('include_adult', False) ]), ) data = await self.get_data(url) if data is None: return return [ Person.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ]
Retrieve person data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L118-L141
[ "async def get_data(self, url):\n \"\"\"Get data from the TMDb API via :py:func:`aiohttp.get`.\n\n Notes:\n Updates configuration (if required) on successful requests.\n\n Arguments:\n url (:py:class:`str`): The endpoint URL and params.\n\n Returns:\n :py:class:`dict`: The parsed JSON result.\n\n \"\"\"\n logger.debug('making request to %r', url)\n with aiohttp.ClientSession() as session:\n async with session.get(url, headers=self.headers) as response:\n body = json.loads((await response.read()).decode('utf-8'))\n if response.status == HTTPStatus.OK:\n if url != self.url_builder('configuration'):\n await self._update_config()\n return body\n elif response.status == HTTPStatus.TOO_MANY_REQUESTS:\n timeout = self.calculate_timeout(\n response.headers['Retry-After'],\n )\n logger.warning(\n 'Request limit exceeded, waiting %s seconds',\n timeout,\n )\n await asyncio.sleep(timeout)\n return await self.get_data(url)\n logger.warning(\n 'request failed %s: %r',\n response.status,\n body.get('status_message', '<no message>')\n )\n", "def url_builder(self, endpoint, params=None, url_params=None):\n \"\"\"Add authentication URL parameter.\"\"\"\n if url_params is None:\n url_params = OrderedDict()\n url_params[self.AUTH_PARAM] = self.api_token\n return super().url_builder(\n endpoint,\n params=params,\n url_params=url_params,\n )\n" ]
class TMDbClient(UrlParamMixin, Service): """Simple wrapper for the `TMDb`_ API. .. _TMDb: https://www.themoviedb.org/ """ AUTH_PARAM = 'api_key' ROOT = 'https://api.themoviedb.org/3/' TOKEN_ENV_VAR = 'TMDB_API_TOKEN' def __init__(self, *, api_token=None, **kwargs): super().__init__(api_token=api_token, **kwargs) self.config = dict(data=None, last_update=None) @property def headers(self): return dict(Accept='application/json', **super().headers) @property def config_expired(self): """Whether the configuration data has expired.""" return (self.config['last_update'] + timedelta(days=2)) < datetime.now() async def _update_config(self): """Update configuration data if required. Notes: Per `the documentation`_, this updates the API configuration data *"every few days"*. .. _the documentation: http://docs.themoviedb.apiary.io/#reference/configuration """ if self.config['data'] is None or self.config_expired: data = await self.get_data(self.url_builder('configuration')) self.config = dict(data=data, last_update=datetime.now()) async def get_data(self, url): """Get data from the TMDb API via :py:func:`aiohttp.get`. Notes: Updates configuration (if required) on successful requests. Arguments: url (:py:class:`str`): The endpoint URL and params. Returns: :py:class:`dict`: The parsed JSON result. """ logger.debug('making request to %r', url) with aiohttp.ClientSession() as session: async with session.get(url, headers=self.headers) as response: body = json.loads((await response.read()).decode('utf-8')) if response.status == HTTPStatus.OK: if url != self.url_builder('configuration'): await self._update_config() return body elif response.status == HTTPStatus.TOO_MANY_REQUESTS: timeout = self.calculate_timeout( response.headers['Retry-After'], ) logger.warning( 'Request limit exceeded, waiting %s seconds', timeout, ) await asyncio.sleep(timeout) return await self.get_data(url) logger.warning( 'request failed %s: %r', response.status, body.get('status_message', '<no message>') ) async def find_movie(self, query): """Retrieve movie data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ params = OrderedDict([ ('query', query), ('include_adult', False), ]) url = self.url_builder('search/movie', {}, params) data = await self.get_data(url) if data is None: return return [ Movie.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def get_movie(self, id_): """Retrieve movie data by ID. Arguments: id_ (:py:class:`int`): The movie's TMDb ID. Returns: :py:class:`~.Movie`: The requested movie. """ url = self.url_builder( 'movie/{movie_id}', dict(movie_id=id_), url_params=OrderedDict(append_to_response='credits'), ) data = await self.get_data(url) if data is None: return return Movie.from_json(data, self.config['data'].get('images')) async def get_person(self, id_): """Retrieve person data by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. Returns: :py:class:`~.Person`: The requested person. """ data = await self._get_person_json( id_, OrderedDict(append_to_response='movie_credits') ) return Person.from_json(data, self.config['data'].get('images')) async def _get_person_json(self, id_, url_params=None): """Retrieve raw person JSON by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. url_params (:py:class:`dict`): Any additional URL parameters. Returns: :py:class:`dict`: The JSON data. """ url = self.url_builder( 'person/{person_id}', dict(person_id=id_), url_params=url_params or OrderedDict(), ) data = await self.get_data(url) return data async def get_random_popular_person(self, limit=500): """Randomly select a popular person. Notes: Requires at least two API calls. May require three API calls if the randomly-selected index isn't within the first page of required data. Arguments: limit (:py:class:`int`, optional): How many of the most popular people to make random choice from (defaults to top ``500``). Returns: :py:class:`~.Person`: A randomly-selected popular person. """ index = random.randrange(limit) data = await self._get_popular_people_page() if data is None: return if index >= len(data['results']): # result is not on first page page, index = self._calculate_page_index(index, data) data = await self._get_popular_people_page(page) if data is None: return json_data = data['results'][index] details = await self._get_person_json(json_data['id']) details.update(**json_data) return Person.from_json(details, self.config['data'].get('images')) async def _get_popular_people_page(self, page=1): """Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data. """ return await self.get_data(self.url_builder( 'person/popular', url_params=OrderedDict(page=page), )) @staticmethod def _calculate_page_index(index, data): """Determine the location of a given index in paged data. Arguments: index (:py:class:`int`): The overall index. data: (:py:class:`dict`) The first page of data. Returns: :py:class:`tuple`: The location of that index, in the format ``(page, index_in_page)``. """ if index > data['total_results']: raise ValueError('index not in paged data') page_length = len(data['results']) return (index // page_length) + 1, (index % page_length) - 1
textbook/atmdb
atmdb/client.py
TMDbClient.get_movie
python
async def get_movie(self, id_): url = self.url_builder( 'movie/{movie_id}', dict(movie_id=id_), url_params=OrderedDict(append_to_response='credits'), ) data = await self.get_data(url) if data is None: return return Movie.from_json(data, self.config['data'].get('images'))
Retrieve movie data by ID. Arguments: id_ (:py:class:`int`): The movie's TMDb ID. Returns: :py:class:`~.Movie`: The requested movie.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L143-L161
[ "async def get_data(self, url):\n \"\"\"Get data from the TMDb API via :py:func:`aiohttp.get`.\n\n Notes:\n Updates configuration (if required) on successful requests.\n\n Arguments:\n url (:py:class:`str`): The endpoint URL and params.\n\n Returns:\n :py:class:`dict`: The parsed JSON result.\n\n \"\"\"\n logger.debug('making request to %r', url)\n with aiohttp.ClientSession() as session:\n async with session.get(url, headers=self.headers) as response:\n body = json.loads((await response.read()).decode('utf-8'))\n if response.status == HTTPStatus.OK:\n if url != self.url_builder('configuration'):\n await self._update_config()\n return body\n elif response.status == HTTPStatus.TOO_MANY_REQUESTS:\n timeout = self.calculate_timeout(\n response.headers['Retry-After'],\n )\n logger.warning(\n 'Request limit exceeded, waiting %s seconds',\n timeout,\n )\n await asyncio.sleep(timeout)\n return await self.get_data(url)\n logger.warning(\n 'request failed %s: %r',\n response.status,\n body.get('status_message', '<no message>')\n )\n", "def url_builder(self, endpoint, params=None, url_params=None):\n \"\"\"Add authentication URL parameter.\"\"\"\n if url_params is None:\n url_params = OrderedDict()\n url_params[self.AUTH_PARAM] = self.api_token\n return super().url_builder(\n endpoint,\n params=params,\n url_params=url_params,\n )\n" ]
class TMDbClient(UrlParamMixin, Service): """Simple wrapper for the `TMDb`_ API. .. _TMDb: https://www.themoviedb.org/ """ AUTH_PARAM = 'api_key' ROOT = 'https://api.themoviedb.org/3/' TOKEN_ENV_VAR = 'TMDB_API_TOKEN' def __init__(self, *, api_token=None, **kwargs): super().__init__(api_token=api_token, **kwargs) self.config = dict(data=None, last_update=None) @property def headers(self): return dict(Accept='application/json', **super().headers) @property def config_expired(self): """Whether the configuration data has expired.""" return (self.config['last_update'] + timedelta(days=2)) < datetime.now() async def _update_config(self): """Update configuration data if required. Notes: Per `the documentation`_, this updates the API configuration data *"every few days"*. .. _the documentation: http://docs.themoviedb.apiary.io/#reference/configuration """ if self.config['data'] is None or self.config_expired: data = await self.get_data(self.url_builder('configuration')) self.config = dict(data=data, last_update=datetime.now()) async def get_data(self, url): """Get data from the TMDb API via :py:func:`aiohttp.get`. Notes: Updates configuration (if required) on successful requests. Arguments: url (:py:class:`str`): The endpoint URL and params. Returns: :py:class:`dict`: The parsed JSON result. """ logger.debug('making request to %r', url) with aiohttp.ClientSession() as session: async with session.get(url, headers=self.headers) as response: body = json.loads((await response.read()).decode('utf-8')) if response.status == HTTPStatus.OK: if url != self.url_builder('configuration'): await self._update_config() return body elif response.status == HTTPStatus.TOO_MANY_REQUESTS: timeout = self.calculate_timeout( response.headers['Retry-After'], ) logger.warning( 'Request limit exceeded, waiting %s seconds', timeout, ) await asyncio.sleep(timeout) return await self.get_data(url) logger.warning( 'request failed %s: %r', response.status, body.get('status_message', '<no message>') ) async def find_movie(self, query): """Retrieve movie data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ params = OrderedDict([ ('query', query), ('include_adult', False), ]) url = self.url_builder('search/movie', {}, params) data = await self.get_data(url) if data is None: return return [ Movie.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def find_person(self, query): """Retrieve person data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ url = self.url_builder( 'search/person', dict(), url_params=OrderedDict([ ('query', query), ('include_adult', False) ]), ) data = await self.get_data(url) if data is None: return return [ Person.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def get_person(self, id_): """Retrieve person data by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. Returns: :py:class:`~.Person`: The requested person. """ data = await self._get_person_json( id_, OrderedDict(append_to_response='movie_credits') ) return Person.from_json(data, self.config['data'].get('images')) async def _get_person_json(self, id_, url_params=None): """Retrieve raw person JSON by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. url_params (:py:class:`dict`): Any additional URL parameters. Returns: :py:class:`dict`: The JSON data. """ url = self.url_builder( 'person/{person_id}', dict(person_id=id_), url_params=url_params or OrderedDict(), ) data = await self.get_data(url) return data async def get_random_popular_person(self, limit=500): """Randomly select a popular person. Notes: Requires at least two API calls. May require three API calls if the randomly-selected index isn't within the first page of required data. Arguments: limit (:py:class:`int`, optional): How many of the most popular people to make random choice from (defaults to top ``500``). Returns: :py:class:`~.Person`: A randomly-selected popular person. """ index = random.randrange(limit) data = await self._get_popular_people_page() if data is None: return if index >= len(data['results']): # result is not on first page page, index = self._calculate_page_index(index, data) data = await self._get_popular_people_page(page) if data is None: return json_data = data['results'][index] details = await self._get_person_json(json_data['id']) details.update(**json_data) return Person.from_json(details, self.config['data'].get('images')) async def _get_popular_people_page(self, page=1): """Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data. """ return await self.get_data(self.url_builder( 'person/popular', url_params=OrderedDict(page=page), )) @staticmethod def _calculate_page_index(index, data): """Determine the location of a given index in paged data. Arguments: index (:py:class:`int`): The overall index. data: (:py:class:`dict`) The first page of data. Returns: :py:class:`tuple`: The location of that index, in the format ``(page, index_in_page)``. """ if index > data['total_results']: raise ValueError('index not in paged data') page_length = len(data['results']) return (index // page_length) + 1, (index % page_length) - 1
textbook/atmdb
atmdb/client.py
TMDbClient.get_person
python
async def get_person(self, id_): data = await self._get_person_json( id_, OrderedDict(append_to_response='movie_credits') ) return Person.from_json(data, self.config['data'].get('images'))
Retrieve person data by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. Returns: :py:class:`~.Person`: The requested person.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L163-L177
[ "async def _get_person_json(self, id_, url_params=None):\n \"\"\"Retrieve raw person JSON by ID.\n\n Arguments:\n id_ (:py:class:`int`): The person's TMDb ID.\n url_params (:py:class:`dict`): Any additional URL parameters.\n\n Returns:\n :py:class:`dict`: The JSON data.\n\n \"\"\"\n url = self.url_builder(\n 'person/{person_id}',\n dict(person_id=id_),\n url_params=url_params or OrderedDict(),\n )\n data = await self.get_data(url)\n return data\n", "def from_json(cls, json, image_config=None):\n json['movie_credits'] = {\n Movie.from_json(movie, image_config) for movie in\n json.get('movie_credits', {}).get('cast', [])\n } or None\n json['known_for'] = {\n Movie.from_json(movie, image_config)\n for movie in json.get('known_for', [])\n if movie.get('media_type') == 'movie'\n } or None\n json['birthday'] = cls.extract_date(json.get('birthday'))\n json['deathday'] = cls.extract_date(json.get('deathday'))\n return super().from_json(json, image_config)\n" ]
class TMDbClient(UrlParamMixin, Service): """Simple wrapper for the `TMDb`_ API. .. _TMDb: https://www.themoviedb.org/ """ AUTH_PARAM = 'api_key' ROOT = 'https://api.themoviedb.org/3/' TOKEN_ENV_VAR = 'TMDB_API_TOKEN' def __init__(self, *, api_token=None, **kwargs): super().__init__(api_token=api_token, **kwargs) self.config = dict(data=None, last_update=None) @property def headers(self): return dict(Accept='application/json', **super().headers) @property def config_expired(self): """Whether the configuration data has expired.""" return (self.config['last_update'] + timedelta(days=2)) < datetime.now() async def _update_config(self): """Update configuration data if required. Notes: Per `the documentation`_, this updates the API configuration data *"every few days"*. .. _the documentation: http://docs.themoviedb.apiary.io/#reference/configuration """ if self.config['data'] is None or self.config_expired: data = await self.get_data(self.url_builder('configuration')) self.config = dict(data=data, last_update=datetime.now()) async def get_data(self, url): """Get data from the TMDb API via :py:func:`aiohttp.get`. Notes: Updates configuration (if required) on successful requests. Arguments: url (:py:class:`str`): The endpoint URL and params. Returns: :py:class:`dict`: The parsed JSON result. """ logger.debug('making request to %r', url) with aiohttp.ClientSession() as session: async with session.get(url, headers=self.headers) as response: body = json.loads((await response.read()).decode('utf-8')) if response.status == HTTPStatus.OK: if url != self.url_builder('configuration'): await self._update_config() return body elif response.status == HTTPStatus.TOO_MANY_REQUESTS: timeout = self.calculate_timeout( response.headers['Retry-After'], ) logger.warning( 'Request limit exceeded, waiting %s seconds', timeout, ) await asyncio.sleep(timeout) return await self.get_data(url) logger.warning( 'request failed %s: %r', response.status, body.get('status_message', '<no message>') ) async def find_movie(self, query): """Retrieve movie data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ params = OrderedDict([ ('query', query), ('include_adult', False), ]) url = self.url_builder('search/movie', {}, params) data = await self.get_data(url) if data is None: return return [ Movie.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def find_person(self, query): """Retrieve person data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ url = self.url_builder( 'search/person', dict(), url_params=OrderedDict([ ('query', query), ('include_adult', False) ]), ) data = await self.get_data(url) if data is None: return return [ Person.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def get_movie(self, id_): """Retrieve movie data by ID. Arguments: id_ (:py:class:`int`): The movie's TMDb ID. Returns: :py:class:`~.Movie`: The requested movie. """ url = self.url_builder( 'movie/{movie_id}', dict(movie_id=id_), url_params=OrderedDict(append_to_response='credits'), ) data = await self.get_data(url) if data is None: return return Movie.from_json(data, self.config['data'].get('images')) async def _get_person_json(self, id_, url_params=None): """Retrieve raw person JSON by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. url_params (:py:class:`dict`): Any additional URL parameters. Returns: :py:class:`dict`: The JSON data. """ url = self.url_builder( 'person/{person_id}', dict(person_id=id_), url_params=url_params or OrderedDict(), ) data = await self.get_data(url) return data async def get_random_popular_person(self, limit=500): """Randomly select a popular person. Notes: Requires at least two API calls. May require three API calls if the randomly-selected index isn't within the first page of required data. Arguments: limit (:py:class:`int`, optional): How many of the most popular people to make random choice from (defaults to top ``500``). Returns: :py:class:`~.Person`: A randomly-selected popular person. """ index = random.randrange(limit) data = await self._get_popular_people_page() if data is None: return if index >= len(data['results']): # result is not on first page page, index = self._calculate_page_index(index, data) data = await self._get_popular_people_page(page) if data is None: return json_data = data['results'][index] details = await self._get_person_json(json_data['id']) details.update(**json_data) return Person.from_json(details, self.config['data'].get('images')) async def _get_popular_people_page(self, page=1): """Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data. """ return await self.get_data(self.url_builder( 'person/popular', url_params=OrderedDict(page=page), )) @staticmethod def _calculate_page_index(index, data): """Determine the location of a given index in paged data. Arguments: index (:py:class:`int`): The overall index. data: (:py:class:`dict`) The first page of data. Returns: :py:class:`tuple`: The location of that index, in the format ``(page, index_in_page)``. """ if index > data['total_results']: raise ValueError('index not in paged data') page_length = len(data['results']) return (index // page_length) + 1, (index % page_length) - 1
textbook/atmdb
atmdb/client.py
TMDbClient._get_person_json
python
async def _get_person_json(self, id_, url_params=None): url = self.url_builder( 'person/{person_id}', dict(person_id=id_), url_params=url_params or OrderedDict(), ) data = await self.get_data(url) return data
Retrieve raw person JSON by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. url_params (:py:class:`dict`): Any additional URL parameters. Returns: :py:class:`dict`: The JSON data.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L179-L196
[ "async def get_data(self, url):\n \"\"\"Get data from the TMDb API via :py:func:`aiohttp.get`.\n\n Notes:\n Updates configuration (if required) on successful requests.\n\n Arguments:\n url (:py:class:`str`): The endpoint URL and params.\n\n Returns:\n :py:class:`dict`: The parsed JSON result.\n\n \"\"\"\n logger.debug('making request to %r', url)\n with aiohttp.ClientSession() as session:\n async with session.get(url, headers=self.headers) as response:\n body = json.loads((await response.read()).decode('utf-8'))\n if response.status == HTTPStatus.OK:\n if url != self.url_builder('configuration'):\n await self._update_config()\n return body\n elif response.status == HTTPStatus.TOO_MANY_REQUESTS:\n timeout = self.calculate_timeout(\n response.headers['Retry-After'],\n )\n logger.warning(\n 'Request limit exceeded, waiting %s seconds',\n timeout,\n )\n await asyncio.sleep(timeout)\n return await self.get_data(url)\n logger.warning(\n 'request failed %s: %r',\n response.status,\n body.get('status_message', '<no message>')\n )\n", "def url_builder(self, endpoint, params=None, url_params=None):\n \"\"\"Add authentication URL parameter.\"\"\"\n if url_params is None:\n url_params = OrderedDict()\n url_params[self.AUTH_PARAM] = self.api_token\n return super().url_builder(\n endpoint,\n params=params,\n url_params=url_params,\n )\n" ]
class TMDbClient(UrlParamMixin, Service): """Simple wrapper for the `TMDb`_ API. .. _TMDb: https://www.themoviedb.org/ """ AUTH_PARAM = 'api_key' ROOT = 'https://api.themoviedb.org/3/' TOKEN_ENV_VAR = 'TMDB_API_TOKEN' def __init__(self, *, api_token=None, **kwargs): super().__init__(api_token=api_token, **kwargs) self.config = dict(data=None, last_update=None) @property def headers(self): return dict(Accept='application/json', **super().headers) @property def config_expired(self): """Whether the configuration data has expired.""" return (self.config['last_update'] + timedelta(days=2)) < datetime.now() async def _update_config(self): """Update configuration data if required. Notes: Per `the documentation`_, this updates the API configuration data *"every few days"*. .. _the documentation: http://docs.themoviedb.apiary.io/#reference/configuration """ if self.config['data'] is None or self.config_expired: data = await self.get_data(self.url_builder('configuration')) self.config = dict(data=data, last_update=datetime.now()) async def get_data(self, url): """Get data from the TMDb API via :py:func:`aiohttp.get`. Notes: Updates configuration (if required) on successful requests. Arguments: url (:py:class:`str`): The endpoint URL and params. Returns: :py:class:`dict`: The parsed JSON result. """ logger.debug('making request to %r', url) with aiohttp.ClientSession() as session: async with session.get(url, headers=self.headers) as response: body = json.loads((await response.read()).decode('utf-8')) if response.status == HTTPStatus.OK: if url != self.url_builder('configuration'): await self._update_config() return body elif response.status == HTTPStatus.TOO_MANY_REQUESTS: timeout = self.calculate_timeout( response.headers['Retry-After'], ) logger.warning( 'Request limit exceeded, waiting %s seconds', timeout, ) await asyncio.sleep(timeout) return await self.get_data(url) logger.warning( 'request failed %s: %r', response.status, body.get('status_message', '<no message>') ) async def find_movie(self, query): """Retrieve movie data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ params = OrderedDict([ ('query', query), ('include_adult', False), ]) url = self.url_builder('search/movie', {}, params) data = await self.get_data(url) if data is None: return return [ Movie.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def find_person(self, query): """Retrieve person data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ url = self.url_builder( 'search/person', dict(), url_params=OrderedDict([ ('query', query), ('include_adult', False) ]), ) data = await self.get_data(url) if data is None: return return [ Person.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def get_movie(self, id_): """Retrieve movie data by ID. Arguments: id_ (:py:class:`int`): The movie's TMDb ID. Returns: :py:class:`~.Movie`: The requested movie. """ url = self.url_builder( 'movie/{movie_id}', dict(movie_id=id_), url_params=OrderedDict(append_to_response='credits'), ) data = await self.get_data(url) if data is None: return return Movie.from_json(data, self.config['data'].get('images')) async def get_person(self, id_): """Retrieve person data by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. Returns: :py:class:`~.Person`: The requested person. """ data = await self._get_person_json( id_, OrderedDict(append_to_response='movie_credits') ) return Person.from_json(data, self.config['data'].get('images')) async def get_random_popular_person(self, limit=500): """Randomly select a popular person. Notes: Requires at least two API calls. May require three API calls if the randomly-selected index isn't within the first page of required data. Arguments: limit (:py:class:`int`, optional): How many of the most popular people to make random choice from (defaults to top ``500``). Returns: :py:class:`~.Person`: A randomly-selected popular person. """ index = random.randrange(limit) data = await self._get_popular_people_page() if data is None: return if index >= len(data['results']): # result is not on first page page, index = self._calculate_page_index(index, data) data = await self._get_popular_people_page(page) if data is None: return json_data = data['results'][index] details = await self._get_person_json(json_data['id']) details.update(**json_data) return Person.from_json(details, self.config['data'].get('images')) async def _get_popular_people_page(self, page=1): """Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data. """ return await self.get_data(self.url_builder( 'person/popular', url_params=OrderedDict(page=page), )) @staticmethod def _calculate_page_index(index, data): """Determine the location of a given index in paged data. Arguments: index (:py:class:`int`): The overall index. data: (:py:class:`dict`) The first page of data. Returns: :py:class:`tuple`: The location of that index, in the format ``(page, index_in_page)``. """ if index > data['total_results']: raise ValueError('index not in paged data') page_length = len(data['results']) return (index // page_length) + 1, (index % page_length) - 1
textbook/atmdb
atmdb/client.py
TMDbClient.get_random_popular_person
python
async def get_random_popular_person(self, limit=500): index = random.randrange(limit) data = await self._get_popular_people_page() if data is None: return if index >= len(data['results']): # result is not on first page page, index = self._calculate_page_index(index, data) data = await self._get_popular_people_page(page) if data is None: return json_data = data['results'][index] details = await self._get_person_json(json_data['id']) details.update(**json_data) return Person.from_json(details, self.config['data'].get('images'))
Randomly select a popular person. Notes: Requires at least two API calls. May require three API calls if the randomly-selected index isn't within the first page of required data. Arguments: limit (:py:class:`int`, optional): How many of the most popular people to make random choice from (defaults to top ``500``). Returns: :py:class:`~.Person`: A randomly-selected popular person.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L198-L228
[ "async def _get_popular_people_page(self, page=1):\n \"\"\"Get a specific page of popular person data.\n\n Arguments:\n page (:py:class:`int`, optional): The page to get.\n\n Returns:\n :py:class:`dict`: The page data.\n\n \"\"\"\n return await self.get_data(self.url_builder(\n 'person/popular',\n url_params=OrderedDict(page=page),\n ))\n" ]
class TMDbClient(UrlParamMixin, Service): """Simple wrapper for the `TMDb`_ API. .. _TMDb: https://www.themoviedb.org/ """ AUTH_PARAM = 'api_key' ROOT = 'https://api.themoviedb.org/3/' TOKEN_ENV_VAR = 'TMDB_API_TOKEN' def __init__(self, *, api_token=None, **kwargs): super().__init__(api_token=api_token, **kwargs) self.config = dict(data=None, last_update=None) @property def headers(self): return dict(Accept='application/json', **super().headers) @property def config_expired(self): """Whether the configuration data has expired.""" return (self.config['last_update'] + timedelta(days=2)) < datetime.now() async def _update_config(self): """Update configuration data if required. Notes: Per `the documentation`_, this updates the API configuration data *"every few days"*. .. _the documentation: http://docs.themoviedb.apiary.io/#reference/configuration """ if self.config['data'] is None or self.config_expired: data = await self.get_data(self.url_builder('configuration')) self.config = dict(data=data, last_update=datetime.now()) async def get_data(self, url): """Get data from the TMDb API via :py:func:`aiohttp.get`. Notes: Updates configuration (if required) on successful requests. Arguments: url (:py:class:`str`): The endpoint URL and params. Returns: :py:class:`dict`: The parsed JSON result. """ logger.debug('making request to %r', url) with aiohttp.ClientSession() as session: async with session.get(url, headers=self.headers) as response: body = json.loads((await response.read()).decode('utf-8')) if response.status == HTTPStatus.OK: if url != self.url_builder('configuration'): await self._update_config() return body elif response.status == HTTPStatus.TOO_MANY_REQUESTS: timeout = self.calculate_timeout( response.headers['Retry-After'], ) logger.warning( 'Request limit exceeded, waiting %s seconds', timeout, ) await asyncio.sleep(timeout) return await self.get_data(url) logger.warning( 'request failed %s: %r', response.status, body.get('status_message', '<no message>') ) async def find_movie(self, query): """Retrieve movie data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ params = OrderedDict([ ('query', query), ('include_adult', False), ]) url = self.url_builder('search/movie', {}, params) data = await self.get_data(url) if data is None: return return [ Movie.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def find_person(self, query): """Retrieve person data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ url = self.url_builder( 'search/person', dict(), url_params=OrderedDict([ ('query', query), ('include_adult', False) ]), ) data = await self.get_data(url) if data is None: return return [ Person.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def get_movie(self, id_): """Retrieve movie data by ID. Arguments: id_ (:py:class:`int`): The movie's TMDb ID. Returns: :py:class:`~.Movie`: The requested movie. """ url = self.url_builder( 'movie/{movie_id}', dict(movie_id=id_), url_params=OrderedDict(append_to_response='credits'), ) data = await self.get_data(url) if data is None: return return Movie.from_json(data, self.config['data'].get('images')) async def get_person(self, id_): """Retrieve person data by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. Returns: :py:class:`~.Person`: The requested person. """ data = await self._get_person_json( id_, OrderedDict(append_to_response='movie_credits') ) return Person.from_json(data, self.config['data'].get('images')) async def _get_person_json(self, id_, url_params=None): """Retrieve raw person JSON by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. url_params (:py:class:`dict`): Any additional URL parameters. Returns: :py:class:`dict`: The JSON data. """ url = self.url_builder( 'person/{person_id}', dict(person_id=id_), url_params=url_params or OrderedDict(), ) data = await self.get_data(url) return data async def _get_popular_people_page(self, page=1): """Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data. """ return await self.get_data(self.url_builder( 'person/popular', url_params=OrderedDict(page=page), )) @staticmethod def _calculate_page_index(index, data): """Determine the location of a given index in paged data. Arguments: index (:py:class:`int`): The overall index. data: (:py:class:`dict`) The first page of data. Returns: :py:class:`tuple`: The location of that index, in the format ``(page, index_in_page)``. """ if index > data['total_results']: raise ValueError('index not in paged data') page_length = len(data['results']) return (index // page_length) + 1, (index % page_length) - 1
textbook/atmdb
atmdb/client.py
TMDbClient._get_popular_people_page
python
async def _get_popular_people_page(self, page=1): return await self.get_data(self.url_builder( 'person/popular', url_params=OrderedDict(page=page), ))
Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L230-L243
[ "async def get_data(self, url):\n \"\"\"Get data from the TMDb API via :py:func:`aiohttp.get`.\n\n Notes:\n Updates configuration (if required) on successful requests.\n\n Arguments:\n url (:py:class:`str`): The endpoint URL and params.\n\n Returns:\n :py:class:`dict`: The parsed JSON result.\n\n \"\"\"\n logger.debug('making request to %r', url)\n with aiohttp.ClientSession() as session:\n async with session.get(url, headers=self.headers) as response:\n body = json.loads((await response.read()).decode('utf-8'))\n if response.status == HTTPStatus.OK:\n if url != self.url_builder('configuration'):\n await self._update_config()\n return body\n elif response.status == HTTPStatus.TOO_MANY_REQUESTS:\n timeout = self.calculate_timeout(\n response.headers['Retry-After'],\n )\n logger.warning(\n 'Request limit exceeded, waiting %s seconds',\n timeout,\n )\n await asyncio.sleep(timeout)\n return await self.get_data(url)\n logger.warning(\n 'request failed %s: %r',\n response.status,\n body.get('status_message', '<no message>')\n )\n", "def url_builder(self, endpoint, params=None, url_params=None):\n \"\"\"Add authentication URL parameter.\"\"\"\n if url_params is None:\n url_params = OrderedDict()\n url_params[self.AUTH_PARAM] = self.api_token\n return super().url_builder(\n endpoint,\n params=params,\n url_params=url_params,\n )\n" ]
class TMDbClient(UrlParamMixin, Service): """Simple wrapper for the `TMDb`_ API. .. _TMDb: https://www.themoviedb.org/ """ AUTH_PARAM = 'api_key' ROOT = 'https://api.themoviedb.org/3/' TOKEN_ENV_VAR = 'TMDB_API_TOKEN' def __init__(self, *, api_token=None, **kwargs): super().__init__(api_token=api_token, **kwargs) self.config = dict(data=None, last_update=None) @property def headers(self): return dict(Accept='application/json', **super().headers) @property def config_expired(self): """Whether the configuration data has expired.""" return (self.config['last_update'] + timedelta(days=2)) < datetime.now() async def _update_config(self): """Update configuration data if required. Notes: Per `the documentation`_, this updates the API configuration data *"every few days"*. .. _the documentation: http://docs.themoviedb.apiary.io/#reference/configuration """ if self.config['data'] is None or self.config_expired: data = await self.get_data(self.url_builder('configuration')) self.config = dict(data=data, last_update=datetime.now()) async def get_data(self, url): """Get data from the TMDb API via :py:func:`aiohttp.get`. Notes: Updates configuration (if required) on successful requests. Arguments: url (:py:class:`str`): The endpoint URL and params. Returns: :py:class:`dict`: The parsed JSON result. """ logger.debug('making request to %r', url) with aiohttp.ClientSession() as session: async with session.get(url, headers=self.headers) as response: body = json.loads((await response.read()).decode('utf-8')) if response.status == HTTPStatus.OK: if url != self.url_builder('configuration'): await self._update_config() return body elif response.status == HTTPStatus.TOO_MANY_REQUESTS: timeout = self.calculate_timeout( response.headers['Retry-After'], ) logger.warning( 'Request limit exceeded, waiting %s seconds', timeout, ) await asyncio.sleep(timeout) return await self.get_data(url) logger.warning( 'request failed %s: %r', response.status, body.get('status_message', '<no message>') ) async def find_movie(self, query): """Retrieve movie data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ params = OrderedDict([ ('query', query), ('include_adult', False), ]) url = self.url_builder('search/movie', {}, params) data = await self.get_data(url) if data is None: return return [ Movie.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def find_person(self, query): """Retrieve person data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ url = self.url_builder( 'search/person', dict(), url_params=OrderedDict([ ('query', query), ('include_adult', False) ]), ) data = await self.get_data(url) if data is None: return return [ Person.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def get_movie(self, id_): """Retrieve movie data by ID. Arguments: id_ (:py:class:`int`): The movie's TMDb ID. Returns: :py:class:`~.Movie`: The requested movie. """ url = self.url_builder( 'movie/{movie_id}', dict(movie_id=id_), url_params=OrderedDict(append_to_response='credits'), ) data = await self.get_data(url) if data is None: return return Movie.from_json(data, self.config['data'].get('images')) async def get_person(self, id_): """Retrieve person data by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. Returns: :py:class:`~.Person`: The requested person. """ data = await self._get_person_json( id_, OrderedDict(append_to_response='movie_credits') ) return Person.from_json(data, self.config['data'].get('images')) async def _get_person_json(self, id_, url_params=None): """Retrieve raw person JSON by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. url_params (:py:class:`dict`): Any additional URL parameters. Returns: :py:class:`dict`: The JSON data. """ url = self.url_builder( 'person/{person_id}', dict(person_id=id_), url_params=url_params or OrderedDict(), ) data = await self.get_data(url) return data async def get_random_popular_person(self, limit=500): """Randomly select a popular person. Notes: Requires at least two API calls. May require three API calls if the randomly-selected index isn't within the first page of required data. Arguments: limit (:py:class:`int`, optional): How many of the most popular people to make random choice from (defaults to top ``500``). Returns: :py:class:`~.Person`: A randomly-selected popular person. """ index = random.randrange(limit) data = await self._get_popular_people_page() if data is None: return if index >= len(data['results']): # result is not on first page page, index = self._calculate_page_index(index, data) data = await self._get_popular_people_page(page) if data is None: return json_data = data['results'][index] details = await self._get_person_json(json_data['id']) details.update(**json_data) return Person.from_json(details, self.config['data'].get('images')) @staticmethod def _calculate_page_index(index, data): """Determine the location of a given index in paged data. Arguments: index (:py:class:`int`): The overall index. data: (:py:class:`dict`) The first page of data. Returns: :py:class:`tuple`: The location of that index, in the format ``(page, index_in_page)``. """ if index > data['total_results']: raise ValueError('index not in paged data') page_length = len(data['results']) return (index // page_length) + 1, (index % page_length) - 1
textbook/atmdb
atmdb/client.py
TMDbClient._calculate_page_index
python
def _calculate_page_index(index, data): if index > data['total_results']: raise ValueError('index not in paged data') page_length = len(data['results']) return (index // page_length) + 1, (index % page_length) - 1
Determine the location of a given index in paged data. Arguments: index (:py:class:`int`): The overall index. data: (:py:class:`dict`) The first page of data. Returns: :py:class:`tuple`: The location of that index, in the format ``(page, index_in_page)``.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/client.py#L246-L261
null
class TMDbClient(UrlParamMixin, Service): """Simple wrapper for the `TMDb`_ API. .. _TMDb: https://www.themoviedb.org/ """ AUTH_PARAM = 'api_key' ROOT = 'https://api.themoviedb.org/3/' TOKEN_ENV_VAR = 'TMDB_API_TOKEN' def __init__(self, *, api_token=None, **kwargs): super().__init__(api_token=api_token, **kwargs) self.config = dict(data=None, last_update=None) @property def headers(self): return dict(Accept='application/json', **super().headers) @property def config_expired(self): """Whether the configuration data has expired.""" return (self.config['last_update'] + timedelta(days=2)) < datetime.now() async def _update_config(self): """Update configuration data if required. Notes: Per `the documentation`_, this updates the API configuration data *"every few days"*. .. _the documentation: http://docs.themoviedb.apiary.io/#reference/configuration """ if self.config['data'] is None or self.config_expired: data = await self.get_data(self.url_builder('configuration')) self.config = dict(data=data, last_update=datetime.now()) async def get_data(self, url): """Get data from the TMDb API via :py:func:`aiohttp.get`. Notes: Updates configuration (if required) on successful requests. Arguments: url (:py:class:`str`): The endpoint URL and params. Returns: :py:class:`dict`: The parsed JSON result. """ logger.debug('making request to %r', url) with aiohttp.ClientSession() as session: async with session.get(url, headers=self.headers) as response: body = json.loads((await response.read()).decode('utf-8')) if response.status == HTTPStatus.OK: if url != self.url_builder('configuration'): await self._update_config() return body elif response.status == HTTPStatus.TOO_MANY_REQUESTS: timeout = self.calculate_timeout( response.headers['Retry-After'], ) logger.warning( 'Request limit exceeded, waiting %s seconds', timeout, ) await asyncio.sleep(timeout) return await self.get_data(url) logger.warning( 'request failed %s: %r', response.status, body.get('status_message', '<no message>') ) async def find_movie(self, query): """Retrieve movie data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ params = OrderedDict([ ('query', query), ('include_adult', False), ]) url = self.url_builder('search/movie', {}, params) data = await self.get_data(url) if data is None: return return [ Movie.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def find_person(self, query): """Retrieve person data by search query. Arguments: query (:py:class:`str`): Query to search for. Returns: :py:class:`list`: Possible matches. """ url = self.url_builder( 'search/person', dict(), url_params=OrderedDict([ ('query', query), ('include_adult', False) ]), ) data = await self.get_data(url) if data is None: return return [ Person.from_json(item, self.config['data'].get('images')) for item in data.get('results', []) ] async def get_movie(self, id_): """Retrieve movie data by ID. Arguments: id_ (:py:class:`int`): The movie's TMDb ID. Returns: :py:class:`~.Movie`: The requested movie. """ url = self.url_builder( 'movie/{movie_id}', dict(movie_id=id_), url_params=OrderedDict(append_to_response='credits'), ) data = await self.get_data(url) if data is None: return return Movie.from_json(data, self.config['data'].get('images')) async def get_person(self, id_): """Retrieve person data by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. Returns: :py:class:`~.Person`: The requested person. """ data = await self._get_person_json( id_, OrderedDict(append_to_response='movie_credits') ) return Person.from_json(data, self.config['data'].get('images')) async def _get_person_json(self, id_, url_params=None): """Retrieve raw person JSON by ID. Arguments: id_ (:py:class:`int`): The person's TMDb ID. url_params (:py:class:`dict`): Any additional URL parameters. Returns: :py:class:`dict`: The JSON data. """ url = self.url_builder( 'person/{person_id}', dict(person_id=id_), url_params=url_params or OrderedDict(), ) data = await self.get_data(url) return data async def get_random_popular_person(self, limit=500): """Randomly select a popular person. Notes: Requires at least two API calls. May require three API calls if the randomly-selected index isn't within the first page of required data. Arguments: limit (:py:class:`int`, optional): How many of the most popular people to make random choice from (defaults to top ``500``). Returns: :py:class:`~.Person`: A randomly-selected popular person. """ index = random.randrange(limit) data = await self._get_popular_people_page() if data is None: return if index >= len(data['results']): # result is not on first page page, index = self._calculate_page_index(index, data) data = await self._get_popular_people_page(page) if data is None: return json_data = data['results'][index] details = await self._get_person_json(json_data['id']) details.update(**json_data) return Person.from_json(details, self.config['data'].get('images')) async def _get_popular_people_page(self, page=1): """Get a specific page of popular person data. Arguments: page (:py:class:`int`, optional): The page to get. Returns: :py:class:`dict`: The page data. """ return await self.get_data(self.url_builder( 'person/popular', url_params=OrderedDict(page=page), )) @staticmethod
textbook/atmdb
atmdb/utils.py
_overlap
python
async def _overlap(items, overlap_attr, client=None, get_method=None): overlap = set.intersection(*(getattr(item, overlap_attr) for item in items)) if client is None or get_method is None: return overlap results = [] for item in overlap: result = await getattr(client, get_method)(id_=item.id_) results.append(result) return results
Generic overlap implementation. Arguments: item (:py:class:`collections.abc.Sequence`): The objects to find overlaps for. overlap_attr (:py:class:`str`): The attribute of the items to use as input for the overlap. client (:py:class:`~.TMDbClient`, optional): The TMDb client to extract additional information about the overlap. get_method (:py:class:`str`, optional): The method of the client to use for extracting additional information. Returns: :py:class:`list`: The relevant result objects.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/utils.py#L77-L101
null
"""Utilities for working with TMDb models.""" async def overlapping_movies(people, client=None): """Find movies that the same people have been in. Arguments: people (:py:class:`collections.abc.Sequence`): The :py:class:`~.Person` objects to find overlapping movies for. client (:py:class:`~.TMDbClient`, optional): The TMDb client to extract additional information about the overlap. Returns: :py:class:`list`: The relevant :py:class:`~.Movie` objects. """ return await _overlap(people, 'movie_credits', client, 'get_movie') async def overlapping_actors(movies, client=None): """Find actors that appear in the same movies. Arguments: movies (:py:class:`collections.abc.Sequence`): The :py:class:`~.Movie` objects to find overlapping actors for. client (:py:class:`~.TMDbClient`, optional): The TMDb client to extract additional information about the overlap. Returns: :py:class:`list`: The relevant :py:class:`~.Person` objects. """ return await _overlap(movies, 'cast', client, 'get_person') async def find_overlapping_movies(names, client): """Find movies that the same people have been in. Warning: This function requires two API calls per name submitted, plus one API call per overlapping movie in the result; it is therefore relatively slow. Arguments: names (:py:class:`collections.abc.Sequence`): The names of the people to find overlapping movies for. client (:py:class:`~.TMDbClient`): The TMDb client. Returns: :py:class:`list`: The relevant :py:class:`~.Movie` objects. """ return await _find_overlap(names, client, 'find_person', 'get_person', overlapping_movies) async def find_overlapping_actors(titles, client): """Find actors that have been in the same movies. Warning: This function requires two API calls per title submitted, plus one API call per overlapping person in the result; it is therefore relatively slow. Arguments: titles (:py:class:`collections.abc.Sequence`): The titles of the movies to find overlapping actors for. client (:py:class:`~.TMDbClient`): The TMDb client. Returns: :py:class:`list`: The relevant :py:class:`~.Person` objects. """ return await _find_overlap(titles, client, 'find_movie', 'get_movie', overlapping_actors) async def _find_overlap(queries, client, find_method, get_method, overlap_function): """Generic find and overlap implementation. Arguments names (:py:class:`collections.abc.Sequence`): The queries of the people to find overlaps for. client (:py:class:`~.TMDbClient`): The TMDb client. find_method (:py:class:`str`): The name of the client method to use for finding candidates. get_method (:py:class:`str`): The name of the client method to use for getting detailed information on a candidate. overlap_function (:py:class:`collections.abc.Callable`): The function to call for the resulting overlap. """ results = [] for query in queries: candidates = await getattr(client, find_method)(query) if not candidates: raise ValueError('no result found for {!r}'.format(query)) result = await getattr(client, get_method)(id_=candidates[0].id_) results.append(result) return await overlap_function(results, client)
textbook/atmdb
atmdb/utils.py
_find_overlap
python
async def _find_overlap(queries, client, find_method, get_method, overlap_function): results = [] for query in queries: candidates = await getattr(client, find_method)(query) if not candidates: raise ValueError('no result found for {!r}'.format(query)) result = await getattr(client, get_method)(id_=candidates[0].id_) results.append(result) return await overlap_function(results, client)
Generic find and overlap implementation. Arguments names (:py:class:`collections.abc.Sequence`): The queries of the people to find overlaps for. client (:py:class:`~.TMDbClient`): The TMDb client. find_method (:py:class:`str`): The name of the client method to use for finding candidates. get_method (:py:class:`str`): The name of the client method to use for getting detailed information on a candidate. overlap_function (:py:class:`collections.abc.Callable`): The function to call for the resulting overlap.
train
https://github.com/textbook/atmdb/blob/cab14547d2e777a1e26c2560266365c484855789/atmdb/utils.py#L104-L127
[ "async def overlapping_actors(movies, client=None):\n \"\"\"Find actors that appear in the same movies.\n\n Arguments:\n movies (:py:class:`collections.abc.Sequence`): The\n :py:class:`~.Movie` objects to find overlapping actors for.\n client (:py:class:`~.TMDbClient`, optional): The TMDb client\n to extract additional information about the overlap.\n\n Returns:\n :py:class:`list`: The relevant :py:class:`~.Person` objects.\n\n \"\"\"\n return await _overlap(movies, 'cast', client, 'get_person')\n", "async def overlapping_movies(people, client=None):\n \"\"\"Find movies that the same people have been in.\n\n Arguments:\n people (:py:class:`collections.abc.Sequence`): The\n :py:class:`~.Person` objects to find overlapping movies for.\n client (:py:class:`~.TMDbClient`, optional): The TMDb client\n to extract additional information about the overlap.\n\n Returns:\n :py:class:`list`: The relevant :py:class:`~.Movie` objects.\n\n \"\"\"\n return await _overlap(people, 'movie_credits', client, 'get_movie')\n" ]
"""Utilities for working with TMDb models.""" async def overlapping_movies(people, client=None): """Find movies that the same people have been in. Arguments: people (:py:class:`collections.abc.Sequence`): The :py:class:`~.Person` objects to find overlapping movies for. client (:py:class:`~.TMDbClient`, optional): The TMDb client to extract additional information about the overlap. Returns: :py:class:`list`: The relevant :py:class:`~.Movie` objects. """ return await _overlap(people, 'movie_credits', client, 'get_movie') async def overlapping_actors(movies, client=None): """Find actors that appear in the same movies. Arguments: movies (:py:class:`collections.abc.Sequence`): The :py:class:`~.Movie` objects to find overlapping actors for. client (:py:class:`~.TMDbClient`, optional): The TMDb client to extract additional information about the overlap. Returns: :py:class:`list`: The relevant :py:class:`~.Person` objects. """ return await _overlap(movies, 'cast', client, 'get_person') async def find_overlapping_movies(names, client): """Find movies that the same people have been in. Warning: This function requires two API calls per name submitted, plus one API call per overlapping movie in the result; it is therefore relatively slow. Arguments: names (:py:class:`collections.abc.Sequence`): The names of the people to find overlapping movies for. client (:py:class:`~.TMDbClient`): The TMDb client. Returns: :py:class:`list`: The relevant :py:class:`~.Movie` objects. """ return await _find_overlap(names, client, 'find_person', 'get_person', overlapping_movies) async def find_overlapping_actors(titles, client): """Find actors that have been in the same movies. Warning: This function requires two API calls per title submitted, plus one API call per overlapping person in the result; it is therefore relatively slow. Arguments: titles (:py:class:`collections.abc.Sequence`): The titles of the movies to find overlapping actors for. client (:py:class:`~.TMDbClient`): The TMDb client. Returns: :py:class:`list`: The relevant :py:class:`~.Person` objects. """ return await _find_overlap(titles, client, 'find_movie', 'get_movie', overlapping_actors) async def _overlap(items, overlap_attr, client=None, get_method=None): """Generic overlap implementation. Arguments: item (:py:class:`collections.abc.Sequence`): The objects to find overlaps for. overlap_attr (:py:class:`str`): The attribute of the items to use as input for the overlap. client (:py:class:`~.TMDbClient`, optional): The TMDb client to extract additional information about the overlap. get_method (:py:class:`str`, optional): The method of the client to use for extracting additional information. Returns: :py:class:`list`: The relevant result objects. """ overlap = set.intersection(*(getattr(item, overlap_attr) for item in items)) if client is None or get_method is None: return overlap results = [] for item in overlap: result = await getattr(client, get_method)(id_=item.id_) results.append(result) return results
by46/simplekit
simplekit/url/omdict1D.py
omdict1D._bin_update_items
python
def _bin_update_items(self, items, replace_at_most_one, replacements, leftovers): for key, values in items: # <values> is not a list or an empty list. like_list_not_str = self._quacks_like_a_list_but_not_str(values) if not like_list_not_str or (like_list_not_str and not values): values = [values] for value in values: # If the value is [], remove any existing leftovers with # key <key> and set the list of values itself to [], # which in turn will later delete <key> when [] is # passed to omdict.setlist() in # omdict._update_updateall(). if value == []: replacements[key] = [] leftovers[:] = [l for l in leftovers if key != l[0]] continue # If there are existing items with key <key> that have # yet to be marked for replacement, mark that item's # value to be replaced by <value> by appending it to # <replacements>. TODO: Refactor for clarity if (key in self and (key not in replacements or (key in replacements and replacements[key] == []))): replacements[key] = [value] elif (key in self and not replace_at_most_one and len(replacements[key]) < len(self.values(key))): replacements[key].append(value) else: if replace_at_most_one: replacements[key] = [value] else: leftovers.append((key, value))
Subclassed from omdict._bin_update_items() to make update() and updateall() process lists of values as multiple values. <replacements and <leftovers> are modified directly, ala pass by reference.
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/url/omdict1D.py#L62-L104
null
class omdict1D(omdict): """ One dimensional ordered multivalue dictionary. Whenever a list of values is passed to set(), __setitem__(), add(), update(), or updateall(), it's treated as multiple values and the appropriate 'list' method is called on that list, like setlist() or addlist(). For example: omd = omdict1D() omd[1] = [1,2,3] omd[1] != [1,2,3] # True. omd[1] == 1 # True. omd.getlist(1) == [1,2,3] # True. omd.add(2, [2,3,4]) omd[2] != [2,3,4] # True. omd[2] == 2 # True. omd.getlist(2) == [2,3,4] # True. omd.update([(3, [3,4,5])]) omd[3] != [3,4,5] # True. omd[3] == 3 # True. omd.getlist(3) == [3,4,5] # True. omd = omdict([(1,None),(2,None)]) omd.updateall([(1,[1,11]), (2,[2,22])]) omd.allitems == [(1,1), (1,11), (2,2), (2,22)] """ def add(self, key, value=[]): if not self._quacks_like_a_list_but_not_str(value): value = [value] if value: self._map.setdefault(key, []) for val in value: node = self._items.append(key, val) self._map[key].append(node) return self def set(self, key, value=[None]): return self._set(key, value) def __setitem__(self, key, value): return self._set(key, value) def _set(self, key, value=[None]): if not self._quacks_like_a_list_but_not_str(value): value = [value] self.setlist(key, value) return self def _quacks_like_a_list_but_not_str(self, duck): return (hasattr(duck, '__iter__') and callable(duck.__iter__) and not isinstance(duck, str))
by46/simplekit
simplekit/config/__init__.py
import_string
python
def import_string(import_name, silent=False): """Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If `silent` is True the return value will be `None` if the import fails. :param import_name: the dotted name for the object to import. :param silent: if set to `True` import errors are ignored and `None` is returned instead. :return: imported object """ # force the import name to automatically convert to strings # __import__ is not able to handle unicode strings in the fromlist # if the module is a package import_name = str(import_name).replace(':', '.') try: try: __import__(import_name) except ImportError: if '.' not in import_name: raise else: return sys.modules[import_name] module_name, obj_name = import_name.rsplit('.', 1) try: module = __import__(module_name, None, None, [obj_name]) except ImportError: # support importing modules not yet set up by the parent module # (or package for that matter) module = import_string(module_name) try: return getattr(module, obj_name) except AttributeError as e: raise ImportError(e) except ImportError as e: if not silent: raise e
Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If `silent` is True the return value will be `None` if the import fails. :param import_name: the dotted name for the object to import. :param silent: if set to `True` import errors are ignored and `None` is returned instead. :return: imported object
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/config/__init__.py#L15-L56
[ "def import_string(import_name, silent=False):\n \"\"\"Imports an object based on a string. This is useful if you want to\n use import paths as endpoints or something similar. An import path can\n be specified either in dotted notation (``xml.sax.saxutils.escape``)\n or with a colon as object delimiter (``xml.sax.saxutils:escape``).\n\n If `silent` is True the return value will be `None` if the import fails.\n\n :param import_name: the dotted name for the object to import.\n :param silent: if set to `True` import errors are ignored and\n `None` is returned instead.\n :return: imported object\n \"\"\"\n # force the import name to automatically convert to strings\n # __import__ is not able to handle unicode strings in the fromlist\n # if the module is a package\n import_name = str(import_name).replace(':', '.')\n try:\n try:\n __import__(import_name)\n except ImportError:\n if '.' not in import_name:\n raise\n else:\n return sys.modules[import_name]\n\n module_name, obj_name = import_name.rsplit('.', 1)\n try:\n module = __import__(module_name, None, None, [obj_name])\n except ImportError:\n # support importing modules not yet set up by the parent module\n # (or package for that matter)\n module = import_string(module_name)\n\n try:\n return getattr(module, obj_name)\n except AttributeError as e:\n raise ImportError(e)\n\n except ImportError as e:\n if not silent:\n raise e\n" ]
import errno import functools import json import logging import os.path import sqlite3 import sys import types import six __author__ = 'benjamin.c.yan' def import_string(import_name, silent=False): """Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (``xml.sax.saxutils.escape``) or with a colon as object delimiter (``xml.sax.saxutils:escape``). If `silent` is True the return value will be `None` if the import fails. :param import_name: the dotted name for the object to import. :param silent: if set to `True` import errors are ignored and `None` is returned instead. :return: imported object """ # force the import name to automatically convert to strings # __import__ is not able to handle unicode strings in the fromlist # if the module is a package import_name = str(import_name).replace(':', '.') try: try: __import__(import_name) except ImportError: if '.' not in import_name: raise else: return sys.modules[import_name] module_name, obj_name = import_name.rsplit('.', 1) try: module = __import__(module_name, None, None, [obj_name]) except ImportError: # support importing modules not yet set up by the parent module # (or package for that matter) module = import_string(module_name) try: return getattr(module, obj_name) except AttributeError as e: raise ImportError(e) except ImportError as e: if not silent: raise e class Config(dict): def __init__(self, root_path, default=None): dict.__init__(self, default or {}) self.root_path = root_path def from_pyfile(self, filename, silent=False): """Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the `from_object` function. :param filename: the filename of the config. This can either be an absolute filename or a filename relative to the root path. :param silent: set to ``True`` if you want silent failure for missing files. """ filename = os.path.join(self.root_path, filename) d = types.ModuleType("config") d.__file__ = filename try: with open(filename, 'r') as config_file: exec (compile(config_file.read(), filename, 'exec'), d.__dict__) except IOError as e: if silent and e.errno in (errno.EISDIR, errno.ENOENT): return False e.strerror = "Unable to load configuration file (%s)" % e.strerror raise self.from_object(d) return True def from_object(self, obj): """Updates the values from the given object. An object can be of one of the following one types: - an actual object reference: that object is used directly Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_config app.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an import name or object """ if isinstance(obj, six.string_types): obj = import_string(obj) for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key) def from_json(self, filename, silent=False): """Updates the values in the config from a JSON file. This function behaves as if the JSON object was a dictionary and passed to the :meth:`from_mapping` function. :param filename: the filename of the JSON file. This can either be an absolute filename or a filename relative to the root path. :param silent: set to ``True`` if you want silent failure for missing files. """ filename = os.path.join(self.root_path, filename) try: with open(filename) as json_file: obj = json.load(json_file) except IOError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): return False e.strerror = 'Unable to load configuration file (%s)' % e.strerror raise return self.from_mapping(obj) def from_mapping(self, *mapping, **kwargs): """Updates the config like :meth:`update` ignoring items with non-upper keys. """ mappings = [] if len(mapping) == 1: if hasattr(mapping[0], 'items'): mappings.append(mapping[0].items()) else: mappings.append(mapping[0]) elif len(mapping) > 1: raise TypeError('expected at most 1 positional argument, got %d' % len(mapping)) mappings.append(kwargs.items()) for mapping in mappings: for key, value in mapping: if key.isupper(): self[key] = value return True def get_namespace(self, namespace, lowercase=True, trim_namespace=True): """Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE']='fs' app.config['IMAGE_STORE_PATH']='/var/app/images' app.config['IMAGE_STORE_BASE_URL']='http://img.website.com' The result dictionary `image_store` would look like: { 'type': 'fs', 'path': '/var/app/images', 'base_url':'http://image.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. :param namespace: a configuration namespace :param lowercase: a flag indicating if the keys of the resulting dictionary should be lowercase :param trim_namespace: a flag indicating if the keys of the resulting dictionary should not include the namespace :return: a dict instance """ rv = {} for key, value in six.iteritems(self): if not key.startswith(namespace): continue if trim_namespace: key = key[len(namespace):] else: key = key if lowercase: key = key.lower() rv[key] = value return rv def __repr__(self): return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self)) def auto_commit(fn): @functools.wraps(fn) def tmp(self, *args, **kwargs): connection = sqlite3.connect(self.db_full_path) cursor = connection.cursor() try: kwargs['cursor'] = cursor fn(self, *args, **kwargs) finally: cursor.close() connection.commit() connection.close() return tmp class SQLiteConfig(dict): """Configuration with SQLite file Provide retrieve, update, and delete ``(key, value)`` pair style configuration. Any changed will save to SQLite file. Basic Usage:: >>> import simplekit.config >>> config = simplekit.config.SQLiteConfig('configuration.db', default=dict(name='benjamin')) >>> assert config.name == 'benjamin' >>> config.age = 21 >>> config['high'] = 175 >>> config.close() >>> config = simplekit.config.SQLiteConfig('configuration.db') >>> assert config.name == 'benjamin' >>> assert config.age == 21 >>> assert config['age'] == 21 >>> assert config.high == 175 >>> assert config['high'] == 175 >>> del config.age >>> del config['high'] >>> assert config.age is None >>> assert config.high is None >>> config.generic_name = 'benjamin' >>> config.generic_age = 27 >>> config.generic_high = 175 >>> groups = config.get_namespace('generic_') >>> assert groups == dict(name='benjamin', age=27, high=175) """ def __init__(self, db_full_path, default=None, logger=None): """initialize a configuration instance. :param db_full_path: SQLite file's full path which save the configuration :param default: :class:`dict`, default configuration for new configuration base. """ if not logger: logger = logging.getLogger('app') self.__logger = logger self.__db_full_path = db_full_path if not os.path.exists(db_full_path): self.__create_db(db_full_path, default) else: self.__load() @property def logger(self): return self.__logger @property def db_full_path(self): return self.__db_full_path def get_namespace(self, namespace, lowercase=True, trim_namespace=True): """Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage:: app.config['IMAGE_STORE_TYPE']='fs' app.config['IMAGE_STORE_PATH']='/var/app/images' app.config['IMAGE_STORE_BASE_URL']='http://img.website.com' The result dictionary `image_store` would look like:: { 'type': 'fs', 'path': '/var/app/images', 'base_url':'http://image.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. :param namespace: a configuration namespace :param lowercase: a flag indicating if the keys of the resulting dictionary should be lowercase :param trim_namespace: a flag indicating if the keys of the resulting dictionary should not include the namespace :return: a dict instance """ rv = {} for key, value in six.iteritems(self): if not key.startswith(namespace): continue if trim_namespace: key = key[len(namespace):] else: key = key if lowercase: key = key.lower() rv[key] = value return rv def close(self): pass def update(self, *args, **kwargs): raise NotImplementedError() def __setitem__(self, key, value): self.__update_key(key, value) super(SQLiteConfig, self).__setitem__(key, value) def __delitem__(self, key): self.__delete_key(key) super(SQLiteConfig, self).__delitem__(key) def __getattr__(self, key): return self.get(key) def __setattr__(self, key, value): if not key.startswith('_'): self[key] = value else: self.__dict__[key] = value def __delattr__(self, key): if not key.startswith('_'): if key in self: del self[key] else: del self.__dict__[key] @auto_commit def __load(self, cursor=None): cursor.execute('SELECT key, value, type FROM profile') for key, value, type_string in cursor: try: # TODO(benjamin): optimize code, especially security checking value = eval('%s("%s")' % (type_string, value)) except ValueError: pass super(SQLiteConfig, self).__setitem__(str(key), value) @auto_commit def __create_db(self, db_full_path, default=None, cursor=None): try: create_sql = """ CREATE TABLE IF NOT EXISTS profile (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, key TEXT, value TEXT, type TEXT); """ cursor.execute(create_sql) except sqlite3.DatabaseError, e: # TODO(benjamin): log error self.logger.error("create db %s error: %s" % (db_full_path, e)) raise e # TODO(benjamin): valid checking if default: text = "INSERT INTO profile(key, value, type) VALUES(?, ?, ?)" params = [(key, value, type(value).__name__) for key, value in default.items()] cursor.executemany(text, params) super(SQLiteConfig, self).update(default) @auto_commit def __update_key(self, key, value, cursor=None): cursor.execute('SELECT 1 FROM profile WHERE key=?', (key,)) if cursor.rowcount == 1: text = 'UPDATE profile SET value=?, type=? WHERE key=?' data = (value, type(value).__name__, key) else: text = 'INSERT INTO profile(key,value,type) VALUES(?, ?, ?)' data = (key, value, type(value).__name__) cursor.execute(text, data) @auto_commit def __delete_key(self, key, cursor=None): cursor.execute('DELETE FROM profile WHERE key=?', (key,))
by46/simplekit
simplekit/config/__init__.py
Config.from_mapping
python
def from_mapping(self, *mapping, **kwargs): """Updates the config like :meth:`update` ignoring items with non-upper keys. """ mappings = [] if len(mapping) == 1: if hasattr(mapping[0], 'items'): mappings.append(mapping[0].items()) else: mappings.append(mapping[0]) elif len(mapping) > 1: raise TypeError('expected at most 1 positional argument, got %d' % len(mapping)) mappings.append(kwargs.items()) for mapping in mappings: for key, value in mapping: if key.isupper(): self[key] = value return True
Updates the config like :meth:`update` ignoring items with non-upper keys.
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/config/__init__.py#L141-L159
null
class Config(dict): def __init__(self, root_path, default=None): dict.__init__(self, default or {}) self.root_path = root_path def from_pyfile(self, filename, silent=False): """Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the `from_object` function. :param filename: the filename of the config. This can either be an absolute filename or a filename relative to the root path. :param silent: set to ``True`` if you want silent failure for missing files. """ filename = os.path.join(self.root_path, filename) d = types.ModuleType("config") d.__file__ = filename try: with open(filename, 'r') as config_file: exec (compile(config_file.read(), filename, 'exec'), d.__dict__) except IOError as e: if silent and e.errno in (errno.EISDIR, errno.ENOENT): return False e.strerror = "Unable to load configuration file (%s)" % e.strerror raise self.from_object(d) return True def from_object(self, obj): """Updates the values from the given object. An object can be of one of the following one types: - an actual object reference: that object is used directly Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_config app.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an import name or object """ if isinstance(obj, six.string_types): obj = import_string(obj) for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key) def from_json(self, filename, silent=False): """Updates the values in the config from a JSON file. This function behaves as if the JSON object was a dictionary and passed to the :meth:`from_mapping` function. :param filename: the filename of the JSON file. This can either be an absolute filename or a filename relative to the root path. :param silent: set to ``True`` if you want silent failure for missing files. """ filename = os.path.join(self.root_path, filename) try: with open(filename) as json_file: obj = json.load(json_file) except IOError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): return False e.strerror = 'Unable to load configuration file (%s)' % e.strerror raise return self.from_mapping(obj) def from_mapping(self, *mapping, **kwargs): """Updates the config like :meth:`update` ignoring items with non-upper keys. """ mappings = [] if len(mapping) == 1: if hasattr(mapping[0], 'items'): mappings.append(mapping[0].items()) else: mappings.append(mapping[0]) elif len(mapping) > 1: raise TypeError('expected at most 1 positional argument, got %d' % len(mapping)) mappings.append(kwargs.items()) for mapping in mappings: for key, value in mapping: if key.isupper(): self[key] = value return True def get_namespace(self, namespace, lowercase=True, trim_namespace=True): """Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE']='fs' app.config['IMAGE_STORE_PATH']='/var/app/images' app.config['IMAGE_STORE_BASE_URL']='http://img.website.com' The result dictionary `image_store` would look like: { 'type': 'fs', 'path': '/var/app/images', 'base_url':'http://image.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. :param namespace: a configuration namespace :param lowercase: a flag indicating if the keys of the resulting dictionary should be lowercase :param trim_namespace: a flag indicating if the keys of the resulting dictionary should not include the namespace :return: a dict instance """ rv = {} for key, value in six.iteritems(self): if not key.startswith(namespace): continue if trim_namespace: key = key[len(namespace):] else: key = key if lowercase: key = key.lower() rv[key] = value return rv def __repr__(self): return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))
by46/simplekit
simplekit/config/__init__.py
Config.get_namespace
python
def get_namespace(self, namespace, lowercase=True, trim_namespace=True): """Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE']='fs' app.config['IMAGE_STORE_PATH']='/var/app/images' app.config['IMAGE_STORE_BASE_URL']='http://img.website.com' The result dictionary `image_store` would look like: { 'type': 'fs', 'path': '/var/app/images', 'base_url':'http://image.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. :param namespace: a configuration namespace :param lowercase: a flag indicating if the keys of the resulting dictionary should be lowercase :param trim_namespace: a flag indicating if the keys of the resulting dictionary should not include the namespace :return: a dict instance """ rv = {} for key, value in six.iteritems(self): if not key.startswith(namespace): continue if trim_namespace: key = key[len(namespace):] else: key = key if lowercase: key = key.lower() rv[key] = value return rv
Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE']='fs' app.config['IMAGE_STORE_PATH']='/var/app/images' app.config['IMAGE_STORE_BASE_URL']='http://img.website.com' The result dictionary `image_store` would look like: { 'type': 'fs', 'path': '/var/app/images', 'base_url':'http://image.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. :param namespace: a configuration namespace :param lowercase: a flag indicating if the keys of the resulting dictionary should be lowercase :param trim_namespace: a flag indicating if the keys of the resulting dictionary should not include the namespace :return: a dict instance
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/config/__init__.py#L161-L194
null
class Config(dict): def __init__(self, root_path, default=None): dict.__init__(self, default or {}) self.root_path = root_path def from_pyfile(self, filename, silent=False): """Updates the values in the config from a Python file. This function behaves as if the file was imported as module with the `from_object` function. :param filename: the filename of the config. This can either be an absolute filename or a filename relative to the root path. :param silent: set to ``True`` if you want silent failure for missing files. """ filename = os.path.join(self.root_path, filename) d = types.ModuleType("config") d.__file__ = filename try: with open(filename, 'r') as config_file: exec (compile(config_file.read(), filename, 'exec'), d.__dict__) except IOError as e: if silent and e.errno in (errno.EISDIR, errno.ENOENT): return False e.strerror = "Unable to load configuration file (%s)" % e.strerror raise self.from_object(d) return True def from_object(self, obj): """Updates the values from the given object. An object can be of one of the following one types: - an actual object reference: that object is used directly Objects are usually either modules or classes. Just the uppercase variables in that object are stored in the config. Example usage:: from yourapplication import default_config app.config.from_object(default_config) You should not use this function to load the actual configuration but rather configuration defaults. The actual config should be loaded with :meth:`from_pyfile` and ideally from a location not within the package because the package might be installed system wide. :param obj: an import name or object """ if isinstance(obj, six.string_types): obj = import_string(obj) for key in dir(obj): if key.isupper(): self[key] = getattr(obj, key) def from_json(self, filename, silent=False): """Updates the values in the config from a JSON file. This function behaves as if the JSON object was a dictionary and passed to the :meth:`from_mapping` function. :param filename: the filename of the JSON file. This can either be an absolute filename or a filename relative to the root path. :param silent: set to ``True`` if you want silent failure for missing files. """ filename = os.path.join(self.root_path, filename) try: with open(filename) as json_file: obj = json.load(json_file) except IOError as e: if silent and e.errno in (errno.ENOENT, errno.EISDIR): return False e.strerror = 'Unable to load configuration file (%s)' % e.strerror raise return self.from_mapping(obj) def from_mapping(self, *mapping, **kwargs): """Updates the config like :meth:`update` ignoring items with non-upper keys. """ mappings = [] if len(mapping) == 1: if hasattr(mapping[0], 'items'): mappings.append(mapping[0].items()) else: mappings.append(mapping[0]) elif len(mapping) > 1: raise TypeError('expected at most 1 positional argument, got %d' % len(mapping)) mappings.append(kwargs.items()) for mapping in mappings: for key, value in mapping: if key.isupper(): self[key] = value return True def get_namespace(self, namespace, lowercase=True, trim_namespace=True): """Returns a dictionary containing a subset of configuration options that match the specified namespace/prefix. Example usage: app.config['IMAGE_STORE_TYPE']='fs' app.config['IMAGE_STORE_PATH']='/var/app/images' app.config['IMAGE_STORE_BASE_URL']='http://img.website.com' The result dictionary `image_store` would look like: { 'type': 'fs', 'path': '/var/app/images', 'base_url':'http://image.website.com' } This is often useful when configuration options map directly to keyword arguments in functions or class constructors. :param namespace: a configuration namespace :param lowercase: a flag indicating if the keys of the resulting dictionary should be lowercase :param trim_namespace: a flag indicating if the keys of the resulting dictionary should not include the namespace :return: a dict instance """ rv = {} for key, value in six.iteritems(self): if not key.startswith(namespace): continue if trim_namespace: key = key[len(namespace):] else: key = key if lowercase: key = key.lower() rv[key] = value return rv def __repr__(self): return '<%s %s>' % (self.__class__.__name__, dict.__repr__(self))
by46/simplekit
simplekit/objson/dolphin2.py
dumps
python
def dumps(obj, *args, **kwargs): kwargs['default'] = object2dict return json.dumps(obj, *args, **kwargs)
Serialize a object to string Basic Usage: >>> import simplekit.objson >>> obj = {'name':'wendy'} >>> print simplekit.objson.dumps(obj) :param obj: a object which need to dump :param args: Optional arguments that :func:`json.dumps` takes. :param kwargs: Keys arguments that :py:func:`json.dumps` takes. :return: string
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/objson/dolphin2.py#L78-L95
null
import functools import json import re from keyword import iskeyword __author__ = 'benjamin.c.yan' _re_encode = re.compile('[^a-zA-Z0-9]', re.MULTILINE) def object2dict(obj): return obj.__dict__ def object_hook(obj): return Dolphin(obj) def empty(other=None): """ new an empty object basic usage :: >>> from simplekit import objson >>> obj = objson.empty() >>> obj2 = objson.empty(dict(name='benjamin', sex='male')) >>> assert obj2.name == 'benjamin' >>> assert obj2.sex == 'male' :param other: :class:``dict``, initialize properties :return: an instance of :class:``Dolphin`` """ return Dolphin(other) class Dolphin(object): def __init__(self, other=None): if other: if isinstance(other, Dolphin): other = other.__dict__ self.__dict__.update(other) def __iter__(self): return iter(self.__dict__) def __getitem__(self, key): key = str(key) if not key.startswith('_'): return self.__dict__.get(key) def __setitem__(self, key, value): key = str(key) if not key.startswith('_'): self.__dict__[key] = value def __getattr__(self, name): name = str(name) if not name.startswith('_'): if name in self: return self[name] elif name.startswith('m') and (iskeyword(name[1:]) or len(name) > 1 and name[1].isdigit()): return self[name[1:]] elif '_' in name: return self[_re_encode.sub('-', name)] def __str__(self): return '%s (%s)' % (self.__class__.__name__, repr(self)) def __repr__(self): keys = sorted(self.__dict__.keys()) text = ', '.join('%s=%r' % (key, self[key]) for key in keys) return '{%s}' % text def __eq__(self, other): return str(self) == str(other) def dump(obj, fp, *args, **kwargs): """Serialize a object to a file object. Basic Usage: >>> import simplekit.objson >>> from cStringIO import StringIO >>> obj = {'name': 'wendy'} >>> io = StringIO() >>> simplekit.objson.dump(obj, io) >>> print io.getvalue() :param obj: a object which need to dump :param fp: a instance of file object :param args: Optional arguments that :func:`json.dump` takes. :param kwargs: Keys arguments that :func:`json.dump` takes. :return: None """ kwargs['default'] = object2dict json.dump(obj, fp, *args, **kwargs) def _load(fn): @functools.wraps(fn) def tmp(src, *args, **kwargs): """Deserialize json string to a object Provide a brief way to represent a object, Can use ``.`` operate access Json object property Basic Usage: >>> from simplekit import objson >>> text = r'{"Name":"wendy"}' >>> obj = objson.loads(text) >>> assert obj.Name == 'wendy' :param src: string or file object :param args: Optional arguments that :func:`json.load` takes. :param kwargs: Keys arguments that :func:`json.loads` takes. :return: :class:`object` or :class:`list` """ try: kwargs['object_hook'] = object_hook return fn(src, *args, **kwargs) except ValueError: return None return tmp load = _load(json.load) loads = _load(json.loads)
by46/simplekit
simplekit/objson/dolphin2.py
dump
python
def dump(obj, fp, *args, **kwargs): kwargs['default'] = object2dict json.dump(obj, fp, *args, **kwargs)
Serialize a object to a file object. Basic Usage: >>> import simplekit.objson >>> from cStringIO import StringIO >>> obj = {'name': 'wendy'} >>> io = StringIO() >>> simplekit.objson.dump(obj, io) >>> print io.getvalue() :param obj: a object which need to dump :param fp: a instance of file object :param args: Optional arguments that :func:`json.dump` takes. :param kwargs: Keys arguments that :func:`json.dump` takes. :return: None
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/objson/dolphin2.py#L98-L118
null
import functools import json import re from keyword import iskeyword __author__ = 'benjamin.c.yan' _re_encode = re.compile('[^a-zA-Z0-9]', re.MULTILINE) def object2dict(obj): return obj.__dict__ def object_hook(obj): return Dolphin(obj) def empty(other=None): """ new an empty object basic usage :: >>> from simplekit import objson >>> obj = objson.empty() >>> obj2 = objson.empty(dict(name='benjamin', sex='male')) >>> assert obj2.name == 'benjamin' >>> assert obj2.sex == 'male' :param other: :class:``dict``, initialize properties :return: an instance of :class:``Dolphin`` """ return Dolphin(other) class Dolphin(object): def __init__(self, other=None): if other: if isinstance(other, Dolphin): other = other.__dict__ self.__dict__.update(other) def __iter__(self): return iter(self.__dict__) def __getitem__(self, key): key = str(key) if not key.startswith('_'): return self.__dict__.get(key) def __setitem__(self, key, value): key = str(key) if not key.startswith('_'): self.__dict__[key] = value def __getattr__(self, name): name = str(name) if not name.startswith('_'): if name in self: return self[name] elif name.startswith('m') and (iskeyword(name[1:]) or len(name) > 1 and name[1].isdigit()): return self[name[1:]] elif '_' in name: return self[_re_encode.sub('-', name)] def __str__(self): return '%s (%s)' % (self.__class__.__name__, repr(self)) def __repr__(self): keys = sorted(self.__dict__.keys()) text = ', '.join('%s=%r' % (key, self[key]) for key in keys) return '{%s}' % text def __eq__(self, other): return str(self) == str(other) def dumps(obj, *args, **kwargs): """Serialize a object to string Basic Usage: >>> import simplekit.objson >>> obj = {'name':'wendy'} >>> print simplekit.objson.dumps(obj) :param obj: a object which need to dump :param args: Optional arguments that :func:`json.dumps` takes. :param kwargs: Keys arguments that :py:func:`json.dumps` takes. :return: string """ kwargs['default'] = object2dict return json.dumps(obj, *args, **kwargs) def _load(fn): @functools.wraps(fn) def tmp(src, *args, **kwargs): """Deserialize json string to a object Provide a brief way to represent a object, Can use ``.`` operate access Json object property Basic Usage: >>> from simplekit import objson >>> text = r'{"Name":"wendy"}' >>> obj = objson.loads(text) >>> assert obj.Name == 'wendy' :param src: string or file object :param args: Optional arguments that :func:`json.load` takes. :param kwargs: Keys arguments that :func:`json.loads` takes. :return: :class:`object` or :class:`list` """ try: kwargs['object_hook'] = object_hook return fn(src, *args, **kwargs) except ValueError: return None return tmp load = _load(json.load) loads = _load(json.loads)
by46/simplekit
simplekit/docker/utils.py
request
python
def request(method='GET'): """send restful post http request decorator Provide a brief way to manipulate restful api, :param method: :class:`str`, :return: :class:`func` """ def decorator(func): @functools.wraps(func) def action(self, *args, **kwargs): f = furl(self.server) path, body = func(self, *args, **kwargs) # deal with query string query = dict() if isinstance(path, tuple): path, query = path f.path.add(path) f.query.set(query) status_code, result = send_rest(f.url, method=method.upper(), body=body, session=self.session, headers=self.headers) if status_code != httplib.OK: self.logger.error("{impl} {url} headers: {headers}, code: {code}".format( impl=method, url=f.url, headers=self.headers, code=status_code)) return status_code, result return action return decorator
send restful post http request decorator Provide a brief way to manipulate restful api, :param method: :class:`str`, :return: :class:`func`
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/utils.py#L11-L45
null
import functools import httplib from furl import furl from .rest import send_rest __author__ = 'benjamin.c.yan' def request(method='GET'): """send restful post http request decorator Provide a brief way to manipulate restful api, :param method: :class:`str`, :return: :class:`func` """ def decorator(func): @functools.wraps(func) def action(self, *args, **kwargs): f = furl(self.server) path, body = func(self, *args, **kwargs) # deal with query string query = dict() if isinstance(path, tuple): path, query = path f.path.add(path) f.query.set(query) status_code, result = send_rest(f.url, method=method.upper(), body=body, session=self.session, headers=self.headers) if status_code != httplib.OK: self.logger.error("{impl} {url} headers: {headers}, code: {code}".format( impl=method, url=f.url, headers=self.headers, code=status_code)) return status_code, result return action return decorator def parse_image_name(name): """ parse the image name into three element tuple, like below: (repository, name, version) :param name: `class`:`str`, name :return: (repository, name, version) """ name = name or "" if '/' in name: repository, other = name.split('/') else: repository, other = None, name if ':' in other: name, version = other.split(':') else: name, version = other, 'latest' return repository, name, version
by46/simplekit
simplekit/docker/utils.py
parse_image_name
python
def parse_image_name(name): """ parse the image name into three element tuple, like below: (repository, name, version) :param name: `class`:`str`, name :return: (repository, name, version) """ name = name or "" if '/' in name: repository, other = name.split('/') else: repository, other = None, name if ':' in other: name, version = other.split(':') else: name, version = other, 'latest' return repository, name, version
parse the image name into three element tuple, like below: (repository, name, version) :param name: `class`:`str`, name :return: (repository, name, version)
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/utils.py#L48-L66
null
import functools import httplib from furl import furl from .rest import send_rest __author__ = 'benjamin.c.yan' def request(method='GET'): """send restful post http request decorator Provide a brief way to manipulate restful api, :param method: :class:`str`, :return: :class:`func` """ def decorator(func): @functools.wraps(func) def action(self, *args, **kwargs): f = furl(self.server) path, body = func(self, *args, **kwargs) # deal with query string query = dict() if isinstance(path, tuple): path, query = path f.path.add(path) f.query.set(query) status_code, result = send_rest(f.url, method=method.upper(), body=body, session=self.session, headers=self.headers) if status_code != httplib.OK: self.logger.error("{impl} {url} headers: {headers}, code: {code}".format( impl=method, url=f.url, headers=self.headers, code=status_code)) return status_code, result return action return decorator def parse_image_name(name): """ parse the image name into three element tuple, like below: (repository, name, version) :param name: `class`:`str`, name :return: (repository, name, version) """ name = name or "" if '/' in name: repository, other = name.split('/') else: repository, other = None, name if ':' in other: name, version = other.split(':') else: name, version = other, 'latest' return repository, name, version
by46/simplekit
simplekit/objson/dynamic_class.py
make_dynamic_class
python
def make_dynamic_class(typename, field_names): if isinstance(field_names, basestring): field_names = field_names.replace(",", " ").split() field_names = map(str, field_names) safe_fields_names = map(_encode_property_name, field_names) attr = dict((safe_name, _property(name)) for name, safe_name in zip(field_names, safe_fields_names)) attr['__doc__'] = typename attr['__identifier__'] = "dolphin" attr['__init__'] = _dynamic__init attr['__getitem__'] = lambda self, key: self.__dict__.get(key) attr['__setitem__'] = _dynamic__setitem attr['__iter__'] = lambda self: iter(self.__dict__) attr['__repr__'] = lambda self: "{%s}" % (', '.join([ "%s=%r" % (key, self[key]) for key in sorted(self.__dict__.keys()) ])) return type(typename, (object,), attr)
a factory function to create type dynamically The factory function is used by :func:`objson.load` and :func:`objson.loads`. Creating the object deserialize from json string. The inspiration come from :func:`collections.namedtuple`. the difference is that I don't your the class template to define a dynamic class, instead of, I use the :func:`type` factory function. Class prototype definition :: class JsonObject(object): __identifier__ = "dolphin" def __init__(self, kv=None): if kv is None: kv = dict() self.__dict__.update(kv) def __getitem__(self, key): return self.__dict__.get(key) def __setitem__(self, key, value): self.__dict__[key] = value def __iter__(self): return iter(self.__dict__) def __repr__(self): keys = sorted(self.__dict__.keys()) text = ', '.join(["%s=%r" % (key, self[key]) for key in keys]) return '{%s}' % text name=_property('name') Basic Usage :: from objson import make_dynamic_class, dumps Entity = make_dynamic_class('Entity', 'name, sex, age') entity = Entity() entity.name, entity.sex, entity.age = 'benjamin', 'male', 21 dumps(entity) :param typename: dynamic class's name :param field_names: a string :class:`list` and a field name string which separated by comma, ``['name', 'sex']`` or ``"name,sex"`` :return: a class type
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/objson/dynamic_class.py#L46-L113
null
import re from keyword import iskeyword as _iskeyword __author__ = 'benjamin.c.yan@newegg.com' _re_encode = re.compile('[^a-zA-z0-9_]', re.MULTILINE) def _item_setter(key): def _setter(item, value): item[key] = value return _setter def _item_getter(key): def _getter(item): return item[key] return _getter def _dynamic__init(self, kv=None): # self._data = dict() if kv is None: kv = dict() self.__dict__.update(kv) def _dynamic__setitem(self, key, value): self.__dict__[key] = value def _property(name): return property(_item_getter(name), _item_setter(name)) def _encode_property_name(name): if _iskeyword(name) or name[0].isdigit(): return 'm' + name elif not all(c.isalnum() or c == '_' for c in name): return _re_encode.sub('_', name) return name
by46/simplekit
simplekit/docker/docker.py
Docker.pull_image
python
def pull_image(self, name, tag='latest'): """pull the image from repository :param name: `class`:`str`, without docker.neg prefix, invalid like: 'centos' :param tag: `class`:`str`, special the image's version :return: (`class`:`int`, `class`:`object`) """ name = "{0}/{1}:{2}".format(DOCKER_NEG, name, tag) return "/dockerapi/v2/images", dict(image=name)
pull the image from repository :param name: `class`:`str`, without docker.neg prefix, invalid like: 'centos' :param tag: `class`:`str`, special the image's version :return: (`class`:`int`, `class`:`object`)
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L66-L74
null
class Docker(object): """Docker client """ LoggerName = 'Docker' def __init__(self, server, port=8500): self.logger = logging.getLogger('negowl') self._session = requests.session() self._host = server self._port = port self._server = 'http://{host}:{port}'.format(host=server, port=port) self._headers = {} # -------------------------------------------------- # properties methods # -------------------------------------------------- @property def server(self): return self._server @property def session(self): return self._session @property def headers(self): return self._headers # -------------------------------------------------- # public methods # -------------------------------------------------- @request(method='get') def version(self): return '/dockerapi/v2/ping', None @request(method='get') def get_containers(self, list_all=False): return ("/dockerapi/v2/containers", dict(all=list_all)), None @request(method='get') def get_container(self, name): return "/dockerapi/v2/containers/" + name, None @request(method='post') def pull_image(self, name, tag='latest'): """pull the image from repository :param name: `class`:`str`, without docker.neg prefix, invalid like: 'centos' :param tag: `class`:`str`, special the image's version :return: (`class`:`int`, `class`:`object`) """ name = "{0}/{1}:{2}".format(DOCKER_NEG, name, tag) return "/dockerapi/v2/images", dict(image=name) @request(method='post') def create_container(self, name, image, hostname='dfis', networkmode='bridge', ports=None, volumes=None, env=None, restartpolicy='no', restartretrycount='2', command=""): """testing :param name: :param image: :param hostname: :param networkmode: `class`:`str`, host | bridge :param ports: `class`:`list`, [{'type':'tcp', 'publicport':8080, 'privateport':80, 'ip':'0.0.0.0}] :param volumes: `class`:`list`, [{"containervolume":"/app-conf", "hostvolume":"/opt/app/app-conf"}] :param env: `class`:`list`, ["var=value", "var1=value1"] :param restartpolicy: `class`:`str`, always | on-failure | no(default) :param restartretrycount: 仅当 restartpolicy 是 on-failure 时才有用 :param command: :return: """ restartpolicy = restartpolicy.lower() repository, image_name, version = utils.parse_image_name(image) image = '{0}/{1}:{2}'.format(DOCKER_NEG, image_name, version) body = dict(name=name, image=image, hostname=hostname, networkmode=networkmode, ports=ports or [], volumes=volumes or [], env=env or [], restartpolicy=restartpolicy, command=command) if restartpolicy == 'on-failure': body['restartretrycount'] = restartretrycount return "/dockerapi/v2/containers", body @request(method='put') def change_container(self, name, action='stop'): """ action: "[start|stop|restart|kill|pause|unpause]", :param name: container name :param action: status which need to switch :return: """ return "/dockerapi/v2/containers", dict(container=name, action=action) @request(method='delete') def delete_container(self, name): return "/dockerapi/v2/containers/{name}".format(name=name), None @request(method='PUT') def update(self, container, tag='latest'): return '/dockerapi/v2/containers', dict(action='upgrade', container=container, imagetag=tag) def get_containers_by_name(self, name): """ get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list """ code, containers = self.get_containers() if code != httplib.OK: return [] return [container for container in containers if any(map(lambda x: x.startswith(name), container.Names))] def get_containers_count(self, name): return len(self.get_containers_by_name(name)) def delete_container_2(self, name): """ :param name: `class`:`str`, container name :return: `class`:`bool`, return True if delete success, otherwise return False """ code, container = self.get_container(name) if code == httplib.NOT_FOUND: return True elif code != httplib.OK: self.logger.error("Container %s on %s not exists. %d", name, self._host, code) return False if container.status.Running: code, message = self.change_container(name) if code != httplib.OK: self.logger.error("Stop container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False code, message = self.delete_container(name) if code != httplib.OK: self.logger.error("Delete container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False return True def search(self, name, search_all=False): name = name.lower() code, containers = self.get_containers(list_all=search_all) if code == httplib.OK: containers = filter(lambda container: name in container.Names[0].lower(), containers) return code, containers def update_image(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code != httplib.OK: self.logger.error("Container %s is not exists. error code %s, error message %s", container_name, code, container) return False _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: self.logger.error("You image %s must have a 'docker.neg/' prefix string", image_name) return False if not repo.image_exists(name, tag=version): self.logger.error("You image %s must be location in docker.neg repository.", image_name) return False if old_image_name.lower() != name.lower(): self.logger.error("You image %s must be same with container's Image.", image_name, container.image) return False code, result = self.update(container_name, tag=version) if code != httplib.OK: self.logger.error("Update container %s with image failure, code %s, result %s", container_name, code, result) return False return True def update_image_2(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code == httplib.NOT_FOUND: raise ContainerNotFound(container_name) elif code != httplib.OK: raise GeneralError(code) _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: image_name = '{0}/{1}:{2}'.format(DOCKER_NEG, name, version) if not repo.image_exists(name, tag=version): raise ImageNotFound("{0} do not location in docker.neg repository.".format(image_name)) if old_image_name.lower() != name.lower(): raise ImageConflict("{0} is not be same with container's Image.".format(image_name)) code, result = self.pull_image(name, version) if code != httplib.OK: raise GeneralError( 'pull image {0}:{1} failure, status code {2}, result: {3}'.format(name, version, code, result)) code, result = self.update(container_name, tag=version) if code != httplib.OK: raise GeneralError( 'Update container {0} failure, status code {1}, result: {2}'.format(container_name, code, result)) return True
by46/simplekit
simplekit/docker/docker.py
Docker.create_container
python
def create_container(self, name, image, hostname='dfis', networkmode='bridge', ports=None, volumes=None, env=None, restartpolicy='no', restartretrycount='2', command=""): """testing :param name: :param image: :param hostname: :param networkmode: `class`:`str`, host | bridge :param ports: `class`:`list`, [{'type':'tcp', 'publicport':8080, 'privateport':80, 'ip':'0.0.0.0}] :param volumes: `class`:`list`, [{"containervolume":"/app-conf", "hostvolume":"/opt/app/app-conf"}] :param env: `class`:`list`, ["var=value", "var1=value1"] :param restartpolicy: `class`:`str`, always | on-failure | no(default) :param restartretrycount: 仅当 restartpolicy 是 on-failure 时才有用 :param command: :return: """ restartpolicy = restartpolicy.lower() repository, image_name, version = utils.parse_image_name(image) image = '{0}/{1}:{2}'.format(DOCKER_NEG, image_name, version) body = dict(name=name, image=image, hostname=hostname, networkmode=networkmode, ports=ports or [], volumes=volumes or [], env=env or [], restartpolicy=restartpolicy, command=command) if restartpolicy == 'on-failure': body['restartretrycount'] = restartretrycount return "/dockerapi/v2/containers", body
testing :param name: :param image: :param hostname: :param networkmode: `class`:`str`, host | bridge :param ports: `class`:`list`, [{'type':'tcp', 'publicport':8080, 'privateport':80, 'ip':'0.0.0.0}] :param volumes: `class`:`list`, [{"containervolume":"/app-conf", "hostvolume":"/opt/app/app-conf"}] :param env: `class`:`list`, ["var=value", "var1=value1"] :param restartpolicy: `class`:`str`, always | on-failure | no(default) :param restartretrycount: 仅当 restartpolicy 是 on-failure 时才有用 :param command: :return:
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L77-L105
[ "def parse_image_name(name):\n \"\"\"\n parse the image name into three element tuple, like below:\n (repository, name, version)\n :param name: `class`:`str`, name\n :return: (repository, name, version)\n \"\"\"\n name = name or \"\"\n if '/' in name:\n repository, other = name.split('/')\n else:\n repository, other = None, name\n\n if ':' in other:\n name, version = other.split(':')\n else:\n name, version = other, 'latest'\n\n return repository, name, version\n" ]
class Docker(object): """Docker client """ LoggerName = 'Docker' def __init__(self, server, port=8500): self.logger = logging.getLogger('negowl') self._session = requests.session() self._host = server self._port = port self._server = 'http://{host}:{port}'.format(host=server, port=port) self._headers = {} # -------------------------------------------------- # properties methods # -------------------------------------------------- @property def server(self): return self._server @property def session(self): return self._session @property def headers(self): return self._headers # -------------------------------------------------- # public methods # -------------------------------------------------- @request(method='get') def version(self): return '/dockerapi/v2/ping', None @request(method='get') def get_containers(self, list_all=False): return ("/dockerapi/v2/containers", dict(all=list_all)), None @request(method='get') def get_container(self, name): return "/dockerapi/v2/containers/" + name, None @request(method='post') def pull_image(self, name, tag='latest'): """pull the image from repository :param name: `class`:`str`, without docker.neg prefix, invalid like: 'centos' :param tag: `class`:`str`, special the image's version :return: (`class`:`int`, `class`:`object`) """ name = "{0}/{1}:{2}".format(DOCKER_NEG, name, tag) return "/dockerapi/v2/images", dict(image=name) @request(method='post') def create_container(self, name, image, hostname='dfis', networkmode='bridge', ports=None, volumes=None, env=None, restartpolicy='no', restartretrycount='2', command=""): """testing :param name: :param image: :param hostname: :param networkmode: `class`:`str`, host | bridge :param ports: `class`:`list`, [{'type':'tcp', 'publicport':8080, 'privateport':80, 'ip':'0.0.0.0}] :param volumes: `class`:`list`, [{"containervolume":"/app-conf", "hostvolume":"/opt/app/app-conf"}] :param env: `class`:`list`, ["var=value", "var1=value1"] :param restartpolicy: `class`:`str`, always | on-failure | no(default) :param restartretrycount: 仅当 restartpolicy 是 on-failure 时才有用 :param command: :return: """ restartpolicy = restartpolicy.lower() repository, image_name, version = utils.parse_image_name(image) image = '{0}/{1}:{2}'.format(DOCKER_NEG, image_name, version) body = dict(name=name, image=image, hostname=hostname, networkmode=networkmode, ports=ports or [], volumes=volumes or [], env=env or [], restartpolicy=restartpolicy, command=command) if restartpolicy == 'on-failure': body['restartretrycount'] = restartretrycount return "/dockerapi/v2/containers", body @request(method='put') def change_container(self, name, action='stop'): """ action: "[start|stop|restart|kill|pause|unpause]", :param name: container name :param action: status which need to switch :return: """ return "/dockerapi/v2/containers", dict(container=name, action=action) @request(method='delete') def delete_container(self, name): return "/dockerapi/v2/containers/{name}".format(name=name), None @request(method='PUT') def update(self, container, tag='latest'): return '/dockerapi/v2/containers', dict(action='upgrade', container=container, imagetag=tag) def get_containers_by_name(self, name): """ get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list """ code, containers = self.get_containers() if code != httplib.OK: return [] return [container for container in containers if any(map(lambda x: x.startswith(name), container.Names))] def get_containers_count(self, name): return len(self.get_containers_by_name(name)) def delete_container_2(self, name): """ :param name: `class`:`str`, container name :return: `class`:`bool`, return True if delete success, otherwise return False """ code, container = self.get_container(name) if code == httplib.NOT_FOUND: return True elif code != httplib.OK: self.logger.error("Container %s on %s not exists. %d", name, self._host, code) return False if container.status.Running: code, message = self.change_container(name) if code != httplib.OK: self.logger.error("Stop container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False code, message = self.delete_container(name) if code != httplib.OK: self.logger.error("Delete container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False return True def search(self, name, search_all=False): name = name.lower() code, containers = self.get_containers(list_all=search_all) if code == httplib.OK: containers = filter(lambda container: name in container.Names[0].lower(), containers) return code, containers def update_image(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code != httplib.OK: self.logger.error("Container %s is not exists. error code %s, error message %s", container_name, code, container) return False _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: self.logger.error("You image %s must have a 'docker.neg/' prefix string", image_name) return False if not repo.image_exists(name, tag=version): self.logger.error("You image %s must be location in docker.neg repository.", image_name) return False if old_image_name.lower() != name.lower(): self.logger.error("You image %s must be same with container's Image.", image_name, container.image) return False code, result = self.update(container_name, tag=version) if code != httplib.OK: self.logger.error("Update container %s with image failure, code %s, result %s", container_name, code, result) return False return True def update_image_2(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code == httplib.NOT_FOUND: raise ContainerNotFound(container_name) elif code != httplib.OK: raise GeneralError(code) _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: image_name = '{0}/{1}:{2}'.format(DOCKER_NEG, name, version) if not repo.image_exists(name, tag=version): raise ImageNotFound("{0} do not location in docker.neg repository.".format(image_name)) if old_image_name.lower() != name.lower(): raise ImageConflict("{0} is not be same with container's Image.".format(image_name)) code, result = self.pull_image(name, version) if code != httplib.OK: raise GeneralError( 'pull image {0}:{1} failure, status code {2}, result: {3}'.format(name, version, code, result)) code, result = self.update(container_name, tag=version) if code != httplib.OK: raise GeneralError( 'Update container {0} failure, status code {1}, result: {2}'.format(container_name, code, result)) return True
by46/simplekit
simplekit/docker/docker.py
Docker.get_containers_by_name
python
def get_containers_by_name(self, name): """ get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list """ code, containers = self.get_containers() if code != httplib.OK: return [] return [container for container in containers if any(map(lambda x: x.startswith(name), container.Names))]
get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L126-L138
null
class Docker(object): """Docker client """ LoggerName = 'Docker' def __init__(self, server, port=8500): self.logger = logging.getLogger('negowl') self._session = requests.session() self._host = server self._port = port self._server = 'http://{host}:{port}'.format(host=server, port=port) self._headers = {} # -------------------------------------------------- # properties methods # -------------------------------------------------- @property def server(self): return self._server @property def session(self): return self._session @property def headers(self): return self._headers # -------------------------------------------------- # public methods # -------------------------------------------------- @request(method='get') def version(self): return '/dockerapi/v2/ping', None @request(method='get') def get_containers(self, list_all=False): return ("/dockerapi/v2/containers", dict(all=list_all)), None @request(method='get') def get_container(self, name): return "/dockerapi/v2/containers/" + name, None @request(method='post') def pull_image(self, name, tag='latest'): """pull the image from repository :param name: `class`:`str`, without docker.neg prefix, invalid like: 'centos' :param tag: `class`:`str`, special the image's version :return: (`class`:`int`, `class`:`object`) """ name = "{0}/{1}:{2}".format(DOCKER_NEG, name, tag) return "/dockerapi/v2/images", dict(image=name) @request(method='post') def create_container(self, name, image, hostname='dfis', networkmode='bridge', ports=None, volumes=None, env=None, restartpolicy='no', restartretrycount='2', command=""): """testing :param name: :param image: :param hostname: :param networkmode: `class`:`str`, host | bridge :param ports: `class`:`list`, [{'type':'tcp', 'publicport':8080, 'privateport':80, 'ip':'0.0.0.0}] :param volumes: `class`:`list`, [{"containervolume":"/app-conf", "hostvolume":"/opt/app/app-conf"}] :param env: `class`:`list`, ["var=value", "var1=value1"] :param restartpolicy: `class`:`str`, always | on-failure | no(default) :param restartretrycount: 仅当 restartpolicy 是 on-failure 时才有用 :param command: :return: """ restartpolicy = restartpolicy.lower() repository, image_name, version = utils.parse_image_name(image) image = '{0}/{1}:{2}'.format(DOCKER_NEG, image_name, version) body = dict(name=name, image=image, hostname=hostname, networkmode=networkmode, ports=ports or [], volumes=volumes or [], env=env or [], restartpolicy=restartpolicy, command=command) if restartpolicy == 'on-failure': body['restartretrycount'] = restartretrycount return "/dockerapi/v2/containers", body @request(method='put') def change_container(self, name, action='stop'): """ action: "[start|stop|restart|kill|pause|unpause]", :param name: container name :param action: status which need to switch :return: """ return "/dockerapi/v2/containers", dict(container=name, action=action) @request(method='delete') def delete_container(self, name): return "/dockerapi/v2/containers/{name}".format(name=name), None @request(method='PUT') def update(self, container, tag='latest'): return '/dockerapi/v2/containers', dict(action='upgrade', container=container, imagetag=tag) def get_containers_by_name(self, name): """ get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list """ code, containers = self.get_containers() if code != httplib.OK: return [] return [container for container in containers if any(map(lambda x: x.startswith(name), container.Names))] def get_containers_count(self, name): return len(self.get_containers_by_name(name)) def delete_container_2(self, name): """ :param name: `class`:`str`, container name :return: `class`:`bool`, return True if delete success, otherwise return False """ code, container = self.get_container(name) if code == httplib.NOT_FOUND: return True elif code != httplib.OK: self.logger.error("Container %s on %s not exists. %d", name, self._host, code) return False if container.status.Running: code, message = self.change_container(name) if code != httplib.OK: self.logger.error("Stop container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False code, message = self.delete_container(name) if code != httplib.OK: self.logger.error("Delete container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False return True def search(self, name, search_all=False): name = name.lower() code, containers = self.get_containers(list_all=search_all) if code == httplib.OK: containers = filter(lambda container: name in container.Names[0].lower(), containers) return code, containers def update_image(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code != httplib.OK: self.logger.error("Container %s is not exists. error code %s, error message %s", container_name, code, container) return False _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: self.logger.error("You image %s must have a 'docker.neg/' prefix string", image_name) return False if not repo.image_exists(name, tag=version): self.logger.error("You image %s must be location in docker.neg repository.", image_name) return False if old_image_name.lower() != name.lower(): self.logger.error("You image %s must be same with container's Image.", image_name, container.image) return False code, result = self.update(container_name, tag=version) if code != httplib.OK: self.logger.error("Update container %s with image failure, code %s, result %s", container_name, code, result) return False return True def update_image_2(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code == httplib.NOT_FOUND: raise ContainerNotFound(container_name) elif code != httplib.OK: raise GeneralError(code) _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: image_name = '{0}/{1}:{2}'.format(DOCKER_NEG, name, version) if not repo.image_exists(name, tag=version): raise ImageNotFound("{0} do not location in docker.neg repository.".format(image_name)) if old_image_name.lower() != name.lower(): raise ImageConflict("{0} is not be same with container's Image.".format(image_name)) code, result = self.pull_image(name, version) if code != httplib.OK: raise GeneralError( 'pull image {0}:{1} failure, status code {2}, result: {3}'.format(name, version, code, result)) code, result = self.update(container_name, tag=version) if code != httplib.OK: raise GeneralError( 'Update container {0} failure, status code {1}, result: {2}'.format(container_name, code, result)) return True
by46/simplekit
simplekit/docker/docker.py
Docker.delete_container_2
python
def delete_container_2(self, name): """ :param name: `class`:`str`, container name :return: `class`:`bool`, return True if delete success, otherwise return False """ code, container = self.get_container(name) if code == httplib.NOT_FOUND: return True elif code != httplib.OK: self.logger.error("Container %s on %s not exists. %d", name, self._host, code) return False if container.status.Running: code, message = self.change_container(name) if code != httplib.OK: self.logger.error("Stop container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False code, message = self.delete_container(name) if code != httplib.OK: self.logger.error("Delete container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False return True
:param name: `class`:`str`, container name :return: `class`:`bool`, return True if delete success, otherwise return False
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L143-L168
[ "def dumps(obj, *args, **kwargs):\n \"\"\"Serialize a object to string\n\n Basic Usage:\n\n >>> import simplekit.objson\n >>> obj = {'name':'wendy'}\n >>> print simplekit.objson.dumps(obj)\n\n\n :param obj: a object which need to dump\n :param args: Optional arguments that :func:`json.dumps` takes.\n :param kwargs: Keys arguments that :py:func:`json.dumps` takes.\n :return: string\n \"\"\"\n kwargs['default'] = object2dict\n\n return json.dumps(obj, *args, **kwargs)\n" ]
class Docker(object): """Docker client """ LoggerName = 'Docker' def __init__(self, server, port=8500): self.logger = logging.getLogger('negowl') self._session = requests.session() self._host = server self._port = port self._server = 'http://{host}:{port}'.format(host=server, port=port) self._headers = {} # -------------------------------------------------- # properties methods # -------------------------------------------------- @property def server(self): return self._server @property def session(self): return self._session @property def headers(self): return self._headers # -------------------------------------------------- # public methods # -------------------------------------------------- @request(method='get') def version(self): return '/dockerapi/v2/ping', None @request(method='get') def get_containers(self, list_all=False): return ("/dockerapi/v2/containers", dict(all=list_all)), None @request(method='get') def get_container(self, name): return "/dockerapi/v2/containers/" + name, None @request(method='post') def pull_image(self, name, tag='latest'): """pull the image from repository :param name: `class`:`str`, without docker.neg prefix, invalid like: 'centos' :param tag: `class`:`str`, special the image's version :return: (`class`:`int`, `class`:`object`) """ name = "{0}/{1}:{2}".format(DOCKER_NEG, name, tag) return "/dockerapi/v2/images", dict(image=name) @request(method='post') def create_container(self, name, image, hostname='dfis', networkmode='bridge', ports=None, volumes=None, env=None, restartpolicy='no', restartretrycount='2', command=""): """testing :param name: :param image: :param hostname: :param networkmode: `class`:`str`, host | bridge :param ports: `class`:`list`, [{'type':'tcp', 'publicport':8080, 'privateport':80, 'ip':'0.0.0.0}] :param volumes: `class`:`list`, [{"containervolume":"/app-conf", "hostvolume":"/opt/app/app-conf"}] :param env: `class`:`list`, ["var=value", "var1=value1"] :param restartpolicy: `class`:`str`, always | on-failure | no(default) :param restartretrycount: 仅当 restartpolicy 是 on-failure 时才有用 :param command: :return: """ restartpolicy = restartpolicy.lower() repository, image_name, version = utils.parse_image_name(image) image = '{0}/{1}:{2}'.format(DOCKER_NEG, image_name, version) body = dict(name=name, image=image, hostname=hostname, networkmode=networkmode, ports=ports or [], volumes=volumes or [], env=env or [], restartpolicy=restartpolicy, command=command) if restartpolicy == 'on-failure': body['restartretrycount'] = restartretrycount return "/dockerapi/v2/containers", body @request(method='put') def change_container(self, name, action='stop'): """ action: "[start|stop|restart|kill|pause|unpause]", :param name: container name :param action: status which need to switch :return: """ return "/dockerapi/v2/containers", dict(container=name, action=action) @request(method='delete') def delete_container(self, name): return "/dockerapi/v2/containers/{name}".format(name=name), None @request(method='PUT') def update(self, container, tag='latest'): return '/dockerapi/v2/containers', dict(action='upgrade', container=container, imagetag=tag) def get_containers_by_name(self, name): """ get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list """ code, containers = self.get_containers() if code != httplib.OK: return [] return [container for container in containers if any(map(lambda x: x.startswith(name), container.Names))] def get_containers_count(self, name): return len(self.get_containers_by_name(name)) def delete_container_2(self, name): """ :param name: `class`:`str`, container name :return: `class`:`bool`, return True if delete success, otherwise return False """ code, container = self.get_container(name) if code == httplib.NOT_FOUND: return True elif code != httplib.OK: self.logger.error("Container %s on %s not exists. %d", name, self._host, code) return False if container.status.Running: code, message = self.change_container(name) if code != httplib.OK: self.logger.error("Stop container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False code, message = self.delete_container(name) if code != httplib.OK: self.logger.error("Delete container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False return True def search(self, name, search_all=False): name = name.lower() code, containers = self.get_containers(list_all=search_all) if code == httplib.OK: containers = filter(lambda container: name in container.Names[0].lower(), containers) return code, containers def update_image(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code != httplib.OK: self.logger.error("Container %s is not exists. error code %s, error message %s", container_name, code, container) return False _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: self.logger.error("You image %s must have a 'docker.neg/' prefix string", image_name) return False if not repo.image_exists(name, tag=version): self.logger.error("You image %s must be location in docker.neg repository.", image_name) return False if old_image_name.lower() != name.lower(): self.logger.error("You image %s must be same with container's Image.", image_name, container.image) return False code, result = self.update(container_name, tag=version) if code != httplib.OK: self.logger.error("Update container %s with image failure, code %s, result %s", container_name, code, result) return False return True def update_image_2(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code == httplib.NOT_FOUND: raise ContainerNotFound(container_name) elif code != httplib.OK: raise GeneralError(code) _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: image_name = '{0}/{1}:{2}'.format(DOCKER_NEG, name, version) if not repo.image_exists(name, tag=version): raise ImageNotFound("{0} do not location in docker.neg repository.".format(image_name)) if old_image_name.lower() != name.lower(): raise ImageConflict("{0} is not be same with container's Image.".format(image_name)) code, result = self.pull_image(name, version) if code != httplib.OK: raise GeneralError( 'pull image {0}:{1} failure, status code {2}, result: {3}'.format(name, version, code, result)) code, result = self.update(container_name, tag=version) if code != httplib.OK: raise GeneralError( 'Update container {0} failure, status code {1}, result: {2}'.format(container_name, code, result)) return True
by46/simplekit
simplekit/docker/docker.py
Docker.update_image
python
def update_image(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code != httplib.OK: self.logger.error("Container %s is not exists. error code %s, error message %s", container_name, code, container) return False _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: self.logger.error("You image %s must have a 'docker.neg/' prefix string", image_name) return False if not repo.image_exists(name, tag=version): self.logger.error("You image %s must be location in docker.neg repository.", image_name) return False if old_image_name.lower() != name.lower(): self.logger.error("You image %s must be same with container's Image.", image_name, container.image) return False code, result = self.update(container_name, tag=version) if code != httplib.OK: self.logger.error("Update container %s with image failure, code %s, result %s", container_name, code, result) return False return True
update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False.
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L178-L211
[ "def parse_image_name(name):\n \"\"\"\n parse the image name into three element tuple, like below:\n (repository, name, version)\n :param name: `class`:`str`, name\n :return: (repository, name, version)\n \"\"\"\n name = name or \"\"\n if '/' in name:\n repository, other = name.split('/')\n else:\n repository, other = None, name\n\n if ':' in other:\n name, version = other.split(':')\n else:\n name, version = other, 'latest'\n\n return repository, name, version\n" ]
class Docker(object): """Docker client """ LoggerName = 'Docker' def __init__(self, server, port=8500): self.logger = logging.getLogger('negowl') self._session = requests.session() self._host = server self._port = port self._server = 'http://{host}:{port}'.format(host=server, port=port) self._headers = {} # -------------------------------------------------- # properties methods # -------------------------------------------------- @property def server(self): return self._server @property def session(self): return self._session @property def headers(self): return self._headers # -------------------------------------------------- # public methods # -------------------------------------------------- @request(method='get') def version(self): return '/dockerapi/v2/ping', None @request(method='get') def get_containers(self, list_all=False): return ("/dockerapi/v2/containers", dict(all=list_all)), None @request(method='get') def get_container(self, name): return "/dockerapi/v2/containers/" + name, None @request(method='post') def pull_image(self, name, tag='latest'): """pull the image from repository :param name: `class`:`str`, without docker.neg prefix, invalid like: 'centos' :param tag: `class`:`str`, special the image's version :return: (`class`:`int`, `class`:`object`) """ name = "{0}/{1}:{2}".format(DOCKER_NEG, name, tag) return "/dockerapi/v2/images", dict(image=name) @request(method='post') def create_container(self, name, image, hostname='dfis', networkmode='bridge', ports=None, volumes=None, env=None, restartpolicy='no', restartretrycount='2', command=""): """testing :param name: :param image: :param hostname: :param networkmode: `class`:`str`, host | bridge :param ports: `class`:`list`, [{'type':'tcp', 'publicport':8080, 'privateport':80, 'ip':'0.0.0.0}] :param volumes: `class`:`list`, [{"containervolume":"/app-conf", "hostvolume":"/opt/app/app-conf"}] :param env: `class`:`list`, ["var=value", "var1=value1"] :param restartpolicy: `class`:`str`, always | on-failure | no(default) :param restartretrycount: 仅当 restartpolicy 是 on-failure 时才有用 :param command: :return: """ restartpolicy = restartpolicy.lower() repository, image_name, version = utils.parse_image_name(image) image = '{0}/{1}:{2}'.format(DOCKER_NEG, image_name, version) body = dict(name=name, image=image, hostname=hostname, networkmode=networkmode, ports=ports or [], volumes=volumes or [], env=env or [], restartpolicy=restartpolicy, command=command) if restartpolicy == 'on-failure': body['restartretrycount'] = restartretrycount return "/dockerapi/v2/containers", body @request(method='put') def change_container(self, name, action='stop'): """ action: "[start|stop|restart|kill|pause|unpause]", :param name: container name :param action: status which need to switch :return: """ return "/dockerapi/v2/containers", dict(container=name, action=action) @request(method='delete') def delete_container(self, name): return "/dockerapi/v2/containers/{name}".format(name=name), None @request(method='PUT') def update(self, container, tag='latest'): return '/dockerapi/v2/containers', dict(action='upgrade', container=container, imagetag=tag) def get_containers_by_name(self, name): """ get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list """ code, containers = self.get_containers() if code != httplib.OK: return [] return [container for container in containers if any(map(lambda x: x.startswith(name), container.Names))] def get_containers_count(self, name): return len(self.get_containers_by_name(name)) def delete_container_2(self, name): """ :param name: `class`:`str`, container name :return: `class`:`bool`, return True if delete success, otherwise return False """ code, container = self.get_container(name) if code == httplib.NOT_FOUND: return True elif code != httplib.OK: self.logger.error("Container %s on %s not exists. %d", name, self._host, code) return False if container.status.Running: code, message = self.change_container(name) if code != httplib.OK: self.logger.error("Stop container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False code, message = self.delete_container(name) if code != httplib.OK: self.logger.error("Delete container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False return True def search(self, name, search_all=False): name = name.lower() code, containers = self.get_containers(list_all=search_all) if code == httplib.OK: containers = filter(lambda container: name in container.Names[0].lower(), containers) return code, containers def update_image(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code != httplib.OK: self.logger.error("Container %s is not exists. error code %s, error message %s", container_name, code, container) return False _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: self.logger.error("You image %s must have a 'docker.neg/' prefix string", image_name) return False if not repo.image_exists(name, tag=version): self.logger.error("You image %s must be location in docker.neg repository.", image_name) return False if old_image_name.lower() != name.lower(): self.logger.error("You image %s must be same with container's Image.", image_name, container.image) return False code, result = self.update(container_name, tag=version) if code != httplib.OK: self.logger.error("Update container %s with image failure, code %s, result %s", container_name, code, result) return False return True def update_image_2(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code == httplib.NOT_FOUND: raise ContainerNotFound(container_name) elif code != httplib.OK: raise GeneralError(code) _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: image_name = '{0}/{1}:{2}'.format(DOCKER_NEG, name, version) if not repo.image_exists(name, tag=version): raise ImageNotFound("{0} do not location in docker.neg repository.".format(image_name)) if old_image_name.lower() != name.lower(): raise ImageConflict("{0} is not be same with container's Image.".format(image_name)) code, result = self.pull_image(name, version) if code != httplib.OK: raise GeneralError( 'pull image {0}:{1} failure, status code {2}, result: {3}'.format(name, version, code, result)) code, result = self.update(container_name, tag=version) if code != httplib.OK: raise GeneralError( 'Update container {0} failure, status code {1}, result: {2}'.format(container_name, code, result)) return True
by46/simplekit
simplekit/docker/docker.py
Docker.update_image_2
python
def update_image_2(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code == httplib.NOT_FOUND: raise ContainerNotFound(container_name) elif code != httplib.OK: raise GeneralError(code) _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: image_name = '{0}/{1}:{2}'.format(DOCKER_NEG, name, version) if not repo.image_exists(name, tag=version): raise ImageNotFound("{0} do not location in docker.neg repository.".format(image_name)) if old_image_name.lower() != name.lower(): raise ImageConflict("{0} is not be same with container's Image.".format(image_name)) code, result = self.pull_image(name, version) if code != httplib.OK: raise GeneralError( 'pull image {0}:{1} failure, status code {2}, result: {3}'.format(name, version, code, result)) code, result = self.update(container_name, tag=version) if code != httplib.OK: raise GeneralError( 'Update container {0} failure, status code {1}, result: {2}'.format(container_name, code, result)) return True
update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False.
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/docker.py#L213-L247
[ "def parse_image_name(name):\n \"\"\"\n parse the image name into three element tuple, like below:\n (repository, name, version)\n :param name: `class`:`str`, name\n :return: (repository, name, version)\n \"\"\"\n name = name or \"\"\n if '/' in name:\n repository, other = name.split('/')\n else:\n repository, other = None, name\n\n if ':' in other:\n name, version = other.split(':')\n else:\n name, version = other, 'latest'\n\n return repository, name, version\n", "def image_exists(self, image_name, tag='latest'):\n \"\"\"\n\n :param image_name:\n :return: True the image_name location in docker.neg pos\n \"\"\"\n code, image = self.image_tags(image_name)\n if code != httplib.OK:\n return False\n tag = tag.lower()\n return any(x.lower() == tag for x in image.tags)\n" ]
class Docker(object): """Docker client """ LoggerName = 'Docker' def __init__(self, server, port=8500): self.logger = logging.getLogger('negowl') self._session = requests.session() self._host = server self._port = port self._server = 'http://{host}:{port}'.format(host=server, port=port) self._headers = {} # -------------------------------------------------- # properties methods # -------------------------------------------------- @property def server(self): return self._server @property def session(self): return self._session @property def headers(self): return self._headers # -------------------------------------------------- # public methods # -------------------------------------------------- @request(method='get') def version(self): return '/dockerapi/v2/ping', None @request(method='get') def get_containers(self, list_all=False): return ("/dockerapi/v2/containers", dict(all=list_all)), None @request(method='get') def get_container(self, name): return "/dockerapi/v2/containers/" + name, None @request(method='post') def pull_image(self, name, tag='latest'): """pull the image from repository :param name: `class`:`str`, without docker.neg prefix, invalid like: 'centos' :param tag: `class`:`str`, special the image's version :return: (`class`:`int`, `class`:`object`) """ name = "{0}/{1}:{2}".format(DOCKER_NEG, name, tag) return "/dockerapi/v2/images", dict(image=name) @request(method='post') def create_container(self, name, image, hostname='dfis', networkmode='bridge', ports=None, volumes=None, env=None, restartpolicy='no', restartretrycount='2', command=""): """testing :param name: :param image: :param hostname: :param networkmode: `class`:`str`, host | bridge :param ports: `class`:`list`, [{'type':'tcp', 'publicport':8080, 'privateport':80, 'ip':'0.0.0.0}] :param volumes: `class`:`list`, [{"containervolume":"/app-conf", "hostvolume":"/opt/app/app-conf"}] :param env: `class`:`list`, ["var=value", "var1=value1"] :param restartpolicy: `class`:`str`, always | on-failure | no(default) :param restartretrycount: 仅当 restartpolicy 是 on-failure 时才有用 :param command: :return: """ restartpolicy = restartpolicy.lower() repository, image_name, version = utils.parse_image_name(image) image = '{0}/{1}:{2}'.format(DOCKER_NEG, image_name, version) body = dict(name=name, image=image, hostname=hostname, networkmode=networkmode, ports=ports or [], volumes=volumes or [], env=env or [], restartpolicy=restartpolicy, command=command) if restartpolicy == 'on-failure': body['restartretrycount'] = restartretrycount return "/dockerapi/v2/containers", body @request(method='put') def change_container(self, name, action='stop'): """ action: "[start|stop|restart|kill|pause|unpause]", :param name: container name :param action: status which need to switch :return: """ return "/dockerapi/v2/containers", dict(container=name, action=action) @request(method='delete') def delete_container(self, name): return "/dockerapi/v2/containers/{name}".format(name=name), None @request(method='PUT') def update(self, container, tag='latest'): return '/dockerapi/v2/containers', dict(action='upgrade', container=container, imagetag=tag) def get_containers_by_name(self, name): """ get all task which relative with task name :param name: :class:`str`, task name :return: :class:`list`, container list """ code, containers = self.get_containers() if code != httplib.OK: return [] return [container for container in containers if any(map(lambda x: x.startswith(name), container.Names))] def get_containers_count(self, name): return len(self.get_containers_by_name(name)) def delete_container_2(self, name): """ :param name: `class`:`str`, container name :return: `class`:`bool`, return True if delete success, otherwise return False """ code, container = self.get_container(name) if code == httplib.NOT_FOUND: return True elif code != httplib.OK: self.logger.error("Container %s on %s not exists. %d", name, self._host, code) return False if container.status.Running: code, message = self.change_container(name) if code != httplib.OK: self.logger.error("Stop container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False code, message = self.delete_container(name) if code != httplib.OK: self.logger.error("Delete container %s on %s error, status code %d, message %s", name, self._host, code, objson.dumps(message)) return False return True def search(self, name, search_all=False): name = name.lower() code, containers = self.get_containers(list_all=search_all) if code == httplib.OK: containers = filter(lambda container: name in container.Names[0].lower(), containers) return code, containers def update_image(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code != httplib.OK: self.logger.error("Container %s is not exists. error code %s, error message %s", container_name, code, container) return False _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: self.logger.error("You image %s must have a 'docker.neg/' prefix string", image_name) return False if not repo.image_exists(name, tag=version): self.logger.error("You image %s must be location in docker.neg repository.", image_name) return False if old_image_name.lower() != name.lower(): self.logger.error("You image %s must be same with container's Image.", image_name, container.image) return False code, result = self.update(container_name, tag=version) if code != httplib.OK: self.logger.error("Update container %s with image failure, code %s, result %s", container_name, code, result) return False return True def update_image_2(self, container_name, image_name): """ update a container's image, :param container_name: `class`:`str`, container name :param image_name: `class`:`str`, the full image name, like alpine:3.3 :return: `class`:`bool`, True if success, otherwise False. """ code, container = self.get_container(container_name) if code == httplib.NOT_FOUND: raise ContainerNotFound(container_name) elif code != httplib.OK: raise GeneralError(code) _, old_image_name, _ = utils.parse_image_name(container.image) repository, name, version = utils.parse_image_name(image_name) if not repository or repository.lower() != DOCKER_NEG: image_name = '{0}/{1}:{2}'.format(DOCKER_NEG, name, version) if not repo.image_exists(name, tag=version): raise ImageNotFound("{0} do not location in docker.neg repository.".format(image_name)) if old_image_name.lower() != name.lower(): raise ImageConflict("{0} is not be same with container's Image.".format(image_name)) code, result = self.pull_image(name, version) if code != httplib.OK: raise GeneralError( 'pull image {0}:{1} failure, status code {2}, result: {3}'.format(name, version, code, result)) code, result = self.update(container_name, tag=version) if code != httplib.OK: raise GeneralError( 'Update container {0} failure, status code {1}, result: {2}'.format(container_name, code, result)) return True
by46/simplekit
simplekit/docker/repository.py
Repository.image_exists
python
def image_exists(self, image_name, tag='latest'): """ :param image_name: :return: True the image_name location in docker.neg pos """ code, image = self.image_tags(image_name) if code != httplib.OK: return False tag = tag.lower() return any(x.lower() == tag for x in image.tags)
:param image_name: :return: True the image_name location in docker.neg pos
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/docker/repository.py#L27-L37
null
class Repository(object): """It's used to retrieve docker information from BTS's docker repository """ def __init__(self, base): self.server = base.strip("/") self.session = requests.session() self.headers = {} self.logger = logging.getLogger("negowl") @request(method='GET') def image_tags(self, image_name): return "/{name}/tags/list".format(name=image_name), None @request(method="GET") def images(self): return "/_catalog", None def image_exists(self, image_name, tag='latest'): """ :param image_name: :return: True the image_name location in docker.neg pos """ code, image = self.image_tags(image_name) if code != httplib.OK: return False tag = tag.lower() return any(x.lower() == tag for x in image.tags)
by46/simplekit
simplekit/url/path.py
remove_path_segments
python
def remove_path_segments(segments, removes): if segments == ['']: segments.append('') if removes == ['']: removes.append('') if segments == removes: ret = [] elif len(removes) > len(segments): ret = segments else: # TODO(benjamin): incomplete removes2 = list(removes) if len(removes) > 1 and removes[0] == '': removes2.pop(0) if removes2 and removes2 == segments[-1 * len(removes2):]: ret = segments[:len(segments) - len(removes2)] if removes[0] != '' and ret: ret.append('') else: ret = segments return ret
Removes the removes from the tail of segments. Examples:: >>> # '/a/b/c' - 'b/c' == '/a/' >>> assert remove_path_segments(['', 'a', 'b', 'c'], ['b', 'c']) == ['', 'a', ''] >>> # '/a/b/c' - '/b/c' == '/a >>> assert remove_path_segments(['', 'a', 'b', 'c'], ['', 'b', 'c']) == ['', 'a'] :param segments: :class:`list`, a list of the path segment :param removes: :class:`list`, a list of the path segment :return: :class:`list`, The list of all remaining path segments after all segments in ``removes`` have been removed from the end of ``segments``. If no segment from ``removes`` were removed from the ``segments``, the ``segments`` is return unmodified.
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/url/path.py#L9-L48
null
from posixpath import normpath import six from six.moves.urllib.parse import quote, unquote __author__ = 'benjamin.c.yan' # TODO(benjamin): incomplete def join_path_segments(*args): """Join multiple list of path segments This function is not encoding aware, it does not test for, or changed the encoding of the path segments it's passed. Example:: >>> assert join_path_segments(['a'], ['b']) == ['a','b'] >>> assert join_path_segments(['a',''], ['b']) == ['a','b'] >>> assert join_path_segments(['a'], ['','b']) == ['a','b'] >>> assert join_path_segments(['a',''], ['','b']) == ['a','','b'] >>> assert join_path_segments(['a','b'], ['c','d']) == ['a','b','c','d'] :param args: optional arguments :return: :class:`list`, the segment list of the result path """ finals = [] for segments in args: if not segments or segments[0] == ['']: continue elif not finals: finals.extend(segments) else: # Example #1: ['a',''] + ['b'] == ['a','b'] # Example #2: ['a',''] + ['','b'] == ['a','','b'] if finals[-1] == '' and (segments[0] != '' or len(segments) > 1): finals.pop(-1) # Example: ['a'] + ['','b'] == ['a','b'] elif finals[-1] != '' and segments[0] == '' and len(segments) > 1: segments.pop(0) finals.extend(segments) return finals class Path(object): def __init__(self, path): self.segments = [] self.is_absolute = True self.load(path) @property def is_dir(self): return (self.segments == [] or (self.segments and self.segments[-1] == '')) @property def is_file(self): return not self.is_dir def load(self, path): if not path: segments = [] elif isinstance(path, six.string_types): segments = self._segment_from_path(path) else: # list interface segments = path if len(segments) > 1 and segments[0] == '': segments.pop(0) self.segments = [unquote(segment) for segment in segments] return self def normalize(self): """ Normalize the path. Turn /file/title/../author to /file/author :return: <self> """ if str(self): normalized = normpath(str(self)) + ('/' * self.is_dir) if normalized.startswith('//'): # http://bugs.python.org/636648 normalized = '/' + normalized.lstrip('/') self.load(normalized) return self def set(self, path): self.load(path) return self def remove(self, path=None): if path is None: self.load('') else: segments = path if isinstance(path, six.string_types): segments = self._segment_from_path(path) base = ([''] if self.is_absolute else []) + self.segments self.load(remove_path_segments(base, segments)) return self def add(self, path): new_segments = path if isinstance(path, six.string_types): new_segments = self._segment_from_path(path) if self.segments == [''] and new_segments and new_segments[0] != '': new_segments.insert(0, '') segments = self.segments if self.is_absolute and segments and segments[0] != '': segments.insert(0, '') self.load(join_path_segments(segments, new_segments)) return self def __str__(self): segments = list(self.segments) if self.is_absolute: if not segments: segments = ['', ''] else: segments.insert(0, '') return self._path_from_segments(segments) def __repr__(self): return "%s('%s')" % (self.__class__.__name__, str(self)) def __bool__(self): return len(self.segments) > 0 __nonzero__ = __bool__ def __eq__(self, other): return str(self) == str(other) def __ne__(self, other): return not self == other # TODO(benjamin): incomplete @staticmethod def _segment_from_path(path): return [unquote(segment) for segment in path.split('/')] # TODO(benjamin): incomplete @staticmethod def _path_from_segments(segments): if '%' not in '/'.join(segments): segments = [quote(segment) for segment in segments] return '/'.join(segments)
by46/simplekit
simplekit/url/path.py
join_path_segments
python
def join_path_segments(*args): finals = [] for segments in args: if not segments or segments[0] == ['']: continue elif not finals: finals.extend(segments) else: # Example #1: ['a',''] + ['b'] == ['a','b'] # Example #2: ['a',''] + ['','b'] == ['a','','b'] if finals[-1] == '' and (segments[0] != '' or len(segments) > 1): finals.pop(-1) # Example: ['a'] + ['','b'] == ['a','b'] elif finals[-1] != '' and segments[0] == '' and len(segments) > 1: segments.pop(0) finals.extend(segments) return finals
Join multiple list of path segments This function is not encoding aware, it does not test for, or changed the encoding of the path segments it's passed. Example:: >>> assert join_path_segments(['a'], ['b']) == ['a','b'] >>> assert join_path_segments(['a',''], ['b']) == ['a','b'] >>> assert join_path_segments(['a'], ['','b']) == ['a','b'] >>> assert join_path_segments(['a',''], ['','b']) == ['a','','b'] >>> assert join_path_segments(['a','b'], ['c','d']) == ['a','b','c','d'] :param args: optional arguments :return: :class:`list`, the segment list of the result path
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/url/path.py#L52-L83
null
from posixpath import normpath import six from six.moves.urllib.parse import quote, unquote __author__ = 'benjamin.c.yan' def remove_path_segments(segments, removes): """Removes the removes from the tail of segments. Examples:: >>> # '/a/b/c' - 'b/c' == '/a/' >>> assert remove_path_segments(['', 'a', 'b', 'c'], ['b', 'c']) == ['', 'a', ''] >>> # '/a/b/c' - '/b/c' == '/a >>> assert remove_path_segments(['', 'a', 'b', 'c'], ['', 'b', 'c']) == ['', 'a'] :param segments: :class:`list`, a list of the path segment :param removes: :class:`list`, a list of the path segment :return: :class:`list`, The list of all remaining path segments after all segments in ``removes`` have been removed from the end of ``segments``. If no segment from ``removes`` were removed from the ``segments``, the ``segments`` is return unmodified. """ if segments == ['']: segments.append('') if removes == ['']: removes.append('') if segments == removes: ret = [] elif len(removes) > len(segments): ret = segments else: # TODO(benjamin): incomplete removes2 = list(removes) if len(removes) > 1 and removes[0] == '': removes2.pop(0) if removes2 and removes2 == segments[-1 * len(removes2):]: ret = segments[:len(segments) - len(removes2)] if removes[0] != '' and ret: ret.append('') else: ret = segments return ret # TODO(benjamin): incomplete class Path(object): def __init__(self, path): self.segments = [] self.is_absolute = True self.load(path) @property def is_dir(self): return (self.segments == [] or (self.segments and self.segments[-1] == '')) @property def is_file(self): return not self.is_dir def load(self, path): if not path: segments = [] elif isinstance(path, six.string_types): segments = self._segment_from_path(path) else: # list interface segments = path if len(segments) > 1 and segments[0] == '': segments.pop(0) self.segments = [unquote(segment) for segment in segments] return self def normalize(self): """ Normalize the path. Turn /file/title/../author to /file/author :return: <self> """ if str(self): normalized = normpath(str(self)) + ('/' * self.is_dir) if normalized.startswith('//'): # http://bugs.python.org/636648 normalized = '/' + normalized.lstrip('/') self.load(normalized) return self def set(self, path): self.load(path) return self def remove(self, path=None): if path is None: self.load('') else: segments = path if isinstance(path, six.string_types): segments = self._segment_from_path(path) base = ([''] if self.is_absolute else []) + self.segments self.load(remove_path_segments(base, segments)) return self def add(self, path): new_segments = path if isinstance(path, six.string_types): new_segments = self._segment_from_path(path) if self.segments == [''] and new_segments and new_segments[0] != '': new_segments.insert(0, '') segments = self.segments if self.is_absolute and segments and segments[0] != '': segments.insert(0, '') self.load(join_path_segments(segments, new_segments)) return self def __str__(self): segments = list(self.segments) if self.is_absolute: if not segments: segments = ['', ''] else: segments.insert(0, '') return self._path_from_segments(segments) def __repr__(self): return "%s('%s')" % (self.__class__.__name__, str(self)) def __bool__(self): return len(self.segments) > 0 __nonzero__ = __bool__ def __eq__(self, other): return str(self) == str(other) def __ne__(self, other): return not self == other # TODO(benjamin): incomplete @staticmethod def _segment_from_path(path): return [unquote(segment) for segment in path.split('/')] # TODO(benjamin): incomplete @staticmethod def _path_from_segments(segments): if '%' not in '/'.join(segments): segments = [quote(segment) for segment in segments] return '/'.join(segments)
by46/simplekit
simplekit/url/path.py
Path.normalize
python
def normalize(self): if str(self): normalized = normpath(str(self)) + ('/' * self.is_dir) if normalized.startswith('//'): # http://bugs.python.org/636648 normalized = '/' + normalized.lstrip('/') self.load(normalized) return self
Normalize the path. Turn /file/title/../author to /file/author :return: <self>
train
https://github.com/by46/simplekit/blob/33f3ce6de33accc185e1057f096af41859db5976/simplekit/url/path.py#L115-L126
null
class Path(object): def __init__(self, path): self.segments = [] self.is_absolute = True self.load(path) @property def is_dir(self): return (self.segments == [] or (self.segments and self.segments[-1] == '')) @property def is_file(self): return not self.is_dir def load(self, path): if not path: segments = [] elif isinstance(path, six.string_types): segments = self._segment_from_path(path) else: # list interface segments = path if len(segments) > 1 and segments[0] == '': segments.pop(0) self.segments = [unquote(segment) for segment in segments] return self def set(self, path): self.load(path) return self def remove(self, path=None): if path is None: self.load('') else: segments = path if isinstance(path, six.string_types): segments = self._segment_from_path(path) base = ([''] if self.is_absolute else []) + self.segments self.load(remove_path_segments(base, segments)) return self def add(self, path): new_segments = path if isinstance(path, six.string_types): new_segments = self._segment_from_path(path) if self.segments == [''] and new_segments and new_segments[0] != '': new_segments.insert(0, '') segments = self.segments if self.is_absolute and segments and segments[0] != '': segments.insert(0, '') self.load(join_path_segments(segments, new_segments)) return self def __str__(self): segments = list(self.segments) if self.is_absolute: if not segments: segments = ['', ''] else: segments.insert(0, '') return self._path_from_segments(segments) def __repr__(self): return "%s('%s')" % (self.__class__.__name__, str(self)) def __bool__(self): return len(self.segments) > 0 __nonzero__ = __bool__ def __eq__(self, other): return str(self) == str(other) def __ne__(self, other): return not self == other # TODO(benjamin): incomplete @staticmethod def _segment_from_path(path): return [unquote(segment) for segment in path.split('/')] # TODO(benjamin): incomplete @staticmethod def _path_from_segments(segments): if '%' not in '/'.join(segments): segments = [quote(segment) for segment in segments] return '/'.join(segments)
dalloriam/engel
engel/widgets/structure.py
Head.load_stylesheet
python
def load_stylesheet(self, id, path): self.add_child(HeadLink(id=id, link_type="stylesheet", path=path))
Proper way to dynamically inject a stylesheet in a page. :param path: Path of the stylesheet to inject.
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/structure.py#L31-L37
[ "def add_child(self, child):\n \"\"\"\n Add a new child element to this widget.\n\n :param child: Object inheriting :class:`BaseElement`.\n \"\"\"\n self.children.append(child)\n child.parent = self\n\n if self.view and self.view.is_loaded:\n self.view.dispatch({\n 'name': 'append',\n 'html': child.compile(),\n 'selector': '#' + str(self.id)\n })\n" ]
class Head(BaseContainer): html_tag = "head" def load_script(self, path): """ Proper way to dynamically inject a script in a page. :param path: Path of the script to inject. """ self.view.dispatch({'name': 'script', 'path': path})
dalloriam/engel
engel/widgets/structure.py
List.add_child
python
def add_child(self, widget): li_itm = _li(id=self.id + str(self._count)) li_itm.add_child(widget) super(List, self).add_child(li_itm) self._items.append((widget, li_itm)) self._count += 1
Append a widget to the list. :param widget: Object inheriting :class:`~.widgets.base.BaseElement`
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/structure.py#L70-L81
[ "def add_child(self, child):\n \"\"\"\n Add a new child element to this widget.\n\n :param child: Object inheriting :class:`BaseElement`.\n \"\"\"\n self.children.append(child)\n child.parent = self\n\n if self.view and self.view.is_loaded:\n self.view.dispatch({\n 'name': 'append',\n 'html': child.compile(),\n 'selector': '#' + str(self.id)\n })\n" ]
class List(BaseContainer): """ Bridges python and HTML lists. :class:`List` exposes an interface similar to python lists and takes care of updating the corresponding HTML ``<ul>`` when the python object is updated. """ html_tag = "ul" def __init__(self, id, classname=None, parent=None, **kwargs): super(List, self).__init__(id, classname, parent, **kwargs) self._count = 0 self._items = [] def remove_child(self, widget): """ Remove a widget from the list. :param widget: Object inheriting :class:`~.widgets.base.BaseElement` """ raw = list(filter(lambda x: x[0] == widget, self._items)) if raw: itm, wrapped = raw[0] self._items.remove(raw[0]) super(List, self).remove_child(wrapped) else: raise ValueError("Child not in list.") def __iter__(self): return iter(list([x[0] for x in self._items])) def __len__(self): return len(self._items) def __getitem__(self, index): return self._items[index][0] def __setitem__(self, index, widget): old_li = self._items[index] li_itm = _li(id=old_li[1].id) li_itm.add_child(widget) old_wid = self.children[index] self.replace_child(old_wid, li_itm) self._items[index] = (widget, li_itm)
dalloriam/engel
engel/widgets/structure.py
List.remove_child
python
def remove_child(self, widget): raw = list(filter(lambda x: x[0] == widget, self._items)) if raw: itm, wrapped = raw[0] self._items.remove(raw[0]) super(List, self).remove_child(wrapped) else: raise ValueError("Child not in list.")
Remove a widget from the list. :param widget: Object inheriting :class:`~.widgets.base.BaseElement`
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/structure.py#L83-L95
[ "def remove_child(self, child):\n \"\"\"\n Remove a child widget from this widget.\n\n :param child: Object inheriting :class:`BaseElement`\n \"\"\"\n self.children.remove(child)\n child.parent = None\n\n if self.view and self.view.is_loaded:\n self.view.dispatch({\n 'name': 'remove',\n 'selector': '#' + child.id\n })\n" ]
class List(BaseContainer): """ Bridges python and HTML lists. :class:`List` exposes an interface similar to python lists and takes care of updating the corresponding HTML ``<ul>`` when the python object is updated. """ html_tag = "ul" def __init__(self, id, classname=None, parent=None, **kwargs): super(List, self).__init__(id, classname, parent, **kwargs) self._count = 0 self._items = [] def add_child(self, widget): """ Append a widget to the list. :param widget: Object inheriting :class:`~.widgets.base.BaseElement` """ li_itm = _li(id=self.id + str(self._count)) li_itm.add_child(widget) super(List, self).add_child(li_itm) self._items.append((widget, li_itm)) self._count += 1 def __iter__(self): return iter(list([x[0] for x in self._items])) def __len__(self): return len(self._items) def __getitem__(self, index): return self._items[index][0] def __setitem__(self, index, widget): old_li = self._items[index] li_itm = _li(id=old_li[1].id) li_itm.add_child(widget) old_wid = self.children[index] self.replace_child(old_wid, li_itm) self._items[index] = (widget, li_itm)
dalloriam/engel
engel/widgets/abstract.py
HeadLink.build
python
def build(self, link_type, path): super(HeadLink, self).build() self.target = path self.link_type = link_type self.autoclosing = True
:param link_type: Link type :param target: Link target
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/abstract.py#L30-L38
[ "def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n" ]
class HeadLink(BaseElement): """ Widget representing links described in the ``<head>`` section of a typical HTML document. This widget is used by the framework to generate links to stylesheets and auto-generated javascript files. """ html_tag = "link" target = html_property('href') """ File to which the HeadLink is pointing """ link_type = html_property('rel') """ Link type (Ex: stylesheet) """
dalloriam/engel
engel/widgets/abstract.py
PageTitle.build
python
def build(self, text): super(PageTitle, self).build() self.content = text
:param text: Page title
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/abstract.py#L49-L54
[ "def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n" ]
class PageTitle(BaseElement): """ Widget representing the title of the page. This widget is used by :meth:`~.application.View.render`. """ html_tag = "title"
dalloriam/engel
engel/widgets/abstract.py
Script.build
python
def build(self, js_path): super(Script, self).build() self.source = js_path
:param js_path: Javascript source code.
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/abstract.py#L69-L74
[ "def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n" ]
class Script(BaseElement): """ Widget representing a script element. """ html_tag = "script" source = html_property('src') """ Location of the script """
dalloriam/engel
engel/application.py
Application.start
python
def start(self, on_exit_callback=None): # TODO: Support params for services by mapping {servicename: {class, # params}}? for service in self.services.keys(): self.services[service] = self.services[service]() self.server.start(on_exit_callback)
Start the Engel application by initializing all registered services and starting an Autobahn IOLoop. :param on_exit_callback: Callback triggered on application exit
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/application.py#L59-L70
null
class Application(object): """ The ``Application`` abstract class represents the entirety of an Engel application. Your application should inherit from this class and redefine the specifics, like Views, Services, and any additional logic required by your project. """ base_title = None """ Page title pattern for the whole application. Gets set on a per-view basis by ``Application.base_title.format(view.title)``. """ # TODO: Add favicon def __init__(self, debug=False): """ Constructor of the Application. :param debug: Sets the logging level of the application :raises NotImplementedError: When ``Application.base_title`` not set in the class definition. """ self.debug = debug loglevel = logging.DEBUG if debug else logging.WARNING logging.basicConfig( format='%(asctime)s - [%(levelname)s] %(message)s', datefmt='%I:%M:%S %p', level=loglevel) self.processor = EventProcessor() self.server = EventServer(processor=self.processor) if self.base_title is None: raise NotImplementedError self.services = {} self.views = {} self.current_view = None self.register('init', lambda evt, interface: self._load_view('default')) def register(self, event, callback, selector=None): """ Resister an event that you want to monitor. :param event: Name of the event to monitor :param callback: Callback function for when the event is received (Params: event, interface). :param selector: `(Optional)` CSS selector for the element(s) you want to monitor. """ self.processor.register(event, callback, selector) def unregister(self, event, callback, selector=None): """ Unregisters an event that was being monitored. :param event: Name of the event to monitor :param callback: Callback function for when the event is received (Params: event, interface). :param selector: `(Optional)` CSS selector for the element(s) you want to monitor """ self.processor.unregister(event, callback, selector) def dispatch(self, command): """ Method used for sending events to the client. Refer to ``engel/engeljs.js`` to see the events supported by the client. :param command: Command dict to send to the client. """ self.processor.dispatch(command) @asyncio.coroutine def _load_view(self, view_name): if view_name not in self.views: raise NotImplementedError if self.current_view is not None: self.current_view.unload() self.current_view = self.views[view_name](self) return self.current_view._render()
dalloriam/engel
engel/application.py
Application.register
python
def register(self, event, callback, selector=None): self.processor.register(event, callback, selector)
Resister an event that you want to monitor. :param event: Name of the event to monitor :param callback: Callback function for when the event is received (Params: event, interface). :param selector: `(Optional)` CSS selector for the element(s) you want to monitor.
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/application.py#L72-L80
[ "def register(self, event, callback, selector=None):\n logging.debug('Registering: ' + str(event))\n\n if selector:\n key = str(id(callback))\n else:\n key = '_'\n\n self.handlers[event][key].append(callback)\n\n if event not in ('init', 'load', 'close'):\n capture = False\n if selector is None:\n selector = 'html'\n capture = True\n\n logging.debug('Dispatching: ' + str(event))\n self.dispatch({\n 'name': 'subscribe',\n 'event': event,\n 'selector': selector,\n 'capture': capture,\n 'key': str(id(callback))\n })\n" ]
class Application(object): """ The ``Application`` abstract class represents the entirety of an Engel application. Your application should inherit from this class and redefine the specifics, like Views, Services, and any additional logic required by your project. """ base_title = None """ Page title pattern for the whole application. Gets set on a per-view basis by ``Application.base_title.format(view.title)``. """ # TODO: Add favicon def __init__(self, debug=False): """ Constructor of the Application. :param debug: Sets the logging level of the application :raises NotImplementedError: When ``Application.base_title`` not set in the class definition. """ self.debug = debug loglevel = logging.DEBUG if debug else logging.WARNING logging.basicConfig( format='%(asctime)s - [%(levelname)s] %(message)s', datefmt='%I:%M:%S %p', level=loglevel) self.processor = EventProcessor() self.server = EventServer(processor=self.processor) if self.base_title is None: raise NotImplementedError self.services = {} self.views = {} self.current_view = None self.register('init', lambda evt, interface: self._load_view('default')) def start(self, on_exit_callback=None): """ Start the Engel application by initializing all registered services and starting an Autobahn IOLoop. :param on_exit_callback: Callback triggered on application exit """ # TODO: Support params for services by mapping {servicename: {class, # params}}? for service in self.services.keys(): self.services[service] = self.services[service]() self.server.start(on_exit_callback) def unregister(self, event, callback, selector=None): """ Unregisters an event that was being monitored. :param event: Name of the event to monitor :param callback: Callback function for when the event is received (Params: event, interface). :param selector: `(Optional)` CSS selector for the element(s) you want to monitor """ self.processor.unregister(event, callback, selector) def dispatch(self, command): """ Method used for sending events to the client. Refer to ``engel/engeljs.js`` to see the events supported by the client. :param command: Command dict to send to the client. """ self.processor.dispatch(command) @asyncio.coroutine def _load_view(self, view_name): if view_name not in self.views: raise NotImplementedError if self.current_view is not None: self.current_view.unload() self.current_view = self.views[view_name](self) return self.current_view._render()
dalloriam/engel
engel/application.py
Application.unregister
python
def unregister(self, event, callback, selector=None): self.processor.unregister(event, callback, selector)
Unregisters an event that was being monitored. :param event: Name of the event to monitor :param callback: Callback function for when the event is received (Params: event, interface). :param selector: `(Optional)` CSS selector for the element(s) you want to monitor
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/application.py#L82-L90
null
class Application(object): """ The ``Application`` abstract class represents the entirety of an Engel application. Your application should inherit from this class and redefine the specifics, like Views, Services, and any additional logic required by your project. """ base_title = None """ Page title pattern for the whole application. Gets set on a per-view basis by ``Application.base_title.format(view.title)``. """ # TODO: Add favicon def __init__(self, debug=False): """ Constructor of the Application. :param debug: Sets the logging level of the application :raises NotImplementedError: When ``Application.base_title`` not set in the class definition. """ self.debug = debug loglevel = logging.DEBUG if debug else logging.WARNING logging.basicConfig( format='%(asctime)s - [%(levelname)s] %(message)s', datefmt='%I:%M:%S %p', level=loglevel) self.processor = EventProcessor() self.server = EventServer(processor=self.processor) if self.base_title is None: raise NotImplementedError self.services = {} self.views = {} self.current_view = None self.register('init', lambda evt, interface: self._load_view('default')) def start(self, on_exit_callback=None): """ Start the Engel application by initializing all registered services and starting an Autobahn IOLoop. :param on_exit_callback: Callback triggered on application exit """ # TODO: Support params for services by mapping {servicename: {class, # params}}? for service in self.services.keys(): self.services[service] = self.services[service]() self.server.start(on_exit_callback) def register(self, event, callback, selector=None): """ Resister an event that you want to monitor. :param event: Name of the event to monitor :param callback: Callback function for when the event is received (Params: event, interface). :param selector: `(Optional)` CSS selector for the element(s) you want to monitor. """ self.processor.register(event, callback, selector) def dispatch(self, command): """ Method used for sending events to the client. Refer to ``engel/engeljs.js`` to see the events supported by the client. :param command: Command dict to send to the client. """ self.processor.dispatch(command) @asyncio.coroutine def _load_view(self, view_name): if view_name not in self.views: raise NotImplementedError if self.current_view is not None: self.current_view.unload() self.current_view = self.views[view_name](self) return self.current_view._render()
dalloriam/engel
engel/application.py
View.on
python
def on(self, event, callback, selector=None): cbk = asyncio.coroutine(callback) self._event_cache.append( {'event': event, 'callback': cbk, 'selector': selector}) if self.is_loaded: self.context.register(event, cbk, selector)
Wrapper around :meth:`~.application.Application.register`. If :meth:`~.application.View.on` is called, for instance, during :meth:`~.application.View.build`, the event handlers will be enqueued and registered when the view is loaded. Similarly, if :meth:`~.application.View.on` is called once the view is loaded (for example, in a button callback), the event handler will be registered immediately. :param event: Name of the event to monitor :param callback: Callback function for when the event is received (Params: event, interface). :param selector: `(Optional)` CSS selector for the element(s) you want to monitor
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/application.py#L177-L193
null
class View(object): title = None """ Title of the view. """ stylesheet = None """ Stylesheet of the view. """ libraries = [] """ List of modules encapsulating the javascript libraries used by the view. """ def __init__(self, context): """ Constructor of the view. :param context: Application instantiating the view. :raises NotImplementedError: When ``View.title`` is not set. """ if self.title is None: raise NotImplementedError self.is_loaded = False self._doc_root = Document(id="engel-main", view=self) self._head = Head(id="engel-head", parent=self._doc_root) self.root = Body(id="main-body", parent=self._doc_root) self.context = context for library in self.libraries: print("Loading library...") for stylesheet in library.stylesheets: self._head.load_stylesheet(id(stylesheet), stylesheet) for script in library.scripts: self._head.load_script(script) if self.stylesheet is not None: self._head.load_stylesheet('main-stylesheet', self.stylesheet) self._event_cache = [] self.context.register('load', self._unpack_events) def build(self): """ Method building the layout of the view. Override this in your view subclass to define your view's layout. """ raise NotImplementedError def redirect(self, view_name): """ Function used for view switching. Use it to get the callback in an event handler declaration. ``self.on('click', self.redirect('myview'), '#' + mybtn.id)`` :param view_name: Target view :returns: View loader callback """ return lambda x, y: self.context._load_view(view_name) def dispatch(self, command): """ Dispatch a command to the client at view-level. :param command: Command dict to send to the client. """ self.context.dispatch(command) @asyncio.coroutine def _unpack_events(self, event, interface): self.is_loaded = True for evt in self._event_cache: self.context.register( evt['event'], evt['callback'], evt['selector']) def unload(self): """ Overridable method called when a view is unloaded (either on view change or on application shutdown). Handles by default the unregistering of all event handlers previously registered by the view. """ self.is_loaded = False for evt in self._event_cache: self.context.unregister( evt['event'], evt['callback'], evt['selector']) self._event_cache = {} def _render(self): PageTitle(id="_page-title", text=self.context.base_title.format(self.title), parent=self._head) self.build() return {'name': 'init', 'html': self._doc_root.compile(), 'debug': self.context.debug}
dalloriam/engel
engel/application.py
View.unload
python
def unload(self): self.is_loaded = False for evt in self._event_cache: self.context.unregister( evt['event'], evt['callback'], evt['selector']) self._event_cache = {}
Overridable method called when a view is unloaded (either on view change or on application shutdown). Handles by default the unregistering of all event handlers previously registered by the view.
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/application.py#L210-L220
null
class View(object): title = None """ Title of the view. """ stylesheet = None """ Stylesheet of the view. """ libraries = [] """ List of modules encapsulating the javascript libraries used by the view. """ def __init__(self, context): """ Constructor of the view. :param context: Application instantiating the view. :raises NotImplementedError: When ``View.title`` is not set. """ if self.title is None: raise NotImplementedError self.is_loaded = False self._doc_root = Document(id="engel-main", view=self) self._head = Head(id="engel-head", parent=self._doc_root) self.root = Body(id="main-body", parent=self._doc_root) self.context = context for library in self.libraries: print("Loading library...") for stylesheet in library.stylesheets: self._head.load_stylesheet(id(stylesheet), stylesheet) for script in library.scripts: self._head.load_script(script) if self.stylesheet is not None: self._head.load_stylesheet('main-stylesheet', self.stylesheet) self._event_cache = [] self.context.register('load', self._unpack_events) def build(self): """ Method building the layout of the view. Override this in your view subclass to define your view's layout. """ raise NotImplementedError def redirect(self, view_name): """ Function used for view switching. Use it to get the callback in an event handler declaration. ``self.on('click', self.redirect('myview'), '#' + mybtn.id)`` :param view_name: Target view :returns: View loader callback """ return lambda x, y: self.context._load_view(view_name) def on(self, event, callback, selector=None): """ Wrapper around :meth:`~.application.Application.register`. If :meth:`~.application.View.on` is called, for instance, during :meth:`~.application.View.build`, the event handlers will be enqueued and registered when the view is loaded. Similarly, if :meth:`~.application.View.on` is called once the view is loaded (for example, in a button callback), the event handler will be registered immediately. :param event: Name of the event to monitor :param callback: Callback function for when the event is received (Params: event, interface). :param selector: `(Optional)` CSS selector for the element(s) you want to monitor """ cbk = asyncio.coroutine(callback) self._event_cache.append( {'event': event, 'callback': cbk, 'selector': selector}) if self.is_loaded: self.context.register(event, cbk, selector) def dispatch(self, command): """ Dispatch a command to the client at view-level. :param command: Command dict to send to the client. """ self.context.dispatch(command) @asyncio.coroutine def _unpack_events(self, event, interface): self.is_loaded = True for evt in self._event_cache: self.context.register( evt['event'], evt['callback'], evt['selector']) def _render(self): PageTitle(id="_page-title", text=self.context.base_title.format(self.title), parent=self._head) self.build() return {'name': 'init', 'html': self._doc_root.compile(), 'debug': self.context.debug}
dalloriam/engel
engel/libraries/bootstrap4/widgets/structure.py
ImageCard.build
python
def build(self, title, text, img_url): super(ImageCard, self).build() self.title = Title(id=self.id + "-title", text=title, classname="card-title", size=3, parent=self) self.block = Panel(id=self.id + "-block", classname="card-block", parent=self) self.image = Image(id=self.id + "-image", img_url=img_url, classname="card-image-top img-fluid", parent=self.block) self.text = Paragraph(id=self.id + "-text", text=text, classname="card-text", parent=self.block)
:param title: Title of the card :param text: Description of the card :param img_url: Image of the card
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/libraries/bootstrap4/widgets/structure.py#L32-L44
[ "def build(self):\n super(BaseCard, self).build()\n self.add_class('card')\n" ]
class ImageCard(BaseCard): """ Image card, with a title and short description. """
dalloriam/engel
engel/widgets/base.py
BaseContainer.add_child
python
def add_child(self, child): self.children.append(child) child.parent = self if self.view and self.view.is_loaded: self.view.dispatch({ 'name': 'append', 'html': child.compile(), 'selector': '#' + str(self.id) })
Add a new child element to this widget. :param child: Object inheriting :class:`BaseElement`.
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/base.py#L166-L180
[ "def compile(self):\n \"\"\"\n Generate the HTML representing this widget.\n\n :returns: HTML string representing this widget.\n \"\"\"\n return self._generate_html()\n", "def compile(self):\n \"\"\"\n Recursively compile this widget as well as all of its children to HTML.\n\n :returns: HTML string representation of this widget.\n \"\"\"\n self.content = \"\".join(map(lambda x: x.compile(), self.children))\n return self._generate_html()\n" ]
class BaseContainer(BaseElement): """ Base class common to all widgets that can contain other widgets. """ @BaseElement.parent.setter def parent(self, value): self._set_parent(value) if value is not None: for child in self.children: child.view = self.view def __init__(self, id, classname=None, parent=None, **kwargs): """ Constructor of the Base Container """ self.children = [] super(BaseContainer, self).__init__(id, classname, parent, **kwargs) """ List of objects inheriting :class:`BaseElement`. """ def remove_child(self, child): """ Remove a child widget from this widget. :param child: Object inheriting :class:`BaseElement` """ self.children.remove(child) child.parent = None if self.view and self.view.is_loaded: self.view.dispatch({ 'name': 'remove', 'selector': '#' + child.id }) def clear_children(self): """ Remove the children of this widget """ for child in reversed(self.children): self.remove_child(child) def replace_child(self, old_child, new_child): for i, child in enumerate(self.children): if child is old_child: old_child.parent = None new_child.parent = self self.children[i] = new_child if self.view and self.view.is_loaded: self.view.dispatch({ 'name': 'replace', 'selector': '#' + old_child.id, 'html': new_child.compile() }) return def compile(self): """ Recursively compile this widget as well as all of its children to HTML. :returns: HTML string representation of this widget. """ self.content = "".join(map(lambda x: x.compile(), self.children)) return self._generate_html()
dalloriam/engel
engel/widgets/base.py
BaseContainer.remove_child
python
def remove_child(self, child): self.children.remove(child) child.parent = None if self.view and self.view.is_loaded: self.view.dispatch({ 'name': 'remove', 'selector': '#' + child.id })
Remove a child widget from this widget. :param child: Object inheriting :class:`BaseElement`
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/base.py#L182-L195
null
class BaseContainer(BaseElement): """ Base class common to all widgets that can contain other widgets. """ @BaseElement.parent.setter def parent(self, value): self._set_parent(value) if value is not None: for child in self.children: child.view = self.view def __init__(self, id, classname=None, parent=None, **kwargs): """ Constructor of the Base Container """ self.children = [] super(BaseContainer, self).__init__(id, classname, parent, **kwargs) """ List of objects inheriting :class:`BaseElement`. """ def add_child(self, child): """ Add a new child element to this widget. :param child: Object inheriting :class:`BaseElement`. """ self.children.append(child) child.parent = self if self.view and self.view.is_loaded: self.view.dispatch({ 'name': 'append', 'html': child.compile(), 'selector': '#' + str(self.id) }) def clear_children(self): """ Remove the children of this widget """ for child in reversed(self.children): self.remove_child(child) def replace_child(self, old_child, new_child): for i, child in enumerate(self.children): if child is old_child: old_child.parent = None new_child.parent = self self.children[i] = new_child if self.view and self.view.is_loaded: self.view.dispatch({ 'name': 'replace', 'selector': '#' + old_child.id, 'html': new_child.compile() }) return def compile(self): """ Recursively compile this widget as well as all of its children to HTML. :returns: HTML string representation of this widget. """ self.content = "".join(map(lambda x: x.compile(), self.children)) return self._generate_html()
dalloriam/engel
engel/widgets/base.py
BaseContainer.compile
python
def compile(self): self.content = "".join(map(lambda x: x.compile(), self.children)) return self._generate_html()
Recursively compile this widget as well as all of its children to HTML. :returns: HTML string representation of this widget.
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/base.py#L220-L227
[ "def _generate_html(self):\n if self.autoclosing:\n return \"<{0}{1}>\".format(self._get_html_tag(), self._format_attributes())\n else:\n return \"<{0}{1}>{2}</{0}>\".format(self._get_html_tag(), self._format_attributes(), self.content)\n" ]
class BaseContainer(BaseElement): """ Base class common to all widgets that can contain other widgets. """ @BaseElement.parent.setter def parent(self, value): self._set_parent(value) if value is not None: for child in self.children: child.view = self.view def __init__(self, id, classname=None, parent=None, **kwargs): """ Constructor of the Base Container """ self.children = [] super(BaseContainer, self).__init__(id, classname, parent, **kwargs) """ List of objects inheriting :class:`BaseElement`. """ def add_child(self, child): """ Add a new child element to this widget. :param child: Object inheriting :class:`BaseElement`. """ self.children.append(child) child.parent = self if self.view and self.view.is_loaded: self.view.dispatch({ 'name': 'append', 'html': child.compile(), 'selector': '#' + str(self.id) }) def remove_child(self, child): """ Remove a child widget from this widget. :param child: Object inheriting :class:`BaseElement` """ self.children.remove(child) child.parent = None if self.view and self.view.is_loaded: self.view.dispatch({ 'name': 'remove', 'selector': '#' + child.id }) def clear_children(self): """ Remove the children of this widget """ for child in reversed(self.children): self.remove_child(child) def replace_child(self, old_child, new_child): for i, child in enumerate(self.children): if child is old_child: old_child.parent = None new_child.parent = self self.children[i] = new_child if self.view and self.view.is_loaded: self.view.dispatch({ 'name': 'replace', 'selector': '#' + old_child.id, 'html': new_child.compile() }) return
dalloriam/engel
engel/widgets/text.py
Title.build
python
def build(self, text, size=1): super(Title, self).build() self.content = text self.size = size
:param text: Text of the widget :param size: Size of the text (Higher size = smaller title)
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/text.py#L11-L18
[ "def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n" ]
class Title(BaseElement): """ Title widget analogous to the HTML <h{n}> elements. """ def _get_html_tag(self): return "h{0}".format(self.size)
dalloriam/engel
engel/widgets/text.py
Paragraph.build
python
def build(self, text): super(Paragraph, self).build() self.content = text
:param text: Content of the paragraph
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/text.py#L31-L36
[ "def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n" ]
class Paragraph(BaseElement): """ Simple paragraph widget """ html_tag = "p"
dalloriam/engel
engel/widgets/text.py
Span.build
python
def build(self, text): super(Span, self).build() self.content = text
:param text: Content of the span
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/text.py#L46-L51
[ "def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n" ]
class Span(BaseElement): """ Simple span widget """ html_tag = "span"
dalloriam/engel
engel/widgets/text.py
TextLink.build
python
def build(self, text, url): super(TextLink, self).build() self.target = url self.content = text
:param text: Text of the link :param url: Target URL
train
https://github.com/dalloriam/engel/blob/f3477cd546e885bc53e755b3eb1452ce43ef5697/engel/widgets/text.py#L66-L73
[ "def build(self, **kwargs):\n \"\"\"\n Gets called before the widget gets attached to a view. Override this\n to define your widget's specific traits.\n \"\"\"\n pass\n" ]
class TextLink(BaseElement): """ Text widget linking to an external URL. """ html_tag = "a" target = html_property('href') """ Target of the link """
JoaoFelipe/pyposast
pyposast/__init__.py
parse
python
def parse(code, filename='<unknown>', mode='exec', tree=None): visitor = Visitor(code, filename, mode, tree=tree) return visitor.tree
Parse the source into an AST node with PyPosAST. Enhance nodes with positions Arguments: code -- code text Keyword Arguments: filename -- code path mode -- execution mode (exec, eval, single) tree -- current tree, if it was optimized
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/__init__.py#L12-L27
null
# Copyright (c) 2016 Universidade Federal Fluminense (UFF) # This file is part of PyPosAST. # Please, consult the license terms in the LICENSE file. """PyPosAST Module""" from __future__ import (absolute_import, division) import ast from .visitor import LineProvenanceVisitor as Visitor, extract_code from .cross_version import native_decode_source, decode_source_to_unicode class _GetVisitor(ast.NodeVisitor): """Visit nodes and store them in .result if they match the given type""" def __init__(self, tree, desired_type): self.desired_type = desired_type self.result = [] self.visit(tree) def generic_visit(self, node): if isinstance(node, self.desired_type): self.result.append(node) return ast.NodeVisitor.generic_visit(self, node) def get_nodes(code, desired_type, path="__main__", mode="exec", tree=None): """Find all nodes of a given type Arguments: code -- code text desired_type -- ast Node or tuple Keyword Arguments: path -- code path mode -- execution mode (exec, eval, single) tree -- current tree, if it was optimized """ return _GetVisitor(parse(code, path, mode, tree), desired_type).result
JoaoFelipe/pyposast
pyposast/__init__.py
get_nodes
python
def get_nodes(code, desired_type, path="__main__", mode="exec", tree=None): return _GetVisitor(parse(code, path, mode, tree), desired_type).result
Find all nodes of a given type Arguments: code -- code text desired_type -- ast Node or tuple Keyword Arguments: path -- code path mode -- execution mode (exec, eval, single) tree -- current tree, if it was optimized
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/__init__.py#L44-L58
[ "def parse(code, filename='<unknown>', mode='exec', tree=None):\n \"\"\"Parse the source into an AST node with PyPosAST.\n Enhance nodes with positions\n\n\n Arguments:\n code -- code text\n\n\n Keyword Arguments:\n filename -- code path\n mode -- execution mode (exec, eval, single)\n tree -- current tree, if it was optimized\n \"\"\"\n visitor = Visitor(code, filename, mode, tree=tree)\n return visitor.tree\n" ]
# Copyright (c) 2016 Universidade Federal Fluminense (UFF) # This file is part of PyPosAST. # Please, consult the license terms in the LICENSE file. """PyPosAST Module""" from __future__ import (absolute_import, division) import ast from .visitor import LineProvenanceVisitor as Visitor, extract_code from .cross_version import native_decode_source, decode_source_to_unicode def parse(code, filename='<unknown>', mode='exec', tree=None): """Parse the source into an AST node with PyPosAST. Enhance nodes with positions Arguments: code -- code text Keyword Arguments: filename -- code path mode -- execution mode (exec, eval, single) tree -- current tree, if it was optimized """ visitor = Visitor(code, filename, mode, tree=tree) return visitor.tree class _GetVisitor(ast.NodeVisitor): """Visit nodes and store them in .result if they match the given type""" def __init__(self, tree, desired_type): self.desired_type = desired_type self.result = [] self.visit(tree) def generic_visit(self, node): if isinstance(node, self.desired_type): self.result.append(node) return ast.NodeVisitor.generic_visit(self, node)
JoaoFelipe/pyposast
pyposast/visitor.py
extract_code
python
def extract_code(lines, node, lstrip="", ljoin="\n", strip=""): first_line, first_col = node.first_line - 1, node.first_col last_line, last_col = node.last_line - 1, node.last_col if first_line == last_line: return lines[first_line][first_col:last_col].strip(strip) result = [] # Add first line result.append(lines[first_line][first_col:].strip(lstrip)) # Add middle lines if first_line + 1 != last_line: for line in range(first_line + 1, last_line): result.append(lines[line].strip(lstrip)) # Add last line result.append(lines[last_line][:last_col].strip(lstrip)) return ljoin.join(result).strip(strip)
Get corresponding text in the code Arguments: lines -- code splitted by linebreak node -- PyPosAST enhanced node Keyword Arguments: lstrip -- During extraction, strip lines with this arg (default="") ljoin -- During extraction, join lines with this arg (default="\n") strip -- After extraction, strip all code with this arg (default="")
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L30-L58
null
# Copyright (c) 2016 Universidade Federal Fluminense (UFF) # This file is part of PyPosAST. # Please, consult the license terms in the LICENSE file. from __future__ import (absolute_import, division) import ast from copy import copy from operator import sub from functools import wraps from .cross_version import only_python2, only_python3, native_decode_source from .cross_version import only_python36 from .constants import OPERATORS from .parser import extract_tokens from .utils import (pairwise, inc_tuple, dec_tuple, position_between, find_next_parenthesis, find_next_comma, extract_positions, find_next_colon, find_next_equal) from .node_helpers import (NodeWithPosition, nprint, copy_info, ast_pos, copy_from_lineno_col_offset, set_pos, r_set_pos, min_first_max_last, set_max_position, set_max_position, set_previous_element, r_set_previous_element, update_expr_parenthesis, increment_node_position, keyword_followed_by_ids, start_by_keyword) def visit_all(fn): @wraps(fn) def decorator(self, node, *args, **kwargs): result = self.generic_visit(node) fn(self, node, *args, **kwargs) return result return decorator def visit_expr(fn): @wraps(fn) def decorator(self, node, *args, **kwargs): result = self.generic_visit(node) fn(self, node, *args, **kwargs) update_expr_parenthesis(self.lcode, self.parenthesis, node) return result return decorator visit_stmt = visit_all visit_mod = visit_all class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.dnode
python
def dnode(self, node): new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node
Duplicate node and adjust it for deslocated line and column
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L119-L124
null
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.dposition
python
def dposition(self, node, dcol=0): nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol)
Return deslocated line and column
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L126-L129
[ "def dnode(self, node):\n \"\"\"Duplicate node and adjust it for deslocated line and column\"\"\"\n new_node = copy(node)\n new_node.lineno += self.dline\n new_node.col_offset += self.dcol\n return new_node\n" ]
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.calculate_infixop
python
def calculate_infixop(self, node, previous, next_node): previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) )
Create new node for infixop
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L131-L150
null
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.calculate_unaryop
python
def calculate_unaryop(self, node, next_node): position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) )
Create new node for unaryop
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L152-L166
null
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.uid_something_colon
python
def uid_something_colon(self, node): node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last
Creates op_pos for node from uid to colon
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L168-L176
null
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.optional_else
python
def optional_else(self, node, last): if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst))
Create op_pos for optional else
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L178-L187
[ "def min_first_max_last(node, other):\n node.first_line, node.first_col = min(\n (node.first_line, node.first_col),\n (other.first_line, other.first_col))\n node.last_line, node.last_col = max(\n (node.last_line, node.last_col),\n (other.last_line, other.last_col))\n" ]
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.comma_separated_list
python
def comma_separated_list(self, node, subnodes): for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first))
Process comma separated list
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L189-L195
[ "def find_next_comma(code, position):\n \"\"\"Find next comman and return its first and last positions\"\"\"\n return find_next_character(code, position, ',')\n" ]
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.visit_Constant
python
def visit_Constant(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col)
PEP 511: Constants are generated by optimizers
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L245-L251
[ "def ast_pos(node, bytes_pos_to_utf8):\n bytes_pos = bytes_pos_to_utf8[node.lineno - 1]\n return node.lineno, bytes_pos.get(node.col_offset)\n", "def dnode(self, node):\n \"\"\"Duplicate node and adjust it for deslocated line and column\"\"\"\n new_node = copy(node)\n new_node.lineno += self.dline\n new_node.col_offset += self.dcol\n return new_node\n" ]
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.visit_Repr
python
def visit_Repr(self, node): position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ]
Python 2
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L396-L406
[ "def r_set_pos(node, last, first):\n node.first_line, node.first_col = first\n node.uid = node.last_line, node.last_col = last\n" ]
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.find_next_comma
python
def find_next_comma(self, node, sub): position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first))
Find comma after sub andd add NodeWithPosition in node
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L586-L591
[ "def find_next_comma(code, position):\n \"\"\"Find next comman and return its first and last positions\"\"\"\n return find_next_character(code, position, ',')\n" ]
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.visit_Starred
python
def visit_Starred(self, node): position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ]
Python 3
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L706-L714
[ "def dec_tuple(tup):\n return (tup[0], tup[1] - 1)\n", "def r_set_pos(node, last, first):\n node.first_line, node.first_col = first\n node.uid = node.last_line, node.last_col = last\n" ]
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.visit_NameConstant
python
def visit_NameConstant(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node)
Python 3
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L717-L721
[ "def copy_from_lineno_col_offset(node, identifier, bytes_pos_to_utf8, to=None):\n if to is None:\n to = node\n to.first_line, to.first_col = ast_pos(node, bytes_pos_to_utf8)\n to.last_line = node.lineno\n len_id = len(identifier)\n to.last_col = to.first_col + len_id\n to.uid = (to.last_line, to.last_col)\n", "def dnode(self, node):\n \"\"\"Duplicate node and adjust it for deslocated line and column\"\"\"\n new_node = copy(node)\n new_node.lineno += self.dline\n new_node.col_offset += self.dcol\n return new_node\n" ]
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt def visit_Print(self, node): """ Python 2 """ start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes) @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
pyposast/visitor.py
LineProvenanceVisitor.visit_Print
python
def visit_Print(self, node): start_by_keyword(node, self.operators['print'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] subnodes = [] if node.dest: min_first_max_last(node, node.dest) position = (node.dest.first_line, node.dest.first_col) last, first = self.operators['>>'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) subnodes.append(node.dest) if node.values: min_first_max_last(node, node.values[-1]) subnodes.extend(node.values) self.comma_separated_list(node, subnodes)
Python 2
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/visitor.py#L1054-L1071
[ "def min_first_max_last(node, other):\n node.first_line, node.first_col = min(\n (node.first_line, node.first_col),\n (other.first_line, other.first_col))\n node.last_line, node.last_col = max(\n (node.last_line, node.last_col),\n (other.last_line, other.last_col))\n", "def start_by_keyword(node, keyword, bytes_pos_to_utf8, set_last=True):\n position = ast_pos(node, bytes_pos_to_utf8)\n try:\n node.uid, first = keyword.find_next(position)\n if first != position:\n raise IndexError\n except IndexError:\n node.uid, first = keyword.find_previous(position)\n node.first_line, node.first_col = first\n if set_last:\n node.last_line, node.last_col = node.uid\n", "def comma_separated_list(self, node, subnodes):\n \"\"\"Process comma separated list \"\"\"\n for item in subnodes:\n position = (item.last_line, item.last_col)\n first, last = find_next_comma(self.lcode, position)\n if first: # comma exists\n node.op_pos.append(NodeWithPosition(last, first))\n" ]
class LineProvenanceVisitor(ast.NodeVisitor): # pylint: disable=invalid-name, missing-docstring # pylint: disable=too-many-instance-attributes, too-many-public-methods # pylint: disable=no-self-use def __init__(self, code, path, mode='exec', tree=None): code = native_decode_source(code) self.tree = tree or ast.parse(code, path, mode=mode) self.code = code self.lcode = code.split('\n') self.utf8_pos_to_bytes = [] self.bytes_pos_to_utf8 = [] if ((only_python2 and isinstance(code, str)) or (only_python3 and isinstance(code, bytes))): for line in self.lcode: same = {j: j for j, c in enumerate(line)} self.utf8_pos_to_bytes.append(same) self.bytes_pos_to_utf8.append(same) else: for line in self.lcode: utf8, byte = extract_positions(line) self.utf8_pos_to_bytes.append(utf8) self.bytes_pos_to_utf8.append(byte) tokens, self.operators, self.names = extract_tokens(code) self.parenthesis = tokens[0] self.sbrackets = tokens[1] self.brackets = tokens[2] self.strings = tokens[3] self.attributes = tokens[4] self.numbers = tokens[5] self.dline = 0 self.dcol = 0 self.visit(self.tree) def dnode(self, node): """Duplicate node and adjust it for deslocated line and column""" new_node = copy(node) new_node.lineno += self.dline new_node.col_offset += self.dcol return new_node def dposition(self, node, dcol=0): """Return deslocated line and column""" nnode = self.dnode(node) return (nnode.lineno, nnode.col_offset + dcol) def calculate_infixop(self, node, previous, next_node): """Create new node for infixop""" previous_position = (previous.last_line, previous.last_col - 1) position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if previous_position < pos[1] < position: possible.append(pos) except KeyError: pass if not possible: raise ValueError("not a single {} between {} and {}".format( OPERATORS[node.__class__], previous_position, position)) return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def calculate_unaryop(self, node, next_node): """Create new node for unaryop""" position = (next_node.first_line, next_node.first_col + 1) possible = [] for ch in OPERATORS[node.__class__]: try: pos = self.operators[ch].find_previous(position) if pos[1] < position: possible.append(pos) except KeyError: pass return NodeWithPosition( *min(possible, key=lambda x: tuple(map(sub, position, x[0]))) ) def uid_something_colon(self, node): """ Creates op_pos for node from uid to colon """ node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) return last def optional_else(self, node, last): """ Create op_pos for optional else """ if node.orelse: min_first_max_last(node, node.orelse[-1]) if 'else' in self.operators: position = (node.orelse[0].first_line, node.orelse[0].first_col) _, efirst = self.operators['else'].find_previous(position) if efirst and efirst > last: elast, _ = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(elast, efirst)) def comma_separated_list(self, node, subnodes): """Process comma separated list """ for item in subnodes: position = (item.last_line, item.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_Name(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, node.id, self.bytes_pos_to_utf8, to=node ) @visit_expr def visit_Num(self, node): nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = nnode.lineno position = (node.first_line, node.first_col) node.last_line, node.last_col = self.numbers.find_next(position)[0] node.uid = (node.last_line, node.last_col) @visit_expr def visit_Str(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_JoinedStr(self, node): position = self.dposition(node) last_position = (node.lineno, node.col_offset) for value in node.values: if isinstance(value, ast.FormattedValue): value.bracket = self.brackets.find_next(last_position) self.visit(value) last_position = ( value.bracket[0][0], value.bracket[0][1] + 1, ) else: self.visit(value) position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @only_python36 def visit_FormattedValue(self, node): set_pos(node, *node.bracket) self.visit(node.value) if node.format_spec: self.visit(node.format_spec) update_expr_parenthesis(self.lcode, self.parenthesis, node) @only_python36 def visit_Constant(self, node): """PEP 511: Constants are generated by optimizers""" nnode = self.dnode(node) node.first_line, node.first_col = ast_pos(nnode, self.bytes_pos_to_utf8) node.last_line = node.first_line node.last_col = node.first_col + len(repr(node.value)) node.uid = (node.last_line, node.last_col) @visit_expr def visit_Attribute(self, node): copy_info(node, node.value) position = (node.last_line, node.last_col) last, _ = self.names[node.attr].find_next(position) node.last_line, node.last_col = last node.uid, first_dot = self.operators['.'].find_next(position) node.op_pos = [NodeWithPosition(node.uid, first_dot)] @visit_all def visit_Index(self, node): copy_info(node, node.value) @only_python3 @visit_expr def visit_Ellipsis(self, node): if 'lineno' in dir(node): """Python 3""" position = self.dposition(node) r_set_pos(node, *self.operators['...'].find_next(position)) @visit_all def visit_Slice(self, node): set_max_position(node) children = [node.lower, node.upper, node.step] node.children = [x for x in children if x] if isinstance(node.step, ast.Name) and node.step.id == 'None': position = (node.step.first_line, node.step.first_col - 1) empty_none = True try: last, first = self.operators['None'].find_next(position) if first == (node.step.first_line, node.step.first_col): empty_none = False except (KeyError, IndexError): pass if empty_none: node.step.last_col = self.dnode(node.step).col_offset + 1 node.step.uid = (node.step.last_line, node.step.last_col) node.op_pos = [] for sub_node in node.children: min_first_max_last(node, sub_node) def process_slice(self, the_slice, previous): if isinstance(the_slice, ast.Ellipsis): """Python 2 ellipsis has no location""" position = (previous.last_line, previous.last_col + 1) r_set_pos(the_slice, *self.operators['...'].find_next(position)) elif isinstance(the_slice, ast.Slice): position = (previous.last_line, previous.last_col + 1) the_slice.uid = self.operators[':'].find_next(position)[0] if not the_slice.lower: the_slice.first_line, the_slice.first_col = the_slice.uid the_slice.first_col -= 1 if not the_slice.upper and not the_slice.step: the_slice.last_line, the_slice.last_col = the_slice.uid elif isinstance(the_slice, ast.ExtSlice): set_max_position(the_slice) last_dim = previous for dim in the_slice.dims: self.process_slice(dim, last_dim) min_first_max_last(the_slice, dim) last_dim = dim for previous, dim in pairwise(the_slice.dims): self.post_process_slice(previous, (dim.first_line, dim.first_col)) the_slice.uid = (the_slice.dims[0].last_line, the_slice.dims[0].last_col + 1) def post_process_slice(self, previous, position): if isinstance(previous, ast.ExtSlice): self.post_process_slice(previous.dims[-1], position) previous.op_pos = [] self.comma_separated_list(previous, previous.dims) if isinstance(previous, (ast.Slice, ast.ExtSlice)): new_position = self.operators[':'].find_previous(position)[0] if new_position > (previous.last_line, previous.last_col): previous.last_line, previous.last_col = new_position if isinstance(previous, ast.Slice): if ':' in self.operators: start = (previous.first_line, previous.first_col) position = inc_tuple((previous.last_line, previous.last_col)) for _ in range(2): clast, cfirst = self.operators[':'].find_previous(position) if cfirst and cfirst >= start: previous.op_pos.append(NodeWithPosition(clast, cfirst)) position = inc_tuple(cfirst) else: break previous.op_pos.reverse() @visit_expr def visit_Subscript(self, node): self.process_slice(node.slice, node.value) position = (node.value.last_line, node.value.last_col) first, last = self.sbrackets.find_next(position) set_pos(node, first, last) node.op_pos = [ NodeWithPosition(inc_tuple(first), first), NodeWithPosition(last, dec_tuple(last)), ] node.first_line = node.value.first_line node.first_col = node.value.first_col self.post_process_slice(node.slice, node.uid) @visit_expr def visit_Tuple(self, node): node.op_pos = [] if not node.elts: position = self.dposition(node, dcol=1) set_pos(node, *self.parenthesis.find_previous(position)) else: first = node.elts[0] position = (first.last_line, first.last_col + 1) last, node.uid = self.operators[','].find_next(position) set_max_position(node) node.last_line, node.last_col = last for elt in node.elts: min_first_max_last(node, elt) position = (elt.last_line, elt.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.op_pos[-1]) @visit_expr def visit_List(self, node): position = self.dposition(node, dcol=1) set_pos(node, *self.sbrackets.find_previous(position)) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Repr(self, node): """ Python 2 """ position = (node.value.last_line, node.value.last_col + 1) r_set_pos(node, *self.operators['`'].find_next(position)) position = (node.value.first_line, node.value.first_col + 1) first = self.operators['`'].find_previous(position)[1] node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition((node.first_line, node.first_col + 1), first), NodeWithPosition(node.uid, (node.last_line, node.last_col - 1)), ] @visit_expr def visit_Call(self, node): node.op_pos = [] copy_info(node, node.func) position = (node.last_line, node.last_col) first, last = self.parenthesis.find_next(position) node.op_pos.append(NodeWithPosition(inc_tuple(first), first)) node.uid = node.last_line, node.last_col = last children = [] if hasattr(node, 'starargs'): # Python <= 3.4 children += [['starargs', node.starargs], ['kwargs', node.kwargs]] children += [['args', x] for x in node.args] children += [['keywords', x] for x in node.keywords] children = [x for x in children if x[1] is not None] if len(children) == 1 and isinstance(children[0][1], ast.expr): increment_node_position(self.lcode, children[0][1]) for child in children: position = (child[1].last_line, child[1].last_col) firstc, lastc = find_next_comma(self.lcode, position) if firstc: # comma exists child.append(NodeWithPosition(lastc, firstc)) else: child.append(None) children.sort(key=lambda x: (x[2] is None, getattr(x[2], 'uid', None))) for child in children: if child[-1]: node.op_pos.append(child[-1]) node.arg_order = children node.op_pos.append(NodeWithPosition(last, dec_tuple(last))) @visit_expr def visit_Compare(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.left) previous = node.left for i, comparator in enumerate(node.comparators): # Cannot set to the cmpop node as they are singletons node.op_pos.append( self.calculate_infixop(node.ops[i], previous, comparator) ) min_first_max_last(node, comparator) previous = comparator node.uid = node.last_line, node.last_col @visit_expr def visit_Await(self, node): start_by_keyword(node, self.operators['await'], self.bytes_pos_to_utf8) min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_expr def visit_Yield(self, node): start_by_keyword(node, self.operators['yield'], self.bytes_pos_to_utf8) if node.value: min_first_max_last(node, node.value) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_all def visit_comprehension(self, node): set_max_position(node) if hasattr(node, 'is_async') and node.is_async: # async in python 3.6 r_set_previous_element(node, node.target, self.operators['async']) first = node.first_line, node.first_col r_set_previous_element(node, node.target, self.operators['for']) node.first_line, node.first_col = first else: r_set_previous_element(node, node.target, self.operators['for']) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] min_first_max_last(node, node.iter) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) for eif in node.ifs: min_first_max_last(node, eif) position = dec_tuple((eif.first_line, eif.first_col)) last, first = self.operators['if'].find_next(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_GeneratorExp(self, node): set_max_position(node) min_first_max_last(node, node.elt) for generator in node.generators: min_first_max_last(node, generator) node.uid = node.elt.last_line, node.elt.last_col @visit_expr def visit_DictComp(self, node): set_previous_element(node, node.key, self.brackets) @visit_expr def visit_SetComp(self, node): set_previous_element(node, node.elt, self.brackets) @visit_expr def visit_ListComp(self, node): set_previous_element(node, node.elt, self.sbrackets) @visit_expr def visit_Set(self, node): set_previous_element(node, node.elts[0], self.brackets) node.op_pos = [] self.comma_separated_list(node, node.elts) @visit_expr def visit_Dict(self, node): node.op_pos = [] position = self.dposition(node, dcol=1) set_pos(node, *self.brackets.find_previous(position)) for key, value in zip(node.keys, node.values): position = (key.last_line, key.last_col) first, last = find_next_colon(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) position = (value.last_line, value.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_expr def visit_IfExp(self, node): set_max_position(node) min_first_max_last(node, node.body) min_first_max_last(node, node.orelse) position = (node.test.first_line, node.test.first_col + 1) node.uid = self.operators['if'].find_previous(position)[0] else_pos = self.operators['else'].find_previous(position)[0] node.op_pos = [ NodeWithPosition(node.uid, (node.uid[0], node.uid[1] - 2)), NodeWithPosition(else_pos, (else_pos[0], else_pos[1] - 4)) ] def update_arguments(self, args, previous, after): arg_position = position_between(self.lcode, previous, after) args.first_line, args.first_col = arg_position[0] args.uid = args.last_line, args.last_col = arg_position[1] @visit_expr def visit_Lambda(self, node): copy_info(node, node.body) position = inc_tuple((node.body.first_line, node.body.first_col)) node.uid, before_colon = self.operators[':'].find_previous(position) after_lambda, first = self.operators['lambda'].find_previous(position) node.first_line, node.first_col = first self.update_arguments(node.args, after_lambda, before_colon) node.op_pos = [ NodeWithPosition(after_lambda, first), NodeWithPosition(node.uid, before_colon), ] @visit_all def visit_arg(self, node): nnode = self.dnode(node) node.op_pos = [] if node.annotation: copy_info(node, node.annotation) position = (node.first_line, node.first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) else: node.last_line = nnode.lineno node.last_col = nnode.col_offset + len(node.arg) node.first_line, node.first_col = nnode.lineno, nnode.col_offset node.uid = (node.last_line, node.last_col) def find_next_comma(self, node, sub): """Find comma after sub andd add NodeWithPosition in node""" position = (sub.last_line, sub.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_arguments(self, node): node.op_pos = [] if hasattr(node, 'kwonlyargs'): # Python 3 node.vararg_node = node.vararg node.kwarg_node = node.kwarg else: set_max_position(node) for arg in node.args: min_first_max_last(node, arg) node.vararg_node = None node.kwarg_node = None position = (node.first_line, node.first_col) if node.vararg: last, first = self.names[node.vararg].find_next(position) node.vararg_node = NodeWithPosition(last, first) if node.kwarg: last, first = self.names[node.kwarg].find_next(position) node.kwarg_node = NodeWithPosition(last, first) set_max_position(node) for arg in node.args: min_first_max_last(node, arg) for arg in node.defaults: min_first_max_last(node, arg) # Positional args / defaults pos_args = node.args[:-len(node.defaults) or None] self.comma_separated_list(node, pos_args) for arg, default in zip(node.args[len(pos_args):], node.defaults): position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, default) # *args if node.vararg_node: min_first_max_last(node, node.vararg_node) position = (node.vararg_node.first_line, node.vararg_node.first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.vararg_node) # **kwargs if node.kwarg_node: min_first_max_last(node, node.kwarg_node) position = (node.kwarg_node.first_line, node.kwarg_node.first_col) last, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.kwarg_node) if hasattr(node, 'kwonlyargs'): # Python 3 if node.kwonlyargs and not node.vararg: position = (node.kwonlyargs[0].first_line, node.kwonlyargs[0].first_col) last, first = self.operators['*'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, node.op_pos[-1]) for arg, default in zip(node.kwonlyargs, node.kw_defaults): min_first_max_last(node, arg) last_node = arg if default: min_first_max_last(node, default) last_node = default position = (arg.last_line, arg.last_col) first, last = find_next_equal(self.lcode, position) node.op_pos.append(NodeWithPosition(last, first)) self.find_next_comma(node, last_node) node.uid = (node.last_line, node.last_col) @visit_expr def visit_UnaryOp(self, node): # Cannot set to the unaryop node as they are singletons node.op_pos = [self.calculate_unaryop(node.op, node.operand)] copy_info(node, node.op_pos[0]) min_first_max_last(node, node.operand) @visit_expr def visit_BinOp(self, node): set_max_position(node) min_first_max_last(node, node.left) min_first_max_last(node, node.right) node.op_pos = [self.calculate_infixop(node.op, node.left, node.right)] node.uid = node.op_pos[0].uid @visit_expr def visit_BoolOp(self, node): node.op_pos = [] set_max_position(node) previous = None for value in node.values: # Cannot set to the boolop nodes as they are singletons if previous: node.op_pos.append( self.calculate_infixop(node.op, previous, value) ) min_first_max_last(node, value) previous = value node.uid = node.last_line, node.last_col @visit_expr def visit_Starred(self, node): """ Python 3 """ position = (node.value.first_line, node.value.first_col + 1) r_set_pos(node, *self.operators['*'].find_previous(position)) last = node.value node.last_line, node.last_col = last.last_line, last.last_col node.op_pos = [ NodeWithPosition(node.uid, dec_tuple(node.uid)) ] @visit_expr def visit_NameConstant(self, node): """ Python 3 """ nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, str(node.value), self.bytes_pos_to_utf8, to=node) @visit_expr def visit_Bytes(self, node): position = self.dposition(node) r_set_pos(node, *self.strings.find_next(position)) @visit_expr def visit_YieldFrom(self, node): copy_info(node, node.value) position = self.dposition(node) node.uid, first = self.operators['yield from'].find_next(position) node.first_line, node.first_col = first node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] @visit_stmt def visit_Pass(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'pass', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Break(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( node, 'break', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Continue(self, node): nnode = self.dnode(node) copy_from_lineno_col_offset( nnode, 'continue', self.bytes_pos_to_utf8, to=node) @visit_stmt def visit_Expr(self, node): copy_info(node, node.value) @visit_stmt def visit_Nonlocal(self, node): keyword_followed_by_ids(node, self.operators['nonlocal'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Global(self, node, op='global'): keyword_followed_by_ids(node, self.operators['global'], self.names, node.names, self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.ids_pos) @visit_stmt def visit_Exec(self, node): copy_info(node, node.body) start_by_keyword(node, self.operators['exec'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.globals: position = self.dposition(node.globals) last, first = self.operators['in'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.globals) if node.locals: position = self.dposition(node.locals) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) min_first_max_last(node, node.locals) def process_alias(self, position, alias): alias.op_pos = [] splitted = alias.name.split('.') first = None for subname in splitted: names = self.names if subname != '*' else self.operators last, p1 = names[subname].find_next(position) if not first: first = p1 if alias.asname: last, _ = self.names[alias.asname].find_next(last) alast, afirst = self.operators["as"].find_previous(last) alias.op_pos.append(NodeWithPosition(alast, afirst)) alias.first_line, alias.first_col = first alias.uid = alias.last_line, alias.last_col = last return last @visit_stmt def visit_ImportFrom(self, node): start_by_keyword(node, self.operators['from'], self.bytes_pos_to_utf8) last = node.uid last, first = self.operators['import'].find_next(last) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), NodeWithPosition(last, first), ] for alias in node.names: last = self.process_alias(last, alias) par = find_next_parenthesis(self.lcode, last, self.parenthesis) if par: last = par node.last_line, node.last_col = last @visit_stmt def visit_Import(self, node): start_by_keyword(node, self.operators['import'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] last = node.uid for alias in node.names: last = self.process_alias(last, alias) node.last_line, node.last_col = last @visit_stmt def visit_Assert(self, node): copy_info(node, node.test) start_by_keyword(node, self.operators['assert'], self.bytes_pos_to_utf8, set_last=False) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if node.msg: min_first_max_last(node, node.msg) position = self.dposition(node.msg) last, first = self.operators[','].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryFinally(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) min_first_max_last(node, node.finalbody[-1]) position = node.uid last, _ = self.operators[':'].find_next(position) body = node.body if len(body) == 1 and isinstance(body[0], ast.TryExcept): node.skip_try = True node.op_pos = [] else: node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_TryExcept(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_all def visit_ExceptHandler(self, node): start_by_keyword(node, self.operators['except'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) self.uid_something_colon(node) node.name_node = node.name node_position = (node.first_line, node.first_col) if only_python3 and node.name: last, first = self.names[node.name].find_next(node_position) node.name_node = NodeWithPosition(last, first) if node.name_node: position = (node.name_node.first_line, node.name_node.first_col) first = None if 'as' in self.operators: last, first = self.operators["as"].find_previous(position) if not first: last, first = self.operators[","].find_previous(position) if first and first > node_position: node.op_pos.insert(1, NodeWithPosition(last, first)) @visit_stmt def visit_Try(self, node): start_by_keyword(node, self.operators['try'], self.bytes_pos_to_utf8) position = node.uid last, _ = self.operators[':'].find_next(position) node.op_pos = [ NodeWithPosition(last, self.dposition(node)), ] last_body = node.body for handler in node.handlers: min_first_max_last(node, handler) if node.orelse: min_first_max_last(node, node.orelse[-1]) position = self.dposition(node.orelse[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['else'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) if node.finalbody: min_first_max_last(node, node.finalbody[-1]) position = self.dposition(node.finalbody[0]) last, _ = self.operators[':'].find_previous(position) _, first = self.operators['finally'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_Raise(self, node): start_by_keyword(node, self.operators['raise'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, self.dposition(node)), ] if 'type' in dir(node): # Python 2 children = [node.type, node.inst, node.tback] for child in children: if not child: continue min_first_max_last(node, child) position = (child.last_line, child.last_col) first, last = find_next_comma(self.lcode, position) if first: # comma exists node.op_pos.append(NodeWithPosition(last, first)) else: # Python 3 children = [node.exc, node.cause] for child in children: if not child: continue min_first_max_last(node, child) if node.cause: position = self.dposition(node.cause) last, first = self.operators['from'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_With(self, node, keyword='with'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['with'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] skip_colon = False if hasattr(node, 'optional_vars'): # Python 2 last_node = node.context_expr if node.optional_vars: var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) last_node = var if len(node.body) == 1 and isinstance(node.body[0], ast.With): position = (last_node.last_line, last_node.last_col) last, first = self.operators[','].find_next(position) if first: node.body[0].op_pos[0] = NodeWithPosition(last, first) skip_colon = True else: self.comma_separated_list(node, node.items) if not skip_colon: position = (node.body[0].first_line, node.body[0].first_col) last, first = self.operators[':'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_AsyncWith(self, node): """ Python 3.5 """ self.visit_With(node, keyword='async') @visit_all def visit_withitem(self, node): copy_info(node, node.context_expr) node.op_pos = [] if node.optional_vars: min_first_max_last(node, node.optional_vars) var = node.optional_vars position = (var.first_line, var.first_col) last, first = self.operators['as'].find_previous(position) node.op_pos.append(NodeWithPosition(last, first)) @visit_stmt def visit_If(self, node): start_by_keyword(node, self.operators['if'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_While(self, node): start_by_keyword(node, self.operators['while'], self.bytes_pos_to_utf8) min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) self.optional_else(node, last) @visit_stmt def visit_For(self, node, keyword='for'): start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['for'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first min_first_max_last(node, node.body[-1]) last = self.uid_something_colon(node) position = (node.iter.first_line, node.iter.first_col) last, first = self.operators['in'].find_previous(position) node.op_pos.insert(1, NodeWithPosition(last, first)) self.optional_else(node, last) @visit_stmt def visit_AsyncFor(self, node): """ Python 3.5 """ self.visit_For(node, keyword='async') @visit_stmt @visit_stmt def visit_AugAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.value) node.op_pos = [self.calculate_infixop(node.op, node.target, node.value)] node.uid = node.op_pos[0].uid @visit_stmt def visit_AnnAssign(self, node): set_max_position(node) min_first_max_last(node, node.target) min_first_max_last(node, node.annotation) node.op_pos = [] node.op_pos.append( self.calculate_infixop(node, node.target, node.annotation) ) if node.value: min_first_max_last(node, node.value) node.op_pos.append( self.calculate_infixop(node, node.annotation, node.value) ) node.uid = node.op_pos[0].uid @visit_stmt def visit_Assign(self, node): node.op_pos = [] set_max_position(node) min_first_max_last(node, node.value) last = node.value for i, target in reversed(list(enumerate(node.targets))): node.op_pos.append( self.calculate_infixop(node, target, last) ) min_first_max_last(node, target) last = target node.op_pos = list(reversed(node.op_pos)) node.uid = node.last_line, node.last_col @visit_stmt def visit_Delete(self, node): start_by_keyword(node, self.operators['del'], self.bytes_pos_to_utf8) for target in node.targets: min_first_max_last(node, target) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] self.comma_separated_list(node, node.targets) @visit_stmt def visit_Return(self, node): start_by_keyword(node, self.operators['return'], self.bytes_pos_to_utf8) node.op_pos = [ NodeWithPosition(node.uid, (node.first_line, node.first_col)) ] if node.value: min_first_max_last(node, node.value) def adjust_decorator(self, node, dec): position = dec.first_line, dec.first_col last, first = self.operators['@'].find_previous(position) if (node.first_line, node.first_col) == position: node.first_line, node.first_col = first node.op_pos.insert(-2, NodeWithPosition(last, first)) @visit_stmt def visit_ClassDef(self, node): start_by_keyword(node, self.operators['class'], self.bytes_pos_to_utf8) self.uid_something_colon(node) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) position = (node.first_line, node.first_col) last, first = self.names[node.name].find_next(position) node.name_node = NodeWithPosition(last, first) len_keywords = len(getattr(node, "keywords", [])) if len(node.bases) == 1 and len_keywords == 0: increment_node_position(self.lcode, node.bases[0]) @visit_all def visit_keyword(self, node): copy_info(node, node.value) node.op_pos = [] position = (node.first_line, node.first_col + 1) if node.arg: node.uid, first = self.operators['='].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) _, first = self.names[node.arg].find_previous(first) else: node.uid, first = self.operators['**'].find_previous(position) node.op_pos.append(NodeWithPosition(node.uid, first)) node.first_line, node.first_col = first @visit_stmt def visit_FunctionDef(self, node, keyword='def'): lineno, col_offset = node.lineno, node.col_offset for dec in node.decorator_list: node.lineno = max(node.lineno, dec.last_line + 1) start_by_keyword(node, self.operators[keyword], self.bytes_pos_to_utf8) first = node.first_line, node.first_col start_by_keyword(node, self.operators['def'], self.bytes_pos_to_utf8) node.first_line, node.first_col = first self.uid_something_colon(node) previous, last = self.parenthesis.find_next(node.uid) self.update_arguments(node.args, inc_tuple(previous), dec_tuple(last)) for dec in node.decorator_list: min_first_max_last(node, dec) self.adjust_decorator(node, dec) min_first_max_last(node, node.body[-1]) node.lineno = lineno last, first = self.names[node.name].find_next(first) node.name_node = NodeWithPosition(last, first) first, last = self.parenthesis.find_next(first) node.op_pos.insert(-1, NodeWithPosition(inc_tuple(first), first)) node.op_pos.insert(-1, NodeWithPosition(last, dec_tuple(last))) if hasattr(node, 'returns') and node.returns: # Python 3 last, first = self.operators['->'].find_next(last) node.op_pos.insert(-1, NodeWithPosition(last, first)) @visit_stmt def visit_AsyncFunctionDef(self, node): """ Python 3.5 """ self.visit_FunctionDef(node, keyword='async') @visit_mod def visit_Module(self, node): set_max_position(node) for stmt in node.body: min_first_max_last(node, stmt) if node.first_line == float('inf'): node.first_line, node.first_col = 0, 0 node.last_line, node.last_col = 0, 0 node.uid = node.last_line, node.last_col @visit_mod def visit_Interactive(self, node): self.visit_Module(node) @visit_mod def visit_Expression(self, node): copy_info(node, node.body)
JoaoFelipe/pyposast
setup.py
get_version
python
def get_version(): proc = subprocess.Popen( ("git", "describe", "--tag", "--always"), stdout=subprocess.PIPE, stderr=subprocess.STDOUT ) output, _ = proc.communicate() result = output.decode("utf-8").strip() if proc.returncode != 0: sys.stderr.write( ">>> Git Describe Error:\n " + result ) return "1+unknown" split = result.split("-", 1) version = "+".join(split).replace("-", ".") if len(split) > 1: sys.stderr.write( ">>> Please verify the commit tag:\n " + version + "\n" ) return version
Use git describe to get version from tag
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/setup.py#L6-L28
null
#!/usr/bin/env python import subprocess import sys from setuptools import setup, find_packages try: import pypandoc long_description = pypandoc.convert('README.md', 'rst') except (IOError, ImportError): sys.stderr.write( ">>> Please verify the pypandoc installation.\n" ) long_description = "Extends Python ast nodes with positional informations" setup( name="PyPosAST", version=get_version(), description="Extends Python ast nodes with positional informations", long_description=long_description, packages=find_packages(exclude=["tests_*", "tests"]), author=("Joao Pimentel",), author_email="joaofelipenp@gmail.com", license="MIT", keywords="ast python position offset", url="https://github.com/JoaoFelipe/PyPosAST", )
JoaoFelipe/pyposast
pyposast/utils.py
find_next_character
python
def find_next_character(code, position, char): end = LineCol(code, *position) while not end.eof and end.char() in WHITESPACE: end.inc() if not end.eof and end.char() == char: return end.tuple(), inc_tuple(end.tuple()) return None, None
Find next char and return its first and last positions
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/utils.py#L132-L140
[ "def inc_tuple(tup):\n return (tup[0], tup[1] + 1)\n", "def char(self):\n try:\n return self.code[self.line - 1][self.col]\n except IndexError as e:\n raise IndexError(\n str(e) +\n (\": self.code[self.line - 1][self.col] with \\n\"\n \"self.line = {}; self.col = {}; len(self.code) = {}\")\n .format(self.line, self.col, len(self.code)))\n" ]
# Copyright (c) 2015 Universidade Federal Fluminense (UFF) # This file is part of PyPosAST. # Please, consult the license terms in the LICENSE file. from __future__ import (absolute_import, division) from .constants import WHITESPACE def pairwise(iterable): it = iter(iterable) a = next(it) for b in it: yield (a, b) a = b def inc_tuple(tup): return (tup[0], tup[1] + 1) def dec_tuple(tup): return (tup[0], tup[1] - 1) class LineCol(object): def __init__(self, code, line, col): self.code = code self.line, self.col = line, col self.adjust() def char(self): try: return self.code[self.line - 1][self.col] except IndexError as e: raise IndexError( str(e) + (": self.code[self.line - 1][self.col] with \n" "self.line = {}; self.col = {}; len(self.code) = {}") .format(self.line, self.col, len(self.code))) def inc(self): self.col += 1 while len(self.code[self.line - 1]) == self.col and not self.eof: self.col = 0 self.line += 1 def dec(self): self.col -= 1 while self.col == -1 and not self.bof: self.col = len(self.code[self.line - 2]) - 1 self.line -= 1 def adjust(self): while len(self.code[self.line - 1]) == self.col and not self.eof: self.col = 0 self.line += 1 while self.col == -1 and not self.bof: self.col = len(self.code[self.line - 2]) - 1 self.line -= 1 @property def eof(self): return self.line >= len(self.code) and self.col >= len(self.code[-1]) @property def bof(self): return self.line <= 0 and self.col <= 0 def tuple(self): return (self.line, self.col) def __lt__(self, other): return self.tuple() < other.tuple() def __eq__(self, other): return self.tuple() == other.tuple() def __repr__(self): return str(self.tuple()) def find_in_between(position, elements): try: p1, p2 = elements.find_previous(position) except IndexError: return None, None if not p1 < position < p2: return None, None return p1, p2 def position_between(code, position1, position2): if position1 > position2: position1, position2 = position2, position1 p1, p2 = LineCol(code, *position1), LineCol(code, *position2) start = LineCol(code, *position1) while start < p2 and start.char() in WHITESPACE: start.inc() end = LineCol(code, *dec_tuple(position2)) while end > p1 and end.char() in WHITESPACE: end.dec() if end > p1: end.inc() if end == start: return position1, position2 if start > end: tup = start.tuple() return tup, tup return start.tuple(), end.tuple() def find_next_parenthesis(code, position, parenthesis): p1, p2 = find_in_between(position, parenthesis) if not p1: return p2 = LineCol(code, *dec_tuple(p2)) end = LineCol(code, *position) while end < p2 and not end.eof and end.char() in WHITESPACE: end.inc() if end == p2: return inc_tuple(end.tuple()) return def find_next_comma(code, position): """Find next comman and return its first and last positions""" return find_next_character(code, position, ',') def find_next_colon(code, position): """Find next colon and return its first and last positions""" return find_next_character(code, position, ':') def find_next_equal(code, position): """Find next equal sign and return its first and last positions""" return find_next_character(code, position, '=') def extract_positions(utf8): j = 0 utf8_pos_to_bytes = {} bytes_pos_to_utf8 = {} for i, c in enumerate(utf8): utf8_pos_to_bytes[i] = j bytes_pos_to_utf8[j] = i j += len(c.encode("utf-8")) return utf8_pos_to_bytes, bytes_pos_to_utf8
JoaoFelipe/pyposast
pyposast/cross_version.py
native_decode_source
python
def native_decode_source(text): if ((only_python3 and isinstance(text, bytes)) or (only_python2 and isinstance(text, str))): text = decode_source_to_unicode(text) if only_python2: return text.encode('ascii', 'replace') return text
Use codec specified in file to decode to unicode Then, encode unicode to native str: Python 2: bytes Python 3: unicode
train
https://github.com/JoaoFelipe/pyposast/blob/497c88c66b451ff2cd7354be1af070c92e119f41/pyposast/cross_version.py#L136-L147
[ "def decode_source_to_unicode(source_bytes):\n encoding = detect_encoding(readlines(source_bytes.splitlines(True)))\n return source_bytes.decode(encoding[0], 'replace')\n" ]
# Copyright (c) 2016 Universidade Federal Fluminense (UFF) # This file is part of PyPosAST. # Please, consult the license terms in the LICENSE file. import sys try: from cStringIO import StringIO except ImportError: from io import StringIO class SelectVersion(object): def __init__(self, compare_func): self.compare_func = compare_func def __call__(self, fn): def inner(*args, **kwargs): if self.compare_func(sys.version_info): return fn(*args, **kwargs) return None return inner def __bool__(self): return self.compare_func(sys.version_info) def __nonzero__(self): return self.__bool__() try: iter([]).next except AttributeError: def iternext(seq): """Get the `next` function for iterating over `seq`.""" return iter(seq).__next__ else: def iternext(seq): """Get the `next` function for iterating over `seq`.""" return iter(seq).next only_python2 = SelectVersion(lambda x: x < (3, 0)) only_python3 = SelectVersion(lambda x: x >= (3, 0)) only_python35 = SelectVersion(lambda x: x >= (3, 5)) only_python36 = SelectVersion(lambda x: x >= (3, 6)) if only_python3: from tokenize import detect_encoding readlines = lambda seq: iter(seq).__next__ if only_python2: import re from codecs import lookup, BOM_UTF8 cookie_re = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)', re.L) blank_re = re.compile(br'^[ \t\f]*(?:[#\r\n]|$)', re.L) def _get_normal_name(orig_enc): """Extracted from Python 3.5.0/Lib/tokenize.py for compability""" # Only care about the first 12 characters. enc = orig_enc[:12].lower().replace("_", "-") if enc == "utf-8" or enc.startswith("utf-8-"): return "utf-8" if enc in ("latin-1", "iso-8859-1", "iso-latin-1") or \ enc.startswith(("latin-1-", "iso-8859-1-", "iso-latin-1-")): return "iso-8859-1" return orig_enc def detect_encoding(readline): """Extracted from Python 3.5.0/Lib/tokenize.py for compability""" bom_found = False encoding = None default = 'ascii' def read_or_stop(): try: return readline() except StopIteration: return b'' def find_cookie(line): try: line_string = line.decode('ascii') except UnicodeDecodeError: return None match = cookie_re.match(line_string) if not match: return None encoding = _get_normal_name(match.group(1)) try: lookup(encoding) except LookupError: # This behaviour mimics the Python interpreter raise SyntaxError("unknown encoding: " + encoding) if bom_found: if encoding != 'utf-8': # This behavior mimics the Python interpreter raise SyntaxError('encoding problem: utf-8') encoding += '-sig' return encoding first = read_or_stop() if first.startswith(BOM_UTF8): bom_found = True first = first[3:] default = 'utf-8-sig' if not first: return default, [] encoding = find_cookie(first) if encoding: return encoding, [first] if not blank_re.match(first): return default, [first] second = read_or_stop() if not second: return default, [first] encoding = find_cookie(second) if encoding: return encoding, [first, second] return default, [first, second] readlines = lambda seq: iter(seq).next def decode_source_to_unicode(source_bytes): encoding = detect_encoding(readlines(source_bytes.splitlines(True))) return source_bytes.decode(encoding[0], 'replace')
anlutro/russell
russell/content.py
Entry.from_string
python
def from_string(cls, contents, **kwargs): lines = contents.splitlines() title = None description = None line = lines.pop(0) while line != '': if not title and line.startswith('#'): title = line[1:].strip() elif line.startswith('title:'): title = line[6:].strip() elif line.startswith('description:'): description = line[12:].strip() elif line.startswith('subtitle:'): kwargs['subtitle'] = line[9:].strip() elif line.startswith('comments:'): try: kwargs['allow_comments'] = _str_to_bool(line[9:]) except ValueError: LOG.warning('invalid boolean value for comments', exc_info=True) cls.process_meta(line, kwargs) line = lines.pop(0) # the only lines left should be the actual contents body = '\n'.join(lines).strip() excerpt = _get_excerpt(body) if description is None: description = _get_description(excerpt, 160) if issubclass(cls, Post): kwargs['excerpt'] = render_markdown(excerpt) body = render_markdown(body) return cls(title=title, body=body, description=description, **kwargs)
Given a markdown string, create an Entry object. Usually subclasses will want to customize the parts of the markdown where you provide values for attributes like public - this can be done by overriding the process_meta method.
train
https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/content.py#L107-L148
[ "def render_markdown(md):\n\textensions = ['markdown.extensions.fenced_code']\n\treturn markdown.markdown(md, extensions=extensions)\n", "def _get_excerpt(body):\n\texcerpt_parts = []\n\t# iterate through lines until we find an empty line, which would indicate\n\t# two newlines in a row\n\tfor line in body.splitlines():\n\t\tif line == '':\n\t\t\tbreak\n\t\texcerpt_parts.append(line)\n\treturn ' '.join(excerpt_parts)\n", "def _get_description(body, max_chars, search='. '):\n\tstop_idx = body.rfind(search, 0, max_chars)\n\tif stop_idx == -1 or stop_idx < (max_chars / 2):\n\t\tstop_idx = body.find(search, max_chars)\n\tif stop_idx == -1:\n\t\treturn body\n\treturn body[0:stop_idx+1]\n", "def process_meta(cls, line, kwargs):\n\tsuper().process_meta(line, kwargs)\n\n\tif line.startswith('pubdate:'):\n\t\tpubdate_str = line[8:].strip()\n\t\ttry:\n\t\t\tkwargs['pubdate'] = dateutil.parser.parse(pubdate_str)\n\t\texcept ValueError:\n\t\t\tLOG.warning('invalid pubdate given', exc_info=True)\n\t\tif 'pubdate' in kwargs and not kwargs['pubdate'].tzinfo:\n\t\t\tkwargs['pubdate'] = kwargs['pubdate'].replace(tzinfo=SYSTEM_TZINFO)\n\t\t\tLOG.warning('found pubdate without timezone: %r - using %r',\n\t\t\t\tpubdate_str, SYSTEM_TZINFO)\n\n\telif line.startswith('tags:'):\n\t\tline_tags = line[5:].strip().split(',')\n\t\tkwargs['tags'] = [cls.make_tag(tag) for tag in line_tags if tag]\n" ]
class Entry(Content): """ Abstract class for text content. """ def __init__(self, title, body, slug=None, subtitle=None, description=None, public=True): """ Constructor. Args: title (str): Title. body (str): Markdown body of the entry. slug (str): Optional slug for the entry. If not provided, sulg will be guessed based on the title. subtitle (str): Optional subtitle. description (str): Optional description/excerpt. Mostly used for <meta> tags. public (bool): Whether the entry should be public or not. Usually this defines whether the entry shows up in the front page, archive pages etc., but even private entries are publicly accessable if you know the URL. """ self.title = title self.body = body self.slug = slug or slugify.slugify(title) self.subtitle = subtitle self.description = description self.public = public @property def url(self): return self.root_url + '/' + self.slug @classmethod @classmethod def process_meta(cls, line, kwargs): """ Process a line of metadata found in the markdown. Lines are usually in the format of "key: value". Modify the kwargs dict in order to change or add new kwargs that should be passed to the class's constructor. """ if line.startswith('slug:'): kwargs['slug'] = line[5:].strip() elif line.startswith('public:'): try: kwargs['public'] = _str_to_bool(line[7:]) except ValueError: LOG.warning('invalid boolean value for public', exc_info=True) elif line.startswith('private:'): try: kwargs['public'] = not _str_to_bool(line[8:]) except ValueError: LOG.warning('invalid boolean value for private', exc_info=True) @classmethod def from_file(cls, path, **kwargs): """ Given a markdown file, get an Entry object. """ LOG.debug('creating %s from "%s"', cls, path) # the filename will be the default slug - can be overridden later kwargs['slug'] = os.path.splitext(os.path.basename(path))[0] # TODO: ideally this should be part of the Post class. # if a pubdate isn't explicitly passed, get it from the file metadata # instead. note that it might still be overriden later on while reading # the file contents. if issubclass(cls, Post) and not kwargs.get('pubdate'): # you would think creation always comes before modification, but you # can manually modify a file's modification date to one earlier than # the creation date. this lets you set a post's pubdate by running # the command `touch`. we support this behaviour by simply finding # the chronologically earliest date of creation and modification. timestamp = min(os.path.getctime(path), os.path.getmtime(path)) kwargs['pubdate'] = datetime.fromtimestamp(timestamp) with open(path, 'r') as file: entry = cls.from_string(file.read(), **kwargs) return entry def __lt__(self, other): """ Implement "less than" comparisons to allow alphabetic sorting. """ return self.title < other.title
anlutro/russell
russell/content.py
Entry.process_meta
python
def process_meta(cls, line, kwargs): if line.startswith('slug:'): kwargs['slug'] = line[5:].strip() elif line.startswith('public:'): try: kwargs['public'] = _str_to_bool(line[7:]) except ValueError: LOG.warning('invalid boolean value for public', exc_info=True) elif line.startswith('private:'): try: kwargs['public'] = not _str_to_bool(line[8:]) except ValueError: LOG.warning('invalid boolean value for private', exc_info=True)
Process a line of metadata found in the markdown. Lines are usually in the format of "key: value". Modify the kwargs dict in order to change or add new kwargs that should be passed to the class's constructor.
train
https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/content.py#L151-L173
null
class Entry(Content): """ Abstract class for text content. """ def __init__(self, title, body, slug=None, subtitle=None, description=None, public=True): """ Constructor. Args: title (str): Title. body (str): Markdown body of the entry. slug (str): Optional slug for the entry. If not provided, sulg will be guessed based on the title. subtitle (str): Optional subtitle. description (str): Optional description/excerpt. Mostly used for <meta> tags. public (bool): Whether the entry should be public or not. Usually this defines whether the entry shows up in the front page, archive pages etc., but even private entries are publicly accessable if you know the URL. """ self.title = title self.body = body self.slug = slug or slugify.slugify(title) self.subtitle = subtitle self.description = description self.public = public @property def url(self): return self.root_url + '/' + self.slug @classmethod def from_string(cls, contents, **kwargs): """ Given a markdown string, create an Entry object. Usually subclasses will want to customize the parts of the markdown where you provide values for attributes like public - this can be done by overriding the process_meta method. """ lines = contents.splitlines() title = None description = None line = lines.pop(0) while line != '': if not title and line.startswith('#'): title = line[1:].strip() elif line.startswith('title:'): title = line[6:].strip() elif line.startswith('description:'): description = line[12:].strip() elif line.startswith('subtitle:'): kwargs['subtitle'] = line[9:].strip() elif line.startswith('comments:'): try: kwargs['allow_comments'] = _str_to_bool(line[9:]) except ValueError: LOG.warning('invalid boolean value for comments', exc_info=True) cls.process_meta(line, kwargs) line = lines.pop(0) # the only lines left should be the actual contents body = '\n'.join(lines).strip() excerpt = _get_excerpt(body) if description is None: description = _get_description(excerpt, 160) if issubclass(cls, Post): kwargs['excerpt'] = render_markdown(excerpt) body = render_markdown(body) return cls(title=title, body=body, description=description, **kwargs) @classmethod @classmethod def from_file(cls, path, **kwargs): """ Given a markdown file, get an Entry object. """ LOG.debug('creating %s from "%s"', cls, path) # the filename will be the default slug - can be overridden later kwargs['slug'] = os.path.splitext(os.path.basename(path))[0] # TODO: ideally this should be part of the Post class. # if a pubdate isn't explicitly passed, get it from the file metadata # instead. note that it might still be overriden later on while reading # the file contents. if issubclass(cls, Post) and not kwargs.get('pubdate'): # you would think creation always comes before modification, but you # can manually modify a file's modification date to one earlier than # the creation date. this lets you set a post's pubdate by running # the command `touch`. we support this behaviour by simply finding # the chronologically earliest date of creation and modification. timestamp = min(os.path.getctime(path), os.path.getmtime(path)) kwargs['pubdate'] = datetime.fromtimestamp(timestamp) with open(path, 'r') as file: entry = cls.from_string(file.read(), **kwargs) return entry def __lt__(self, other): """ Implement "less than" comparisons to allow alphabetic sorting. """ return self.title < other.title
anlutro/russell
russell/content.py
Entry.from_file
python
def from_file(cls, path, **kwargs): LOG.debug('creating %s from "%s"', cls, path) # the filename will be the default slug - can be overridden later kwargs['slug'] = os.path.splitext(os.path.basename(path))[0] # TODO: ideally this should be part of the Post class. # if a pubdate isn't explicitly passed, get it from the file metadata # instead. note that it might still be overriden later on while reading # the file contents. if issubclass(cls, Post) and not kwargs.get('pubdate'): # you would think creation always comes before modification, but you # can manually modify a file's modification date to one earlier than # the creation date. this lets you set a post's pubdate by running # the command `touch`. we support this behaviour by simply finding # the chronologically earliest date of creation and modification. timestamp = min(os.path.getctime(path), os.path.getmtime(path)) kwargs['pubdate'] = datetime.fromtimestamp(timestamp) with open(path, 'r') as file: entry = cls.from_string(file.read(), **kwargs) return entry
Given a markdown file, get an Entry object.
train
https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/content.py#L176-L201
null
class Entry(Content): """ Abstract class for text content. """ def __init__(self, title, body, slug=None, subtitle=None, description=None, public=True): """ Constructor. Args: title (str): Title. body (str): Markdown body of the entry. slug (str): Optional slug for the entry. If not provided, sulg will be guessed based on the title. subtitle (str): Optional subtitle. description (str): Optional description/excerpt. Mostly used for <meta> tags. public (bool): Whether the entry should be public or not. Usually this defines whether the entry shows up in the front page, archive pages etc., but even private entries are publicly accessable if you know the URL. """ self.title = title self.body = body self.slug = slug or slugify.slugify(title) self.subtitle = subtitle self.description = description self.public = public @property def url(self): return self.root_url + '/' + self.slug @classmethod def from_string(cls, contents, **kwargs): """ Given a markdown string, create an Entry object. Usually subclasses will want to customize the parts of the markdown where you provide values for attributes like public - this can be done by overriding the process_meta method. """ lines = contents.splitlines() title = None description = None line = lines.pop(0) while line != '': if not title and line.startswith('#'): title = line[1:].strip() elif line.startswith('title:'): title = line[6:].strip() elif line.startswith('description:'): description = line[12:].strip() elif line.startswith('subtitle:'): kwargs['subtitle'] = line[9:].strip() elif line.startswith('comments:'): try: kwargs['allow_comments'] = _str_to_bool(line[9:]) except ValueError: LOG.warning('invalid boolean value for comments', exc_info=True) cls.process_meta(line, kwargs) line = lines.pop(0) # the only lines left should be the actual contents body = '\n'.join(lines).strip() excerpt = _get_excerpt(body) if description is None: description = _get_description(excerpt, 160) if issubclass(cls, Post): kwargs['excerpt'] = render_markdown(excerpt) body = render_markdown(body) return cls(title=title, body=body, description=description, **kwargs) @classmethod def process_meta(cls, line, kwargs): """ Process a line of metadata found in the markdown. Lines are usually in the format of "key: value". Modify the kwargs dict in order to change or add new kwargs that should be passed to the class's constructor. """ if line.startswith('slug:'): kwargs['slug'] = line[5:].strip() elif line.startswith('public:'): try: kwargs['public'] = _str_to_bool(line[7:]) except ValueError: LOG.warning('invalid boolean value for public', exc_info=True) elif line.startswith('private:'): try: kwargs['public'] = not _str_to_bool(line[8:]) except ValueError: LOG.warning('invalid boolean value for private', exc_info=True) @classmethod def __lt__(self, other): """ Implement "less than" comparisons to allow alphabetic sorting. """ return self.title < other.title
anlutro/russell
russell/content.py
Post.make_tag
python
def make_tag(cls, tag_name): if cls.cm: return cls.cm.make_tag(tag_name) return Tag(tag_name.strip())
Make a Tag object from a tag name. Registers it with the content manager if possible.
train
https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/content.py#L244-L251
null
class Post(Entry): def __init__(self, *args, pubdate=None, excerpt=None, tags=None, allow_comments=True, **kwargs): """ Constructor. Also see Entry.__init__. Args: pubdate (datetime): When the post was published. excerpt (str): An excerpt of the post body. tags (list): A list of Tag objects associated with the post. allow_comments (bool): Whether to allow comments. Default False. """ super().__init__(*args, **kwargs) self.excerpt = excerpt or _get_excerpt(self.body) self.pubdate = pubdate self.tags = tags or [] self.allow_comments = allow_comments @classmethod @classmethod def process_meta(cls, line, kwargs): super().process_meta(line, kwargs) if line.startswith('pubdate:'): pubdate_str = line[8:].strip() try: kwargs['pubdate'] = dateutil.parser.parse(pubdate_str) except ValueError: LOG.warning('invalid pubdate given', exc_info=True) if 'pubdate' in kwargs and not kwargs['pubdate'].tzinfo: kwargs['pubdate'] = kwargs['pubdate'].replace(tzinfo=SYSTEM_TZINFO) LOG.warning('found pubdate without timezone: %r - using %r', pubdate_str, SYSTEM_TZINFO) elif line.startswith('tags:'): line_tags = line[5:].strip().split(',') kwargs['tags'] = [cls.make_tag(tag) for tag in line_tags if tag] @property def url(self): return '%s/posts/%s' % (self.root_url, self.slug) @property def tag_links(self): """ Get a list of HTML links for all the tags associated with the post. """ return [ '<a href="%s">%s</a>' % (tag.url, tag.title) for tag in self.tags ] def __lt__(self, other): """ Implement comparison/sorting that takes pubdate into consideration. """ if self.pubdate == other.pubdate: return super().__lt__(other) return self.pubdate > other.pubdate
anlutro/russell
russell/engine.py
make_link
python
def make_link(title, url, blank=False): attrs = 'href="%s"' % url if blank: attrs += ' target="_blank" rel="noopener noreferrer"' return '<a %s>%s</a>' % (attrs, title)
Make a HTML link out of an URL. Args: title (str): Text to show for the link. url (str): URL the link will point to. blank (bool): If True, appends target=_blank, noopener and noreferrer to the <a> element. Defaults to False.
train
https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L27-L40
null
from datetime import datetime import hashlib import logging import os import os.path import shutil import jinja2 import russell.content import russell.feed import russell.sitemap LOG = logging.getLogger(__name__) def _listfiles(root_dir): results = set() for root, _, files in os.walk(root_dir): for file in files: results.add(os.path.join(root, file)) return results class BlogEngine: """ The main instance that contains blog configuration and content, as well as generating end results. """ def __init__(self, root_path, root_url, site_title, site_desc=None): """ Constructor. Args: root_path (str): Full path to the directory which contains the posts, pages, templates etc. directories. root_url (str): The root URL of your website. site_title (str): The title of your website. site_desc (str): A subtitle or description of your website. """ self.root_path = root_path self.root_url = root_url self.site_title = site_title self.site_desc = site_desc self.cm = russell.content.ContentManager(root_url) #pylint: disable=invalid-name self.pages = self.cm.pages self.posts = self.cm.posts self.tags = self.cm.tags self.asset_hash = {} self.jinja = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.join(root_path, 'templates')), ) self.jinja.globals.update({ 'a': make_link, 'asset_hash': self.asset_hash, 'asset_url': self.get_asset_url, 'now': datetime.now(), 'root_url': self.root_url, 'site_description': self.site_desc, 'site_title': self.site_title, 'tags': self.tags, }) def get_asset_url(self, path): """ Get the URL of an asset. If asset hashes are added and one exists for the path, it will be appended as a query string. Args: path (str): Path to the file, relative to your "assets" directory. """ url = self.root_url + '/assets/' + path if path in self.asset_hash: url += '?' + self.asset_hash[path] return url def add_pages(self, path='pages'): """ Look through a directory for markdown files and add them as pages. """ pages_path = os.path.join(self.root_path, path) pages = [] for file in _listfiles(pages_path): page_dir = os.path.relpath(os.path.dirname(file), pages_path) if page_dir == '.': page_dir = None pages.append(self.cm.Page.from_file(file, directory=page_dir)) self.cm.add_pages(pages) def add_posts(self, path='posts'): """ Look through a directory for markdown files and add them as posts. """ path = os.path.join(self.root_path, path) self.cm.add_posts([ self.cm.Post.from_file(file) for file in _listfiles(path) ]) def copy_assets(self, path='assets'): """ Copy assets into the destination directory. """ path = os.path.join(self.root_path, path) for root, _, files in os.walk(path): for file in files: fullpath = os.path.join(root, file) relpath = os.path.relpath(fullpath, path) copy_to = os.path.join(self._get_dist_path(relpath, directory='assets')) LOG.debug('copying %r to %r', fullpath, copy_to) shutil.copyfile(fullpath, copy_to) def add_asset_hashes(self, path='dist/assets'): """ Scan through a directory and add hashes for each file found. """ for fullpath in _listfiles(os.path.join(self.root_path, path)): relpath = fullpath.replace(self.root_path + '/' + path + '/', '') md5sum = hashlib.md5(open(fullpath, 'rb').read()).hexdigest() LOG.debug('MD5 of %s (%s): %s', fullpath, relpath, md5sum) self.asset_hash[relpath] = md5sum def get_posts(self, num=None, tag=None, private=False): """ Get all the posts added to the blog. Args: num (int): Optional. If provided, only return N posts (sorted by date, most recent first). tag (Tag): Optional. If provided, only return posts that have a specific tag. private (bool): By default (if False), private posts are not included. If set to True, private posts will also be included. """ posts = self.posts if not private: posts = [post for post in posts if post.public] if tag: posts = [post for post in posts if tag in post.tags] if num: return posts[:num] return posts def _get_dist_path(self, path, directory=None): if isinstance(path, str): path = [path] if directory: path.insert(0, directory) return os.path.join(self.root_path, 'dist', *path) def _get_template(self, template): if isinstance(template, str): template = self.jinja.get_template(template) return template def generate_pages(self): """ Generate HTML out of the pages added to the blog. """ for page in self.pages: self.generate_page(page.slug, template='page.html.jinja', page=page) def generate_posts(self): """ Generate single-post HTML files out of posts added to the blog. Will not generate front page, archives or tag files - those have to be generated separately. """ for post in self.posts: self.generate_page( ['posts', post.slug], template='post.html.jinja', post=post, ) def generate_tags(self): """ Generate one HTML page for each tag, each containing all posts that match that tag. """ for tag in self.tags: posts = self.get_posts(tag=tag, private=True) self.generate_page(['tags', tag.slug], template='archive.html.jinja', posts=posts) def generate_page(self, path, template, **kwargs): """ Generate the HTML for a single page. You usually don't need to call this method manually, it is used by a lot of other, more end-user friendly methods. Args: path (str): Where to place the page relative to the root URL. Usually something like "index", "about-me", "projects/example", etc. template (str): Which jinja template to use to render the page. **kwargs: Kwargs will be passed on to the jinja template. Also, if the `page` kwarg is passed, its directory attribute will be prepended to the path. """ directory = None if kwargs.get('page'): directory = kwargs['page'].dir path = self._get_dist_path(path, directory=directory) if not path.endswith('.html'): path = path + '.html' if not os.path.isdir(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) html = self._get_template(template).render(**kwargs) with open(path, 'w+') as file: file.write(html) def generate_index(self, num_posts=5): """ Generate the front page, aka index.html. """ posts = self.get_posts(num=num_posts) self.generate_page('index', template='index.html.jinja', posts=posts) def generate_archive(self): """ Generate the archive HTML page. """ self.generate_page('archive', template='archive.html.jinja', posts=self.get_posts()) def generate_rss(self, path='rss.xml', only_excerpt=True, https=False): """ Generate the RSS feed. Args: path (str): Where to save the RSS file. Make sure that your jinja templates refer to the same path using <link>. only_excerpt (bool): If True (the default), don't include the full body of posts in the RSS. Instead, include the first paragraph and a "read more" link to your website. https (bool): If True, links inside the RSS with relative scheme (e.g. //example.com/something) will be set to HTTPS. If False (the default), they will be set to plain HTTP. """ feed = russell.feed.get_rss_feed(self, only_excerpt=only_excerpt, https=https) feed.rss_file(self._get_dist_path(path)) def generate_sitemap(self, path='sitemap.xml', https=False): """ Generate an XML sitemap. Args: path (str): The name of the file to write to. https (bool): If True, links inside the sitemap with relative scheme (e.g. example.com/something) will be set to HTTPS. If False (the default), they will be set to plain HTTP. """ sitemap = russell.sitemap.generate_sitemap(self, https=https) self.write_file(path, sitemap) def write_file(self, path, contents): """ Write a file of any type to the destination path. Useful for files like robots.txt, manifest.json, and so on. Args: path (str): The name of the file to write to. contents (str or bytes): The contents to write. """ path = self._get_dist_path(path) if not os.path.isdir(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) if isinstance(contents, bytes): mode = 'wb+' else: mode = 'w' with open(path, mode) as file: file.write(contents)
anlutro/russell
russell/engine.py
BlogEngine.get_asset_url
python
def get_asset_url(self, path): url = self.root_url + '/assets/' + path if path in self.asset_hash: url += '?' + self.asset_hash[path] return url
Get the URL of an asset. If asset hashes are added and one exists for the path, it will be appended as a query string. Args: path (str): Path to the file, relative to your "assets" directory.
train
https://github.com/anlutro/russell/blob/6e4a95929f031926d3acd5d9e6c9ca7bb896b1b5/russell/engine.py#L85-L96
null
class BlogEngine: """ The main instance that contains blog configuration and content, as well as generating end results. """ def __init__(self, root_path, root_url, site_title, site_desc=None): """ Constructor. Args: root_path (str): Full path to the directory which contains the posts, pages, templates etc. directories. root_url (str): The root URL of your website. site_title (str): The title of your website. site_desc (str): A subtitle or description of your website. """ self.root_path = root_path self.root_url = root_url self.site_title = site_title self.site_desc = site_desc self.cm = russell.content.ContentManager(root_url) #pylint: disable=invalid-name self.pages = self.cm.pages self.posts = self.cm.posts self.tags = self.cm.tags self.asset_hash = {} self.jinja = jinja2.Environment( loader=jinja2.FileSystemLoader(os.path.join(root_path, 'templates')), ) self.jinja.globals.update({ 'a': make_link, 'asset_hash': self.asset_hash, 'asset_url': self.get_asset_url, 'now': datetime.now(), 'root_url': self.root_url, 'site_description': self.site_desc, 'site_title': self.site_title, 'tags': self.tags, }) def add_pages(self, path='pages'): """ Look through a directory for markdown files and add them as pages. """ pages_path = os.path.join(self.root_path, path) pages = [] for file in _listfiles(pages_path): page_dir = os.path.relpath(os.path.dirname(file), pages_path) if page_dir == '.': page_dir = None pages.append(self.cm.Page.from_file(file, directory=page_dir)) self.cm.add_pages(pages) def add_posts(self, path='posts'): """ Look through a directory for markdown files and add them as posts. """ path = os.path.join(self.root_path, path) self.cm.add_posts([ self.cm.Post.from_file(file) for file in _listfiles(path) ]) def copy_assets(self, path='assets'): """ Copy assets into the destination directory. """ path = os.path.join(self.root_path, path) for root, _, files in os.walk(path): for file in files: fullpath = os.path.join(root, file) relpath = os.path.relpath(fullpath, path) copy_to = os.path.join(self._get_dist_path(relpath, directory='assets')) LOG.debug('copying %r to %r', fullpath, copy_to) shutil.copyfile(fullpath, copy_to) def add_asset_hashes(self, path='dist/assets'): """ Scan through a directory and add hashes for each file found. """ for fullpath in _listfiles(os.path.join(self.root_path, path)): relpath = fullpath.replace(self.root_path + '/' + path + '/', '') md5sum = hashlib.md5(open(fullpath, 'rb').read()).hexdigest() LOG.debug('MD5 of %s (%s): %s', fullpath, relpath, md5sum) self.asset_hash[relpath] = md5sum def get_posts(self, num=None, tag=None, private=False): """ Get all the posts added to the blog. Args: num (int): Optional. If provided, only return N posts (sorted by date, most recent first). tag (Tag): Optional. If provided, only return posts that have a specific tag. private (bool): By default (if False), private posts are not included. If set to True, private posts will also be included. """ posts = self.posts if not private: posts = [post for post in posts if post.public] if tag: posts = [post for post in posts if tag in post.tags] if num: return posts[:num] return posts def _get_dist_path(self, path, directory=None): if isinstance(path, str): path = [path] if directory: path.insert(0, directory) return os.path.join(self.root_path, 'dist', *path) def _get_template(self, template): if isinstance(template, str): template = self.jinja.get_template(template) return template def generate_pages(self): """ Generate HTML out of the pages added to the blog. """ for page in self.pages: self.generate_page(page.slug, template='page.html.jinja', page=page) def generate_posts(self): """ Generate single-post HTML files out of posts added to the blog. Will not generate front page, archives or tag files - those have to be generated separately. """ for post in self.posts: self.generate_page( ['posts', post.slug], template='post.html.jinja', post=post, ) def generate_tags(self): """ Generate one HTML page for each tag, each containing all posts that match that tag. """ for tag in self.tags: posts = self.get_posts(tag=tag, private=True) self.generate_page(['tags', tag.slug], template='archive.html.jinja', posts=posts) def generate_page(self, path, template, **kwargs): """ Generate the HTML for a single page. You usually don't need to call this method manually, it is used by a lot of other, more end-user friendly methods. Args: path (str): Where to place the page relative to the root URL. Usually something like "index", "about-me", "projects/example", etc. template (str): Which jinja template to use to render the page. **kwargs: Kwargs will be passed on to the jinja template. Also, if the `page` kwarg is passed, its directory attribute will be prepended to the path. """ directory = None if kwargs.get('page'): directory = kwargs['page'].dir path = self._get_dist_path(path, directory=directory) if not path.endswith('.html'): path = path + '.html' if not os.path.isdir(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) html = self._get_template(template).render(**kwargs) with open(path, 'w+') as file: file.write(html) def generate_index(self, num_posts=5): """ Generate the front page, aka index.html. """ posts = self.get_posts(num=num_posts) self.generate_page('index', template='index.html.jinja', posts=posts) def generate_archive(self): """ Generate the archive HTML page. """ self.generate_page('archive', template='archive.html.jinja', posts=self.get_posts()) def generate_rss(self, path='rss.xml', only_excerpt=True, https=False): """ Generate the RSS feed. Args: path (str): Where to save the RSS file. Make sure that your jinja templates refer to the same path using <link>. only_excerpt (bool): If True (the default), don't include the full body of posts in the RSS. Instead, include the first paragraph and a "read more" link to your website. https (bool): If True, links inside the RSS with relative scheme (e.g. //example.com/something) will be set to HTTPS. If False (the default), they will be set to plain HTTP. """ feed = russell.feed.get_rss_feed(self, only_excerpt=only_excerpt, https=https) feed.rss_file(self._get_dist_path(path)) def generate_sitemap(self, path='sitemap.xml', https=False): """ Generate an XML sitemap. Args: path (str): The name of the file to write to. https (bool): If True, links inside the sitemap with relative scheme (e.g. example.com/something) will be set to HTTPS. If False (the default), they will be set to plain HTTP. """ sitemap = russell.sitemap.generate_sitemap(self, https=https) self.write_file(path, sitemap) def write_file(self, path, contents): """ Write a file of any type to the destination path. Useful for files like robots.txt, manifest.json, and so on. Args: path (str): The name of the file to write to. contents (str or bytes): The contents to write. """ path = self._get_dist_path(path) if not os.path.isdir(os.path.dirname(path)): os.makedirs(os.path.dirname(path)) if isinstance(contents, bytes): mode = 'wb+' else: mode = 'w' with open(path, mode) as file: file.write(contents)