2 ##############################################################################
3 # Copyright (c) 2018 AT&T Intellectual Property. All rights reserved. #
5 # Licensed under the Apache License, Version 2.0 (the "License"); you may #
6 # not use this file except in compliance with the License. #
8 # You may obtain a copy of the License at #
9 # http://www.apache.org/licenses/LICENSE-2.0 #
11 # Unless required by applicable law or agreed to in writing, software #
12 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT #
13 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
14 # See the License for the specific language governing permissions and #
15 # limitations under the License. #
16 ##############################################################################
19 # jcopy.py - Copy a file or files to a target directory, making
20 # substitutions as needed from the values contained in a YAML file.
22 # usage: jcopy.py <yaml> <in_dir_or_file> <out_dir>
24 # Note: jcopy.sh is for Python2, jcopy3.sh is for Python3
32 def expand_files(target_dir, dir_name, files):
34 xlen = len(sys.argv[2])
35 targdir = target_dir + dir_name[xlen:]
36 if not os.path.exists(targdir):
38 env = jinja2.Environment()
39 env.trim_blocks = True
40 env.lstrip_blocks = True
44 t = f.replace(".j2", ".yaml")
45 source_path = dir_name + '/' + f
46 target_path = targdir + '/' + t
47 if os.path.isfile(source_path):
48 with open(source_path) as fd:
49 template = env.from_string(fd.read())
50 data = template.render(yaml=yaml)
51 fd2 = open(target_path,'w')
55 print '{0} -> {1}'.format(source_path, target_path)
58 def expand_file(target_file, file):
60 if not os.path.exists(os.path.dirname(target_file)):
61 os.makedirs(os.path.dirname(target_file))
62 env = jinja2.Environment()
63 env.trim_blocks = True
64 env.lstrip_blocks = True
65 with open(file) as fd:
66 template = env.from_string(fd.read())
67 data = template.render(yaml=yaml)
68 fd2 = open(target_file,'w')
72 print '{0} -> {1}'.format(file, target_file)
75 if len(sys.argv) != 4:
76 print 'usage: jcopy.py <yaml> <in_dir_or_file> <out_dir>'
79 with open(sys.argv[1]) as f:
80 yaml = yaml.safe_load(f)
83 if os.path.isfile(sys.argv[2]):
84 expand_file(sys.argv[3], sys.argv[2])
86 os.path.walk(sys.argv[2], expand_files, sys.argv[3])
87 print '%d files processed.' % total
90 # sudo python -m ensurepip --default-pip
91 # sudo python -m pip install --upgrade pip setuptools wheel
92 # pip install --user jinja2 PyYAML