summaryrefslogtreecommitdiff
path: root/lib/gall/tag.lua
blob: 7bafbe7588f0b9a0ce68f07c8a95cb613cb680fb (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
-- gall.tag
--
-- Git Abstraction Layer for Lua -- Tag object interface
--
-- Copyright 2012 Daniel Silverstone <dsilvers@digital-scurf.org>
--
--

local ll = require "gall.ll"

local objs = setmetatable({}, {__mode="k"})
local repos = setmetatable({}, {__mode="k"})
local parsed = setmetatable({}, {__mode="k"})

local function parse_person(pers)
   local real, email, when, tz = pers:match("^(.-) <([^>]+)> ([0-9]+) ([+-][0-9]+)$")
   return {
      realname = real,
      email = email,
      unixtime = when,
      timezone = tz
   }
end

local PGP_SIG_START = "-----BEGIN PGP SIGNATURE-----"

local function tagindex(tag, field)
   if not parsed[tag] then
      local raw = objs[tag].raw
      local headers, body, signature = {}, ""
      local state = "headers"

      for l in raw:gmatch("([^\n]*)\n") do
	 if state == "headers" then
	    local first, second = l:match("^([^ ]+) (.+)$")
	    if first then
	       if headers[first] then
		  headers[first][#headers[first]+1] = second
	       else
		  headers[first] = { second }
	       end
	    else
	       state = "message"
	    end
	 elseif state == "message" then
	    if l == PGP_SIG_START then
	       signature = l .. "\n"
	       state = "signature"
	    else
	       body = body .. l .. "\n"
	    end
	 else
	    signature = signature .. l .. "\n"
	 end
      end

      -- there's always one object
      rawset(tag, "object", repos[tag]:get(headers.object[1]))
      -- Always one type
      rawset(tag, "type", headers.type[1])
      -- Always one tag name
      rawset(tag, "tag", headers.tag[1])
      -- Always one tagger
      rawset(tag, "tagger", parse_person(headers.tagger[1]))
      -- A message
      rawset(tag, "message", body)
      -- And an optional signature
      rawset(tag, "signature", signature)
      -- Promote the SHA
      rawset(tag, "sha", objs[tag].sha)

      -- Signal we are parsed
      parsed[tag] = true
   end

   return rawget(tag, field)
end

local function tagtostring(tag)
   return "<GitTag(" .. tostring(objs[tag].sha) .. ") in " .. tostring(repos[tag]) .. ">"
end

local tagmeta = {
   __index = tagindex,
   __tostring = tagtostring
}

local function _new(repo, obj)
   local ret =  setmetatable({}, tagmeta)
   objs[ret] = obj
   repos[ret] = repo
   return ret
end

return {
   new = _new
}