[examples/truncate] Add example for osx.chsize().

This commit is contained in:
Lorenzo Cogotti 2022-12-15 16:45:32 +01:00
parent 90753c7002
commit 55f642b328
1 changed files with 42 additions and 0 deletions

42
examples/truncate.lua Normal file
View File

@ -0,0 +1,42 @@
#!/bin/env lua
-- Stripped down version of util-linux coreutils(1).
--
-- SYNOPSIS:
-- truncate.lua <size> <file>
--
-- Size may have a suffix: K (kilobytes), M (megabytes), G (gigabytes) with K = 1024
--
-- Example use:
-- lua truncate.lua 10K myfile
--
-- Author: Lorenzo Cogotti, The DoubleFourteen Code Forge
local osx = require 'osx'
local size = assert(select(1, ...), "Missing size argument")
local path = assert(select(2, ...), "Missing file path")
local function parsesize(s)
local u = s:sub(-1)
local scale = 1
if u == 'K' then
scale = 1024
s = s:sub(1, -2)
elseif u == 'M' then
scale = 1024*1024
s = s:sub(1, -2)
elseif u == 'G' then
scale = 1024*1024*1024
s = s:sub(1, -2)
end
local v = tonumber(s)
if not v or v < 0 then
error("'"..s.."' is not a valid file size")
end
return v * scale
end
size = parsesize(size)
assert(osx.chsize(path, size))