Skip to content

Instantly share code, notes, and snippets.

@weaming weaming/sqlfmt.py
Created Apr 18, 2019

Embed
What would you like to do?
Format `mysqldump` sql file into editable style.
#!/usr/bin/env python3
# coding: utf-8
"""
Author : weaming
Created Time : 2019-04-18 15:18:31
"""
import sys
import argparse
class TextState:
last_2_state = None
last_1_state = None
state = None
levels = [] # (), ", ', `
wrap = False
def need_wrap(self):
rv = False
if self.wrap:
self.wrap = False
return True
if self.is_escaped():
return False
self.wrap = False
return rv
def forward(self, char):
self.last_2_state = self.last_1_state
self.last_1_state = self.state
self.state = char
if not self.is_escaped():
l12 = f"{self.last_1_state}{self.state}"
if char == "(" and self.level(-1) not in ["--", "/*"]:
self.levels.append("()")
if self.level(-2) == "()":
return char
else:
return "\n" + char
if not self.levels:
if l12 == "--":
self.levels.append("--")
elif l12 == "/*":
self.levels.append("/*")
elif char == "`":
self.levels.append("`")
else:
ll = self.levels[-1]
if ll == "()":
if char == '"':
self.levels.append('"')
elif char == "'":
self.levels.append("'")
for last, current in [
("()", ")"),
('"', '"'),
("'", "'"),
("`", "`"),
("--", "\n"),
("/*", "*/"),
]:
if ll == last and (char == current or l12 == current):
self.levels and self.levels.pop()
break
if self.need_wrap():
return char + "\n"
else:
return char
def level(self, n):
try:
return self.levels[n]
except IndexError:
return None
def is_escaped(self):
return (
self.level(-1) != "--"
and self.last_2_state != "\\"
and self.last_1_state == "\\"
)
def main(args):
with open(args.file) as f:
text = f.read()
sm = TextState()
with open(args.out, "w") as out:
for c in text:
v = sm.forward(c)
out.write(v)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("file")
parser.add_argument("-o", "--out", default="/dev/stdout")
args = parser.parse_args()
main(args)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.