summaryrefslogtreecommitdiff
path: root/maint/crates-io-utils.sh
blob: 1cb6e904927d071bc5788b02988a319f0100aa12 (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
75
76
77
# Utilities for querying crates.io

# Shellcheck is confused.
# It thinks it ought to be checking this as a standalone script, and prints
#   -- SC2148 (error): Tips depend on target shell and yours is unknown.
#             Add a shebang or a 'shell' directive.
# shellcheck shell=bash

CRATES_IO_URL_BASE=https://crates.io/api

fail () {
    echo >&2 "$0: error: $*"
    exit 12
}

tmp_trap_exit_setup () {
    if [ "$MAINT_DDLETE_CREATE_TMP" != "" ]; then
	rm -rf -- "$MAINT_DDLETE_CREATE_TMP"
	mkdir -- "$MAINT_DDLETE_CREATE_TMP"
	tmp="$MAINT_DDLETE_CREATE_TMP"
    else
	tmp=$(mktemp -d)
	trap 'set +e; rm -rf "$tmp"; exit $exit_rc' 0
    fi
    exit_rc=8
}

tmp_trap_exit_finish_status () {
    exit_rc=$1
}

tmp_trap_exit_finish_ok () {
    tmp_trap_exit_finish_status 0
}

# Queries
#   https://crates.io/api/$endpoint
# Expects to receive either
#   HTTP 200 and a json document which `jq "$expect_key"` accepts
#   HTTP 404 and a json document containing a `.errors` key
# The fetched document is stored in "$output"
# The HTTP code is left in the global variable `http_code`
# (and also written to "$output.http")
#
# There is a Python reimplementation `cargo-check-publishable`
# TODO: possibly, break that function out into a library and
#       replace this shell implementation with a veneer over the Python one.
crates_io_api_call () {
    local endpoint="$1"
    local expect_key="$2"
    local output="$3"

    local url="${CRATES_IO_URL_BASE}/$endpoint"

    sleep 1
    curl -A 'maint/ scripts for Tor Project CI (shell script)' \
	 -L -sS -o "$output" -w '%{http_code}' >"$output.http" "$url"
    http_code=$(cat "$output.http")

    case "$http_code" in
	200) expect="$expect_key" ;;
	404) expect=.errors ;;
	*)
	    cat -vet "$output" >&2
	    fail "unexpected HTTP response status code $http_code from $url"
	    ;;
    esac

    set +e
    jq -e "$expect" <"$output" >/dev/null
    jq_rc=$?
    set -e
    if [ $jq_rc != 0 ]; then
	cat -vet "$output" >&2
	fail "bad JSON data from $url (expected $expect)"
    fi
}