069512d14a78849f09487590ad17085fce3d1b43

Author
Rishvic Pushpakaran <40887886+rishvic@users.noreply.github.com>
Committer
GitHub <noreply@github.com>
Date

Message

feat(gitignore): add caching to `gi` completion (#13735)

Adds a cache policy for the `gi` command completion function, i.e.
`_gitignoreio`. Previously, every completion call would request the list
endpoint of gitignore.io over the network, resulting in a delay between
pressing <Tab> and the autocomplete options showing up.

Since we don't expect the gitignore.io templates to change that
frequently, configured the cache policy to expire after 7 days.

Signed-off-by: Rishvic Pushpakaran <rishvic@gmail.com>
Co-authored-by: Carlo Sala <carlosalag@protonmail.com>

Diff

 1diff --git a/plugins/gitignore/gitignore.plugin.zsh b/plugins/gitignore/gitignore.plugin.zsh
 2index a9f3f645396b7871fb078143deea7e6ac52945e6..1823615f538e4916942f9dcf23fbf609209a3fc7 100644
 3--- a/plugins/gitignore/gitignore.plugin.zsh
 4+++ b/plugins/gitignore/gitignore.plugin.zsh
 5@@ -10,12 +10,48 @@ function gi() {
 6 }
 7 
 8 _gitignoreio_get_command_list() {
 9+  setopt local_options pipe_fail
10   _gi_curl "list" | tr "," "\n"
11 }
12 
13-_gitignoreio () {
14+__gitignoreio_caching_policy() {
15+  local -a oldp
16+  oldp=("$1"(Nm+7))
17+  (($#oldp))
18+}
19+
20+_gitignoreio_retrieve_stale_cache() {
21+  zstyle -t ":completion:${curcontext}:" use-cache || return 1
22+
23+  local cache_dir
24+  zstyle -s ":completion:${curcontext}:" cache-path cache_dir
25+  : ${cache_dir:=${ZDOTDIR:-$HOME}/.zcompcache}
26+
27+  [[ -e "$cache_dir/gi-list" ]] || return 1
28+  . "$cache_dir/gi-list"
29+}
30+
31+_gitignoreio() {
32   compset -P '*,'
33-  compadd -S '' $(_gitignoreio_get_command_list)
34+
35+  local cache_policy
36+  zstyle -s ":completion:${curcontext}:" cache-policy cache_policy
37+  if [[ -z "$cache_policy" ]]; then
38+    zstyle ":completion:${curcontext}:" cache-policy __gitignoreio_caching_policy
39+  fi
40+
41+  local -a _gi_list
42+  if _cache_invalid gi-list || ! _retrieve_cache gi-list; then
43+    local command_list
44+    if command_list="$(_gitignoreio_get_command_list)" && [[ -n "$command_list" ]]; then
45+      _gi_list=(${(f)command_list})
46+      _store_cache gi-list _gi_list
47+    else
48+      _gitignoreio_retrieve_stale_cache
49+    fi
50+  fi
51+
52+  compadd -S '' -a _gi_list
53 }
54 
55-compdef _gitignoreio gi
56+compdef _gitignoreio gi