Skip to content

Instantly share code, notes, and snippets.

@Cyrixus
Created April 15, 2012 02:46
Show Gist options
  • Save Cyrixus/2389573 to your computer and use it in GitHub Desktop.
Save Cyrixus/2389573 to your computer and use it in GitHub Desktop.
A ComputerCraft version of wget (based on HttpTest)
--[[
wget
A program adapted from HttpTest, by Epsen:
http://www.computercraft.info/forums2/index.php?/topic/82-121-httptest-v13/page__hl__http__fromsearch__1
Credit for the original work goes to him. Additional modifications have been
made to the file to make it suitable for my own purposes.
Matthew DiBernardo [04.14.2012]
--]]
--[[ Setting up variables ]]
local fileWriteOK
local url
local filename
local tArgs = { ... }
local function getHttpBody( url )
http.request( url )
while true do
local event, url, hBody = os.pullEvent()
if event == "http_success" then
print( "HTTP SUCCESS\nURL = "..url )
return hBody
else
error( "HTTP FAILURE\nURL = "..url ) -- If the error is not catched, this will exit the program.
return nil -- In case this function is called via pcall.
end
end
end
local function processHttpBody( hBody, filename )
local hFile
if hBody then
local body = hBody.readAll() -- Read the whole body.
hFile = io.open( filename, "w" ) -- Open the provided filename for writing.
hFile:write( body ) -- Write the body to the file.
hFile:close() -- Save the changes and close the file.
else
print( "Sorry, no body to process." )
end
hBody.close() -- Do not know for sure if this is really necessary, but just in case.
end
local function checkOverwrite( filename )
term.setCursorBlink( false )
print("\nWarning: File already exists. Overwrite? (Y/N)")
while true do
event, choice = os.pullEvent( "char" ) -- Only listen for "char" events.
if string.lower( choice ) == "y" then return true end
if string.lower( choice ) == "n" then return false end
end
end
local function printUsage()
print("wget <url> [outfile]")
end
--[[ ===== Execution Entry ===== ]]
--[[ Processing arguments ]]
if tArgs[1] then url = tArgs[1] end
if tArgs[2] then filename = tArgs[2] end
--[[ Making sure all necessary arguments were provided by the user ]]
if not url then
printUsage()
elseif not filename then
b = getHttpBody(url)
print(b.readAll())
b.close()
elseif not fs.exists( filename ) or checkOverwrite( filename ) then
processHttpBody( getHttpBody( url ), filename ) --If getHttpBody successfully returns a body, we continue with processing the body and saving it to a file.
end
@djfj74
Copy link

djfj74 commented Dec 29, 2014

Very useful

@maprambo
Copy link

maprambo commented Aug 7, 2015

better than uploading things to pastebin you don't really like to have there, like your own http api urls 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment