From 6ba7499ac5992c8cc849ffcbd6d2837d305f5b63 Mon Sep 17 00:00:00 2001 From: Mark Pulford Date: Mon, 16 May 2011 19:46:05 +0930 Subject: Add support for stdin to encode.lua/decode.lua --- tests/common.lua | 33 +++++++++++++++++++++++++-------- tests/decode.lua | 15 +++++++++------ tests/encode.lua | 14 ++++++++------ 3 files changed, 42 insertions(+), 20 deletions(-) diff --git a/tests/common.lua b/tests/common.lua index e08b6c2..0b231bd 100644 --- a/tests/common.lua +++ b/tests/common.lua @@ -96,12 +96,21 @@ function dump_value(value) end function file_load(filename) - local file, err = io.open(filename) - if file == nil then - error("Unable to read " .. filename) + local file + if filename == nil then + file = io.stdin + else + local err + file, err = io.open(filename) + if file == nil then + error(string.format("Unable to read '%s': %s", filename, err)) + end end local data = file:read("*a") - file:close() + + if filename ~= nil then + file:close() + end if data == nil then error("Failed to read " .. filename) @@ -111,12 +120,20 @@ function file_load(filename) end function file_save(filename, data) - local file, err = io.open(filename, "w") - if file == nil then - error("Unable to write " .. filename) + local file + if filename == nil then + file = io.stdout + else + local err + file, err = io.open(filename, "w") + if file == nil then + error(string.format("Unable to write '%s': %s", filename, err)) + end end file:write(data) - file:close() + if filename ~= nil then + file:close() + end end function compare_values(val1, val2) diff --git a/tests/decode.lua b/tests/decode.lua index c042168..cac29e6 100755 --- a/tests/decode.lua +++ b/tests/decode.lua @@ -1,11 +1,14 @@ #!/usr/bin/env lua +-- usage: decode.lua [json_file] +-- +-- Eg: +-- echo '[ "testing" ]' | ./decode.lua +-- ./decode.lua test.json + require "common" require "cjson" -if not arg[1] then - print("usage: decode.lua FILE") - os.exit(-1) -end - -print(serialise_value(cjson.decode(file_load(arg[1])))) +local json_text = file_load(arg[1]) +local t = cjson.decode(json_text) +print(serialise_value(t)) diff --git a/tests/encode.lua b/tests/encode.lua index e8026cc..f13787c 100755 --- a/tests/encode.lua +++ b/tests/encode.lua @@ -1,5 +1,11 @@ #!/usr/bin/env lua +-- usage: encode.lua [lua_file] +-- +-- Eg: +-- echo '{ "testing" }' | ./encode.lua +-- ./encode.lua lua_data.lua + require "common" require "cjson" @@ -16,11 +22,7 @@ function get_lua_table(file) return env.data end -if not arg[1] then - print("usage: encode.lua FILE") - os.exit(-1) -end - -print(cjson.encode(get_lua_table(arg[1]))) +local t = get_lua_table(arg[1]) +print(cjson.encode(t)) -- vi:ai et sw=4 ts=4: -- cgit v1.2.3-55-g6feb