Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for relative requires #1634

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Guldoman
Copy link
Member

@Guldoman Guldoman commented Oct 5, 2023

This keeps a stack of require "paths", and uses the topmost one when resolving relative requires to calculate the "absolute path".

From inside "path_1.path_2":

  • Calling require ".b" will require "path_1.path_2.b".
  • Calling require "..b" will require "path_1.b".

This has a few caveats:

  1. The relative require must be called "inside" the parent require; this means that requires called "later" will have the wrong path.
    So:
    require ".b" -- OK
    
    local function blabla()
      require ".c" -- Not OK
    end
  2. The path traversal is limited by the parent path; so if the parent path is core.plugins and the relative path is .......plugin_name, the resulting path is plugin_name.

(2) might be considered a feature, to limit the require range and not go outside our managed directories (even thought a plugin could still add its own custom search path).

To provide a workaround for (1), I added get_current_require_path which will return the topmost path in the stack. This still needs to be called inside the parent require, but its result can be used later.
So:

require ".b" -- OK
local path = get_current_require_path() -- OK

local function blabla()
  require ".c" -- Not OK
  require(path .. ".c") -- OK
  get_current_require_path() -- Not OK
end

Suggestions for a better name for get_current_require_path are welcome.
Should we also add a level parameter to get_current_require_path, so that path traversal doesn't need to be implemented by each plugin that uses it?

EDIT: If we want to avoid using pcall, we could use a to-be-closed object that does the stack popping.

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

Successfully merging this pull request may close these issues.

None yet

1 participant