|
1 | 1 | #!/usr/bin/env python
|
| 2 | +# |
| 3 | +# This source file is part of the Swift.org open source project |
| 4 | +# |
| 5 | +# Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors |
| 6 | +# Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +# |
| 8 | +# See http://swift.org/LICENSE.txt for license information |
| 9 | +# See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | + |
| 11 | +import argparse |
| 12 | +import os |
| 13 | +import re |
| 14 | +import sys |
2 | 15 |
|
3 |
| -""" |
4 |
| -split_file.py [-o <dir>] <path> |
5 |
| -
|
| 16 | +parser = argparse.ArgumentParser( |
| 17 | + description=""" |
6 | 18 | Take the file at <path> and write it to multiple files, switching to a new file
|
7 | 19 | every time an annotation of the form "// BEGIN file1.swift" is encountered. If
|
8 | 20 | <dir> is specified, place the files in <dir>; otherwise, put them in the
|
9 | 21 | current directory.
|
10 |
| -""" |
11 |
| - |
12 |
| -import getopt |
13 |
| -import os |
14 |
| -import re |
15 |
| -import sys |
16 |
| - |
17 |
| - |
18 |
| -def usage(): |
19 |
| - sys.stderr.write(__doc__.strip() + "\n") |
20 |
| - sys.exit(1) |
| 22 | +""") |
| 23 | +parser.add_argument( |
| 24 | + "-o", dest="out_dir", default=".", metavar="<dir>", |
| 25 | + help="directory path where the output files are placed in. " |
| 26 | + "(defaults to current directory)") |
| 27 | +parser.add_argument( |
| 28 | + "input", type=argparse.FileType("r"), nargs="?", default=sys.stdin, |
| 29 | + metavar="<path>", |
| 30 | + help="input file. (defaults to stdin)") |
| 31 | +args = parser.parse_args() |
21 | 32 |
|
22 | 33 | fp_out = None
|
23 |
| -dest_dir = '.' |
24 |
| - |
25 |
| -try: |
26 |
| - opts, args = getopt.getopt(sys.argv[1:], 'o:h') |
27 |
| - for (opt, arg) in opts: |
28 |
| - if opt == '-o': |
29 |
| - dest_dir = arg |
30 |
| - elif opt == '-h': |
31 |
| - usage() |
32 |
| -except getopt.GetoptError: |
33 |
| - usage() |
34 |
| - |
35 |
| -if len(args) != 1: |
36 |
| - usage() |
37 |
| -fp_in = open(args[0], 'r') |
38 | 34 |
|
39 |
| -for line in fp_in: |
| 35 | +for line in args.input: |
40 | 36 | m = re.match(r'^//\s*BEGIN\s+([^\s]+)\s*$', line)
|
41 | 37 | if m:
|
42 | 38 | if fp_out:
|
43 | 39 | fp_out.close()
|
44 |
| - fp_out = open(os.path.join(dest_dir, m.group(1)), 'w') |
| 40 | + fp_out = open(os.path.join(args.out_dir, m.group(1)), 'w') |
45 | 41 | elif fp_out:
|
46 | 42 | fp_out.write(line)
|
47 | 43 |
|
48 |
| -fp_in.close() |
| 44 | +args.input.close() |
49 | 45 | if fp_out:
|
50 | 46 | fp_out.close()
|
0 commit comments