1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
|
#!/usr/bin/env python
# Remove ending PHP tags '?>'
# @author Oleg Pudeyev
# @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2
import sys, os, os.path, optparse
def error(message, code):
print >>sys.stderr, message
exit(code)
parser = optparse.OptionParser()
parser.add_option('-a', '--aggressive', help='Remove ending tags when they are followed by whitespace', action='store_true')
options, args = parser.parse_args()
if len(args) != 1:
parser.usage()
error("Usage: remove-php-end-tags path", 2)
path = args[0]
if not os.path.exists(path):
error("Path does not exist: %s" % path, 3)
if options.aggressive:
import re
fix_re = re.compile(r'\s*\?>\s*$')
def fix_content(content):
content = fix_re.sub(r'\n', content)
return content
else:
def fix_content(content):
if content.endswith('?>'):
content = content[:-2].strip() + "\n"
return content
def process_file(path):
f = open(path)
try:
content = f.read()
finally:
f.close()
fixed_content = fix_content(content)
if content != fixed_content:
f = open(path, 'w')
try:
f.write(fixed_content)
finally:
f.close()
def process_dir(path):
for root, dirs, files in os.walk(path):
if '.svn' in dirs:
dirs.remove('.svn')
for file in files:
if file.endswith('.php'):
path = os.path.join(root, file)
process_file(path)
if os.path.isdir(path):
process_dir(path)
else:
process_file(path)
|