2 ##############################################################################
3 # Copyright © 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_dir, file):
60 if not os.path.exists(target_dir):
61 os.makedirs(target_dir)
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 target_path = target_dir + '/' + os.path.basename(file)
69 fd2 = open(target_path,'w')
73 print '{0} -> {1}'.format(file, target_path)
76 if len(sys.argv) != 4:
77 print 'usage: jcopy.py <yaml> <in_dir_or_file> <out_dir>'
80 with open(sys.argv[1]) as f:
81 yaml = yaml.safe_load(f)
84 if os.path.isfile(sys.argv[2]):
85 expand_file(sys.argv[3], sys.argv[2])
87 os.path.walk(sys.argv[2], expand_files, sys.argv[3])
88 print '%d files processed.' % total
91 # sudo python -m ensurepip --default-pip
92 # sudo python -m pip install --upgrade pip setuptools wheel
93 # pip install --user jinja2 PyYAML