-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpush-to-gh
More file actions
executable file
·107 lines (79 loc) · 2.35 KB
/
push-to-gh
File metadata and controls
executable file
·107 lines (79 loc) · 2.35 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#!/usr/bin/env zsh
# Dependencies: yq, gh, jq, git, python3
set -o ERR_EXIT
function main() {
if [ $# -lt 1 ]; then
echo "USAGE ${0:t} FILE..."
return 1
fi
for f in "$@"; do
echo "$f"
push-one-file "$f" || true
echo ""
done
}
function push-one-file() {
file_path="$1:A"
file_name="${file_path:t}"
file_content="$(<"$file_path")"
file_content_lines=( "${(@f)file_content}" )
if [ "${file_content_lines[1]}" != "---" ]; then
echo "The input file doesn't contain frontmatter."
return 2
fi
file_content_lines=( ${file_content_lines[2,-1]} )
idx="${file_content_lines[(i)---]}"
if [ "$idx" -ge "${#file_content_lines}" ]; then
echo "The input file doesn't contain frontmatter - no terminator."
return 2
fi
frontmatter=( ${file_content_lines[1,$idx-1]} )
frontmatter="${(j:\n:)frontmatter}"
upstream="$(echo "$frontmatter" | yq .upstream)"
if [ -z "$upstream" -o "$upstream" = "null" ]; then
echo "The frontmatter doesn't contain a \"upstream\" key."
return 3
fi
if ! [[ -o extendedglob ]]; then
setopt -o extendedglob
upstream=${upstream##/#}
upstream=${upstream%%/#}
setopt +o extendedglob
fi
the_repo="${upstream:h2}"
the_path="${upstream#$the_repo/}"
if [ -z "$the_repo" -o -z "$the_path" ]; then
echo "The \"upstream\" field in frontmatter is invalid."
return 4
fi
the_api_url="$(urlencode repos/"$the_repo"/contents/"$the_path"/"$file_name")"
file_upstream="$(gh api "$the_api_url" 2>/dev/null || true)"
file_upstream_sha="$(jq <<<"$file_upstream" ".sha" -r)"
if [ "$file_upstream_sha" = 'null' ]; then
file_upstream_sha=""
fi
file_sha_local="$(git hash-object -t blob "$file_path")"
if [ "$file_sha_local" = "$file_upstream_sha" ]; then
jq <<<"$file_upstream" ".html_url" -r
printf 'Up-to-date\n'
return 0
fi
gh_args=(
-H "Accept: application/vnd.github+json"
-H "X-GitHub-Api-Version: 2022-11-28"
)
jq <<<0 --rawfile the_input_file "$file_path" --arg sha "$file_upstream_sha" '
{
message: "Sync",
content: ($the_input_file | @base64)
}
| if ($sha | length) >= 7 then . += {sha: $sha} end
' - \
| gh api -X PUT "${gh_args[@]}" --input - --jq '"\(.content.html_url)\n\(.commit.html_url)"' "$the_api_url"
}
function urlencode() {
python3 -c 'import sys, urllib.parse; print(urllib.parse.quote(sys.argv[1]))' "$1"
}
if [ "${zsh_eval_context[-1]}" != "file" ]; then
main "$@"
fi