summaryrefslogtreecommitdiff
path: root/ar/.config/qutebrowser/userscripts/gitclone
blob: ad62d1757dca2871041ca6210fd91bd471e3db8b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/bin/sh
#
# Author: palb91
# Date:   2022
#
# Clone a git repository directly from qutebrowser
#
# In config.py:
#   bind('gc', 'spawn -u -- gitclone')
#
#   # Run a shell command after successful clone
#   import os
#   os.environ['QUTE_POST_CLONE'] = 'notify-send "git clone" "${QUTE_URL}"'

set -e

# Local storage
BASE_DIR="${HOME}"/Public/repos
TEMP_DIR="$(mktemp -d)"

# Get informations from userscripts variables
QUTE_URL="${QUTE_URL%%\#*}"
QUTE_URL="${QUTE_URL%%\?*}"
QUTE_URL="${QUTE_URL%%\&*}"

DOMAIN="${QUTE_URL#*//}"
DOMAIN="${DOMAIN%%/*}"

REPO="${QUTE_URL#*"${DOMAIN}"/}"
REPO="${REPO%/}"
REPO="${REPO##*/}"
[ "${REPO#\.}" != "${REPO}" ] && REPO="_${REPO}"

BASE_REPO="${BASE_DIR}/${DOMAIN}/${REPO}"
TEMP_REPO="${TEMP_DIR}/${DOMAIN}/${REPO}"

# logging
info() { printf 'message-info    "%s"\n' "${*}" >>"${QUTE_FIFO}"; }
warn() { printf 'message-warning "%s"\n' "${*}" >>"${QUTE_FIFO}"; }
err() {
  printf 'message-error   "%s"\n' "${*}" >>"${QUTE_FIFO}"
  return 1
}
clean() {
  rm -rf "${TEMP_DIR}"
  exit "${1:-0}"
}

# Check repo exists
if [ -d "${BASE_REPO}"/.git ]; then
  warn "${REPO} already cloned in ${BASE_REPO}"
  clean 0

# Try cloning
else
  info "Cloning ${DOMAIN}/${REPO}..."
  git clone "${QUTE_URL}" "${TEMP_REPO}" ||
    err "Error while cloning ${DOMAIN}/${REPO}, is it a repository?"

  if [ ! -d "${TEMP_REPO}"/.git ]; then
    err 'An error occured, cloning failed...'
    clean 2
  fi
fi

# Move the temp folder to its final destination
[ -d "${BASE_REPO%/*}" ] || mkdir -p "${BASE_REPO%/*}"
mv "${TEMP_REPO}" "${BASE_REPO}"
info "${REPO} successfully cloned in ${BASE_REPO}"

# Run post hook
if [ -n "${QUTE_POST_CLONE}" ]; then
  eval "${QUTE_POST_CLONE}"
fi