Skip to content

Commit

Permalink
{Misc} Replace aliased errors with OSError
Browse files Browse the repository at this point in the history
  • Loading branch information
atombrella committed Nov 29, 2024
1 parent 616496b commit 2970453
Show file tree
Hide file tree
Showing 29 changed files with 42 additions and 42 deletions.
4 changes: 2 additions & 2 deletions scripts/curl_install_pypi/install.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ def _backup_rc(rc_file):
try:
shutil.copyfile(rc_file, rc_file+'.backup')
print_status("Backed up '{}' to '{}'".format(rc_file, rc_file+'.backup'))
except (OSError, IOError):
except OSError:
pass


Expand Down Expand Up @@ -233,7 +233,7 @@ def _find_line_in_file(file_path, search_pattern):
for line in search_file:
if search_pattern in line:
return True
except (OSError, IOError):
except OSError:
pass
return False

Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli-core/azure/cli/core/_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def load(self, filename, max_age=0):
self.save()
with open(self.filename, 'r', encoding=self._encoding) as f:
self.data = json.load(f)
except (OSError, IOError, json.JSONDecodeError) as load_exception:
except (OSError, json.JSONDecodeError) as load_exception:
# OSError / IOError should imply file not found issues which are expected on fresh runs (e.g. on build
# agents or new systems). A parse error indicates invalid/bad data in the file. We do not wish to warn
# on missing files since we expect that, but do if the data isn't parsing as expected.
Expand Down
4 changes: 2 additions & 2 deletions src/azure-cli-core/azure/cli/core/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def _maybe_load_file(arg):
if ix == 0:
try:
return _load_file(poss_file)
except IOError:
except OSError:
logger.debug("Failed to load '%s', assume not a file", arg)
return arg

Expand Down Expand Up @@ -471,7 +471,7 @@ def _put_operation():
obj_path = os.path.join(obj_dir, obj_file)
try:
os.remove(obj_path)
except (OSError, IOError): # FileNotFoundError introduced in Python 3
except OSError: # FileNotFoundError introduced in Python 3
pass
return result

Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli-core/azure/cli/core/keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def generate_ssh_keys(private_key_filepath, public_key_filepath):
public_key_filepath, pub_ssh_dir)

return public_key
except IOError as e:
except OSError as e:
raise CLIError(e)

ssh_dir = os.path.dirname(private_key_filepath)
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli-core/azure/cli/core/tests/test_keys.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def test_error_raised_when_public_key_file_exists_IOError(self):
with mock.patch('azure.cli.core.keys.open') as mocked_open:
# mock failed call to read
mocked_f = mocked_open.return_value.__enter__.return_value
mocked_f.read = mock.MagicMock(side_effect=IOError("Mocked IOError"))
mocked_f.read = mock.MagicMock(side_effect=OSError("Mocked IOError"))

# assert that CLIError raised when generate_ssh_keys is called
with self.assertRaises(CLIError):
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli-telemetry/azure/cli/telemetry/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ def main():
# another upload process is running.
logger.info('Lock out from note file under %s which means another process is running. Exit 0.', config_dir)
sys.exit(0)
except IOError as err:
except OSError as err:
logger.warning('Unexpected IO Error %s. Exit 1.', err)
sys.exit(1)
except Exception as err: # pylint: disable=broad-except
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def _read_file(self, path):
self._add_record(line)

self._logger.info("Processed file %s into %d records.", path, len(self._records))
except IOError as err:
except OSError as err:
self._logger.warning("Fail to open file %s. Reason: %s.", path, err)

def _add_record(self, content_line):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,5 @@ def _ensure_telemetry_log_folder(config_dir):
if not os.path.isdir(ret):
os.makedirs(ret)
return ret
except (OSError, IOError, TypeError):
except (OSError, TypeError):
return None
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ def get_last_sent(self):
last_send = datetime.datetime.strptime(raw, '%Y-%m-%dT%H:%M:%S')
self._logger.info("Read timestamp from the note. The last send was %s.", last_send)
return last_send
except (AttributeError, ValueError, IOError) as err:
except (OSError, AttributeError, ValueError) as err:
self._logger.warning("Fail to parse or read the timestamp '%s' in the note file. Set the last send time "
"to minimal. Reason: %s", raw, err)
return fallback
Expand All @@ -54,7 +54,7 @@ def update_telemetry_note(self, next_send):
self.fh.write(next_send.strftime('%Y-%m-%dT%H:%M:%S'))
self.fh.truncate()
break
except IOError:
except OSError:
self._logger.warning('Fail to update the note file. This is the %d try.', retry + 1)
else:
# TODO: how to save this?
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli/azure/cli/command_modules/acr/helm.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ def acr_helm_install_cli(client_version='2.16.3', install_location=None, yes=Fal

if os.path.splitext(f.name)[0] in ('helm', 'tiller'):
os.chmod(target_path, os.stat(target_path).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
except IOError as e:
except OSError as e:
import traceback
logger.debug(traceback.format_exc())
raise CLIError('Error while installing {} to {}: {}'.format(cli, install_dir, e))
Expand Down
6 changes: 3 additions & 3 deletions src/azure-cli/azure/cli/command_modules/acs/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -1474,7 +1474,7 @@ def load_kubernetes_configuration(filename):
try:
with open(filename) as stream:
return yaml.safe_load(stream)
except (IOError, OSError) as ex:
except OSError as ex:
if getattr(ex, 'errno', 0) == errno.ENOENT:
raise CLIError('{} does not exist'.format(filename))
raise
Expand Down Expand Up @@ -1925,7 +1925,7 @@ def k8s_install_kubectl(cmd, client_version='latest', install_location=None, sou
_urlretrieve(file_url, install_location)
os.chmod(install_location,
os.stat(install_location).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
except IOError as ex:
except OSError as ex:
raise CLIError(
'Connection error while attempting to download client ({})'.format(ex))

Expand Down Expand Up @@ -1989,7 +1989,7 @@ def k8s_install_kubelogin(cmd, client_version='latest', install_location=None, s
logger.warning('Downloading client to "%s" from "%s"',
download_path, file_url)
_urlretrieve(file_url, download_path)
except IOError as ex:
except OSError as ex:
raise CLIError(
'Connection error while attempting to download client ({})'.format(ex))
_unzip(download_path, tmp_dir)
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli/azure/cli/command_modules/apim/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -611,7 +611,7 @@ def apim_api_export(client, resource_group_name, service_name, api_id, export_fo
f.write(xml_string)
else:
f.write(str(exportedResultContent))
except IOError as e:
except OSError as e:
logger.warning("Error writing exported API to file.: %s", e)

# Write the response to a file
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def zip_contents_from_dir(dirPath, lang):
zip_dotnet_project_references(abs_src, "{}".format(zip_file_path))
except (OSError, ValueError, TypeError, ParseError, BadZipFile, LargeZipFile):
logger.warning("Analysing and bundling dotnet project references have failed.")
except IOError as e:
except OSError as e:
if e.errno == 13:
raise CLIError('Insufficient permissions to create a zip in current directory. '
'Please re-run the command with administrator privileges')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ def parse(self, namespace):
if namespace.json_file:
try:
namespace.json_file = get_file_json(namespace.json_file)
except EnvironmentError:
except OSError:
raise ValueError("Cannot access JSON request file: " + namespace.json_file)
except ValueError as err:
raise ValueError(f"Invalid JSON file: {err}")
Expand Down
6 changes: 3 additions & 3 deletions src/azure-cli/azure/cli/command_modules/batch/_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ def validate_json_file(namespace):
if namespace.json_file:
try:
get_file_json(namespace.json_file)
except EnvironmentError:
except OSError:
raise ValueError("Cannot access JSON request file: " + namespace.json_file)
except ValueError as err:
raise ValueError(f"Invalid JSON file: {err}")
Expand All @@ -215,7 +215,7 @@ def validate_cert_file(namespace):
try:
with open(namespace.certificate_file, "rb"):
pass
except EnvironmentError:
except OSError:
raise ValueError("Cannot access certificate file: " + namespace.certificate_file)


Expand Down Expand Up @@ -250,7 +250,7 @@ def validate_file_destination(namespace):
elif not os.path.isdir(file_dir):
try:
os.mkdir(file_dir)
except EnvironmentError as exp:
except OSError as exp:
message = "Directory {} does not exist, and cannot be created: {}"
raise ValueError(message.format(file_dir, exp))
if os.path.isfile(file_path):
Expand Down
6 changes: 3 additions & 3 deletions src/azure-cli/azure/cli/command_modules/configure/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ def show_cache_contents(cmd, resource_group_name, item_name, resource_type):
try:
with open(item_path, 'r') as cache_file:
cache_obj = json.loads(cache_file.read())
except (OSError, IOError):
except OSError:
raise CLIError('Not found in cache: {}'.format(item_path))
return cache_obj['_payload']

Expand All @@ -185,7 +185,7 @@ def delete_cache_contents(cmd, resource_group_name, item_name, resource_type):
item_path = os.path.join(directory, resource_group_name, resource_type, '{}.json'.format(item_name))
try:
os.remove(item_path)
except (OSError, IOError):
except OSError:
logger.info('%s not found in object cache.', item_path)


Expand All @@ -195,5 +195,5 @@ def purge_cache_contents():
directory = os.path.join(get_config_dir(), 'object_cache')
try:
shutil.rmtree(directory)
except (OSError, IOError) as ex:
except OSError as ex:
logger.debug(ex)
Original file line number Diff line number Diff line change
Expand Up @@ -1054,7 +1054,7 @@ def _flush_stdin(ws, buff, lock):
buff.clear()
lock.release()
ws.send(x, opcode=0x2) # OPCODE_BINARY = 0x2
except (OSError, IOError, websocket.WebSocketConnectionClosedException) as e:
except (OSError, websocket.WebSocketConnectionClosedException) as e:
if isinstance(e, websocket.WebSocketConnectionClosedException):
pass
elif e.errno == 9: # [Errno 9] Bad file descriptor
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def load_yaml_file(file_name):
try:
with open(file_name) as stream: # pylint: disable=unspecified-encoding
return yaml.safe_load(stream.read().replace('\x00', ''))
except (IOError, OSError) as ex:
except OSError as ex:
if getattr(ex, 'errno', 0) == errno.ENOENT:
raise ValidationError('{} does not exist'.format(file_name)) from ex
raise
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ def load_yaml_file(file_name):
try:
with open(file_name) as stream: # pylint: disable=unspecified-encoding
return yaml.safe_load(stream.read().replace('\x00', ''))
except (IOError, OSError) as ex:
except OSError as ex:
if getattr(ex, 'errno', 0) == errno.ENOENT:
raise ValidationError('{} does not exist'.format(file_name)) from ex
raise
Expand Down
2 changes: 1 addition & 1 deletion src/azure-cli/azure/cli/command_modules/feedback/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ def _get_log_record_list(log_fp, p_id):
try:
with open(file_name, 'r') as log_fp:
log_record_list = _get_log_record_list(log_fp, p_id)
except IOError:
except OSError:
logger.debug("Failed to open command log file %s", file_name)
return {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -459,7 +459,7 @@ def certificate_type(string):
with open(os.path.expanduser(string), 'rb') as f:
cert_data = f.read()
return cert_data
except (IOError, OSError) as e:
except OSError as e:
raise CLIError("Unable to load certificate file '{}': {}.".format(string, e.strerror))


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -491,7 +491,7 @@ def validate_servers(namespace):
try:
socket.inet_aton(item) # pylint:disable=no-member
servers.append({'ipAddress' if camel_case else 'ip_address': item})
except socket.error: # pylint:disable=no-member
except OSError: # pylint:disable=no-member
servers.append({'fqdn': item})
namespace.servers = servers if servers else None

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def export_zone(cmd, resource_group_name, zone_name, file_name=None): # pylint:
try:
with open(file_name, 'w') as f:
f.write(zone_file_content)
except IOError:
except OSError:
raise CLIError('Unable to export to file: {}'.format(file_name))


Expand Down
6 changes: 3 additions & 3 deletions src/azure-cli/azure/cli/command_modules/network/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -432,7 +432,7 @@ def server_trans(_, server):
try:
socket.inet_aton(str(server)) # pylint:disable=no-member
return {"ip_address": server}
except socket.error: # pylint:disable=no-member
except OSError: # pylint:disable=no-member
return {"fqdn": server}

args.backend_addresses = assign_aaz_list_arg(
Expand Down Expand Up @@ -478,7 +478,7 @@ def server_trans(_, server):
try:
socket.inet_aton(str(server)) # pylint:disable=no-member
return {"ip_address": server}
except socket.error: # pylint:disable=no-member
except OSError: # pylint:disable=no-member
return {"fqdn": server}

args.backend_addresses = assign_aaz_list_arg(
Expand Down Expand Up @@ -2653,7 +2653,7 @@ def export_zone(cmd, resource_group_name, zone_name, file_name=None): # pylint:
try:
with open(file_name, 'w') as f:
f.write(zone_file_content)
except IOError:
except OSError:
raise CLIError('Unable to export to file: {}'.format(file_name))


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def export_zone(cmd, resource_group_name, private_zone_name, file_name=None):
try:
with open(file_name, 'w') as f:
f.write(zone_file_content)
except IOError:
except OSError:
raise CLIError('Unable to export to file: {}'.format(file_name))


Expand Down
6 changes: 3 additions & 3 deletions src/azure-cli/azure/cli/command_modules/resource/_bicep.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ def ensure_bicep_installation(cli_ctx, release_tag=None, target_platform=None, s
"Successfully installed Bicep CLI to %s",
installation_path,
)
except IOError as err:
except OSError as err:
raise ClientRequestError(f"Error while attempting to download Bicep CLI: {err}")


Expand Down Expand Up @@ -190,7 +190,7 @@ def get_bicep_available_release_tags():
os.environ.setdefault("CURL_CA_BUNDLE", certifi.where())
response = requests.get("https://aka.ms/BicepReleases", verify=_requests_verify)
return [release["tag_name"] for release in response.json()]
except IOError as err:
except OSError as err:
raise ClientRequestError(f"Error while attempting to retrieve available Bicep versions: {err}.")


Expand Down Expand Up @@ -258,7 +258,7 @@ def _load_bicep_version_check_result_from_cache():
cache_expired = datetime.now() - last_check_time > _bicep_version_check_cache_ttl

return latest_release_tag, cache_expired
except (IOError, JSONDecodeError):
except (OSError, JSONDecodeError):
return None, True


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def install_azcopy(self, install_location):
_urlretrieve(file_url, install_location)
os.chmod(install_location,
os.stat(install_location).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
except IOError as err:
except OSError as err:
raise CLIError('Connection error while attempting to download azcopy {}. You could also install the '
'specified azcopy version to {} manually. ({})'.format(AZCOPY_VERSION, install_dir, err))

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ def write_to_file(notebook, path):
notebook_result['cells'] = notebook_properties['cells']
with open(path, 'w') as f:
json.dump(notebook_result, f, indent=4)
except IOError:
except OSError:
raise CLIError('Unable to export to file: {}'.format(path))


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,5 +220,5 @@ def write_to_file(kql_script, path):
query = kql_script.properties.content.query
with open(path, 'w') as f:
f.write(query)
except IOError:
except OSError:
raise CLIError('Unable to export to file: {}'.format(path))

0 comments on commit 2970453

Please sign in to comment.