diff options
author | typebrook <typebrook@gmail.com> | 2020-02-16 19:54:32 +0800 |
---|---|---|
committer | typebrook <typebrook@gmail.com> | 2020-02-16 19:54:32 +0800 |
commit | 3a1654819edf6492b6510e55a8b0b18871fcf37b (patch) | |
tree | 6970c2d67770ab07c5f231a90176a99532ac2654 | |
parent | 189b99d83c4f5911f6e3ed58f58ca1d1ce385c75 (diff) |
update
-rw-r--r-- | alias | 3 | ||||
l---------[-rwxr-xr-x] | scripts/gist | 609 |
2 files changed, 2 insertions, 610 deletions
@@ -264,8 +264,7 @@ alias cdW='cd ~/git/geoBingAnWeb' | |||
264 | alias and='cd ~/git/geoBingAn.Android' | 264 | alias and='cd ~/git/geoBingAn.Android' |
265 | alias cdT='cd ~/git/taiwan-topo' | 265 | alias cdT='cd ~/git/taiwan-topo' |
266 | alias cdand='cd ~/git/sample' | 266 | alias cdand='cd ~/git/sample' |
267 | alias cdm='cd ~/git/sharkbig.github.io/rescue' | 267 | alias cdm='cd ~/git/Bash-Snippets/gist' |
268 | alias cdmw='cd ~/git/sharkbig.github.io/.github/workflows' | ||
269 | 268 | ||
270 | TAIWAN_BBOX='118.1036,20.72799,122.9312,26.60305' | 269 | TAIWAN_BBOX='118.1036,20.72799,122.9312,26.60305' |
271 | TAIWAN_BBOX_V='20.72799,118.1036,26.60305,122.9312' | 270 | TAIWAN_BBOX_V='20.72799,118.1036,26.60305,122.9312' |
diff --git a/scripts/gist b/scripts/gist index cafe44a..aef983c 100755..120000 --- a/scripts/gist +++ b/scripts/gist | |||
@@ -1,608 +1 @@ | |||
1 | #!/usr/bin/env bash | /home/jojo/git/Bash-Snippets/gist/gist \ No newline at end of file | |
2 | # | ||
3 | # Author: Hsieh Chin Fan (typebrook) <typebrook@gmail.com> | ||
4 | # License: MIT | ||
5 | # https://gist.github.com/typebrook/b0d2e7e67aa50298fdf8111ae7466b56 | ||
6 | # | ||
7 | # gist | ||
8 | # Description: Manage your gists with git and Github API v3 | ||
9 | # Usage: gist [command] [<args>] | ||
10 | # | ||
11 | # [star | s] List your gists with format below, star for your starred gists: | ||
12 | # [index_of_gist] [url] [file_num] [comment_num] [short description] | ||
13 | # fetch, f [star | s] Update the local list of your gists, star for your starred gists | ||
14 | # <index_of_gist> [--no-action] Show the path of local gist repo and do custom actions | ||
15 | # new, n [-d | --desc <description>] [-p] <files>... create a new gist with files | ||
16 | # new, n [-d | --desc <description>] [-p] [-f | --file <file_name>] create a new gist from STDIN | ||
17 | # detail, d <index_of_gist> Show the detail of a gist | ||
18 | # edit, e <index_of_gist> Edit a gist's description | ||
19 | # delete, D <index_of_gist>... Delete a gist | ||
20 | # clean, C Clean removed gists in local | ||
21 | # config, c [token | user | folder | auto_sync | EDITOR | action [value] ] Do configuration | ||
22 | # user, U <user> Get gists from a given Github user | ||
23 | # grep, g <pattern> Grep gists by a given pattern | ||
24 | # push, p <index_of_gist> Push changes by git (well, better to make commit by youself) | ||
25 | # github, G <index_of_gist> Import selected gist as a new Github repo | ||
26 | # help, h Show this help message | ||
27 | # version Get the tool version | ||
28 | # update Update Bash-Snippet Tools | ||
29 | # | ||
30 | # Example: | ||
31 | # gist (Show your gists) | ||
32 | # gist update (update the list of gists from github.com) | ||
33 | # gist 3 (show the repo path of your 3rd gist, and do custom actions) | ||
34 | # gist 3 --no-action (show the repo path of your 3rd gist, and do not perform actions) | ||
35 | # gist new --desc bar foo (create a new gist with file and description) | ||
36 | # | ||
37 | # Since now a gist is a local cloned repo | ||
38 | # It is your business to do git commit and git push | ||
39 | |||
40 | currentVersion="1.23.0" | ||
41 | configuredClient="" | ||
42 | |||
43 | GITHUB_API=https://api.github.com | ||
44 | CONFIG=~/.config/gist.conf; mkdir -p ~/.config | ||
45 | |||
46 | folder=~/gist && mkdir -p $folder | ||
47 | action="${EDITOR:-vi} ." | ||
48 | auto_sync=true # automatically clone the gist repo | ||
49 | [[ -z $hint ]] && hint=true # default to show hint with list of gist | ||
50 | |||
51 | # Shell configuration | ||
52 | set -o pipefail | ||
53 | [[ $TRACE == 'true' ]] && set -x | ||
54 | [[ $(uname) == 'Darwin' ]] && alias tac='tail -r' | ||
55 | trap 'rm -f "$http_data" "$tmp_file"' EXIT | ||
56 | |||
57 | # This function determines which http get tool the system has installed and returns an error if there isnt one | ||
58 | getConfiguredClient() { | ||
59 | if command -v curl &>/dev/null; then | ||
60 | configuredClient="curl" | ||
61 | elif command -v wget &>/dev/null; then | ||
62 | configuredClient="wget" | ||
63 | elif command -v http &>/dev/null; then | ||
64 | configuredClient="httpie" | ||
65 | else | ||
66 | echo "Error: This tool requires either curl, wget, or httpie to be installed." >&2 | ||
67 | return 1 | ||
68 | fi | ||
69 | } | ||
70 | |||
71 | # Allows to call the users configured client without if statements everywhere | ||
72 | # TODO return false if code is not 20x | ||
73 | http_method() { | ||
74 | local METHOD=$1; shift | ||
75 | local header_opt; local header; local data_opt | ||
76 | case "$configuredClient" in | ||
77 | curl) [[ -n $token ]] && header_opt="--header" header="Authorization: token $token" | ||
78 | [[ $METHOD =~ (POST|PATCH) ]] && data_opt='--data' | ||
79 | curl -X "$METHOD" -A curl -s $header_opt "$header" $data_opt "@$http_data" "$@" ;; | ||
80 | wget) [[ -n $token ]] && header_opt="--header" header="Authorization: token $token" | ||
81 | [[ $METHOD =~ (POST|PATCH) ]] && data_opt='--body-file' | ||
82 | wget --method="$METHOD" -qO- $header_opt "$header" $data_opt "$http_data" "$@" ;; | ||
83 | httpie) [[ -n $token ]] && header="Authorization:token $token" | ||
84 | [[ $METHOD =~ (POST|PATCH) ]] && data_opt="@$http_data" | ||
85 | http -b "$METHOD" "$@" "$header" "$data_opt" ;; | ||
86 | esac | ||
87 | } | ||
88 | |||
89 | httpGet(){ | ||
90 | http_method GET "$@" | ||
91 | } | ||
92 | |||
93 | # parse JSON from STDIN with string of commands | ||
94 | _process_json() { | ||
95 | PYTHONIOENCODING=utf-8 \ | ||
96 | python -c "from __future__ import print_function; import sys, json; $1" | ||
97 | return "$?" | ||
98 | } | ||
99 | |||
100 | checkInternet() { | ||
101 | httpGet github.com 2>&1 || { echo "Error: no active internet connection" >&2; return 1; } # query github with a get request | ||
102 | } | ||
103 | |||
104 | update() { | ||
105 | # Author: Alexander Epstein https://github.com/alexanderepstein | ||
106 | # Update utility version 2.2.0 | ||
107 | # To test the tool enter in the defualt values that are in the examples for each variable | ||
108 | repositoryName="Bash-Snippets" #Name of repostiory to be updated ex. Sandman-Lite | ||
109 | githubUserName="alexanderepstein" #username that hosts the repostiory ex. alexanderepstein | ||
110 | nameOfInstallFile="install.sh" # change this if the installer file has a different name be sure to include file extension if there is one | ||
111 | latestVersion=$(httpGet https://api.github.com/repos/$githubUserName/$repositoryName/tags | grep -Eo '"name":.*?[^\\]",'| head -1 | grep -Eo "[0-9.]+" ) #always grabs the tag without the v option | ||
112 | |||
113 | if [[ $currentVersion == "" || $repositoryName == "" || $githubUserName == "" || $nameOfInstallFile == "" ]]; then | ||
114 | echo "Error: update utility has not been configured correctly." >&2 | ||
115 | exit 1 | ||
116 | elif [[ $latestVersion == "" ]]; then | ||
117 | echo "Error: no active internet connection" >&2 | ||
118 | exit 1 | ||
119 | else | ||
120 | if [[ $latestVersion != "$currentVersion" ]]; then | ||
121 | echo "Version $latestVersion available" | ||
122 | echo -n "Do you wish to update $repositoryName [Y/n]: " | ||
123 | read -r answer | ||
124 | if [[ $answer == [Yy] ]]; then | ||
125 | cd ~ || { echo 'Update Failed'; exit 1; } | ||
126 | if [[ -d ~/$repositoryName ]]; then rm -r -f $repositoryName || { echo "Permissions Error: try running the update as sudo"; exit 1; } ; fi | ||
127 | echo -n "Downloading latest version of: $repositoryName." | ||
128 | # shellcheck disable=SC2015 | ||
129 | git clone -q "https://github.com/$githubUserName/$repositoryName" && touch .BSnippetsHiddenFile || { echo "Failure!"; exit 1; } & | ||
130 | while [ ! -f .BSnippetsHiddenFile ]; do { echo -n "."; sleep 2; };done | ||
131 | rm -f .BSnippetsHiddenFile | ||
132 | echo "Success!" | ||
133 | cd $repositoryName || { echo 'Update Failed'; exit 1; } | ||
134 | git checkout "v$latestVersion" 2> /dev/null || git checkout "$latestVersion" 2> /dev/null || echo "Couldn't git checkout to stable release, updating to latest commit." | ||
135 | chmod a+x install.sh #this might be necessary in your case but wasnt in mine. | ||
136 | ./$nameOfInstallFile "update" || exit 1 | ||
137 | cd .. | ||
138 | rm -r -f $repositoryName || { echo "Permissions Error: update succesfull but cannot delete temp files located at ~/$repositoryName delete this directory with sudo"; exit 1; } | ||
139 | else | ||
140 | exit 1 | ||
141 | fi | ||
142 | else | ||
143 | echo "$repositoryName is already the latest version" | ||
144 | fi | ||
145 | fi | ||
146 | } | ||
147 | |||
148 | # handle configuration cases | ||
149 | _configure() { | ||
150 | [[ $# == 0 ]] && (${EDITOR:-vi} "$CONFIG") && return 0 | ||
151 | |||
152 | local valid_keys='user|token|folder|auto_sync|EDITOR|action' | ||
153 | if [[ $1 =~ ^($valid_keys)$ ]]; then | ||
154 | if [[ $1 == 'user' ]]; then | ||
155 | [[ -z $2 ]] && echo "Must specify username" >&2 && return 1 | ||
156 | elif [[ $1 == 'token' ]]; then | ||
157 | [[ ${#2} -ne 40 ]] && echo 'Invalid token format, it is not 40 chars' >&2 \ | ||
158 | && return 1 | ||
159 | elif [[ $1 == 'auto_sync' ]]; then | ||
160 | [[ ! $2 =~ ^(true|false)$ ]] && return 1 | ||
161 | fi | ||
162 | local key=$1 && shift && local target=$key="'$*'" | ||
163 | else | ||
164 | echo "Not a valid key for configuration, use <$valid_keys> instead." | ||
165 | return 1 | ||
166 | fi | ||
167 | |||
168 | umask 0077 && touch "$CONFIG" | ||
169 | sed -i'' -e "/^$key=/ d" "$CONFIG" && [[ -n $target ]] && echo "$target" >> "$CONFIG" | ||
170 | cat "$CONFIG" | ||
171 | } | ||
172 | |||
173 | # prompt for username | ||
174 | _ask_username() { | ||
175 | while [[ ! $user =~ ^[[:alnum:]]+$ ]]; do | ||
176 | [[ -n $user ]] && echo "Not a valid username" | ||
177 | read -r -p "Github username: " user < /dev/tty | ||
178 | done | ||
179 | _configure user "$user" | ||
180 | } | ||
181 | |||
182 | # prompt for token | ||
183 | # TODO check token scope contains gist, ref: https://developer.github.com/v3/apps/oauth_applications/#check-a-token | ||
184 | _ask_token() { | ||
185 | echo -n "Create a new token from web browser? [Y/n] " | ||
186 | read -r answer < /dev/tty | ||
187 | if [[ ! $answer =~ ^(N|n|No|NO|no)$ ]]; then | ||
188 | python -mwebbrowser https://github.com/settings/tokens/new?scopes=gist | ||
189 | fi | ||
190 | |||
191 | while [[ ! $token =~ ^[[:alnum:]]{40}$ ]]; do | ||
192 | [[ -n $token ]] && echo "Not a valid token" | ||
193 | read -r -p "Paste your token here (Ctrl-C to skip): " token < /dev/tty | ||
194 | done | ||
195 | _configure token "$token" | ||
196 | } | ||
197 | |||
198 | # check configuration is fine with user setting | ||
199 | _validate_config(){ | ||
200 | # shellcheck source=/dev/null | ||
201 | source "$CONFIG" 2> /dev/null | ||
202 | [[ $1 =~ ^(c|config|h|help|u|user|update|version) ]] && return 0 | ||
203 | if [[ -z $user ]]; then | ||
204 | echo 'Hi fellow! To access your gists, I need your Github username' | ||
205 | echo "Also a personal token with scope which allows \"gist\"!" | ||
206 | echo | ||
207 | _ask_username && _ask_token && init=true | ||
208 | elif [[ -z $token && $1 =~ ^(n|new|e|edit|D|delete)$ ]]; then | ||
209 | if ! (_ask_token); then | ||
210 | echo 'To create/edit/delete a gist, a token is needed' | ||
211 | return 1 | ||
212 | fi | ||
213 | elif [[ -z $token && $1 =~ ^(f|fetch)$ && $2 =~ ^(s|star) ]]; then | ||
214 | if ! (_ask_token); then | ||
215 | echo 'To get user starred gists, a token is needed' | ||
216 | return 1 | ||
217 | fi | ||
218 | fi | ||
219 | } | ||
220 | |||
221 | # load configuration | ||
222 | _apply_config() { | ||
223 | _validate_config "$@" || return 1 | ||
224 | INDEX=$folder/index; [[ -e $INDEX ]] || touch $INDEX | ||
225 | } | ||
226 | |||
227 | _check_repo_status() { | ||
228 | if [[ ! -d $1 ]]; then | ||
229 | if [[ $auto_sync == 'true' ]]; then | ||
230 | echo "\e[32m[cloning]\e[0m"; | ||
231 | else | ||
232 | echo "\e[32m[Not cloned yet]\e[0m"; | ||
233 | fi | ||
234 | else | ||
235 | cd "$1" || exit | ||
236 | if [[ -n $(git status --short) ]] &>/dev/null; then | ||
237 | echo "\e[36m[working]\e[0m" | ||
238 | else | ||
239 | [[ $(_blob_code "$1") != "$2" ]] 2>/dev/null && echo "\e[31m[outdated]\e[0m" | ||
240 | [[ -n $(git cherry) ]] 2>/dev/null && echo "\e[31m[ahead]\e[0m" | ||
241 | fi | ||
242 | fi | ||
243 | } | ||
244 | |||
245 | # Show the list of gist, but not updated time | ||
246 | # show username for starred gist | ||
247 | _show_list() { | ||
248 | if [[ ! -e $INDEX ]]; then | ||
249 | echo 'No local file found for last update, please run command:' | ||
250 | echo ' gist update' | ||
251 | return 0 | ||
252 | fi | ||
253 | local filter='/^ *s/ d; /^$/ d' | ||
254 | [[ $mark == 's' ]] && filter='/^ *[^ s]/ d; /^$/ d' | ||
255 | |||
256 | sed -e "$filter" $INDEX \ | ||
257 | | while read -r index link blob_code file_num comment_num author description; do | ||
258 | [[ $mark == 's' ]] && local name=$author | ||
259 | #local repo; repo=$folder/$(echo $link | sed 's#.*/##') | ||
260 | local repo; repo=$folder/${link##*/} | ||
261 | local extra; extra=$(_check_repo_status "$repo" "$blob_code") | ||
262 | [[ -z $extra ]] && extra="$file_num $comment_num" | ||
263 | |||
264 | echo -e "$(printf "% 3s" "$index") $link $name $extra $description" \ | ||
265 | | cut -c -"$(tput cols)" | ||
266 | done | ||
267 | |||
268 | [[ $hint == 'true' ]] && echo -e '\nrun "gist fetch" to update gists or "gist help" for more details' > /dev/tty \ | ||
269 | || return 0 | ||
270 | } | ||
271 | |||
272 | # TODO support filenames, file contents | ||
273 | _grep_content() { | ||
274 | _show_list | grep -i "$1" | ||
275 | } | ||
276 | |||
277 | # Open Github repository import page | ||
278 | _import_to_github() { | ||
279 | _gist_id "$1" | ||
280 | echo put the folowing URL into web page: | ||
281 | echo -n "git@github.com:$GIST_ID.git" | ||
282 | python -mwebbrowser https://github.com/new/import | ||
283 | } | ||
284 | |||
285 | _push_to_remote() { | ||
286 | _gist_id "$1" | ||
287 | cd "$folder/$GIST_ID" && git add . \ | ||
288 | && git commit --allow-empty-message -m '' && git push origin master | ||
289 | } | ||
290 | |||
291 | _parse_gists() { | ||
292 | _process_json ' | ||
293 | raw = json.load(sys.stdin) | ||
294 | for gist in raw: | ||
295 | print(gist["html_url"], end=" ") | ||
296 | print([file["raw_url"] for file in gist["files"].values()], end=" ") | ||
297 | print(gist["public"], end=" ") | ||
298 | print(len(gist["files"]), end=" ") | ||
299 | print(gist["comments"], end=" ") | ||
300 | print(gist["owner"]["login"], end=" ") | ||
301 | print(gist["description"]) | ||
302 | ' | ||
303 | } | ||
304 | |||
305 | # TODO check if a user has no gist | ||
306 | # parse response from gists require | ||
307 | _parse_response() { | ||
308 | _parse_gists \ | ||
309 | | tac | sed -e 's/, /,/g' | nl -s' ' \ | ||
310 | | while read -r index link file_url_array public file_num comment_num author description; do | ||
311 | local blob_code; blob_code=$(echo "$file_url_array" | tr ',' '\n' | sed -E -e 's#.*raw/(.*)/.*#\1#' | sort | cut -c -7 | paste -s -d '-' -) | ||
312 | [[ $public == 'False' ]] && local mark=p | ||
313 | [[ -n $1 ]] && local index=$1 | ||
314 | echo "$mark$index $link $blob_code $file_num $comment_num $author $description" | tr -d '"' | ||
315 | done | ||
316 | } | ||
317 | |||
318 | # TODO pagnation for more than 30 gists | ||
319 | # TODO add files and date of a gist | ||
320 | # get latest list of gists from Github API | ||
321 | _fetch_gists() { | ||
322 | echo "fetching $user's gists from $GITHUB_API..." | ||
323 | echo | ||
324 | local route="users/$user/gists" | ||
325 | local filter='/^[^s]/ d; /^$/ d' | ||
326 | if [[ $1 =~ ^(star|s)$ ]];then | ||
327 | route="gists/starred" | ||
328 | local mark="s" | ||
329 | filter='/^[s]/ d; /^$/ d' | ||
330 | fi | ||
331 | |||
332 | result=$(http_method GET $GITHUB_API/$route | mark=$mark _parse_response) | ||
333 | [[ -z $result ]] && echo Failed to update gists && return 1 | ||
334 | |||
335 | sed -i'' -e "$filter" $INDEX && echo "$result" >> $INDEX | ||
336 | mark=$mark _show_list | ||
337 | |||
338 | [[ $auto_sync == 'true' ]] && (_sync_repos "$1" > /dev/null 2>&1 &) | ||
339 | } | ||
340 | |||
341 | _query_user() { | ||
342 | local route="users/$1/gists" | ||
343 | result=$(http_method GET $GITHUB_API/"$route" | _parse_response) | ||
344 | [[ -z $result ]] && echo "Failed to query $1's gists" && return 1 | ||
345 | |||
346 | echo "$result" \ | ||
347 | | while read -r index link blob_code file_num extra description; do | ||
348 | echo "$link $file_num $extra $description" | cut -c -"$(tput cols)" | ||
349 | done | ||
350 | } | ||
351 | |||
352 | _blob_code() { | ||
353 | cd "$1" && git ls-tree master | cut -d' ' -f3 | cut -c-7 | sort | paste -sd '-' | ||
354 | } | ||
355 | |||
356 | # update local git repos | ||
357 | # TODO support HTTPS protocol | ||
358 | _sync_repos() { | ||
359 | # clone repos which are not in the local | ||
360 | comm -13 <(find $folder -maxdepth 1 -type d | sed -e '1d; s#.*/##' | sort) \ | ||
361 | <(cut -d' ' -f2 < "$INDEX" | sed -e 's#.*/##' | sort) \ | ||
362 | | xargs -I{} --max-procs 8 git clone git@github.com:{}.git $folder/{} | ||
363 | |||
364 | # pull if remote repo has different blob objects | ||
365 | cut -d' ' -f2,3 < "$INDEX" \ | ||
366 | | while read -r url blob_code_remote; do | ||
367 | local repo; repo=$folder/${url##*/} | ||
368 | local blob_code_local; blob_code_local=$(_blob_code "$repo") | ||
369 | cd "$repo" \ | ||
370 | && [[ $blob_code_local != "$blob_code_remote" ]] \ | ||
371 | && [[ $(git rev-parse origin/master) == $(git rev-parse master) ]] \ | ||
372 | && git pull | ||
373 | done | ||
374 | echo Everything is fine! | ||
375 | } | ||
376 | |||
377 | # get gist id from index files | ||
378 | _gist_id() { | ||
379 | GIST_ID=$( (grep -hs '' $INDEX || true) | sed -n -e "/^$1 / p" | cut -d' ' -f2 | sed -E -e 's#.*/##') | ||
380 | if [[ -z $GIST_ID ]]; then | ||
381 | echo -e "Not a valid index: \e[31m$1\e[0m" | ||
382 | echo 'Use the index in the first column instead (like 1 or s1):' | ||
383 | echo | ||
384 | _show_list | ||
385 | return 1 | ||
386 | fi | ||
387 | } | ||
388 | |||
389 | _goto_gist() { | ||
390 | _gist_id "$1" || return 1 | ||
391 | |||
392 | if [[ ! -d $folder/$GIST_ID ]]; then | ||
393 | echo 'Cloning gist as repo...' | ||
394 | if git clone "git@github.com:$GIST_ID".git "$folder/$GIST_ID"; then | ||
395 | echo 'Repo is cloned' > /dev/tty | ||
396 | else | ||
397 | echo 'Failed to clone the gist' > /dev/tty | ||
398 | return 1 | ||
399 | fi | ||
400 | fi | ||
401 | |||
402 | [[ $2 != '--no-action' ]] && cd "$folder/$GIST_ID" && eval "$action" | ||
403 | echo "$folder/$GIST_ID" | ||
404 | } | ||
405 | |||
406 | _delete_gist() { | ||
407 | read -r -p "Delete gists above? [y/N] " response | ||
408 | response=${response,,} | ||
409 | [[ ! $response =~ ^(yes|y)$ ]] && return 0 | ||
410 | |||
411 | for i in "$@"; do | ||
412 | _gist_id "$i" | ||
413 | http_method DELETE "$GITHUB_API/gists/$GIST_ID" \ | ||
414 | && echo "$i" deleted \ | ||
415 | && sed -E -i'' -e "/^$i / d" $INDEX | ||
416 | done | ||
417 | } | ||
418 | |||
419 | # remove repos which are not in user gists anymore | ||
420 | _clean_repos() { | ||
421 | comm -23 <(find $folder -maxdepth 1 -type d | sed -e '1d; s#.*/##' | sort) \ | ||
422 | <(cut -d' ' -f2 < "$INDEX" | sed -e 's#.*/##' | sort 2> /dev/null ) \ | ||
423 | | while read -r dir; do | ||
424 | mv $folder/"$dir" /tmp && echo move $folder/"$dir" to /tmp | ||
425 | done | ||
426 | } | ||
427 | |||
428 | # parse JSON from gist detail | ||
429 | _parse_gist() { | ||
430 | _process_json ' | ||
431 | raw = json.load(sys.stdin) | ||
432 | print("site:", raw["html_url"]) | ||
433 | print("description:", raw["description"]) | ||
434 | print("public:", raw["public"]) | ||
435 | print("API:", raw["url"]) | ||
436 | print("created_at:", raw["created_at"]) | ||
437 | print("updated_at:", raw["updated_at"]) | ||
438 | print("files:") | ||
439 | for file in raw["files"].keys(): | ||
440 | print(" ", file) | ||
441 | ' | ||
442 | } | ||
443 | |||
444 | # equal to jq '.[] | {user: .user.login, created_at: .created_at, updated_at: .updated_at, body: .body}' | ||
445 | _parse_comment() { | ||
446 | _process_json ' | ||
447 | raw = json.load(sys.stdin); | ||
448 | for comment in raw: | ||
449 | print() | ||
450 | print("|", "user:", comment["user"]["login"]) | ||
451 | print("|", "created_at:", comment["created_at"]) | ||
452 | print("|", "updated_at:", comment["updated_at"]) | ||
453 | print("|", comment["body"]) | ||
454 | ' | ||
455 | } | ||
456 | |||
457 | _show_detail() { | ||
458 | _gist_id "$1" | ||
459 | http_method GET "$GITHUB_API/gists/$GIST_ID" \ | ||
460 | | _parse_gist | ||
461 | |||
462 | http_method GET "$GITHUB_API/gists/$GIST_ID"/comments \ | ||
463 | | _parse_comment | ||
464 | } | ||
465 | |||
466 | # set filename/description/permission for a new gist | ||
467 | _set_gist() { | ||
468 | files=() | ||
469 | public=True | ||
470 | while [[ -n "$*" ]]; do case $1 in | ||
471 | -d | --desc) | ||
472 | description="$2" | ||
473 | shift; shift;; | ||
474 | -f | --file) | ||
475 | filename="$2" | ||
476 | shift; shift;; | ||
477 | -p) | ||
478 | public=False | ||
479 | shift;; | ||
480 | *) | ||
481 | files+=($1) | ||
482 | shift;; | ||
483 | esac | ||
484 | done | ||
485 | ls "${files[@]}" > /dev/null || return 1 | ||
486 | } | ||
487 | |||
488 | # Let user type the content of gist before setting filename | ||
489 | _new_file() { | ||
490 | [[ -t 0 ]] && echo "Type a gist. <Ctrl-C> to cancel, <Ctrl-D> when done" > /dev/tty | ||
491 | tmp_file=$(mktemp) | ||
492 | cat > "$tmp_file" | ||
493 | echo -e '\n' > /dev/tty | ||
494 | [[ -z $1 ]] && read -r -p 'Type file name: ' filename < /dev/tty | ||
495 | mv "$tmp_file" /tmp/"$filename" | ||
496 | echo /tmp/"$filename" | ||
497 | } | ||
498 | |||
499 | _gist_body(){ | ||
500 | _process_json " | ||
501 | import os.path | ||
502 | files_json = {} | ||
503 | files = sys.stdin.readline().split() | ||
504 | description = sys.stdin.readline().replace('\n','') | ||
505 | for file in files: | ||
506 | with open(file, 'r') as f: | ||
507 | files_json[os.path.basename(file)] = {'content': f.read()} | ||
508 | print(json.dumps({'public': $public, 'files': files_json, 'description': description})) | ||
509 | " | ||
510 | } | ||
511 | |||
512 | # create a new gist with files | ||
513 | _create_gist() { | ||
514 | _set_gist "$@" || return 1 | ||
515 | [[ -z $files ]] && files=(_new_file "$filename") | ||
516 | [[ -z $description ]] && read -r -p 'Type description: ' description < /dev/tty | ||
517 | |||
518 | echo 'Creating a new gist...' | ||
519 | http_data=$(mktemp) | ||
520 | |||
521 | echo -e "${files[*]}\n$description" \ | ||
522 | | _gist_body > "$http_data" \ | ||
523 | && http_method POST $GITHUB_API/gists \ | ||
524 | | sed -e '1 s/^/[/; $ s/$/]/' \ | ||
525 | | _parse_response $(( $(sed -e '/^s/ d' $INDEX | wc -l) +1 )) \ | ||
526 | | tee -a $INDEX \ | ||
527 | | cut -d' ' -f2 | sed -E -e 's#.*/##' \ | ||
528 | | (xargs -I{} git clone git@github.com:{}.git $folder/{} &> /dev/null &) | ||
529 | |||
530 | if [[ $? -eq 0 ]]; then | ||
531 | echo 'Gist is created' | ||
532 | hint=false _show_list | tail -1 | ||
533 | else | ||
534 | echo 'Failed to create gist' | ||
535 | fi | ||
536 | } | ||
537 | |||
538 | # update description of a gist | ||
539 | # TODO use response to modify index file, do not fetch gists again | ||
540 | _edit_gist() { | ||
541 | _gist_id "$1" | ||
542 | |||
543 | echo -n 'Type new description: ' | ||
544 | read -r DESC < /dev/tty | ||
545 | |||
546 | http_data=$(mktemp) | ||
547 | echo '{' \"description\": \"${$DESC//\"/\\\"}\" '}' > "$http_data" | ||
548 | http_method PATCH "$http_data $GITHUB_API/gists/$GIST_ID" > /dev/null \ | ||
549 | && hint=false _fetch_gists | grep -E "^[ ]+$1" | ||
550 | } | ||
551 | |||
552 | usage() { | ||
553 | sed -E -n -e ' /^$/ q; 7,$ s/^# //p' "$0" | ||
554 | } | ||
555 | |||
556 | _apply_config "$@" || exit 1 | ||
557 | getConfiguredClient || exit 1 | ||
558 | if [[ $init ]]; then _fetch_gists; exit 0; fi | ||
559 | case "$1" in | ||
560 | "") | ||
561 | _show_list ;; | ||
562 | star | s) | ||
563 | mark=s _show_list ;; | ||
564 | fetch | f) | ||
565 | _fetch_gists "$2" ;; | ||
566 | new | n) | ||
567 | shift | ||
568 | _create_gist "$@" ;; | ||
569 | edit | e) | ||
570 | _edit_gist "$2" ;; | ||
571 | sync | S) | ||
572 | _sync_repos ;; | ||
573 | detail | d) | ||
574 | shift | ||
575 | _show_detail "$@" ;; | ||
576 | delete | D) | ||
577 | shift | ||
578 | _delete_gist "$@" ;; | ||
579 | clean | C) | ||
580 | _clean_repos ;; | ||
581 | config | c) | ||
582 | shift | ||
583 | _configure "$@" ;; | ||
584 | user | U) | ||
585 | shift | ||
586 | _query_user "$@" ;; | ||
587 | grep | g) | ||
588 | shift | ||
589 | _grep_content "$@" ;; | ||
590 | github | G) | ||
591 | shift | ||
592 | _import_to_github "$1" ;; | ||
593 | push | p) | ||
594 | shift | ||
595 | _push_to_remote "$1" ;; | ||
596 | version) | ||
597 | echo "Version $currentVersion" | ||
598 | exit 0 ;; | ||
599 | update) | ||
600 | checkInternet || exit 1 | ||
601 | update | ||
602 | exit 0 | ||
603 | ;; | ||
604 | help | h) | ||
605 | usage ;; | ||
606 | *) | ||
607 | _goto_gist "$@" ;; | ||
608 | esac | ||