From 08182e1d044c3d099cf2c628c3ff62aae9cf84d1 Mon Sep 17 00:00:00 2001 From: Buduf Date: Thu, 30 Jun 2022 11:35:05 +0200 Subject: [PATCH] getscript --- getscript.lua | 93 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) create mode 100644 getscript.lua diff --git a/getscript.lua b/getscript.lua new file mode 100644 index 0000000..2db9512 --- /dev/null +++ b/getscript.lua @@ -0,0 +1,93 @@ +local repo = "https://buduf.ddns.net/git/Buduf/ComputerCraft/raw/branch/master/" +local function printUsage() + local programName = arg[0] or fs.getName(shell.getRunningProgram()) + print("This program downloads a file from my git repository. Usage:") + print(programName .. " [filename]") + print(programName .. " run ") +end + +local tArgs = { ... } + +local run = false +if tArgs[1] == "run" then + table.remove(tArgs, 1) + run = true +end + +if #tArgs < 1 then + printUsage() + return +end + +local url = repo .. table.remove(tArgs, 1) .. ".lua" + +if not http then + printError("getscript requires the http API") + printError("Set http.enabled to true in CC: Tweaked's config") + return +end + +local function getFilename(sUrl) + sUrl = sUrl:gsub("[#?].*", ""):gsub("/+$", "") + return sUrl:match("/([^/]+)$") +end + +local function get(sUrl) + -- Check if the URL is valid + local ok, err = http.checkURL(url) + if not ok then + printError(err or "Invalid URL.") + return + end + + write("Connecting to " .. sUrl .. "... ") + + local response = http.get(sUrl, nil, true) + if not response then + print("Failed.") + return nil + end + + print("Success.") + + local sResponse = response.readAll() + response.close() + return sResponse or "" +end + +if run then + local res = get(url) + if not res then return end + + local func, err = load(res, getFilename(url), "t", _ENV) + if not func then + printError(err) + return + end + + local ok, err = pcall(func, table.unpack(tArgs)) + if not ok then + printError(err) + end +else + local sFile = tArgs[1] or getFilename(url) or url + local sPath = shell.resolve(sFile) + if fs.exists(sPath) then + print("File already exists") + return + end + + local res = get(url) + if not res then return end + + local file, err = fs.open(sPath, "wb") + if not file then + printError("Cannot save file: " .. err) + return + end + + file.write(res) + file.close() + + print("Downloaded as " .. sFile) +end