This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
skwerlman's profile picture

Wrapping a filesystem

Started by skwerlman, 29 May 2014 - 08:58 AM
skwerlman #1
Posted 29 May 2014 - 10:58 AM
I've been working on this for far too long, so I've decided to ask for help.

I'd like to wrap all the functions that deal with paths they return modified values. I'd also like this to affect all further operations on the computer. (I need it to work with user supplied code, like an OS)
For example, if a program calls shell.run('/bar.lua'), I'd like it to actually run /foo/bar.lua
I've tried stuff like:

local root = '/foo/'
local oldShell = shell

local wrap(...)
  local tArg = {...}
  local tOut = {}
  for k,v in ipairs(tArg) do
	if type(v) == "string" then
	  if v=="." then
		tOut[k] = root
	  else
		tOut[k] = root..v
	  end
	else
	  error('Expected string, got '..type(v))
	end
  end
  return unpack(tOut)
end

function shell.run(command, ...)
  return oldShell.run(wrap(command), ...)
end

-- repeat for all api functions that use paths

but it doesn't seem to work correctly.
Any tips?
CometWolf #2
Posted 29 May 2014 - 11:13 AM
You're putting too much thought into this :P/> just overwrite the global fs functions and you're good to go. Here's some code i used to hide files of my choosing, it's the same principle, just modify the path differently.

_B._H.checkHidden = function(path)
  for k,v in pairs(_B._H.tHide) do
	if v == path then
	  return true
	end
  end
  return false
end

_G.fs.list = function(path)
  local tFiles = _B.fs.list(path)
  local i = 1
  while true do
	if _B.string.match(tFiles[i],"Fake$") then
	  tFiles[i] = _B.string.sub(tFiles[i],1,#tFiles[i]-4)
	  i = i+1
	elseif _B._H.checkHidden(tFiles[i]) then
	  _B.table.remove(tFiles,i)
	else
	  i = i+1
	end
	if i > #tFiles then
	  break
	end
  end
  return tFiles
end

_G.fs.open = function(path,mode)
  if _B._H.checkHidden(path) then
	if _B.string.match(mode,"w") then
	  path = path.."Fake"
	elseif (_B.string.match(mode,"r") or _B.string.match(mode,"a"))
	and _B.fs.exists(path.."Fake") then
	  path = path.."Fake"
	end
  end
  return _B.fs.open(path,mode)
end

_G.fs.exists = function(path)
  if _B._H.checkHidden(path) then
	path = path.."Fake"
  end
  return _B.fs.exists(path)
end

_G.fs.delete = function(path)
  if _B._H.checkHidden(path)  then
	path = path.."Fake"
  end
  return _B.fs.delete(path)
end

_G.fs.move = function(path,path2)
  if _B._H.checkHidden(path) then
	path = path.."Fake"
  end
  if _B._H.checkHidden(path2) then
	path2 = path2.."Fake"
  end
  return _B.fs.move(path,path2)
end

_G.fs.copy = function(path,path2)
  if _B._H.checkHidden(path) then
	path = path.."Fake"
  end
  if _B._H.checkHidden(path2) then
	path2 = path2.."Fake"
  end
  return _B.fs.copy(path,path2)
end
also _B is just a backup of _G, since this particulair code overwrote a lot of _G
Edited on 29 May 2014 - 09:14 AM