Skip to content
Snippets Groups Projects
Commit 27362112 authored by Hugo Hörnquist's avatar Hugo Hörnquist
Browse files

open: Docstrings.

parent c07d33f6
No related branches found
No related tags found
No related merge requests found
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Figure out the HTTP source of a remote, and open it in a browser."""
import sys import sys
import subprocess import subprocess
import argparse import argparse
import re import re
import os.path import os.path
def err(s):
"""Print error message."""
print("\x1b[0;31mError\x1b[m " + s, file=sys.stderr)
def warn(s):
"""Print warning message."""
print("\x1b[0;33mWarn\x1b[m " + s, file=sys.stderr)
def info(s):
"""Print info message."""
print("\x1b[0;32mInfo\x1b[m " + s, file=sys.stderr)
try: try:
# package python-pyxdg on Arch # package python-pyxdg on Arch
from xdg.BaseDirectory import xdg_config_dirs from xdg.BaseDirectory import xdg_config_dirs
except ModuleNotFoundError: except ModuleNotFoundError:
print("xdg module not found, defaulting to $HOME/.config", file=sys.stderr) warn("xdg module not found, defaulting to $HOME/.config")
import os import os
home = os.getenv("HOME") home = os.getenv("HOME")
xdg_config_dirs = [os.path.join(home, ".config")] xdg_config_dirs = [os.path.join(home, ".config")]
...@@ -20,8 +39,7 @@ try: ...@@ -20,8 +39,7 @@ try:
import yaml import yaml
can_load_configuration = True can_load_configuration = True
except ModuleNotFoundError: except ModuleNotFoundError:
print("yaml module not found, configuration will NOT be loaded", warn("yaml module not found, configuration will NOT be loaded")
file=sys.stderr)
configuration = { configuration = {
...@@ -31,6 +49,7 @@ configuration = { ...@@ -31,6 +49,7 @@ configuration = {
def popen(str): def popen(str):
"""Exec str, and return its stdout."""
p = subprocess.Popen(str.split(" "), p = subprocess.Popen(str.split(" "),
universal_newlines=True, universal_newlines=True,
stdout=subprocess.PIPE) stdout=subprocess.PIPE)
...@@ -42,15 +61,24 @@ def popen(str): ...@@ -42,15 +61,24 @@ def popen(str):
def gitconf(field): def gitconf(field):
"""Get git config field, or die."""
return popen("git config " + field) return popen("git config " + field)
def remote_url(remote_name): def remote_url(remote_name):
"""Get url for git remote by name."""
# return gitconf("remote.{}.url".format(remote_name)) # return gitconf("remote.{}.url".format(remote_name))
return popen(f'git remote get-url {remote_name}').strip() return popen(f'git remote get-url {remote_name}').strip()
def to_http(url): def to_http(url):
"""
Convert url into matching HTTP url.
Uses configuration['patterns'] to check for special cases,
otherwise anything starting with http is returned verbatim, and
git@ is replaced with https://.
"""
for pattern in configuration['patterns']: for pattern in configuration['patterns']:
if match := re.match(pattern['i'], url): if match := re.match(pattern['i'], url):
rx = re.compile('[$]([0-9]+)') rx = re.compile('[$]([0-9]+)')
...@@ -74,28 +102,33 @@ def to_http(url): ...@@ -74,28 +102,33 @@ def to_http(url):
def xdg_open(item): def xdg_open(item):
"""Run xdg-open on argument."""
subprocess.run(["xdg-open", item]) subprocess.run(["xdg-open", item])
def err(s):
print("\x1b[0;31mError\x1b[m " + s)
def warn(s):
print("\x1b[0;33mWarn\x1b[m " + s)
def info(s):
print("\x1b[0;32mInfo\x1b[m " + s)
def open_remote(remote): def open_remote(remote):
"""Open url for the named remote."""
url = to_http(remote_url(remote)) url = to_http(remote_url(remote))
xdg_open(url) xdg_open(url)
info(f'opening {url}') info(f'opening {url}')
def load_configuration():
"""Load configuration file, updates `configuration`."""
global configuration
# TODO possibly add ~/.config/git/open.yaml to list
for dir in xdg_config_dirs:
try:
with open(os.path.join(dir, 'git-open.yaml')) as f:
conf = yaml.unsafe_load(f)
configuration |= conf
break
except FileNotFoundError:
pass
def main(args): def main(args):
"""Entry point, args should come from ArgumentParser.parse_args."""
out = popen("git remote") out = popen("git remote")
remotes = out.strip().split("\n") remotes = out.strip().split("\n")
...@@ -127,19 +160,6 @@ def main(args): ...@@ -127,19 +160,6 @@ def main(args):
err("All remotes failed") err("All remotes failed")
def load_configuration():
global configuration
# TODO possibly add ~/.config/git/open.yaml to list
for dir in xdg_config_dirs:
try:
with open(os.path.join(dir, 'git-open.yaml')) as f:
conf = yaml.unsafe_load(f)
configuration |= conf
break
except FileNotFoundError:
pass
if __name__ == "__main__": if __name__ == "__main__":
# Note that argparse gives `--help' and `-h', but git "eats" # Note that argparse gives `--help' and `-h', but git "eats"
# `--help'. `-h' does however work. # `--help'. `-h' does however work.
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment