Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,8 @@ def validateOne(self, opt, validations, val):
else:
if not isinstance(val, validations['type']):
raise ValueError("{} should be {}".format(opt, str(validations['type'])))
if 'in' in validations:
if not val in validations['in']:
raise ValueError("{} should be in {}".format(opt, ", ".join(validations['in'])))
if 'in' in validations and val not in validations['in']:
raise ValueError("{} should be in {}".format(opt, ", ".join(validations['in'])))
Comment on lines -51 to +52
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function NetworkAdapter.validateOne refactored with the following changes:

  • Merge nested if conditions
  • Swap positions of nested conditionals
  • Hoist repeated code outside conditional statement
  • Simplify logical expression


def validateIP(self, ip):
'''
Expand Down Expand Up @@ -183,7 +182,7 @@ def appendPostDown(self, cmd):

def setUnknown(self, key, val):
''' it's impossible to know about all available options, so storing uncommon ones as if '''
if not 'unknown' in self._ifAttributes:
if 'unknown' not in self._ifAttributes:
Comment on lines -186 to +185
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function NetworkAdapter.setUnknown refactored with the following changes:

  • Simplify logical expression

self._ifAttributes['unknown'] = {}
self._ifAttributes['unknown'][key] = val

Expand Down Expand Up @@ -225,12 +224,13 @@ def __init__(self, options=None):

def reset(self):
''' Initialize attribute storage structre. '''
self._ifAttributes = {}
self._ifAttributes['bridge-opts'] = {}
self._ifAttributes['up'] = []
self._ifAttributes['down'] = []
self._ifAttributes['pre-up'] = []
self._ifAttributes['post-down'] = []
self._ifAttributes = {
'bridge-opts': {},
'up': [],
'down': [],
'pre-up': [],
'post-down': [],
}
Comment on lines -228 to +233
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function NetworkAdapter.reset refactored with the following changes:

  • Merge dictionary assignment with declaration


def set_options(self, options):
''' raise ValueError or socket.error on issue '''
Expand Down
11 changes: 4 additions & 7 deletions dnsmasqRange.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,15 @@ class DnsmasqRange(object):
def __init__(self, path, backup_path=None):
self._config = {}
self._path = path
if not backup_path:
self.backup_path = path + ".bak"
else:
self.backup_path = backup_path
self.backup_path = path + ".bak" if not backup_path else backup_path
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DnsmasqRange.__init__ refactored with the following changes:

  • Replace if statement with if expression


@property
def config(self):
return self._config

def set(self, key, value):
if key == "dhcp-range":
if not "dhcp-range" in self._config:
if "dhcp-range" not in self._config:
Comment on lines -26 to +23
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DnsmasqRange.set refactored with the following changes:

  • Simplify logical expression

self._config["dhcp-range"] = []
if isinstance(value, str):
value = self._extract_range_info(value)
Expand All @@ -36,7 +33,7 @@ def validate(self):
for r in self._config["dhcp-range"]:
required = ["interface", "start", "end", "lease_time"]
for k in required:
if not k in r:
if k not in r:
Comment on lines -39 to +36
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DnsmasqRange.validate refactored with the following changes:

  • Simplify logical expression

raise ValueError("Missing option : {}".format(k))
socket.inet_aton(r["start"])
socket.inet_aton(r["end"])
Expand All @@ -47,7 +44,7 @@ def validate(self):

def get_itf_range(self, if_name):
''' If no if, return None '''
if not "dhcp-range" in self._config:
if "dhcp-range" not in self._config:
Comment on lines -50 to +47
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function DnsmasqRange.get_itf_range refactored with the following changes:

  • Simplify logical expression

return None
for v in self._config['dhcp-range']:
if v["interface"] == if_name:
Expand Down
25 changes: 9 additions & 16 deletions hostapd.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,7 @@ class Hostapd(object):
def __init__(self, path, backup_path=None):
self._config = {}
self._path = path
if not backup_path:
self.backup_path = path + ".bak"
else:
self.backup_path = backup_path
self.backup_path = path + ".bak" if not backup_path else backup_path
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Hostapd.__init__ refactored with the following changes:

  • Replace if statement with if expression


@property
def config(self):
Expand All @@ -36,8 +33,6 @@ def validate(self):
basic = ['interface', 'driver']
bridge = ['bridge']
wireless = ['ssid', 'channel', 'hw_mode']
auth = ['wpa', 'wpa_passphrase', 'wpa_key_mgmt']

Comment on lines -39 to -40
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Hostapd.validate refactored with the following changes:

  • Move assignments closer to their usage
  • Merge nested if conditions
  • Simplify logical expression

for k in basic:
if self._config[k] is None:
raise ValueError("Missing required {} option".format(k))
Expand All @@ -55,17 +50,17 @@ def validate(self):

if 'wpa' in self._config:
self._config['wpa'] = int(self._config['wpa'])
if not self._config['wpa'] in [1, 2, 3]:
if self._config['wpa'] not in [1, 2, 3]:
raise ValueError("Wpa option is not valid")
auth = ['wpa', 'wpa_passphrase', 'wpa_key_mgmt']

for k in auth:
if self._config[k] is None:
raise ValueError("Missing required {} option for wireless security".format(k))
if self._config['wpa'] in [1, 3]:
if not self._config['wpa_pairwise']:
raise ValueError("Missing required option for wireless security : wpa_pairwise")
if self._config['wpa'] in [2, 3]:
if not self._config['rsn_pairwise']:
raise ValueError("Missing required option for wireless security rsn_pairwise")
if self._config['wpa'] in [1, 3] and not self._config['wpa_pairwise']:
raise ValueError("Missing required option for wireless security : wpa_pairwise")
if self._config['wpa'] in [2, 3] and not self._config['rsn_pairwise']:
raise ValueError("Missing required option for wireless security rsn_pairwise")

def set_defaults(self):
''' Defaults for my needs, you should probably override this one '''
Expand Down Expand Up @@ -108,9 +103,7 @@ def read(self, path=None):

with open(path, "r") as hostapd:
for line in hostapd:
if line.startswith('#') is True:
pass
else:
if line.startswith('#') is not True:
Comment on lines -111 to +106
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Hostapd.read refactored with the following changes:

  • Swap if/else to remove empty if body

param, value = line.split("=")
if param and value:
self.set(param, value)
Expand Down
79 changes: 36 additions & 43 deletions interfacesReader.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,10 @@ def _read_lines_from_file(self, fileObj):
for line in fileObj:
# Identify the clauses by analyzing the first word of each line.
# Go to the next line if the current line is a comment.
if line.strip().startswith("#") is True:
pass
else:
if line.strip().startswith("#") is not True:
self._parse_iface(line)
# Ignore blank lines.
if line.isspace() is True:
pass
else:
if line.isspace() is not True:
Comment on lines -59 to +62
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InterfacesReader._read_lines_from_file refactored with the following changes:

  • Swap if/else to remove empty if body

self._parse_details(line)
self._read_auto(line)
self._read_hotplug(line)
Expand All @@ -78,56 +74,53 @@ def _parse_iface(self, line):
self._adapters[self._context].setAddrFam(sline[2])

def _parse_details(self, line):
if line[0].isspace() is True:
sline = line.split()
if sline[0] == 'address':
self._adapters[self._context].setAddress(sline[1])
elif sline[0] == 'netmask':
self._adapters[self._context].setNetmask(sline[1])
elif sline[0] == 'gateway':
self._adapters[self._context].setGateway(sline[1])
elif sline[0] == 'broadcast':
self._adapters[self._context].setBroadcast(sline[1])
elif sline[0] == 'network':
self._adapters[self._context].setNetwork(sline[1])
elif sline[0].startswith('bridge') is True:
opt = sline[0].split('_')
sline.pop(0)
ifs = " ".join(sline)
self._adapters[self._context].replaceBropt(opt[1], ifs)
elif sline[0] == 'up' or sline[0] == 'down' or sline[0] == 'pre-up' or sline[0] == 'post-down':
ud = sline.pop(0)
cmd = ' '.join(sline)
if ud == 'up':
self._adapters[self._context].appendUp(cmd)
elif ud == 'down':
self._adapters[self._context].appendDown(cmd)
elif ud == 'pre-up':
self._adapters[self._context].appendPreUp(cmd)
elif ud == 'post-down':
self._adapters[self._context].appendPostDown(cmd)
else:
# store as if so as not to loose it
self._adapters[self._context].setUnknown(sline[0], sline[1])
if line[0].isspace() is not True:
return
sline = line.split()
if sline[0] == 'address':
self._adapters[self._context].setAddress(sline[1])
elif sline[0] == 'netmask':
self._adapters[self._context].setNetmask(sline[1])
elif sline[0] == 'gateway':
self._adapters[self._context].setGateway(sline[1])
elif sline[0] == 'broadcast':
self._adapters[self._context].setBroadcast(sline[1])
elif sline[0] == 'network':
self._adapters[self._context].setNetwork(sline[1])
elif sline[0].startswith('bridge') is True:
opt = sline[0].split('_')
sline.pop(0)
ifs = " ".join(sline)
self._adapters[self._context].replaceBropt(opt[1], ifs)
elif sline[0] in ['up', 'down', 'pre-up', 'post-down']:
ud = sline.pop(0)
cmd = ' '.join(sline)
if ud == 'up':
self._adapters[self._context].appendUp(cmd)
elif ud == 'down':
self._adapters[self._context].appendDown(cmd)
elif ud == 'pre-up':
self._adapters[self._context].appendPreUp(cmd)
elif ud == 'post-down':
self._adapters[self._context].appendPostDown(cmd)
else:
# store as if so as not to loose it
self._adapters[self._context].setUnknown(sline[0], sline[1])
Comment on lines -81 to +108
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InterfacesReader._parse_details refactored with the following changes:

  • Add guard clause
  • Replace multiple comparisons of same variable with in operator


def _read_auto(self, line):
''' Identify which adapters are flagged auto. '''
if line.startswith('auto'):
sline = line.split()
for word in sline:
if word == 'auto':
pass
else:
if word != 'auto':
Comment on lines -118 to +115
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InterfacesReader._read_auto refactored with the following changes:

  • Swap if/else to remove empty if body

self._auto_list.append(word)

def _read_hotplug(self, line):
''' Identify which adapters are flagged allow-hotplug. '''
if line.startswith('allow-hotplug'):
sline = line.split()
for word in sline:
if word == 'allow-hotplug':
pass
else:
if word != 'allow-hotplug':
Comment on lines -128 to +123
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function InterfacesReader._read_hotplug refactored with the following changes:

  • Swap if/else to remove empty if body

self._hotplug_list.append(word)

def _reset(self):
Expand Down