Skip to content

Commit d5bab50

Browse files
committed
Add gist#list_recursively function.
gist#list_recursively(user, [use_cache: 1], [limit: -1], [verbose: 1]) Load gists recursively when there are several pages.
1 parent 1b97d16 commit d5bab50

File tree

1 file changed

+56
-0
lines changed

1 file changed

+56
-0
lines changed

autoload/gist.vim

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,62 @@ function! s:GistList(gistls, page) abort
219219
redraw | echo ''
220220
endfunction
221221

222+
function! gist#list_recursively(user, ...)
223+
let use_cache = get(a:000, 0, 1)
224+
let limit = get(a:000, 1, -1)
225+
let verbose = get(a:000, 2, 1)
226+
if a:user == 'mine'
227+
let url = g:gist_api_url . 'gists'
228+
elseif a:user == 'starred'
229+
let url = g:gist_api_url . 'gists/starred'
230+
else
231+
let url = g:gist_api_url.'users/'.a:user.'/gists'
232+
endif
233+
234+
let auth = s:GistGetAuthHeader()
235+
if len(auth) == 0
236+
" anonymous user cannot get gists to prevent infinite recursive loading
237+
return []
238+
endif
239+
240+
if use_cache && exists('g:gist_list_recursively_cache')
241+
if has_key(g:gist_list_recursively_cache, a:user)
242+
return webapi#json#decode(g:gist_list_recursively_cache[a:user])
243+
endif
244+
endif
245+
246+
let page = 1
247+
let gists = []
248+
let lastpage = -1
249+
250+
function! s:get_lastpage(res)
251+
let links = split(a:res.header[match(a:res.header, 'Link')], ',')
252+
let link = links[match(links, 'rel=[''"]last[''"]')]
253+
let page = str2nr(matchlist(link, '\%(page=\)\(\d\+\)')[1])
254+
return page
255+
endfunction
256+
257+
if verbose > 0
258+
redraw | echon "Loading gists..."
259+
endif
260+
261+
while limit == -1 || page <= limit
262+
let res = webapi#http#get(url.'?page='.page, '', {'Authorization': auth})
263+
if limit == -1
264+
" update limit to the last page
265+
let limit = s:get_lastpage(res)
266+
endif
267+
if verbose > 0
268+
redraw | echon "Loading gists... " . page . '/' . limit . " pages has loaded."
269+
endif
270+
let gists = gists + webapi#json#decode(res.content)
271+
let page = page + 1
272+
endwhile
273+
let g:gist_list_recursively_cache = get(g:, 'gist_list_recursively_cache', {})
274+
let g:gist_list_recursively_cache[a:user] = webapi#json#encode(gists)
275+
return gists
276+
endfunction
277+
222278
function! gist#list(user, ...)
223279
let page = get(a:000, 0, 0)
224280
if a:user == '-all'

0 commit comments

Comments
 (0)