Created
February 7, 2013 10:25
-
-
Save agateau/4730103 to your computer and use it in GitHub Desktop.
Handy tool to extract filename and line number from a line of text and open vi on it
This file contains hidden or 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 python | |
# encoding: utf-8 | |
import re | |
import os | |
import sys | |
import argparse | |
DESCRIPTION = """\ | |
Try to figure out a filename and line number from the command line arguments | |
and start vi on it. This is handy to quickly edit a faulty line by copy and | |
pasting from stderr. | |
For example, if stderr contains this: | |
file:///home/jdoe/project/source.qml:43: Unable to do assign null to QIcon | |
file:///home/jdoe/project/source.qml:43: Unable to do assign null to QIcon | |
file:///home/jdoe/project/source.qml:43: Unable to do assign null to QIcon | |
Running: | |
vl file:///home/jdoe/project/source.qml:43: Unable to do assign null to QIc | |
or: | |
vl file:///home/jdoe/project/source.qml:43: | |
Will open vi on /home/jdoe/project/source.qml, at line 43. | |
--- | |
""" | |
REGEXS = [ | |
r"^file://(.+?):(\d+)", | |
r"^(.+?):(\d+)", | |
r" *File \"?(.+?)\"?, line (\d+)", | |
] | |
class VlException(Exception): | |
pass | |
def parse(line): | |
for rx in REGEXS: | |
match = re.search(rx, line) | |
if match: | |
return match.group(1), match.group(2) | |
raise VlException() | |
def edit(name, number): | |
os.execlp("vi", "vi", name, "+" + number) | |
def main(): | |
parser = argparse.ArgumentParser( | |
description=DESCRIPTION, | |
formatter_class=argparse.RawDescriptionHelpFormatter | |
) | |
parser.add_argument("--dry-run", action="store_true", | |
help="Just parse the line, do not launch editor") | |
parser.add_argument("text", nargs=argparse.REMAINDER, | |
help="Line to parse") | |
args = parser.parse_args() | |
text = " ".join(args.text) | |
try: | |
name, number = parse(text) | |
except VlException: | |
print "ERROR: Could not extract file name and line number from `%s`" % text | |
return 1 | |
if args.dry_run: | |
print "file: %s\nline: %s" % (name, number) | |
return 0 | |
edit(name, number) | |
return 0 | |
if __name__ == "__main__": | |
sys.exit(main()) | |
# vi: ts=4 sw=4 et |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment