Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
unasync rewriter
"""
remove code from unasync-generated code wherever there is a `unasync: remove` comment is placed
MIT License
Copyright (c) 2022 Spencer Phillip Young
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import argparse
import ast
from tokenize_rt import src_to_tokens
from tokenize_rt import tokens_to_src
from tokenize_rt import reversed_enumerate
def _rewrite_file(filename: str) -> int:
with open(filename, encoding='UTF-8') as f:
contents = f.read()
tree = ast.parse(contents, filename=filename)
tokens = src_to_tokens(contents)
nodes_on_lines_to_remove = []
for tok in tokens:
if tok.name == 'COMMENT' and 'unasync: remove' in tok.src:
nodes_on_lines_to_remove.append(tok.line)
lines_to_remove = set()
for node in ast.walk(tree):
if hasattr(node, 'lineno') and node.lineno in nodes_on_lines_to_remove:
for lineno in range(node.lineno, node.end_lineno + 1):
lines_to_remove.add(lineno)
for i, tok in reversed_enumerate(tokens):
if tok.line in lines_to_remove:
tokens.pop(i)
new_contents = tokens_to_src(tokens)
with open(filename, 'w') as f:
f.write(new_contents)
return new_contents != contents
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument('sync_root', help='The root directory containing sync code generated by unasync')
args = parser.parse_args()
ret = 0
for root, dirs, files in os.walk(args.sync_root):
for fname in files:
if fname.endswith('.py'):
fp = os.path.join(root, fname)
ret |= _rewrite_file(fp)
return ret
if __name__ == '__main__':
raise SystemExit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment