Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement type check #2

Merged
merged 3 commits into from Jul 4, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 6 additions & 2 deletions .github/workflows/test.yml
Expand Up @@ -7,9 +7,9 @@ jobs:

runs-on: ubuntu-latest
strategy:
max-parallel: 4
max-parallel: 3
matrix:
python-version: [3.5, 3.6, 3.7, 3.8]
python-version: [3.6, 3.7, 3.8]

steps:
- uses: actions/checkout@v1
Expand All @@ -21,6 +21,10 @@ jobs:
run: |
pip install pycodestyle
pycodestyle --max-line-length=100 hosts.py
- name: Type check with mypy
run: |
pip install mypy
mypy hosts.py
- name: Test with pytest
run: |
pip install pytest
Expand Down
29 changes: 16 additions & 13 deletions hosts.py
@@ -1,16 +1,19 @@
#!/usr/bin/env python
import os
import re
import json
import argparse
import ipaddress
from typing import Dict, List, Union, Any


# if you want to use different file as hosts, update hostsfile
hostsfile = '/etc/hosts'
hostsfile: str = '/etc/hosts'

# Define Type for Inventories
Inventories = Dict[str, Union[Dict[Any, Any], Dict[str, List[str]]]]

def _getargs():

def _getargs() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description='Parse /etc/hosts for Ansible Inventory')
parser.add_argument('--list',
Expand All @@ -24,29 +27,29 @@ def _getargs():
return args


def makeInventory(f):
inventories = {
def makeInventory(f: str) -> Inventories:
inventories: Inventories = {
'_meta': {'hostvars': {}},
'targets': {'hosts': []}
}

with open(f, 'r') as f:
hosts = f.readlines()
with open(f, 'r') as filepath:
hosts: List[str] = filepath.readlines()

hostlines = [host.strip() for host in hosts
if not host.startswith('#') and host.strip() != '']
hostlines: List[str] = [host.strip() for host in hosts
if not host.startswith('#') and host.strip() != '']

for i in hostlines:
splitted = re.split(' +| +', i)
splitted: List[str] = re.split(' +| +', i)
if len(splitted) < 2:
continue
if splitted[1] == '':
continue
try:
ip = ipaddress.ip_address(splitted[0])
ip: ipaddress.IPv4Address = ipaddress.ip_address(splitted[0])
except ValueError:
continue
hostname = splitted[1]
hostname: str = splitted[1]
if ip.is_loopback or ip.is_link_local or ip.is_multicast or ip.is_reserved:
continue
if str(ip) == '255.255.255.255':
Expand All @@ -59,5 +62,5 @@ def makeInventory(f):


if __name__ == "__main__":
args = _getargs()
args: argparse.Namespace = _getargs()
print(json.dumps(makeInventory(args.f), indent=4))