|
|
@ -1,5 +1,6 @@
|
|
|
|
local _ENV = mkmodule('json')
|
|
|
|
local _ENV = mkmodule('json')
|
|
|
|
local internal = require 'json.internal'
|
|
|
|
local internal = require 'json.internal'
|
|
|
|
|
|
|
|
local fs = dfhack.filesystem
|
|
|
|
|
|
|
|
|
|
|
|
encode_defaults = {
|
|
|
|
encode_defaults = {
|
|
|
|
-- For compatibility with jsonxx (C++)
|
|
|
|
-- For compatibility with jsonxx (C++)
|
|
|
@ -14,11 +15,8 @@ function encode(data, options, msg)
|
|
|
|
return internal:encode(data, msg, opts)
|
|
|
|
return internal:encode(data, msg, opts)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
function encode_file(data, path, overwrite, ...)
|
|
|
|
function encode_file(data, path, ...)
|
|
|
|
if dfhack.filesystem.exists(path) and not overwrite then
|
|
|
|
if fs.isdir(path) then
|
|
|
|
error('File exists: ' .. path)
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
if dfhack.filesystem.isdir(path) then
|
|
|
|
|
|
|
|
error('Is a directory: ' .. path)
|
|
|
|
error('Is a directory: ' .. path)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
local contents = encode(data, ...)
|
|
|
|
local contents = encode(data, ...)
|
|
|
@ -41,4 +39,42 @@ function decode_file(path, ...)
|
|
|
|
return decode(contents, ...)
|
|
|
|
return decode(contents, ...)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
local _file = defclass()
|
|
|
|
|
|
|
|
function _file:init(opts)
|
|
|
|
|
|
|
|
self.path = opts.path
|
|
|
|
|
|
|
|
self.data = {}
|
|
|
|
|
|
|
|
self.exists = false
|
|
|
|
|
|
|
|
self:read(opts.strict)
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function _file:read(strict)
|
|
|
|
|
|
|
|
if not fs.exists(self.path) then
|
|
|
|
|
|
|
|
if strict then
|
|
|
|
|
|
|
|
error('cannot read file: ' .. self.path)
|
|
|
|
|
|
|
|
else
|
|
|
|
|
|
|
|
self.data = {}
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
else
|
|
|
|
|
|
|
|
self.exists = true
|
|
|
|
|
|
|
|
self.data = decode_file(self.path)
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
return self.data
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function _file:write(data)
|
|
|
|
|
|
|
|
if data then
|
|
|
|
|
|
|
|
self.data = data
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
encode_file(self.data, self.path)
|
|
|
|
|
|
|
|
self.exists = true
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function _file:__tostring()
|
|
|
|
|
|
|
|
return ('<json file: %s>'):format(self.path)
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
function open(path, strict)
|
|
|
|
|
|
|
|
return _file{path=path, strict=strict}
|
|
|
|
|
|
|
|
end
|
|
|
|
|
|
|
|
|
|
|
|
return _ENV
|
|
|
|
return _ENV
|
|
|
|