generate.py 3.87 KB
Newer Older
1
#!/usr/bin/env python3
Tobias Langer committed
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20

"""
This utility script helps in the creation of experiment setups. It therefore
reads experiment descriptions from json files and creates everything necessary
as a result.

It therefore performs the following actions:
* [x] Read the json file of every experiment
* [x] Create folders for every experiment
* [ ] Create the header file for every experiment
* [x] Add the make file for every experiment
* [x] Add c++ file for every experiment
"""

import sys
import os
import argparse
import shutil
import json
21
import pystache
Tobias Langer committed
22 23 24 25 26 27 28 29

def query_yes_no(question, default=None):
    """
    Queries the user for a decision.
    """

    if default is None:
        prompt = ' [y/n]'
30
    elif default.lower() == 'yes':
Tobias Langer committed
31
        prompt = ' [Y/n]'
32
    elif default.lower() == 'no':
Tobias Langer committed
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
        prompt = ' [y/N]'
    else:
        raise ValueError('Invalid default answer {}'.format(default))

    while True:
        print(question, prompt)
        choice = input().lower()
        if 'yes'.find(choice) == 0:
            return True
        elif 'no'.find(choice) == 0:
            return False

def create_dir(filename):
    """
    Create the directory denoted by filename, if it doesn't exists. Ask for its
    removal if it exists.
    """
    try:
51
        os.makedirs(filename)
Tobias Langer committed
52 53 54
    except FileExistsError:
        if not query_yes_no('Folder exists, remove?', default='yes'):
            return False
55 56
        shutil.rmtree(filename)
        os.makedirs(filename)
Tobias Langer committed
57 58
    return True

59
def create_header(headerfile, experiment, destination):
Tobias Langer committed
60 61 62
    """
    Create a header file for the experiment.
    """
63 64 65 66 67
    with open(headerfile, 'r') as header_template:
        template = header_template.read()
    header_txt = pystache.render(template, experiment)
    with open(destination, 'w') as header:
        print(header_txt, file=header)
Tobias Langer committed
68 69 70 71 72 73 74 75

def main():
    """
    Starting point of the script, parses arguments and creates the experiments.
    """

    parser = argparse.ArgumentParser(description='Generate experiment data.')
    parser.add_argument('description', type=str, nargs='+', help='file containing the taskset description.')
76 77 78
    parser.add_argument('--header', dest='header', type=str, nargs='?', default='./template/config.h', help='path to optional custom header file.')
    parser.add_argument('--makefile', dest='makefile', type=str, nargs='?', default='./template/Makefile', help='path to optional custom makefile.')
    parser.add_argument('--cpp', dest='cpp', type=str, nargs='?', default='./template/experiment.cpp', help='path to optional custom c++ implementation.')
Tobias Langer committed
79 80

    args = parser.parse_args()
81 82
    cwd = os.getcwd()

Tobias Langer committed
83 84 85 86 87
    for num, experiment_file in enumerate(args.description):
        with open(experiment_file, 'r') as experiment_description:
            descr_json = experiment_description.read()
        experiment = json.loads(descr_json)

Tobias Langer committed
88
        print('[{}/{}] Creating experiment {}:'.format(num + 1,
Tobias Langer committed
89 90 91 92
                                                       len(args.description),
                                                       experiment['name']),
              file=sys.stderr)

93 94
        experiment_dir = os.path.join(cwd, experiment['name'])

Tobias Langer committed
95
        # Create folder
96
        print('create folder ', experiment_dir, file=sys.stderr)
97
        if not create_dir(experiment_dir):
Tobias Langer committed
98 99 100 101
            print('Skipping experiment ', experiment['name'], file=sys.stderr)
            continue

        # Add header
102
        print('create header file', file=sys.stderr)
103
        create_header(args.headerfile, experiment, experiment_dir)
Tobias Langer committed
104 105

        # Add makefile & c++ file
106
        print('add Makefile', file=sys.stderr)
107 108
        makefile_path = os.path.join(experiment_dir, 'Makefile')
        shutil.copyfile(args.makefile, makefile_path)
109
        print('add C++ file', file=sys.stderr)
110 111
        cpp_file_path = os.path.join(experiment_dir, 'experiment.cpp')
        shutil.copyfile(args.cpp, cpp_file_path)
Tobias Langer committed
112 113 114

if __name__ == '__main__':
    main()