Test Failed
Push — develop ( ac9f81...07ed12 )
by Shalom
01:57
created

inji.utils.load_file()   A

Complexity

Conditions 1

Size

Total Lines 2
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 2
ccs 2
cts 2
cp 1
rs 10
c 0
b 0
f 0
cc 1
nop 1
crap 1
1
#!/usr/bin/env python3
2
3
# -*- coding: utf-8 -*-
4
5 1
import argparse
6 1
from os.path import abspath, basename, dirname, exists, expandvars, isdir, isfile, join
7 1
import json
8 1
import os
9 1
import fnmatch
10 1
import requests
11 1
import subprocess
12 1
import sys
13 1
import yaml
14
15 1
def json_parse(string):
16
  """ Parse a JSON string into a dictionary """
17 1
  try:
18 1
    return json.loads(string)
19 1
  except Exception as e:
20 1
    msg = 'Error parsing JSON config: {}'.format(str(e))
21 1
    print(msg, file=sys.stderr)
22 1
    raise TypeError(msg)
23
24
25 1
def kv_parse(string):
26
  """ Parse a string of the form foo=bar into a dictionary """
27 1
  try:
28 1
    key, val = string.split('=', 1)
29 1
    if key is None or key == '':
30 1
      raise TypeError('Empty key')
31 1
  except Exception as e:
32 1
    err = "Invalid key found parsing KV string '{}': {}".format(string, str(e))
33 1
    print(err, file=sys.stderr)
34 1
    raise
35 1
  return { key: val }
36
37
38 1
def read_context(yaml_file):
39 1
  yaml_file = yaml_file.__str__()
40 1
  with open(yaml_file, 'r') as f:
41 1
    try:
42 1
      in_vars = yaml.load(f, Loader=yaml.SafeLoader)
43 1
      if in_vars is None:
44 1
        raise TypeError("'{}' contains no data".format(yaml_file))
45 1
    except TypeError as exc:
46 1
      raise exc
47 1
  return in_vars
48
49
50 1
def recursive_iglob(rootdir='.', pattern='*'):
51 1
  for root, dirnames, filenames in os.walk(rootdir):
52 1
    for filename in fnmatch.filter(filenames, pattern):
53 1
      yield os.path.join(root, filename)
54
55
56 1
def path(fspath, type='file'):
57
  """
58
  Checks if a filesystem path exists with the correct type
59
  """
60
61 1
  fspath = abspath(expandvars(str(fspath)))
62 1
  msg = None
63 1
  prefix = "path '{0}'".format(fspath)
64
65 1
  if not exists(fspath):
66 1
    msg = "{0} does not exist".format(prefix)
67
68 1
  if type == 'file' and isdir(fspath):
69 1
    msg = "{0} is not a file".format(prefix)
70
71 1
  if msg is not None:
72 1
    print(msg, file=sys.stderr)
73 1
    raise argparse.ArgumentTypeError(msg)
74
75 1
  return fspath
76
77
78 1
def file_or_stdin(file):
79
  # /dev/stdin is a special case allowing bash (and other shells?) to name stdin
80
  # as a file. While python should have no problem reading from it, we actually
81
  # read template relative to the template's basedir and /dev has no templates.
82 1
  if file == '-' or file == '/dev/stdin':
83 1
    return '-'
84 1
  return path(file)
85
86
87 1
def cmd(args):
88 1
  return subprocess.check_output(args.split(' ')).decode('utf-8').strip()
89
90 1
def load_file(file):
91 1
  return open(file, encoding='utf-8').read().strip()
92
93 1
def get(url):
94
  return requests.get(url).content.decode('utf8')
95