penguin/utils

my env utils

bash/core/20_io.bash

raw ยท 1493 bytes

rbash_url() {
  local path="$1"
  printf '%s/%s/raw/%s/%s/%s\n' \
    "$RBASH_REMOTE" "$RBASH_REPO" "$RBASH_REF" "$RBASH_PATH" "$path"
}

rbash_download() {
  local url="$1"

  if command -v curl >/dev/null 2>&1; then
    curl -fsSL "$url" || {
      local rc=$?
      echo "rbash: download failed: $url" >&2
      echo "rbash: curl exit code: $rc" >&2
      return "$rc"
    }
  elif command -v wget >/dev/null 2>&1; then
    wget -qO- "$url" || {
      local rc=$?
      echo "rbash: download failed: $url" >&2
      echo "rbash: wget exit code: $rc" >&2
      return "$rc"
    }
  else
    echo "rbash: curl or wget is required" >&2
    return 127
  fi
}

rbash_cache() {
  local url="$1"
  local key file

  if [ -z "${RBASH_CACHE_DIR:-}" ]; then
    echo "rbash: RBASH_CACHE_DIR is not set" >&2
    return 1
  fi

  mkdir -p "$RBASH_CACHE_DIR" || {
    echo "rbash: failed to create cache dir: $RBASH_CACHE_DIR" >&2
    return 1
  }

  if command -v md5sum >/dev/null 2>&1; then
    key="$(printf '%s' "$url" | md5sum | cut -d' ' -f1)"
  else
    key="$(printf '%s' "$url" | md5 | cut -d' ' -f1)"
  fi

  file="$RBASH_CACHE_DIR/$key"

  if [ ! -f "$file" ]; then
    rbash_download "$url" > "$file" || {
      local rc=$?
      rm -f "$file"
      echo "rbash: download failed: $url" >&2
      return "$rc"
    }
    chmod 700 "$file"
  fi

  printf '%s\n' "$file"
}

_require_jq() {
  if ! command -v jq >/dev/null 2>&1; then
    echo "This command requires jq." >&2
    return 1
  fi
}