Source

aurum / plugin / aurum / repo.vim

Full commit
  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
"▶1
scriptencoding utf-8
if !exists('s:_pluginloaded')
    execute frawor#Setup('2.2', {'@/resources': '0.0',
                \                       '@/os': '0.0',
                \                  '@/options': '0.0',
                \             '@aurum/bufvars': '0.0',}, 0)
    finish
elseif s:_pluginloaded
    finish
endif
let s:drivers={}
let s:repos={}
let s:_options={
            \'diffopts':  {'default': {},
            \              'checker': 'dict {numlines         range 0 inf '.
            \                               '?in diffoptslst  bool}'},
        \}
" XXX Some code relies on the fact that all options from s:diffoptslst are
"     numeric
let s:diffoptslst=['git', 'reverse', 'ignorews', 'iwsamount', 'iblanks',
            \      'numlines', 'showfunc', 'alltext', 'dates']
let s:diffoptsstr=join(map(copy(s:diffoptslst),
            \          'v:val is# "numlines" ? '.
            \               '" ?".v:val." range 0 inf" : '.
            \               '"!?".v:val'))
let s:_messages={
            \    'nrm': 'Failed to remove file %s from repository %s',
            \  'iname': 'Error while registering driver for plugin %s: '.
            \           'invalid name: it must be a non-empty sting, '.
            \           'containing only latin letters, digits and underscores',
            \   'nimp': 'Function %s was not implemented in driver %s',
            \  'tgtex': 'Target already exists: %s',
            \ 'cpfail': 'Failed to copy %s to %s: %s',
            \ 'wrfail': 'Failed to write copy of %s to %s',
        \}
call extend(s:_messages, map({
            \   'dreg': 'driver was already registered by plugin %s',
            \  'fndct': 'second argument is not a dictionary',
            \   'fmis': 'some required functions are missing',
            \   'nfun': 'some of dictionary values are not '.
            \           'callable function references',
        \}, '"Error while registering driver %s for plugin %s: ".v:val'))
let s:deffuncs={}
let s:iterfuncs={}
"▶1 sort_in_topological_order :: [cs] → [cs]
" TODO put sorting requirement on getchangesets and revrange functions.
function s:F.sort_in_topological_order(repo, css)
    try
        call map(copy(a:css), 'extend(v:val, {"indegree": 1})')
        for parents in map(copy(a:css), 'v:val.parents')
            for parent in filter(map(filter(copy(parents),
                        \                   'has_key(a:repo.changesets,v:val)'),
                        \            'a:repo.changesets[v:val]'),
                        \        'get(v:val, "indegree", 0)')
                let parent.indegree+=1
            endfor
        endfor
        let work=[]
        call map(copy(a:css), 'v:val.indegree==1 ? add(work, v:val) : 0')
        call sort(work, 's:DateCmp')
        let r=[]
        while !empty(work)
            let cs=remove(work, 0)
            for parent in filter(map(filter(copy(cs.parents),
                        \                   'has_key(a:repo.changesets,v:val)'),
                        \            'a:repo.changesets[v:val]'),
                        \        'get(v:val, "indegree", 0)')
                let parent.indegree-=1
                if parent.indegree==1
                    let j=0
                    let lwork=len(work)
                    while j<lwork && work[j].time<parent.time
                        let j+=1
                    endwhile
                    call insert(work, parent, j)
                endif
            endfor
            let cs.indegree=0
            call add(r, cs)
        endwhile
    finally
        call map(copy(a:css), 'remove(v:val, "indegree")')
    endtry
    return r
endfunction
"▶1 iterfuncs: cs generators
" startfunc (here)  :: repo, opts → d
"▶2 ancestors
let s:iterfuncs.ancestors={}
function s:iterfuncs.ancestors.start(repo, opts)
    let cs=a:repo.functions.getcs(a:repo,
                \a:repo.functions.getrevhex(a:repo, a:opts.revision))
    let indegree={cs.hex : 1}
    for parenthex in cs.parents
        let indegree[parenthex]=2
    endfor
    return {'addrevs': [cs], 'revisions': {}, 'repo': a:repo,
                \'hasrevisions': get(a:repo, 'hasrevisions', 1),
                \'indegree': indegree, 'incremented': {cs.hex : 1}}
endfunction
function! s:RevCmp(cs1, cs2)
    let rev1=a:cs1.rev
    let rev2=a:cs2.rev
    return ((rev1==rev2)?(0):((rev1<rev2)?(1):(-1)))
endfunction
let s:_functions+=['s:RevCmp']
function s:iterfuncs.ancestors.next(d)
    if empty(a:d.addrevs)
        return 0
    endif
    " XXX cs variables should be kept after cycle ends
    let i=-1
    for cs in a:d.addrevs
        let i+=1
        if a:d.indegree[cs.hex]<=1
            break
        endif
    endfor
    call remove(a:d.addrevs, i)
    let a:d.revisions[cs.hex]=cs
    for parenthex in filter(copy(cs.parents), '!has_key(a:d.revisions, v:val)')
        let parent=a:d.repo.functions.getcs(a:d.repo, parenthex)
        let a:d.indegree[parenthex]=a:d.indegree[parenthex]-1
        if !has_key(a:d.incremented, parenthex)
            let a:d.incremented[parenthex]=1
            for pparhex in parent.parents
                let a:d.indegree[pparhex]=get(a:d.indegree, pparhex, 1)+1
            endfor
            let a:d.addrevs+=[parent]
        endif
    endfor
    return cs
endfunction
"▶2 revrange
let s:iterfuncs.revrange={}
function s:iterfuncs.revrange.start(repo, opts)
    if has_key(a:opts, 'revrange')
        call map(a:opts.revrange, 'a:repo.functions.getrevhex(a:repo, v:val)')
        let cslist=copy(call(a:repo.functions.revrange,
                    \   [a:repo]+a:opts.revrange, {}))
    else
        let cslist=copy(a:repo.functions.getchangesets(a:repo))
    endif
    if get(a:repo, 'requires_sort', 1)
        let cslist=s:F.sort_in_topological_order(a:repo, cslist)
    else
        call reverse(cslist)
    endif
    return {'cslist': cslist}
endfunction
function s:iterfuncs.revrange.next(d)
    if empty(a:d.cslist)
        return 0
    endif
    return remove(a:d.cslist, 0)
endfunction
"▶2 changesets
let s:iterfuncs.changesets=s:iterfuncs.revrange
"▶1 setlines :: [String], read::Bool → + buffer
function s:F.setlines(lines, read)
    let d={'set': function((a:read)?('append'):('setline'))}
    if len(a:lines)>1 && empty(a:lines[-1])
        call d.set('.', a:lines[:-2])
    else
        if !a:read
            setlocal binary noendofline
        endif
        call d.set('.', a:lines)
    endif
endfunction
"▶1 dirty :: repo, file → Bool
function s:deffuncs.dirty(repo, file)
    let status=a:repo.functions.status(a:repo, 0, 0, [a:file])
    for [type, files] in items(status)
        if type is# 'ignored' || type is# 'clean'
            continue
        endif
        if index(files, a:file)!=-1
            return 1
        endif
    endfor
    return 0
endfunction
"▶1 getnthparent :: repo, rev, n → cs
function s:deffuncs.getnthparent(repo, rev, n)
    let r=a:repo.functions.getcs(a:repo, a:rev)
    let key=((a:n>0)?('parents'):('children'))
    for i in range(1, abs(a:n))
        let rl=a:repo.functions.getcsprop(a:repo, r, key)
        if empty(rl)
            break
        endif
        let r=a:repo.functions.getcs(a:repo, rl[0])
    endfor
    return r
endfunction
"▶1 reltorepo :: repo, path → rpath
function s:deffuncs.reltorepo(repo, path)
    return join(s:_r.os.path.split(s:_r.os.path.relpath(a:path,
                \                                       a:repo.path))[1:], '/')
endfunction
"▶1 getcsprop :: repo, Either cs rev, propname → a
function s:deffuncs.getcsprop(repo, csr, propname)
    if type(a:csr)==type({})
        let cs=a:csr
    else
        let cs=a:repo.functions.getcs(a:repo, a:csr)
    endif
    if has_key(cs, a:propname)
        return cs[a:propname]
    endif
    call a:repo.functions.setcsprop(a:repo, cs, a:propname)
    " XXX There is much code relying on the fact that after getcsprop property 
    " with given name is added to changeset dictionary
    return cs[a:propname]
endfunction
"▶1 revrange :: repo, rev, rev → [cs]
function s:F.getrev(repo, rev, cslist)
    if type(a:rev)==type(0)
        if a:rev<0
            return len(a:cslist)+a:rev
        else
            return a:rev
        endif
    else
        return a:repo.functions.getcs(a:repo, a:rev).rev
    endif
endfunction
function s:deffuncs.revrange(repo, rev1, rev2)
    if empty(a:repo.cslist)
        let cslist=a:repo.functions.getchangesets(a:repo)
    else
        let cslist=a:repo.cslist
    endif
    let rev1=s:F.getrev(a:repo, a:rev1, cslist)
    let rev2=s:F.getrev(a:repo, a:rev2, cslist)
    if rev1>rev2
        let [rev1, rev2]=[rev2, rev1]
    endif
    return cslist[(rev1):(rev2)]
endfunction
"▶1 difftobuffer
function s:deffuncs.difftobuffer(repo, buf, ...)
    let diff=call(a:repo.functions.diff, [a:repo]+a:000, {})
    let oldbuf=bufnr('%')
    if oldbuf!=a:buf
        execute 'buffer' a:buf
    endif
    call s:F.setlines(diff, 0)
    if oldbuf!=a:buf
        execute 'buffer' oldbuf
    endif
endfunction
"▶1 diffname :: _, line, diffre, _ → rpath
function s:deffuncs.diffname(repo, line, diffre, opts)
    return get(matchlist(a:line, a:diffre), 1, 0)
endfunction
"▶1 getstats :: _, diff, diffopts → stats
" stats :: { ( "insertions" | "deletions" ): UInt,
"            "files": { ( "insertions" | "deletions" ): UInt } }
function s:deffuncs.getstats(repo, diff, opts)
    let diffre=a:repo.functions.diffre(a:repo, a:opts)
    let i=0
    let llines=len(a:diff)
    let stats={'files': {}, 'insertions': 0, 'deletions': 0}
    let file=0
    while i<llines
        let line=a:diff[i]
        if line[:3] is# 'diff'
            let file=a:repo.functions.diffname(a:repo, line, diffre, a:opts)
            if file isnot 0
                let stats.files[file]={'insertions': 0, 'deletions': 0,}
                let i+=1
                let oldi=i
                let pmlines=2
                while pmlines && i<llines
                    let lstart=a:diff[i][:2]
                    if lstart is# '+++' || lstart is# '---'
                        let pmlines-=1
                    endif
                    let i+=1
                    if i-oldi>=4
                        let i=oldi
                        break
                    endif
                endwhile
                continue
            endif
        elseif file is 0
        elseif line[0] is# '+'
            let stats.insertions+=1
            let stats.files[file].insertions+=1
        elseif line[0] is# '-'
            let stats.deletions+=1
            let stats.files[file].deletions+=1
        endif
        let i+=1
    endwhile
    return stats
endfunction
"▶1 copy
function s:deffuncs.copy(repo, force, source, target)
    let src=s:_r.os.path.normpath(s:_r.os.path.join(a:repo.path, a:source))
    let tgt=s:_r.os.path.normpath(s:_r.os.path.join(a:repo.path, a:target))
    if filewritable(tgt)==1
        if a:force
            call delete(tgt)
        else
            call s:_f.throw('tgtex', tgt)
        endif
    elseif s:_r.os.path.exists(tgt)
        " Don’t try to delete directories and non-writable files.
        call s:_f.throw('tgtex', tgt)
    endif
    let cmd=0
    if executable('cp')
        let cmd='cp --'
    elseif executable('copy')
        let cmd='copy'
    endif
    if cmd is 0
        try
            if writefile(readfile(src, 'b'), tgt, 'b')!=0
                call s:_f.throw('wrfail', src, tgt)
            endif
        endtry
    else
        let hasnls=(stridx(src.tgt, "\n")==-1)
        let cmd.=' '.shellescape(src, hasnls).' '.shellescape(tgt, hasnls)
        if hasnls
            let shout=system(cmd)
        else
            noautocmd tabnew
            noautocmd setlocal buftype=nofile
            noautocmd execute 'silent! %!'.cmd
            let shout=join(getline(1, '$'), "\n")
            noautocmd tabclose
        endif
        if v:shell_error
            call s:_f.throw('cpfail', src, tgt, shout)
        endif
    endif
    call a:repo.functions.add(a:repo, tgt)
endfunction
"▶1 move
function s:deffuncs.move(repo, force, source, target)
    call a:repo.functions.copy(a:repo, a:force, a:source, a:target)
    call a:repo.functions.remove(a:repo, a:source)
endfunction
"▶1 remove
function s:deffuncs.remove(repo, file)
    call a:repo.functions.forget(a:repo, a:file)
    let file=s:_r.os.path.join(a:repo.path, a:file)
    if s:_r.os.path.isfile(file)
        if delete(file)
            call s:_f.throw('nrm', a:file, a:repo.path)
        endif
    endif
endfunction
"▶1 checkremote
function s:deffuncs.checkremote(...)
    return 0
endfunction
"▶1 getrevhex
function s:deffuncs.getrevhex(repo, rev)
    return a:rev.''
endfunction
"▶1 getdriver :: path, type → Maybe driver
function s:F.getdriver(path, ptype)
    for driver in values(s:drivers)
        if driver.functions['check'.a:ptype](a:path)
            return driver
        endif
    endfor
    return 0
endfunction
"▶1 getrepo :: path → repo
function s:F.getrepo(path)
    "▶2 Pull in drivers if there are no
    if empty(s:drivers)
        for src in s:_r.os.listdir(s:_r.os.path.join(s:_frawor.runtimepath,
                    \              'plugin', 'aurum', 'drivers'))
            if len(src)<5 || src[-4:] isnot# '.vim'
                continue
            endif
            call FraworLoad('@aurum/drivers/'.src[:-5])
        endfor
    endif
    "▶2 Get path
    if empty(a:path)
        let path=s:_r.os.path.realpath('.')
    elseif a:path is# ':'
        let buf=bufnr('%')
        if has_key(s:_r.bufvars, buf) && has_key(s:_r.bufvars[buf], 'repo')
            let path=s:_r.bufvars[buf].repo.path
        elseif has_key(s:_r.bufvars,buf) && s:_r.bufvars[buf].command is# 'copy'
            let path=s:_r.os.path.dirname(
                        \s:_r.os.path.realpath(s:_r.bufvars[buf].file))
        elseif empty(&buftype) && isdirectory(expand('%:p:h'))
            let path=s:_r.os.path.realpath(expand('%:p:h'))
        else
            let path=s:_r.os.path.realpath('.')
        endif
    elseif stridx(a:path, '://')==-1
        let path=s:_r.os.path.realpath(a:path)
    else
        let path=a:path
    endif
    "▶2 Get driver
    if stridx(path, '://')==-1
        let olddir=''
        let driver=0
        while path isnot# olddir
            unlet driver
            let driver=s:F.getdriver(path, 'dir')
            if driver isnot 0
                break
            endif
            let olddir=path
            let path=fnamemodify(path, ':h')
        endwhile
    else
        let driver=s:F.getdriver(path, 'remote')
    endif
    if driver is 0
        return 0
    endif
    "▲2
    if has_key(s:repos, path)
        let repo=s:repos[path]
        if !empty(repo.cslist)
            call repo.functions.updatechangesets(repo)
        endif
        return repo
    endif
    let repo=driver.functions.repo(path)
    if repo is 0
        return 0
    endif
    let repo.type=driver.id
    let repo.path=path
    let repo.functions=copy(driver.functions)
    let repo.diffopts=copy(s:_f.getoption('diffopts'))
    if !has_key(repo, 'iterfuncs')
        let repo.iterfuncs=deepcopy(s:iterfuncs)
    else
        call extend(repo.iterfuncs, s:iterfuncs, 'keep')
    endif
    if !has_key(repo, 'initprops')
        let repo.initprops=['rev', 'hex', 'parents', 'tags', 'bookmarks',
                    \       'branch', 'time', 'user', 'description']
    endif
    lockvar! repo
    unlockvar! repo.cslist
    unlockvar! repo.changesets
    unlockvar 1 repo
    return repo
endfunction
"▶1 update
function s:F.update(repo, rev, count)
    let rev=a:rev
    if a:count>1
        let rev=a:repo.functions.getnthparent(a:repo, rev, a:count-1).hex
    endif
    return a:repo.functions.update(a:repo, rev, 0)
endfunction
"▶1 Post resource
call s:_f.postresource('repo', {'get': s:F.getrepo,
            \                'update': s:F.update,
            \           'diffoptslst': s:diffoptslst,
            \           'diffoptsstr': s:diffoptsstr,})
call s:_f.postresource('setlines', s:F.setlines)
"▶1 regdriver feature
let s:requiredfuncs=['repo', 'getcs', 'checkdir']
let s:optfuncs=['readfile', 'annotate', 'diff', 'status', 'commit', 'update',
            \   'dirty', 'diffre', 'getrepoprop', 'forget', 'branch', 'label']
"▶2 regdriver :: {f}, name, funcs → + s:drivers
function s:F.regdriver(plugdict, fdict, name, funcs)
    "▶3 Check arguments
    if type(a:name)!=type('') || a:name!~#'\v^\w+$'
        call s:_f.throw('iname', a:plugdict.id)
    elseif has_key(s:drivers, a:name)
        call s:_f.throw('dreg', a:name, a:plugdict.id, s:drivers[a:name].plid)
    elseif type(a:funcs)!=type({})
        call s:_f.throw('fndct', a:name, a:plugdic.id)
    elseif !empty(filter(copy(s:requiredfuncs), '!exists("*a:funcs[v:val]")'))
        call s:_f.throw('fmis', a:name, a:plugdict.id)
    elseif !empty(filter(copy(a:funcs), '!exists("*v:val")'))
        call s:_f.throw('nfun', a:name, a:plugdict.id)
    endif
    "▲3
    let driver={'functions': copy(a:funcs)}
    let driver.plid=a:plugdict.id
    let driver.id=a:name
    call extend(driver.functions, s:deffuncs, 'keep')
    for funname in filter(copy(s:optfuncs), '!has_key(driver.functions, v:val)')
        execute      "function driver.functions.".funname."(...)\n".
                    \"    call s:_f.throw('nimp', '".funname."', ".
                    \                    "'".a:name."')\n".
                    \"endfunction"
    endfor
    lockvar! driver
    let a:fdict[a:name]=driver
    let s:drivers[a:name]=driver
endfunction
"▶2 deldriver :: {f} → + s:drivers
function s:F.deldriver(plugdict, fdict)
    call map(keys(a:fdict), 'remove(s:drivers, v:val)')
endfunction
"▶2 Register feature
call s:_f.newfeature('regdriver', {'cons': s:F.regdriver,
            \                    'unload': s:F.deldriver})
"▶1
call frawor#Lockvar(s:, '_pluginloaded,_r,repos,drivers')
" vim: ft=vim ts=4 sts=4 et fmr=▶,▲