jecs-nightly/src/sync.luau
2025-03-02 05:07:57 +01:00

110 lines
3 KiB
Text

--!strict
local fs = require("@lune/fs")
local net = require("@lune/net")
local stdio = require("@lune/stdio")
local progress_bar = require("./util/progress")
local result = require("./util/result")
--- Fetches the given file raw from the jecs github
local function fetch_raw(file: string): result.Identity<string>
local res = net.request(`https://raw.githubusercontent.com/Ukendio/jecs/refs/heads/main/{file}`)
if not res.ok then
return result(false, `Not ok: {res.statusMessage} @ {res.statusCode}`)
end
return result(true, res.body)
end
local function save_if_diff(filepath: string, contents: string): result.Identity<nil>
if not fs.metadata(filepath).exists then
fs.writeFile(filepath, contents)
return result(true, nil)
end
local existing = fs.readFile(filepath)
if existing == contents then
return result(false, "Contents are the same.")
end
fs.writeFile(filepath, contents)
return result(true, nil)
end
local function round_to(n: number, places: number)
local x = 10 ^ (places or 0)
return math.round(n * x) / x
end
--- Synchronizes the required files from the jecs main branch.
local function sync(to: string): result.Identity<boolean>
local begin = os.clock()
local progress = progress_bar
.new()
:withStage("init", "Initializing")
:withStage("fetch", "Fetching latest files")
:withStage("save", "Saving files")
progress:start()
if not fs.metadata(to).exists then
fs.writeDir(to)
end
progress:nextStage()
local includes = {
"jecs.luau",
"README.md",
"CHANGELOG.md",
"LICENSE",
".luaurc",
"default.project.json",
}
local sources = {}
for _, file in includes do
local contents = fetch_raw(file)
if not contents.ok then
progress:stop()
stdio.ewrite(`🔥 Couldn't get the latest source for {file}:\n{contents.err}\n`)
return result(false, `Couldn't get the latest source for {file}.`)
end
sources[file] = contents.val
end
progress:nextStage()
local sources_modified = {}
local any_changed = false
for file, contents in sources do
local res = save_if_diff(`{to}/{file}`, contents)
if res.ok then
any_changed = true
table.insert(sources_modified, file)
end
end
if not any_changed then
progress:stop()
local took = round_to((os.clock() - begin) * 1_000, 2)
print(
`🕛 Finished synchronizing, no changes since latest source {stdio.style("dim")}(took {took}ms){stdio.style(
"reset"
)}`
)
return result(true, false)
end
progress:stop()
local took = round_to((os.clock() - begin) * 1_000, 2)
print(`🪨 Finished synchronizing {stdio.style("dim")}(took {took}ms){stdio.style("reset")}`)
print(`Changed files:`)
print(sources_modified)
return result(true, true)
end
return sync