formatting & more nil checks

This commit is contained in:
2026-08-21 21:18:51 +02:00
parent 712cfab946
commit 4d8b615ccb
+19 -17
View File
@@ -1,9 +1,3 @@
-- Save as /home/git.lua
local http = require("http")
local fs = require("fs")
local json = textutils.unserializeJSON
-- Configuration
local GIT_TOKEN = "" -- Leave empty for public repos, or add "your-token-here"
-- Parse a Gitea URL like: https://gitea.example.com/owner/repo or /owner/repo/branch/filename
@@ -41,20 +35,24 @@ end
local function downloadFile(base, owner, repo, branch, path, target)
local url = ("%s/api/v1/repos/%s/%s/raw/%s/%s"):format(base, owner, repo, branch, path)
local req = {url = url}
local req = { url = url }
if GIT_TOKEN ~= "" then
req.headers = {Authorization = "token " .. GIT_TOKEN}
req.headers = { Authorization = "token " .. GIT_TOKEN }
end
local response = http.get(req)
if not response then error("Failed to download: "..path) end
if not response then error("Failed to download: " .. path) end
local data = response.readAll()
response.close()
local file = fs.open(target, "w")
local file, fileError = fs.open(target, "w")
if file then
file.write(data)
file.close()
else
error("Could not download file '" .. target "' due to: " .. fileError)
end
end
local function cloneRepo(url)
@@ -63,18 +61,22 @@ local function cloneRepo(url)
print("Cloning: " .. info.owner .. "/" .. info.repo .. "@" .. info.branch)
local treeUrl = ("%s/api/v1/repos/%s/%s/git/trees/%s?recursive=1"):format(info.base, info.owner, info.repo, info.branch)
local treeUrl = ("%s/api/v1/repos/%s/%s/git/trees/%s?recursive=1"):format(info.base, info.owner, info.repo,
info.branch)
local req = {url = treeUrl}
local req = { url = treeUrl }
if GIT_TOKEN ~= "" then
req.headers = {Authorization = "token " .. GIT_TOKEN}
req.headers = { Authorization = "token " .. GIT_TOKEN }
end
local resp = http.get(req)
if not resp then error("Cannot access repository. Check URL or token.") end
local tree = json(resp.readAll())
local responseJSON = resp.readAll()
resp.close()
if not responseJSON then error("Response returned empty.") end
local tree = textutils.unserializeJSON(responseJSON)
if not tree then error("Response could not be unserialized") end
local count = 0
for _, node in ipairs(tree.tree) do
@@ -92,8 +94,8 @@ local function cloneRepo(url)
print(("Cloned %d files to /home/git/%s/%s"):format(count, info.owner, info.repo))
end
local args = {...}
if args[1] == "pull" and args[2] then
local args = { ... }
if args[1] == "clone" and args[2] then
cloneRepo(args[2])
else
print("Usage:")