forked from Djuuu/git-mr
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-mr
More file actions
executable file
·2743 lines (2100 loc) · 86 KB
/
Copy pathgit-mr
File metadata and controls
executable file
·2743 lines (2100 loc) · 86 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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env bash
################################################################################
# Git functions
git_current_branch() {
# `git branch --show-current` is available starting from Git 2.22
# fallback to `git rev-parse --abbrev-ref HEAD` if first command fails
(git branch --show-current 2>/dev/null) ||
git rev-parse --abbrev-ref HEAD
}
git_base_branch() {
local branch=${1:-$(git_current_branch)}
local default_branch; default_branch=$(git_default_branch)
[[ -n $branch ]] || exit "$ERR_GIT" # Not on any branch
[[ $branch != "$default_branch" ]] || exit "$ERR_GIT" # On default branch
git_branch_exists "$branch" || exit "$ERR_GIT" # Branch does not exist
# Nearest branch in commit history
local base_branch
local refs_logs; refs_logs=$(git log --oneline --decorate "${branch}" \
--simplify-by-decoration --decorate-refs='refs/heads/*') # select only commits with a local branch
local ref_count; ref_count="${refs_logs//[!$'\n']/}"; ref_count=$((${#ref_count} + 1))
if [[ $ref_count -gt 1 ]]; then
base_branch=$( \
echo "$refs_logs" |
sed '
2!d # keep only 2nd line (closest decoration before current HEAD)
s/[a-f0-9]* (\([^),]*\).*/\1/ # keep only first decoration
')
fi
# First possible merge base
if ! git_branch_exists "$base_branch"; then
base_branch=$(git show-branch --merge-base "$branch" "$default_branch" | head -n1)
fi
echo_debug "Base branch: $base_branch"
echo "$base_branch"
}
git_remote() {
git remote | head -n1
}
git_branch_exists() {
local branch=$1
git show-ref -q --heads "$branch"
}
git_default_branch() {
local remote; remote=$(gitlab_remote || git_remote)
local default; default=$(git symbolic-ref "refs/remotes/${remote}/HEAD" -- 2>/dev/null)
if [[ -n $default ]]; then
local local_tracking
local_tracking=$(git branch -vv | grep "${default#"refs/remotes/"}")
local_tracking=${local_tracking:2} # remove first 2 characters (" " or "* ")
local_tracking=${local_tracking%% *} # remove all trailing characters after first space (included)
# -> only short local branch name remains
# local branch tracking default remote with a different name
[[ -n $local_tracking ]] && echo "$local_tracking" && return 0
# short local name of remote default
echo "${default#"refs/remotes/${remote}/"}"
return 0
fi
git_branch_exists "main" && echo "main" && return 0
git_branch_exists "master" && echo "master" && return 0
}
git_remote_branch_exists() {
local branch=$1
local remote=${2:-$(gitlab_remote)}
[[ -n "$(git ls-remote --heads "$remote" "$branch")" ]]
}
git_check_branches() {
local source_branch="$1"
local target_branch="$2"
[[ -n $source_branch ]] ||
exit_error "$ERR_GIT" "Not on any branch"
[[ $source_branch != "$(git_default_branch)" ]] ||
exit_error "$ERR_GIT" "On default branch"
git_branch_exists "$source_branch" ||
exit_error "$ERR_GIT" "Branch '$source_branch' does not exist"
[[ -n $target_branch ]] ||
exit_error "$ERR_GIT" "Unable to determine target branch"
[[ $target_branch == "$GIT_MR_TARGET" ]] && ! git_branch_exists "$target_branch" &&
exit_error "$ERR_GIT" "Branch '$target_branch' does not exist"
return 0
}
git_commits() {
local source_branch=${1:-$(git_current_branch)}
local target_branch=${2:-${GIT_MR_TARGET:-$(git_base_branch "$source_branch")}}
git log --oneline --reverse --no-decorate "${target_branch}..${source_branch}"
}
git_commits_extended() {
local source_branch=${1:-$(git_current_branch)}
local target_branch=${2:-${GIT_MR_TARGET:-$(git_base_branch "$source_branch")}}
local prefix="* ${MD_BOLD}"
local suffix="${MD_BOLD}${MD_BR}"
local end="---COMMIT-BODY-END---" # useful to remove trailing blank line
local format="${prefix}%h %s${suffix}%n%b${end}"
git log --reverse --no-decorate --format="${format}" "${target_branch}".."${source_branch}" |
grep -v "^${end}" | # remove trailing blank line
sed -r "s/${end}$//g" # remove trailing body end for bodies without trailing blank line
}
git_commit_extended() {
local revision=${1:-HEAD}
local prefix="* ${MD_BOLD}"
local suffix="${MD_BOLD}${MD_BR}"
local end="---COMMIT-BODY-END---" # useful to remove trailing blank line
local format="${prefix}%h %s${suffix}%n%b${end}"
git show -s --format="${format}" "${revision}" |
grep -v "^${end}" | # remove trailing blank line
sed -r "s/${end}$//g" # remove trailing body end for bodies without trailing blank line
}
git_titlize_branch() {
local branch=${1:-$(git_current_branch)}
# Split prefix, issue id & label parts
local branch_split_pattern="^(.*)($JIRA_CODE_PATTERN)[^a-zA-Z0-9]?(.*)$"
local prefix; prefix=$( echo "$branch" | sed -r "s/$branch_split_pattern/\1/") # ex: 'feature/'
local issue_id; issue_id=$(echo "$branch" | sed -r "s/$branch_split_pattern/\2/") # ex: 'XY-1234'
local label; label=$( echo "$branch" | sed -r "s/$branch_split_pattern/\3/") # ex: 'my-branch-name'
# When Jira code pattern is not matched
if [[ $prefix == "$issue_id" ]]; then
# Split prefix & label parts
branch_split_pattern="^([^\/]*\/?)(.*)$"
prefix=$(echo "$branch" | sed -r "s/$branch_split_pattern/\1/")
label=$(echo "$branch" | sed -r "s/$branch_split_pattern/\2/")
issue_id=
else
issue_id="$issue_id " # add space
fi
# When Jira code pattern and prefix are not matched
if [[ -z $label ]]; then
label="$prefix"
prefix=
fi
# Formatting
local title_ref; title_ref="${prefix^}${issue_id}"
local title_label; title_label=${label^}
title_label=${title_label//-/ }
title_label=${title_label//_/ }
echo "${title_ref}${title_label}"
}
################################################################################
# Misc. utilities
# sed wrapper (use gsed if available on Mac)
sed() {
if type gsed >/dev/null 2>&1; then
gsed "$@"
else
command sed "$@"
fi
}
# grep wrapper (use ggrep if available on Mac)
grep() {
if type ggrep >/dev/null 2>&1; then
ggrep "$@"
else
command grep "$@"
fi
}
exit_error() {
local code=$1
local msg="$2"
echo_error "$msg"
exit "$code"
}
# https://gist.github.com/cdown/1163649#gistcomment-1639097
urlencode() {
local oLANG="$LANG"
local oLC_ALL="$LC_ALL"
LANG=C
LC_ALL=C
local length="${#1}"
for (( i = 0; i < length; i++ )); do
local c="${1:i:1}"
case $c in
[a-zA-Z0-9.~_-]) printf "%s" "$c" ;;
*) printf '%%%02X' "'$c" ;;
esac
done
LANG="$oLANG"
LC_ALL="$oLC_ALL"
}
has_terminal_colors() {
command -v tput > /dev/null 2>&1 &&
[[ -n $TERM ]] &&
[[ "$(tput -T"$TERM" colors)" -ge 8 ]]
}
has_colors() {
[[ $GIT_MR_NO_COLORS -ne 1 ]] && has_terminal_colors
}
has_links() {
[[ $GIT_MR_NO_TERMINAL_LINK -ne 1 ]] && has_terminal_colors
}
# shellcheck disable=SC2034 # Ignore unused color variables
colorize() {
local input=$1
if has_colors; then
local bold='\e[1m'; local nobold='\e[21m'
local red='\e[31m'; local lightred='\e[91m'
local green='\e[32m'; local lightgreen='\e[92m'
local orange='\e[33m'; local lightyellow='\e[93m'
local blue='\e[34m'; local lightblue='\e[94m'
local purple='\e[35m'; local lightpurple='\e[95m'
local cyan='\e[36m'; local lightcyan='\e[96m'
local gray='\e[090m'; local lightgray='\e[37m'
local midgray='\e[38;5;247m'
local reset='\e[0m'
for style in "${@:2}"; do
echo -en "${!style}"
done
echo -en "$input"
echo -en "$reset"
else
echo -en "$input"
fi
}
echolor() {
colorize "$1\n" "${@:2}"
}
# https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda
terminal_link() {
local href=$1
local text=$2
if has_links; then
printf "\e]8;;%s\e\\%s\e]8;;\e\\" "$href" "$text"
else
echo -n "$text"
fi
}
echolink() {
terminal_link "$@"; echo
}
echo_error() {
colorize "$1\n" "orange" >&2
}
echo_debug() {
[[ $GIT_MR_VERBOSE -eq 1 ]] || return 0
colorize "$1\n" "gray" >&2
}
echo_spacer() {
local count=$1
local char=${2:-" "}
for ((i=1; i <= count; i++)); do
echo -n "$char"
done
}
trim() {
# shellcheck disable=SC2064 # expand now to restore initial value on exit
trap "$(shopt -p extglob)" RETURN
shopt -s extglob
local str=$1
local char=$2
str=${str##*("$2")} # trim leading characters
str=${str%%*("$2")} # trim trailing characters
echo "$str"
}
confirm() {
local question=$1
if [[ $GIT_MR_YES -eq 1 ]]; then
echo "$(colorize "${question}" "cyan") -> yes" >&2
return 0
fi
local response
read -r -p "$(colorize "$question" "lightcyan" "bold") [y/N] " response
case "$response" in
[yY][eE][sS]|[yY]) return 0 ;;
*) return 1 ;;
esac
}
clear_screen() {
command -v tput > /dev/null 2>&1 &&
[[ -n $TERM ]] &&
tput -x clear
}
jq_build() {
local key=${1}
local value=${2}
local initial_data=${3:-"{}"}
local is_obj; is_obj=$(echo "$value" | grep '^{.*}$')
local is_num; is_num=$(echo "$value" | grep '^[0-9]*$')
local current_object
if [[ -n $is_obj || -n $is_num ]]; then
current_object="$(jq --null-input --compact-output --argjson value "$value" "{\"${key}\": \$value}")"
else
current_object="$(jq --null-input --compact-output --arg value "$value" "{\"${key}\": \$value}")"
fi
jq --null-input --compact-output \
--argjson initial_data "$initial_data" \
--argjson current_object "$current_object" \
'$initial_data + $current_object'
}
# escape regex special characters for literal usage
regex_escape() {
echo "${1}" | sed -e 's/[]\/$*.^[]/\\&/g'
}
open_in_browser() {
local url=$1
[[ -n $url ]] || return "$ERR_MR"
local open_command open_args
if [[ "$OSTYPE" == "linux-gnu"* ]]; then
if grep -qi microsoft /proc/version; then
# https://github.com/microsoft/WSL/issues/3832#issuecomment-1173571126
open_command='rundll32.exe'
open_args="url.dll,FileProtocolHandler"
else open_command='xdg-open'; fi
elif [[ "$OSTYPE" == "darwin"* ]]; then open_command='open';
elif [[ "$OSTYPE" == "msys"* ]]; then open_command='explorer';
fi
if [[ -n $open_command && -x "$(command -v "$open_command")" ]]; then
"$open_command" "$open_args" "${url}" > /dev/null 2>&1
return 0
fi
echo_error "Unable to open browser"
echo_error
echo "${url}"
echo
return "$ERR_MR"
}
git_mr_readonly() {
[[ $GIT_MR_READONLY -eq 1 ]] || return 1
[[ -n $1 ]] &&
echolor "🚫 Read-only 🚫" "gray" >&2
return 0
}
################################################################################
# Markdown formatting
markdown_title() {
local label=$1
local level=${2:-1}
for ((i=1; i<=level; i++)); do
echo -n '#'
done
echo " ${label}"
}
markdown_link() {
local label=$1
local url=$2
if [[ -z $url ]]; then
echo "[$label]"
return 0
fi
echo "[$label]($url)"
}
markdown_list() {
local content=$1
local prefix="* ${MD_BOLD}"
local suffix="${MD_BOLD}${MD_BR}"
echo "${prefix}${content//$'\n'/${suffix}$'\n'${prefix}}${suffix}"
}
markdown_indent_list_items() {
local content=$1
local list_prefix_pattern
list_prefix_pattern="$(regex_escape "* ${MD_BOLD}")"
# indent extended description (not starting with list prefix)
local indent=" "
echo "$content" | sed -E \
-e "/^${list_prefix_pattern}/! s/^(.*)$/${indent}\1${MD_BR}/gm" \
-e "s/^${indent}${MD_BR}$/${indent}/gm"
}
################################################################################
# Jira functions
jira_check_env() {
[[ -n $JIRA_USER ]] || exit_error "$ERR_MR_ENV" "JIRA_USER is not set"
[[ -n $JIRA_TOKEN ]] || exit_error "$ERR_MR_ENV" "JIRA_TOKEN is not set"
[[ -n $JIRA_INSTANCE ]] || exit_error "$ERR_MR_ENV" "JIRA_INSTANCE is not set"
}
jira_request() {
jira_check_env
local request_url=$1
local request_verb=${2:-"GET"}
local request_data=${3}
local jira_base_url="https://${JIRA_INSTANCE}/rest/api/3"
local auth_token; auth_token=$(echo -n "${JIRA_USER}:${JIRA_TOKEN}" | base64 -w 0)
echo_debug "Jira - ${request_verb} ${request_url} ${request_data}"
[[ $request_verb != "GET" ]] && git_mr_readonly && return 0
curl -Ss \
-X "${request_verb}" \
-H "Authorization: Basic ${auth_token}" \
-H "Content-Type: application/json" \
--data "${request_data}" \
--max-time "${GIT_MR_TIMEOUT:-5}" \
"${jira_base_url}/${request_url}" || exit_error "$ERR_JIRA_API" "Jira request error"
}
jira_ticket_data() {
jira_check_env
local issue_code=$1; [[ -n $issue_code ]] || exit_error "$ERR_MR" "issue_code required"
jira_request "issue/${issue_code}?fields=summary" || exit $?
}
jira_show_transitions() {
local issue_code=${1:-${GIT_MR_CODE:-$(guess_issue_code "$(git_current_branch)")}}
echo "Available Jira transitions:"
jira_request "issue/${issue_code}/transitions" |
jq -r '.transitions[] | [
"", .id,
"\"" + .name + "\"" + (" " * (23 - (.name | length))),
"-> " + (.to | .name + (" " * (23 - (.name | length)))),
"[" + .to.statusCategory.name + "]"
] | @tsv' |
tr -d '\r'
}
jira_transition() {
jira_check_env
local issue_code=$1; [[ -n $issue_code ]] || exit_error "$ERR_MR" "issue_code required"
local transition_id=$2; [[ -n $transition_id ]] || exit_error "$ERR_MR" "transition_id required"
local transition; transition=$(jq_build "id" "$transition_id") || exit "$ERR_MR"
local request_data; request_data=$(jq_build "transition" "$transition") || exit "$ERR_MR"
jira_request "issue/${issue_code}/transitions" "POST" "$request_data" || exit $?
}
################################################################################
# Gitlab functions
gitlab_check_env() {
[[ -n $GITLAB_DOMAIN ]] || exit_error "$ERR_MR_ENV" "GITLAB_DOMAIN is not set"
[[ -n $GITLAB_TOKEN ]] || exit_error "$ERR_MR_ENV" "GITLAB_TOKEN is not set"
}
gitlab_remote() {
local remote remote_url
for remote in $(git remote); do
remote_url=$(git remote get-url --push "$remote" | grep "${GITLAB_DOMAIN}" || true)
[[ -n "$remote_url" ]] && echo "$remote" && return 0
done
return "$ERR_GIT_REPO"
}
gitlab_project_url() {
local remote
local remote_url
local project_url
remote=$(gitlab_remote)
[[ -n $remote ]] &&
remote_url=$(git remote get-url --push "$remote" | grep "${GITLAB_DOMAIN}")
if [[ "$remote_url" == git* ]]; then
project_url=$remote_url
project_url=${project_url#"git@${GITLAB_DOMAIN}:"}
project_url=${project_url%".git"}
elif [[ "$remote_url" == https* ]]; then
project_url=$remote_url
project_url=${project_url#"https://${GITLAB_DOMAIN}/"}
project_url=${project_url%".git"}
fi
if [[ -z $project_url ]]; then
remote=$(git remote | head -n 1)
remote_url=$(git remote get-url --push "$remote")
local suggested_domain
suggested_domain=$(git remote get-url --push "$remote" | sed 's/.*@\(.*\):.*/\1/')
exit_error "$ERR_GIT_REPO" "$(cat <<- EOF
Unable to determine Gitlab project URL, check GITLAB_DOMAIN configuration
${remote}: ${remote_url}
current: GITLAB_DOMAIN="${GITLAB_DOMAIN}"
Suggestion: GITLAB_DOMAIN="${suggested_domain}"
EOF
)"
fi
echo "$project_url"
}
gitlab_current_project_request() {
gitlab_check_env
local request_url=$1
local request_verb=${2:-"GET"}
local request_data=${3}
local project_url; project_url=$(gitlab_project_url) || exit $?
gitlab_project_request "$project_url" "$request_url" "$request_verb" "$request_data"
}
gitlab_project_request() {
local project_url=$1
local request_url=$2
local request_verb=${3:-"GET"}
local request_data=${4}
gitlab_request "projects/$(urlencode "$project_url")/${request_url}" "$request_verb" "$request_data"
}
gitlab_request() {
gitlab_check_env
local request_url=$1
local request_verb=${2:-"GET"}
local request_data=${3}
local gitlab_base_url="https://${GITLAB_DOMAIN}/api/v4"
echo_debug "GitLab - ${request_verb} ${gitlab_base_url}/${request_url} ${request_data}"
[[ $request_verb != "GET" ]] && git_mr_readonly && echo '{}' && return 0
local result
result=$(curl -Ss \
-X "${request_verb}" \
-H "Private-Token: ${GITLAB_TOKEN}" \
-H "Content-Type: application/json" \
--data "${request_data}" \
--max-time "${GIT_MR_TIMEOUT:-5}" \
"${gitlab_base_url}/${request_url}") || exit_error "$ERR_GITLAB_API" "Gitlab request error"
if [[ $request_verb != "GET" ]]; then
[[ -z "$(gitlab_check_error "$result")" ]] || return "$ERR_GITLAB"
fi
echo "$result"
}
gitlab_check_error() {
local result=$1
local hasErrorMessage
hasErrorMessage=$(echo "$result" | jq 'if type=="object" then (has("error") or has("message")) else false end')
if [[ $hasErrorMessage == 'true' ]]; then
echo_error "\nGitlab error:\n ${result}"
echo "ko"
fi
}
gitlab_new_merge_request_url() {
gitlab_check_env
local project_url; project_url=$(gitlab_project_url) || exit $?
local source_branch=${1:-$(git_current_branch)}
if ! git_remote_branch_exists "$source_branch"; then
echo_error "Branch '$source_branch' does not exist on remote"
return "$ERR_GITLAB"
fi
local target_branch=${2:-${GIT_MR_TARGET:-$(git_base_branch "$source_branch")}}
if ! git_remote_branch_exists "$target_branch"; then
echo_error "Target branch '$target_branch' does not exist on remote"
return "$ERR_GITLAB"
fi
local gitlab_mr_url="https://${GITLAB_DOMAIN}/${project_url}/-/merge_requests/new"
gitlab_mr_url="${gitlab_mr_url}?$(urlencode "merge_request[source_branch]")=${source_branch}"
gitlab_mr_url="${gitlab_mr_url}&$(urlencode "merge_request[target_branch]")=${target_branch}"
# default labels
for label_id in $(gitlab_default_label_ids); do
gitlab_mr_url="${gitlab_mr_url}&$(urlencode "merge_request[label_ids][]")=${label_id}"
done
# other options
if [[ "${GITLAB_DEFAULT_FORCE_REMOVE_SOURCE_BRANCH:-1}" -eq 1 ]]; then
gitlab_mr_url="${gitlab_mr_url}&$(urlencode "merge_request[force_remove_source_branch]")=1"
fi
# title
local title
title=$(git_titlize_branch "$source_branch")
title=$(gitlab_title_to_draft "$title")
title=$(urlencode "$title")
gitlab_mr_url="${gitlab_mr_url}&$(urlencode "merge_request[title]")=${title}"
echo "$gitlab_mr_url"
}
gitlab_merge_request_summary() {
gitlab_check_env
local source_branch=${1:-$(git_current_branch)}
local result
result=$(gitlab_current_project_request "merge_requests?state=opened&view=simple&source_branch=${source_branch}") || exit $?
[[ -n $result && $result != "[]" ]] || return "$ERR_GITLAB"
echo "$result" | jq '.[0]'
}
gitlab_merge_requests_search() {
gitlab_check_env
local search_term=$1; [[ -n $search_term ]] || exit_error "$ERR_MR" "search_term required"
local result
result=$(gitlab_request "merge_requests?scope=all&state=all&view=simple&search=$(urlencode "$search_term")&in=title&order_by=created_at&sort=asc") || exit $?
[[ -n $result && $result != "[]" ]] || return "$ERR_GITLAB"
result=$(echo "$result" | jq -c 'map(select(.state != "closed") | {iid: .iid, title: .title, web_url: .web_url, state: .state, project_id: .project_id})')
[[ -n $result && $result != "[]" ]] || return "$ERR_GITLAB"
echo "$result"
}
gitlab_projects() {
local result
result=$(gitlab_request "projects?simple=true&archived=false&order_by=last_activity_at&per_page=${GIT_MR_LAST_PROJECTS_LIMIT:-40}") || exit $?
[[ -n $result && $result != "[]" ]] || return "$ERR_GITLAB"
result=$(echo "$result" | jq 'map({id: .id, name: .name, path_with_namespace: .path_with_namespace})')
[[ -n $result && $result != "[]" ]] || return "$ERR_GITLAB"
echo "$result"
}
gitlab_merge_request() {
gitlab_check_env
local mr_iid=$1; [[ -n $mr_iid ]] || exit_error "$ERR_MR" "No mr_iid provided"
local project_url=$2; [[ -n $project_url ]] || project_url=$(gitlab_project_url) || exit $?
gitlab_project_request "$project_url" "merge_requests/$mr_iid"
}
gitlab_extract_iid() {
local mr_summary=$1
echo "$mr_summary" | jq -r '.iid'
}
gitlab_extract_url() {
local mr_summary=$1
echo "$mr_summary" | jq -r '.web_url'
}
gitlab_extract_title() {
local mr_summary=$1
echo "$mr_summary" | jq -r '.title'
}
gitlab_extract_description() {
local mr_summary=$1
echo "$mr_summary" | jq -r '.description'
}
gitlab_extract_merge_status() {
local mr_detail=$1
if [[ "$(echo "$mr_detail" | jq -r '.state')" == "merged" ]]; then
echo "merged"
return 0
fi
echo "$mr_detail" | jq -r '.merge_status'
}
gitlab_extract_pipeline_status() {
local mr_detail=$1
echo "$mr_detail" | jq -r '.head_pipeline.status'
}
gitlab_extract_pipeline_url() {
local mr_detail=$1
echo "$mr_detail" | jq -r '.head_pipeline.web_url'
}
gitlab_extract_target_branch() {
local mr_detail=$1
echo "$mr_detail" | jq -r '.target_branch'
}
gitlab_extract_labels() {
local mr_detail=$1
echo "$mr_detail" | jq -r '.labels | join(",")'
}
gitlab_extract_project_url_part() {
local url=$1
url=${url#"https://${GITLAB_DOMAIN}/"} # remove prefix
url=${url%"/-/merge_requests/"*} # remove suffix
echo "$url"
}
gitlab_merge_request_threads() {
gitlab_check_env
local mr_url=$1
local mr_iid="${mr_url##*/}"
local project_url; project_url="$(gitlab_extract_project_url_part "$mr_url")"
[[ -n $mr_url ]] || exit_error "$ERR_MR" "No mr_url provided"
[[ -n $mr_iid ]] || exit_error "$ERR_MR" "Unable to determine mr_iid from mr_url"
[[ -n $project_url ]] || exit_error "$ERR_MR" "Unable to determine project_url from mr_url"
local thread_summaries
local per_page=100
local page=1
local notes_page_count=${per_page}
while [[ $notes_page_count -eq "$per_page" ]]; do
# fetch page
local notes_page
notes_page=$(gitlab_project_request "$project_url" "merge_requests/${mr_iid}/discussions?per_page=${per_page}&page=${page}")
if [[ $notes_page != "[]" ]]; then
local thread_summaries_page
thread_summaries_page=$(echo "$notes_page" | jq -r '
.[] | select(any(.notes[]; .resolvable == true)) | {
id: .id,
resolvables: .notes | map(select(.resolvable == true) | {id: .id, resolved: .resolved})
} |
.id + "\t" +
"unresolved:" + (any(.resolvables[]; .resolved == false) | tostring) + "\t" +
"note_id:" + (.resolvables | map(select(.resolved == false)) | first | .id | tostring)
' | tr -d '\r')
# append page
if [[ -z $thread_summaries ]]; then
thread_summaries="$thread_summaries_page"
else
thread_summaries=$(echo -e "${thread_summaries}\n${thread_summaries_page}")
fi
# increment
notes_page_count=$(echo "$notes_page" | jq -r 'length')
page=$((page + 1))
else
notes_page_count=0
fi
done
echo "$thread_summaries"
}
gitlab_default_label_ids() {
gitlab_check_env
local gitlab_labels; gitlab_labels=$(gitlab_current_project_request "labels")
echo "$GITLAB_DEFAULT_LABELS" | jq -R -r \
--argjson gitlab_labels "$gitlab_labels" \
'split(",") | .[] | . as $name | $gitlab_labels | map(select(.name == $name) | .id) | .[]' |
tr -d '\r'
}
gitlab_merge_request_update() {
gitlab_check_env
local mr_iid=$1; [[ -n $mr_iid ]] || exit_error "$ERR_MR" "No mr_iid provided"
local mr_data=$2; [[ -n $mr_data ]] || exit_error "$ERR_MR" "No data provided"
local project_url=$3; [[ -n $project_url ]] || project_url=$(gitlab_project_url) || exit $?
gitlab_project_request "$project_url" "merge_requests/${mr_iid}" "PUT" "${mr_data}"
}
gitlab_merge_request_merge() {
gitlab_check_env
local mr_iid=$1; [[ -n $mr_iid ]] || exit_error "$ERR_MR" "No mr_iid provided"
gitlab_current_project_request "merge_requests/${mr_iid}/merge?should_remove_source_branch=${GITLAB_DEFAULT_FORCE_REMOVE_SOURCE_BRANCH:-1}" "PUT"
}
gitlab_title_is_draft() {
local title=$1
for prefix in "${GITLAB_DRAFT_PREFIXES[@]}"; do
[[ $title =~ ^${prefix}: ]] && return 0
done
return 1
}
gitlab_title_to_draft() {
local title=$1
echo "${GITLAB_DRAFT_PREFIX}: $title"
}
gitlab_title_undraft() {
local title=$1
for prefix in "${GITLAB_DRAFT_PREFIXES[@]}"; do
title=${title#"${prefix}: "}
done
echo "$title"
}
gitlab_undraft() {
git_mr_readonly show
gitlab_check_env
local source_branch=${1:-$(git_current_branch)}
# Search existing merge request
local mr_summary; mr_summary=$(gitlab_merge_request_summary "$source_branch")
if [[ -z $mr_summary ]]; then
echo_error "Merge request not found"
mr_print "$source_branch"
return "$ERR_GITLAB"
fi
local mr_iid mr_url mr_title
eval "$(echo "$mr_summary" | jq -r '
"mr_iid=" + (.iid | @sh) + ";\n" +
"mr_url=" + (.web_url | @sh) + ";\n" +
"mr_title=" + (.title | @sh) + ";\n"
')"
# Print merge request status summary
echo
mr_status_block "$mr_summary" "" "" "$mr_iid" "$mr_url" "$mr_title"
echo "--------------------------------------------------------------------------------"
echo
if ! gitlab_title_is_draft "$mr_title"; then
echo_error "Merge request is not a draft"
echo_error
return 0
fi
local undraft_title; undraft_title=$(gitlab_title_undraft "$mr_title")
if confirm "Do you want to resolve draft status?"; then
echo -n "Resolving draft status... "
local mr_data; mr_data=$(jq_build "title" "$undraft_title") || exit "$ERR_MR"
local result; result=$(gitlab_merge_request_update "$mr_iid" "$mr_data")
[[ -n $result ]] && echo -e "OK\n"
fi
}
# Async functions
gitlab_load_mr() {
exec {git_mr_fd_mr}< <(gitlab_merge_request "$@")
}
gitlab_load_threads() {
exec {git_mr_fd_th}< <(gitlab_merge_request_threads "$@")
}
gitlab_read_mr() {
local var_name=$1
IFS= read -r -d '' -u "$git_mr_fd_mr" "$var_name"
exec {git_mr_fd_mr}<&-
}
gitlab_read_threads() {
local var_name=$1
IFS= read -r -d '' -u "$git_mr_fd_th" "$var_name"
exec {git_mr_fd_th}<&-
}
################################################################################
# Merge request utility functions
guess_issue_code() {
[[ -z $git_mr_unguessable_issue_code ]] || return
[[ -n $JIRA_CODE_PATTERN ]] || { echo_error "JIRA_CODE_PATTERN not set - unable to guess issue code"; return "$ERR_MR_ENV"; }
local branch=${1:-$(git_current_branch)}
local issue_code; issue_code=$(echo "${branch}" |
grep -Eo "$JIRA_CODE_PATTERN" |
tail -n1)
if [[ -z $issue_code ]]; then
echo_error "Unable to guess issue code"
return 1
fi
echo_debug "Issue code: $issue_code"
echo "$issue_code"
}
mr_title() {