Skip to content

Commit

Permalink
Add pre-commit hooks and fix linting
Browse files Browse the repository at this point in the history
  • Loading branch information
benjaoming committed Jul 20, 2017
1 parent 0fa269c commit 261a17b
Show file tree
Hide file tree
Showing 16 changed files with 151 additions and 127 deletions.
20 changes: 20 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
- repo: git://github.com/pre-commit/pre-commit-hooks
sha: a11d9314b22d8f8c7556443875b731ef05965464
hooks:
- id: trailing-whitespace
- id: flake8
- id: check-yaml
- id: check-added-large-files
- id: debug-statements
- id: end-of-file-fixer
- repo: git://github.com/FalconSocial/pre-commit-python-sorter
sha: 5991d2aea26858d3c3538e0b4e09255b6b99413e
hooks:
- id: python-import-sorter
args:
- --silent-overwrite
- repo: git://github.com/pre-commit/mirrors-eslint
sha: v3.14.0
hooks:
- id: eslint
additional_dependencies: [ 'eslint', 'eslint-plugin-html', 'eslint-config-airbnb', 'eslint-plugin-import', 'eslint-plugin-jsx-a11y']
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,4 @@ notifications:
- "irc.freenode.org#django-wiki"

after_success:
- bash <(curl -s https://codecov.io/bash)
- codecov
76 changes: 38 additions & 38 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,21 @@ Python Ifconfig Wrapper for Unix/Linux/MacOSX
=============================================================================

Ifcfg is a cross-platform (*nix) library for parsing 'ifconfig' output in
Python. It is useful for pulling information such as IP, Netmask, MAC Address,
Python. It is useful for pulling information such as IP, Netmask, MAC Address,
Hostname, etc.

Some Limitations:

* Targeted for Unix-like operating systems including Linux and Mac OSX
* Relies on parsing `ifconfig` or `ip address` output


Usage
-----

import ifcfg
import json

for interface in ifcfg.interfaces:
# do something with interface
print interface['device']
Expand All @@ -28,53 +28,53 @@ Usage
default = ifcfg.default_interface()


The output of 'ifcfg.interfaces' dumped to JSON looks something like the
The output of 'ifcfg.interfaces' dumped to JSON looks something like the
following:

$ python test.py | python -mjson.tool
{
"eth0": {
"broadcast": "172.16.217.255",
"ether": "00:0c:29:0c:da:5d",
"flags": "4163<up,broadcast,running,multicast> ",
"hostname": "derks-vm.local",
"inet": "172.16.217.10",
"inet6": "fe80::20c:29ff:fe0c:da5d",
"mtu": "1500",
"name": "eth0",
"netmask": "255.255.255.0",
"prefixlen": "64",
"broadcast": "172.16.217.255",
"ether": "00:0c:29:0c:da:5d",
"flags": "4163<up,broadcast,running,multicast> ",
"hostname": "derks-vm.local",
"inet": "172.16.217.10",
"inet6": "fe80::20c:29ff:fe0c:da5d",
"mtu": "1500",
"name": "eth0",
"netmask": "255.255.255.0",
"prefixlen": "64",
"scopeid": "0x20<link>"
},
},
"lo": {
"broadcast": null,
"ether": null,
"flags": "73<up,loopback,running> ",
"hostname": "localhost",
"inet": "127.0.0.1",
"inet6": "::1",
"mtu": "16436",
"name": "lo",
"netmask": "255.0.0.0",
"prefixlen": "128",
"broadcast": null,
"ether": null,
"flags": "73<up,loopback,running> ",
"hostname": "localhost",
"inet": "127.0.0.1",
"inet6": "::1",
"mtu": "16436",
"name": "lo",
"netmask": "255.0.0.0",
"prefixlen": "128",
"scopeid": "0x10<host>"
},
},
"virbr0": {
"broadcast": "192.168.122.255",
"ether": "52:54:00:5b:70:0d",
"flags": "4099<up,broadcast,multicast> ",
"hostname": "derks-vm.local",
"inet": "192.168.122.1",
"inet6": null,
"mtu": "1500",
"name": "virbr0",
"netmask": "255.255.255.0",
"prefixlen": null,
"broadcast": "192.168.122.255",
"ether": "52:54:00:5b:70:0d",
"flags": "4099<up,broadcast,multicast> ",
"hostname": "derks-vm.local",
"inet": "192.168.122.1",
"inet6": null,
"mtu": "1500",
"name": "virbr0",
"netmask": "255.255.255.0",
"prefixlen": null,
"scopeid": null
}
}
License
-------

The Ifcfg library is Open Source and is distributed under the BSD License
The Ifcfg library is Open Source and is distributed under the BSD License
(three clause). Please see the LICENSE file included with this software.
9 changes: 9 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,12 @@ exclude = */*migrations

[metadata]
description-file = README.rst

[isort]
atomic = true
multi_line_output = 5
line_length = 160
indent = ' '
combine_as_imports = true
skip = setup.py,.eggs,build

14 changes: 5 additions & 9 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import os
import sys
from setuptools import setup, find_packages

from setuptools import find_packages, setup

sys.path.append(os.path.join(os.path.dirname(__file__), 'src'))

import ifcfg
import ifcfg # noqa


setup(
name='ifcfg',
Expand All @@ -22,13 +24,7 @@
include_package_data=True,
zip_safe=False,
test_suite='nose.collector',
install_requires=[
### Required to build documentation
# "Sphinx >= 1.0",
### Required for testing
# "nose",
# "coverage",
],
install_requires=[],
setup_requires=[],
entry_points="""
""",
Expand Down
22 changes: 10 additions & 12 deletions src/ifcfg/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import os
import platform
import re
from . import parser
from . import tools
from . import exc

Expand All @@ -13,21 +12,21 @@
def get_parser(**kw):
"""
Detect the proper parser class, and return it instantiated.
Optional Arguments:
parser
The parser class to use instead of detecting the proper one.
distro
The distro to parse for (used for testing).
kernel
The kernel to parse for (used for testing).
ifconfig
The ifconfig (stdout) to pass to the parser (used for testing).
"""
Parser = kw.get('parser', None)
ifconfig = kw.get('ifconfig', None)
Expand All @@ -36,7 +35,7 @@ def get_parser(**kw):
full_kernel = kw.get('kernel', platform.uname()[2])
split_kernel = full_kernel.split('.')[0:2]
kernel_version = int(split_kernel[0])

if len(split_kernel) > 1:
kernel_major_rev = int(re.match('\d+', split_kernel[1]).group())
else:
Expand All @@ -62,20 +61,19 @@ def get_parser(**kw):
Parser = UnixIPParser

return Parser(ifconfig=ifconfig)

def interfaces():
"""
Return just the parsed interfaces dictionary from the proper parser.
"""
parser = get_parser()
return parser.interfaces

def default_interface():
"""
Return just the default interface device dictionary.
"""
parser = get_parser()
return parser.default_interface

4 changes: 2 additions & 2 deletions src/ifcfg/exc.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ class IfcfgError(Exception):
"""Generic Ifcfg Errors."""
def __init__(self, msg):
self.msg = msg

class IfcfgParserError(IfcfgError):
"""Ifcfg Parsing Errors."""
def __init__(self, *args, **kw):
super(IfcfgParserError, self).__init__(*args, **kw)
super(IfcfgParserError, self).__init__(*args, **kw)
25 changes: 12 additions & 13 deletions src/ifcfg/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def __init__(self, *args, **kw):
@classmethod
def get_command(cls):
ifconfig_cmd = 'ifconfig'
for path in ['/sbin','/usr/sbin','/bin','/usr/bin']:
for path in ['/sbin', '/usr/sbin', '/bin', '/usr/bin']:
if os.path.exists(os.path.join(path, ifconfig_cmd)):
ifconfig_cmd = os.path.join(path, ifconfig_cmd)
break
Expand All @@ -39,7 +39,7 @@ def get_patterns(cls):
'.*(ether )(?P<ether>[^\s]*).*',
]

def parse(self, ifconfig=None):
def parse(self, ifconfig=None): # noqa: max-complexity=12
"""
Parse ifconfig output into self._interfaces.
Expand All @@ -50,7 +50,6 @@ def parse(self, ifconfig=None):
call exec_cmd(self.get_command()).
"""
_interfaces = []
if not ifconfig:
ifconfig, __, __ = exec_cmd(self.get_command())
if hasattr(ifconfig, 'decode'):
Expand All @@ -70,7 +69,7 @@ def parse(self, ifconfig=None):
# device block.
if 'device' in groupdict:
cur = groupdict['device']
if not cur in self._interfaces:
if cur not in self._interfaces:
self._interfaces[cur] = {}

for key in groupdict:
Expand All @@ -83,7 +82,7 @@ def parse(self, ifconfig=None):

# standardize
for key in all_keys:
for device,device_dict in self._interfaces.items():
for device, device_dict in self._interfaces.items():
if key not in device_dict:
self._interfaces[device][key] = None
if type(device_dict[key]) == str:
Expand All @@ -104,7 +103,7 @@ def alter(self, interfaces):
"""
# fixup some things
for device,device_dict in interfaces.items():
for device, device_dict in interfaces.items():
if 'inet' in device_dict:
try:
host = socket.gethostbyaddr(device_dict['inet'])[0]
Expand Down Expand Up @@ -140,7 +139,7 @@ def default_interface(self):
if interface == iface:
return self.interfaces[interface]

return None # pragma: nocover
return None


class UnixParser(IfcfgParser):
Expand Down Expand Up @@ -180,12 +179,12 @@ class UnixIPParser(IfcfgParser):
@classmethod
def get_command(cls):
ifconfig_cmd = 'ip'
for path in ['/sbin','/usr/sbin','/bin','/usr/bin']:
for path in ['/sbin', '/usr/sbin', '/bin', '/usr/bin']:
if os.path.exists(os.path.join(path, ifconfig_cmd)):
ifconfig_cmd = os.path.join(path, ifconfig_cmd)
break
return [ifconfig_cmd, 'address', 'show']

@classmethod
def get_patterns(cls):
return [
Expand All @@ -195,9 +194,9 @@ def get_patterns(cls):
'.*(ether )(?P<ether>[^\s]*).*',
'.*inet\s.*(brd )(?P<broadcast>[^\s]*).*',
'.*(inet )[^/]+(?P<netmask>[/][0-9]+).*',
#'.*(prefixlen )(?P<prefixlen>[^\s]*).*',
#'.*(scopeid )(?P<scopeid>[^\s]*).*',
#'.*(ether )(?P<ether>[^\s]*).*',
# '.*(prefixlen )(?P<prefixlen>[^\s]*).*',
# '.*(scopeid )(?P<scopeid>[^\s]*).*',
# '.*(ether )(?P<ether>[^\s]*).*',
]


Expand All @@ -214,7 +213,7 @@ def parse(self, *args, **kw):
super(MacOSXParser, self).parse(*args, **kw)

# fix up netmask address for mac
for device,device_dict in self.interfaces.items():
for device, device_dict in self.interfaces.items():
if device_dict['netmask'] is not None:
netmask = self.interfaces[device]['netmask']
self.interfaces[device]['netmask'] = hex2dotted(netmask)
16 changes: 8 additions & 8 deletions src/ifcfg/tools.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@

import os
import logging
import sys
from subprocess import Popen, PIPE
import os
from subprocess import PIPE, Popen


def minimal_logger(name):
log = logging.getLogger(name)
formatter = logging.Formatter(
"%(asctime)s IFCFG DEBUG : %(name)s : %(message)s")
"%(asctime)s IFCFG DEBUG : %(name)s : %(message)s"
)
console = logging.StreamHandler()
console.setFormatter(formatter)
console.setLevel(logging.DEBUG)
console.setLevel(logging.DEBUG)

if 'IFCFG_DEBUG' in os.environ.keys() and os.environ['IFCFG_DEBUG'] == '1':
log.setLevel(logging.DEBUG)
log.addHandler(console)
return log

def exec_cmd(cmd_args):
proc = Popen(cmd_args, stdout=PIPE, stderr=PIPE)
(stdout, stderr) = proc.communicate()
Expand Down
Loading

0 comments on commit 261a17b

Please sign in to comment.