Passed
Push — develop ( 503712...bde8f9 )
by Shalom
02:13
created

inji.utils.recursive_iglob()   A

Complexity

Conditions 3

Size

Total Lines 4
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3

Importance

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