Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
BBEdit script to open the file I'm looking at in github and copy the URL to my pasteboard
#!/usr/local/bin/python3
import os
import re
import subprocess
from typing import Optional, Sequence
from pathlib import Path, PurePath
doc_path: Optional[str] = os.getenv('BB_DOC_PATH')
if doc_path is None:
pass
else:
path = Path(doc_path)
directory = path
line = int(os.getenv('BB_DOC_SELSTART_LINE') or 1)
if not path.is_dir():
directory = path.parent
def write_to_clipboard(output: str) -> None:
process = subprocess.Popen(
'pbcopy', env={'LANG': 'en_US.UTF-8'}, stdin=subprocess.PIPE)
process.communicate(output.encode('utf-8'))
def read_command(command: Sequence[str], cwd: Path) -> Optional[str]:
process = subprocess.Popen(
command, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
bytes, _ = process.communicate()
if len(bytes) > 0:
return bytes.decode('utf-8')
else:
return None
origin = read_command(["git", "remote", "get-url", "origin"], directory)
branch = read_command(
["git", "rev-parse", "--abbrev-ref", "HEAD"], directory)
if origin is None:
pass
elif branch is None:
pass
else:
branch = branch.rstrip()
matches = re.match("git@github.com:(.*)\.git", origin)
match = matches[1]
(account, repo_name) = PurePath(match).parts
dest = []
reached = False
for part in path.parts:
if part == repo_name:
reached = True
elif reached:
dest.append(part)
joined = os.path.join(account, repo_name, 'tree', branch, *dest)
if line > 1:
url = "https://github.com/%s#L%s" % (joined, line)
else:
url = "https://github.com/%s" % joined
write_to_clipboard(url)
subprocess.call(["/usr/bin/open", url])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment