Skip to content

Commit 7573462

Browse files
committed
[utils] Refactor split_file.py
* Migrate to argparse * Ability to input from STDIN
1 parent ddd2f1e commit 7573462

File tree

1 file changed

+28
-32
lines changed

1 file changed

+28
-32
lines changed

utils/split_file.py

+28-32
Original file line numberDiff line numberDiff line change
@@ -1,50 +1,46 @@
11
#!/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
215

3-
"""
4-
split_file.py [-o <dir>] <path>
5-
16+
parser = argparse.ArgumentParser(
17+
description="""
618
Take the file at <path> and write it to multiple files, switching to a new file
719
every time an annotation of the form "// BEGIN file1.swift" is encountered. If
820
<dir> is specified, place the files in <dir>; otherwise, put them in the
921
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()
2132

2233
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')
3834

39-
for line in fp_in:
35+
for line in args.input:
4036
m = re.match(r'^//\s*BEGIN\s+([^\s]+)\s*$', line)
4137
if m:
4238
if fp_out:
4339
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')
4541
elif fp_out:
4642
fp_out.write(line)
4743

48-
fp_in.close()
44+
args.input.close()
4945
if fp_out:
5046
fp_out.close()

0 commit comments

Comments
 (0)