summaryrefslogtreecommitdiffhomepage
path: root/scripts/gist
blob: 558b65989400fb14bcd13da9fbba3639712286ac (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#!/bin/bash

github_api_token=$(cat $SETTING_DIR/tokens/github)
user=typebrook
folder=~/git/gist

mkdir -p $folder
index=$folder/index

_update() {
    # get the list of gists
    curl -s -H "Authorization: token $github_api_token" https://api.github.com/users/$user/gists |\
    jq '.[] | "\( .html_url ) \(.files | keys | length) \( .description )"' |\
    tr -d '"' | tac | nl |\
    while read line_num link file_num description; do
        echo $line_num $link $file_num $(echo $description | cut -c -70)
    done | tee $index
}

_sync_repos() {
    # clone repos which are not in the local machine
    comm -13 <(find $folder -maxdepth 1 -type d | sed '1d; s#.*/##' | sort) \
             <(cat $index | cut -d' ' -f2 | sed 's#.*/##' | sort) |\
    xargs -I{} git clone git@github.com:{}.git $folder/{}
}

_goto_gist() {
    GIST_ID=$(cat $index | sed -n "$1"p | cut -d' ' -f2 | sed -r 's#.*/##')
    echo this gist is at $folder/$GIST_ID
    cd $folder/$GIST_ID && tig --all 2> /dev/null
}

_delete_gist() {
    GIST_ID=$(cat $index | sed -n "$1"p | cut -d' ' -f2 | sed -r 's#.*/##')
    curl -X DELETE -s -H "Authorization: token $github_api_token" https://api.github.com/gists/$GIST_ID
    _update
}

_clean_repos() {
    comm -23 <(find $folder -maxdepth 1 -type d | sed '1d; s#.*/##' | sort) \
             <(cat $index | cut -d' ' -f2 | sed 's#.*/##' | sort) |\
    xargs -I{} rm -rf $folder/{}
}

_show_detail() {
    GIST_ID=$(cat $index | sed -n "$1"p | cut -d' ' -f2 | sed -r 's#.*/##')
    curl -s -H "Authorization: token $github_api_token" https://api.github.com/gists/$GIST_ID
}

_create_gist() {
    FILE=$(basename $1)

    jq --arg FILE "$FILE" --arg DESC "$2" '. as $content | {
        public: true, 
        files: {
            ($FILE): {content: $content}
        },
        description: ($DESC)
    }' -R -s $1 |\
    curl -s -H "Authorization: token $github_api_token" \
        --data @- \
        https://api.github.com/gists
}

if [[ $# -eq 0 ]]; then
    cat $index 
    exit 0
fi

case "$1" in
  create | c)
    _create_gist $2 "$3"
    ;;
  update | u)
    _update
    ;;
  sync | s)
    _sync_repos
    ;;
  detail | d)
    _show_detail $2
    ;;
  delete | D)
    _delete_gist $2
    ;;
  clean | C)
    _clean_repos
    ;;
  *)
    _goto_gist $1
    ;;
esac