summaryrefslogtreecommitdiff
path: root/xmake/core/base/io.lua
blob: f6c93197034d15d970c8745c26a24622513d9b66 (plain)
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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
--!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
--     http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015 - 2019, TBOOX Open Source Group.
--
-- @author      ruki
-- @file        io.lua
--

-- define module
local io        = io or {}
local _file     = _file or {}
local _filelock = _filelock or {}

-- load modules
local path   = require("base/path")
local table  = require("base/table")
local string = require("base/string")

-- save metatable and builtin functions
io._file        = _file
io._filelock    = _filelock
io._stdfile     = io._stdfile or io.stdfile

-- new an file
function _file.new(filepath, fileref)
    local file = table.inherit(_file)
    file._NAME = path.filename(filepath)
    file._PATH = path.absolute(filepath)
    file._FILE = fileref
    setmetatable(file, _file)
    return file
end

-- get the file name 
function _file:name()
    return self._NAME
end

-- get the file path 
function _file:path()
    return self._PATH
end

-- close file
function _file:close()
    if not self._FILE then
        return false, string.format("file(%s) has been closed!", self:name())
    end
    local ok, errors = io.file_close(self._FILE)
    if ok then
        self._FILE = nil
    end
    return ok, errors
end

-- tostring(file)
function _file:__tostring()
    return "file: " .. self:name()
end

-- gc(file)
function _file:__gc()
    if self._FILE and io.file_close(self._FILE) then
        self._FILE = nil
    end
end

-- get file length
function _file:__len()
    return self:size()
end

-- get file rawfd
function _file:rawfd()
    if not self._FILE then
        return false, string.format("file(%s) has been closed!", self:name())
    end
    local result, errors = io.file_rawfd(self._FILE)
    if not result and errors then
        errors = string.format("file(%s): %s", self:name(), errors)
    end
    return result, errors
end

-- get file size
function _file:size()
    if not self._FILE then
        return false, string.format("file(%s) has been closed!", self:name())
    end
    local result, errors = io.file_size(self._FILE)
    if not result and errors then
        errors = string.format("file(%s): %s", self:name(), errors)
    end
    return result, errors
end

-- read data from file
function _file:read(fmt, opt)
    if not self._FILE then
        return false, string.format("file(%s) has been closed!", self:name())
    end
    opt = opt or {}
    local result, errors = io.file_read(self._FILE, fmt, opt.continuation)
    if errors then
        errors = string.format("file(%s): %s", self:name(), errors)
    end
    return result, errors
end

-- write data to file
function _file:write(...)
    if not self._FILE then
        return false, string.format("file(%s) has been closed!", self:name())
    end
    local ok, errors = io.file_write(self._FILE, ...)
    if not ok and errors then
        errors = string.format("file(%s): %s", self:name(), errors)
    end
    return ok, errors
end

-- seek offset at file
function _file:seek(whence, offset)
    if not self._FILE then
        return false, string.format("file(%s) has been closed!", self:name())
    end
    local result, errors = io.file_seek(self._FILE, whence, offset)
    if not result and errors then
        errors = string.format("file(%s): %s", self:name(), errors)
    end
    return result, errors
end

-- flush data to file
function _file:flush()
    if not self._FILE then
        return false, string.format("file(%s) has been closed!", self:name())
    end
    local ok, errors = io.file_flush(self._FILE)
    if not ok and errors then
        errors = string.format("file(%s): %s", self:name(), errors)
    end
    return ok, errors
end

-- this file is a tty?
function _file:isatty()
    if not self._FILE then
        return false, string.format("file(%s) has been closed!", self:name())
    end
    local ok, errors = io.file_isatty(self._FILE)
    if ok == nil and errors then
        errors = string.format("file(%s): %s", self:name(), errors)
    end
    return ok, errors
end

-- iterator of lines
function _file._lines_iter(data)
    local l = data.file:read("l", data.opt)
    if not l and data.opt.close_on_finished then
        data.file:close()
    end
    return l
end

-- read all lines from a file
function _file:lines(opt)
    return _file._lines_iter, { file = assert(self), opt = opt or {} }
end

-- print file
function _file:print(...)
    return self:write(string.format(...), "\n")
end

-- printf file
function _file:printf(...)
    return self:write(string.format(...))
end

-- save object
function _file:save(object, opt)
    local str, errors = string.serialize(object, opt)
    if errors then
        return false, errors
    else
        return self:write(str)
    end
end

-- load object
function _file:load()
    local data, err = self:read("*all")
    if err then
        return nil, err
    end
    if data and type(data) == "string" then
        return data:deserialize()
    end
end

-- new an filelock
function _filelock.new(lockpath, lock)
    local filelock = table.inherit(_filelock)
    filelock._NAME = path.filename(lockpath)
    filelock._PATH = path.absolute(lockpath)
    filelock._LOCK = lock
    filelock._LOCKED_NUM = 0
    setmetatable(filelock, _filelock)
    return filelock
end

-- get the filelock name 
function _filelock:name()
    return self._NAME
end

-- get the filelock path 
function _filelock:path()
    return self._PATH
end

-- is locked?
function _filelock:islocked()
    return self._LOCKED_NUM > 0
end

-- lock file
--
-- @param opt       the argument option, {shared = true}
--
-- @return          ok, errors
--
function _filelock:lock(opt)
    if not self._LOCK then
        return false, string.format("filelock(%s) has been closed!", self:name())
    end
    if self._LOCKED_NUM > 0 or io.filelock_lock(self._LOCK, opt) then
        self._LOCKED_NUM = self._LOCKED_NUM + 1
        return true
    else
        return false, string.format("filelock(%s): lock %s failed!", self:name(), self:path())
    end
end

-- try to lock file
--
-- @param opt       the argument option, {shared = true}
--
-- @return          ok, errors
--
function _filelock:trylock(opt)
    if not self._LOCK then
        return false, string.format("filelock(%s) has been closed!", self:name())
    end
    if self._LOCKED_NUM > 0 or io.filelock_trylock(self._LOCK, opt) then
        self._LOCKED_NUM = self._LOCKED_NUM + 1
        return true
    else
        return false, string.format("filelock(%s): trylock %s failed!", self:name(), self:path())
    end
end

-- unlock file
function _filelock:unlock(opt)
    if not self._LOCK then
        return false, string.format("filelock(%s) has been closed!", self:name())
    end
    if self._LOCKED_NUM > 1 or (self._LOCKED_NUM > 0 and io.filelock_unlock(self._LOCK)) then
        if self._LOCKED_NUM > 0 then
            self._LOCKED_NUM = self._LOCKED_NUM - 1
        else 
            self._LOCKED_NUM = 0
        end
        return true
    else
        return false, string.format("filelock(%s): unlock %s failed!", self:name(), self:path())
    end
end

-- close filelock
function _filelock:close()
    if not self._LOCK then
        return false, string.format("filelock(%s) has been closed!", self:name())
    end
    local ok = io.filelock_close(self._LOCK)
    if ok then
        self._LOCK = nil
        self._LOCKED_NUM = 0
    end
    return ok
end

-- tostring(filelock)
function _filelock:__tostring()
    return "filelock: " .. self:name()
end

-- gc(filelock)
function _filelock:__gc()
    if self._LOCK and io.filelock_close(self._LOCK) then
        self._LOCK = nil
        self._LOCKED_NUM = 0
    end
end

-- read all lines from file
function io.lines(filepath, opt)

    -- close on finished
    opt = opt or {}
    if opt.close_on_finished == nil then
        opt.close_on_finished = true
    end

    -- open file
    local file = io.open(filepath, "r", opt)
    if not file then
        return function() return nil end
    end

    return file:lines(opt)
end

-- read all data from file
function io.readfile(filepath, opt)

    opt = opt or {}

    -- open file
    local file = io.open(filepath, "r", opt)
    if not file then
        -- error
        return nil, string.format("open %s failed!", filepath)
    end

    -- read all
    local data, err = file:read("*all", opt)

    -- exit file
    file:close()

    -- ok?
    return data, err
end

function io.read(fmt, opt)
    return io.stdin:read(fmt, opt)
end

function io.write(...)
    return io.stdout:write(...)
end

function io.print(...)
    return io.stdout:print(...)
end

function io.printf(...)
    return io.stdout:printf(...)
end

function io.flush()
    return io.stdout:flush()
end

-- write data to file
function io.writefile(filepath, data, opt)

    -- init option
    opt = opt or {}

    -- open file
    local file = io.open(filepath, "w", opt)
    if not file then
        return false, string.format("open %s failed!", filepath)
    end

    -- write all
    file:write(data)

    -- exit file
    file:close()

    -- ok?
    return true
end

-- isatty
function io.isatty(file)
    file = file or io.stdout
    return file:isatty()
end

-- get std file, /dev/stdin, /dev/stdout, /dev/stderr
function io.stdfile(filepath)
    local file = nil
    if filepath == "/dev/stdin" then
        file = io._stdfile(1)
    elseif filepath == "/dev/stdout" then
        file = io._stdfile(2)
    elseif filepath == "/dev/stderr" then
        file = io._stdfile(3)
    end
    if file then
        return _file.new(filepath, file)
    else
        return nil, string.format("failed to get std file: %s", filepath)
    end
end

-- open file
function io.open(filepath, mode, opt)

    -- check
    assert(filepath)

    -- init option and mode
    opt  = opt or {}
    mode = mode or "r"

    -- open it
    local file = io.file_open(filepath, mode .. (opt.encoding or ""))
    if file then
        return _file.new(filepath, file)
    else
        return nil, string.format("failed to open file: %s", filepath)
    end
end

-- open a filelock
function io.openlock(filepath)

    -- check
    assert(filepath)

    -- open it
    local lock = io.filelock_open(filepath)
    if lock then
        return _filelock.new(filepath, lock)
    else
        return nil, string.format("failed to open lock: %s", filepath)
    end
end

-- close file
function io.close(file)
    return (file or io.stdout):close()
end

-- save object the the given filepath
function io.save(filepath, object, opt)

    -- check
    assert(filepath and object)

    -- init option
    opt = opt or {}

    -- open the file
    local file, err = io.open(filepath, "wb", opt)
    if err then
        -- error
        return false, err
    end

    -- save object to file
    local ok, errors = file:save(object, opt)
    -- close file
    file:close()
    if not ok then
        -- error
        return false, string.format("save %s failed, %s!", filepath, errors)
    end

    -- ok
    return true
end

-- load object from the given file
function io.load(filepath, opt)

    -- check
    assert(filepath)

    -- init option
    opt = opt or {}

    -- open the file
    local file, err = io.open(filepath, "rb", opt)
    if err then
        -- error
        return nil, err
    end

    -- load object
    local result, errors = file:load()

    -- close file
    file:close()

    -- ok?
    return result, errors
end

-- gsub the given file and return replaced data
function io.gsub(filepath, pattern, replace, opt)

    -- init option
    opt = opt or {}

    -- read all data from file
    local data, errors = io.readfile(filepath, opt)
    if not data then return nil, 0, errors end

    -- replace it
    local count = 0
    if type(data) == "string" then
        data, count = data:gsub(pattern, replace)
    else
        return nil, 0, string.format("data is not string!")
    end

    -- replace ok?
    if count ~= 0 then
        -- write all data to file
        local ok, errors = io.writefile(filepath, data, opt)
        if not ok then return nil, 0, errors end
    end

    -- ok
    return data, count
end

-- cat the given file
function io.cat(filepath, linecount, opt)

    -- init option
    opt = opt or {}

    -- open file
    local file = io.open(filepath, "r", opt)
    if file then

        -- show file
        local count = 1
        for line in file:lines(opt) do

            -- show line
            io.print(line)

            -- end?
            if linecount and count >= linecount then
                break
            end

            -- update the line count
            count = count + 1
        end

        -- exit file
        file:close()
    end
end

-- tail the given file
function io.tail(filepath, linecount, opt)

    -- init option
    opt = opt or {}

    -- all?
    if linecount < 0 then
        return io.cat(filepath, opt)
    end

    -- open file
    local file = io.open(filepath, "r", opt)
    if file then

        -- read lines
        local lines = {}
        for line in file:lines(opt) do
            table.insert(lines, line)
        end

        -- tail lines
        local tails = {}
        if #lines ~= 0 then
            local count = 1
            for index = #lines, 1, -1 do

                -- show line
                table.insert(tails, lines[index])

                -- end?
                if linecount and count >= linecount then
                    break
                end

                -- update the line count
                count = count + 1
            end
        end

        -- show tails
        if #tails ~= 0 then
            for index = #tails, 1, -1 do

                -- show tail
                io.print(tails[index])

            end
        end

        -- exit file
        file:close()
    end
end

-- lazy loading stdfile
io.stdin  = nil
io.stdout = nil
io.stderr = nil
setmetatable(io, { __index = function (tbl, key)    
        local val = rawget(tbl, key)
        if val == nil and (key == "stdin" or key == "stdout" or key == "stderr") then
            val = io.stdfile("/dev/" .. key)
            if val ~= nil then
                rawset(tbl, key, val)
            end
        end
        return val
    end})

-- return module
return io