summaryrefslogtreecommitdiff
path: root/git-pull-request.sh
blob: 6531e11288f36048bba4ea3d28af21896c23e70e (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
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
#!/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]

Primary 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 Mark a pull request as needing additional work before merging
merged     Mark a pull request as merged
reject     Mark a pull request as rejected
update     Mark a pull request as updated, updating the anchors etc also.
archive    Archive a pull request

File attachment sub-commands are:

attach     Attach a file to a pull request
ls         List files attached to a pull request
extract    Extract an attached file from 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

 Attach Options
o,overwrite Overwrite any extant file with the new one given
"

. 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 ;;
	-o)     OVERWRITE_ATTACH=1 ;;
        -p)     SHOW_PATTERN="$2"; shift ;;
        --) shift; break;;
        *)      usage ;;
        esac
        shift
done

SUBCMD="$1"
shift

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

SUBCMD=$(echo "${SUBCMD}" | tr 'A-Z' 'a-z' | sed -e's/[^a-z]/_/g')

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

PR_META_FILE="${GIT_DIR}/PULL_REQUEST_META"
PR_EDIT_MSG="${GIT_DIR}/PULL_REQUEST_EDITMSG"
PR_INDEX_FILE="${GIT_DIR}/PULL-REQUEST.index"

#############################################################################
##  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}")
}

load_index_from ()
{
    local SHA
    SHA="$1"
    rm -f "${PR_INDEX_FILE}"
    GIT_INDEX_FILE="${PR_INDEX_FILE}" rgit read-tree "${SHA}"
}

meta_file_exists ()
{
    GIT_INDEX_FILE="${PR_INDEX_FILE}" rgit ls-files --cached | \
	sane_grep -q '^'"$1"'$'
}

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 > "${PR_META_FILE}" <<EOF
STATE=${METADATA[STATE]}
COMMIT=${METADATA[COMMIT]}
LANDINTO=${METADATA[LANDINTO]}
ONTOP=${METADATA[ONTOP]}
EOF
    rgit hash-object -t blob -w "${PR_META_FILE}"
    rm -f "${PR_META_FILE}"
}

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
}

sanitise_filename ()
{
    echo "$1" | sed -e's@^[\./]*@@' -e's@/[\.]*@/@g'
}

#############################################################################
##  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 > "${PR_EDIT_MSG}" <<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 "${PR_EDIT_MSG}")
    git_editor "${PR_EDIT_MSG}"
    POSTSUM=$(rgit hash-object -t blob "${PR_EDIT_MSG}")
    # 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 "${PR_EDIT_MSG}"
	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' < "${PR_EDIT_MSG}" | \
                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 "${PR_EDIT_MSG}"
    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}"
}

cmd_attach () {
    local PR FILE AS
    PR="$1"
    FILE="$2"
    AS="$3"
    if test "x$PR" = "x"; then
	echo >&2 "Please specify a pull-request name to attach files to."
	exit 1
    fi
    if test "x$FILE" = "x"; then
	echo >&2 "Please specify a file to attach to the pull-request."
	exit 1
    fi
    if test "x$AS" = "x"; then
	AS=$(sanitise_filename $(basename "$FILE"))
    else
	AS=$(sanitise_filename "$AS")
    fi

    # Verify that the PR exists, that $FILE exists, and that $AS is not
    # already present.  If $AS is present and --overwrite was not given
    # then refuse to continue
    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}"

    if ! test -e "$FILE"; then
	echo >&2 "Unable to find '${FILE}', sorry"
	exit 1
    fi

    load_index_from "${COMMIT}"

    if meta_file_exists "attached/${AS}"; then
	if test "x$OVERWRITE_ATTACH" = "x"; then
	    echo >&2 "Unable to continue, '${AS}' already attached"
	    exit 1
	fi
    fi

    # Concoct a commit message
    cat > "${PR_EDIT_MSG}" <<EOF

# This message will become the reasoning for attaching this file.  If you do
# not want to attach the file to the pull request, you should quit the editor
# without saving the file.
#
# Any line starting with a hash mark will be removed before the attachment
# 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 reasoning.  The entire message will be used as the
# commit message on the pull request.
#
# This pull request is called: ${PR}
# You are attaching: ${FILE}
# And it's being called: ${AS}
#
EOF
    local PRESUM POSTSUM
    PRESUM=$(rgit hash-object -t blob "${PR_EDIT_MSG}")
    git_editor "${PR_EDIT_MSG}"
    POSTSUM=$(rgit hash-object -t blob "${PR_EDIT_MSG}")
    # 2.5 (if unchanged, clean up and quit)
    if test "x$PRESUM" = "x$POSTSUM"; then
	echo >&2 "Message unchanged, aborting file attachment"
	rm -f "${PR_EDIT_MSG}"
	exit 1
    fi

    local FSHA
    FSHA=$(rgit hash-object -t blob -w "${FILE}")
    GIT_INDEX_FILE="${PR_INDEX_FILE}" rgit update-index --add \
	--cacheinfo "100644" "${FSHA}" "attached/${AS}"
    local TSHA
    TSHA=$(GIT_INDEX_FILE="${PR_INDEX_FILE}" rgit write-tree)
    local CSHA
    CSHA=$(sed -e'/^#/d' < "${PR_EDIT_MSG}" | \
	rgit commit-tree "${TSHA}" -p "${METADATA[META_SHA]}")
    rgit update-ref -m "Attached '${FILE}' as '${AS}' to '${PR}'" \
	"${BRANCH}" "${CSHA}" "${METADATA[META_SHA]}"
    say "'${FILE}' attached as '${AS}'"
    rm -f "${PR_EDIT_MSG}"
    rm -f "${PR_INDEX_FILE}"
}

cmd_ls () {
    local PR
    PR="$1"
    if test "x$PR" = "x"; then
	echo >&2 "Please specify a pull-request name to list attachments 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 "Pull request '${PR}' not found."
	exit 1
    fi

    load_meta_from "${COMMIT}"
    load_index_from "${COMMIT}"
    
    GIT_INDEX_FILE="${PR_INDEX_FILE}" rgit ls-files attached | \
	sed -e's@^attached/@@'
    rm -f "${PR_INDEX_FILE}"
}

cmd_extract () {
    local PR ATT AS
    PR="$1"
    ATT="$2"
    AS="$3"

    if test "x$PR" = "x"; then
	echo >&2 "Please specify a pull-request name to list attachments 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 "Pull request '${PR}' not found."
	exit 1
    fi

    load_meta_from "${COMMIT}"
    load_index_from "${COMMIT}"
    
    if ! meta_file_exists "attached/$ATT"; then
	echo >&2 "Unable to find attachment '${ATT}'"
	exit 1
    fi

    if test "x${AS}" = "x"; then
	AS=$(basename "${ATT}")
    fi

    if test "x${AS}" = "x-"; then
	git cat-file -p "${METADATA[META_SHA]}:attached/${ATT}"
    else
	if test -d "${AS}"; then
	    AS="${AS}/"$(basename "${ATT}")
	fi

	if test -e "${AS}"; then
	    if test "x$OVERWRITE_ATTACH" = "x"; then
		echo >&2 "Unable to extract '${ATT}', '${AS}' already exists"
	    fi
	fi
	say "Extracting '${ATT}' as '${AS}'"
	git cat-file -p "${METADATA[META_SHA]}:attached/${ATT}" > "${AS}"
    fi
}

_cmd_mark () {
    local PR MARKAS
    PR="$1"
    MARKAS="$2"
    if test "x$PR" = "x"; then
	echo >&2 "Please specify a pull-request name to mark as '${MARKAS}'."
	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 "Pull request '${PR}' not found."
	exit 1
    fi

    load_meta_from "${COMMIT}"
    load_index_from "${COMMIT}"

    # Concoct a commit message
    cat > "${PR_EDIT_MSG}" <<EOF

# This message will become the reasoning for marking this pull-request as
# ${MARKAS}.  If you do not want to attach the file to the pull request, you
# should quit the editor without saving the file.
#
# Any line starting with a hash mark will be removed before the attachment
# 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 reasoning.  The entire message will be used as the
# commit message on the pull request.
#
# This pull request is called: ${PR}
#
EOF
    local PRESUM POSTSUM
    PRESUM=$(rgit hash-object -t blob "${PR_EDIT_MSG}")
    git_editor "${PR_EDIT_MSG}"
    POSTSUM=$(rgit hash-object -t blob "${PR_EDIT_MSG}")
    # (if unchanged, clean up and quit)
    if test "x$PRESUM" = "x$POSTSUM"; then
	echo >&2 "Message unchanged, aborting marking pull request '${MARKAS}'"
	rm -f "${PR_EDIT_MSG}"
	exit 1
    fi
    local MSHA
    METADATA[STATE]="${MARKAS}"
    MSHA=$(inject_metadata_file)

    GIT_INDEX_FILE="${PR_INDEX_FILE}" rgit update-index \
	--cacheinfo "100644" "${MSHA}" "pull-request.meta"
    local TSHA
    TSHA=$(GIT_INDEX_FILE="${PR_INDEX_FILE}" rgit write-tree)
    local CSHA
    CSHA=$(sed -e'/^#/d' < "${PR_EDIT_MSG}" | \
	rgit commit-tree "${TSHA}" -p "${METADATA[META_SHA]}")
    rgit update-ref -m "Updated state of '${PR}' to '${MARKAS}'" \
	"${BRANCH}" "${CSHA}" "${METADATA[META_SHA]}"
    say "'${PR}' marked '${MARKAS}'"
    rm -f "${PR_EDIT_MSG}"
    rm -f "${PR_INDEX_FILE}"
}

cmd_needs_work () {
    _cmd_mark "$1" "needs-work"
}

cmd_reject () {
    _cmd_mark "$1" "rejected"
}

cmd_merged () {
    _cmd_mark "$1" "merged"
}

cmd_update () {
    local PR
    PR="$1"
    if test "x$PR" = "x"; then
	echo >&2 "Please specify a pull-request name to update."
	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 "Pull request '${PR}' not found."
	exit 1
    fi

    load_meta_from "${COMMIT}"
    load_index_from "${COMMIT}"

    require_clean_work_tree

    # Determine new SHA
    local NEWCOMMIT
    NEWCOMMIT=$(rgit for-each-ref --format="%(objectname)" \
	$(rgit symbolic-ref HEAD))

    if test "x${METADATA[COMMIT]}" = "x${NEWCOMMIT}"; then
	echo >&2 "You haven't changed anything, cannot update pull request"
	exit 1
    fi

    # Concoct a commit message
    cat > "${PR_EDIT_MSG}" <<EOF

# This message will become the reasoning for marking this pull-request as
# updated.  If you do not want to attach the file to the pull request, you
# should quit the editor without saving the file.
#
# Any line starting with a hash mark will be removed before the attachment
# 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 reasoning.  The entire message will be used as the
# commit message on the pull request.
#
# This pull request is called: ${PR}
# It was for ${METADATA[COMMIT]}
# It will now be for ${NEWCOMMIT}
#
# The following is the diffstat between the two:
EOF
    local OLDCOMMIT
    OLDCOMMIT="${METADATA[COMMIT]}"
    METADATA[COMMIT]="${NEWCOMMIT}"
    METADATA[STATE]="updated"
    rgit diff --stat "${OLDCOMMIT}" "${NEWCOMMIT}" | \
	sed -e's/^/# /' >> "${PR_EDIT_MSG}"
    local PRESUM POSTSUM
    PRESUM=$(rgit hash-object -t blob "${PR_EDIT_MSG}")
    git_editor "${PR_EDIT_MSG}"
    POSTSUM=$(rgit hash-object -t blob "${PR_EDIT_MSG}")
    # (if unchanged, clean up and quit)
    if test "x$PRESUM" = "x$POSTSUM"; then
	echo >&2 "Message unchanged, aborting marking pull request '${MARKAS}'"
	rm -f "${PR_EDIT_MSG}"
	exit 1
    fi
    local MSHA
    MSHA=$(inject_metadata_file)

    GIT_INDEX_FILE="${PR_INDEX_FILE}" rgit update-index \
	--cacheinfo "100644" "${MSHA}" "pull-request.meta"
    local TSHA
    TSHA=$(GIT_INDEX_FILE="${PR_INDEX_FILE}" rgit write-tree)
    local CSHA
    CSHA=$(sed -e'/^#/d' < "${PR_EDIT_MSG}" | \
	rgit commit-tree "${TSHA}" -p "${METADATA[META_SHA]}")
    rgit update-ref -m "Updated '${PR}' to '${NEWCOMMIT}'" \
	"${BRANCH}" "${CSHA}" "${METADATA[META_SHA]}"
    rgit update-ref -m "Copying anchor for pull-request ${PR}" \
	"refs/pull-requests/heads/${PR}__anchor" "${NEWCOMMIT}" "${OLDCOMMIT}"
    say "'${PR}' updated"
    rm -f "${PR_EDIT_MSG}"
    rm -f "${PR_INDEX_FILE}"
}

cmd_archive () {
    local PR
    PR="$1"
    if test "x$PR" = "x"; then
	echo >&2 "Please specify a pull-request name to archive."
	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 "Pull request '${PR}' not found."
	exit 1
    fi

    if sane_grep -q -F /archive/ <<<"${BRANCH}"; then
	echo >&2 "Pull request '${PR}' is already archived"
	exit 1
    fi

    load_meta_from "${COMMIT}"
    case "${METADATA[STATE]}" in
	merged|rejected)
	    ;;
	*)
	    echo >&2 "Pull request '${PR}' is not merged or rejected"
	    exit 1
	    ;;
    esac

    rgit update-ref -m "Archive '${PR}'" \
	"refs/pull-requests/archive/${PR}__meta" "${COMMIT}"
    rgit update-ref -m "Archive '${PR}'" -d \
	"refs/pull-requests/heads/${PR}__meta"
    rgit update-ref -m "Archive '${PR}'" -d \
	"refs/pull-requests/heads/${PR}__anchor"
    exit 0
}

#############################################################################
##  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