Advertisement
Guest User

90_filesystem.lua

a guest
Oct 19th, 2018
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.91 KB | None | 0 0
  1. local component = require("component")
  2. local event = require("event")
  3. local fs = require("filesystem")
  4. local shell = require("shell")
  5.  
  6. local isInitialized, pendingAutoruns = false, {}
  7.  
  8. local function onInit()
  9.   isInitialized = true
  10.   for _, run in ipairs(pendingAutoruns) do
  11.     local result, reason = pcall(run)
  12.     if not result then
  13.       local path = fs.concat(os.getenv("TMPDIR") or "/tmp", "event.log")
  14.       local log = io.open(path, "a")
  15.       if log then
  16.         log:write(tostring(result) .. ":" .. tostring(reason) .. "\n")
  17.         log:close()
  18.       end
  19.     end
  20.   end
  21.   pendingAutoruns = nil
  22. end
  23.  
  24. local function onComponentAdded(_, address, componentType)
  25.   if componentType == "filesystem" and require("computer").tmpAddress() ~= address then
  26.     local proxy = component.proxy(address)
  27.     if proxy then
  28.       local name = address:sub(1, 3)
  29.       while fs.exists(fs.concat("/mnt", name)) and
  30.             name:len() < address:len() -- just to be on the safe side
  31.       do
  32.         name = address:sub(1, name:len() + 1)
  33.       end
  34.       name = fs.concat("/mnt", name)
  35.       fs.mount(proxy, name)
  36.       if fs.isAutorunEnabled() then
  37.         local file = shell.resolve(fs.concat(name, "autorun"), "lua") or
  38.                       shell.resolve(fs.concat(name, ".autorun"), "lua")
  39.         if file then
  40.           local run = function()
  41.             assert(shell.execute(file, _ENV, proxy))
  42.           end
  43.           if isInitialized then
  44.             run()
  45.           else
  46.             table.insert(pendingAutoruns, run)
  47.           end
  48.         end
  49.       end
  50.     end
  51.   end
  52. end
  53.  
  54. local function onComponentRemoved(_, address, componentType)
  55.   if componentType == "filesystem" then
  56.     if fs.get(shell.getWorkingDirectory()).address == address then
  57.       shell.setWorkingDirectory("/")
  58.     end
  59.     fs.umount(address)
  60.   end
  61. end
  62.  
  63. event.listen("init", onInit)
  64. event.listen("component_added", onComponentAdded)
  65. event.listen("component_removed", onComponentRemoved)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement