Files
kryon/scripts/project_build.zi
T

212 lines
15 KiB
Ziran

// Native helpers for project fingerprints, output modes and codec builds.
#import "std/vec"
#import "std/stdio_linux"
#import "std/c_string"
Args :: #import "std/byte_text_linux"
Env :: #import "std/environment_linux"
Fs :: #import "std/file_tree_linux"
File :: #import "std/file_linux"
Whole :: #import "std/file"
Path :: #import "std/path"
Sort :: #import "std/sort"
J :: #import "std/json_document"
Proc :: #import "std/process_run_linux"
Capture :: #import "std/process_capture_linux"
Libc :: #system_library "libc";
OpenRaw :: (path: *u8,flags: s32) -> s32 #foreign Libc "open";
ModeRaw :: (fd: s32,mode: u32) -> s32 #foreign Libc "fchmod";
CloseRaw :: (fd: s32) -> s32 #foreign Libc "close";
#if #defined(__APPLE__) {
NO_FOLLOW :: 256;
HashPrefix :: string.["shasum", "-a", "256", "--"];
} else {
NO_FOLLOW :: 131072;
HashPrefix :: string.["sha256sum", "--"];
}
failed: bool;
Fail :: (message: string) { if !failed { PrintError("kryon build: "); PrintError(message); PrintError("\n") }; failed=true }
Own :: (value: string) -> string { return TextDetach(TextCopy(value)) }
FreeNames :: (names: *Vec(string)) { Fs.FreeDirectoryNames(names) }
PushUnique :: (names: *Vec(string),value: string) { for i: 0..names.count-1 { if (<<names)[i]==value { return } }; VecPush(<<names,Own(value)) }
Run :: (arguments: []string) -> bool {
run: Proc.ProcessRun
started:=Proc.RunProcess(Proc.ProcessOptions.{arguments=arguments},*run)
if !started || run.code!=0 { Fail("native build command failed"); return false }; return true
}
Canonical :: (path: string) -> Text {
existing: Text=Fs.ResolvePath(path)
if existing.bytes.count>0 { return existing }
parent:=Fs.PathParent(path)
if parent==path || Fs.PathStatus(path,false).kind==.Link { Fail("cannot resolve module path"); return .{} }
base: Text=Canonical(parent); if failed { return .{} }
joined: Text=Fs.JoinPath(TextView(base),Fs.PathName(path)); clean: [4096]u8
value:=Path.CleanAbsolute(TextView(joined),clean[:]); if value=="" { Fail("module path exceeds supported size") }; return TextCopy(value)
}
Resolve :: (path: string) -> Text {
cwd: Text=Fs.WorkingDirectory(); full: Text=Fs.JoinPath(TextView(cwd),path)
return Canonical(TextView(full))
}
Words :: (input: string,out: *Vec(string)) -> bool {
word: Vec(u8); quote: u8; started: bool; index: s64
while index<input.count {
c:=input[index]; index+=1
if quote==39 { if c==39 { quote=0 } else { VecPush(word,c) }; continue }
if c==92 {
if index==input.count { Fail("unfinished module-path escape"); return false }
next:=input[index]
if quote==34 && next!=34 && next!=92 { VecPush(word,c); continue }
index+=1; VecPush(word,next); started=true; continue
}
if quote==34 { if c==34 { quote=0 } else { VecPush(word,c) }; continue }
if c==39 || c==34 { quote=c; started=true; continue }
if c==32 || c==9 || c==10 || c==13 {
if started { VecPush(<<out,Own(TextView(word[:]))); unused VecResize(word,0); started=false }; continue
}
VecPush(word,c); started=true
}
if quote!=0 { Fail("unclosed module-path quote"); return false }
if started { VecPush(<<out,Own(TextView(word[:]))) }; return true
}
Source :: (path: string) -> bool { suffix:=Fs.PathSuffix(path); return (suffix==".zi" || suffix==".ts" || suffix==".tsx") && Fs.IsFile(path) }
Scan :: (root: string,out: *Vec(string)) {
names: Vec(string); defer FreeNames(*names)
if !Fs.ListDirectory(root,*names) { if Fs.IsDirectory(root) { Fail("cannot scan module directory") }; return }
for name: names[:] {
path: Text=Fs.JoinPath(root,name)
if Source(TextView(path)) { PushUnique(out,TextView(path)) }
if Fs.IsDirectory(TextView(path)) {
children: Vec(string); defer FreeNames(*children)
if !Fs.ListDirectory(TextView(path),*children) { Fail("cannot scan module subdirectory"); return }
for child: children[:] { file: Text=Fs.JoinPath(TextView(path),child); if Source(TextView(file)) { PushUnique(out,TextView(file)) } }
}
}
}
Writer :: struct { handle: File.FileHandle; offset: s64 }
Write :: (out: *Writer,value: string) { if File.WriteTextAt(out.handle,value,out.offset)!=value.count { Fail("cannot write fingerprint input") }; out.offset+=value.count }
Byte :: (out: *Writer,value: u8) { bytes: [1]u8=.[value]; if File.WriteAt(out.handle,bytes[:],out.offset)!=1 { Fail("cannot write fingerprint boundary") }; out.offset+=1 }
Fingerprint :: () -> Text {
words: Vec(string); roots: Vec(string); sources: Vec(string); defer FreeNames(*words); defer FreeNames(*roots); defer FreeNames(*sources)
if !Words(Env.EnvironmentText("KRYON_MODULE_PATH_ARGS"),*words) { return .{} }
index: s64
while index<words.count {
word:=words[index]; value: string
if word=="--module-path" { index+=1; if index<words.count { value=words[index] } }
else if word.count>=14 && word[0:14]=="--module-path=" { value=word[14:word.count] }
else { Fail("unexpected module-path argument"); return .{} }
if value=="" { Fail("--module-path needs a directory"); return .{} }
path: Text=Resolve(value); if failed { return .{} }; PushUnique(*roots,TextView(path)); index+=1
}
// The temporary-directory API requires a caller-owned parent. HOME also
// supports ordinary shells and managed builds that do not define TMPDIR.
parent:=Env.EnvironmentText("TMPDIR"); if parent=="" { parent=Env.EnvironmentText("HOME") }
temp: Text=Fs.CreateTemporaryDirectory(parent,"kryon-fingerprint-"); if temp.bytes.count==0 { Fail("cannot create private fingerprint scratch"); return .{} }; defer { unused Fs.RemoveTree(TextView(temp)) }
path: Text=Fs.JoinPath(TextView(temp),"inputs"); writer: Writer; writer.handle=File.OpenExclusivePrivate(TextView(path)); if !writer.handle.valid { Fail("cannot open fingerprint scratch"); return .{} }
for root: roots[:] { Write(*writer,root); Byte(*writer,0); Byte(*writer,ifx Fs.IsDirectory(root) then cast(u8)1 else cast(u8)0); Scan(root,*sources) }
Sort.SortText(sources[:])
for source: sources[:] {
Write(*writer,source); Byte(*writer,0)
input:=File.OpenRead(source); if !input.valid { Fail("cannot read module source"); break }; buffer: [65536]u8; offset: s64
while true { size:=File.ReadAt(input,buffer[:],offset); if size<0 { Fail("cannot read module source"); break }; if size==0 { break }; if File.WriteAt(writer.handle,buffer[0:size],writer.offset)!=size { Fail("cannot hash module source"); break }; offset+=size; writer.offset+=size }
unused File.CloseFile(input); Byte(*writer,0)
}
if !File.CloseFile(writer.handle) { Fail("cannot close fingerprint scratch") }; if failed { return .{} }
output: [8192]u8; arguments: Vec(string); for argument: HashPrefix { VecPush(arguments,argument) }; VecPush(arguments,TextView(path)); result:=Capture.CaptureOutput(arguments[:],output[:])
if result.error || result.code!=0 || result.length<64 { Fail("SHA-256 command failed"); return .{} }
return TextCopy(TextView(output[0:64]))
}
ModuleInputs :: (arguments: []string) -> s32 {
digest: Text=Fingerprint(); if failed { return 1 }
if arguments.count==3 && arguments[0]=="--check" {
expected: Vec(u8); BuilderPrint(*expected,"%\n%\n%\n",arguments[2],Env.EnvironmentText("KRYON_MODULE_PATH_ARGS"),TextView(digest))
actual: Vec(u8); okay:=Whole.ReadFileInto(arguments[1],*actual)
print("%\n",ifx okay && TextView(actual[:])==TextView(expected[:]) then "current" else "stale")
} else { print("%\n",TextView(digest)) }; return 0
}
SetMode :: (arguments: []string) -> s32 {
if arguments.count!=2 || (arguments[0]!="644" && arguments[0]!="755") { Fail("mode requires 644 or 755 and a path"); return 2 }
path: [4096]u8; if !CopyCString(arguments[1],path[:]) { Fail("output path exceeds supported size"); return 1 }
fd:=OpenRaw(*path[0],NO_FOLLOW); if fd<0 { Fail("cannot open output mode descriptor"); return 1 }
mode:=ifx arguments[0]=="644" then cast(u32)420 else cast(u32)493
okay:=ModeRaw(fd,mode)==0; closed:=CloseRaw(fd)==0
if !okay || !closed { Fail("cannot normalize output mode"); return 1 }; return 0
}
Config :: (arguments: []string,out: *J.JsonDocument) -> bool {
out.root=J.JsonNewObject(out)
for argument: arguments { split: s64; while split<argument.count && argument[split]!=61 { split+=1 }; if split==argument.count { Fail("codec input needs key=value"); return false }; unused J.JsonSetCopy(out,out.root,argument[0:split],J.JsonNewStringCopy(out,argument[split+1:argument.count])) }
return true
}
Value :: (doc: *J.JsonDocument,key: string) -> Text { return J.JsonString(doc,J.JsonMember(doc,doc.root,key)) }
Configure :: (build: string,inputs: *J.JsonDocument) -> Text {
if !Fs.CreateDirectories(build) { Fail("cannot create codec build directory"); return .{} }
stamp: Text=Fs.JoinPath(build,"kryon-config.json"); contents: Text=J.JsonWrite(inputs,inputs.root,J.JsonPythonStyle(2,true,true)); text: Vec(u8); BuilderPrint(*text,"%\n",TextView(contents))
cache: Text=Fs.JoinPath(build,"CMakeCache.txt"); old: Vec(u8); okay:=Whole.ReadFileInto(TextView(stamp),*old); changed:=!okay || TextView(old[:])!=TextView(text[:])
source: Text=Value(inputs,"source"); home: Vec(u8); BuilderPrint(*home,"CMAKE_HOME_DIRECTORY:INTERNAL=%",TextView(source))
cache_text: Vec(u8); read:=Whole.ReadFileInto(TextView(cache),*cache_text)
if read { matches:=false; start: s64; raw:=TextView(cache_text[:]); for i: 0..raw.count { if i==raw.count || raw[i]==10 || raw[i]==13 { if raw[start:i]==TextView(home[:]) { matches=true }; start=i+1 } }; if !matches { changed=true } }
if changed {
if Fs.IsFile(TextView(cache)) && !File.RemoveFile(TextView(cache)) { Fail("cannot reset codec CMake cache"); return .{} }
cmake_files: Text=Fs.JoinPath(build,"CMakeFiles"); unused Fs.RemoveTree(TextView(cmake_files))
if !Whole.WriteEntireFile(TextView(stamp),TextView(text[:])) { Fail("cannot write codec configuration"); return .{} }
}
return stamp
}
Later :: (left: Fs.PathInfo,right: Fs.PathInfo) -> bool { return left.modified>right.modified || (left.modified==right.modified && left.modified_nanoseconds>right.modified_nanoseconds) }
Publish :: (source: string,target: string) -> bool {
parent:=Fs.PathParent(target); if !Fs.CreateDirectories(parent) { Fail("cannot create codec output directory"); return false }
temp: Text=Fs.CreateTemporaryDirectory(parent,".kryon-codec-"); if temp.bytes.count==0 { Fail("cannot create codec publication scratch"); return false }; defer { unused Fs.RemoveTree(TextView(temp)) }
input: Text=Fs.ResolvePath(source); staged: Text=Fs.JoinPath(TextView(temp),"library")
if input.bytes.count==0 || !Fs.CopyFileNew(TextView(input),TextView(staged)) || !File.RenamePath(TextView(staged),target) { Fail("cannot publish complete codec library"); return false }; return true
}
Avif :: (arguments: []string) -> s32 {
if arguments.count<1 { Fail("AVIF build directory required"); return 2 }
build:=arguments[0]; jobs: string; archive: string; aom_archive: string; shared: string; decode: bool
inputs: Vec(string); config: Vec(string); defer FreeNames(*inputs); defer FreeNames(*config)
at: s64=1
while at<arguments.count {
arg:=arguments[at]; at+=1
if arg=="--decode-only" { decode=true; continue }
if arg=="--jobs" || arg=="--archive" || arg=="--aom-archive" || arg=="--shared-library" || arg=="--input" {
if at==arguments.count { Fail("AVIF option needs a value"); return 2 }; value:=arguments[at]; at+=1
if arg=="--jobs" { jobs=value } else if arg=="--archive" { archive=value } else if arg=="--aom-archive" { aom_archive=value } else if arg=="--shared-library" { shared=value } else { VecPush(inputs,Own(value)) }
} else { VecPush(config,Own(arg)) }
}
if jobs=="" || archive=="" || decode==(aom_archive!="") { Fail("AVIF needs jobs, archive and either decode-only or aom-archive"); return 2 }
doc: J.JsonDocument; defer J.JsonReset(*doc); if !Config(config[:],*doc) { return 2 }
if !Fs.CreateDirectories(build) { Fail("cannot create AVIF build directory"); return 1 }
lock_path: Text=Fs.JoinPath(build,"kryon-build.lock"); lock:=Fs.LockPath(TextView(lock_path)); if lock<0 { Fail("cannot lock AVIF build directory"); return 1 }; defer Fs.UnlockPath(lock)
cmake_build: Text=Fs.JoinPath(build,"cmake-build"); stamp: Text=Configure(TextView(cmake_build),*doc); if failed { return 1 }
latest:=Fs.PathStatus(TextView(stamp))
for input: inputs[:] { info:=Fs.PathStatus(input); if info.kind==.Missing { Fail("missing AVIF build input"); return 1 }; if Later(info,latest) { latest=info } }
outputs:=string.[archive,aom_archive,shared]; fresh:=true
for output: outputs { if output!="" { info:=Fs.PathStatus(output); if info.kind!=.File || info.size==0 { fresh=false } } }
done: Text=Fs.JoinPath(build,"kryon-built"); done_info:=Fs.PathStatus(TextView(done))
if fresh && done_info.kind==.File && !Later(latest,done_info) { return 0 }
if done_info.kind!=.Missing && !File.RemoveFile(TextView(done)) { Fail("cannot invalidate AVIF completion stamp"); return 1 }
source: Text=Value(*doc,"source"); avif: Text=Value(*doc,"avif"); aom: Text=Value(*doc,"aom"); dav1d: Text=Value(*doc,"dav1d"); package: Text=Value(*doc,"package"); compiler: Text=Value(*doc,"compiler")
definitions: Vec(string); defer FreeNames(*definitions)
names:=string.["AVIF_DIR","DAV1D_DIR","KRYON_AVIF_PACKAGE_DIR","CMAKE_C_COMPILER"]
values:=string.[TextView(avif),TextView(dav1d),TextView(package),TextView(compiler)]
for i: 0..3 { value: Vec(u8); BuilderPrint(*value,"-D%=%",names[i],values[i]); VecPush(definitions,Own(TextView(value[:]))) }
aom_flag: Vec(u8); if decode { BuilderAppend(aom_flag,"-DDECODE_ONLY=ON") } else { BuilderPrint(*aom_flag,"-DAOM_DIR=%",TextView(aom)) }
command:=string.["cmake","-S",TextView(source),"-B",TextView(cmake_build),definitions[0],TextView(aom_flag[:]),definitions[1],definitions[2],"-DCMAKE_POLICY_VERSION_MINIMUM=3.5","-DCMAKE_BUILD_TYPE=Release",definitions[3]]
if !Run(command[:]) { return 1 }
target: Vec(string); VecPush(target,"cmake"); VecPush(target,"--build"); VecPush(target,TextView(cmake_build)); VecPush(target,"--target"); VecPush(target,"avif_static"); if shared!="" { VecPush(target,"kryonavif") }; VecPush(target,"--parallel"); VecPush(target,jobs)
if !Run(target[:]) { return 1 }
paths:=string.["avif/libavif.a","aom/libaom.a","libkryonavif.so"]
for i: 0..2 { if outputs[i]!="" { input: Text=Fs.JoinPath(TextView(cmake_build),paths[i]); if !Publish(TextView(input),outputs[i]) { return 1 } } }
if !Whole.WriteEntireFile(TextView(done),"") { Fail("cannot finish AVIF build stamp"); return 1 }; return 0
}
main :: (argc: s32,argv: **u8) -> s32 {
words: Vec(string); for i: 1..argc-1 { VecPush(words,Args.TextFromCString(argv[i])) }
if words.count==0 { Fail("expected module-inputs, mode, codec-config or avif-build"); return 2 }
command:=words[0]; arguments:=words[1:words.count]
if command=="module-inputs" { return ModuleInputs(arguments) }
if command=="mode" { return SetMode(arguments) }
if command=="codec-config" {
if arguments.count<1 { Fail("codec build directory required"); return 2 }
doc: J.JsonDocument; defer J.JsonReset(*doc); if !Config(arguments[1:arguments.count],*doc) { return 2 }; unused Configure(arguments[0],*doc); return ifx failed then 1 else 0
}
if command=="avif-build" { return Avif(arguments) }
Fail("unknown native build helper"); return 2
}