Created
January 5, 2017 04:16
-
-
Save ysimonson/f0bf41d773ed1aaeab4940c5a7e45604 to your computer and use it in GitHub Desktop.
Replaces all instances of try! in a rust codebase with the ? operator. I used this because I can't use rustfmt.
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
import os | |
import re | |
import sys | |
TRY_PATTERN = re.compile(r"try!\(") | |
def replace_try(contents): | |
match = TRY_PATTERN.search(contents) | |
if match: | |
span = match.span(0) | |
before = contents[:span[0]] | |
after = contents[span[1]:] | |
paren_count = 0 | |
for i, c in enumerate(after): | |
if c == "(": | |
paren_count += 1 | |
elif c == ")": | |
if paren_count == 0: | |
after = after[:i] + "?" + after[i+1:] | |
break | |
elif paren_count < 0: | |
raise Exception() | |
else: | |
paren_count -= 1 | |
return replace_try(before + after) | |
else: | |
return contents | |
def main(dir): | |
for root, _, files in os.walk(dir): | |
for filename in files: | |
if filename.endswith(".rs"): | |
with open(os.path.join(root, filename), "r") as f: | |
contents = f.read() | |
contents = replace_try(contents) | |
with open(os.path.join(root, filename), "w") as f: | |
f.write(contents) | |
if __name__ == "__main__": | |
# To run: python3 rust_try_replacer.py <root dir of rust codebase> | |
main(sys.argv[1]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment