niminst: diverse improvements; fixes #80

This commit is contained in:
Araq 2012-01-13 21:15:00 +01:00
commit 8ed3e295a3
13 changed files with 102 additions and 46 deletions

21
tools/niminst/buildbat.tmpl Executable file
View file

@ -0,0 +1,21 @@
#! stdtmpl(subsChar='?') | standard
#proc GenerateBuildBatchScript(c: TConfigData): string =
# result = "@echo off\nREM Generated by niminst\n"
SET CC=gcc
SET LINKER=gcc
SET COMP_FLAGS=?{c.ccompiler.flags}
SET LINK_FLAGS=?{c.linker.flags}
REM call the compiler:
# var linkCmd = ""
# for f in items(c.cfiles[1][1]):
ECHO %CC% %COMP_FLAGS% -Ibuild -c ?{f} -o ?{changeFileExt(f, "o")}
%CC% %COMP_FLAGS% -Ibuild -c ?{f} -o ?{changeFileExt(f, "o")}
# linkCmd.add(" " & changeFileExt(f, "o"))
# end for
ECHO %LINKER% %LINK_FLAGS% -o ?{c.binPaths[0]}\?{toLower(c.name)}.exe ?linkCmd
%LINKER% %LINK_FLAGS% -o ?{c.binPaths[0]}\?{toLower(c.name)}.exe ?linkCmd
ECHO SUCCESS

110
tools/niminst/buildsh.tmpl Executable file
View file

@ -0,0 +1,110 @@
#! stdtmpl(subsChar='?') | standard
#proc GenerateBuildShellScript(c: TConfigData): string =
# result = "#! /bin/sh\n# Generated from niminst\n" &
# "# Template is in tools/buildsh.tmpl\n" &
# "# To regenerate run ``niminst csource`` or ``koch csource``\n"
CC="gcc"
LINKER="gcc"
COMP_FLAGS="?{c.ccompiler.flags}"
LINK_FLAGS="?{c.linker.flags}"
# add(result, "# platform detection\n")
ucpu=`uname -m`
uos=`uname`
# add(result, "# convert to lower case:\n")
ucpu=`echo $ucpu | tr "[:upper:]" "[:lower:]"`
uos=`echo $uos | tr "[:upper:]" "[:lower:]"`
case $uos in
*linux* )
myos="linux"
LINK_FLAGS="$LINK_FLAGS -ldl -lm"
;;
*freebsd* )
myos="freebsd"
LINK_FLAGS="$LINK_FLAGS -lm"
;;
*openbsd* )
myos="openbsd"
LINK_FLAGS="$LINK_FLAGS -lm"
;;
*netbsd* )
myos="netbsd"
LINK_FLAGS="$LINK_FLAGS -lm"
;;
*darwin* )
myos="macosx"
LINK_FLAGS="$LINK_FLAGS -ldl -lm"
if [ "$HOSTTYPE" = "x86_64" ] ; then
ucpu="amd64"
fi
;;
*aix* )
myos="aix"
LINK_FLAGS="$LINK_FLAGS -ldl -lm"
;;
*solaris* | *sun* )
myos="solaris"
LINK_FLAGS="$LINK_FLAGS -ldl -lm"
;;
*)
echo "Error: unknown operating system: $uos"
exit 1
;;
esac
case $ucpu in
*i386* | *i486* | *i586* | *i686* )
mycpu="i386" ;;
*amd*64* | *x86-64* | *x86_64* )
mycpu="amd64" ;;
*sparc*|*sun* )
mycpu="sparc" ;;
*ppc64* )
if [ "$myos" = "linux" ] ; then
COMP_FLAGS="$COMP_FLAGS -m64"
LINK_FLAGS="$LINK_FLAGS -m64"
fi
mycpu="powerpc64" ;;
*power*|*Power* )
mycpu="powerpc" ;;
*mips* )
mycpu="mips" ;;
*)
echo "Error: unknown processor: $ucpu"
exit 1
;;
esac
# add(result, "# call the compiler:\n")
case $myos in
# for osA in 1..c.oses.len:
?{c.oses[osA-1]})
case $mycpu in
# for cpuA in 1..c.cpus.len:
?{c.cpus[cpuA-1]})
# var linkCmd = ""
# for f in items(c.cfiles[osA][cpuA]):
echo "$CC $COMP_FLAGS -Ibuild -c ?{f} -o ?{changeFileExt(f, "o")}"
$CC $COMP_FLAGS -Ibuild -c ?{f} -o ?{changeFileExt(f, "o")} || exit 1
# add(linkCmd, " \\\n" & changeFileExt(f, "o"))
# end for
echo "$LINKER $LINK_FLAGS -o ?{c.binPaths[0]}/?{toLower(c.name)} ?linkCmd"
$LINKER $LINK_FLAGS -o ?{c.binPaths[0]}/?{toLower(c.name)} ?linkCmd || exit 1
;;
# end for
*)
echo "Error: no C code generated for: [$myos: $mycpu]"
exit 1
;;
esac
;;
# end for
*)
echo "Error: no C code generated for: [$myos: $mycpu]"
exit 1
;;
esac
echo "SUCCESS"

62
tools/niminst/deinstall.tmpl Executable file
View file

@ -0,0 +1,62 @@
#! stdtmpl(subsChar='?') | standard
#proc GenerateDeinstallScript(c: TConfigData): string =
# result = "#! /bin/sh\n# Generated by niminst\n"
# var proj = c.name.toLower
if [ $# -eq 1 ] ; then
case $1 in
"--help"|"-h"|"help"|"h")
echo "?c.displayName deinstallation script"
echo "Usage: [sudo] sh deinstall.sh DIR"
echo "Where DIR may be:"
echo " /usr/bin"
echo " /usr/local/bin"
echo " /opt"
echo " <some other dir> (treated like '/opt')"
exit 1
;;
"/usr/bin")
bindir=/usr/bin
configdir=/etc
libdir=/usr/lib/?proj
docdir=/usr/share/?proj/doc
datadir=/usr/share/?proj/data
;;
"/usr/local/bin")
bindir=/usr/local/bin
configdir=/etc
libdir=/usr/local/lib/?proj
docdir=/usr/local/share/?proj/doc
datadir=/usr/local/share/?proj/data
;;
*)
bindir="$1/?proj/bin"
configdir="$1/?proj/config"
libdir="$1/?proj/lib"
docdir="$1/?proj/doc"
datadir="$1/?proj/data"
;;
esac
echo "removing files..."
#for f in items(c.cat[fcUnixBin]):
rm -f $bindir/?f.skipRoot
#end for
#for f in items(c.cat[fcConfig]):
rm -f $configdir/?f.skipRoot
#end for
rm -rf $docdir
rm -rf $datadir
rm -rf $libdir
echo "deinstallation successful"
else
echo "?c.displayName deinstallation script"
echo "Usage: [sudo] sh deinstall.sh DIR"
echo "Where DIR may be:"
echo " /usr/bin"
echo " /usr/local/bin"
echo " /opt"
echo " <some other dir> (treated like '/opt')"
exit 1
fi

182
tools/niminst/inno.tmpl Executable file
View file

@ -0,0 +1,182 @@
#! stdtmpl | standard
#proc GenerateInnoSetup(c: TConfigData): string =
# result = ""
; Default Template for NimInst
[Setup]
AppName=$c.displayName
AppVerName=$c.displayName $c.version
DefaultDirName={code:GiveMeAPath|$c.displayName}
DefaultGroupName=$c.displayName
AllowNoIcons=yes
LicenseFile=${expandFilename(c.license)}
OutputBaseFilename=${c.name}_${c.version}
Compression=lzma
SolidCompression=yes
PrivilegesRequired=none
ChangesEnvironment=yes
[Languages]
Name: english; MessagesFile: compiler:Default.isl
[Files]
#for i in low(TFileCategory)..fcWindows:
# for f in items(c.cat[i]):
Source: ${expandFilename(f)}; DestDir: {app}\${splitFile(f).dir}; Flags: ignoreversion
# end for
#end for
[Icons]
#if c.app == appConsole:
Name: {group}\Console for $c.displayName; Filename: {cmd}
#else:
Name: {group}\$c.displayName; Filename: {app}\${c.name}.exe
#end if
#for f in items(c.cat[fcDocStart]):
Name: {group}\Documentation; Filename: {app}\$f
#end for
Name: {group}\{cm:UninstallProgram,$c.displayName}; Filename: {uninstallexe}
#if c.binPaths.len > 0:
[Tasks]
Name: modifypath; Description: &Add $c.displayName to your system path (if not in path already);
#end if
[Code]
function GiveMeAPath(const DefaultPathName: string): string;
begin
if IsAdminLoggedOn then Result := ExpandConstant('{pf}')
else Result := ExpandConstant('{userdocs}');
Result := Result + '\' + DefaultPathName;
end;
#if c.binPaths.len > 0:
// ----------------------------------------------------------------------------
//
// Inno Setup Ver: 5.2.1
// Script Version: 1.3.1
// Author: Jared Breland <jbreland@legroom.net>
// Homepage: http://www.legroom.net/software
//
// Script Function:
// Enable modification of system path directly from Inno Setup installers
function ModPathDir(): TArrayOfString;
begin
setArrayLength(result, $c.binPaths.len);
#var i = 0
#for b in items(c.binPaths):
result[$i] := ExpandConstant('{app}') + '\$b';
#inc(i)
#end for
end;
procedure ModPath();
var
oldpath, newpath, aExecFile: String;
pathArr, aExecArr, pathdir: TArrayOfString;
i, d: Integer;
begin
// Get array of new directories and act on each individually
pathdir := ModPathDir();
for d := 0 to GetArrayLength(pathdir)-1 do begin
// Modify WinNT path
if UsingWinNT() then begin
// Get current path, split into an array
RegQueryStringValue(HKEY_LOCAL_MACHINE,
'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
'Path', oldpath);
oldpath := oldpath + ';';
i := 0;
while (Pos(';', oldpath) > 0) do begin
SetArrayLength(pathArr, i+1);
pathArr[i] := Copy(oldpath, 0, Pos(';', oldpath)-1);
oldpath := Copy(oldpath, Pos(';', oldpath)+1, Length(oldpath));
i := i + 1;
// Check if current directory matches app dir
if pathdir[d] = pathArr[i-1] then begin
// if uninstalling, remove dir from path
if IsUninstaller() then continue
// if installing, abort because dir was already in path
else abort;
end;
// Add current directory to new path
if i = 1 then newpath := pathArr[i-1]
else newpath := newpath + ';' + pathArr[i-1];
end;
// Append app dir to path if not already included
if not IsUninstaller() then
newpath := newpath + ';' + pathdir[d];
// Write new path
RegWriteStringValue(HKEY_LOCAL_MACHINE,
'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
'Path', newpath);
end
else begin
// Modify Win9x path
// Convert to shortened dirname
pathdir[d] := GetShortName(pathdir[d]);
// If autoexec.bat exists, check if app dir already exists in path
aExecFile := 'C:\AUTOEXEC.BAT';
if FileExists(aExecFile) then begin
LoadStringsFromFile(aExecFile, aExecArr);
for i := 0 to GetArrayLength(aExecArr)-1 do begin
if not IsUninstaller() then begin
// If app dir already exists while installing, abort add
if (Pos(pathdir[d], aExecArr[i]) > 0) then
abort;
end
else begin
// If app dir exists and = what we originally set,
// then delete at uninstall
if aExecArr[i] = 'SET PATH=%PATH%;' + pathdir[d] then
aExecArr[i] := '';
end;
end;
end;
// If app dir not found, or autoexec.bat didn't exist, then
// (create and) append to current path
if not IsUninstaller() then begin
SaveStringToFile(aExecFile, #13#10 + 'SET PATH=%PATH%;' + pathdir[d],
True);
end
else begin
// If uninstalling, write the full autoexec out
SaveStringsToFile(aExecFile, aExecArr, False);
end;
end;
// Write file to flag modifypath was selected
// Workaround since IsTaskSelected() cannot be called at uninstall and
// AppName and AppId cannot be "read" in Code section
if not IsUninstaller() then
SaveStringToFile(ExpandConstant('{app}') + '\uninsTasks.txt',
WizardSelectedTasks(False), False);
end;
end;
procedure CurStepChanged(CurStep: TSetupStep);
begin
if CurStep = ssPostInstall then begin
if IsTaskSelected('modifypath') then
ModPath();
end
end;
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
var
appdir, selectedTasks: String;
begin
appdir := ExpandConstant('{app}');
if CurUninstallStep = usUninstall then begin
if LoadStringFromFile(appdir + '\uninsTasks.txt', selectedTasks) then
if Pos('modifypath', selectedTasks) > 0 then
ModPath();
DeleteFile(appdir + '\uninsTasks.txt')
end;
end;
function NeedRestart(): Boolean;
begin
result := IsTaskSelected('modifypath') and not UsingWinNT()
end;
#end if

105
tools/niminst/install.tmpl Executable file
View file

@ -0,0 +1,105 @@
#! stdtmpl(subsChar = '?') | standard
#proc GenerateInstallScript(c: TConfigData): string =
# result = "#! /bin/sh\n# Generated by niminst\n"
# var proj = c.name.toLower
if [ $# -eq 1 ] ; then
# if c.cat[fcUnixBin].len > 0:
if test -f ?{c.cat[fcUnixBin][0]}
then
echo "?c.displayName build detected"
else
echo "Please build ?c.displayName before installing it"
exit 1
fi
# end if
case $1 in
"--help"|"-h"|"help"|"h")
echo "?c.displayName installation script"
echo "Usage: [sudo] sh install.sh DIR"
echo "Where DIR may be:"
echo " /usr/bin"
echo " /usr/local/bin"
echo " /opt"
echo " <some other dir> (treated like '/opt')"
echo "To deinstall, use the command:"
echo "sh deinstall.sh DIR"
exit 1
;;
"/usr/bin")
bindir=/usr/bin
configdir=/etc
libdir=/usr/lib/?proj
docdir=/usr/share/?proj/doc
datadir=/usr/share/?proj/data
;;
"/usr/local/bin")
bindir=/usr/local/bin
configdir=/etc
libdir=/usr/local/lib/?proj
docdir=/usr/local/share/?proj/doc
datadir=/usr/local/share/?proj/data
;;
*)
bindir="$1/?proj/bin"
configdir="$1/?proj/config"
libdir="$1/?proj/lib"
docdir="$1/?proj/doc"
datadir="$1/?proj/data"
mkdir -p $1/?proj || exit 1
mkdir -p $bindir || exit 1
mkdir -p $configdir || exit 1
;;
esac
mkdir -p $libdir || exit 1
mkdir -p $docdir || exit 1
echo "copying files..."
#var createdDirs = newStringTable()
#for cat in fcConfig..fcLib:
# for f in items(c.cat[cat]):
# var mk = splitFile(f.skipRoot).dir
# if mk.len > 0:
# mk = unixDirVars[cat] & "/" & mk
# if not createdDirs.hasKey(mk):
# createdDirs[mk] = "true"
mkdir -p ?mk || exit 1
# end if
# end if
# end for
#end for
#for f in items(c.cat[fcUnixBin]):
cp ?f $bindir/?f.skipRoot || exit 1
chmod 755 $bindir/?f.skipRoot
#end for
#for f in items(c.cat[fcConfig]):
cp ?f $configdir/?f.skipRoot || exit 1
chmod 644 $configdir/?f.skipRoot
#end for
#for f in items(c.cat[fcData]):
cp ?f $datadir/?f.skipRoot || exit 1
chmod 644 $datadir/?f.skipRoot
#end for
#for f in items(c.cat[fcDoc]):
cp ?f $docdir/?f.skipRoot || exit 1
chmod 644 $docdir/?f.skipRoot
#end for
#for f in items(c.cat[fcLib]):
cp ?f $libdir/?f.skipRoot || exit 1
chmod 644 $libdir/?f.skipRoot
#end for
echo "installation successful"
else
echo "?c.displayName installation script"
echo "Usage: [sudo] sh install.sh DIR"
echo "Where DIR may be:"
echo " /usr/bin"
echo " /usr/local/bin"
echo " /opt"
echo " <some other dir> (treated like '/opt')"
echo "To deinstall, use the command:"
echo "sh deinstall.sh DIR"
exit 1
fi

425
tools/niminst/niminst.nim Executable file
View file

@ -0,0 +1,425 @@
#
#
# The Nimrod Installation Generator
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
const
haveZipLib = defined(unix)
when haveZipLib:
import zipfiles
import
os, strutils, parseopt, parsecfg, strtabs, streams
const
maxOS = 20 # max number of OSes
maxCPU = 10 # max number of CPUs
buildShFile = "build.sh"
buildBatFile = "build.bat"
installShFile = "install.sh"
deinstallShFile = "deinstall.sh"
type
TAppType = enum appConsole, appGUI
TAction = enum
actionNone, # action not yet known
actionCSource # action: create C sources
actionInno, # action: create Inno Setup installer
actionZip # action: create zip file
TFileCategory = enum
fcWinBin, # binaries for Windows
fcConfig, # configuration files
fcData, # data files
fcDoc, # documentation files
fcLib, # library files
fcOther, # other files; will not be copied on UNIX
fcWindows, # files only for Windows
fcUnix, # files only for Unix; must be after ``fcWindows``
fcUnixBin, # binaries for Unix
fcDocStart # links to documentation for Windows installer
TConfigData = object of TObject
actions: set[TAction]
cat: array[TFileCategory, seq[string]]
binPaths, authors, oses, cpus: seq[string]
cfiles: array[1..maxOS, array[1..maxCPU, seq[string]]]
ccompiler, linker, innosetup: tuple[path, flags: string]
name, displayName, version, description, license, infile, outdir: string
libpath: string
innoSetupFlag, installScript, uninstallScript: bool
vars: PStringTable
app: TAppType
nimrodArgs: string
const
unixDirVars: array[fcConfig..fcLib, string] = [
"$configdir", "$datadir", "$docdir", "$libdir"
]
proc initConfigData(c: var TConfigData) =
c.actions = {}
for i in low(TFileCategory)..high(TFileCategory): c.cat[i] = @[]
c.binPaths = @[]
c.authors = @[]
c.oses = @[]
c.cpus = @[]
c.ccompiler = ("", "")
c.linker = ("", "")
c.innosetup = ("", "")
c.name = ""
c.displayName = ""
c.version = ""
c.description = ""
c.license = ""
c.infile = ""
c.outdir = ""
c.nimrodArgs = ""
c.libpath = ""
c.innoSetupFlag = false
c.installScript = false
c.uninstallScript = false
c.vars = newStringTable(modeStyleInsensitive)
proc skipRoot(f: string): string =
# "abc/def/xyz" --> "def/xyz"
var i = 0
result = ""
for component in split(f, {dirsep, altsep}):
if i > 0: result = result / component
inc i
if result.len == 0: result = f
include "inno.tmpl"
include "buildsh.tmpl"
include "buildbat.tmpl"
include "install.tmpl"
include "deinstall.tmpl"
# ------------------------- configuration file -------------------------------
const
Version = "0.9"
Usage = "niminst - Nimrod Installation Generator Version " & version & """
(c) 2012 Andreas Rumpf
Usage:
niminst [options] command[;command2...] ini-file[.ini] [compile_options]
Command:
csource build C source code for source based installations
zip build the ZIP file
inno build the Inno Setup installer
Options:
-o, --output:dir set the output directory
--var:name=value set the value of a variable
-h, --help shows this help
-v, --version shows the version
Compile_options:
will be passed to the Nimrod compiler
"""
proc parseCmdLine(c: var TConfigData) =
var p = initOptParser()
while true:
next(p)
var kind = p.kind
var key = p.key
var val = p.val.string
case kind
of cmdArgument:
if c.actions == {}:
for a in split(normalize(key.string), {';', ','}):
case a
of "csource": incl(c.actions, actionCSource)
of "zip": incl(c.actions, actionZip)
of "inno": incl(c.actions, actionInno)
else: quit(Usage)
else:
c.infile = addFileExt(key.string, "ini")
c.nimrodArgs = cmdLineRest(p).string
break
of cmdLongOption, cmdShortOption:
case normalize(key.string)
of "help", "h":
stdout.write(Usage)
quit(0)
of "version", "v":
stdout.write(Version & "\n")
quit(0)
of "o", "output": c.outdir = val
of "var":
var idx = val.find('=')
if idx < 0: quit("invalid command line")
c.vars[substr(val, 0, idx-1)] = substr(val, idx+1)
else: quit(Usage)
of cmdEnd: break
if c.infile.len == 0: quit(Usage)
proc walkDirRecursively(s: var seq[string], root: string) =
for k, f in walkDir(root):
case k
of pcFile, pcLinkToFile: add(s, UnixToNativePath(f))
of pcDir: walkDirRecursively(s, f)
of pcLinkToDir: nil
proc addFiles(s: var seq[string], patterns: seq[string]) =
for p in items(patterns):
if existsDir(p):
walkDirRecursively(s, p)
else:
var i = 0
for f in walkFiles(p):
add(s, UnixToNativePath(f))
inc(i)
if i == 0: echo("[Warning] No file found that matches: " & p)
proc pathFlags(p: var TCfgParser, k, v: string,
t: var tuple[path, flags: string]) =
case normalize(k)
of "path": t.path = v
of "flags": t.flags = v
else: quit(errorStr(p, "unknown variable: " & k))
proc filesOnly(p: var TCfgParser, k, v: string, dest: var seq[string]) =
case normalize(k)
of "files": addFiles(dest, split(v, {';'}))
else: quit(errorStr(p, "unknown variable: " & k))
proc yesno(p: var TCfgParser, v: string): bool =
case normalize(v)
of "yes", "y", "on", "true":
result = true
of "no", "n", "off", "false":
result = false
else: quit(errorStr(p, "unknown value; use: yes|no"))
proc parseIniFile(c: var TConfigData) =
var
p: TCfgParser
section: string # current section
var input = newFileStream(c.infile, fmRead)
if input != nil:
open(p, input, c.infile)
while true:
var k = next(p)
case k.kind
of cfgEof: break
of cfgSectionStart:
section = normalize(k.section)
of cfgKeyValuePair:
var v = k.value % c.vars
c.vars[k.key] = v
case section
of "project":
case normalize(k.key)
of "name": c.name = v
of "displayname": c.displayName = v
of "version": c.version = v
of "os": c.oses = split(v, {';'})
of "cpu": c.cpus = split(v, {';'})
of "authors": c.authors = split(v, {';'})
of "description": c.description = v
of "app":
case normalize(v)
of "console": c.app = appConsole
of "gui": c.app = appGUI
else: quit(errorStr(p, "expected: console or gui"))
of "license": c.license = UnixToNativePath(k.value)
else: quit(errorStr(p, "unknown variable: " & k.key))
of "var": nil
of "winbin": filesOnly(p, k.key, v, c.cat[fcWinBin])
of "config": filesOnly(p, k.key, v, c.cat[fcConfig])
of "data": filesOnly(p, k.key, v, c.cat[fcData])
of "documentation":
case normalize(k.key)
of "files": addFiles(c.cat[fcDoc], split(v, {';'}))
of "start": addFiles(c.cat[fcDocStart], split(v, {';'}))
else: quit(errorStr(p, "unknown variable: " & k.key))
of "lib": filesOnly(p, k.key, v, c.cat[fcLib])
of "other": filesOnly(p, k.key, v, c.cat[fcOther])
of "windows":
case normalize(k.key)
of "files": addFiles(c.cat[fcWindows], split(v, {';'}))
of "binpath": c.binPaths = split(v, {';'})
of "innosetup": c.innoSetupFlag = yesno(p, v)
else: quit(errorStr(p, "unknown variable: " & k.key))
of "unix":
case normalize(k.key)
of "files": addFiles(c.cat[fcUnix], split(v, {';'}))
of "installscript": c.installScript = yesno(p, v)
of "uninstallscript": c.uninstallScript = yesno(p, v)
else: quit(errorStr(p, "unknown variable: " & k.key))
of "unixbin": filesOnly(p, k.key, v, c.cat[fcUnixBin])
of "innosetup": pathFlags(p, k.key, v, c.innoSetup)
of "ccompiler": pathFlags(p, k.key, v, c.ccompiler)
of "linker": pathFlags(p, k.key, v, c.linker)
else: quit(errorStr(p, "invalid section: " & section))
of cfgOption: quit(errorStr(p, "syntax error"))
of cfgError: quit(errorStr(p, k.msg))
close(p)
if c.name.len == 0: c.name = changeFileExt(extractFilename(c.infile), "")
if c.displayName.len == 0: c.displayName = c.name
else:
quit("cannot open: " & c.infile)
# ------------------------- generate source based installation ---------------
proc readCFiles(c: var TConfigData, osA, cpuA: int) =
var p: TCfgParser
var f = splitFile(c.infile).dir / "mapping.txt"
c.cfiles[osA][cpuA] = @[]
var input = newFileStream(f, fmRead)
var section = ""
if input != nil:
open(p, input, f)
while true:
var k = next(p)
case k.kind
of cfgEof: break
of cfgSectionStart:
section = normalize(k.section)
of cfgKeyValuePair:
case section
of "ccompiler": pathFlags(p, k.key, k.value, c.ccompiler)
of "linker":
pathFlags(p, k.key, k.value, c.linker)
# HACK: we conditionally add ``-lm -ldl``, so remove them from the
# linker flags:
c.linker.flags = c.linker.flags.replaceWord("-lm").replaceWord(
"-ldl").strip
else:
if cmpIgnoreStyle(k.key, "libpath") == 0:
c.libpath = k.value
of cfgOption:
if section == "cfiles" and cmpIgnoreStyle(k.key, "file") == 0:
add(c.cfiles[osA][cpuA], k.value)
of cfgError: quit(errorStr(p, k.msg))
close(p)
else:
quit("Cannot open: " & f)
proc buildDir(os, cpu: int): string =
return "build" / ($os & "_" & $cpu)
proc writeFile(filename, content, newline: string) =
var f: TFile
if open(f, filename, fmWrite):
for x in splitLines(content):
write(f, x)
write(f, newline)
close(f)
else:
quit("Cannot open for writing: " & filename)
proc removeDuplicateFiles(c: var TConfigData) =
for osA in countdown(c.oses.len, 1):
for cpuA in countdown(c.cpus.len, 1):
for i in 0..c.cfiles[osA][cpuA].len-1:
var dup = c.cfiles[osA][cpuA][i]
var f = extractFilename(dup)
for osB in 1..c.oses.len:
for cpuB in 1..c.cpus.len:
if osB != osA or cpuB != cpuA:
var orig = buildDir(osB, cpuB) / f
if ExistsFile(orig) and ExistsFile(dup) and
sameFileContent(orig, dup):
# file is identical, so delete duplicate:
RemoveFile(dup)
c.cfiles[osA][cpuA][i] = orig
proc srcdist(c: var TConfigData) =
for x in walkFiles(c.libpath / "lib/*.h"):
CopyFile(dest="build" / extractFilename(x), source=x)
for osA in 1..c.oses.len:
for cpuA in 1..c.cpus.len:
var dir = buildDir(osA, cpuA)
if existsDir(dir): removeDir(dir)
createDir(dir)
var cmd = ("nimrod compile -f --symbolfiles:off --compileonly " &
"--gen_mapping " &
" --os:$# --cpu:$# $# $#") %
[c.oses[osA-1], c.cpus[cpuA-1], c.nimrodArgs,
changeFileExt(c.infile, "nim")]
echo(cmd)
if execShellCmd(cmd) != 0:
quit("Error: call to nimrod compiler failed")
readCFiles(c, osA, cpuA)
for i in 0 .. c.cfiles[osA][cpuA].len-1:
var dest = dir / extractFilename(c.cfiles[osA][cpuA][i])
CopyFile(dest=dest, source=c.cfiles[osA][cpuA][i])
c.cfiles[osA][cpuA][i] = dest
# second pass: remove duplicate files
removeDuplicateFiles(c)
writeFile(buildShFile, GenerateBuildShellScript(c), "\10")
writeFile(buildBatFile, GenerateBuildBatchScript(c), "\13\10")
if c.installScript:
writeFile(installShFile, GenerateInstallScript(c), "\10")
if c.uninstallScript:
writeFile(deinstallShFile, GenerateDeinstallScript(c), "\10")
# --------------------- generate inno setup -----------------------------------
proc setupDist(c: var TConfigData) =
var scrpt = GenerateInnoSetup(c)
var n = "build" / "install_$#_$#.iss" % [toLower(c.name), c.version]
writeFile(n, scrpt, "\13\10")
when defined(windows):
if c.innoSetup.path.len == 0:
c.innoSetup.path = "iscc.exe"
var outcmd = if c.outdir.len == 0: "build" else: c.outdir
var cmd = "$# $# /O$# $#" % [quoteIfContainsWhite(c.innoSetup.path),
c.innoSetup.flags, outcmd, n]
Echo(cmd)
if execShellCmd(cmd) == 0:
removeFile(n)
else:
quit("External program failed")
# ------------------ generate ZIP file ---------------------------------------
when haveZipLib:
proc zipDist(c: var TConfigData) =
var proj = toLower(c.name)
var n = "$#_$#.zip" % [proj, c.version]
if c.outdir.len == 0: n = "build" / n
else: n = c.outdir / n
var z: TZipArchive
if open(z, n, fmWrite):
addFile(z, proj / buildBatFile, buildBatFile)
addFile(z, proj / buildShFile, buildShFile)
addFile(z, proj / installShFile, installShFile)
addFile(z, proj / deinstallShFile, deinstallShFile)
for f in walkFiles(c.libpath / "lib/*.h"):
addFile(z, proj / "build" / extractFilename(f), f)
for osA in 1..c.oses.len:
for cpuA in 1..c.cpus.len:
var dir = buildDir(osA, cpuA)
for k, f in walkDir(dir):
if k == pcFile: addFile(z, proj / dir / extractFilename(f), f)
for cat in items({fcConfig..fcOther, fcUnix}):
for f in items(c.cat[cat]): addFile(z, proj / f, f)
close(z)
else:
quit("Cannot open for writing: " & n)
# ------------------- main ----------------------------------------------------
var c: TConfigData
initConfigData(c)
parseCmdLine(c)
parseIniFile(c)
if actionInno in c.actions:
setupDist(c)
if actionCSource in c.actions:
srcdist(c)
if actionZip in c.actions:
when haveZipLib:
zipdist(c)
else:
quit("libzip is not installed")