robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
40.6 KiB1130 linesraw
1#!/usr/bin/env bash
2
3set -e
4set -u
5# Use privileged mode, which e.g. skips using CDPATH.
6set -p
7# https://www.shellcheck.net/wiki/SC2031
8shopt -s lastpipe
9
10# Ensure that the user has a bash that supports -A
11if [[ "${BASH_VERSINFO[0]}" -lt 4  ]]; then
12  >&2 echo "error: script requires bash 4+ (you have ${BASH_VERSION})."
13  exit 1
14fi
15
16readonly NVIM_SOURCE_DIR="${NVIM_SOURCE_DIR:-$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)}"
17readonly VIM_SOURCE_DIR_DEFAULT="${NVIM_SOURCE_DIR}/.vim-src"
18readonly VIM_SOURCE_DIR="${VIM_SOURCE_DIR:-${VIM_SOURCE_DIR_DEFAULT}}"
19BASENAME="$(basename "${0}")"
20readonly BASENAME
21readonly BRANCH_PREFIX="vim-"
22readonly VIMPATCH_RANGE=38fb83585421c45828a4934fc75f7952b2baf116..HEAD
23
24CREATED_FILES=()
25
26usage() {
27  echo "Port Vim patches to Neovim"
28  echo "https://neovim.io/doc/user/dev_vimpatch.html"
29  echo
30  echo "Usage:  ${BASENAME} [-h | -l | -p vim-revision | -r pr-number]"
31  echo
32  echo "Options:"
33  echo "    -h                 Show this message and exit."
34  echo "    -l [git-log opts]  List missing Vim patches."
35  echo "    -L [git-log opts]  List missing Vim patches (for scripts)."
36  echo "    -m {vim-revision}  List previous (older) missing Vim patches."
37  echo "    -M                 List all merged patch-numbers (since current v:version) in ascending order."
38  echo "    -n                 List possible N/A Vim patches."
39  echo "    -p {vim-revision}  Download and generate a Vim patch. vim-revision"
40  echo "                       can be a Vim version (8.1.xxx) or a Git hash."
41  echo "    -P {vim-revision}  Download, generate and apply a Vim patch."
42  echo "    -g {vim-revision}  Download a Vim patch."
43  echo "    -s [pr args]       Create a vim-patch pull request."
44  echo "    -r {pr-number}     Review a vim-patch pull request."
45  echo "    -V                 Clone the Vim source code to \$VIM_SOURCE_DIR."
46  echo
47  echo "    \$VIM_SOURCE_DIR controls where Vim sources are found"
48  echo "    (default: '${VIM_SOURCE_DIR_DEFAULT}')"
49  echo
50  echo "Examples:"
51  echo
52  echo " - List missing patches for a given file (in the Vim source):"
53  echo "   $0 -l -- src/edit.c"
54}
55
56# Run git with inline config to avoid error with developer's .gitconfig.
57_git() {
58  local -a git_args
59  git_args=("$@")
60  git -c log.showSignature=false "${git_args[@]}"
61}
62
63msg_ok() {
64  printf '\e[32m✔\e[0m %s\n' "$@"
65}
66
67msg_err() {
68  printf '\e[31m✘\e[0m %s\n' "$@" >&2
69}
70
71# Checks if a program is in the user's PATH, and is executable.
72check_executable() {
73  test -x "$(command -v "${1}")"
74}
75
76require_executable() {
77  if ! check_executable "${1}"; then
78    >&2 echo "${BASENAME}: '${1}' not found in PATH or not executable."
79    exit 1
80  fi
81}
82
83clean_files() {
84  if [[ ${#CREATED_FILES[@]} -eq 0 ]]; then
85    return
86  fi
87
88  echo
89  echo "Created files:"
90  local file
91  for file in "${CREATED_FILES[@]}"; do
92    echo "  • ${file}"
93  done
94
95  read -p "Delete these files (Y/n)? " -n 1 -r reply
96  echo
97  if [[ "${reply}" == n ]]; then
98    echo "You can use 'git clean' to remove these files when you're done."
99  else
100    rm -- "${CREATED_FILES[@]}"
101  fi
102}
103
104get_vim_sources() {
105  require_executable git
106
107  if [[ ! -d ${VIM_SOURCE_DIR} ]]; then
108    echo "Cloning Vim into: ${VIM_SOURCE_DIR}"
109    git clone https://github.com/vim/vim.git "${VIM_SOURCE_DIR}"
110    cd "${VIM_SOURCE_DIR}"
111  elif [[ "${1-}" == update ]]; then
112    cd "${VIM_SOURCE_DIR}"
113    if ! [ -d ".git" ] \
114        && ! [ "$(git rev-parse --show-toplevel)" = "${VIM_SOURCE_DIR}" ]; then
115      msg_err "${VIM_SOURCE_DIR} does not appear to be a git repository."
116      echo "  Please remove it and try again."
117      exit 1
118    fi
119    echo "Updating Vim sources: ${VIM_SOURCE_DIR}"
120    if git pull --ff; then
121      msg_ok "Updated Vim sources."
122    else
123      msg_err "Could not update Vim sources; ignoring error."
124    fi
125  else
126    cd "${VIM_SOURCE_DIR}"
127  fi
128}
129
130commit_message() {
131  if [[ "${vim_message}" == "vim-patch:${vim_version}:"* ]]; then
132    printf '%s\n\n%s\n\n%s' "${vim_message}" "${vim_commit_url}" "${vim_coauthors}"
133  else
134    printf 'vim-patch:%s: %s\n\n%s\n\n%s' "${vim_version:0:7}" "${vim_message}" "${vim_commit_url}" "${vim_coauthors}"
135  fi
136}
137
138find_git_remote() {
139  local git_remote
140  if [[ "${1-}" == fork ]]; then
141    git_remote=$(git remote -v | awk '$2 !~ /github.com[:\/]neovim\/neovim/ && $3 == "(fetch)" {print $1; exit}')
142  else
143    git_remote=$(git remote -v | awk '$2 ~ /github.com[:\/]neovim\/neovim/ && $3 == "(fetch)" {print $1; exit}')
144  fi
145  if [[ -z "$git_remote" ]]; then
146    git_remote="origin"
147  fi
148  echo "$git_remote"
149}
150
151# Assign variables for a given Vim tag, patch version, or commit.
152# Might exit in case it cannot be found, after updating Vim sources.
153assign_commit_details() {
154  local vim_commit_ref
155  if [[ ${1} =~ v?[0-9]\.[0-9]\.[0-9]{3,4} ]]; then
156    # Interpret parameter as version number (tag).
157    if [[ "${1:0:1}" == v ]]; then
158      vim_version="${1:1}"
159      vim_tag="${1}"
160    else
161      vim_version="${1}"
162      vim_tag="v${1}"
163    fi
164    vim_commit_ref="$vim_tag"
165    local munge_commit_line=true
166  else
167    # Interpret parameter as commit hash.
168    vim_version="${1:0:7}"
169    vim_tag=
170    vim_commit_ref="$vim_version"
171    local munge_commit_line=false
172  fi
173
174  local get_vim_commit_cmd="_git -C ${VIM_SOURCE_DIR} log -1 --format=%H ${vim_commit_ref} --"
175  vim_commit=$($get_vim_commit_cmd 2>&1) || {
176    # Update Vim sources.
177    get_vim_sources update
178    vim_commit=$($get_vim_commit_cmd 2>&1) || {
179      >&2 msg_err "Couldn't find Vim revision '${vim_commit_ref}': git error: ${vim_commit}."
180      exit 3
181    }
182  }
183
184  vim_commit_url="https://github.com/vim/vim/commit/${vim_commit}"
185  vim_message="$(_git -C "${VIM_SOURCE_DIR}" log -1 --pretty='format:%B' "${vim_commit}" \
186      | sed -Ee 's/([^A-Za-z0-9])(#[0-9]{1,})/\1vim\/vim\2/g')"
187  local vim_coauthor0
188  vim_coauthor0="$(_git -C "${VIM_SOURCE_DIR}" log -1 --pretty='format:Co-authored-by: %an <%ae>' "${vim_commit}")"
189  # Extract co-authors from the commit message.
190  vim_coauthors="$(echo "${vim_message}" | (grep -E '^Co-[Aa]uthored-[Bb]y: ' || true) | (grep -Fxv "${vim_coauthor0}" || true))"
191  vim_coauthors="$(echo "${vim_coauthor0}"; echo "${vim_coauthors}")"
192  # Upstream may credit an AI tool; we don't advertise those, see AGENTS.md.
193  vim_coauthors="$(echo "${vim_coauthors}" \
194      | (grep -Eiv '^Co-authored-by: .*(aider|anthropic|chatgpt|claude|codex|copilot|cursor|devin|gemini|openai|opencode|windsurf)' || true))"
195  # Remove Co-authored-by and Signed-off-by lines from the commit message.
196  vim_message="$(echo "${vim_message}" | grep -Ev '^(Co-[Aa]uthored|Signed-[Oo]ff)-[Bb]y: ')"
197  if [[ ${munge_commit_line} == "true" ]]; then
198    # Remove first line of commit message.
199    vim_message="$(echo "${vim_message}" | sed -Ee '1s/^patch /vim-patch:/')"
200  fi
201  patch_file="vim-${vim_version}.patch"
202}
203
204# Patch surgery
205preprocess_patch() {
206  local file="$1"
207  local nvim="nvim -u NONE -n -i NONE --headless"
208
209  # Remove Filelist, README
210  local na_files='Filelist\|README.*'
211  2>/dev/null $nvim --cmd 'set dir=/tmp' +'g@^diff --git [ab]/\<\%('"${na_files}"'\)\>@exe "norm! d/\\v(^diff)|%$\r"' +w +q "$file"
212
213  # Remove *.proto, Make*, INSTALL*, gui_*, beval.*, some if_*, gvim, libvterm, tee, VisVim, xpm, xxd
214  local na_src='auto\|configure.*\|GvimExt\|hardcopy.*\|libvterm\|proto\|tee\|VisVim\|xpm\|xxd\|Make.*\|INSTALL.*\|beval.*\|gui.*\|if_cscop\|if_lua\|if_mzsch\|if_olepp\|if_ole\|if_perl\|if_py\|if_ruby\|if_tcl\|if_xcmdsrv'
215  2>/dev/null $nvim --cmd 'set dir=/tmp' +'g@^diff --git [ab]/src/\S*\<\%(testdir/\)\@<!\%('"${na_src}"'\)\>@exe "norm! d/\\v(^diff)|%$\r"' +w +q "$file"
216
217  # Remove runtime/print/
218  local na_rt='print\/.*'
219  2>/dev/null $nvim --cmd 'set dir=/tmp' +'g@^diff --git [ab]/runtime/\<\%('"${na_rt}"'\)\>@exe "norm! d/\\v(^diff)|%$\r"' +w +q "$file"
220
221  # Remove unwanted Vim doc files.
222  local na_doc='channel\.txt\|if_cscop\.txt\|netbeans\.txt\|os_\w\+\.txt\|print\.txt\|term\.txt\|testing\.txt\|todo\.txt\|vim9\.txt\|tags\|test_urls\.vim'
223  2>/dev/null $nvim --cmd 'set dir=/tmp' +'g@^diff --git [ab]/runtime/doc/\<\%('"${na_doc}"'\)\>@exe "norm! d/\\v(^diff)|%$\r"' +w +q "$file"
224
225  # Remove "Last change ..." changes in doc files.
226  2>/dev/null $nvim --cmd 'set dir=/tmp' +'%s/^@@.*\n.*For Vim version.*Last change.*\n.*For Vim version.*Last change.*//' +w +q "$file"
227
228  # Remove gui, setup, screen dumps, testdir/Make_*.mak files
229  local na_src_testdir='gui_.*\|Make_amiga\.mak\|Make_dos\.mak\|Make_ming\.mak\|Make_vms\.mms\|dumps/.*\.dump\|setup_gui\.vim'
230  2>/dev/null $nvim --cmd 'set dir=/tmp' +'g@^diff --git [ab]/src/testdir/\<\%('"${na_src_testdir}"'\)\>@exe "norm! d/\\v(^diff)|%$\r"' +w +q "$file"
231
232  # Remove testdir/test_*.vim files
233  local na_src_testdir='balloon.*\|behave\.vim\|channel.*\|crypt\.vim\|cscope\.vim\|hardcopy\.vim\|job_fails\.vim\|json\.vim\|listener\.vim\|mzscheme\.vim\|netbeans.*\|paste\.vim\|popupwin.*\|python2\.vim\|pyx2\.vim\|restricted\.vim\|shortpathname\.vim\|sound\.vim\|tcl\.vim\|terminal.*\|xxd\.vim'
234  2>/dev/null $nvim --cmd 'set dir=/tmp' +'g@^diff --git [ab]/src/testdir/\<test_\%('"${na_src_testdir}"'\)\>@exe "norm! d/\\v(^diff)|%$\r"' +w +q "$file"
235
236  # Remove runtime/*/testdir/ files
237  local na_runtime_testdir='.\+'
238  2>/dev/null $nvim --cmd 'set dir=/tmp' +'g@^diff --git [ab]/runtime/\f\+/testdir/\%('${na_runtime_testdir}'\)\>@exe "norm! d/\\v(^diff)|%$\r"' +w +q "$file"
239
240  # Remove N/A src/*.[ch] files: sound.c, version.c
241  local na_src_c='sound\|version'
242  2>/dev/null $nvim --cmd 'set dir=/tmp' +'g@^diff --git [ab]/src/\<\%('"${na_src_c}"'\)\.[ch]\>@exe "norm! d/\\v(^diff)|%$\r"' +w +q "$file"
243
244  # Remove some *.po files. #5622
245  # Also remove vim.pot which is updated on almost every source change.
246  local na_po='sjiscorr\.c\|ja\.sjis\.po\|ko\.po\|pl\.cp1250\.po\|pl\.po\|ru\.cp1251\.po\|uk\.cp1251\.po\|zh_CN\.cp936\.po\|zh_CN\.po\|zh_TW\.po\|vim\.pot'
247  2>/dev/null $nvim --cmd 'set dir=/tmp' +'g@^diff --git [ab]/src/po/\<\%('${na_po}'\)\>@exe "norm! d/\\v(^diff)|%$\r"' +w +q "$file"
248
249  # Remove vimrc_example.vim
250  local na_vimrcexample='vimrc_example\.vim'
251  2>/dev/null $nvim --cmd 'set dir=/tmp' +'g@^diff --git [ab]/runtime/\<\%('${na_vimrcexample}'\)\>@exe "norm! d/\\v(^diff)|%$\r"' +w +q "$file"
252
253  # Rename src/testdir/ paths to test/old/testdir/
254  LC_ALL=C sed -Ee 's/( [ab])\/src\/testdir/\1\/test\/old\/testdir/g' \
255    "$file" > "$file".tmp && mv "$file".tmp "$file"
256
257  # Rename src/ paths to src/nvim/
258  LC_ALL=C sed -Ee 's/( [ab]\/src)/\1\/nvim/g' \
259    "$file" > "$file".tmp && mv "$file".tmp "$file"
260
261  # Rename evalfunc.c to eval/funcs.c
262  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/evalfunc\.c/\1\/eval\/funcs.c/g' \
263    "$file" > "$file".tmp && mv "$file".tmp "$file"
264
265  # Rename list.c to eval/list.c
266  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/list\.c/\1\/eval\/list.c/g' \
267    "$file" > "$file".tmp && mv "$file".tmp "$file"
268
269  # Rename evalvars.c to eval/vars.c
270  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/evalvars\.c/\1\/eval\/vars.c/g' \
271    "$file" > "$file".tmp && mv "$file".tmp "$file"
272
273  # Rename userfunc.c to eval/userfunc.c
274  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/userfunc\.c/\1\/eval\/userfunc.c/g' \
275    "$file" > "$file".tmp && mv "$file".tmp "$file"
276
277  # Rename evalbuffer.c to eval/buffer.c
278  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/evalbuffer\.c/\1\/eval\/buffer.c/g' \
279    "$file" > "$file".tmp && mv "$file".tmp "$file"
280
281  # Rename evalwindow.c to eval/window.c
282  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/evalwindow\.c/\1\/eval\/window.c/g' \
283    "$file" > "$file".tmp && mv "$file".tmp "$file"
284
285  # Rename cindent.c to indent_c.c
286  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/cindent\.c/\1\/indent_c.c/g' \
287    "$file" > "$file".tmp && mv "$file".tmp "$file"
288
289  # Rename map.c to mapping.c
290  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/map\.c/\1\/mapping.c/g' \
291    "$file" > "$file".tmp && mv "$file".tmp "$file"
292
293  # Rename getchar.c to input.c
294  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/getchar\.c/\1\/input.c/g' \
295    "$file" > "$file".tmp && mv "$file".tmp "$file"
296
297  # Rename edit.c to insert.c
298  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/edit\.c/\1\/insert.c/g' \
299    "$file" > "$file".tmp && mv "$file".tmp "$file"
300
301  # Rename profiler.c to profile.c
302  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/profiler\.c/\1\/profile.c/g' \
303    "$file" > "$file".tmp && mv "$file".tmp "$file"
304
305  # Rename regexp_(bt|nfa).c to regexp.c
306  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/regexp_(bt|nfa)\.c/\1\/regexp.c/g' \
307    "$file" > "$file".tmp && mv "$file".tmp "$file"
308
309  # Rename scriptfile.c to runtime.c
310  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/scriptfile\.c/\1\/runtime.c/g' \
311    "$file" > "$file".tmp && mv "$file".tmp "$file"
312
313  # Rename session.c to ex_session.c
314  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/session\.c/\1\/ex_session.c/g' \
315    "$file" > "$file".tmp && mv "$file".tmp "$file"
316
317  # Rename highlight.c to highlight_group.c
318  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/highlight\.c/\1\/highlight_group.c/g' \
319    "$file" > "$file".tmp && mv "$file".tmp "$file"
320
321  # Rename locale.c to os/lang.c
322  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/locale\.c/\1\/os\/lang.c/g' \
323    "$file" > "$file".tmp && mv "$file".tmp "$file"
324
325  # Rename keymap.h to keycodes.h
326  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/keymap\.h/\1\/keycodes.h/g' \
327    "$file" > "$file".tmp && mv "$file".tmp "$file"
328
329  # Rename term.c to keycodes.c
330  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/term\.c/\1\/keycodes.c/g' \
331    "$file" > "$file".tmp && mv "$file".tmp "$file"
332
333  # Rename option.h to option_vars.h
334  LC_ALL=C sed -Ee 's/( [ab]\/src\/nvim)\/option\.h/\1\/option_vars.h/g' \
335    "$file" > "$file".tmp && mv "$file".tmp "$file"
336
337  # Rename runtime/doc/eval.txt to runtime/doc/vimeval.txt
338  LC_ALL=C sed -Ee 's/( [ab]\/runtime\/doc)\/eval\.txt/\1\/vimeval.txt/g' \
339    "$file" > "$file".tmp && mv "$file".tmp "$file"
340
341  # Rename <lang>.txt to l10n-<lang>.txt
342  LC_ALL=C sed -Ee 's/( [ab]\/runtime\/doc)\/(arabic|hebrew|russian|vietnamese)\.txt/\1\/l10n-\2.txt/g' \
343    "$file" > "$file".tmp && mv "$file".tmp "$file"
344
345  # Rename version*.txt to news.txt
346  LC_ALL=C sed -Ee 's/( [ab]\/runtime\/doc)\/version[0-9]+\.txt/\1\/news.txt/g' \
347    "$file" > "$file".tmp && mv "$file".tmp "$file"
348
349  # Rename sponsor.txt to intro.txt
350  LC_ALL=C sed -Ee 's/( [ab]\/runtime\/doc)\/sponsor\.txt/\1\/intro.txt/g' \
351    "$file" > "$file".tmp && mv "$file".tmp "$file"
352
353  # Rename path to check_colors.vim
354  LC_ALL=C sed -Ee 's/( [ab]\/runtime)\/colors\/(tools\/check_colors\.vim)/\1\/\2/g' \
355    "$file" > "$file".tmp && mv "$file".tmp "$file"
356}
357
358uncrustify_patch() {
359  git diff --quiet || {
360    >&2 echo 'Vim source working tree dirty, aborting.'
361    exit 1
362  }
363
364  local patch_path="$NVIM_SOURCE_DIR"/build/vim_patch
365  rm -rf "$patch_path"
366  mkdir -p "$patch_path"/{a,b}
367
368  local commit="$1"
369  for file in $(git diff-tree --name-only --no-commit-id -r --diff-filter=a "$commit"); do
370    git --work-tree="$patch_path"/a checkout --quiet "$commit"~ -- "$file"
371  done
372  for file in $(git diff-tree --name-only --no-commit-id -r --diff-filter=d "$commit"); do
373    git --work-tree="$patch_path"/b checkout --quiet "$commit" -- "$file"
374  done
375  git reset --quiet --hard HEAD
376
377  # If the difference are drastic enough uncrustify may need to be used more
378  # than once. This is obviously a bug that needs to be fixed on uncrustify's
379  # end, but in the meantime this workaround is sufficient.
380  for _ in {1..2}; do
381    "$NVIM_SOURCE_DIR"/build/usr/bin/uncrustify -c "$NVIM_SOURCE_DIR"/src/uncrustify.cfg -q --replace --no-backup "$patch_path"/{a,b}/src/*.[ch]
382  done
383
384  (cd "$patch_path" && (git --no-pager diff --no-index --no-prefix --patch --unified=5 --color=never a/ b/ || true))
385}
386
387get_vimpatch() {
388  get_vim_sources
389
390  assign_commit_details "${1}"
391
392  msg_ok "Found Vim revision '${vim_commit}'."
393
394  local patch_content
395  if check_executable "$NVIM_SOURCE_DIR"/build/usr/bin/uncrustify; then
396    patch_content="$(uncrustify_patch "${vim_commit}")"
397  else
398    patch_content="$(git --no-pager show --unified=5 --color=never -1 --pretty=medium "${vim_commit}")"
399  fi
400
401  cd "${NVIM_SOURCE_DIR}"
402
403  printf "Creating patch...\n"
404  echo "$patch_content" > "${NVIM_SOURCE_DIR}/${patch_file}"
405
406  printf "Pre-processing patch...\n"
407  preprocess_patch "${NVIM_SOURCE_DIR}/${patch_file}"
408
409  msg_ok "Saved patch to '${NVIM_SOURCE_DIR}/${patch_file}'."
410}
411
412stage_patch() {
413  get_vimpatch "$1"
414  local try_apply="${2:-}"
415
416  local nvim_remote
417  nvim_remote="$(find_git_remote)"
418  local checked_out_branch
419  checked_out_branch="$(git rev-parse --abbrev-ref HEAD)"
420
421  if [[ "${checked_out_branch}" == ${BRANCH_PREFIX}* ]]; then
422    msg_ok "Current branch '${checked_out_branch}' seems to be a vim-patch"
423    echo "  branch; not creating a new branch."
424  else
425    printf '\nFetching "%s/master".\n' "${nvim_remote}"
426    if output="$(git fetch "$nvim_remote" master 2>&1)"; then
427      msg_ok "$output"
428    else
429      msg_err "$output"
430      exit 1
431    fi
432
433    local nvim_branch="${BRANCH_PREFIX}${vim_version}"
434    echo
435    echo "Creating new branch '${nvim_branch}' based on '${nvim_remote}/master'."
436    cd "${NVIM_SOURCE_DIR}"
437    if output="$(git checkout -b "$nvim_branch" "$nvim_remote/master" 2>&1)"; then
438      msg_ok "$output"
439    else
440      msg_err "$output"
441      exit 1
442    fi
443  fi
444
445  printf "\nCreating empty commit with correct commit message.\n"
446  if output="$(commit_message | git commit --allow-empty --file 2>&1 -)"; then
447    msg_ok "$output"
448  else
449    msg_err "$output"
450    exit 1
451  fi
452
453  local ret=0
454  if test -n "$try_apply" ; then
455    if ! check_executable patch; then
456      printf "\n"
457      msg_err "'patch' command not found\n"
458    else
459      printf "\nApplying patch...\n"
460      patch -p1 --fuzz=1 --no-backup-if-mismatch < "${patch_file}" || ret=$?
461    fi
462    printf "\nInstructions:\n  Proceed to port the patch.\n"
463  else
464    printf '\nInstructions:\n  Proceed to port the patch.\n  Try the "patch" command (or use "%s -P ..." next time):\n    patch -p1 < %s\n' "${BASENAME}" "${patch_file}"
465  fi
466
467  printf '
468  Stage your changes ("git add ..."), then use "git commit --amend" to commit.
469
470  To port more patches (if any) related to %s,
471  run "%s" again.
472    * Do this only for _related_ patches (otherwise it increases the
473      size of the pull request, making it harder to review)
474
475  When you are done, try "%s -s" to create the pull request,
476  or "%s -s --draft" to create a draft pull request.
477
478  See the wiki for more information:
479    * https://neovim.io/doc/user/dev_vimpatch.html
480' "${vim_version}" "${BASENAME}" "${BASENAME}" "${BASENAME}"
481  return $ret
482}
483
484gh_pr() {
485  local pr_title
486  local pr_body
487  pr_title="$1"
488  pr_body="$2"
489  shift 2
490  gh pr create --title "${pr_title}" --body "${pr_body}" "$@"
491}
492
493git_hub_pr() {
494  local pr_message
495  pr_message="$(printf '%s\n\n%s\n' "$1" "$2")"
496  shift 2
497  git hub pull new -m "${pr_message}" "$@"
498}
499
500submit_pr() {
501  require_executable git
502  local push_first
503  push_first=1
504  local submit_fn
505  if check_executable gh; then
506    submit_fn="gh_pr"
507  elif check_executable git-hub; then
508    push_first=0
509    submit_fn="git_hub_pr"
510  else
511    >&2 echo "${BASENAME}: 'gh' or 'git-hub' not found in PATH or not executable."
512    >&2 echo "              Get it here: https://cli.github.com/"
513    exit 1
514  fi
515
516  cd "${NVIM_SOURCE_DIR}"
517  local checked_out_branch
518  checked_out_branch="$(git rev-parse --abbrev-ref HEAD)"
519  if [[ "${checked_out_branch}" != ${BRANCH_PREFIX}* ]]; then
520    msg_err "Current branch '${checked_out_branch}' doesn't seem to be a vim-patch branch."
521    exit 1
522  fi
523
524  local nvim_remote
525  nvim_remote="$(find_git_remote)"
526  local pr_body
527  pr_body="$(_git log --grep=vim-patch --reverse --format='#### %s%n%n%b%n' "${nvim_remote}"/master..HEAD)"
528  local patches
529  # Extract just the "vim-patch:X.Y.ZZZZ" or "vim-patch:sha" portion of each log
530  patches=("$(_git log --grep=vim-patch --reverse --format='%s' "${nvim_remote}"/master..HEAD | sed 's/: .*//')")
531  # shellcheck disable=SC2206
532  patches=(${patches[@]//vim-patch:}) # Remove 'vim-patch:' prefix for each item in array.
533  local pr_title="${patches[*]}" # Create space-separated string from array.
534  pr_title="${pr_title// /,}" # Replace spaces with commas.
535  pr_title="$(printf 'vim-patch:%s' "${pr_title#,}")"
536
537  if [[ $push_first -ne 0 ]]; then
538    local push_remote
539    push_remote="$(git config --get branch."${checked_out_branch}".pushRemote || true)"
540    if [[ -z "$push_remote" ]]; then
541      push_remote="$(git config --get remote.pushDefault || true)"
542      if [[ -z "$push_remote" ]]; then
543        push_remote="$(git config --get branch."${checked_out_branch}".remote || true)"
544        if [[ -z "$push_remote" ]] || [[ "$push_remote" == "$nvim_remote" ]]; then
545          push_remote="$(find_git_remote fork)"
546        fi
547      fi
548    fi
549    echo "Pushing to '${push_remote}/${checked_out_branch}'."
550    if output="$(git push "$push_remote" "$checked_out_branch" 2>&1)"; then
551      msg_ok "$output"
552    else
553      msg_err "$output"
554      exit 1
555    fi
556
557    echo
558  fi
559
560  echo "Creating pull request."
561  if output="$($submit_fn "$pr_title" "$pr_body" "$@" 2>&1)"; then
562    msg_ok "$output"
563  else
564    msg_err "$output"
565    exit 1
566  fi
567
568  echo
569  echo "Cleaning up files."
570  local patch_file
571  for patch_file in "${patches[@]}"; do
572    patch_file="vim-${patch_file}.patch"
573    if [[ ! -f "${NVIM_SOURCE_DIR}/${patch_file}" ]]; then
574      continue
575    fi
576    rm -- "${NVIM_SOURCE_DIR}/${patch_file}"
577    msg_ok "Removed '${NVIM_SOURCE_DIR}/${patch_file}'."
578  done
579}
580
581# Prints all (sorted) "vim-patch:xxx" tokens found in the Nvim git log
582# where xxx is Git commit hash, not X.Y.Z version
583list_vimpatch_hashes() {
584  local patch_pat='[a-z0-9]{7,}'
585  # Use sed…{7,7} to normalize (internal) Git hashes (for tokens caches).
586  diff "${NVIM_SOURCE_DIR}/scripts/vimpatch_commit_ignore.txt" <(
587    _git -C "${NVIM_SOURCE_DIR}" log --format="%H" -E --grep="vim-patch:$patch_pat" "$VIMPATCH_RANGE"
588  ) |
589    grep -e '^> ' |
590    sed -e 's/^> //' |
591    _git -C "${NVIM_SOURCE_DIR}" log --no-walk --stdin \
592    | grep -oE "vim-patch:$patch_pat" \
593    | grep -v "vim-patch:partial" |
594    sed -nEe "s/^vim-patch:($patch_pat).*/\1/p" |
595    sort |
596    uniq
597}
598
599# Prints all merged patches (since current v:version) in ascending order.
600#
601# Search "vim-patch:xxx" tokens in the Nvim git log.
602# Ignore tokens older than current v:version.
603# Left-pad the patch number of "vim-patch:xxx" for stable sort + dedupe.
604# Filter reverted Vim tokens.
605list_vimpatch_numbers() {
606  local patch_pat='(8\.[12]|9\.[0-9])\.[0-9]{1,4}'
607  diff "${NVIM_SOURCE_DIR}/scripts/vimpatch_commit_ignore.txt" <(
608    _git -C "${NVIM_SOURCE_DIR}" log --format="%H" -E --grep="^[* ]*vim-patch:${patch_pat}" "$VIMPATCH_RANGE"
609  ) |
610    grep -e '^> ' |
611    sed -e 's/^> //' |
612    _git -C "${NVIM_SOURCE_DIR}" log --no-walk --stdin --format="%s%n%b" |
613    grep -oE "^[* ]*vim-patch:${patch_pat}" |
614    sed -nEe 's/^[* ]*vim-patch:('"${patch_pat}"').*$/\1/p' |
615    awk '{split($0, a, "."); printf "%d.%d.%04d\n", a[1], a[2], a[3]}' |
616    sort |
617    uniq
618}
619
620# Prints a newline-delimited list of Vim commits, for use by scripts.
621# "$1": use extended format? (with subject)
622# "$@": extra arguments to git-log.
623list_missing_vimpatches() {
624  local VIM_VERSION_0_DATE git_log_format missing_hashes missing_numbers
625  declare -a git_log_args
626  VIM_VERSION_0_DATE=2018-05-17:15:00:00Z
627
628  local extended_format=$1; shift
629  if [[ "$extended_format" == 1 ]]; then
630    git_log_format="%s"
631  else
632    git_log_format=""
633  fi
634
635  # Massage arguments for git-log.
636  declare -A git_log_replacements=(
637    [^\(.*/\)?src/nvim/\(.*\)]="\${BASH_REMATCH[1]}src/\${BASH_REMATCH[2]}"
638    [^\(.*/\)?test/old/\(.*\)]="\${BASH_REMATCH[1]}src/\${BASH_REMATCH[2]}"
639    [^\(.*/\)?\.vim-src/\(.*\)]="\${BASH_REMATCH[2]}"
640  )
641  local i j
642  for i in "$@"; do
643    for j in "${!git_log_replacements[@]}"; do
644      if [[ "$i" =~ $j ]]; then
645        eval "git_log_args+=(${git_log_replacements[$j]})"
646        continue 2
647      fi
648    done
649    git_log_args+=("$i")
650  done
651
652  missing_numbers=$(_git -C "${VIM_SOURCE_DIR}" log --decorate-refs='refs/tags/*' --reverse --since="${VIM_VERSION_0_DATE}" --no-walk --tags --format='%(decorate:prefix=,suffix=,tag=)' "${git_log_args[@]}" |
653    grep -v -F -f <(list_vimpatch_numbers) |
654    sed -E 's/,.*$//')
655  missing_hashes=$(_git -C "${VIM_SOURCE_DIR}" log --decorate-refs='refs/tags/*' --reverse --since="${VIM_VERSION_0_DATE}" --format='%H%D' "${git_log_args[@]}" |
656    grep -v -e 'tag:' |
657    grep -v -f <(list_vimpatch_hashes | sed -E 's/(.*)/^\1/'))
658  if test -n "${git_log_format}"; then
659    (echo "${missing_numbers}"; echo "${missing_hashes}") |
660      _git --no-pager -C "${VIM_SOURCE_DIR}" log --decorate-refs='refs/tags/*' --reverse --no-walk --stdin --format="%H%x00%d%x00: ${git_log_format}" |
661      awk -F '\0' '{ print $2 ? $2$3 : $1$3 }'
662  else
663    echo "${missing_numbers}"
664    echo "${missing_hashes}"
665  fi
666}
667
668# Prints a human-formatted list of Vim commits, with instructional messages.
669# Passes "$@" onto list_missing_vimpatches (args for git-log).
670show_vimpatches() {
671  get_vim_sources update
672  printf "Vim patches missing from Neovim:\n"
673
674  local -A runtime_commits
675  for commit in $(_git -C "${VIM_SOURCE_DIR}" log --format="%H %D" -- runtime | sed -Ee 's/,\? tag: / /g'); do
676    runtime_commits[$commit]=1
677  done
678
679  list_missing_vimpatches 1 "$@" | while read -r vim_commit; do
680    if [[ "${runtime_commits[$vim_commit]-}" ]]; then
681      printf '  • %s (+runtime)\n' "${vim_commit}"
682    else
683      printf '  • %s\n' "${vim_commit}"
684    fi
685  done
686
687  cat << EOF
688
689Instructions:
690  To port one of the above patches to Neovim, execute this script with the patch revision as argument and follow the instructions, e.g.
691  '${BASENAME} -p v8.1.1234', or '${BASENAME} -P v8.1.1234'
692
693  NOTE: Please port the _oldest_ patch if you possibly can.
694        You can use '${BASENAME} -l path/to/file' to see what patches are missing for a file.
695EOF
696}
697
698list_missing_previous_vimpatches_for_patch() {
699  local for_vim_patch="${1}"
700  local vim_commit vim_tag
701  assign_commit_details "${for_vim_patch}"
702
703  local file
704  local -a missing_list
705  local -a fnames
706  while IFS= read -r line ; do
707    fnames+=("$line")
708  done < <(git -C "${VIM_SOURCE_DIR}" diff-tree --no-commit-id --name-only -r "${vim_commit}" -- . ':!src/version.c')
709  local i=0
710  local n=${#fnames[@]}
711  printf '=== getting missing patches for %d files ===\n' "$n"
712  if [[ -z "${vim_tag}" ]]; then
713    printf 'NOTE: "%s" is not a Vim tag - listing all oldest missing patches\n' "${for_vim_patch}" >&2
714  fi
715  for fname in "${fnames[@]}"; do
716    i=$(( i+1 ))
717    printf '[%.*d/%d] %s: ' "${#n}" "$i" "$n" "$fname"
718
719    list_missing_vimpatches 1 -- "${fname}" | while read -r missing_vim_commit_info; do
720      if [[ -z "${missing_vim_commit_info}" ]]; then
721        printf -- "-\r"
722      else
723        printf -- "-\r"
724        local missing_vim_commit="${missing_vim_commit_info%%:*}"
725        if [[ -z "${vim_tag}" ]] || [[ "${missing_vim_commit}" < "${vim_tag}" ]]; then
726          printf -- "%s\n" "$missing_vim_commit_info"
727          missing_list+=("$missing_vim_commit_info")
728        else
729          printf -- "-\r"
730        fi
731      fi
732    done
733  done
734
735  set +u  # Avoid "unbound variable" with bash < 4.4 below.
736  if [[ -z "${missing_list[*]}" ]]; then
737    msg_ok 'no missing previous Vim patches'
738    set -u
739    return 0
740  fi
741  set -u
742
743  local -a missing_unique
744  local stat
745  while IFS= read -r line; do
746    local commit="${line%%:*}"
747    stat="$(git -C "${VIM_SOURCE_DIR}" show --format= --shortstat "${commit}")"
748    missing_unique+=("$(printf '%s\n  %s' "$line" "$stat")")
749  done < <(printf '%s\n' "${missing_list[@]}" | sort -u)
750
751  msg_err "$(printf '%d missing previous Vim patches:' ${#missing_unique[@]})"
752  printf ' - %s\n' "${missing_unique[@]}"
753  return 1
754}
755
756review_commit() {
757  local nvim_commit_url="${1}"
758  local nvim_patch_url="${nvim_commit_url}.patch"
759
760  local git_patch_prefix='Subject: \[PATCH\] '
761  local nvim_patch
762  nvim_patch="$(curl -Ssf "${nvim_patch_url}")"
763  local vim_version
764  vim_version="$(head -n 4 <<< "${nvim_patch}" | sed -nEe 's/'"${git_patch_prefix}"'vim-patch:([a-z0-9.]*)(:.*){0,1}$/\1/p')"
765
766  echo
767  if [[ -n "${vim_version}" ]]; then
768    msg_ok "Detected Vim patch '${vim_version}'."
769  else
770    msg_err "Could not detect the Vim patch number."
771    echo "  This script assumes that the PR contains only commits"
772    echo "  with 'vim-patch:XXX' in their title."
773    echo
774    printf -- '%s\n\n' "$(head -n 4 <<< "${nvim_patch}")"
775    local reply
776    read -p "Continue reviewing (y/N)? " -n 1 -r reply
777    if [[ "${reply}" == y ]]; then
778      echo
779      return
780    fi
781    exit 1
782  fi
783
784  assign_commit_details "${vim_version}"
785
786  echo
787  echo "Creating files."
788  echo "${nvim_patch}" > "${NVIM_SOURCE_DIR}/n${patch_file}"
789  msg_ok "Saved pull request diff to '${NVIM_SOURCE_DIR}/n${patch_file}'."
790  CREATED_FILES+=("${NVIM_SOURCE_DIR}/n${patch_file}")
791
792  local nvim="nvim -u NONE -n -i NONE --headless"
793  2>/dev/null $nvim --cmd 'set dir=/tmp' +'1,/^$/g/^ /-1join' +w +q "${NVIM_SOURCE_DIR}/n${patch_file}"
794
795  local expected_commit_message
796  expected_commit_message="$(commit_message)"
797  local message_length
798  message_length="$(wc -l <<< "${expected_commit_message}")"
799  local commit_message
800  commit_message="$(tail -n +4 "${NVIM_SOURCE_DIR}/n${patch_file}" | head -n "${message_length}")"
801  if [[ "${commit_message#"$git_patch_prefix"}" == "${expected_commit_message}" ]]; then
802    msg_ok "Found expected commit message."
803  else
804    msg_err "Wrong commit message."
805    echo "  Expected:"
806    echo "${expected_commit_message}"
807    echo "  Actual:"
808    echo "${commit_message#"$git_patch_prefix"}"
809  fi
810
811  get_vimpatch "${vim_version}"
812  CREATED_FILES+=("${NVIM_SOURCE_DIR}/${patch_file}")
813
814  echo
815  echo "Launching nvim."
816  nvim -c "cd ${NVIM_SOURCE_DIR}" \
817    -O "${NVIM_SOURCE_DIR}/${patch_file}" "${NVIM_SOURCE_DIR}/n${patch_file}"
818}
819
820review_pr() {
821  require_executable curl
822  require_executable nvim
823  require_executable jq
824
825  get_vim_sources
826
827  local pr="${1}"
828  echo
829  echo "Downloading data for pull request #${pr}."
830
831  local -a pr_commit_urls
832  while IFS= read -r pr_commit_url; do
833    pr_commit_urls+=("$pr_commit_url")
834  done < <(curl -Ssf "https://api.github.com/repos/neovim/neovim/pulls/${pr}/commits" \
835    | jq -r '.[].html_url')
836
837  echo "Found ${#pr_commit_urls[@]} commit(s)."
838
839  local pr_commit_url
840  local reply
841  for pr_commit_url in "${pr_commit_urls[@]}"; do
842    review_commit "${pr_commit_url}"
843    if [[ "${pr_commit_url}" != "${pr_commit_urls[-1]}" ]]; then
844      read -p "Continue with next commit (Y/n)? " -n 1 -r reply
845      echo
846      if [[ "${reply}" == n ]]; then
847        break
848      fi
849    fi
850  done
851
852  clean_files
853}
854
855is_na_patch() {
856  local patch=$1
857  local NA_REGEXP="$NVIM_SOURCE_DIR/scripts/vim_na_regexp.txt"
858  local NA_FILELIST="$NVIM_SOURCE_DIR/scripts/vim_na_files.txt"
859  local NA_HUNKS_C="$NVIM_SOURCE_DIR/scripts/vim_na_hunks_c.txt"
860  local NA_HUNKS_H="$NVIM_SOURCE_DIR/scripts/vim_na_hunks_h.txt"
861  local NA_HUNKS_HELP="$NVIM_SOURCE_DIR/scripts/vim_na_hunks_help.txt"
862  local NA_HUNKS_VIM="$NVIM_SOURCE_DIR/scripts/vim_na_hunks_vim.txt"
863
864  local FILES_REMAINING HUNKS HUNK_NUM_FINAL
865  FILES_REMAINING="$(diff <(git -C "${VIM_SOURCE_DIR}" diff-tree --no-commit-id -r -b --name-only "$patch" | grep -v -f "$NA_REGEXP") "$NA_FILELIST" |
866    grep '^<' | sed 's/^< //')" || true
867  test -z "$FILES_REMAINING" && return 0
868
869  for file in $FILES_REMAINING; do
870    case ${file} in
871      runtime/doc/*.txt | runtime/pack/dist/opt/*/doc/*.txt)
872        HUNKS=$(git -c core.attributesfile="$NVIM_SOURCE_DIR"/.gitattributes -c 'diff.helphelp.xfuncname=^.*\*[^*[:space:]]+\*$' -C "${VIM_SOURCE_DIR}" \
873          diff-tree --no-commit-id -r -b -U0 \
874          '-I^\s+$' \
875          '-I^[-=]+$' \
876          '-I^(Functions:|GUI|Other)\s~$' \
877          '-I^[A-Z]\s+\*\+sodium\*\s+compiled with ' \
878          '-I^\|(ch|popup)_[_a-z]+\(\)\|' \
879          '-I^popup_[_a-z]+\(' \
880          '-I^sodium\s+Compiled with ' \
881          '-I\*\s+For Vim version [0-9]\.[0-9]\.\s+Last change: [0-9]+ [A-Z][a-z]+ [0-9]+' \
882          '-I compiled (with|without) .*\(\|.+\|\) feature\.$' \
883          '-I\{.+ (available|compiled) (with|without) .+\}' \
884          '-I\|(added|changed|patches|version)-[0-9]+\.[0-9]+\|' \
885          '-I\|:(cscope|export|import|redrawtabpanel)\|' \
886          '-I\|52\.6\|' \
887          '-I\|channel-open-[^|]+\|' \
888          '-I\|comment-install\|' \
889          '-I\|os_haiku.txt\|' \
890          '-I\|popup-windows\|' \
891          '-I\|tabpanel\|' \
892          '-I\|xdg\.vim\|' \
893          '-I\sGTK\s?4\s' \
894          '-I\spopup window\s' \
895          '-I\sterm_start\(\)\s' \
896          '-I\-gui=gtk' \
897          "$patch" -- "${file}")
898        if test -n "$HUNKS"; then
899          HUNK_NUM_FINAL=$(echo "$HUNKS" | grep '^@@ .* @@' | sed 's/^@@ .* @@ //' | grep -cv -f "$NA_HUNKS_HELP")
900          test "$HUNK_NUM_FINAL" -ne 0 && return 1
901        fi
902        ;;
903      runtime/syntax/vim.vim)
904        HUNKS=$(git -C "${VIM_SOURCE_DIR}" diff-tree --no-commit-id -r -b -U0 \
905          '-I^\s+$' \
906          '-I^" Last Change:\s' \
907          '-I^\s*syn\s+keyword\s+(vimCommand|vimFuncName)\s+contained\s+' \
908          '-I^\s*syn\s+keyword\s+vimAutoEvent\s+contained\s+[^U]' \
909          '-I^\s*syn\s+match\s+vimFuncName\s+contained\s+"\\<nvim_' \
910          "$patch" -- "${file}")
911        test -n "$HUNKS" && return 1
912        ;;
913      src/po/Make*)
914        HUNKS=$(git -C "${VIM_SOURCE_DIR}" diff-tree --no-commit-id -r -b -U0 \
915          '-I^\$\([_A-Z]+\)\.pot:' \
916          "$patch" -- "${file}")
917        if test -n "$HUNKS"; then
918          # shellcheck disable=SC2016
919          HUNK_NUM_FINAL=$(echo "$HUNKS" | grep '^@@ .* @@' | sed 's/^@@ .* @@ //' | grep -cv \
920            -e '^\$([_A-Z]\+)\.pot:' \
921            -e '^clean:' \
922            -e '^g\?vim\.desktop:' \
923            )
924          test "$HUNK_NUM_FINAL" -ne 0 && return 1
925        fi
926        ;;
927      src/testdir/Makefile)
928        HUNKS=$(git -C "${VIM_SOURCE_DIR}" diff-tree --no-commit-id -r -b -U0 \
929          '-IREDIR_TEST_TO_NULL = ' \
930          "$patch" -- "${file}")
931        test -n "$HUNKS" && return 1
932        ;;
933      src/testdir/Make_all.mak)
934        HUNKS=$(git -C "${VIM_SOURCE_DIR}" diff-tree --no-commit-id -r -b -U0 \
935          '-I\stest8[67]\.out \\$' \
936          "$patch" -- "${file}")
937        if test -n "$HUNKS"; then
938          HUNK_NUM_FINAL=$(echo "$HUNKS" | grep '^@@ .* @@' | sed 's/^@@ .* @@ //' | grep -cv -e '^NEW_TESTS\(\|_RES\) = \\$')
939          test "$HUNK_NUM_FINAL" -ne 0 && return 1
940        fi
941        ;;
942      src/testdir/*.vim)
943        HUNKS=$(git -C "${VIM_SOURCE_DIR}" diff-tree --no-commit-id -r -b -U0 \
944          "$patch" -- "${file}")
945        if test -n "$HUNKS"; then
946          HUNK_NUM_FINAL=$(echo "$HUNKS" | grep '^@@ .* @@' | sed 's/^@@ .* @@ //' | grep -cv -f "$NA_HUNKS_VIM")
947          test "$HUNK_NUM_FINAL" -ne 0 && return 1
948        fi
949        ;;
950      *.h)
951        HUNKS=$(git -C "${VIM_SOURCE_DIR}" diff-tree --no-commit-id -r -b -U0 \
952          '-I^\s+$' \
953          '-I^\s*/?\*/?$' \
954          '-I^\s*(//|/?\*).*\s([vV]im9|E[0-9]{,4} unused|E[0-9]{4} - |FEAT_|JSON-RPC|channel|job|popup|sound|terminal)' \
955          '-I^#\s*((ifdef|ifndef|undef)|(if|elif)\s.*defined\().*(FEAT_[^_]|USE_GTK)' \
956          '-I^#\s*(else|endif)' \
957          '-I^#\s*define\s+(FEAT|POPUPWIN|XDG|t)_[^_]' \
958          '-I^\s+(&&|\|\|)\s.*defined\(.*FEAT_[^_]' \
959          '-IEVENT_TERMINALWINOPEN' \
960          '-I^#\s*define\s+(ASSIGN_VAR|POPF_CURSORLINE)\s' \
961          '-I^typedef enum \{$' \
962          '-I^\s+(CH_MODE|POPCLOSE)_[A-Z]+,?(\s+//.+)?$' \
963          '-I^\} popclose_T;$' \
964          '-I^EXTERN\schar\s+\*popup_transparent' \
965          '-I^EXTERN\sint\s+[_a-z]+_for_testing\s' \
966          '-I^EXTERN type_T static_types\[' \
967          '-I^EXTERN type_T t_.* INIT[2-9]\(' \
968          '-I^EXTERN\swin_T\s+\*popup_dragwin' \
969          '-I^EXTERN char e_(abstract|const|class|enum|final|interface|public|static|type)_' \
970          '-I^EXTERN char e_.*def_function' \
971          '-I^EXTERN char e_.*enddef' \
972          '-I^EXTERN char e_.*vim9' \
973          '-I^EXTERN char e_[_a-z]+_channel' \
974          '-I^EXTERN char e_cannot_add(_redraw|)_listener_in_listener_callback' \
975          '-I^EXTERN char e_cannot_declare_.*variable_str' \
976          '-I^EXTERN char e_cannot_define_new_.+_as_static' \
977          '-I^EXTERN char e_cannot_listen_on_port' \
978          '-I^EXTERN char e_cannot_open_a_popup_window_to_a_closing_buffer' \
979          '-I^EXTERN char e_cannot_use_a_return_type_with_new' \
980          '-I^EXTERN char e_dictionary_not_set' \
981          '-I^EXTERN char e_dictnull' \
982          '-I^EXTERN char e_gethostbyname_in_channel_' \
983          '-I^EXTERN char e_invalid_identifier_in_defineannotype' \
984          '-I\sINIT\(= .+"E[0-9]+: (Abstract|Const|Class|Enum|Final|Interface|Public|Static|Type) ' \
985          '-I\sINIT\(= .+"E[0-9]+: .*:def ' \
986          '-I\sINIT\(= .+"E[0-9]+: .*enddef"' \
987          '-I\sINIT\(= .+"E[0-9]+: .*([vV]im9|interface)' \
988          '-I\sINIT\(= .+"E[0-9]+: .* (ch|channel)_[_a-z]+\(\)' \
989          '-I\sINIT\(= .+"E649: Invalid identifier name in defineAnnoType' \
990          '-I\sINIT\(= .+"E1016: Cannot declare .* variable: ' \
991          '-I\sINIT\(= .+"E1103: Dictionary not set' \
992          '-I\sINIT\(= .+"E1365: Cannot use a return type with the \\"new\\" function"' \
993          '-I\sINIT\(= .+"E1370: Cannot define a .+ as static' \
994          '-I\sINIT\(= .+"E15[0-9]+: Cannot use .*listener_add in a .* listener callback"' \
995          '-I\sINIT\(= .+"E1551: Cannot open a popup window to a closing buffer' \
996          '-I\sINIT\(= .+"E157[34]: ' \
997          '-I\s(bool|char(|_u)|int)\s+w_popup_image_[_a-zA-Z]+;' \
998          '-I\schar(|_u)\s+\*w_popup_title;' \
999          '-I\sint\s+ch_[_a-zA-Z]+;' \
1000          '-I\sint\s+sv_const;' \
1001          '-I\sint\s+w_(filter_mode|firstline|popup_drag|want_scrollbar);' \
1002          '-I\slist_T\s+\*w_popup_mask;' \
1003          '-I\spopclose_T\sw_popup_close;' \
1004          '-I\s\*?w_popup_prop_[_a-z]+;' \
1005          "$patch" -- "${file}")
1006        if test -n "$HUNKS"; then
1007          HUNK_NUM_FINAL=$(echo "$HUNKS" | grep '^@@ .* @@' | sed 's/^@@ .* @@ //' | grep -cv -f "$NA_HUNKS_H")
1008          test "$HUNK_NUM_FINAL" -ne 0 && return 1
1009        fi
1010        ;;
1011      *.c)
1012        HUNKS=$(git -C "${VIM_SOURCE_DIR}" diff-tree --no-commit-id -r -b -U0 \
1013          '-I^\s+$' \
1014          '-I^\s*/?\*/?$' \
1015          '-I^\s*(//|/?\*).*\s([vV]im9|E[0-9]{4} - |FEAT_|channel|job|popup|sound|terminal|uf_type_list)' \
1016          '-I^#\s*((ifdef|ifndef|undef)|(if|elif)\s.*defined\().*(FEAT_[^_]|USE_GTK)' \
1017          '-I^#\s*(else|endif)' \
1018          '-I^#\s*define\s+(FEAT|POPUPWIN|XDG|t)_[^_]' \
1019          '-I^\s+(&&|\|\|)\s.*defined\(.*FEAT_[^_]' \
1020          '-IEVENT_TERMINALWINOPEN' \
1021          '-I^#\s*include\s+<proto/' \
1022          '-I^\s+\{"ch_[_a-z]+",.*\sFEARG_[1-9],\s+arg[1-9]+_' \
1023          '-I^\s+\{"(popup|prop|sound)_[_a-z]+",.*f_(popup|prop|sound)_[_a-z]+\)?},$' \
1024          '-I^\s+ret_[a-z]+,\s+(JOB|PROP)_FUNC\(f_.+\)},$' \
1025          '-I^\s*(static)?\s(char(|_u)|hashtab_T|int|void)( \*)?$' \
1026          '-I^static\s(char(|_u)|hashtab_T|int|void)\s\*?[^*]+\(.+\);$' \
1027          '-I#\s*define.*ex_ni$' \
1028          '-I[.>]b_p_key' \
1029          '-I[_.>]sc_version = ' \
1030          '-I[_.>]uf_script_ctx_version = ' \
1031          '-I[_.>]uf_type_list' \
1032          '-I = skip_type\(.+\);$' \
1033          '-Icheck_typval_type\(.+\)' \
1034          '-Icrypt_get_method_nr\(.+\)' \
1035          '-Imsg\(.*".*GTK.*"\)' \
1036          '-I\spopup_set_firstline\(.+\);' \
1037          '-I\sredraw_tabpanel =' \
1038          '-I\sterm_focus_change\(.+\);$' \
1039          '-I\supdate_vim9_script_var\(.+\);$' \
1040          '-I\svim_free\(.*w_popup_title\);' \
1041          "$patch" -- "${file}")
1042        if test -n "$HUNKS"; then
1043          HUNK_NUM_FINAL=$(echo "$HUNKS" | grep '^@@ .* @@' | sed 's/^@@ .* @@ //' | grep -cv -f "$NA_HUNKS_C")
1044          test "$HUNK_NUM_FINAL" -ne 0 && return 1
1045        fi
1046        ;;
1047      *)
1048        return 1
1049        ;;
1050    esac
1051  done
1052
1053  return 0
1054}
1055
1056list_na_patches() {
1057  list_missing_vimpatches 0 | while read -r patch; do
1058    if is_na_patch "$patch"; then
1059      if (echo "$patch" | grep -q '^v[0-9]\.[0-9]\.[0-9]') && _git -C "${VIM_SOURCE_DIR}" show-ref --exists "refs/tags/$patch" 2>/dev/null; then
1060        echo "vim-patch:${patch:1}: $(_git -C "${VIM_SOURCE_DIR}" log -1 --format="%s" "$patch")"
1061      else
1062        echo "vim-patch:$(_git -C "${VIM_SOURCE_DIR}" log -1 --oneline "$patch")"
1063      fi
1064    fi
1065  done
1066}
1067
1068while getopts "hlLmnMVp:P:g:r:s" opt; do
1069  case ${opt} in
1070    h)
1071      usage
1072      exit 0
1073      ;;
1074    l)
1075      shift  # remove opt
1076      show_vimpatches "$@"
1077      exit 0
1078      ;;
1079    L)
1080      shift  # remove opt
1081      list_missing_vimpatches 0 "$@"
1082      exit 0
1083      ;;
1084    M)
1085      list_vimpatch_numbers
1086      exit 0
1087      ;;
1088    m)
1089      shift  # remove opt
1090      list_missing_previous_vimpatches_for_patch "$@"
1091      exit 0
1092      ;;
1093    n)
1094      list_na_patches
1095      exit 0
1096      ;;
1097    p)
1098      stage_patch "${OPTARG}"
1099      exit
1100      ;;
1101    P)
1102      stage_patch "${OPTARG}" TRY_APPLY
1103      exit 0
1104      ;;
1105    g)
1106      get_vimpatch "${OPTARG}"
1107      exit 0
1108      ;;
1109    r)
1110      review_pr "${OPTARG}"
1111      exit 0
1112      ;;
1113    s)
1114      shift  # remove opt
1115      submit_pr "$@"
1116      exit 0
1117      ;;
1118    V)
1119      get_vim_sources update
1120      exit 0
1121      ;;
1122    *)
1123      exit 1
1124      ;;
1125  esac
1126done
1127
1128usage
1129
1130# vim: et sw=2