Skip to content

Instantly share code, notes, and snippets.

@kbussell
Last active May 11, 2020
Embed
What would you like to do?
open file references from terminal text

Installation

  • Find phpstorm.sh
    • locate -b phpstorm.sh
    • Either put that in your $PATH, or symlink it somewhere easy to find
  • Save the openfile.py script somewhere on your path, and make it executable
  • Edit your copy to update LOCAL_ROOT, LOG_FILENAME, PHP_STORM_SCRIPT
  • Set a Gnome keyboard shortcut to run the script
#!/home/keith/.pyenv/shims/python3
import logging
import os
import re
import subprocess
php_re = re.compile(r"(.+)/(\w+\.php)\((\d+)\)")
LOCAL_ROOT = "/home/keith/Projects/tradesy/core"
LOG_FILENAME = "/tmp/opener.log"
PHP_STORM_SCRIPT = "/home/keith/.local/bin/phpstorm"
def configure_logger():
logger_ = logging.getLogger('openfile')
handler = logging.FileHandler(LOG_FILENAME)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
logger_.addHandler(handler)
logger_.setLevel(logging.DEBUG)
return logger_
logger = configure_logger()
def rebuild_path(path):
tradesy_part_no = None
parts = path.split('/')
for index, part in enumerate(parts):
if part.startswith('tradesy'):
tradesy_part_no = index
break
if not tradesy_part_no:
logger.warning(f"Can't find tradesy path in: {path}")
return None
new_path = os.path.join(LOCAL_ROOT, *parts[tradesy_part_no:])
logger.debug("rebuild_path: %s", new_path)
return new_path
def open_php(path, filename, line_no):
# assume we're looking for a subpath starting with 'tradesy'
logger.debug("open_php: %s / %s (%s)", path, filename, line_no)
full_path = os.path.join(rebuild_path(path), filename)
cmd = [PHP_STORM_SCRIPT, "--line", line_no, full_path]
logger.debug("Running command: %s", " ".join(cmd))
subprocess.run(cmd)
def handle_selection(text):
m = php_re.match(text)
if m:
open_php(*m.groups())
else:
logger.warning(f"handle_selection: no handler for '%s'", text)
def main():
sel = subprocess.run("xsel", capture_output=True, shell=True)
handle_selection(sel.stdout.decode('utf-8'))
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment