Download:
child 1:f765e0e5649b
0:616025111516
Anton Shestakov <av6@dwimlabs.net>, Wed, 07 Sep 2016 16:07:39 +0800
hglib: absolute basics

3 файлов изменено, 85 вставок(+), 0 удалений(-) [+]
hglib.lua file | annotate | diff | comparison | revisions
spec/data/hello file | annotate | diff | comparison | revisions
spec/hglib_spec.lua file | annotate | diff | comparison | revisions
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/hglib.lua Wed Sep 07 16:07:39 2016 +0800
@@ -0,0 +1,70 @@
+local sizes = { i4 = 4, u4 = 4, c = 1 }
+
+local function read_u4(rh)
+ local value = 0
+ for i = 1, sizes.u4 do
+ local byte = rh:read(1):byte()
+ value = value + byte * (2 ^ ((sizes.u4 - i) * 8))
+ end
+ return value
+end
+
+local function read_c(rh)
+ return rh:read(sizes.c)
+end
+
+local function read_channel(rh)
+ local channel = read_c(rh)
+ local length = read_u4(rh)
+ if channel == 'I' or channel == 'L' then
+ return channel, length
+ else
+ return channel, rh:read(length)
+ end
+end
+
+local Client = {}
+Client.__index = Client
+
+function Client.connect(rh, wh)
+ local client = {}
+ setmetatable(client, Client)
+ client.rh = rh
+ client.wh = wh
+ return client
+end
+
+function Client:read_hello()
+ local channel, message = read_channel(self.rh)
+ assert(channel == 'o', 'channel for the hello message must be "o"')
+ local index = 1
+ while index <= #message do
+ local nexteol = message:find('\n', index + 1, true)
+ if nexteol == nil then nexteol = #message + 1 end
+ local line = message:sub(index, nexteol - 1)
+ local ci = line:find(': ', 1, true)
+ if ci ~= nil then
+ local key, value = line:sub(1, ci - 1), line:sub(ci + 2)
+ if key == 'capabilities' then
+ self.capabilities = {}
+ for cap in value:gmatch('%S+') do
+ self.capabilities[cap] = true
+ end
+ elseif key == 'encoding' then
+ self.encoding = value
+ elseif key == 'pid' then
+ self.pid = tonumber(value)
+ elseif key == 'pgid' then
+ self.pgid = tonumber(value)
+ end
+ end
+ index = nexteol + 1
+ end
+end
+
+return {
+ read_u4 = read_u4,
+ read_c = read_c,
+ read_channel = read_channel,
+ Client = Client
+}
Binary file spec/data/hello has changed
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/spec/hglib_spec.lua Wed Sep 07 16:07:39 2016 +0800
@@ -0,0 +1,15 @@
+local hglib = require('hglib')
+
+describe('hglib client', function()
+ it('can read hello', function()
+ local rh = io.open('spec/data/hello', 'rb')
+ local client = hglib.Client.connect(rh, nil)
+ client:read_hello()
+ rh:close()
+ assert.is_true(client.capabilities.getencoding)
+ assert.is_true(client.capabilities.runcommand)
+ assert.are_equal('UTF-8', client.encoding)
+ assert.are_equal(3615, client.pid)
+ assert.are_equal(3615, client.pgid)
+ end)
+end)