source: branches/active/character_customization/game/utilities/convert_dialogue.py @ 736

Revision 736, 3.9 KB checked in by aspidites, 8 years ago (diff)

Patch by Aspidites:

  • renamed scripts package to parpg
  • renamed parpg module to application
  • removed packaging and other related files (kept locally for reference, will reintroduce similar scripts to resolve bug #275
  • updated all import statements to respect changes above
  • Property svn:executable set to *
  • Property svn:mime-type set to text/plain
Line 
1#!/usr/bin/env python
2"""Convert YAML dialogue files from the Techdemo1 format to the new Techdemo2
3format.
4
5@author: M. George Hansen <technopolitica@gmail.com>
6"""
7import os.path
8import sys
9sys.path.append(os.path.realpath(os.path.join(os.path.dirname(sys.argv[0]),
10                                 os.path.pardir)))
11import shutil
12import logging
13
14from parpg.common.optionparser import OptionParser
15from parpg.dialogueparser import (OldYamlDialogueParser, YamlDialogueParser,
16    DialogueFormatError)
17
18def backup_file(filepath):
19    dirpath = os.path.dirname(filepath)
20    filename = os.path.basename(filepath)
21   
22    shutil.copy2(filepath, os.path.join(dirpath,
23                                        '.'.join([filename, 'backup'])))
24
25def convert_dialogue_file(filepath, backup):
26    logging.info('processing {0}...'.format(filepath))
27    dummy, extension = os.path.splitext(filepath)
28    if (not extension == '.yaml'):
29        logging.info('    skipping {0}: not a yaml file'.format(filepath))
30        return 1
31    with file(filepath, 'r') as dialogue_file:
32        old_parser = OldYamlDialogueParser()
33        new_parser = YamlDialogueParser()
34        try:
35            dialogue = old_parser.load(dialogue_file)
36        except DialogueFormatError as error:
37            logging.info(
38                '    unable to convert {0}: unrecognized dialogue format'
39                .format(filepath)
40            )
41            return 1
42    if (backup):
43        backup_file(filepath)
44    logging.info('    backed up {0} as {0}.backup'.format(filepath))
45    with file(filepath, 'w') as dialogue_file:
46        new_parser.dump(dialogue, dialogue_file)
47    logging.info('    successfully converted {0}!'.format(filepath))
48
49usage_message = '''\
50usage: convert_dialogue.py [-h] [-n] [-v] [-q] file_or_dir
51Convert YAML dialogue files written in Techdemo1 syntax to the new Techdemo2
52syntax.
53
54    -h, --help             show this help message
55    -n, --no-backup        don't backup files before converting them
56    -v, --verbose          increase the verbosity of the script logger; may be
57                               specified multiple times to increase the logger
58                               output
59    -q, --quiet            decrease the verbosity of the script logger; may be
60                              specified multiple times to decrease the logger
61                              output
62
63If the file_or_dir argument is a directory, then this script will attempt to
64convert all .yaml files in the directory that contain valid dialogues.
65
66By default all processed files are first backed up by adding a ".backup" suffix
67to the filename + extension. Backups can be disabled by passing the -n option
68to the script.
69'''
70
71def main(argv=sys.argv):
72    # Options.
73    backup = True
74    logging_level = logging.WARNING
75   
76    option_parser = OptionParser(usage=usage_message, args=argv[1:])
77    for option in option_parser:
78        if (option == '-h' or option == '--help'):
79            print(option_parser.usage)
80            sys.exit(0)
81        elif (option == '-n' or option == '--no-backup'):
82            backup = False
83        elif (option == '-v' or option == '--verbose'):
84            logging_level -= 10
85        elif (option == '-q' or option == '--quiet'):
86            logging_level += 10
87        else:
88            # invalid option
89            message = '"{0}" is not a valid argument or option'.format(option)
90            option_parser.error(message)
91    logging.basicConfig(format='%(message)s', level=logging_level,
92                        stream=sys.stdout)
93   
94    path = option_parser.get_next_prog_arg()
95    if (os.path.isdir(path)):
96        for filepath in os.listdir(path):
97            qualified_filepath = os.path.join(path, filepath)
98            if (not os.path.isfile(qualified_filepath)):
99                continue
100            convert_dialogue_file(qualified_filepath, backup=backup)
101    else:
102        convert_dialogue_file(path, backup=backup)
103
104if __name__ == '__main__':
105    main()
Note: See TracBrowser for help on using the repository browser.