summaryrefslogtreecommitdiff
path: root/git-pull-request.sh
blob: 7ba565f85bf98d4a863c5e902fb85c0bfffbcb66 (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
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
#!/bin/bash
# Note, yes, this is a bash script, don't expect it to work with dash or zsh

SUBDIRECTORY_OK=Yes
OPTIONS_KEEPDASHDASH=Yes
OPTIONS_SPEC="\
git pull-request [options] <cmd> [args]

Available sub-commands are:

list       List pull requests along with their status
precis     Show the precis from a given pull-request's creation
create     Create a new pull request
merge      Merge a given pull request into your current branch
needs-work Indicate a pull request needs additional work before merging
reject     Reject a pull request
archive    Archive a pull request

--
 General Options
q,quiet     Be less verbose
g,git       Show the git commands being run behind the curtain

 List Options
H,heads     Show the non-archived pull requests
A,archive   Show the archived pull requests
w,waiting   Show only those which are 'waiting' on review/merge
p,pattern=  Specify a regexp to match for which pull requests to show
"

. git-sh-setup

# Cmdline options
# GIT_QUIET defined in git-sh-setup and is for 'say'
# GIT_SHOWCMD if 1 will show any sub-executed git commands
GIT_SHOWCMD=0

while test $# != 0
do
        case "$1" in
	-q)     GIT_QUIET=1 ;;
	-g)     GIT_SHOWCMD=1 ;;
	-H)     SHOW_HEADS=1 ;;
        -A)     SHOW_ARCHIVE=1 ;;
	-w)     SHOW_WAITING=1 ;;
        -p)     SHOW_PATTERN="$2"; shift ;;
        --) shift; break;;
        *)      usage ;;
        esac
        shift
done

SUBCMD="$1"
shift

if test "x$SUBCMD" = "x"; then
  SUBCMD="list"
fi

#############################################################################
##  Utility functions  ######################################################
#############################################################################

rgit ()
{
    test "x$GIT_SHOWCMD" = "x1" && echo >&2 "+ git $*"
    git "$@"
}

find_requests ()
{
    local SUB
    SUB="$1"
    test "x$SUB" = "x" && SUB="heads"
    rgit show-ref | sane_grep " refs/pull-requests/${SUB}/.*__meta\$" | \
	sed -e 's!.* refs/pull-requests/'"${SUB}"'/!!' | sed -e 's/__meta$//'
}

first_commit_on ()
{
    rgit rev-list --reverse "$1" | head -n 1
}

load_meta_from ()
{
    local SHA
    SHA="$1"
    
    unset -v METADATA
    declare -g -A METADATA
    METADATA[META_SHA]="$SHA"
    
    local METATEXT
    METATEXT=$(rgit cat-file -p "$SHA":pull-request.meta | \
	sed -e's/=/ /')

    if test "x$METATEXT" = "x"; then
	echo >&2 Unable to read metadata from "$SHA":pull-request.meta
	exit 128
    fi

    while read KEY VALUE; do
	METADATA["${KEY}"]="${VALUE}"
    done <<<"${METATEXT}"

    local BAD
    for REQ in STATE COMMIT ONTOP LANDINTO; do
	if test "x${METADATA[${REQ}]}" = "x"; then
	    echo >&2 "Reading ${SHA}:pull-request.meta: Metadata lacks $REQ"
	    BAD=1
	fi
    done
    test "x$BAD" = "x" || exit 1
    METADATA[ROOT]=$(first_commit_on "${SHA}")
}

display_meta_summary ()
{
    local PR
    PR="$1"
    
    echo -ne "${PR}\t${METADATA[STATE]}\t"
    echo $(rgit log --pretty="format:%s" "${METADATA[ROOT]}")
}

summarise_meta_at ()
{
    local PR SHA BRANCH
    PR="$1"
    SHA="$2"

    load_meta_from "$SHA"
    display_meta_summary "${PR}"
}

inject_metadata_file ()
{
    cat > "${GIT_DIR}/PULL_REQUEST_META" <<EOF
STATE=${METADATA[STATE]}
COMMIT=${METADATA[COMMIT]}
LANDINTO=${METADATA[LANDINTO]}
ONTOP=${METADATA[ONTOP]}
EOF
    rgit hash-object -t blob -w "${GIT_DIR}/PULL_REQUEST_META"
    rm -f "${GIT_DIR}/PULL_REQUEST_META"
}

commit_is_merged ()
{
    local WHAT WHERE EMPTY
    WHAT="$1"
    WHERE="$2"
    EMPTY=$(rgit rev-list "$WHERE" | sane_grep -F "$WHAT")
    test "x$EMPTY" = "x" && return 1
    return 0
}

#############################################################################
##  Command implementations  ################################################
#############################################################################

cmd_list () {
    test "x$SHOW_HEADS$SHOW_ARCHIVE" = "x" && SHOW_HEADS=1
    local GREP
    test "x$SHOW_PATTERN" = "x" || GREP="| sane_grep '$SHOW_PATTERN'"
    local META_HEADS META_ARCHIVE
    test "x$SHOW_HEADS" = "x1" && META_HEADS=$(find_requests heads ${GREP})
    test "x$SHOW_ARCHIVE" = "x1" && META_ARCHIVE=$(find_requests archive ${GREP})

    local SHOWN
    METAS="${META_HEADS} ${META_ARCHIVE}"
    for META in ${METAS}; do
	local COMMIT BRANCH
	while read COMMIT BRANCH; do
	    load_meta_from "${COMMIT}"
	    local WANT=1
	    if test "x$SHOW_WAITING" = "x1"; then
		case "${METADATA[STATE]}" in
		    new|updated) ;;
		    *)
			WANT=0
			;;
		esac
	    fi
	    if test "x$WANT" = "x1"; then
		display_meta_summary "${META}"
		SHOWN=1
	    fi
	done <<<$(rgit show-ref "${META}"__meta | sane_grep -v -F "/remotes/")
    done

    if test "x$SHOWN" != "x1"; then
	echo 2>&1 "No pull-requests found matching criteria"
	exit 1
    fi
}

cmd_precis () {
    local PR
    PR="$1"
    if test "x$PR" = "x"; then
	echo >&2 "Please specify a pull-request to retrieve the precis of."
	exit 1
    fi
    local COMMIT BRANCH
    while read _COMMIT _BRANCH; do
	COMMIT="${_COMMIT}"
	BRANCH="${_BRANCH}"
    done <<<$(rgit show-ref "$PR"__meta)
    if test "x$COMMIT" = "x"; then
	echo >&2 "Unknown pull-request '${PR}'"
	exit 1
    fi
    load_meta_from "${COMMIT}"
    rgit log --pretty="%B" "${METADATA[ROOT]}"
}

cmd_create () {
    local PR
    PR="$1"
    if test "x$PR" = "x"; then
	echo >&2 "Please specify a pull-request name to create."
	exit 1
    fi
    local COMMIT BRANCH
    while read _COMMIT _BRANCH; do
	COMMIT="${_COMMIT}"
	BRANCH="${_BRANCH}"
    done <<<$(rgit show-ref "$PR"__meta)
    if test "x$COMMIT" != "x"; then
	load_meta_from "${COMMIT}"
	echo >&2 "A pull request with that name already exists."
	display_meta_summary "$PR"
	exit 1
    fi

    require_clean_work_tree

    # 0. Ensure we're a tracking something
    BRANCH=$(rgit for-each-ref --format="%(refname:short)" \
             $(rgit symbolic-ref HEAD))
    local TRACKING
    TRACKING=$(rgit config "branch.${BRANCH}.remote" 2>/dev/null)
    if test "x$TRACKING" = "x"; then
	echo >&2 "This branch is not a tracking branch.  Cannot continue"
	exit 1
    fi
    
    # 1. Determine metadata
    unset -v METADATA
    declare -g -A METADATA
    METADATA[STATE]="new"
    while read _COMMIT _BRANCH; do
	METADATA[COMMIT]="${_COMMIT}"
    done <<<$(rgit show-ref --verify $(rgit symbolic-ref HEAD))
    while read _UNAMBIG _LAND; do
	METADATA[LANDINTO]=$(echo "${_LAND}" | sed -e's@^[^/]*/@@')
	METADATA[ONTOP]=$(rgit merge-base "${METADATA[COMMIT]}" "${_UNAMBIG}")
    done <<<$(rgit for-each-ref --format="%(upstream) %(upstream:short)" \
              $(rgit symbolic-ref HEAD))

    # 2. Produce precis template and edit it
    cat > "${GIT_DIR}/PULL_REQUEST_EDITMSG" <<EOF

# This message will become the precis for your pull request.
# If you do not want to create the pull request, you should quit the editor
# without saving the file.
#
# Any line starting with a hash mark will be removed before the pull request
# is committed to the repository.
#
# The first line of your message will be used as the title and the remainder
# will be the body of the precis.  The entire message will be used as the
# commit message for the pull request.
#
# This pull request is called: ${PR}
# It will be of ${METADATA[COMMIT]}
# Against ${METADATA[LANDINTO]} at ${METADATA[ONTOP]}
#
EOF
    local PRESUM POSTSUM
    PRESUM=$(rgit hash-object -t blob "${GIT_DIR}/PULL_REQUEST_EDITMSG")
    git_editor "${GIT_DIR}/PULL_REQUEST_EDITMSG"
    POSTSUM=$(rgit hash-object -t blob "${GIT_DIR}/PULL_REQUEST_EDITMSG")
    # 2.5 (if unchanged, clean up and quit)
    if test "x$PRESUM" = "x$POSTSUM"; then
	echo >&2 "Message unchanged, aborting creation of pull-request"
	rm -f "${GIT_DIR}/PULL_REQUEST_EDITMSG"
	exit 1
    fi
    # 3. Create metadata file, tree, commit and ref.
    local METASUM TREESUM COMMITSUM
    METASUM=$(inject_metadata_file)
    TREESUM=$(echo -e "100644 blob ${METASUM}\tpull-request.meta" | \
	      rgit mktree)
    COMMITSUM=$(sed -e'/^#/d' < "${GIT_DIR}/PULL_REQUEST_EDITMSG" | \
                rgit commit-tree "${TREESUM}")
    rgit update-ref -m "Creation of pull-request ${PR}" \
	"refs/pull-requests/heads/${PR}__meta" "${COMMITSUM}"
    rgit update-ref -m "Copying anchor for pull-request ${PR}" \
	"refs/pull-requests/heads/${PR}__anchor" "${METADATA[COMMIT]}"
    rm -f "${GIT_DIR}/PULL_REQUEST_EDITMSG"
    echo "Pull request ${PR} created successfully"
}

cmd_merge () {
    local PR
    PR="$1"
    shift
    if test "x$PR" = "x"; then
	echo >&2 "Please specify a pull-request name to create."
	exit 1
    fi
    local COMMIT BRANCH
    while read _COMMIT _BRANCH; do
	COMMIT="${_COMMIT}"
	BRANCH="${_BRANCH}"
    done <<<$(rgit show-ref "$PR"__meta)
    if test "x$COMMIT" = "x"; then
	echo >&2 "Specified pull request '${PR}' does not exist."
	exit 1
    fi
    load_meta_from "${COMMIT}"
    display_meta_summary "$PR"

    require_clean_work_tree

    # 1. Find the merge source
    local MERGESRC
    MERGESRC=$(rgit for-each-ref --format="%(refname)" | \
	sane_grep -v -F "/remotes/" | sane_grep -F "/$PR"__anchor)
    test "x$MERGESRC" = "x" && MERGESRC="${METADATA[COMMIT]}"
    # 2. Verify that it's present in the repository
    if ! rgit cat-file -t "$MERGESRC" 2>/dev/null >/dev/null; then
	echo >&2 "Unable to locate merge source ${MERGESRC}.  Cannot continue"
	exit 1
    fi
    # 3. Establish if the current branch is suitable.
    #    ONTOP must exist in this branch
    #    COMMIT must not exist in this branch
    if ! commit_is_merged "${METADATA[ONTOP]}" "HEAD"; then
	echo >&2 "Unable to proceed, the pull-request is on top of something"
	echo >&2 "which is not in this branch."
	echo >&2 "${METADATA[ONTOP]}"
	exit 1
    fi
    if commit_is_merged "${METADATA[COMMIT]}" "HEAD"; then
	echo >&2 "Unable to proceed.  Pull-request already merged into here?"
	exit 1
    fi
    # 4. Warn if the current branch is not the target
    local CURNAME
    CURNAME=$(rgit for-each-ref --format="%(refname:short)" \
	$(rgit symbolic-ref HEAD))
    if test "x$CURNAME" != "x${METADATA[LANDINTO]}"; then
	say "WARNING: Branch wants to land into '${METADATA[LANDINTO]}', not '${CURNAME}'"
	say "         Merge will proceed but pull-request will not auto-close"
    fi
    # 5. Do the merge
    rgit merge --no-ff --no-commit "${MERGESRC}"
}

#############################################################################
##  Command invocation  #####################################################
#############################################################################

if declare -F "cmd_${SUBCMD}" >/dev/null 2>/dev/null; then
    "cmd_${SUBCMD}" "$@"
else
    echo >&2 $0: Unknown sub-command: $SUBCMD
    usage
fi

exit 0