Skip to content

Commit 7b579c1

Browse files
committed
adding initial code refactor
1 parent 4924a00 commit 7b579c1

7 files changed

Lines changed: 201 additions & 0 deletions

File tree

netsim_wrapper/json.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
from logging import INFO
2+
from json import load, dump
3+
4+
from .system import System
5+
6+
7+
class Json(System):
8+
def __init__(self, level=INFO) -> None:
9+
super(Json, self).__init__(level=level)
10+
self.log.debug(f"base class: {__class__.__name__} initialize")
11+
12+
def load(self, fpath):
13+
data = None
14+
try:
15+
self.log.debug(f"base class: {__class__.__name__}.{__class__.__module__}")
16+
with open(fpath) as f:
17+
data = load(f)
18+
except EnvironmentError as e:
19+
self.log.error("error while loading the file: {}".format(fpath))
20+
self.log.error(e)
21+
return data
22+
23+
def dump(self, fpath, template):
24+
try:
25+
self.log.debug(f"base class: {__class__.__name__}.{__class__.__module__}")
26+
with open(fpath, 'w') as f:
27+
dump(template, f, indent=2)
28+
self.log.info("please, find the file in: {}".format(fpath))
29+
except EnvironmentError as e:
30+
self.log.error("error while createing of template")
31+
self.log.error(e)
32+

netsim_wrapper/netsim.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from .utils import Utils
2+
from logging import INFO
3+
4+
class Netsim(Utils):
5+
name = 'ncs-netsim'
6+
command = ['ncs-netsim']
7+
netsim_options = []
8+
netsim_dir = 'netsim'
9+
10+
def __init__(self, path='.', level=INFO) -> None:
11+
super().__init__(path, level)
12+
13+

netsim_wrapper/run.py

Whitespace-only changes.

netsim_wrapper/system.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
"""
2+
The module is for system operations exit, unlink and setting logger
3+
"""
4+
5+
import logging
6+
7+
from pathlib import Path
8+
from sys import exit as sys_exit
9+
import subprocess
10+
11+
format = '%(levelname)-8s | %(asctime)s | %(module)-8s:%(lineno)-4d | %(message)s'
12+
13+
14+
def get_log(level):
15+
logging.basicConfig(level=level, format=format)
16+
return logging.getLogger()
17+
18+
19+
class System:
20+
def __init__(self, path='.', level=logging.INFO) -> None:
21+
super(System, self).__init__()
22+
self.log = get_log(level)
23+
self.log.debug(f"base class: {__class__.__name__} initialize")
24+
self.path = Path(path).absolute()
25+
26+
@property
27+
def exit(self):
28+
sys_exit()
29+
30+
def delete(self, fpath):
31+
path = Path(fpath).absolute()
32+
if path.exists():
33+
path.unlink()
34+
35+
def is_file(self, fpath):
36+
path = Path(fpath).absolute()
37+
return path.is_file()
38+
39+
def is_dir(self, fpath):
40+
path = Path(fpath).absolute()
41+
return path.is_dir()
42+
43+
def call(self, cmd):
44+
try:
45+
subprocess.call(cmd, shell=True)
46+
except EnvironmentError as e:
47+
self.log.error("failed to run command: {}".format(cmd))
48+
self.log.error(e)
49+
50+
def run(self, cmd, error=True):
51+
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
52+
out, err = p.communicate()
53+
out, err = out.decode('utf-8'), err.decode('utf-8')
54+
if err == '' or 'env.sh' in err:
55+
self.log.debug("`{}` ran successfully".format(' '.join(cmd)))
56+
return out
57+
if error:
58+
self.log.error("an error occured while running command `{}`".format(' '.join(cmd)))
59+
self.log.error('message: {}'.format(err))
60+
if 'command not found' in err or 'Unknown command' in err:
61+
raise ValueError("command not found.")
62+
return False

netsim_wrapper/utils.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
"""
2+
The module is for system operations (subprocess) and setting logger
3+
"""
4+
5+
from logging import INFO
6+
from pathlib import Path
7+
8+
from .system import System
9+
from .json import Json
10+
11+
class Xml(System):
12+
def __init__(self, level=INFO) -> None:
13+
super().__init__(level=level)
14+
self.log.debug(f"base class: {__class__.__name__} initialize")
15+
16+
def dump(self, fpath, xml_data):
17+
try:
18+
self.log.debug(f"base class: {__class__.__name__}.{__class__.__module__}")
19+
with open(fpath, 'w') as fp:
20+
fp.write(xml_data)
21+
self.log.info("please, find the file in: {}".format(fpath))
22+
except EnvironmentError as e:
23+
self.log.error("error on createing xml file")
24+
self.log.error(e)
25+
26+
27+
class Utils(Json, System):
28+
def __init__(self, path='.', level=INFO) -> None:
29+
super(Utils, self).__init__(path, level)
30+
self.log.debug(f"base class: {__class__.__name__} initialize")
31+
32+
def create(self, fpath):
33+
if not self.is_file(fpath):
34+
self.dump(fpath, {})
35+
36+
def rstrip_digits(self, given_string):
37+
return given_string.rstrip('1234567890')
38+
39+
def get_index(self, given_list, element):
40+
try:
41+
return given_list.index(element)
42+
except ValueError:
43+
return None
44+
45+
def get_path(self):
46+
path = None
47+
# if len(cmd_lst) > index+1:
48+
# path = cmd_lst[index+1]
49+
# else:
50+
# path = '{}/{}.{}'.format(self.path, filename, filetype)
51+
return path

netsim_wrapper/wrapper.py

Whitespace-only changes.

netsim_wrapper/yaml.py

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from logging import INFO
2+
from collections import OrderedDict
3+
from yaml import add_representer, dump, load, FullLoader
4+
5+
from .system import System
6+
7+
8+
class Yaml(System):
9+
def __init__(self, level=INFO) -> None:
10+
super(Yaml, self).__init__(level=level)
11+
self.log.debug(f"base class: {__class__.__name__} initialize")
12+
self._setup_yaml
13+
14+
@property
15+
def _setup_yaml(self):
16+
represent_dict_order = lambda self, data: \
17+
self.represent_mapping(
18+
'tag:yaml.org,2002:map',
19+
data.items()
20+
)
21+
add_representer(OrderedDict, represent_dict_order)
22+
23+
def load(self, fpath):
24+
data = None
25+
try:
26+
self.log.debug(f"base class: {__class__.__name__}.{__class__.__module__}")
27+
with open(fpath) as f:
28+
data = load(f, Loader=FullLoader)
29+
except EnvironmentError as e:
30+
self.log.error("error while loading the file {}".format(fpath))
31+
self.log.error(e)
32+
return data
33+
34+
def dump(self, fpath, template):
35+
try:
36+
self.log.debug(f"base class: {__class__.__name__}.{__class__.__module__}")
37+
with open(fpath, 'w') as f:
38+
dump(template, f, sort_keys=False)
39+
self.log.info("please, find the file in: {}".format(fpath))
40+
except EnvironmentError as e:
41+
self.log.error("error while createing of template")
42+
self.log.error(e)
43+

0 commit comments

Comments
 (0)