Source

aurum / autoload / aurum / commit.vim

  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
"▶1 
scriptencoding utf-8
execute frawor#Setup('1.4', {'@/resources': '0.0',
            \                '@/functions': '0.1',
            \                  '@/options': '0.0',
            \                       '@/os': '0.0',
            \                      '@/fwc': '0.0',
            \             '@%aurum/status': '1.2',
            \           '@%aurum/cmdutils': '4.3',
            \            '@%aurum/bufvars': '0.0',
            \            '@%aurum/vimdiff': '1.1',
            \               '@%aurum/edit': '1.0',
            \              '@%aurum/cache': '2.4',})
let s:_messages={
            \'emptmsg': 'Message must contain at least one non-blank character',
            \'nocfile': 'Unsure what should be commited',
            \'nocread': 'Cannot read aurum://commit',
            \  'nocom': 'Nothing to commit',
        \}
let s:_options={
            \'remembermsg':         {'default': 1, 'filter': 'bool'},
            \'bufleaveremembermsg': {'default': 1, 'filter': 'bool'},
            \'commitautoopendiff':  {'default': 0, 'filter': 'bool'},
            \'commitinfowincmd':    {
            \   'default': 'largest_adjacent',
            \   'checker': 'match /\v^%([jkhlwWtbpvs]|'.
            \                          'largest%(_%(vertical|'.
            \                                      'horizontal|'.
            \                                      'adjacent))?)$/'},
        \}
"▶1 parsedate string → [year, month, day, hour, minute, second]
" Date must have one of the following formats (XXX it is not validated):
" %Y-%m-%d %H:%M:%S
" %Y-%m-%d %H:%M
" %Y-%m-%d
"    %m-%d %H:%M:%S
"    %m-%d %H:%M
"    %m-%d
"          %H:%M:%S
"          %H:%M
function s:F.parsedate(str)
    let parts=split(a:str)
    if len(parts)==1
        if stridx(parts[0], ':')==-1
            let day=parts[0]
            let time=0
        else
            let day=0
            let time=parts[0]
        endif
    else
        let [day, time]=parts
    endif
    let r=[]
    if day is# 0
        let r+=[0, 0, 0]
    else
        let parts=split(day, '-')
        if len(parts)==2
            let r+=[0]
        else
            let year=remove(parts, 0)
            if len(year)<=2
                let y=str2nr(year)
                let cy=str2nr(strftime('%y'))
                let c=str2nr(strftime('%Y')[:-3])
                if y<=cy
                    let year=''.((c*100)+y)
                else
                    let year=''.(((c-1)*100)+y)
                endif
            endif
            let r+=[year]
        endif
        let r+=map(parts, 'len(v:val)==1 ? "0".v:val : v:val')
    endif
    if time is# 0
        let r+=[0, 0, 0]
    else
        let parts=map(split(time, ':'), 'len(v:val)==1 ? "0".v:val : v:val')
        let r+=parts
        if len(parts)==2
            let r+=[0]
        endif
    endif
    return r
endfunction
"▶1 vimdiffcb
function s:F.vimdiffcb(file, bvar, hex)
    execute 'silent tabnew'
                \ fnameescape(s:_r.os.path.join(a:bvar.repo.path, a:file))
    return s:_r.vimdiff.split([['file', a:bvar.repo, a:hex, a:file]], 0)
endfunction
"▶1 findwindow :: () -> winexisted::Bool
function s:F.winsize(wnr)
    let width=winwidth(a:wnr)
    return (width>80 ? 80 : width)*winheight(a:wnr)
endfunction
function s:F.winsplit()
    if winwidth(0)>=&textwidth*2
        execute 'silent' (winwidth(0)-&textwidth)                'vsplit'
    else
        execute 'silent' (max([winheight(0)-5, winheight(0)/2]))  'split'
    endif
    return 0
endfunction
function s:F.findwindow()
    let wcommand=s:_f.getoption('commitinfowincmd')
    if len(wcommand)==1
        let commit_mark=reltime()
        let wscope=w:
        let w:aurum_commit_mark=commit_mark
        try
            execute 'wincmd' wcommand
            if              exists('w:aurum_commit_mark')
                        \&& w:aurum_commit_mark is# commit_mark
                return s:F.winsplit()
            endif
            return (stridx('sv', wcommand)==-1)
        finally
            call remove(wscope, 'aurum_commit_mark')
        endtry
    elseif wcommand is# 'largest'
        let maxsize=0
        let mwnr=0
        for wnr in filter(range(1, winnr('$')), 'v:val!='.winnr())
            let size=s:F.winsize(a:wnr)
            if size>maxsize
                let maxsize=size
                let mwnr=a:wnr
            endif
        endfor
        if mwnr
            execute mwnr.'wincmd w'
            return 1
        else
            return s:F.winsplit()
        endif
    else
        let maxsize=0
        let mwcmd=0
        let wcmds={
                    \'vertical':   ['j', 'k'],
                    \'horizontal': ['h', 'l'],
                    \'adjacent':   ['h', 'l', 'j', 'k'],
                \}[wcommand[8:]]
        let curwin=winnr()
        for wcmd in wcmds
            execute 'wincmd' wcmd
            if winnr()!=curwin
                let size=s:F.winsize(0)
                wincmd p
                if size>maxsize
                    let maxsize=size
                    let mwcmd=wcmd
                endif
            endif
        endfor
        if mwcmd is 0
            return s:F.winsplit()
        else
            execute 'wincmd' mwcmd
            return 1
        endif
    endif
endfunction
"▶1 commit :: repo, opts, files, status, types[, cmd[, bvarpart[, edit]]]
let s:defdate=['strftime("%Y")',
            \  'strftime("%m")',
            \  'strftime("%d")',
            \  '"00"',
            \  '"00"',
            \  '"00"']
let s:statmsgs={
            \'added': 'Added',
            \'removed': 'Removed',
            \'modified': 'Modified',
        \}
let s:statmsgs.unknown=s:statmsgs.added
let s:statmsgs.deleted=s:statmsgs.removed
" TODO Investigate why closing commit buffer on windows consumes next character
" XXX Do not change names of options used here, see :AuRecord
function s:F.commit(repo, opts, files, status, types, ...)
    let user=''
    let date=''
    let message=''
    let cb=get(a:opts, 'closebranch', 0)
    let revstatus={}
    call map(filter(copy(a:status), 'index(a:types, v:key)!=-1'),
                \'map(copy(v:val),"extend(revstatus,{v:val : ''".v:key."''})")')
    if !empty(a:files)
        call filter(revstatus, 'index(a:files, v:key)!=-1')
    endif
    if empty(revstatus)
        call s:_f.throw('nocom')
    endif
    for key in filter(['user', 'date', 'message'], 'has_key(a:opts, v:val)')
        let l:{key}=a:opts[key]
    endfor
    "▶2 Normalize date
    if has_key(a:opts, 'date')
        let date=substitute(date, '_', ' ', '')
        let dparts=map(s:F.parsedate(date), 'v:val is 0 ? '.
                    \                               'eval(s:defdate[v:key]) : '.
                    \                               'v:val')
        let date=join(dparts[:2], '-').' '.join(dparts[3:], ':')
    endif
    "▲2
    if empty(message) || (a:0>2 && a:3 isnot 0)
        call s:_r.run(((a:0 && a:1 isnot 0)? a:1 : 'silent new'),
                    \ 'commit', a:repo, user, date, cb, a:files)
        " Workaround problem with templates created on BufNewFile. Namely if you 
        " try to commit a ebuild (or something that ends with a ".ebuild") you 
        " will see ebuild template inserted
        %delete _
        let bvar=s:_r.bufvars[bufnr('%')]
        if a:0>1 && a:2 isnot 0
            call extend(bvar, a:2)
        endif
        let bvar.revstatus=revstatus
        "▶2 Add previous message
        let addedprevmessage=0
        if exists('g:AuPreviousRepoPath') &&
                    \   g:AuPreviousRepoPath is# a:repo.path &&
                    \exists('g:AuPreviousTip') &&
                    \   g:AuPreviousTip is# a:repo.functions.gettiphex(a:repo)&&
                    \exists('g:AuPreviousCommitMessage')
            let addedprevmessage=1
            call setline('.', split(g:AuPreviousCommitMessage, "\n", 1))
            call cursor(line('$'), col([line('$'), '$']))
            unlet g:AuPreviousRepoPath g:AuPreviousTip g:AuPreviousCommitMessage
        elseif a:0>2 && a:3 isnot 0
            call setline('.', split(message, "\n", 1))
            call cursor(line('$'), col([line('$'), '$']))
        endif
        "▶2 Add comment
        let fmessage=[]
        for [file, state] in items(revstatus)
            let fmessage+=['# '.s:statmsgs[state].' '.file]
        endfor
        call sort(fmessage)
        call append('.', fmessage)
        if !addedprevmessage
            setlocal nomodified
        endif
        startinsert!
        "▶2 Open diff
        if s:_f.getoption('commitautoopendiff')
            let winexisted=bvar.findwindow()
            if winexisted
                let prevbuf=bufnr('%')
            else
                let prevbuf=0
            endif
            let existed=s:_r.mrun('silent edit', 'diff', bvar.repo, 0, 0,
                        \                                keys(revstatus), {})
            if !existed
                setlocal bufhidden=wipe
            endif
            let dbuf=bufnr('%')
            let dtabpagenr=tabpagenr()
            silent! %foldopen!
            wincmd p
            augroup AuCommitAutoCloseDiff
                execute 'autocmd BufWipeOut <buffer> '.
                            \':call s:F.closediffbuf('.dbuf.', '.
                            \                          dtabpagenr.', '.
                            \                          prevbuf.', '
                            \                          existed.', '.
                            \                          winexisted.')'
            augroup END
        endif
        "▲2
        return 0
    else
        call a:repo.functions.commit(a:repo, message, a:files, user, date, cb)
        return 1
    endif
endfunction
let s:_augroups+=['AuCommitAutoCloseDiff']
"▶1 closediffbuf
function s:F.closediffbuf(dbuf, dtabpagenr, prevbuf, existed, winexisted)
    if bufexists(a:dbuf) && count(tabpagebuflist(a:dtabpagenr), a:dbuf)==1
        let cmds=[]
        let switchcmds=[]
        if (a:prevbuf && bufexists(a:prevbuf)) || a:winexisted
            let curtab=tabpagenr()
            if curtab!=a:dtabpagenr
                let cmds+=['tabnext '.a:dtabpagenr]
                call insert(switchcmds, 'tabnext '.curtab)
            endif
            let cmds+=['execute bufwinnr('.a:dbuf.') "wincmd w"']
            call insert(switchcmds, 'wincmd p')
            if a:prevbuf && bufexists(a:prevbuf)
                let cmds += ['if bufexists('.a:prevbuf.')',
                            \   'buffer '.a:prevbuf,
                            \'else',
                            \   'bnext',
                            \'endif']
            else
                let cmds+=['bnext']
            endif
        endif
        if !a:existed
            let cmds+=['if bufexists('.a:dbuf.')', 'bwipeout '.a:dbuf, 'endif']
        endif
        let cmds+=switchcmds
        return feedkeys("\<C-\>\<C-n>:".join(cmds, '|')."\n\<C-l>", 'n')
    endif
endfunction
"▶1 savemsg :: message, bvar → + g:
function s:F.savemsg(message, bvar)
    if a:message!~#"[^[:blank:]\n]"
        return
    endif
    let g:AuPreviousCommitMessage=a:message
    let g:AuPreviousTip=a:bvar.repo.functions.gettiphex(a:bvar.repo)
    let g:AuPreviousRepoPath=a:bvar.repo.path
endfunction
"▶1 finish :: bvar → + bvar.repo
function s:F.finish(bvar)
    let message=join(filter(getline(1, '$'), 'v:val[0] isnot# "#"'), "\n")
    if message!~#"[^[:blank:]\n]"
        call s:_f.throw('emptmsg')
    endif
    if s:_f.getoption('remembermsg')
        call s:F.savemsg(message, a:bvar)
    endif
    call a:bvar.repo.functions.commit(a:bvar.repo, message, a:bvar.files,
                \                     a:bvar.user, a:bvar.date,
                \                     a:bvar.closebranch)
    call map(copy(s:_r.cache.allkeys), 's:_r.cache.wipe(v:val)')
    let a:bvar.did_message=1
    if has_key(a:bvar, 'sbvar')
        call a:bvar.bwfunc(a:bvar)
        let a:bvar.bwfunc=a:bvar.sbvar.bwfunc
    endif
    call feedkeys("\<C-\>\<C-n>:bwipeout!\n\<C-l>")
endfunction
"▶1 commfunc
let s:_aufunctions.cmd={'@FWC': ['-onlystrings '.
            \'{  repo '.s:_r.cmdutils.comp.repo.
            \' *?type      (either (in [modified added '.
            \                          'removed deleted '.
            \                          'unknown all] '.
            \                         '~start,'.
            \                      'match /\v^[MARDU?!]+$/))'.
            \'  ?message   type ""'.
            \'  ?user      type ""'.
            \'  ?date      match /\v%(^%(\d*\d\d-)?'.
            \                         '%(%(1[0-2]|0?[1-9])-'.
            \                           '%(3[01]|0?[1-9]|[12]\d)))?'.
            \                      '%(%(^|[ _])%(2[0-3]|[01]\d)'.
            \                                 '\:[0-5]\d'.
            \                                 '%(\:[0-5]\d)?)?$/'.
            \' !?closebranch'.
            \'}'.
            \'+ '.s:_r.cmdutils.comp.file, 'filter']}
let s:_aufunctions.comp=s:_r.cmdutils.gencompfunc(s:_aufunctions.cmd['@FWC'][0],
            \                                     [], s:_f.fwc.compile)
function s:_aufunctions.cmd.function(opts, ...)
    let rrfopts=copy(a:opts)
    let hasall=index(a:000, 'all')!=-1
    if a:0 && !hasall
        let rrfopts.files=a:000
    endif
    let [repo, rev, files]=s:_r.cmdutils.getrrf(rrfopts,
                \                               ((a:0)?(0):('nocfile')),
                \                               'getfiles')[1:]
    call s:_r.cmdutils.checkrepo(repo)
    let status=repo.functions.status(repo)
    "▶2 Get file list
    let types=['modified', 'added', 'removed']
    if hasall
        unlet files
        let files=[]
    elseif a:0
        if has_key(a:opts, 'type')
            let types=s:_r.status.parseshow(a:opts.type)
            call filter(types, 'v:val isnot# "clean" && v:val isnot# "ignored"')
        endif
        let filepats=map(filter(copy(a:000), 'v:val isnot# ":"'),
                    \    's:_r.globtopat('.
                    \    'repo.functions.reltorepo(repo, v:val))')
        let statfiles={}
        for [type, sfiles] in items(status)
            if index(types, type)==-1
                continue
            endif
            let curfiles=[]
            for pattern in filepats
                let curfiles+=filter(copy(sfiles), 'v:val=~#pattern')
            endfor
            if !empty(curfiles)
                let statfiles[type]=curfiles
                let files+=curfiles
            endif
        endfor
    elseif files is 0
        call s:_f.throw('nocfile')
    endif
    "▲2
    return s:F.commit(repo, a:opts, files, status, types)
endfunction
"▶1 aurum://commit
let s:commit={'arguments': 3,
            \  'listargs': 1,
            \'modifiable': 1,
            \  'filetype': 'aurumcommit',
            \}
function s:F.bufleave()
    let bvar=s:_r.bufvars[+expand('<abuf>')]
    if !bvar.did_message && s:_f.getoption('bufleaveremembermsg')
        let message=join(filter(getline(1,'$'),'v:val[0] isnot# "#"'), "\n")
        call s:F.savemsg(message, bvar)
    endif
endfunction
function s:commit.function(read, repo, user, date, cb, files)
    if a:read
        call s:_f.throw('nocread')
    endif
    augroup AuCommit
        autocmd! BufLeave <buffer> :call s:F.bufleave()
    augroup END
    return {'user': a:user, 'date': a:date, 'files': a:files,
                \'closebranch': !!a:cb, 'write': s:F.finish,
                \'did_message': 0, 'vimdiffcb': s:F.vimdiffcb,
                \'findwindow': s:F.findwindow,}
endfunction
let s:_augroups+=['AuCommit']
function s:commit.write(lines, repo, user, date, cb, files)
    let message=join(filter(copy(a:lines), 'v:val[0] isnot# "#"'), "\n")
    call a:repo.functions.commit(a:repo, message, a:files, a:user, a:date, a:cb)
    call map(copy(s:_r.cache.allkeys), 's:_r.cache.wipe(v:val)')
endfunction
call s:_f.newcommand(s:commit)
"▶1 Post resource
call s:_f.postresource('commit', {'commit': s:F.commit,
            \                     'finish': s:F.finish,})
"▶1
call frawor#Lockvar(s:, '_r,_pluginloaded')
" vim: ft=vim ts=4 sts=4 et fmr=▶,▲
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.