1# -*- coding: utf-8 -*- 2 3""" 4cookiecutter.replay. 5 6------------------- 7""" 8 9from __future__ import unicode_literals 10 11import json 12import os 13 14import six 15 16from cookiecutter.utils import make_sure_path_exists 17 18 19def get_file_name(replay_dir, template_name): 20 """Get the name of file.""" 21 file_name = '{}.json'.format(template_name) 22 return os.path.join(replay_dir, file_name) 23 24 25def dump(replay_dir, template_name, context): 26 """Write json data to file.""" 27 if not make_sure_path_exists(replay_dir): 28 raise IOError('Unable to create replay dir at {}'.format(replay_dir)) 29 30 if not isinstance(template_name, six.string_types): 31 raise TypeError('Template name is required to be of type str') 32 33 if not isinstance(context, dict): 34 raise TypeError('Context is required to be of type dict') 35 36 if 'cookiecutter' not in context: 37 raise ValueError('Context is required to contain a cookiecutter key') 38 39 replay_file = get_file_name(replay_dir, template_name) 40 41 with open(replay_file, 'w') as outfile: 42 json.dump(context, outfile, indent=2) 43 44 45def load(replay_dir, template_name): 46 """Read json data from file.""" 47 if not isinstance(template_name, six.string_types): 48 raise TypeError('Template name is required to be of type str') 49 50 replay_file = get_file_name(replay_dir, template_name) 51 52 with open(replay_file, 'r') as infile: 53 context = json.load(infile) 54 55 if 'cookiecutter' not in context: 56 raise ValueError('Context is required to contain a cookiecutter key') 57 58 return context 59