Skip to content

Instantly share code, notes, and snippets.

@meeuw
Created March 20, 2014 20:47
Show Gist options
  • Save meeuw/9673464 to your computer and use it in GitHub Desktop.
Save meeuw/9673464 to your computer and use it in GitHub Desktop.
git smudge filter to k&r style php code
#!/usr/bin/python
import sys
import re
CANTSMUDGE = '<?php //cantsmudgethis ?>'
class RewStream:
def __init__(self, holdlines=0):
self.holdlines = holdlines
self.current = 0
self.lines = []
def write(self, line):
self.lines.append([line,None])
def read(self):
if self.holdlines == None: holdlines = 0
else: holdlines = self.holdlines
for i in range(0, len(self.lines) - holdlines):
if self.holdlines != None:
self.current -= 1
line = self.lines.pop(0)
if line[1] == None: yield line[0]
else: yield line[1]
def getCurrent(self):
if self.lines[self.current][1] == None: return self.lines[self.current][0]
else: return self.lines[self.current][1]
def setCurrent(self, line):
self.lines[self.current][1] = line
def seek(self, where):
self.current += where
return self.current > 0
def seekback(self):
seeked = 0
while 1:
seeked += 1
s.seek(-1)
if s.getCurrent() != '': break
return seeked
def revert(self):
self.lines[self.current][1] = None
if sys.argv[1] == 'smudge':
s = RewStream(None)
cantsmudge = False
for inp in sys.stdin:
s.write(inp)
if cantsmudge:
while 1:
s.revert()
if not s.seek(-1):
s.setCurrent(CANTSMUDGE+s.getCurrent())
break
break
if '{' in s.getCurrent():
if len(s.getCurrent()) >= 2 and s.getCurrent()[-2] != '\r' and re.match('^( )*{$', s.getCurrent()):
seeked = s.seekback()
s.setCurrent(s.getCurrent()[:-1]+' {\n')
s.seek(seeked)
s.setCurrent('')
else:
cantsmudge = True
print >> sys.stderr, [s.getCurrent()]
continue
if re.match('^( )*else', s.getCurrent()):
cur = re.sub('^( )*', '', s.getCurrent())
seeked = s.seekback()
s.setCurrent(s.getCurrent()[:-1]+' '+cur)
s.seek(seeked)
s.setCurrent('')
for outpl in s.read():
sys.stdout.write(outpl)
s.seek(1)
for inp in sys.stdin: s.write(inp)
s.holdlines = 0
for outpl in s.read():
sys.stdout.write(outpl)
else:
s = RewStream(2)
first = True
cantsmudge = False
for inp in sys.stdin:
s.write(inp)
if first:
first = False
if s.getCurrent().startswith(CANTSMUDGE):
s.setCurrent(s.getCurrent()[len(CANTSMUDGE):])
cantsmudge = True
if not cantsmudge:
if ' {' in s.getCurrent():
m = re.match('^((?: )*)', s.getCurrent())
prefix = m.group(1)
s.setCurrent(s.getCurrent().replace(' {', '\n'+prefix+'{'))
if '} else' in s.getCurrent():
m = re.match('^((?: )*)', s.getCurrent())
prefix = m.group(1)
s.setCurrent(s.getCurrent().replace('} else', '}\n'+prefix+'else'))
for outpl in s.read():
sys.stdout.write(outpl)
s.seek(1)
s.holdlines = 0
for outpl in s.read():
sys.stdout.write(outpl)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment