-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen-gh-permalink
executable file
·86 lines (71 loc) · 1.99 KB
/
gen-gh-permalink
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
#!/bin/sh
#- Constructs github permalinks given filename and line number or range of lines.
#- Formats them as `[src/file.js:3](...)` markdown link and inserts into clipboard
#- ```sh
#- gen-gh-permalink src/file.js 3 4
#- ```
#-
#- You can use `-s`/`--snippet` parameter and pipe a piece of code into this script to get
#- ````markdown
#- [src/file.js:3](...):
#- ```js
#- const a = 3;
#- ...
#- ```
#- ````
#- -style snippet.
#-
#- Useful vim bindings:
#- ```vim
#- nnoremap gH :execute '!' . 'gen-gh-permalink ' . shellescape(expand('%')) . ' ' . line(".")<cr>
#- vnoremap gH <esc>:execute '!' . 'gen-gh-permalink ' . shellescape(expand('%')) . ' ' . getpos("'<")[1] . ' ' . getpos("'>")[1]<cr>
#- vnoremap gHH <esc>:execute "'<,'>w !" . 'gen-gh-permalink -s ' . shellescape(expand('%')) . ' ' . getpos("'<")[1] . ' ' . getpos("'>")[1]<cr>
#- ```
#-
#* xclip git sed grep
if [ "$1" = '-s' ] || [ "$1" = '--snippet' ]; then
snippet=true
shift
fi
fname="$1"
l1=$2
l2=$3
abs_fname="$PWD/$fname"
cd "$(dirname "$fname")"
# git rev-parse --git-dir || return 0
gitdir=$(git rev-parse --show-toplevel) && [ ! -z $? ] || exit 1
rel_fname="${abs_fname#"$gitdir/"}"
if [ $l1 = "$l2" ]; then
l2=''
fi
if [ ! -z "$(git diff --name-only "$abs_fname")" ]; then
echo "File $fname contains changes. Stash them and try again"
exit 1
fi
origin=$(git remote get-url origin)
if [ -z $(echo "$origin" | grep 'github.com') ]; then
echo "Not implemented: origin is not github"
exit 1
fi
repo=$(echo $origin | sed 's/^\([email protected]:\|https:\/\/github.com\/\)\([a-zA-Z_-]\+\)\/\([a-zA-Z_-]\+\)\.git$/\2\/\3/')
if [ "$origin" = "$repo" ]; then
echo "Invalid origin"
exit 1
fi
commit=$(git rev-parse HEAD)
if [ -z "$l2" ]; then
l2mb=''
else
l2mb="-L$l2"
fi
link="https://github.com/$repo/blob/$commit/$rel_fname#L${l1}${l2mb}"
path="$rel_fname:$l1"
(
echo -n "[$path]($link)"
if [ ! -z "$snippet" ]; then
echo ':'
echo '```'"${abs_fname##*.}"
cat
echo '```'
fi
) | xclip -i -selection clipboard