Created
November 13, 2012 06:15
-
-
Save adyliu/4064269 to your computer and use it in GitHub Desktop.
fixed wordpress rss error with blank lines
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
#-*- coding:utf-8 -*- | |
#author: adyliu([email protected]) | |
#version: 0.1 | |
import os | |
import os.path | |
import sys | |
DEBUG='--debug' in sys.argv | |
FIX ='--fix' in sys.argv | |
SUFFIX='.php' | |
ENCODING='utf-8' | |
if len(sys.argv) < 2: | |
print('Usage: [--debug] [--fix] <file>') | |
sys.exit(1) | |
def checkdir(filepath): | |
if DEBUG: print('check file',filepath) | |
if os.path.isdir(filepath): | |
for fname in os.listdir(filepath): | |
checkdir(os.path.join(filepath,fname)) | |
if os.path.isfile(filepath) and filepath.endswith(SUFFIX): | |
fail=True | |
fixedmsg = '' | |
try: | |
lines=[] | |
with open(filepath,'r',encoding=ENCODING,errors='ignore') as f: | |
lines=f.readlines() | |
fail=len(lines)>0 and (len(lines[0].strip())==0 or len(lines[-1].strip()) ==0) | |
if fail and FIX: | |
start,end = 0,0 | |
for i in range(len(lines)): | |
if len(lines[i].strip()) >0: | |
start = i | |
break | |
i=len(lines) | |
while i> 0: | |
if len(lines[i-1].strip()) >0: | |
end = i | |
break | |
i -= 1 | |
with open(filepath,'w',encoding=ENCODING) as f: | |
for line in lines[start:end]: | |
if DEBUG: print(line) | |
f.write(line) | |
if DEBUG: print('write lines[%s:%s], total=%s'%(start,end,len(lines))) | |
fixedlines = start + len(lines) - end | |
fixedmsg = 'FIXED %s lines' % (fixedlines,) | |
finally: | |
if DEBUG or fail: | |
print(filepath,'=>','FAIL' if fail else 'OK',fixedmsg) | |
checkdir(os.path.abspath(sys.argv[-1])) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment