Source

frawor / plugin / frawor / os.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
"▶1 Header
scriptencoding utf-8
execute frawor#Setup('0.2', {'@/resources': '0.0'}, 1)
"▶1 os resource
let s:os={}
"▶2 os.fullname
for s:os.fullname in ['unix', 'win16', 'win32', 'win64', 'win32unix', 'win95',
            \         'mac', 'macunix', 'amiga', 'os2', 'qnx', 'beos', 'vms']
    if has(s:os.fullname)
        break
    endif
    let s:os.fullname='unknown'
endfor
"▶2 os.name
if s:os.fullname[-3:] is# 'nix' || s:os.fullname[:2] is# 'mac' ||
            \s:os.fullname is# 'qnx' || s:os.fullname is# 'vms'
    let s:os.name='posix'
elseif s:os.fullname[:2] is# 'win'
    let s:os.name='nt'
elseif s:os.fullname is# 'os2'
    let s:os.name='os2'
else
    let s:os.name='other'
endif
"▲2
let s:os.sep=fnamemodify(expand('<sfile>:h'), ':p')[-1:]
"▶2 os.linesep
if s:os.name is# 'nt'
    let s:os.linesep="\r\n"
elseif s:os.fullname[:2] is# 'mac'
    let s:os.linesep="\r"
else
    let s:os.linesep="\n"
endif
"▶2 os.pathsep
if s:os.name is# 'nt' || s:os.name is# 'os2'
    let s:os.pathsep=';'
else
    let s:os.pathsep=':'
endif
"▶2 os.path
let s:os.path={}
"▶3 os.path.abspath   :: path + FS → path
function s:os.path.abspath(path)
    let components=s:os.path.split(fnamemodify(a:path, ':p'))
    if empty(components[-1])
        call remove(components, -1)
    endif
    if components[0] is# '.'
        let components[:0]=[fnamemodify('.', ':p')]
        if len(components[0])>1
            let components[0]=components[0][:-2]
        endif
    endif
    return s:os.path.join(components)
endfunction
"▶3 os.path.realpath  :: path + FS → path
function s:os.path.realpath(path)
    return resolve(s:os.path.abspath(a:path))
endfunction
"▶3 os.path.relpath   :: path[, curdir] → path
function s:os.path.relpath(path, ...)
    let components=s:os.path.split(s:os.path.normpath(
                \                                    s:os.path.abspath(a:path)))
    let tcomponents=s:os.path.split(s:os.path.normpath(
                \                         s:os.path.abspath((a:0)?(a:1):('.'))))
    call map([components, tcomponents], 'empty(v:val[-1])?remove(v:val, -1):0')
    if components[0] isnot# tcomponents[0]
        " This is valid for windows: you can't construct a relative path if 
        " directory to which path should be relative is on another drive
        return 0
    endif
    let l=min([len(components), len(tcomponents)])
    let i=1
    while i<l && components[i] is# tcomponents[i]
        let i+=1
    endwhile
    let r=s:os.path.join(repeat(['..'], len(tcomponents)-i)+components[(i):])
    if empty(r)
        let r='.'
    endif
    return r
endfunction
"▶3 os.path.basename  :: path → component
function s:os.path.basename(path)
    return fnamemodify(a:path, ':t')
endfunction
"▶3 os.path.dirname   :: path → path
function s:os.path.dirname(path)
    return fnamemodify(a:path, ':h')
endfunction
"▶3 os.path.join      :: path[, path[, ...]] | [path] → path
"▶4 s:eps
if s:os.name is# 'nt'
    let s:eps='[/\\]'
else
    let s:eps='\V'.escape(s:os.sep, '\')
endif
"▲4
function s:os.path.join(...)
    let components=copy((a:0 && type(a:1)==type([]))?
                \           (a:1):
                \           (a:000))
    call filter(components, 'type(v:val)=='.type(''))
    return substitute(join(components, s:os.sep), s:eps.'\+',
                \     escape(s:os.sep, '\&~'), 'g')
endfunction
"▶3 os.path.split     :: path → [component]
" Note: unlike python's one, this splits into a list of components
function s:os.path.split(path)
    let r=[]
    let path=a:path
    let oldpath=0
    while oldpath isnot# path
        call insert(r, s:os.path.basename(path))
        let oldpath=path
        let path=s:os.path.dirname(path)
    endwhile
    if !empty(r) && empty(r[0])
        let r[0]=path
    endif
    return r
endfunction
"▶3 os.path.normpath  :: path → path
function s:os.path.normpath(path)
    return simplify(s:os.path.join(s:os.path.split(a:path)))
endfunction
"▶3 os.path.samefile  :: path, path + FS → Bool
function s:os.path.samefile(path1, path2)
    return (s:os.path.normpath(s:os.path.realpath(a:path1))==
                \s:os.path.normpath(s:os.path.realpath(a:path2)))
endfunction
"▶3 os.path.exists    :: path + FS → Bool
if s:os.name is# 'nt'
    function s:os.path.exists(path)
        " Path cannot contain these symbols, but glob('\*') will list files
        " Same for «"<>|», but those are not special to glob()
        if a:path=~#'[*?]'
            return 0
        endif
        return !empty(glob(fnameescape(a:path), 1))
    endfunction
else
    function s:os.path.exists(path)
        return !empty(glob(fnameescape(a:path), 1))
    endfunction
endif
"▶3 os.path.isdir     :: path + FS → Bool
function s:os.path.isdir(path)
    return isdirectory(s:os.path.abspath(a:path))
endfunction
"▶3 os.path.isfile    :: path + FS → Bool
function s:os.path.isfile(path)
    return s:os.path.exists(a:path) && !s:os.path.isdir(a:path)
endfunction
"▶3 os.path.walk      :: path, F[, arg] + FS
function s:os.path.walk(path, Func, ...)
    let arg=get(a:000, 0, 0)
    let path=s:os.path.abspath(a:path)
    let files=s:os.listdir(path)
    call call(a:Func, [arg, path, files], {})
    call map(filter(map(files, 's:os.path.join(path, v:val)'),
                \   's:os.path.isdir(v:val)'),
                \'s:os.path.walk(v:val, a:Func, arg)')
endfunction
"▶2 os.listdir        :: path[, keepdirname] + FS → [component]
"▶3 s:F.globdir
function s:F.globdir(directory, ...)
    let r=split(glob(fnameescape(a:directory.s:os.sep).
               \     get(a:000, 0, '*'), 1),
               \"\n", 1)
    return ((len(r)==1 && empty(r[0]))?([]):(r))
endfunction
"▲3
function s:os.listdir(path, ...)
    let path=s:os.path.abspath(a:path)
    let filelist=s:F.globdir(path)
    if s:os.name is# 'posix'
        let filelist+=s:F.globdir(path, '.*')
    else
        call filter(filelist, '!empty(v:val)')
        return ((a:0)?(filelist):(map(filelist, 'fnamemodify(v:val, ":t")')))
    endif
    let nlnum=len(substitute(path, '[^\x0A]', '', 'g'))
    let r=[]
    let i=0
    let addfragment=''
    for file in filelist
        if i==0 && file[:0] isnot# '/'
            let r[-1].="\n".file
            continue
        elseif i<nlnum
            let i+=1
            let addfragment.=file."\n"
            continue
        else
            let file=addfragment.file
            let i=0
            let addfragment=''
        endif
        let tail=fnamemodify(file, ':t')
        if tail is# '.' || tail is# '..'
            continue
        endif
        call add(r, ((a:0)?(file):(tail)))
    endfor
    return r
endfunction
"▶2 os.chdir          :: path[, Bool] → Bool + WD
function s:os.chdir(path, ...)
    if s:os.path.isdir(a:path)
        try
            " Normpath is needed because paths like `directory/' (without 
            " preceding `/', `.' or `..') are subject to searching in &cdpath
            execute ((a:0 && a:1)?('lcd'):('cd'))
                        \ fnameescape(s:os.path.normpath(a:path))
            return 1
        catch
            return 0
        endtry
    endif
    return 0
endfunction
"▶2 run               :: command[, path] → shell_error + sh
let s:opts={
            \ 'eventignore': 'all',
            \   'autowrite':   0,
            \'autowriteall':   0,
            \  'lazyredraw':   1,
        \}
function s:F.run(cmd, ...)
    try
        let savedopts={}
        for [opt, val] in items(s:opts)
            let savedopts[opt]=eval('&g:'.opt)
            execute 'let &g:'.opt.'=val'
        endfor
        if a:0
            if !s:os.chdir(a:1)
                return -1
            endif
        endif
        execute 'silent! !'.a:cmd
        return v:shell_error
    finally
        if a:0
            cd -
        endif
        if exists('savedopts')
            for [opt, val] in items(savedopts)
                execute 'let &g:'.opt.'=val'
            endfor
            redraw!
        endif
    endtry
endfunction
"▶2 getcmd            :: command → cmd
function s:F.getcmd(command)
    if type(a:command)==type('')
        return a:command
    endif
    if s:os.name is# 'nt'
        let cmd=escape(a:command[0], '\ %')
        if len(a:command)>1
            let cmd.=' '.join(map(a:command[1:],
                        \'((v:val=~#"^[[:alnum:]/\\-]\\+$")?'.
                        \   '(v:val):'.
                        \   '(shellescape(v:val, 1)))'))
        endif
    else
        let cmd=join(map(copy(a:command), 'shellescape(v:val, 1)'))
    endif
    return cmd
endfunction
"▶2 os.run            :: command[, cwd::path] → shell_error + sh
function s:os.run(command, ...)
    return call(s:F.run, [s:F.getcmd(a:command)]+a:000, {})
endfunction
"▶2 os.readsystem :: command[, path] → [String] + sh
function s:os.readsystem(command, ...)
    let tempfile=tempname()
    let cmd=s:F.getcmd(a:command)
    let etempfile=shellescape(tempfile, stridx(cmd, "\n")!=-1)
    if stridx(&shellredir, '%s')!=-1
        let cmd.=printf(&shellredir, etempfile)
    else
        let cmd.=&shellredir.etempfile
    endif
    try
        call call(s:F.run, [cmd]+a:000, {})
        if !filereadable(tempfile)
            return 0
        endif
        return readfile(tempfile, 'b')
    finally
        if filereadable(tempfile)
            call delete(tempfile)
        endif
    endtry
endfunction
"▶2 os.readrun
"▶2 mkdir, makedirs
if exists('*mkdir')
    "▶3 os.makedirs       :: path[, mode] → Bool + FS
    function s:os.makedirs(path, ...)
        let mode=get(a:000, 0, 0755)
        let tocreate=[]
        let path=a:path
        while !s:os.path.isdir(path)
            call insert(tocreate, path)
            let path=s:os.path.dirname(path)
        endwhile
        try
            call map(tocreate, 'mkdir(v:val, "", '.mode.')')
            return 1
        catch
            return 0
        endtry
    endfunction
    "▶3 os.mkdir          :: path[, mode] → Bool + FS
    function s:os.mkdir(path, ...)
        let mode=get(a:000, 0, 0755)
        if !s:os.path.isdir(s:os.path.dirname(a:path))
            return 0
        endif
        try
            call mkdir(a:path, '', mode)
            return 1
        catch
            return 0
        endtry
    endfunction
    "▲3
endif
"▶2 os.unlink         :: path + FS → Bool + FS
function s:os.unlink(path)
    return delete(a:path) is# 0
endfunction
let s:os.remove=s:os.unlink
"▶2 os.rmdir          :: path → Bool + FS
function s:os.rmdir(path)
    let path=s:os.path.normpath(s:os.path.realpath(a:path))
    if !(s:os.path.isdir(path) && empty(s:os.listdir(path)))
        return 0
    endif
    if s:os.name is# 'posix'
        if executable('rmdir')
            return !s:os.run(['rmdir', path])
        elseif executable('rm') && empty(s:os.listdir(path))
            return !s:os.run(['rm', '-r', path])
        endif
    elseif s:os.name is# 'nt'
        " For some reason |executable()| function does not work
        return ((!s:os.run(['rmdir', path])) || (!s:os.run(['deltree', path])))
    endif
    return 0
endfunction
"▶2 os.removedirs     :: path → UInt + FS
function s:os.removedirs(path)
    let path=s:os.path.normpath(a:path)
    let prevpath=''
    let i=0
    while path isnot# '.' && path isnot# prevpath && s:os.rmdir(path)
        let prevpath=path
        let path=s:os.path.dirname(path)
        let i+=1
    endwhile
    return i
endfunction
"▶2 os.removetree     :: path → Bool + FS
function s:os.removetree(path)
    if s:os.path.isdir(a:path)
        let path=s:os.path.normpath(s:os.path.realpath(a:path))
        let toremove=[path]
        let files=s:os.listdir(path, 1)
        while !empty(files)
            let file=remove(files, 0)
            " Trying to unlink file before testing whether it is a directory 
            " prevents occasinal recursion into symbolic links
            if !s:os.unlink(file)
                if s:os.path.isdir(file)
                    let files+=s:os.listdir(file, 1)
                    call insert(toremove, file)
                else
                    return 0
                endif
            endif
        endwhile
        for directory in toremove
            if !s:os.rmdir(directory)
                return 0
            endif
        endfor
    else
        return s:os.unlink(a:path)
    endif
endfunction
"▶2 os.walk           :: path + FS → [(path, [ component ], [ component ])]
function s:os.walk(path)
    let r=[]
    let dirs=[s:os.path.normpath(a:path)]
    let processed=[]
    while !empty(dirs)
        let dir=remove(dirs, 0)
        "▶3 Check whether directory was already processed
        let realdir=s:os.path.realpath(dir)
        if index(processed, realdir)!=-1
            continue
        endif
        call add(processed, realdir)
        "▲3
        let cur=[dir, [], []]
        call add(r, cur)
        let files=s:os.listdir(dir)
        for file in files
            let fullname=s:os.path.join(dir, file)
            if s:os.path.isdir(fullname)
                call add(dirs, fullname)
                call add(cur[1], file)
            else
                call add(cur[2], file)
            endif
        endfor
    endwhile
    return r
endfunction
"▶2 post resource
call s:_f.postresource('os', s:os)
"▶1
call frawor#Lockvar(s:, '')
" vim: fmr=▶,▲ sw=4 ts=4 sts=4 et tw=80
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.