|
- #!/usr/bin/env bash
- if [[ $# -eq 0 || "$1" == @(--help|-h) ]]; then
- printf 'Usage: ia-metadata ITEM [CHANGE...]\n' >&2
- printf 'Reads or modifies metadata of an item or file in an item\n' >&2
- printf 'Each CHANGE consists of two or more arguments: an operation, a field, and potentially variable further arguments for the operation.\n' >&2
- printf 'The following operations are supported:\n' >&2
- printf ' append FIELD VALUE appends a value to a list field\n' >&2
- printf ' remove FIELD VALUE removes the first appearance of the value in a list field\n' >&2
- printf ' set FIELD VALUE sets the field to the value; any existing value is overwritten\n' >&2
- printf ' unset FIELD removes the field\n' >&2
- exit 1
- fi
-
- if (($# == 1)); then
- # Read
- curl --silent --show-error --user-agent 'little-things +https://gitea.arpa.li/JustAnotherArchivist/little-things' "https://archive.org/metadata/$1"
- st="$?"
-
- # Emit an LF terminator if stdout is a TTY
- [[ -t 1 ]] && printf '\n'
-
- exit "${st}"
- fi
-
- # Write
- #TODO Add 'test' operations to ensure the local state matches what's in the item: https://archive.org/developers/md-write-adv.html#use-the-test-operator
- target="$1"
- shift
- args=()
- while (($#)); do
- case "$1" in
- append)
- (($# >= 3)) || { printf 'Error: expected two arguments on append\n' >&2; exit 1; }
- args+=(op add path "/$2/-" value "$3")
- shift 3
- ;;
- remove)
- printf 'Error: remove is currently unsupported due to a an apparent bug on the Internet Archive side\n' >&2
- exit 1
- (($# >= 3)) || { printf 'Error: expected two arguments on remove\n' >&2; exit 1; }
- # IA extension to JSON Patch
- args+=(op remove-first path "/$2" value "$3")
- shift 3
- ;;
- set)
- (($# >= 3)) || { printf 'Error: expected two arguments on set\n' >&2; exit 1; }
- args+=(op add path "/$2" value "$3")
- shift 3
- ;;
- unset)
- (($# >= 2)) || { printf 'Error: expected an argument on unset\n' >&2; exit 1; }
- args+=(op remove path "/$2")
- shift 2
- ;;
- *)
- printf 'Error: invalid operation %q\n' "$1" >&2
- exit 1
- ;;
- esac
- done
-
- patch="$(jq --null-input --compact-output '$ARGS.positional | . as $arr | [range(0; length/2) * 2 | $arr[. : . + 2]] | reduce .[] as [$key, $value] ([]; if $key == "op" then . += [{($key): $value}] elif .[-1][$key] then if .[-1][$key] | type == "array" then .[-1][$key] += [$value] else .[-1][$key] = [.[-1][$key], $value] end else .[-1] += {($key): $value} end)' --args "${args[@]}")"
-
- "$(cd "$(dirname "$0")"; pwd -P)/curl-ia" header --silent --show-error --user-agent 'little-things +https://gitea.arpa.li/JustAnotherArchivist/little-things' --form '-target=metadata' --form "-patch=${patch}" "https://archive.org/metadata/${target}"
- st="$?"
- [[ -t 1 ]] && printf '\n'
- exit "${st}"
|