1
0
mirror of https://github.com/kepler155c/opus synced 2024-11-15 05:04:50 +00:00
opus/sys/apis/git.lua

85 lines
1.9 KiB
Lua
Raw Normal View History

2016-12-27 03:26:43 +00:00
local json = require('json')
2016-12-11 21:36:36 +00:00
local Util = require('util')
2016-12-11 19:24:52 +00:00
2018-11-04 18:00:37 +00:00
-- Limit queries to once per minecraft day
-- TODO: will not work if time is stopped
2016-12-11 19:24:52 +00:00
local TREE_URL = 'https://api.github.com/repos/%s/%s/git/trees/%s?recursive=1'
2017-10-01 00:35:36 +00:00
local FILE_URL = 'https://raw.githubusercontent.com/%s/%s/%s/%s'
2016-12-11 19:24:52 +00:00
local git = { }
2018-11-04 18:00:37 +00:00
local fs = _G.fs
2018-11-03 22:13:41 +00:00
local os = _G.os
if not _G.GIT then
_G.GIT = { }
end
2017-09-16 00:27:56 +00:00
2018-11-04 18:00:37 +00:00
function git.list(repository)
2018-01-24 22:39:38 +00:00
local t = Util.split(repository, '(.-)/')
2017-09-16 00:27:56 +00:00
2018-11-04 18:00:37 +00:00
local user = table.remove(t, 1)
local repo = table.remove(t, 1)
local branch = table.remove(t, 1) or 'master'
local path
2018-11-03 22:13:41 +00:00
2018-11-04 18:00:37 +00:00
if not Util.empty(t) then
path = table.concat(t, '/') .. '/'
end
2016-12-11 19:24:52 +00:00
2018-11-04 18:00:37 +00:00
local cacheKey = table.concat({ user, repo, branch }, '-')
local fname = fs.combine('.git', cacheKey)
local function getContents()
if fs.exists(fname) then
local contents = Util.readTable(fname)
if contents and contents.data == os.day() then
return contents.data
end
fs.delete(fname)
end
local dataUrl = string.format(TREE_URL, user, repo, branch)
local contents = Util.download(dataUrl)
if contents then
return json.decode(contents)
end
2018-01-24 22:39:38 +00:00
end
2016-12-11 19:24:52 +00:00
2018-11-04 18:00:37 +00:00
local data = getContents() or error('Invalid repository')
2018-01-24 22:39:38 +00:00
if data.message and data.message:find("API rate limit exceeded") then
error("Out of API calls, try again later")
end
2016-12-11 19:24:52 +00:00
2018-01-24 22:39:38 +00:00
if data.message and data.message == "Not found" then
error("Invalid repository")
end
2016-12-11 19:24:52 +00:00
2018-11-04 18:00:37 +00:00
if not fs.exists(fname) then
Util.writeTable('.git/' .. cacheKey, { day = os.day(), data = data })
end
2016-12-11 19:24:52 +00:00
2018-11-04 18:00:37 +00:00
local list = { }
2018-01-24 22:39:38 +00:00
for _,v in pairs(data.tree) do
if v.type == "blob" then
v.path = v.path:gsub("%s","%%20")
2018-11-04 18:00:37 +00:00
if not path then
list[v.path] = {
url = string.format(FILE_URL, user, repo, branch, v.path),
size = v.size,
}
elseif Util.startsWith(v.path, path) then
local p = string.sub(v.path, #path)
list[p] = {
url = string.format(FILE_URL, user, repo, branch, path .. p),
size = v.size,
}
end
2018-01-24 22:39:38 +00:00
end
end
2016-12-11 19:24:52 +00:00
2018-01-24 22:39:38 +00:00
return list
2016-12-11 19:24:52 +00:00
end
return git