aboutsummaryrefslogtreecommitdiffstats
path: root/lua/mason-core/installer/context/InstallContextCwd.lua
blob: b365cbd9539a73b3fe59521fbbf2607165c6014d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
local Result = require "mason-core.result"
local fs = require "mason-core.fs"
local path = require "mason-core.path"

---@class InstallContextCwd
---@field private handle InstallHandle
---@field private cwd string?
local InstallContextCwd = {}
InstallContextCwd.__index = InstallContextCwd

---@param handle InstallHandle
function InstallContextCwd:new(handle)
    ---@type InstallContextCwd
    local instance = {}
    setmetatable(instance, self)
    instance.handle = handle
    instance.cwd = nil
    return instance
end

function InstallContextCwd:initialize()
    return Result.try(function(try)
        local staging_dir = self.handle.location:staging(self.handle.package.name)
        if fs.sync.dir_exists(staging_dir) then
            try(Result.pcall(fs.sync.rmrf, staging_dir))
        end
        try(Result.pcall(fs.sync.mkdirp, staging_dir))
        self:set(staging_dir)
    end)
end

function InstallContextCwd:get()
    assert(self.cwd ~= nil, "Tried to access cwd before it was set.")
    return self.cwd
end

---@param new_abs_cwd string
function InstallContextCwd:set(new_abs_cwd)
    assert(type(new_abs_cwd) == "string", "new_cwd is not a string")
    assert(
        path.is_subdirectory(self.handle.location:get_dir(), new_abs_cwd),
        ("%q is not a subdirectory of %q"):format(new_abs_cwd, self.handle.location)
    )
    self.cwd = new_abs_cwd
    return self
end

return InstallContextCwd