diff --color -urN a/build-aux/luke b/build-aux/luke --- a/build-aux/luke +++ b/build-aux/luke @@ -0,0 +1,946 @@ +#!/usr/bin/env lua +--[[ minified code follows, see --help text for source location! ]] +local require=function(modname)if package.loaded[modname]==nil then +if type(package.preload[modname])~="function"then +io.stderr:write("module '" .. modname .. "' not found:\n no valid field package.preload['" .. modname .. "']\n") +return nil +end +package.loaded[modname]=package.preload[modname](modname,"package.preload")end +return package.loaded[modname]end +package.preload['luke._base']=function() +local _ENV=require'luke.normalize'{}local function fatal(...)local msg=(...)if select('#',...)>1 then +msg=format(...)end +stdout:flush()stderr:write('luke: fatal: '..msg..'\n')exit(1)end +return{diagnose=function(predicate,...)if not predicate then +fatal(...)end +end,fatal=fatal,} +end +package.preload['luke.cli']=function() +local _ENV=require'luke.normalize'{'luke._base','luke.compile','luke.lukefile','luke.platforms','luke.functional','luke.version','type.context-manager',}local function version()print(versiontext)exit(0)end +local function help()print[[ +Usage: luke [OPTION]... [VAR=VALUE]... [TARGET] + +Use the source, Luke! + + --help print this help, then exit + --version print version number, then exit + --dry-run print the commands, without running them + --file=FILE use FILE instead of lukefile + --value=NAME print the value of variable NAME + --quiet without any output + --verbose provide more progress output + +Each TARGET can be one of the module table keys from lukefile, or: + + all build all targets in lukefile + install copy all built targets to $PREFIX + release cut a release of the version given by version=VERSION + +If no TARGET is given, 'all' is implied. + +Report bugs to https://github.com/gvvaughan/luke/issues.]]exit(0)end +local progname=arg[0]local function opterr(...)local msg=(...)if select('#',...)>1 then +msg=format(...)end +msg=gsub(msg,'%.$','')stderr:write('luke: error: '..msg..'.\n')stderr:write("luke: try '"..progname.." --help' for help.\n")exit(2)end +local function display(...)return stdout:write(concat{...})end +local function dump(...)local s=concat(map(list(...),str))if len(s)>0 then +gsub(concat(map(list(...),str)),'\n*$','\n'):gsub('(.-)\n',function(line)stderr:write(' DEBUG: '..line..'\n')end)end +end +local function interpolate_to_substitute(s)return(gsub(s,'%$([%w_]+)','@%1@'))end +local function gitref()local out=slurp(Pipe('git rev-parse --short HEAD 2>/dev/null'))return match(out or'','^(%x+)\n?$')or''end +local function abs_top_srcdir()return(gsub(slurp(Pipe('pwd'))or'','\n$',''))end +return{parse_arguments=function(args)local r={clidefs={},debug=false,dryrun=false,valreqs={},fname='lukefile',install={},log=nop,spawn=spawn,targets={},verbose=nop,write=display,}map(args,function(opt)case(opt,{['--debug']=function()r.debug=true +r.log=dump +end,['--dry-run']=function()r.dryrun=true +r.spawn=function()return 0,'',''end +end,['%-%-file=(.+)']=function(optarg)r.fname=optarg +end,['%-%-value=(.+)']=function(optarg)r.valreqs[#r.valreqs+1]=optarg +end,['--quiet']=function()r.write=nop +end,['--verbose']=function()r.verbose=display +end,['--help']=help,['--version']=version,['([^-][^=]-)=(.+)']=function(name,value)r.clidefs[name]=value +end,function(opt)if match(opt,'^-')~=nil then +opterr("unrecognized option '%s'",opt)end +append(r.targets,opt)end,})end)return r +end,validate_arguments=function(parsed)local luke,err=loadluke(parsed.fname)diagnose(luke~=nil,'bad %s: %s',parsed.fname,err)if isempty(luke.modules or{})then +fatal("no modules table in '%s', nothing to build",parsed.fname)end +map({'package','version'},function(key)diagnose(luke[key]~=nil,"no %s in '%s'",key,parsed.fname)end)local release +if contains(parsed.targets,'release')then +if len(parsed.targets)>1 then +fatal('release cannot be combined with other targets')end +release=parsed.clidefs.version +diagnose(release~=nil,'release needs a version=VERSION argument')case(release,{['%d+']=nop,['%d+%.%d+']=nop,['%d+%.%d+%.%d+']=nop,function()fatal("bad release version '%s': X, X.Y or X.Y.Z expected",release)end,})parsed.targets={}end +local sections=script_sections(luke)local installbin=sections.install +local rulesets={luke.modules,sections.bin,sections.files,installbin}local function hasrule(target)return target=='install'or any(map(rulesets,function(rules)return ordered_get(rules,target)~=nil +end))end +local targets=call(function()if isempty(parsed.targets)or contains(parsed.targets,'all')then +return except(flatten(parsed.targets,map(rulesets,ordered_keys)),'all')end +local unknown=except(parsed.targets,hasrule)diagnose(isempty(unknown),"no rule to make target '%s'",unknown[1])assert(len(parsed.targets)>0,"no build targets specified")return parsed.targets +end)local named=except(targets,'install')local build=ordered_pluck(named,luke.modules)local scripts={build=reduce(SCRIPT_SECTIONS,list(),function(entries,section)return reduce(ordered_keys(ordered_pluck(named,sections[section])),entries,function(entries,name)return append(entries,{name=name,section=section})end)end),install={},}local install +if contains(targets,'install')then +if isempty(named)then +install,scripts.install=luke.modules,ordered_keys(installbin)else +install,scripts.install=build,ordered_keys(ordered_pluck(named,installbin))end +end +luke.modules=build +local ref,srcdir=gitref(),abs_top_srcdir()luke.substitute=merge(luke.substitute or{},{abs_top_srcdir=srcdir,gitref=ref,package=interpolate_to_substitute(luke.package),version=interpolate_to_substitute(luke.version),})luke.variables=merge(luke.variables or{},collect_variables(luke),{LUA_DIR='/usr',LUA_BINDIR='$LUA_DIR/bin',LUA_INCDIR='$LUA_DIR/include/lua$LUAVERSION',LUA_LIBDIR='$LUA_DIR/lib',abs_top_srcdir=srcdir,gitref=ref,objdir=platforms[1],package=luke.package,version=luke.version,})return{clidefs=parsed.clidefs,debug=parsed.debug,dryrun=parsed.dryrun,filled={},install=install,log=parsed.log,luke=luke,release=release,scripts=scripts,spawn=parsed.spawn,valreqs=parsed.valreqs,verbose=parsed.verbose,write=parsed.write,}end,} +end +package.preload['luke.compile']=function() +local _ENV=require'luke.normalize'{'luke._base','luke.environment','luke.functional','type.context-manager','type.path',}local function spawn(env,...)local command=interpolate(env,concat({...},' '))return with(TmpFile(),TmpFile(),function(out,err)local pipe=concat{'{ ',command,'\n} >',out.filename,' 2>',err.filename,'; printf $?'}return tonumber(slurp(Pipe(pipe))),slurp(File(err.filename)),slurp(File(out.filename))end)end +local function run(L,env,command)L.write(interpolate(env,concat(command,' ')),'\n')local status,err,out=L.spawn(env,unpack(command))if status~=0 then +if L.write==nop then +stdout:write(concat(command,' ')..'\n')end +stderr:write(err..'\n')end +return status,out,err +end +local function defines(...)return map(ordered_merge(...),function(definition)local name,value=destructure(definition)local fmt=cond({[int(value)==1]='-D%s'},{[true]='-D%s=%s'})return format(fmt,name,shellword(value))end)end +local function incdirs(...)return map(flatten(...),function(v)return'-I'..v +end)end +local function libdirs(...)return map(flatten(...),function(v)return'-L'..v +end)end +local function c_module_path(objdir,name)return format('%s/%s.$LIB_EXTENSION',objdir,gsub(name,'%.','/'))end +local function c_source(module,objdir)local path=gsub(module,'%.','/')local src=c_module_path(objdir,path)return src,(gsub('$INST_LIBDIR/'..path,'/[^/]+$',''))end +local function lua_source(module,src)local abspath='$INST_LUADIR/'..gsub(module,'%.','/')if match(src,'/init%.lua$')then +abspath=abspath..'/init'end +abspath=abspath..'.lua'return src,(gsub(abspath,'/[^/]+%.lua$',''))end +local function script_target(name,rules,objdir,installed)if isstring(rules)then +return(gsub(rules,'%.in$',''))elseif installed then +return format('%s/%s',objdir,name)end +return name +end +local function c_sources(sources)return dropuntil(sources,bind(match,{[2]='%.[ch]$'}))end +local function module_to_path(module,sources,objdir)return dropuntil(sources,function(source)return case(source,{['.*%.[ch]']=bind(c_source,{module,objdir}),['(.*%.[ch])%.in']=bind(c_source,{module,objdir}),['.*%.lua']=bind(lua_source,{module}),['(.*%.lua)%.in']=bind(lua_source,{module}),function(src)fatal("unsupported source type '%s'",src)end,})end)end +return{build_c_module=function(L,env,luke,name)local rules=ordered_get(luke.modules,name)local c_module=c_module_path(luke.variables.objdir,name)local command={'$MAKEDIRS',dirname(c_module)}local status,err,out=L.spawn(env,unpack(command))if status~=0 then +stdout:write(concat(command,' ')..'\n')stderr:write(err..'\n')exit(status)end +return run(L,env,flatten('$CC $CFLAGS $LIBFLAG $PKGFLAGS $CPPFLAGS',defines(luke.defines,rules.defines),incdirs(rules.incdirs,luke.incdirs),rules.sources,'-o',c_module,'$LDFLAGS',libdirs(rules.libdirs,luke.libdirs),'$LIBS',rules.libraries,luke.libraries))end,c_modules=function(modules)return filter(ordered_keys(modules),function(name)return dropuntil(ordered_get(modules,name).sources,bind(match,{[2]='%.[ch]$'}))end)end,defines=defines,incdirs=incdirs,install_modules=function(L,env,luke,modules)return reduce(ordered_keys(modules),0,function(status,name)if status==0 then +local src,dir=module_to_path(name,ordered_get(modules,name).sources,luke.variables.objdir)if not exists(interpolate(env,dir))then +status=run(L,env,{'$MAKEDIRS',dir})end +if status==0 then +status=run(L,env,{'$INSTALL',src,dir..'/'})end +end +return status +end)end,build_program=function(L,env,luke,rules,target,sources)if match(target,'/')then +local command={'$MAKEDIRS',dirname(target)}local status,err=L.spawn(env,unpack(command))if status~=0 then +stdout:write(concat(command,' ')..'\n')stderr:write(err..'\n')return status +end +end +if rules.command~=nil then +local names=sorted(keys(rules.env))env=mkenv({sources=concat(sources,' '),target=target},rules.env,env)local exports={}if not isempty(names)then +exports=flatten('export',map(names,function(name)return format('%s=%s',name,shellword(interpolate(env,rules.env[name])))end),';')end +return run(L,env,flatten(exports,rules.command))end +if c_sources(sources)==nil then +fatal("no command to build '%s' from %s",target,concat(sources,' '))end +return run(L,env,flatten('$CC $CFLAGS $CPPFLAGS',defines(luke.defines,rules.defines),incdirs(rules.incdirs,luke.incdirs),sources,'-o',target,'$LDFLAGS',libdirs(rules.libdirs,luke.libdirs),'$LIBS',rules.libraries,luke.libraries))end,c_program=function(rules)return istable(rules)and rules.command==nil and c_sources(rules.sources)~=nil +end,install_scripts=function(L,env,luke,names)if isempty(names)then +return 0 +end +local status=0 +if not exists(interpolate(env,'$INST_BINDIR'))then +status=run(L,env,{'$MAKEDIRS','$INST_BINDIR'})end +return reduce(names,status,function(status,name)local rules=ordered_get(luke.install.bin,name)local src=script_target(name,rules,luke.variables.objdir,true)local dest='$INST_BINDIR/'..name +if status==0 then +status=run(L,env,{'$INSTALL',src,dest})end +if status==0 then +status=run(L,env,{'$CHMOD','+x',dest})end +return status +end)end,libdirs=libdirs,make_executable=function(L,env,path)return run(L,env,{'$CHMOD','+x',path})end,run_command=run,script_target=script_target,spawn=spawn,} +end +package.preload['luke.configure']=function() +local _ENV=require'luke.normalize'{'luke._base','luke.compile','luke.environment','luke.functional','type.context-manager','type.dict',CCPROGS={'cc','gcc','clang'},}local function logspawn(L,env,filename,...)local status,err=spawn(env,...)if status~=0 and err~=''then +with(File(filename,'r'),function(h)L.log(h.filename..':')L.log(slurp(h))end)L.log(err)end +return status +end +local function Conftest(L)local cm=CTest(L.debug)if L.debug and cm~=nil then +L.log('keeping '..cm.filename..' and '..cm.objfile)end +return cm +end +local function checking(L,...)L.verbose('checking ',concat({...},' '),'... ')end +local function found_library(L,x)if x==nil or x==''then +L.verbose'none required'elseif isempty(x)then +L.verbose'not supported'else +L.verbose(x)end +L.verbose'\n'return x +end +local function found_prog(L,x)L.verbose(x and'yes\n'or'no\n')return x +end +local function found_result(L,x)L.verbose(x==0 and'yes\n'or'no\n')return x~=0 and 0 or 1 +end +local function bindirs(...)return map(flatten(...),function(v)return v..':'end)end +local function compile_command(L,env,config,objfile,filename)local command=flatten('$CC','-c','$CFLAGS',defines(L.luke.defines),incdirs(config.incdir),'$CPPFLAGS','-o',objfile,filename)L.log(interpolate(env,concat(command,' ')))return unpack(command)end +local function link_command(L,env,config,a_out,source,lib)local command=flatten('$CC','$CFLAGS',defines(L.luke.defines),incdirs(config.incdir),'$CPPFLAGS','-o',a_out,source,libdirs(config.libdir),'$LDFLAGS',lib,'$libs',CONFIGENV.libs)L.log(interpolate(env,concat(command,' ')))return unpack(command)end +local function check_executable_in_path(L,env,config,prog)local PATH=concat(bindirs(config.bindir))..getenv('PATH')local found=dropuntil(gmatch(PATH,'[^:]+'),function(path)local progpath=path..'/'..prog +return with(File(progpath,'r'),function(h)return h and isfile(h.context)and progpath or nil +end)end)L.log(found and'found '..found or prog..' not found')return found~=nil +end +local function check_header_compile(L,env,config,header,extra_hdrs)return with(Conftest(L),function(conftest)conftest:write(format('%s\n#include "%s"\n',extra_hdrs,header))conftest:flush()return logspawn(L,env,conftest.filename,compile_command(L,env,config,conftest.objfile,conftest.filename))end)end +local function check_struct_member_compile(L,env,config,structname,member,extra_hdrs)return with(Conftest(L),function(conftest)conftest:write(format([[ +%s +int main () { +static %s aggr; +if (sizeof aggr.%s) + return 0; +return 0; +} +]],extra_hdrs,structname,member))conftest:flush()return logspawn(L,env,conftest.filename,compile_command(L,env,config,conftest.objfile,conftest.filename))end)end +local function try_link(L,env,config,lib,symbol)return with(Conftest(L),TmpFile(),function(conftest,a_out)conftest:write(format([[ +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +char %s (); +int main () { +return %s (); +} +]],symbol,symbol))conftest:flush()return logspawn(L,env,conftest.filename,link_command(L,env,config,a_out.filename,conftest.filename,lib))end)end +local function try_compile(L,env,config,headers)return with(Conftest(L),TmpFile(),function(conftest,a_out)conftest:write(format([[ +%s +#if !defined %s || %s == -1 +choke me +#endif +int +main() +{ +return 0; +} +]],headers,config.ifdef,config.ifdef))conftest:flush()return logspawn(L,env,conftest.filename,link_command(L,env,config,a_out.filename,conftest.filename))end)end +local function check_func_decl(L,env,config,fname,extra_hdrs)return with(Conftest(L),function(conftest)conftest:write(format([[ +%s +int +main() +{ +#ifndef %s +(void) %s; +#endif +return 0; +} +]],extra_hdrs,fname,fname))conftest:flush()return logspawn(L,env,conftest.filename,compile_command(L,env,config,conftest.objfile,conftest.filename))end)end +local function check_func_link(L,env,config,fname)return with(Conftest(L),TmpFile(),function(conftest,a_out)conftest:write(format([[ +/* Define to an innocous variant, in case declares it. + For example, HP-UX 11i declares gettimeofday. */ +#define %s innocuous_%s + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with declaration below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef %s + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +char %s (); + +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_%s || defined __stub__%s +choke me +#endif + +int main () { +return %s (); +} +]],fname,fname,fname,fname,fname,fname,fname))conftest:flush()return logspawn(L,env,conftest.filename,link_command(L,env,config,a_out.filename,conftest.filename))end)end +local function add_external_deps(env,config,prefix)if prefix~=nil then +for k,v in next,{bindir='$%s_BINDIR',incdir='$%s_INCDIR',libdir='$%s_LIBDIR'}do +local envvar=interpolate(env,format(v,prefix))if envvar~=''then +config[k]=envvar +end +end +end +end +local function format_includes(includes)return map(includes or{},function(include)return format('#include "%s"',include)end)end +local configure=setmetatable(OrderedDict({checkprog=function(L,env,config)return dropuntil(config.progs,function(prog)checking(L,'for',prog)if found_prog(L,check_executable_in_path(L,env,config,prog))then +return prog +end +end)or fatal('cannot find '..config.checkprog)end},{checkheader=function(L,env,config)checking(L,'for',config.checkheader)local extra_hdrs=concat(format_includes(config.includes),'\n')return found_result(L,check_header_compile(L,env,config,config.checkheader,extra_hdrs))end},{checkdecl=function(L,env,config)checking(L,'whether',config.checkdecl,'is declared')local extra_hdrs=concat(format_includes(config.includes),'\n')return found_result(L,check_func_decl(L,env,config,config.checkdecl,extra_hdrs))end},{checksymbol=function(L,env,config)checking(L,'for library containing',config.checksymbol)if config.ifdef~=nil then +local headers=concat(format_includes(config.includes),'\n')if try_compile(L,env,config,headers)~=0 then +return found_library(L,{})end +end +local libraries,symbol=config.libraries,config.checksymbol +local trylibs=reduce(libraries,{''},function(r,lib)append(r,'-l'..lib)end)return dropuntil(trylibs,function(lib)if try_link(L,env,config,lib,symbol)==0 then +if lib~=''then +if CONFIGENV.libs~=''then +CONFIGENV.libs=' '..CONFIGENV.libs +end +CONFIGENV.libs=lib..CONFIGENV.libs +end +return found_library(L,lib)end +end)or call(function()L.verbose'\n'fatal("required symbol '%s' not found in any of libc, lib%s",symbol,concat(libraries,', lib'))end)end},{checkfunc=function(L,env,config)checking(L,'for',config.checkfunc)return found_result(L,check_func_link(L,env,config,config.checkfunc))end},{checkmember=function(L,env,config)checking(L,'for',config.checkmember)local extra_hdrs=concat(format_includes(config.includes),'\n')local i=find(config.checkmember,'%.')local structname=sub(config.checkmember,1,i-1)local member=sub(config.checkmember,i+1)return found_result(L,check_struct_member_compile(L,env,config,structname,member,extra_hdrs))end}),{__call=function(self,L,env,config,prefix)return case(type(config),{['number']=function()return str(config)end,['string']=function()return config +end,['table']=function()return dropuntil(self,function(fname)if config[fname]~=nil then +add_external_deps(env,config,prefix)return apply(self[fname],list(L,env,config))end +end)or fatal("unable to configure with keys '%s'",concat(keys(config),"', '"))end,function(type)fatal("unsupported configure type '%s'",type)end,})end,})return{config_compiler=function(L,env)local CC=env.CC +if CC==nil then +CC=configure(L,env,{checkprog='C compiler',progs=CCPROGS})env=mkenv(env,{CC=CC})end +checking(L,interpolate(env,'whether $CC works'))local cm=Conftest(L)local works,err=with(cm,function(conftest)conftest:write('typedef int x;\n')conftest:flush()return spawn(env,'$compile','-o',conftest.objfile,conftest.filename)end)if works~=0 then +L.verbose'no\n'L.log(interpolate(env,'$compile -o '..cm.objfile..' '..cm.filename))if err and err~=''then +L.log(err)end +fatal('could not find a working C compiler')end +found_prog(L,CC)return env +end,config_ldoc=function(L,env)local LDOC=env.LDOC +if LDOC==nil then +LDOC=configure(L,env,{checkprog='LDocs generator',progs={'ldoc','true'}})env=mkenv(env,{LDOC=LDOC})end +return env +end,configure=configure,} +end +package.preload['luke.environment']=function() +local _ENV=require'luke.normalize'{'luke.platforms','luke.functional',LUAVERSION=string.gsub(_VERSION,'[^0-9%.]+',''),SHELLMETACHARS='[%s%$"\'&;|<>()*?`\\]',}local env_mt={__index=function(self,varname)return dropuntil(self,function(env)local value=env[varname]if value~=nil then +self[varname]=value +return value +end +end)end,}local function interpolate_with(pattern,env,s)local r=''while r~=s do +r=s +s=gsub(r,pattern,function(varname)return env[varname]or''end)end +return r +end +local function isenv(t)return getmetatable(t)==env_mt +end +return{CONFIGENV={compile='$CC -c $CFLAGS $CPPFLAGS',libs='',link='$CC $CFLAGS $CPPFLAGS $LDFLAGS',},DEFAULTENV=filter_platforms{LUA='lua',LUAVERSION=LUAVERSION,PREFIX='/usr/local',INST_BINDIR='$PREFIX/bin',INST_LIBDIR='$PREFIX/lib/lua/$LUAVERSION',INST_LUADIR='$PREFIX/share/lua/$LUAVERSION',LIB_EXTENSION='so',OBJ_EXTENSION='o',CHMOD='chmod',INSTALL='cp',MAKEDIRS='mkdir -p',CFLAGS='-O2',platforms={macosx={LIBFLAG='-fPIC -bundle -undefined dynamic_lookup -all_load',},LIBFLAG='-shared -fPIC',},},SHELLENV=setmetatable({},{__index=function(_,v)return getenv(v)end,}),expand=bind(interpolate_with,{'@([%w_]+)@'}),interpolate=bind(interpolate_with,{'%$([%w_]+)'}),shellword=function(s)return choose(match(s,SHELLMETACHARS)~=nil,function()return"'"..gsub(s,"'",[['\'']]).."'"end,s)end,mkenv=function(...)local env=reduce(except(list(...),nil),function(r,t)if isenv(t)then +map(t,bind(append,{r}))else +append(r,t)end +end)return setmetatable(env,env_mt)end,} +end +package.preload['luke.functional']=function() +local _ENV=require'luke.normalize'{destructure=next,isfile=function(x)return io.type(x)=='file'end,wrap=coroutine.wrap,yield=coroutine.yield,}local function apply(fn,argu)assert(fn~=nil,'cannot apply nil-valued function')if iscallable(fn)then +return fn(unpack(argu))end +return fn +end +local function call(fn,...)assert(fn~=nil,'cannot call nil-valued function')if iscallable(fn)then +return fn(...)end +return fn +end +local function wrapnonnil(iterator)return function(...)local r=list(iterator(...))if r[1]~=nil then +return r +end +end +end +local function each(seq)if type(seq)=='function'then +return wrapnonnil(seq)end +local i,n=0,int(seq.n)or len(seq)return function()if i=i and n or i-1 +return apply(fn,argu)end +end,call=call,choose=function(test,consequent,alternative)local leg=alternative +if test then +leg=consequent +end +if leg~=nil then +return call(leg,test)end +end,case=function(s,branches)if branches[s]~=nil then +return call(branches[s],s)end +local DEFAULT=1 +for pattern,fn in next,branches do +if s~=nil and pattern~=DEFAULT then +local argu=list(match(s,'^'..pattern..'$'))if argu[1]~=nil then +return apply(fn,argu)end +end +end +local default=branches[DEFAULT]if iscallable(default)then +return call(default,s)end +return default +end,cond=function(...)for clauseu in each(list(...))do +local expr,consequence=destructure(unpack(clauseu))if expr then +return call(consequence,expr)end +end +end,contains=function(seq,predicate)if type(predicate)~='function'then +predicate=eq(predicate)end +for valu in each(seq)do +if predicate(unpack(valu))then +return true +end +end +end,destructure=destructure,dropuntil=function(seq,predicate,block)if block==nil then +predicate,block=isnonnil,predicate +end +if block~=nil then +for valu in each(seq)do +local r=list(block(unpack(valu)))if predicate(unpack(r))then +return unpack(r)end +end +else +for r in each(seq)do +if predicate(unpack(r))then +return unpack(r)end +end +end +end,except=except,filter=function(seq,predicate)predicate=mkpredicate(predicate)local r={}for valu in each(seq)do +if predicate(unpack(valu))then +r[#r+1]=unpack(valu)end +end +return r +end,flatten=flatten,foldkeys=function(keymap,dict,combinator)local r={}for k,v in next,dict or{}do +local key=keymap[k]if key then +r[key]=combinator(v,dict[key])else +r[k]=r[k]or v +end +end +return r +end,get=function(dict,key)return(dict or{})[key]end,hoist=function(keylist,dict)local r={}for keyu in each(keylist)do +merge(r,dict[unpack(keyu)])end +return next(r)and r or nil +end,id=function(...)return...end,isempty=function(x)if type(x)~='table'then +return false +end +local k=next(x)return k==nil or(k=='n'and x.n==0 and next(x,k)==nil)end,isfile=isfile,isfunction=function(x)return type(x)=='function'end,islistkey=function(t,k)return type(k)=='number'and int(k)==k and k>=1 and k<=len(t)end,isnil=function(x)return x==nil +end,isstring=function(x)return type(x)=='string'end,istable=function(x)return type(x)=='table'end,isnonzero=function(x)return x~=0 +end,keys=keys,map=function(seq,block)local r=list()for valu in each(seq)do +append(r,block(unpack(valu)))end +return r +end,mapvalues=function(iterable,block)local r={}for k,v in next,iterable or{}do +r[k]=block(v)or v +end +return r +end,nop=function()end,ordered_merge=function(...)local at={}return reduce(except(list(...),nil),{},function(r,pairs)reduce(pairs,r,function(r,pair)local k,v=destructure(pair)at[k]=at[k]or#r+1 +r[at[k]]={[k]=v}end)end)end,ordered_get=function(om,key)return reduce(om or{},nil,function(_,pair)return pair[key]end)end,ordered_keys=function(om)return reduce(om or{},list(),function(r,pair)return append(r,(destructure(pair)))end)end,ordered_mapvalues=function(om,fn)return reduce(om or{},{},function(r,pair)local k,v=destructure(pair)r[#r+1]={[k]=fn(v)}end)end,ordered_pluck=function(keylist,om)local wanted=reduce(keylist,{},function(r,k)r[k]=true +end)return except(om or{},function(pair)return not wanted[(destructure(pair))]end)end,partition=function(seq,block)local r,s=list(),list()for valu in each(seq)do +append(block(unpack(valu))and r or s,unpack(valu))end +return r,s +end,pluck=function(keylist,dict)local r={}for keyu in each(keylist)do +local key=unpack(keyu)r[key]=dict[key]end +return next(r)and r or nil +end,reduce=reduce,reversed=function(seq)return reduce(seq,{},function(r,v)return{v,unpack(r)}end)end,sorted_keys=function(iterable)local rank={number=1,string=2}local r=keys(iterable)sort(r,function(a,b)local ra,rb=rank[type(a)]or 3,rank[type(b)]or 3 +return ran then +n=i +end +end +return n +end,merge=function(r,...)local argu=pack(...)for i=1,argu.n do +for k,v in next,argu[i]or{}do +r[k]=r[k]or v +end +end +return r +end,next=next,open=io.open,pack=pack,pcall=pcall,pop=function(seq)local n,r=seq.n or len(seq)r,seq[n]=seq[n]if int(seq.n)and seq.n>0 then +seq.n=seq.n-1 +end +return r +end,popen=io.popen,print=print,rawget=rawget,rawset=rawset,rep=string.rep,rm=os.remove,select=select,setmetatable=setmetatable,sort=sort,stderr=io.stderr,stdout=io.stdout,str=str,sub=string.sub,tmpname=os.tmpname,tonumber=tonumber,type=type,unpack=function(seq,i,j)return unpack(seq,int(i)or 1,int(j)or int(seq.n)or len(seq))end,write=io.write,},{__call=function(self,env,level)local userenv,level=copy(self),level or 1 +for name,value in next,env do +if int(name)and type(value)=='string'then +for k,v in next,(require(value))do +userenv[k]=userenv[k]or v +end +else +userenv[name]=value +end +end +setfenv(level+1,userenv)return userenv +end,}) +end +package.preload['luke.platforms']=function() +local _ENV=require'luke.normalize'{'luke.functional',}local CANON={['AIX']=list('aix','unix'),['FreeBSD']=list('freebsd','bsd','unix'),['OpenBSD']=list('openbsd','bsd','unix'),['NetBSD']=list('netbsd','bsd','unix'),['Darwin']=list('macosx','bsd','unix'),['Linux']=list('linux','unix'),['SunOS']=list('solaris','unix'),['^CYGWIN']=list('cygwin','unix'),['^MSYS']=list('msys','cygwin','unix'),['^Windows']=list('win32','windows'),['^MINGW']=list('mingw32','win32','windows'),['^procnto']=list('qnx'),['QNX']=list('qnx'),['Haiku']=list('haiku','unix'),}local ALLPLATFORMS=reduce(values(CANON),function(acc,platforms)map(platforms,function(v)acc[v]=true +end)end)local function match_uname(canon,uname,x)return match(uname,x)and canon[x]end +local function toplatforms(canon,uname)local literalkeys,patternkeys=partition(keys(canon),function(k)return sub(k,1,1)~='^'end)return(pluck(literalkeys,canon)or{})[uname]or dropuntil(map(patternkeys,bind(match_uname,{canon,uname})))or list('unix')end +local supported=toplatforms(CANON,popen('uname -s'):read'*l')local function isplatform(x)return ALLPLATFORMS[x]~=nil +end +local function selected(platforms,supported,isplatform)local matches=map(filter(supported,bind(get,{platforms})),bind(get,{platforms}))return choose(isempty(matches),function()return{pluck(except(keys(platforms),isplatform),platforms)}end,function()return matches +end)end +local function layers(t,using,predicate)local supported,isplatform=using or supported,predicate or isplatform +local own=pluck(except(keys(t),'platforms'),t)or{}return{own,unpack(reversed(selected(t.platforms or{},supported,isplatform)))}end +local function filter_platforms(t,using,predicate,opaque)local supported,isplatform,opaque=using or supported,predicate or isplatform,opaque or{}local function narrow(v,k)return choose(opaque[k]or not istable(v),function()return v +end,function()return filter_platforms(v,supported,isplatform,opaque)end)end +local tables=map(layers(t,supported,isplatform),function(layer)return layer.platforms and narrow(layer)or layer +end)local r=reduce(tables,{},function(r,layer)map(layer,function(v)r[len(r)+1]=narrow(v)end)end)return reduce(reversed(tables),r,function(r,layer)map(filter(keys(layer),function(k)return not islistkey(layer,k)and r[k]==nil +end),function(k)r[k]=narrow(layer[k],k)end)end)end +return{filter_platforms=filter_platforms,isplatform=isplatform,layers=layers,platforms=supported,toplatforms=toplatforms,} +end +package.preload['luke.release']=function() +local _ENV=require'luke.normalize'{'luke._base','luke.compile','luke.configure','luke.environment','luke.functional','luke.lukefile','type.context-manager','type.path',date=os.date,}local PLACEHOLDER='\n(## [^\n]*%?%.%?[^\n]*\n)'local MODREV="^(local _MODREV, _SPECREV = ')[^']*(')"local DEVROCKSPEC='^(.-%-)dev(%-%d+%.rockspec)$'local function git(env,...)local status,err,out=spawn(env,'git',...)if status==0 then +return(gsub(out,'\n$',''))end +end +local function dependencies_installed(env,rockspec)local status,err,out=spawn(env,env.LUAROCKS or'luarocks','--lua-version=$LUAVERSION','make --only-deps --only-server=',shellword(rockspec))if status~=0 then +stderr:write(match(out or'','^(Missing dependencies.-)\n\n')or err or'','\n')end +return status==0 +end +local function has_placeholder(text)local header,body=match('\n'..text,'\n(## [^\n]*\n)(.*)')if header==nil or match('\n'..header,PLACEHOLDER)==nil then +return false +end +return match(match(body,'^(.-)\n## ')or body,'%S')~=nil +end +local function add_release_header(text,version,date)local header=format('## Noteworthy changes in release %s (%s) [stable]',version,date)return(gsub(text,PLACEHOLDER..'\n*','\n%1\n\n'..header..'\n\n',1))end +local function release_news(text,version)local header='\n(## Noteworthy changes in release '..gsub(version,'%p','%%%0')..' %(.*)'local news=match('\n'..text,header)if news~=nil then +return(gsub(match(news,'^(.-)\n## ')or news,'%s*$',''))end +end +local function rockspec_fields(text)local r={}local chunk=text and loadstring(text,'rockspec',r)if chunk==nil or not pcall(chunk)then +return{}end +return r +end +local function announcement(package,version,news,rockspec)local fields=rockspec_fields(rockspec)local description=istable(fields.description)and fields.description or{}package=isstring(fields.package)and fields.package or package +local lines=flatten(isstring(description.summary)and{description.summary,''}or{},format('I am happy to announce release %s of %s.',version,package),'',isstring(description.homepage)and{format("%s's home page is at %s",package,description.homepage),''}or{},news and{news,''}or{},rockspec and{'Install it with LuaRocks, using:','',format(' luarocks install %s %s',package,version)}or{})return package,match(concat(lines,'\n'),'^(.-)%s*$')..'\n'end +local function remove_placeholder(text)return(gsub(text,PLACEHOLDER..'\n?','\n',1))end +local function run(L,env,...)local command=concat({...},' ')L.write(interpolate(env,command),'\n')local status,err=L.spawn(env,command)if status~=0 then +stderr:write(err,'\n')end +return status +end +local function tag(L,env,version,notes)local filename=tmpname()with(File(filename,'w'),function(h)h:write(notes)end)local status=run(L,env,'git tag -a --cleanup=verbatim','v'..version,'-F',filename)rm(filename)return status +end +local function edit(L,path,fn,dest)dest=dest or path +L.write((dest==path and'updating 'or'creating ')..dest,'\n')if not L.dryrun then +local content=fn(slurp(File(path)))with(File(dest,'w'),function(h)h:write(content)end)end +return 0 +end +local function replace(text,substitute,pairs)return reduce(pairs,text,function(r,pair)local find,replacement=destructure(pair)return(gsub(r,(gsub(find,'%p','%%%0')),(gsub(expand(substitute,replacement),'%%','%%%%'))))end)end +local function rockspec_name(rockspec,version)return(gsub(rockspec,DEVROCKSPEC,'%1'..version..'%2'))end +local function set_modrev(text,version)return(gsub(text,MODREV,'%1'..version..'%2',1))end +local function copy_command(source,worktree,path,optional)local dest=worktree..'/'..path +local from,to=shellword(source),shellword(dest)local copy=format("git -C %s rm -r --quiet --ignore-unmatch -- %s ':(exclude)*.in'"..' && if test -d %s; then $MAKEDIRS %s && cp -R %s/. %s; else $MAKEDIRS %s && cp %s %s; fi',shellword(worktree),shellword(path),from,to,from,to,shellword(dirname(dest)),from,to)return choose(optional,format('if test -e %s; then %s; fi',from,copy),copy)end +local function publish_steps(L,env,substitute,worktree,copies)return flatten(map(copies,function(pair)local path,copy=destructure(pair)local source,optional=copy.source,copy.optional +local dest=worktree..'/'..path +local template=match(source,'%.in$')~=nil +return except(list(choose(optional or not template,function()return bind(run,{L,env,copy_command(source,worktree,path,optional)})end),choose(template,function()return bind(edit,{L,choose(optional,dest,source),bind(expand,{substitute}),(gsub(dest,'%.in$',''))})end)),nil)end),copies.command and bind(run,{L,env,'cd',worktree,'&&',copies.command}))end +local function preconditions(env,release,version,main,substitute)local branch,tag='release-v'..version,'v'..version +local name=choose(main~=nil,main,'a branch')local checkout=format('git checkout --force %s',name)local checks={{'the working tree is clean',function()return git(env,'status --porcelain')==''end,checkout},{format('%s is checked out',name),function()return main~=nil and git(env,'symbolic-ref --short HEAD')==main +end,checkout},{'origin can be fetched',function()return git(env,'fetch --quiet origin')~=nil +end},{format('%s is up to date with origin',name),function()return git(env,'rev-parse refs/heads/'..main)==git(env,'rev-parse origin/'..main)end,format('git reset --hard origin/%s',name)},{format('branch %s is unused',branch),function()return git(env,'rev-parse --verify --quiet refs/heads/'..branch)==nil +end,'git branch -D '..branch},{format('tag %s is unused',tag),function()return git(env,'rev-parse --verify --quiet refs/tags/'..tag)==nil +end,'git tag -d '..tag},}if release.news~=nil then +local news=slurp(File(release.news))append(checks,{format('%s has news under a placeholder header',release.news),function()return news~=nil and has_placeholder(news)end})append(checks,{format('%s has no %s release yet',release.news,version),function()return news~=nil and find(news,'release '..version..' (',1,true)==nil +end})end +map(release.replacements or{},function(entry)local path,pairs=destructure(entry)append(checks,{format('%s exists',path),function()return exists(path)end})reduce(pairs,{},function(before,pair)local text,earlier=destructure(pair),copy(before)append(checks,{format("%s contains '%s'",path,text),function()local content=slurp(File(path))return content~=nil and find(replace(content,substitute,earlier),text,1,true)~=nil +end})append(before,pair)end)end)map(branches(release),function(pages)local copies=release[pages]append(checks,{format('%s is not ahead of origin',pages),function()local ref,origin=git(env,'rev-parse refs/heads/'..pages),git(env,'rev-parse origin/'..pages)return origin~=nil and(ref==nil or ref==origin +or git(env,'merge-base --is-ancestor',ref,origin)~=nil)end,format('git branch -f %s origin/%s',pages,pages)})append(checks,{format('%s can be checked out in a new worktree',pages),function()local worktrees=git(env,'worktree list --porcelain')return worktrees~=nil +and find('\n'..worktrees..'\n','\nbranch refs/heads/'..pages..'\n',1,true)==nil +end})map(filter(ordered_keys(copies),function(path)return ordered_get(copies,path).optional and match(path,'%.in$')~=nil +end),function(template)append(checks,{format('%s or the release has %s',pages,template),function()return exists(template)or git(env,format('cat-file -e origin/%s:%s',pages,template))~=nil +end})end)end)if release.rockspec~=nil then +local rockspec=slurp(File(release.rockspec))append(checks,{format('%s is a development rockspec',release.rockspec),function()return match(release.rockspec,DEVROCKSPEC)~=nil +end})append(checks,{format('%s sets _MODREV on its first line',release.rockspec),function()return rockspec~=nil and match(rockspec,MODREV)~=nil +end})if release.check_dependencies then +append(checks,{format('the dependencies of %s are installed',release.rockspec),function()return dependencies_installed(env,release.rockspec)end})end +end +return checks +end +local function undo_commands(checks)return reduce(filter(checks,function(check)local _,predicate,undo=unpack(check)return undo~=nil and not predicate()end),{},function(r,check)choose(not contains(r,check[3]),bind(append,{r,check[3]}))end)end +local function generated(luke)local templates=map(luke.modules or{},function(pair)local _,rules=destructure(pair)return map(filter(rules.sources or{},function(source)return match(source,'%.in$')~=nil +end),function(source)return(gsub(source,'%.in$',''))end)end)return flatten(templates,map(ordered_keys(luke.files),function(name)return script_target(name,ordered_get(luke.files,name))end))end +local function ignoring(env,paths)local files={}local listed=git(env,'ls-files --others --ignored --exclude-standard --',unpack(map(paths,shellword)))for file in gmatch(listed or'','[^\n]+')do +append(files,shellword(file))end +local r={}if not isempty(files)then +local verbose=git(env,'check-ignore --no-index --verbose --',unpack(files))for source,n in gmatch(verbose or'','([^\n]-):(%d+):[^\n]*')do +if match(source,'^[^/]')and match(source,'^%.git/')==nil and match(source,'%.gitignore$')then +r[source]=r[source]or{}r[source][tonumber(n)]=true +end +end +end +return r +end +local function unignore(L,env,paths)repeat +local lines=ignoring(env,paths)local sources=sorted(keys(lines))map(sources,function(source)edit(L,source,function(text)local kept,n={},0 +for line in gmatch(text,'[^\n]*\n?')do +if line~=''then +n=n+1 +choose(not lines[source][n],bind(append,{kept,line}))end +end +return concat(kept)end)end)until L.dryrun or isempty(sources)return 0 +end +return{copy_command=copy_command,release=function(L,env,build)local version,main=L.release,git(env,'symbolic-ref --short HEAD')local substitute=mkenv({version=version},L.clidefs,L.luke.substitute,SHELLENV)local checks=preconditions(env,L.luke.release or{},version,main,substitute)local failed=dropuntil(checks,function(check)local description,predicate=unpack(check)L.verbose('checking whether ',description,'... ')local ok=predicate()L.verbose(ok and'yes\n'or'no\n')if not ok then +return description +end +end)if failed~=nil then +fatal('cannot release %s: check failed: %s',version,failed)return 1 +end +local rules=L.luke.release or{}local news,rockspec=rules.news,rules.rockspec +local released=rockspec and rockspec_name(rockspec,version)local added=flatten(rules.add,generated(L.luke),released)local today=date'%Y-%m-%d'local package,notes=announcement((interpolate(env,L.luke.package)),version,news and release_news(add_release_header(slurp(File(news))or'',version,today),version),rockspec and slurp(File(rockspec)))local pages=branches(rules)local worktrees=reduce(pages,{},function(r,branch)r[branch]=tmpname()rm(r[branch])end)local steps=flatten(news and{bind(edit,{L,news,bind(add_release_header,{[2]=version,[3]=today})}),bind(run,{L,env,'git commit',format("-m 'maint: update NEWS.md for %s.'",version),news}),},bind(run,{L,env,'git checkout -b','release-v'..version}),news and bind(edit,{L,news,remove_placeholder}),map(rules.replacements or{},function(entry)local path,pairs=destructure(entry)return bind(edit,{L,path,bind(replace,{[2]=substitute,[3]=pairs})})end),build,rockspec and{bind(edit,{L,rockspec,bind(set_modrev,{[2]=version}),released}),bind(run,{L,env,'git rm --quiet',rockspec}),},not isempty(added)and{bind(unignore,{L,env,added}),bind(run,{L,env,'git add -f',unpack(added)}),}or nil,bind(run,{L,env,format("git commit -a -m 'Release v%s.'",version)}),bind(tag,{L,env,version,notes}),map(pages,function(branch)local worktree=worktrees[branch]return{git(env,'rev-parse refs/heads/'..branch)~=git(env,'rev-parse origin/'..branch)and bind(run,{L,env,'git branch --quiet --force',branch,'origin/'..branch})or{},bind(run,{L,env,'git worktree add --quiet',worktree,branch}),publish_steps(L,env,substitute,worktree,rules[branch]),bind(run,{L,env,'git -C',worktree,"add -A && git -C",worktree,format("commit -m '%s: update to $package %s.'",branch,version)}),bind(run,{L,env,'git worktree remove',worktree}),}end),bind(run,{L,env,'git checkout --quiet',main}))local status=dropuntil(steps,isnonzero,call)or 0 +choose(status~=0,function()map(filter(sorted(values(worktrees)),exists),function(worktree)run(L,env,'git worktree remove --force',worktree)end)end)if status==0 then +local pushed=flatten(main,'release-v'..version,'v'..version,pages)L.write(format('\nRelease v%s is ready. To publish it:\n\n git push origin %s\n',version,concat(pushed,' ')))local GH=env.GH or configure(L,env,{checkprog='GitHub CLI',progs={'gh','true'}})if GH~='true'then +L.write(format(" %s release create v%s --verify-tag --latest --title '[ANN] %s v%s released' --notes-from-tag\n",GH,version,package,version))end +if released~=nil then +L.write(format(' git checkout release-v%s\n luarocks upload %s\n git checkout %s\n',version,released,main))end +else +local undo=undo_commands(checks)choose(not isempty(undo),function()L.write(format('\nRelease v%s failed. To undo it before trying again:\n\n%s',version,concat(map(undo,function(command)return' '..command..'\n'end))))end)end +return status +end,} +end +package.preload['luke.schema']=function() +local _ENV=require'luke.normalize'{'luke._base','luke.configure','luke.functional','luke.platforms','type.path',}local FORMAT=0 +local MACRO='^[%a_][%w_]*$'local ORDERED={bin=true,defines=true,external_dependencies=true,files=true,modules=true,}local function bad(path,...)fatal('bad %s: %s',path,format(...))end +local function index(path,k)if isstring(k)and match(k,'^[%a_][%w_]*$')then +return path==''and k or path..'.'..k +end +return format(isstring(k)and"%s['%s']"or'%s[%s]',path,str(k))end +local function claim(r,name,value,path)choose(r[name]~=nil,bind(bad,{path,"more than one entry for '%s'",name}))r[name]=value +end +local function mkcheck(kind)return function(x,path)if x~=nil and type(x)~=kind then +bad(path,'%s expected, got %s',kind,type(x))end +return x +end +end +local function list_of(normalize)return function(x,path)if isstring(x)then +x={x}end +mkcheck'table'(x,path)if x~=nil then +local r={}for i=1,len(x)do +r[i]=normalize(x[i],index(path,i))end +return r +end +end +end +local function map_of(normalize,names)return function(x,path)mkcheck'table'(x,path)if x~=nil then +local r={}for k,v in next,x do +if names~=nil then +names(k,index(path,k))end +r[k]=normalize(v,index(path,k))end +return r +end +end +end +local function fields(schema,others)local rest=choose(others==true,function()return id end,function()return others end)return setmetatable({schema=schema},{__call=function(_,x,path)return mkcheck'table'(x,path)and reduce(keys(x),{},function(r,k)local normalize=schema[k]or rest or bind(bad,{path,"unsupported key '%s'",str(k)})r[k]=normalize(x[k],index(path,k))end)end})end +local function keypaths(normalize,path)return sorted(flatten(map(keys(normalize.schema),function(k)local nested,p=normalize.schema[k],index(path or'',k)return choose(istable(nested),function()return{p,keypaths(nested,p)}end,p)end)))end +local function pathname(x,path)choose(mkcheck'string'(x,path)=='',bind(bad,{path,'empty path'}))local r=x and match(x,'^/?')..concat(except(gmatch(x,'[^/]+'),'.'),'/')return choose(r=='','.',r)end +local function luke_format(x,path)choose(x==nil,bind(bad,{path,'missing; this luke reads format %d, which replaces the lukefiles of luke 0.4 and earlier',FORMAT}))choose(int(mkcheck'number'(x,path))==nil or x<0,bind(bad,{path,'non-negative integer expected, got %s',str(x)}))choose(x~=FORMAT,function()bad(path,'lukefile format %d needs %s luke; this one reads format %d',x,choose(x>FORMAT,'a newer','an older'),FORMAT)end)return x +end +local function isprobe(x)return istable(x)and contains(configure,function(name)return x[name]~=nil +end)end +local function definition(x,path)return case(type(x),{['string']=function()local name,eq,value=match(x,'^([%a_][%w_]*)(=?)(.*)$')choose(name==nil or eq==''and value~='',bind(bad,{path,"bad macro definition '%s'",x}))return{[name]=choose(eq=='',1,value)}end,['table']=function()local names=keys(x)choose(names.n~=1,bind(bad,{path,'one definition expected, got %d',names.n}))local name=names[1]choose(isstring(name)and configure[name]~=nil,bind(bad,{path,'probe needs a macro name, such as {HAVE_X = {%s = ...}}',str(name)}))choose(not isstring(name)or match(name,MACRO)==nil,bind(bad,{path,"bad macro name '%s'",str(name)}))local value=x[name]choose(not(isstring(value)or type(value)=='number'or isprobe(value)),bind(bad,{index(path,name),'string, number or probe expected, got %s',type(value)}))return{[name]=value}end,function(kind)bad(path,'string or table expected, got %s',kind)end,})end +local function pair_of(normalize,rename)return function(x,path)local names=keys(mkcheck'table'(x,path))choose(names.n~=1,bind(bad,{path,'one entry expected, got %d',names.n}))local name=names[1]choose(not isstring(name),bind(bad,{path,'name expected, got %s',type(name)}))return{[(rename or id)(name,path)]=normalize(x[name],index(path,name))}end +end +local function ordered_map(entry)local function narrowed(x,path)return entry(istable(x)and filter_platforms(x,nil,nil,ORDERED)or x,path)end +local function layer_entries(layer,path)map(filter(sorted_keys(layer),function(k)return k~='platforms'and not islistkey(layer,k)end),function(k)bad(index(path,k),'list entry expected, such as {%s = ...}',index('',k))end)local r=list_of(narrowed)(layer,path)reduce(r,{},function(seen,pair)claim(seen,(next(pair)),true,path)end)return r +end +local function check_layers(x,path)layer_entries(mkcheck'table'(x,path),path)local at=index(path,'platforms')local platforms=mkcheck'table'(x.platforms,at)choose(platforms~=nil,function()local names,others=partition(sorted_keys(platforms),isplatform)map(names,function(name)check_layers(platforms[name],index(at,name))end)check_layers(pluck(others,platforms)or{},at)end)end +local function resolve(x,path)return ordered_merge(unpack(map(layers(x),function(layer)return choose(layer.platforms~=nil,function()return resolve(layer,path)end,function()return layer_entries(layer,path)end)end)))end +return function(x,path)local t=choose(isstring(x),function()return{x}end,function()return x +end)choose(t~=nil,bind(check_layers,{t,path}))return t and resolve(t,path)end +end +local defines=ordered_map(definition)local function dependency_name(name,path)choose(match(name,MACRO)==nil,bind(bad,{path,"bad dependency name '%s'",name}))return name +end +local dependencies=ordered_map(pair_of(mkcheck'table',dependency_name))local function rules(x,path)local r=case(type(x),{['nil']=nop,['string']=function()return{sources={x}}end,['table']=function()if len(x)>0 then +return{sources=x}elseif isstring(x.sources)then +return merge({sources={x.sources}},x)end +return x +end,function(kind)bad(path,'string or table expected, got %s',kind)end,})return r and merge({defines=defines(r.defines,index(path,'defines')),sources=list_of(pathname)(r.sources,index(path,'sources')),incdirs=list_of(pathname)(r.incdirs,index(path,'incdirs')),libdirs=list_of(pathname)(r.libdirs,index(path,'libdirs')),},r)end +local function program(x,path)local r=rules(x,path)if isempty(r.sources or{})then +bad(path,'no sources')end +mkcheck'string'(r.command,index(path,'command'))map_of(mkcheck'string',mkcheck'string')(r.env,index(path,'env'))return r +end +local function script(x,path)return case(type(x),{['string']=function()return pathname(x,path)end,['table']=function()return program(x,path)end,function(kind)bad(path,'string or table expected, got %s',kind)end,})end +local function mkscripts(mkname)local pair=pair_of(script,pathname)return ordered_map(function(x,path)return case(type(x),{['string']=function()local source=pathname(x,path)return{[mkname(source)]=source}end,['table']=function()choose(x.sources~=nil,bind(bad,{path,'programs need a name, such as {prog = {sources = ...}}'}))return pair(x,path)end,function(kind)bad(path,'string or table expected, got %s',kind)end,})end)end +local function filled(path)return(gsub(path,'%.in$',''))end +local scripts=mkscripts(function(source)return filled(basename(source))end)local files=mkscripts(filled)local function fills_too(dest,source)return match(dest,'%.in$')~=nil and match(source,'%.in$')~=nil +end +local copy_pair=pair_of(function(x,path)return{optional=false,source=pathname(x,path)}end,pathname)local function copy_entry(x,path)return case(type(x),{['string']=function()local source=pathname(x,path)return{[source]={optional=true,source=source}}end,['table']=function()return copy_pair(x,path)end,function(kind)bad(path,'string or table expected, got %s',kind)end,})end +local function copies(x,path)if mkcheck'table'(x,path)==nil then +return nil +end +local entries=copy(x)entries.command=nil +local r=ordered_map(copy_entry)(entries,path)r.command=mkcheck'string'(x.command,index(path,'command'))local written=reduce(ordered_keys(r),{},function(written,dest)written[dest]=true +end)map(r or{},function(pair)local dest,copy=destructure(pair)choose(fills_too(dest,copy.source),function()claim(written,filled(dest),true,path)end)end)return r +end +return{ORDERED=ORDERED,copies=copies,defines=defines,dependencies=dependencies,fields=fields,files=files,keypaths=keypaths,list_of=list_of,luke_format=luke_format,map_of=map_of,mkcheck=mkcheck,ordered_map=ordered_map,pair_of=pair_of,pathname=pathname,rules=rules,scripts=scripts,} +end +package.preload['luke.version']=function() +return{VERSION='0.6',versiontext=[[ +luke (Luke) 0.6 +Written by Gary V. Vaughan , 2014 + +Copyright (C) 2026, Gary V. Vaughan +Luke comes with ABSOLUTELY NO WARRANTY. +You may redistribute copies of Luke under the terms of the MIT license; +it may be used for any purpose at absolutely no cost, without permission. +See for details. +]],} +end +package.preload['type.context-manager']=function() +local _ENV=require'luke.normalize'{'luke.functional',}local contextmanager_mt={__index=function(self,key)if iscallable(self.context[key])then +return function(_,...)return self.context[key](self.context,...)end +end +if key=='filename'then +return self[1]end +end,}local function ContextManager(release,acquire,...)local fh,err=acquire(...)if not fh then +return nil,err +end +local cm={context=fh,release=release,n=select("#",...),...}if cm.context~=nil then +setmetatable(cm,contextmanager_mt)end +return cm +end +local function context_close(cm)return isfile(cm.context)and close(cm.context)end +local function with(...)local argu=list(...)local block=pop(argu)local r=list(apply(block,argu))map(argu,function(cm)if cm~=nil then +cm:release()end +end)return unpack(r)end +return{ContextManager=ContextManager,CTest=function(keep)local conftest=tmpname()local cm,err=ContextManager(function(cm)local closed=context_close(cm)if keep then +return closed +end +rm(conftest)rm(cm.objfile)return closed and rm(cm.filename)end,open,conftest..'.c','w')if cm~=nil then +cm.objfile=gsub(conftest,'^.*/','')..'.o'end +return cm,err +end,File=function(fname,mode)return ContextManager(context_close,open,fname,mode)end,Pipe=function(cmd,mode)return ContextManager(context_close,popen,cmd,mode)end,TmpFile=function(fname,mode)return ContextManager(function(cm)if context_close(cm)then +return rm(cm.filename)end +return false +end,open,fname or tmpname(),mode or'w')end,slurp=function(cm,...)if not cm then +return cm,...end +return with(cm,function(h)return h:read'*a'end)end,with=with,} +end +package.preload['type.dict']=function() +local _ENV=require'luke.normalize'{destructure=next,}return{OrderedDict=function(...)local r,argu={},list(...)for i=1,argu.n do +local k,v=destructure(argu[i])append(r,k)r[k]=v +end +return r +end,} +end +package.preload['type.path']=function() +local _ENV=require'luke.normalize'{}local BASENAMEPAT='.*'..dirsep +local DIRNAMEPAT=dirsep..'[^'..dirsep..']*$'return{basename=function(path)return(gsub(path,BASENAMEPAT,''))end,dirname=function(path)return(gsub(path,DIRNAMEPAT,'',1))end,exists=function(path)local fh=open(path)if fh==nil then +return false +end +close(fh)return true +end,} +end +os.exit(require'luke'.main(arg)) diff --color -urN a/lukefile b/lukefile --- a/lukefile +++ b/lukefile @@ -1,17 +1,160 @@ ---[[ - POSIX library for Lua 5.1, 5.2, 5.3, 5.4, & 5.5. - Copyright (C) 2013-2026 Gary V. Vaughan - Copyright (C) 2010-2013 Reuben Thomas - Copyright (C) 2008-2010 Natanael Copa -]] - luke_format = 0 package = 'luaposix' -version = '$USER/$gitref' +version = '$USER' + +defines = { + {PACKAGE = '"$package"'}, + {VERSION = '"$version"'}, + 'NDEBUG', + '_FORTIFY_SOURCE=2', + platforms = { + aix = {'_ALL_SOURCE'}, + bsd = {'_BSD_SOURCE'}, + freebsd = {'__BSD_VISIBLE'}, + -- Some Linux distros only reveal tm.tm_gmtoff and tm.tm_zone with + -- _BSD_SOURCE defined. + linux = { + '_BSD_SOURCE', + '_DEFAULT_SOURCE', + }, + macosx = {'_DARWIN_C_SOURCE'}, + -- QNX is only POSIX 2001, but _XOPEN_SOURCE turns off other functions + -- luaposix can bind. + qnx = {'_POSIX_C_SOURCE=200112L'}, + unix = { + '_POSIX_C_SOURCE=200809L', + '_XOPEN_SOURCE=700', + }, + -- Otherwise, enable POSIX 2008. Please send the output of `uname -s` if + -- your host is not compliant. + '_POSIX_C_SOURCE=200809L', + }, +} + +incdirs = { + 'ext/include', + '$LUA_INCDIR', +} ldocs = 'build-aux/config.ld.in' +modules = { + {['posix'] = 'lib/posix/init.lua'}, + {['posix._base'] = 'lib/posix/_base.lua'}, + {['posix.compat'] = 'lib/posix/compat.lua'}, + {['posix.sys'] = 'lib/posix/sys.lua'}, + {['posix.util'] = 'lib/posix/util.lua'}, + + {['posix.ctype'] = 'ext/posix/ctype.c'}, + {['posix.dirent'] = 'ext/posix/dirent.c'}, + {['posix.errno'] = 'ext/posix/errno.c'}, + {['posix.fcntl'] = { + defines = { + {HAVE_POSIX_FADVISE = {checkfunc='posix_fadvise'}}, + }, + sources = 'ext/posix/fcntl.c', + }}, + {['posix.fnmatch'] = 'ext/posix/fnmatch.c'}, + {['posix.glob'] = 'ext/posix/glob.c'}, + {['posix.grp'] = 'ext/posix/grp.c'}, + {['posix.libgen'] = 'ext/posix/libgen.c'}, + {['posix.poll'] = 'ext/posix/poll.c'}, + {['posix.pwd'] = 'ext/posix/pwd.c'}, + {['posix.sched'] = { + defines = { + {HAVE_SCHED_H = {checkheader='sched.h'}}, + {HAVE_SCHED_GETSCHEDULER = {checkfunc='sched_getscheduler'}}, + {HAVE_SCHED_SETSCHEDULER = {checkfunc='sched_setscheduler'}}, + }, + sources = 'ext/posix/sched.c', + }}, + {['posix.signal'] = 'ext/posix/signal.c'}, + {['posix.stdio'] = 'ext/posix/stdio.c'}, + {['posix.stdlib'] = 'ext/posix/stdlib.c'}, + {['posix.sys.msg'] = { + defines = { + {HAVE_SYS_MSG_H = {checkheader='sys/msg.h'}}, + {HAVE_MSGRCV = {checkfunc='msgrcv'}}, + {HAVE_MSGSND = {checkfunc='msgsnd'}}, + }, + sources = 'ext/posix/sys/msg.c', + }}, + {['posix.sys.resource'] = 'ext/posix/sys/resource.c'}, + {['posix.sys.socket'] = { + defines = { + {HAVE_NET_IF_H = {checkheader='net/if.h', include='sys/socket.h'}}, + {HAVE_LINUX_NETLINK_H = {checkheader='linux/netlink.h', include='sys/socket.h'}}, + {HAVE_LINUX_IF_PACKET_H = {checkheader='linux/if_packet.h', include='sys/socket.h'}}, + }, + libraries = { + {checksymbol='socket', library='socket'}, + }, + sources = 'ext/posix/sys/socket.c', + }}, + {['posix.sys.stat'] = 'ext/posix/sys/stat.c'}, + {['posix.sys.statvfs'] = { + defines = { + {HAVE_STATVFS = {checkfunc='statvfs'}}, + }, + sources = 'ext/posix/sys/statvfs.c', + }}, + {['posix.sys.time'] = 'ext/posix/sys/time.c'}, + {['posix.sys.times'] = 'ext/posix/sys/times.c'}, + {['posix.sys.utsname'] = 'ext/posix/sys/utsname.c'}, + {['posix.sys.wait'] = 'ext/posix/sys/wait.c'}, + {['posix.syslog'] = 'ext/posix/syslog.c'}, + {['posix.termio'] = { + defines = { + {HAVE_TERMIOS_H = {checkheader='termios.h'}}, + {HAVE_WS_XPIXEL = {checkmember='struct winsize.ws_xpixel', include='termios.h'}}, + {HAVE_WS_YPIXEL = {checkmember='struct winsize.ws_ypixel', include='termios.h'}}, + }, + sources = 'ext/posix/termio.c', + }}, + {['posix.time'] = { + defines = { + -- Check the function directly rather than _POSIX_TIMERS, because + -- OpenBSD has clock_getres and clock_gettime but defines + -- _POSIX_TIMERS to -1. + {HAVE_CLOCK_GETTIME = {checkfunc='clock_gettime'}}, + {HAVE_TM_GMTOFF = {checkmember='struct tm.tm_gmtoff', include='time.h'}}, + {HAVE_TM_ZONE = {checkmember='struct tm.tm_zone', include='time.h'}}, + }, + libraries = { + { + ifdef = '_POSIX_TIMERS', + include = 'unistd.h', + checksymbol = 'clock_gettime', + library = 'rt', + }, + }, + sources = 'ext/posix/time.c', + }}, + {['posix.unistd'] = { + defines = { + {HAVE_CRYPT = {checkfunc='crypt'}}, + {HAVE_CRYPT_H = {checkheader='crypt.h'}}, + {HAVE_DECL_FDATASYNC = {checkdecl='fdatasync', include='unistd.h'}}, + {HAVE_FDATASYNC = {checkfunc='fdatasync'}}, + {HAVE_GETHOSTID = {checkfunc='gethostid'}}, + {HAVE_SETGROUPS = {checkfunc='setgroups'}}, + }, + libraries = { + {checksymbol='crypt', library='crypt'}, + }, + sources = 'ext/posix/unistd.c', + }}, + {['posix.utime'] = 'ext/posix/utime.c'}, + {['posix.version'] = 'lib/posix/version.lua.in'}, +} + + +-- Luke builds luaposix before committing it, without LuaRocks to say +-- where lua.h is, so pass it yourself. With Homebrew, for example: +-- +-- build-aux/luke release version=X.Y \ +-- LUA_INCDIR=/opt/homebrew/include/lua5.5 release = { news = 'NEWS.md', rockspec = 'luaposix-dev-1.rockspec', diff --color -urN a/spec/spec_helper.lua b/spec/spec_helper.lua --- a/spec/spec_helper.lua +++ b/spec/spec_helper.lua @@ -6,14 +6,18 @@ do local std = require 'specl.std' + local spawn = require 'specl.shell'.spawn + local objdir = spawn(LUA .. ' ./build-aux/luke --value=objdir').output - -- Run the Lua modules from this tree, for coverage, and the C modules - -- from the rock that `luarocks make` installed. package.path = std.package.normalize ( './lib/?.lua', './lib/?/init.lua', package.path ) + package.cpath = std.package.normalize( + './' .. objdir:match("^objdir='(.*)'") .. '/?.so', + package.cpath + ) end @@ -25,7 +29,6 @@ -- luaposix checks the arguments of its Lua functions only when typecheck -- loads, so skip their bad argument examples without it. have_typecheck = pcall(require, 'typecheck') -have_strict = pcall(require, 'std.strict.init') hell = require 'specl.shell' posix = require 'posix'