Use proper quotes everywhere

This commit is contained in:
Eelco Dolstra 2014-08-20 17:00:17 +02:00
parent 373fad75e1
commit 11849a320e
54 changed files with 548 additions and 543 deletions

View file

@ -1,6 +1,7 @@
use strict; use strict;
use Cwd; use Cwd;
use IO::Handle; use IO::Handle;
use utf8;
STDOUT->autoflush(1); STDOUT->autoflush(1);
@ -53,18 +54,18 @@ sub createLinks {
elsif (-l _) { elsif (-l _) {
my $target = readlink $dstFile or die; my $target = readlink $dstFile or die;
if (!-d $target) { if (!-d $target) {
die "collision between directory `$srcFile' and non-directory `$target'"; die "collision between directory $srcFile and non-directory $target";
} }
unlink $dstFile or die "error unlinking `$dstFile': $!"; unlink $dstFile or die "error unlinking $dstFile: $!";
mkdir $dstFile, 0755 || mkdir $dstFile, 0755 ||
die "error creating directory `$dstFile': $!"; die "error creating directory $dstFile: $!";
createLinks($target, $dstFile, $priorities{$dstFile}); createLinks($target, $dstFile, $priorities{$dstFile});
createLinks($srcFile, $dstFile, $priority); createLinks($srcFile, $dstFile, $priority);
} }
else { else {
symlink($srcFile, $dstFile) || symlink($srcFile, $dstFile) ||
die "error creating link `$dstFile': $!"; die "error creating link $dstFile: $!";
$priorities{$dstFile} = $priority; $priorities{$dstFile} = $priority;
$symlinks++; $symlinks++;
} }
@ -75,17 +76,16 @@ sub createLinks {
if (-l $dstFile) { if (-l $dstFile) {
my $target = readlink $dstFile; my $target = readlink $dstFile;
my $prevPriority = $priorities{$dstFile}; my $prevPriority = $priorities{$dstFile};
die ( "collision between `$srcFile' and `$target'; " die("collision between $srcFile and $target; " .
. "use `nix-env --set-flag " "use nix-env --set-flag priority NUMBER PKGNAME " .
. "priority NUMBER PKGNAME' to change the priority of " "to change the priority of one of the conflicting packages\n")
. "one of the conflicting packages\n" )
if $prevPriority == $priority; if $prevPriority == $priority;
next if $prevPriority < $priority; next if $prevPriority < $priority;
unlink $dstFile or die; unlink $dstFile or die;
} }
symlink($srcFile, $dstFile) || symlink($srcFile, $dstFile) ||
die "error creating link `$dstFile': $!"; die "error creating link $dstFile: $!";
$priorities{$dstFile} = $priority; $priorities{$dstFile} = $priority;
$symlinks++; $symlinks++;
} }

View file

@ -31,7 +31,7 @@ sub readConfig {
my $config = "$confDir/nix.conf"; my $config = "$confDir/nix.conf";
return unless -f $config; return unless -f $config;
open CONFIG, "<$config" or die "cannot open `$config'"; open CONFIG, "<$config" or die "cannot open $config";
while (<CONFIG>) { while (<CONFIG>) {
/^\s*([\w\-\.]+)\s*=\s*(.*)$/ or next; /^\s*([\w\-\.]+)\s*=\s*(.*)$/ or next;
$config{$1} = $2; $config{$1} = $2;

View file

@ -1,5 +1,6 @@
package Nix::CopyClosure; package Nix::CopyClosure;
use utf8;
use strict; use strict;
use Nix::Config; use Nix::Config;
use Nix::Store; use Nix::Store;
@ -41,7 +42,7 @@ sub copyToOpen {
# Send the "import paths" command. # Send the "import paths" command.
syswrite($to, pack("L<x4", 4)) or die; syswrite($to, pack("L<x4", 4)) or die;
exportPaths(fileno($to), $sign, @missing); exportPaths(fileno($to), $sign, @missing);
readInt($from) == 1 or die "remote machine \`$sshHost' failed to import closure\n"; readInt($from) == 1 or die "remote machine $sshHost failed to import closure\n";
} }
@ -105,7 +106,7 @@ sub oldCopyTo {
unless ($dryRun) { unless ($dryRun) {
open SSH, "| ssh $sshHost @{$sshOpts} @globalSshOpts 'nix-store --import' > /dev/null" or die; open SSH, "| ssh $sshHost @{$sshOpts} @globalSshOpts 'nix-store --import' > /dev/null" or die;
exportPaths(fileno(SSH), $sign, @missing); exportPaths(fileno(SSH), $sign, @missing);
close SSH or die "copying store paths to remote machine `$sshHost' failed: $?"; close SSH or die "copying store paths to remote machine $sshHost failed: $?";
} }
} }
} }

View file

@ -1,5 +1,6 @@
package Nix::Manifest; package Nix::Manifest;
use utf8;
use strict; use strict;
use DBI; use DBI;
use DBD::SQLite; use DBD::SQLite;
@ -58,10 +59,10 @@ sub readManifest_ {
# Decompress the manifest if necessary. # Decompress the manifest if necessary.
if ($manifest =~ /\.bz2$/) { if ($manifest =~ /\.bz2$/) {
open MANIFEST, "$Nix::Config::bzip2 -d < $manifest |" open MANIFEST, "$Nix::Config::bzip2 -d < $manifest |"
or die "cannot decompress `$manifest': $!"; or die "cannot decompress $manifest: $!";
} else { } else {
open MANIFEST, "<$manifest" open MANIFEST, "<$manifest"
or die "cannot open `$manifest': $!"; or die "cannot open $manifest: $!";
} }
my $inside = 0; my $inside = 0;
@ -239,7 +240,7 @@ sub updateManifestDB {
# Open/create the database. # Open/create the database.
our $dbh = DBI->connect("dbi:SQLite:dbname=$dbPath", "", "") our $dbh = DBI->connect("dbi:SQLite:dbname=$dbPath", "", "")
or die "cannot open database `$dbPath'"; or die "cannot open database $dbPath";
$dbh->{RaiseError} = 1; $dbh->{RaiseError} = 1;
$dbh->{PrintError} = 0; $dbh->{PrintError} = 0;
@ -354,10 +355,10 @@ EOF
my $version = readManifest_($manifest, \&addNARToDB, \&addPatchToDB); my $version = readManifest_($manifest, \&addNARToDB, \&addPatchToDB);
if ($version < 3) { if ($version < 3) {
die "you have an old-style or corrupt manifest `$manifestLink'; please delete it\n"; die "you have an old-style or corrupt manifest $manifestLink; please delete it\n";
} }
if ($version >= 10) { if ($version >= 10) {
die "manifest `$manifestLink' is too new; please delete it or upgrade Nix\n"; die "manifest $manifestLink is too new; please delete it or upgrade Nix\n";
} }
} }
@ -434,27 +435,27 @@ sub parseNARInfo {
if ($requireValidSig) { if ($requireValidSig) {
if (!defined $sig) { if (!defined $sig) {
warn "NAR info file `$location' lacks a signature; ignoring\n"; warn "NAR info file $location lacks a signature; ignoring\n";
return undef; return undef;
} }
my ($sigVersion, $keyName, $sig64) = split ";", $sig; my ($sigVersion, $keyName, $sig64) = split ";", $sig;
$sigVersion //= 0; $sigVersion //= 0;
if ($sigVersion != 1) { if ($sigVersion != 1) {
warn "NAR info file `$location' has unsupported version $sigVersion; ignoring\n"; warn "NAR info file $location has unsupported version $sigVersion; ignoring\n";
return undef; return undef;
} }
return undef unless defined $keyName && defined $sig64; return undef unless defined $keyName && defined $sig64;
my $publicKeyFile = $Nix::Config::config{"binary-cache-public-key-$keyName"}; my $publicKeyFile = $Nix::Config::config{"binary-cache-public-key-$keyName"};
if (!defined $publicKeyFile) { if (!defined $publicKeyFile) {
warn "NAR info file `$location' is signed by unknown key `$keyName'; ignoring\n"; warn "NAR info file $location is signed by unknown key $keyName; ignoring\n";
return undef; return undef;
} }
if (! -f $publicKeyFile) { if (! -f $publicKeyFile) {
die "binary cache public key file `$publicKeyFile' does not exist\n"; die "binary cache public key file $publicKeyFile does not exist\n";
return undef; return undef;
} }
if (!isValidSignature($publicKeyFile, $sig64, $signedData)) { if (!isValidSignature($publicKeyFile, $sig64, $signedData)) {
warn "NAR info file `$location' has an invalid signature; ignoring\n"; warn "NAR info file $location has an invalid signature; ignoring\n";
return undef; return undef;
} }
$res->{signedBy} = $keyName; $res->{signedBy} = $keyName;

View file

@ -1,5 +1,6 @@
package Nix::Utils; package Nix::Utils;
use utf8;
use File::Temp qw(tempdir); use File::Temp qw(tempdir);
our @ISA = qw(Exporter); our @ISA = qw(Exporter);
@ -25,7 +26,7 @@ sub uniq {
sub writeFile { sub writeFile {
my ($fn, $s) = @_; my ($fn, $s) = @_;
open TMP, ">$fn" or die "cannot create file `$fn': $!"; open TMP, ">$fn" or die "cannot create file $fn: $!";
print TMP "$s" or die; print TMP "$s" or die;
close TMP or die; close TMP or die;
} }
@ -33,7 +34,7 @@ sub writeFile {
sub readFile { sub readFile {
local $/ = undef; local $/ = undef;
my ($fn) = @_; my ($fn) = @_;
open TMP, "<$fn" or die "cannot open file `$fn': $!"; open TMP, "<$fn" or die "cannot open file $fn: $!";
my $s = <TMP>; my $s = <TMP>;
close TMP or die; close TMP or die;
return $s; return $s;

View file

@ -202,7 +202,7 @@ REQ: while (1) {
}; };
last REQ unless $@; last REQ unless $@;
print STDERR "$@"; print STDERR "$@";
warn "unable to open SSH connection to `$hostName', trying other available machines...\n"; warn "unable to open SSH connection to $hostName, trying other available machines...\n";
$from = undef; $from = undef;
$to = undef; $to = undef;
$machine->{enabled} = 0; $machine->{enabled} = 0;
@ -251,7 +251,7 @@ close UPLOADLOCK;
# Perform the build. # Perform the build.
print STDERR "building `$drvPath' on `$hostName'\n"; print STDERR "building $drvPath on $hostName\n";
writeInt(6, $to) or die; # == cmdBuildPaths writeInt(6, $to) or die; # == cmdBuildPaths
writeStrings([$drvPath], $to); writeStrings([$drvPath], $to);
writeInt($maxSilentTime, $to); writeInt($maxSilentTime, $to);
@ -259,7 +259,7 @@ writeInt($buildTimeout, $to);
my $res = readInt($from); my $res = readInt($from);
if ($res != 0) { if ($res != 0) {
my $msg = readString($from); my $msg = readString($from);
print STDERR "error: $msg on `$hostName'\n"; print STDERR "error: $msg on $hostName\n";
exit $res; exit $res;
} }

View file

@ -1,5 +1,6 @@
#! @perl@ -w @perlFlags@ #! @perl@ -w @perlFlags@
use utf8;
use strict; use strict;
use File::Basename; use File::Basename;
use IO::Handle; use IO::Handle;
@ -57,16 +58,16 @@ if ($ARGV[0] eq "--query") {
$ENV{"NIX_DB_DIR"} = "$store/var/nix/db"; $ENV{"NIX_DB_DIR"} = "$store/var/nix/db";
my $deriver = `$binDir/nix-store --query --deriver $storePath`; my $deriver = `$binDir/nix-store --query --deriver $storePath`;
die "cannot query deriver of `$storePath'" if $? != 0; die "cannot query deriver of $storePath" if $? != 0;
chomp $deriver; chomp $deriver;
$deriver = "" if $deriver eq "unknown-deriver"; $deriver = "" if $deriver eq "unknown-deriver";
my @references = split "\n", my @references = split "\n",
`$binDir/nix-store --query --references $storePath`; `$binDir/nix-store --query --references $storePath`;
die "cannot query references of `$storePath'" if $? != 0; die "cannot query references of $storePath" if $? != 0;
my $narSize = `$binDir/nix-store --query --size $storePath`; my $narSize = `$binDir/nix-store --query --size $storePath`;
die "cannot query size of `$storePath'" if $? != 0; die "cannot query size of $storePath" if $? != 0;
chomp $narSize; chomp $narSize;
print "$storePath\n"; print "$storePath\n";
@ -80,7 +81,7 @@ if ($ARGV[0] eq "--query") {
print "\n"; print "\n";
} }
else { die "unknown command `$cmd'"; } else { die "unknown command $cmd"; }
} }
} }
@ -91,9 +92,9 @@ elsif ($ARGV[0] eq "--substitute") {
my $destPath = $ARGV[2]; my $destPath = $ARGV[2];
my ($store, $sourcePath) = findStorePath $storePath; my ($store, $sourcePath) = findStorePath $storePath;
die unless $store; die unless $store;
print STDERR "\n*** Copying `$storePath' from `$sourcePath'\n\n"; print STDERR "\n*** Copying $storePath from $sourcePath\n\n";
system("$binDir/nix-store --dump $sourcePath | $binDir/nix-store --restore $destPath") == 0 system("$binDir/nix-store --dump $sourcePath | $binDir/nix-store --restore $destPath") == 0
or die "cannot copy `$sourcePath' to `$storePath'"; or die "cannot copy $sourcePath to $storePath";
print "\n"; # no hash to verify print "\n"; # no hash to verify
} }

View file

@ -134,7 +134,7 @@ sub initCache {
# Open/create the database. # Open/create the database.
$dbh = DBI->connect("dbi:SQLite:dbname=$dbPath", "", "") $dbh = DBI->connect("dbi:SQLite:dbname=$dbPath", "", "")
or die "cannot open database `$dbPath'"; or die "cannot open database $dbPath";
$dbh->{RaiseError} = 1; $dbh->{RaiseError} = 1;
$dbh->{PrintError} = 0; $dbh->{PrintError} = 0;
@ -544,7 +544,7 @@ sub downloadBinary {
print STDERR "\n*** Downloading $url ", ($requireSignedBinaryCaches ? "(signed by $info->{signedBy}) " : ""), "to $storePath...\n"; print STDERR "\n*** Downloading $url ", ($requireSignedBinaryCaches ? "(signed by $info->{signedBy}) " : ""), "to $storePath...\n";
checkURL $url; checkURL $url;
if (system("$Nix::Config::curl --fail --location --insecure --connect-timeout $curlConnectTimeout '$url' $decompressor | $Nix::Config::binDir/nix-store --restore $destPath") != 0) { if (system("$Nix::Config::curl --fail --location --insecure --connect-timeout $curlConnectTimeout '$url' $decompressor | $Nix::Config::binDir/nix-store --restore $destPath") != 0) {
warn "download of `$url' failed" . ($! ? ": $!" : "") . "\n"; warn "download of $url failed" . ($! ? ": $!" : "") . "\n";
next; next;
} }
@ -590,7 +590,7 @@ if ($ARGV[0] eq "--query") {
print "\n"; print "\n";
} }
else { die "unknown command `$cmd'"; } else { die "unknown command $cmd"; }
flush STDOUT; flush STDOUT;
} }

View file

@ -1,5 +1,6 @@
#! @perl@ -w @perlFlags@ #! @perl@ -w @perlFlags@
use utf8;
use strict; use strict;
use Nix::Config; use Nix::Config;
use Nix::Manifest; use Nix::Manifest;
@ -228,7 +229,7 @@ if ($ARGV[0] eq "--query") {
print "\n"; print "\n";
} }
else { die "unknown command `$cmd'"; } else { die "unknown command $cmd"; }
} }
exit 0; exit 0;
@ -257,7 +258,7 @@ open LOGFILE, ">>$logFile" or die "cannot open log file $logFile";
my $date = strftime ("%F %H:%M:%S UTC", gmtime (time)); my $date = strftime ("%F %H:%M:%S UTC", gmtime (time));
print LOGFILE "$$ get $targetPath $date\n"; print LOGFILE "$$ get $targetPath $date\n";
print STDERR "\n*** Trying to download/patch `$targetPath'\n"; print STDERR "\n*** Trying to download/patch $targetPath\n";
# Compute the shortest path. # Compute the shortest path.
@ -286,7 +287,7 @@ while (scalar @path > 0) {
print STDERR "\n*** Step $curStep/$maxStep: "; print STDERR "\n*** Step $curStep/$maxStep: ";
if ($edge->{type} eq "present") { if ($edge->{type} eq "present") {
print STDERR "using already present path `$v'\n"; print STDERR "using already present path $v\n";
print LOGFILE "$$ present $v\n"; print LOGFILE "$$ present $v\n";
if ($curStep < $maxStep) { if ($curStep < $maxStep) {
@ -295,13 +296,13 @@ while (scalar @path > 0) {
# into a NAR archive, to which we can apply the patch. # into a NAR archive, to which we can apply the patch.
print STDERR " packing base path...\n"; print STDERR " packing base path...\n";
system("$Nix::Config::binDir/nix-store --dump $v > $tmpNar") == 0 system("$Nix::Config::binDir/nix-store --dump $v > $tmpNar") == 0
or die "cannot dump `$v'"; or die "cannot dump $v";
} }
} }
elsif ($edge->{type} eq "patch") { elsif ($edge->{type} eq "patch") {
my $patch = $edge->{info}; my $patch = $edge->{info};
print STDERR "applying patch `$patch->{url}' to `$u' to create `$v'\n"; print STDERR "applying patch $patch->{url} to $u to create $v\n";
print LOGFILE "$$ patch $patch->{url} $patch->{size} $patch->{baseHash} $u $v\n"; print LOGFILE "$$ patch $patch->{url} $patch->{size} $patch->{baseHash} $u $v\n";
@ -310,13 +311,13 @@ while (scalar @path > 0) {
my $patchPath = "$tmpDir/patch"; my $patchPath = "$tmpDir/patch";
checkURL $patch->{url}; checkURL $patch->{url};
system("$curl '$patch->{url}' -o $patchPath") == 0 system("$curl '$patch->{url}' -o $patchPath") == 0
or die "cannot download patch `$patch->{url}'\n"; or die "cannot download patch $patch->{url}\n";
# Apply the patch to the NAR archive produced in step 1 (for # Apply the patch to the NAR archive produced in step 1 (for
# the already present path) or a later step (for patch sequences). # the already present path) or a later step (for patch sequences).
print STDERR " applying patch...\n"; print STDERR " applying patch...\n";
system("$Nix::Config::libexecDir/nix/bspatch $tmpNar $tmpNar2 $patchPath") == 0 system("$Nix::Config::libexecDir/nix/bspatch $tmpNar $tmpNar2 $patchPath") == 0
or die "cannot apply patch `$patchPath' to $tmpNar\n"; or die "cannot apply patch $patchPath to $tmpNar\n";
if ($curStep < $maxStep) { if ($curStep < $maxStep) {
# The archive will be used as the base of the next patch. # The archive will be used as the base of the next patch.
@ -326,7 +327,7 @@ while (scalar @path > 0) {
# into the target path. # into the target path.
print STDERR " unpacking patched archive...\n"; print STDERR " unpacking patched archive...\n";
system("$Nix::Config::binDir/nix-store --restore $destPath < $tmpNar2") == 0 system("$Nix::Config::binDir/nix-store --restore $destPath < $tmpNar2") == 0
or die "cannot unpack $tmpNar2 to `$v'\n"; or die "cannot unpack $tmpNar2 to $v\n";
} }
$finalNarHash = $patch->{narHash}; $finalNarHash = $patch->{narHash};
@ -334,7 +335,7 @@ while (scalar @path > 0) {
elsif ($edge->{type} eq "narfile") { elsif ($edge->{type} eq "narfile") {
my $narFile = $edge->{info}; my $narFile = $edge->{info};
print STDERR "downloading `$narFile->{url}' to `$v'\n"; print STDERR "downloading $narFile->{url} to $v\n";
my $size = $narFile->{size} || -1; my $size = $narFile->{size} || -1;
print LOGFILE "$$ narfile $narFile->{url} $size $v\n"; print LOGFILE "$$ narfile $narFile->{url} $size $v\n";
@ -345,16 +346,16 @@ while (scalar @path > 0) {
$narFile->{compressionType} eq "bzip2" ? "| $Nix::Config::bzip2 -d" : $narFile->{compressionType} eq "bzip2" ? "| $Nix::Config::bzip2 -d" :
$narFile->{compressionType} eq "xz" ? "| $Nix::Config::xz -d" : $narFile->{compressionType} eq "xz" ? "| $Nix::Config::xz -d" :
$narFile->{compressionType} eq "none" ? "" : $narFile->{compressionType} eq "none" ? "" :
die "unknown compression type `$narFile->{compressionType}'"; die "unknown compression type $narFile->{compressionType}";
if ($curStep < $maxStep) { if ($curStep < $maxStep) {
# The archive will be used a base to a patch. # The archive will be used a base to a patch.
system("$curl '$narFile->{url}' $decompressor > $tmpNar") == 0 system("$curl '$narFile->{url}' $decompressor > $tmpNar") == 0
or die "cannot download and unpack `$narFile->{url}' to `$v'\n"; or die "cannot download and unpack $narFile->{url} to $v\n";
} else { } else {
# Unpack the archive to the target path. # Unpack the archive to the target path.
system("$curl '$narFile->{url}' $decompressor | $Nix::Config::binDir/nix-store --restore '$destPath'") == 0 system("$curl '$narFile->{url}' $decompressor | $Nix::Config::binDir/nix-store --restore '$destPath'") == 0
or die "cannot download and unpack `$narFile->{url}' to `$v'\n"; or die "cannot download and unpack $narFile->{url} to $v\n";
} }
$finalNarHash = $narFile->{narHash}; $finalNarHash = $narFile->{narHash};

View file

@ -24,15 +24,15 @@ echo "performing a single-user installation of Nix..." >&2
if ! [ -e $dest ]; then if ! [ -e $dest ]; then
cmd="mkdir -m 0755 $dest && chown $USER $dest" cmd="mkdir -m 0755 $dest && chown $USER $dest"
echo "directory $dest does not exist; creating it by running \`$cmd' using sudo" >&2 echo "directory $dest does not exist; creating it by running $cmd using sudo" >&2
if ! sudo sh -c "$cmd"; then if ! sudo sh -c "$cmd"; then
echo "$0: please manually run \`$cmd' as root to create $dest" >&2 echo "$0: please manually run $cmd as root to create $dest" >&2
exit 1 exit 1
fi fi
fi fi
if ! [ -w $dest ]; then if ! [ -w $dest ]; then
echo "$0: directory $dest exists, but is not writable by you; please run \`chown -R $USER $dest' as root" >&2 echo "$0: directory $dest exists, but is not writable by you; please run chown -R $USER $dest as root" >&2
exit 1 exit 1
fi fi

View file

@ -55,37 +55,37 @@ for (my $n = 0; $n < scalar @ARGV; $n++) {
elsif ($arg eq "--drv-link") { elsif ($arg eq "--drv-link") {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
$drvLink = $ARGV[$n]; $drvLink = $ARGV[$n];
} }
elsif ($arg eq "--out-link" || $arg eq "-o") { elsif ($arg eq "--out-link" || $arg eq "-o") {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
$outLink = $ARGV[$n]; $outLink = $ARGV[$n];
} }
elsif ($arg eq "--attr" || $arg eq "-A" || $arg eq "-I") { elsif ($arg eq "--attr" || $arg eq "-A" || $arg eq "-I") {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
push @instArgs, ($arg, $ARGV[$n]); push @instArgs, ($arg, $ARGV[$n]);
} }
elsif ($arg eq "--arg" || $arg eq "--argstr") { elsif ($arg eq "--arg" || $arg eq "--argstr") {
die "$0: `$arg' requires two arguments\n" unless $n + 2 < scalar @ARGV; die "$0: $arg requires two arguments\n" unless $n + 2 < scalar @ARGV;
push @instArgs, ($arg, $ARGV[$n + 1], $ARGV[$n + 2]); push @instArgs, ($arg, $ARGV[$n + 1], $ARGV[$n + 2]);
$n += 2; $n += 2;
} }
elsif ($arg eq "--log-type") { elsif ($arg eq "--log-type") {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
push @instArgs, ($arg, $ARGV[$n]); push @instArgs, ($arg, $ARGV[$n]);
push @buildArgs, ($arg, $ARGV[$n]); push @buildArgs, ($arg, $ARGV[$n]);
} }
elsif ($arg eq "--option") { elsif ($arg eq "--option") {
die "$0: `$arg' requires two arguments\n" unless $n + 2 < scalar @ARGV; die "$0: $arg requires two arguments\n" unless $n + 2 < scalar @ARGV;
push @instArgs, ($arg, $ARGV[$n + 1], $ARGV[$n + 2]); push @instArgs, ($arg, $ARGV[$n + 1], $ARGV[$n + 2]);
push @buildArgs, ($arg, $ARGV[$n + 1], $ARGV[$n + 2]); push @buildArgs, ($arg, $ARGV[$n + 1], $ARGV[$n + 2]);
$n += 2; $n += 2;
@ -93,7 +93,7 @@ for (my $n = 0; $n < scalar @ARGV; $n++) {
elsif ($arg eq "--max-jobs" || $arg eq "-j" || $arg eq "--max-silent-time" || $arg eq "--log-type" || $arg eq "--cores" || $arg eq "--timeout" || $arg eq '--add-root') { elsif ($arg eq "--max-jobs" || $arg eq "-j" || $arg eq "--max-silent-time" || $arg eq "--log-type" || $arg eq "--cores" || $arg eq "--timeout" || $arg eq '--add-root') {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
push @buildArgs, ($arg, $ARGV[$n]); push @buildArgs, ($arg, $ARGV[$n]);
} }
@ -131,13 +131,13 @@ for (my $n = 0; $n < scalar @ARGV; $n++) {
elsif ($arg eq "--command") { elsif ($arg eq "--command") {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
$envCommand = "$ARGV[$n]\nexit $!"; $envCommand = "$ARGV[$n]\nexit $!";
} }
elsif ($arg eq "--exclude") { elsif ($arg eq "--exclude") {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
push @envExclude, $ARGV[$n]; push @envExclude, $ARGV[$n];
} }
@ -195,7 +195,7 @@ foreach my $expr (@exprs) {
die "$0: a single derivation is required\n" if scalar @drvPaths != 1; die "$0: a single derivation is required\n" if scalar @drvPaths != 1;
my $drvPath = $drvPaths[0]; my $drvPath = $drvPaths[0];
$drvPath = (split '!',$drvPath)[0]; $drvPath = (split '!',$drvPath)[0];
$drvPath = readlink $drvPath or die "cannot read symlink `$drvPath'" if -l $drvPath; $drvPath = readlink $drvPath or die "cannot read symlink $drvPath" if -l $drvPath;
my $drv = derivationFromPath($drvPath); my $drv = derivationFromPath($drvPath);
# Build or fetch all dependencies of the derivation. # Build or fetch all dependencies of the derivation.
@ -257,7 +257,7 @@ foreach my $expr (@exprs) {
} else { } else {
$p = $drvPath; $p = $drvPath;
} }
my $target = readlink $p or die "cannot read symlink `$p'"; my $target = readlink $p or die "cannot read symlink $p";
print STDERR "derivation is $target\n" if $verbose; print STDERR "derivation is $target\n" if $verbose;
if ($target eq $prevDrvPath) { if ($target eq $prevDrvPath) {
push @drvPaths2, (pop @drvPaths2) . "," . $output; push @drvPaths2, (pop @drvPaths2) . "," . $output;
@ -280,7 +280,7 @@ foreach my $expr (@exprs) {
next if $dryRun; next if $dryRun;
foreach my $outPath (@outPaths) { foreach my $outPath (@outPaths) {
my $target = readlink $outPath or die "cannot read symlink `$outPath'"; my $target = readlink $outPath or die "cannot read symlink $outPath";
print "$target\n"; print "$target\n";
} }
} }

View file

@ -32,7 +32,7 @@ my %channels;
# Reads the list of channels. # Reads the list of channels.
sub readChannels { sub readChannels {
return if (!-f $channelsList); return if (!-f $channelsList);
open CHANNELS, "<$channelsList" or die "cannot open `$channelsList': $!"; open CHANNELS, "<$channelsList" or die "cannot open $channelsList: $!";
while (<CHANNELS>) { while (<CHANNELS>) {
chomp; chomp;
next if /^\s*\#/; next if /^\s*\#/;
@ -47,7 +47,7 @@ sub readChannels {
# Writes the list of channels. # Writes the list of channels.
sub writeChannels { sub writeChannels {
open CHANNELS, ">$channelsList" or die "cannot open `$channelsList': $!"; open CHANNELS, ">$channelsList" or die "cannot open $channelsList: $!";
foreach my $name (keys %channels) { foreach my $name (keys %channels) {
print CHANNELS "$channels{$name} $name\n"; print CHANNELS "$channels{$name} $name\n";
} }
@ -74,7 +74,7 @@ sub removeChannel {
writeChannels; writeChannels;
system("$Nix::Config::binDir/nix-env --profile '$profile' -e '$name'") == 0 system("$Nix::Config::binDir/nix-env --profile '$profile' -e '$name'") == 0
or die "cannot remove channel `$name'\n"; or die "cannot remove channel $name\n";
} }
@ -97,7 +97,7 @@ sub update {
# consistency if the redirection is changed between # consistency if the redirection is changed between
# downloading the manifest and the tarball. # downloading the manifest and the tarball.
my $headers = `$Nix::Config::curl --silent --head '$url'`; my $headers = `$Nix::Config::curl --silent --head '$url'`;
die "$0: unable to check `$url'\n" if $? != 0; die "$0: unable to check $url\n" if $? != 0;
$headers =~ s/\r//g; $headers =~ s/\r//g;
$url = $1 if $headers =~ /^Location:\s*(.*)\s*$/m; $url = $1 if $headers =~ /^Location:\s*(.*)\s*$/m;
@ -115,19 +115,19 @@ sub update {
if ($getManifest) { if ($getManifest) {
# No binary cache, so pull the channel manifest. # No binary cache, so pull the channel manifest.
mkdir $manifestDir, 0755 unless -e $manifestDir; mkdir $manifestDir, 0755 unless -e $manifestDir;
die "$0: you do not have write permission to `$manifestDir'!\n" unless -W $manifestDir; die "$0: you do not have write permission to $manifestDir!\n" unless -W $manifestDir;
$ENV{'NIX_ORIG_URL'} = $origUrl; $ENV{'NIX_ORIG_URL'} = $origUrl;
system("$Nix::Config::binDir/nix-pull", "--skip-wrong-store", "$url/MANIFEST") == 0 system("$Nix::Config::binDir/nix-pull", "--skip-wrong-store", "$url/MANIFEST") == 0
or die "cannot pull manifest from `$url'\n"; or die "cannot pull manifest from $url\n";
} }
# Download the channel tarball. # Download the channel tarball.
my $fullURL = "$url/nixexprs.tar.xz"; my $fullURL = "$url/nixexprs.tar.xz";
system("$Nix::Config::curl --fail --silent --head '$fullURL' > /dev/null") == 0 or system("$Nix::Config::curl --fail --silent --head '$fullURL' > /dev/null") == 0 or
$fullURL = "$url/nixexprs.tar.bz2"; $fullURL = "$url/nixexprs.tar.bz2";
print STDERR "downloading Nix expressions from `$fullURL'...\n"; print STDERR "downloading Nix expressions from $fullURL...\n";
my ($hash, $path) = `PRINT_PATH=1 QUIET=1 $Nix::Config::binDir/nix-prefetch-url '$fullURL'`; my ($hash, $path) = `PRINT_PATH=1 QUIET=1 $Nix::Config::binDir/nix-prefetch-url '$fullURL'`;
die "cannot fetch `$fullURL'\n" if $? != 0; die "cannot fetch $fullURL\n" if $? != 0;
chomp $path; chomp $path;
# If the URL contains a version number, append it to the name # If the URL contains a version number, append it to the name
@ -148,10 +148,10 @@ sub update {
# Make the channels appear in nix-env. # Make the channels appear in nix-env.
unlink $nixDefExpr if -l $nixDefExpr; # old-skool ~/.nix-defexpr unlink $nixDefExpr if -l $nixDefExpr; # old-skool ~/.nix-defexpr
mkdir $nixDefExpr or die "cannot create directory `$nixDefExpr'" if !-e $nixDefExpr; mkdir $nixDefExpr or die "cannot create directory $nixDefExpr" if !-e $nixDefExpr;
my $channelLink = "$nixDefExpr/channels"; my $channelLink = "$nixDefExpr/channels";
unlink $channelLink; # !!! not atomic unlink $channelLink; # !!! not atomic
symlink($profile, $channelLink) or die "cannot symlink `$channelLink' to `$profile'"; symlink($profile, $channelLink) or die "cannot symlink $channelLink to $profile";
} }
@ -162,7 +162,7 @@ while (scalar @ARGV) {
my $arg = shift @ARGV; my $arg = shift @ARGV;
if ($arg eq "--add") { if ($arg eq "--add") {
die "$0: `--add' requires one or two arguments\n" if scalar @ARGV < 1 || scalar @ARGV > 2; die "$0: --add requires one or two arguments\n" if scalar @ARGV < 1 || scalar @ARGV > 2;
my $url = shift @ARGV; my $url = shift @ARGV;
my $name = shift @ARGV; my $name = shift @ARGV;
unless (defined $name) { unless (defined $name) {
@ -175,13 +175,13 @@ while (scalar @ARGV) {
} }
if ($arg eq "--remove") { if ($arg eq "--remove") {
die "$0: `--remove' requires one argument\n" if scalar @ARGV != 1; die "$0: --remove requires one argument\n" if scalar @ARGV != 1;
removeChannel(shift @ARGV); removeChannel(shift @ARGV);
last; last;
} }
if ($arg eq "--list") { if ($arg eq "--list") {
die "$0: `--list' requires one argument\n" if scalar @ARGV != 0; die "$0: --list requires one argument\n" if scalar @ARGV != 0;
readChannels; readChannels;
foreach my $name (keys %channels) { foreach my $name (keys %channels) {
print "$name $channels{$name}\n"; print "$name $channels{$name}\n";
@ -204,6 +204,6 @@ while (scalar @ARGV) {
} }
else { else {
die "unknown argument `$arg'; try `--help'\n"; die "unknown argument $arg; try --help\n";
} }
} }

View file

@ -38,7 +38,7 @@ while (@ARGV) {
$sign = 1; $sign = 1;
} }
elsif ($arg eq "--gzip" || $arg eq "--bzip2" || $arg eq "--xz") { elsif ($arg eq "--gzip" || $arg eq "--bzip2" || $arg eq "--xz") {
warn "$0: `$arg' is not implemented\n" if $arg ne "--gzip"; warn "$0: $arg is not implemented\n" if $arg ne "--gzip";
push @globalSshOpts, "-C"; push @globalSshOpts, "-C";
} }
elsif ($arg eq "--from") { elsif ($arg eq "--from") {
@ -51,7 +51,7 @@ while (@ARGV) {
$includeOutputs = 1; $includeOutputs = 1;
} }
elsif ($arg eq "--show-progress") { elsif ($arg eq "--show-progress") {
warn "$0: `$arg' is not implemented\n"; warn "$0: $arg is not implemented\n";
} }
elsif ($arg eq "--dry-run") { elsif ($arg eq "--dry-run") {
$dryRun = 1; $dryRun = 1;

View file

@ -23,7 +23,7 @@ while (scalar @args) {
} }
elsif ($arg eq "--profile" || $arg eq "-p") { elsif ($arg eq "--profile" || $arg eq "-p") {
my $profile = shift @args; my $profile = shift @args;
die "$0: `--profile' requires an argument\n" if !defined $profile; die "$0: --profile requires an argument\n" if !defined $profile;
push @extraNixEnvArgs, "-p", $profile; push @extraNixEnvArgs, "-p", $profile;
} }
elsif ($arg eq "--non-interactive") { elsif ($arg eq "--non-interactive") {
@ -45,7 +45,7 @@ if ($interactive && !defined $ENV{"NIX_HAVE_TERMINAL"}) {
foreach my $term ("xterm", "konsole", "gnome-terminal", "xterm") { foreach my $term ("xterm", "konsole", "gnome-terminal", "xterm") {
exec($term, "-e", "$Nix::Config::binDir/nix-install-package", @ARGV); exec($term, "-e", "$Nix::Config::binDir/nix-install-package", @ARGV);
} }
die "cannot execute `xterm'"; die "cannot execute xterm";
} }
@ -70,7 +70,7 @@ if ($fromURL) {
# Read and parse the package file. # Read and parse the package file.
open PKGFILE, "<$pkgFile" or barf "cannot open `$pkgFile': $!"; open PKGFILE, "<$pkgFile" or barf "cannot open $pkgFile: $!";
my $contents = <PKGFILE>; my $contents = <PKGFILE>;
close PKGFILE; close PKGFILE;
@ -92,12 +92,12 @@ my $drvPath = $5;
my $outPath = $6; my $outPath = $6;
my $binaryCacheURL = $8; my $binaryCacheURL = $8;
barf "invalid package version `$version'" unless $version eq "NIXPKG1"; barf "invalid package version $version" unless $version eq "NIXPKG1";
if ($interactive) { if ($interactive) {
# Ask confirmation. # Ask confirmation.
print "Do you want to install `$drvName' (Y/N)? "; print "Do you want to install $drvName (Y/N)? ";
my $reply = <STDIN>; my $reply = <STDIN>;
chomp $reply; chomp $reply;
exit if $reply ne "y" && $reply ne "Y"; exit if $reply ne "y" && $reply ne "Y";

View file

@ -17,9 +17,9 @@ while ($arg = shift) {
exec "man nix-prefetch-url" or die; exec "man nix-prefetch-url" or die;
} elsif ($arg eq "--type") { } elsif ($arg eq "--type") {
$hashType = shift; $hashType = shift;
die "$0: `$arg' requires an argument\n" unless defined $hashType; die "$0: $arg requires an argument\n" unless defined $hashType;
} elsif (substr($arg, 0, 1) eq "-") { } elsif (substr($arg, 0, 1) eq "-") {
die "$0: unknown flag `$arg'\n"; die "$0: unknown flag $arg\n";
} else { } else {
push @args, $arg; push @args, $arg;
} }

View file

@ -13,7 +13,7 @@ umask 0022;
# Create the manifests directory if it doesn't exist. # Create the manifests directory if it doesn't exist.
if (! -e $manifestDir) { if (! -e $manifestDir) {
mkdir $manifestDir, 0755 or die "cannot create directory `$manifestDir'"; mkdir $manifestDir, 0755 or die "cannot create directory $manifestDir";
} }
@ -21,7 +21,7 @@ if (! -e $manifestDir) {
my $gcRootsDir = "$Nix::Config::stateDir/gcroots"; my $gcRootsDir = "$Nix::Config::stateDir/gcroots";
my $manifestDirLink = "$gcRootsDir/manifests"; my $manifestDirLink = "$gcRootsDir/manifests";
if (! -l $manifestDirLink) { if (! -l $manifestDirLink) {
symlink($manifestDir, $manifestDirLink) or die "cannot create symlink `$manifestDirLink'"; symlink($manifestDir, $manifestDirLink) or die "cannot create symlink $manifestDirLink";
} }
@ -32,7 +32,7 @@ sub downloadFile {
$ENV{"PRINT_PATH"} = 1; $ENV{"PRINT_PATH"} = 1;
$ENV{"QUIET"} = 1; $ENV{"QUIET"} = 1;
my ($dummy, $path) = `$Nix::Config::binDir/nix-prefetch-url '$url'`; my ($dummy, $path) = `$Nix::Config::binDir/nix-prefetch-url '$url'`;
die "cannot fetch `$url'" if $? != 0; die "cannot fetch $url" if $? != 0;
die "nix-prefetch-url did not return a path" unless defined $path; die "nix-prefetch-url did not return a path" unless defined $path;
chomp $path; chomp $path;
return $path; return $path;
@ -49,13 +49,13 @@ sub processURL {
# First see if a bzipped manifest is available. # First see if a bzipped manifest is available.
if (system("$Nix::Config::curl --fail --silent --location --head '$url'.bz2 > /dev/null") == 0) { if (system("$Nix::Config::curl --fail --silent --location --head '$url'.bz2 > /dev/null") == 0) {
print "fetching list of Nix archives at `$url.bz2'...\n"; print "fetching list of Nix archives at $url.bz2...\n";
$manifest = downloadFile "$url.bz2"; $manifest = downloadFile "$url.bz2";
} }
# Otherwise, just get the uncompressed manifest. # Otherwise, just get the uncompressed manifest.
else { else {
print "fetching list of Nix archives at `$url'...\n"; print "fetching list of Nix archives at $url...\n";
$manifest = downloadFile $url; $manifest = downloadFile $url;
} }
@ -65,11 +65,11 @@ sub processURL {
} }
my $hash = `$Nix::Config::binDir/nix-hash --flat '$manifest'` my $hash = `$Nix::Config::binDir/nix-hash --flat '$manifest'`
or die "cannot hash `$manifest'"; or die "cannot hash $manifest";
chomp $hash; chomp $hash;
my $urlFile = "$manifestDir/$baseName-$hash.url"; my $urlFile = "$manifestDir/$baseName-$hash.url";
open URL, ">$urlFile" or die "cannot create `$urlFile'"; open URL, ">$urlFile" or die "cannot create $urlFile";
print URL $origUrl; print URL $origUrl;
close URL; close URL;
@ -78,7 +78,7 @@ sub processURL {
unlink $finalPath if -e $finalPath; unlink $finalPath if -e $finalPath;
symlink("$manifest", "$finalPath") symlink("$manifest", "$finalPath")
or die "cannot link `$finalPath to `$manifest'"; or die "cannot link $finalPath to $manifest";
deleteOldManifests($origUrl, $urlFile); deleteOldManifests($origUrl, $urlFile);
} }

View file

@ -41,33 +41,33 @@ for (my $n = 0; $n < scalar @ARGV; $n++) {
$force = 1; $force = 1;
} elsif ($arg eq "--dest") { } elsif ($arg eq "--dest") {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
$destDir = $ARGV[$n]; $destDir = $ARGV[$n];
mkpath($destDir, 0, 0755); mkpath($destDir, 0, 0755);
} elsif ($arg eq "--manifest") { } elsif ($arg eq "--manifest") {
$writeManifest = 1; $writeManifest = 1;
} elsif ($arg eq "--manifest-path") { } elsif ($arg eq "--manifest-path") {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
$manifestPath = $ARGV[$n]; $manifestPath = $ARGV[$n];
$writeManifest = 1; $writeManifest = 1;
mkpath(dirname($manifestPath), 0, 0755); mkpath(dirname($manifestPath), 0, 0755);
} elsif ($arg eq "--url-prefix") { } elsif ($arg eq "--url-prefix") {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
$archivesURL = $ARGV[$n]; $archivesURL = $ARGV[$n];
} elsif ($arg eq "--link") { } elsif ($arg eq "--link") {
$link = 1; $link = 1;
} elsif ($arg eq "--key") { } elsif ($arg eq "--key") {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
$privateKeyFile = $ARGV[$n]; $privateKeyFile = $ARGV[$n];
} elsif ($arg eq "--key-name") { } elsif ($arg eq "--key-name") {
$n++; $n++;
die "$0: `$arg' requires an argument\n" unless $n < scalar @ARGV; die "$0: $arg requires an argument\n" unless $n < scalar @ARGV;
$keyName = $ARGV[$n]; $keyName = $ARGV[$n];
} elsif (substr($arg, 0, 1) eq "-") { } elsif (substr($arg, 0, 1) eq "-") {
die "$0: unknown flag `$arg'\n"; die "$0: unknown flag $arg\n";
} else { } else {
push @roots, $arg; push @roots, $arg;
} }
@ -108,7 +108,7 @@ foreach my $storePath (@storePaths) {
my $pathHash = substr(basename($storePath), 0, 32); my $pathHash = substr(basename($storePath), 0, 32);
my $narInfoFile = "$destDir/$pathHash.narinfo"; my $narInfoFile = "$destDir/$pathHash.narinfo";
if (-e $narInfoFile) { if (-e $narInfoFile) {
my $narInfo = parseNARInfo($storePath, readFile($narInfoFile), 0, $narInfoFile) or die "cannot read `$narInfoFile'\n"; my $narInfo = parseNARInfo($storePath, readFile($narInfoFile), 0, $narInfoFile) or die "cannot read $narInfoFile\n";
my $narFile = "$destDir/$narInfo->{url}"; my $narFile = "$destDir/$narInfo->{url}";
if (-e $narFile) { if (-e $narFile) {
print STDERR "skipping existing $storePath\n"; print STDERR "skipping existing $storePath\n";
@ -197,7 +197,7 @@ for (my $n = 0; $n < scalar @storePaths2; $n++) {
system("$Nix::Config::binDir/nix-store --dump $storePath > $nar") == 0 system("$Nix::Config::binDir/nix-store --dump $storePath > $nar") == 0
or die "cannot dump $storePath\n"; or die "cannot dump $storePath\n";
$narHash = `$Nix::Config::binDir/nix-hash --type sha256 --base32 --flat $nar`; $narHash = `$Nix::Config::binDir/nix-hash --type sha256 --base32 --flat $nar`;
die "cannot hash `$nar'" if $? != 0; die "cannot hash $nar" if $? != 0;
chomp $narHash; chomp $narHash;
$narHash = "sha256:$narHash"; $narHash = "sha256:$narHash";
$narSize = stat("$nar")->size; $narSize = stat("$nar")->size;

View file

@ -85,7 +85,7 @@ static void query(std::pair<FdSink, FdSource> & pipes)
std::cout << readLongLong(pipes.second) << std::endl; std::cout << readLongLong(pipes.second) << std::endl;
} }
} else } else
throw Error(format("unknown substituter query `%1%'") % cmd); throw Error(format("unknown substituter query %1%") % cmd);
std::cout << std::endl; std::cout << std::endl;
} }
} }
@ -132,10 +132,10 @@ int main(int argc, char * * argv)
throw UsageError("download-via-ssh: --substitute takes exactly two arguments"); throw UsageError("download-via-ssh: --substitute takes exactly two arguments");
Path storePath = argv[2]; Path storePath = argv[2];
Path destPath = argv[3]; Path destPath = argv[3];
printMsg(lvlError, format("downloading `%1%' via SSH from `%2%'...") % storePath % host); printMsg(lvlError, format("downloading %1% via SSH from %2%...") % storePath % host);
substitute(pipes, storePath, destPath); substitute(pipes, storePath, destPath);
} }
else else
throw UsageError(format("download-via-ssh: unknown command `%1%'") % arg); throw UsageError(format("download-via-ssh: unknown command %1%") % arg);
}); });
} }

View file

@ -19,7 +19,7 @@ static Strings parseAttrPath(const string & s)
++i; ++i;
while (1) { while (1) {
if (i == s.end()) if (i == s.end())
throw Error(format("missing closing quote in selection path `%1%'") % s); throw Error(format("missing closing quote in selection path %1%") % s);
if (*i == '"') break; if (*i == '"') break;
cur.push_back(*i++); cur.push_back(*i++);
} }
@ -38,7 +38,7 @@ Value * findAlongAttrPath(EvalState & state, const string & attrPath,
Strings tokens = parseAttrPath(attrPath); Strings tokens = parseAttrPath(attrPath);
Error attrError = Error attrError =
Error(format("attribute selection path `%1%' does not match expression") % attrPath); Error(format("attribute selection path %1% does not match expression") % attrPath);
Value * v = &vIn; Value * v = &vIn;
@ -63,15 +63,15 @@ Value * findAlongAttrPath(EvalState & state, const string & attrPath,
if (v->type != tAttrs) if (v->type != tAttrs)
throw TypeError( throw TypeError(
format("the expression selected by the selection path `%1%' should be a set but is %2%") format("the expression selected by the selection path %1% should be a set but is %2%")
% attrPath % showType(*v)); % attrPath % showType(*v));
if (attr.empty()) if (attr.empty())
throw Error(format("empty attribute name in selection path `%1%'") % attrPath); throw Error(format("empty attribute name in selection path %1%") % attrPath);
Bindings::iterator a = v->attrs->find(state.symbols.create(attr)); Bindings::iterator a = v->attrs->find(state.symbols.create(attr));
if (a == v->attrs->end()) if (a == v->attrs->end())
throw Error(format("attribute `%1%' in selection path `%2%' not found") % attr % attrPath); throw Error(format("attribute %1% in selection path %2% not found") % attr % attrPath);
v = &*a->value; v = &*a->value;
} }
@ -79,11 +79,11 @@ Value * findAlongAttrPath(EvalState & state, const string & attrPath,
if (v->type != tList) if (v->type != tList)
throw TypeError( throw TypeError(
format("the expression selected by the selection path `%1%' should be a list but is %2%") format("the expression selected by the selection path %1% should be a list but is %2%")
% attrPath % showType(*v)); % attrPath % showType(*v));
if (attrIndex >= v->list.length) if (attrIndex >= v->list.length)
throw Error(format("list index %1% in selection path `%2%' is out of range") % attrIndex % attrPath); throw Error(format("list index %1% in selection path %2% is out of range") % attrIndex % attrPath);
v = v->list.elems[attrIndex]; v = v->list.elems[attrIndex];
} }

View file

@ -12,7 +12,7 @@ bool parseAutoArgs(Strings::iterator & i,
string arg = *i; string arg = *i;
if (arg != "--arg" && arg != "--argstr") return false; if (arg != "--arg" && arg != "--argstr") return false;
UsageError error(format("`%1%' requires two arguments") % arg); UsageError error(format("%1% requires two arguments") % arg);
if (++i == argsEnd) throw error; if (++i == argsEnd) throw error;
string name = *i; string name = *i;
@ -43,7 +43,7 @@ bool parseSearchPathArg(Strings::iterator & i,
const Strings::iterator & argsEnd, Strings & searchPath) const Strings::iterator & argsEnd, Strings & searchPath)
{ {
if (*i != "-I") return false; if (*i != "-I") return false;
if (++i == argsEnd) throw UsageError("`-I' requires an argument"); if (++i == argsEnd) throw UsageError("-I requires an argument");
searchPath.push_back(*i); searchPath.push_back(*i);
return true; return true;
} }

View file

@ -396,7 +396,7 @@ inline Value * EvalState::lookupVar(Env * env, const ExprVar & var, bool noEval)
return j->value; return j->value;
} }
if (!env->prevWith) if (!env->prevWith)
throwUndefinedVarError("undefined variable `%1%' at %2%", var.name, var.pos); throwUndefinedVarError("undefined variable %1% at %2%", var.name, var.pos);
for (unsigned int l = env->prevWith; l; --l, env = env->up) ; for (unsigned int l = env->prevWith; l; --l, env = env->up) ;
} }
} }
@ -537,12 +537,12 @@ void EvalState::evalFile(const Path & path, Value & v)
return; return;
} }
startNest(nest, lvlTalkative, format("evaluating file `%1%'") % path2); startNest(nest, lvlTalkative, format("evaluating file %1%") % path2);
Expr * e = parseExprFromFile(path2); Expr * e = parseExprFromFile(path2);
try { try {
eval(e, v); eval(e, v);
} catch (Error & e) { } catch (Error & e) {
addErrorPrefix(e, "while evaluating the file `%1%':\n", path2); addErrorPrefix(e, "while evaluating the file %1%:\n", path2);
throw; throw;
} }
@ -686,7 +686,7 @@ void ExprAttrs::eval(EvalState & state, Env & env, Value & v)
Symbol nameSym = state.symbols.create(nameVal.string.s); Symbol nameSym = state.symbols.create(nameVal.string.s);
Bindings::iterator j = v.attrs->find(nameSym); Bindings::iterator j = v.attrs->find(nameSym);
if (j != v.attrs->end()) if (j != v.attrs->end())
throwEvalError("dynamic attribute `%1%' at %2% already defined at %3%", nameSym, i->pos, *j->pos); throwEvalError("dynamic attribute %1% at %2% already defined at %3%", nameSym, i->pos, *j->pos);
i->valueExpr->setName(nameSym); i->valueExpr->setName(nameSym);
/* Keep sorted order so find can catch duplicates */ /* Keep sorted order so find can catch duplicates */
@ -764,7 +764,7 @@ void ExprSelect::eval(EvalState & state, Env & env, Value & v)
staticPath.push_back(AttrName(getName(*j, state, env))); staticPath.push_back(AttrName(getName(*j, state, env)));
for (j = j + 1; j != attrPath.end(); ++j) for (j = j + 1; j != attrPath.end(); ++j)
staticPath.push_back(*j); staticPath.push_back(*j);
throwEvalError("attribute `%1%' missing, at %2%", showAttrPath(staticPath), pos); throwEvalError("attribute %1% missing, at %2%", showAttrPath(staticPath), pos);
} }
} }
vAttrs = j->value; vAttrs = j->value;
@ -776,7 +776,7 @@ void ExprSelect::eval(EvalState & state, Env & env, Value & v)
} catch (Error & e) { } catch (Error & e) {
if (pos2 && pos2->file != state.sDerivationNix) if (pos2 && pos2->file != state.sDerivationNix)
addErrorPrefix(e, "while evaluating the attribute `%1%' at %2%:\n", addErrorPrefix(e, "while evaluating the attribute %1% at %2%:\n",
showAttrPath(attrPath), *pos2); showAttrPath(attrPath), *pos2);
throw; throw;
} }
@ -900,7 +900,7 @@ void EvalState::callFunction(Value & fun, Value & arg, Value & v, const Pos & po
foreach (Formals::Formals_::iterator, i, lambda.formals->formals) { foreach (Formals::Formals_::iterator, i, lambda.formals->formals) {
Bindings::iterator j = arg.attrs->find(i->name); Bindings::iterator j = arg.attrs->find(i->name);
if (j == arg.attrs->end()) { if (j == arg.attrs->end()) {
if (!i->def) throwTypeError("%1% called without required argument `%2%', at %3%", if (!i->def) throwTypeError("%1% called without required argument %2%, at %3%",
lambda, i->name, pos); lambda, i->name, pos);
env2.values[displ++] = i->def->maybeThunk(*this, env2); env2.values[displ++] = i->def->maybeThunk(*this, env2);
} else { } else {
@ -916,7 +916,7 @@ void EvalState::callFunction(Value & fun, Value & arg, Value & v, const Pos & po
user. */ user. */
foreach (Bindings::iterator, i, *arg.attrs) foreach (Bindings::iterator, i, *arg.attrs)
if (lambda.formals->argNames.find(i->name) == lambda.formals->argNames.end()) if (lambda.formals->argNames.find(i->name) == lambda.formals->argNames.end())
throwTypeError("%1% called with unexpected argument `%2%', at %3%", lambda, i->name, pos); throwTypeError("%1% called with unexpected argument %2%, at %3%", lambda, i->name, pos);
abort(); // can't happen abort(); // can't happen
} }
} }
@ -963,7 +963,7 @@ void EvalState::autoCallFunction(Bindings & args, Value & fun, Value & res)
if (j != args.end()) if (j != args.end())
actualArgs->attrs->push_back(*j); actualArgs->attrs->push_back(*j);
else if (!i->def) else if (!i->def)
throwTypeError("cannot auto-call a function that has an argument without a default value (`%1%')", i->name); throwTypeError("cannot auto-call a function that has an argument without a default value (%1%)", i->name);
} }
actualArgs->attrs->sort(); actualArgs->attrs->sort();
@ -1233,10 +1233,10 @@ string EvalState::forceStringNoCtx(Value & v, const Pos & pos)
string s = forceString(v, pos); string s = forceString(v, pos);
if (v.string.context) { if (v.string.context) {
if (pos) if (pos)
throwEvalError("the string `%1%' is not allowed to refer to a store path (such as `%2%'), at %3%", throwEvalError("the string %1% is not allowed to refer to a store path (such as %2%), at %3%",
v.string.s, v.string.context[0], pos); v.string.s, v.string.context[0], pos);
else else
throwEvalError("the string `%1%' is not allowed to refer to a store path (such as `%2%')", throwEvalError("the string %1% is not allowed to refer to a store path (such as %2%)",
v.string.s, v.string.context[0]); v.string.s, v.string.context[0]);
} }
return s; return s;
@ -1307,7 +1307,7 @@ string EvalState::coerceToString(const Pos & pos, Value & v, PathSet & context,
string EvalState::copyPathToStore(PathSet & context, const Path & path) string EvalState::copyPathToStore(PathSet & context, const Path & path)
{ {
if (nix::isDerivation(path)) if (nix::isDerivation(path))
throwEvalError("file names are not allowed to end in `%1%'", drvExtension); throwEvalError("file names are not allowed to end in %1%", drvExtension);
Path dstPath; Path dstPath;
if (srcToStore[path] != "") if (srcToStore[path] != "")
@ -1317,7 +1317,7 @@ string EvalState::copyPathToStore(PathSet & context, const Path & path)
? computeStorePathForPath(path).first ? computeStorePathForPath(path).first
: store->addToStore(path, true, htSHA256, defaultPathFilter, repair); : store->addToStore(path, true, htSHA256, defaultPathFilter, repair);
srcToStore[path] = dstPath; srcToStore[path] = dstPath;
printMsg(lvlChatty, format("copied source `%1%' -> `%2%'") printMsg(lvlChatty, format("copied source %1% -> %2%")
% path % dstPath); % path % dstPath);
} }
@ -1330,7 +1330,7 @@ Path EvalState::coerceToPath(const Pos & pos, Value & v, PathSet & context)
{ {
string path = coerceToString(pos, v, context, false, false); string path = coerceToString(pos, v, context, false, false);
if (path == "" || path[0] != '/') if (path == "" || path[0] != '/')
throwEvalError("string `%1%' doesn't represent an absolute path, at %1%", path, pos); throwEvalError("string %1% doesn't represent an absolute path, at %1%", path, pos);
return path; return path;
} }

View file

@ -259,7 +259,7 @@ static void getDerivations(EvalState & state, Value & vIn,
attrs.insert(std::pair<string, Symbol>(i->name, i->name)); attrs.insert(std::pair<string, Symbol>(i->name, i->name));
foreach (SortedSymbols::iterator, i, attrs) { foreach (SortedSymbols::iterator, i, attrs) {
startNest(nest, lvlDebug, format("evaluating attribute `%1%'") % i->first); startNest(nest, lvlDebug, format("evaluating attribute %1%") % i->first);
string pathPrefix2 = addToPath(pathPrefix, i->first); string pathPrefix2 = addToPath(pathPrefix, i->first);
Value & v2(*v.attrs->find(i->second)->value); Value & v2(*v.attrs->find(i->second)->value);
if (combineChannels) if (combineChannels)

View file

@ -65,7 +65,7 @@ static void parseJSON(EvalState & state, const char * & s, Value & v)
values.push_back(v2); values.push_back(v2);
skipWhitespace(s); skipWhitespace(s);
if (*s == ']') break; if (*s == ']') break;
if (*s != ',') throw JSONParseError("expected `,' or `]' after JSON array element"); if (*s != ',') throw JSONParseError("expected , or ] after JSON array element");
s++; s++;
} }
s++; s++;
@ -82,14 +82,14 @@ static void parseJSON(EvalState & state, const char * & s, Value & v)
if (v.attrs->empty() && *s == '}') break; if (v.attrs->empty() && *s == '}') break;
string name = parseJSONString(s); string name = parseJSONString(s);
skipWhitespace(s); skipWhitespace(s);
if (*s != ':') throw JSONParseError("expected `:' in JSON object"); if (*s != ':') throw JSONParseError("expected : in JSON object");
s++; s++;
Value * v2 = state.allocValue(); Value * v2 = state.allocValue();
parseJSON(state, s, *v2); parseJSON(state, s, *v2);
v.attrs->push_back(Attr(state.symbols.create(name), v2)); v.attrs->push_back(Attr(state.symbols.create(name), v2));
skipWhitespace(s); skipWhitespace(s);
if (*s == '}') break; if (*s == '}') break;
if (*s != ',') throw JSONParseError("expected `,' or `}' after JSON member"); if (*s != ',') throw JSONParseError("expected , or } after JSON member");
s++; s++;
} }
v.attrs->sort(); v.attrs->sort();

View file

@ -113,7 +113,7 @@ or { return OR_KW; }
{INT} { errno = 0; {INT} { errno = 0;
yylval->n = strtol(yytext, 0, 10); yylval->n = strtol(yytext, 0, 10);
if (errno != 0) if (errno != 0)
throw ParseError(format("invalid integer `%1%'") % yytext); throw ParseError(format("invalid integer %1%") % yytext);
return INT; return INT;
} }

View file

@ -212,7 +212,7 @@ void ExprVar::bindVars(const StaticEnv & env)
/* Otherwise, the variable must be obtained from the nearest /* Otherwise, the variable must be obtained from the nearest
enclosing `with'. If there is no `with', then we can issue an enclosing `with'. If there is no `with', then we can issue an
"undefined variable" error now. */ "undefined variable" error now. */
if (withLevel == -1) throw UndefinedVarError(format("undefined variable `%1%' at %2%") % name % pos); if (withLevel == -1) throw UndefinedVarError(format("undefined variable %1% at %2%") % name % pos);
fromWith = true; fromWith = true;
this->level = withLevel; this->level = withLevel;
@ -364,7 +364,7 @@ void ExprLambda::setName(Symbol & name)
string ExprLambda::showNamePos() const string ExprLambda::showNamePos() const
{ {
return (format("%1% at %2%") % (name.set() ? "`" + (string) name + "'" : "anonymous function") % pos).str(); return (format("%1% at %2%") % (name.set() ? "" + (string) name + "" : "anonymous function") % pos).str();
} }

View file

@ -224,7 +224,7 @@ struct ExprLambda : Expr
: pos(pos), arg(arg), matchAttrs(matchAttrs), formals(formals), body(body) : pos(pos), arg(arg), matchAttrs(matchAttrs), formals(formals), body(body)
{ {
if (!arg.empty() && formals && formals->argNames.find(arg) != formals->argNames.end()) if (!arg.empty() && formals && formals->argNames.find(arg) != formals->argNames.end())
throw ParseError(format("duplicate formal function argument `%1%' at %2%") throw ParseError(format("duplicate formal function argument %1% at %2%")
% arg % pos); % arg % pos);
}; };
void setName(Symbol & name); void setName(Symbol & name);

View file

@ -67,14 +67,14 @@ namespace nix {
static void dupAttr(const AttrPath & attrPath, const Pos & pos, const Pos & prevPos) static void dupAttr(const AttrPath & attrPath, const Pos & pos, const Pos & prevPos)
{ {
throw ParseError(format("attribute `%1%' at %2% already defined at %3%") throw ParseError(format("attribute %1% at %2% already defined at %3%")
% showAttrPath(attrPath) % pos % prevPos); % showAttrPath(attrPath) % pos % prevPos);
} }
static void dupAttr(Symbol attr, const Pos & pos, const Pos & prevPos) static void dupAttr(Symbol attr, const Pos & pos, const Pos & prevPos)
{ {
throw ParseError(format("attribute `%1%' at %2% already defined at %3%") throw ParseError(format("attribute %1% at %2% already defined at %3%")
% attr % pos % prevPos); % attr % pos % prevPos);
} }
@ -123,7 +123,7 @@ static void addAttr(ExprAttrs * attrs, AttrPath & attrPath,
static void addFormal(const Pos & pos, Formals * formals, const Formal & formal) static void addFormal(const Pos & pos, Formals * formals, const Formal & formal)
{ {
if (formals->argNames.find(formal.name) != formals->argNames.end()) if (formals->argNames.find(formal.name) != formals->argNames.end())
throw ParseError(format("duplicate formal function argument `%1%' at %2%") throw ParseError(format("duplicate formal function argument %1% at %2%")
% formal.name % pos); % formal.name % pos);
formals->formals.push_front(formal); formals->formals.push_front(formal);
formals->argNames.insert(formal.name); formals->argNames.insert(formal.name);
@ -570,7 +570,7 @@ Path resolveExprPath(Path path)
struct stat st; struct stat st;
while (true) { while (true) {
if (lstat(path.c_str(), &st)) if (lstat(path.c_str(), &st))
throw SysError(format("getting status of `%1%'") % path); throw SysError(format("getting status of %1%") % path);
if (!S_ISLNK(st.st_mode)) break; if (!S_ISLNK(st.st_mode)) break;
path = absPath(readLink(path), dirOf(path)); path = absPath(readLink(path), dirOf(path));
} }
@ -621,10 +621,10 @@ void EvalState::addToSearchPath(const string & s, bool warn)
path = absPath(path); path = absPath(path);
if (pathExists(path)) { if (pathExists(path)) {
debug(format("adding path `%1%' to the search path") % path); debug(format("adding path %1% to the search path") % path);
searchPath.push_back(std::pair<string, Path>(prefix, path)); searchPath.push_back(std::pair<string, Path>(prefix, path));
} else if (warn) } else if (warn)
printMsg(lvlError, format("warning: Nix search path entry `%1%' does not exist, ignoring") % path); printMsg(lvlError, format("warning: Nix search path entry %1% does not exist, ignoring") % path);
} }
@ -649,7 +649,7 @@ Path EvalState::findFile(SearchPath & searchPath, const string & path)
} }
if (pathExists(res)) return canonPath(res); if (pathExists(res)) return canonPath(res);
} }
throw ThrownError(format("file `%1%' was not found in the Nix search path (add it using $NIX_PATH or -I)") % path); throw ThrownError(format("file %1% was not found in the Nix search path (add it using $NIX_PATH or -I)") % path);
} }

View file

@ -43,7 +43,7 @@ struct InvalidPathError : EvalError
{ {
Path path; Path path;
InvalidPathError(const Path & path) : InvalidPathError(const Path & path) :
EvalError(format("path `%1%' is not valid") % path), path(path) {}; EvalError(format("path %1% is not valid") % path), path(path) {};
~InvalidPathError() throw () { }; ~InvalidPathError() throw () { };
}; };
@ -82,7 +82,7 @@ static void prim_scopedImport(EvalState & state, const Pos & pos, Value * * args
try { try {
realiseContext(context); realiseContext(context);
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
throw EvalError(format("cannot import `%1%', since path `%2%' is not valid, at %3%") throw EvalError(format("cannot import %1%, since path %2% is not valid, at %3%")
% path % e.path % pos); % path % e.path % pos);
} }
@ -123,7 +123,7 @@ static void prim_scopedImport(EvalState & state, const Pos & pos, Value * * args
env->values[displ++] = attr.value; env->values[displ++] = attr.value;
} }
startNest(nest, lvlTalkative, format("evaluating file `%1%'") % path); startNest(nest, lvlTalkative, format("evaluating file %1%") % path);
Expr * e = state.parseExprFromFile(resolveExprPath(path), staticEnv); Expr * e = state.parseExprFromFile(resolveExprPath(path), staticEnv);
e->eval(state, *env, v); e->eval(state, *env, v);
@ -145,7 +145,7 @@ static void prim_importNative(EvalState & state, const Pos & pos, Value * * args
try { try {
realiseContext(context); realiseContext(context);
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
throw EvalError(format("cannot import `%1%', since path `%2%' is not valid, at %3%") throw EvalError(format("cannot import %1%, since path %2% is not valid, at %3%")
% path % e.path % pos); % path % e.path % pos);
} }
@ -153,16 +153,16 @@ static void prim_importNative(EvalState & state, const Pos & pos, Value * * args
void *handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL); void *handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_LOCAL);
if (!handle) if (!handle)
throw EvalError(format("could not open `%1%': %2%") % path % dlerror()); throw EvalError(format("could not open %1%: %2%") % path % dlerror());
dlerror(); dlerror();
ValueInitializer func = (ValueInitializer) dlsym(handle, sym.c_str()); ValueInitializer func = (ValueInitializer) dlsym(handle, sym.c_str());
if(!func) { if(!func) {
char *message = dlerror(); char *message = dlerror();
if (message) if (message)
throw EvalError(format("could not load symbol `%1%' from `%2%': %3%") % sym % path % message); throw EvalError(format("could not load symbol %1% from %2%: %3%") % sym % path % message);
else else
throw EvalError(format("symbol `%1%' from `%2%' resolved to NULL when a function pointer was expected") throw EvalError(format("symbol %1% from %2% resolved to NULL when a function pointer was expected")
% sym % path); % sym % path);
} }
@ -273,7 +273,7 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar
Bindings::iterator startSet = Bindings::iterator startSet =
args[0]->attrs->find(state.symbols.create("startSet")); args[0]->attrs->find(state.symbols.create("startSet"));
if (startSet == args[0]->attrs->end()) if (startSet == args[0]->attrs->end())
throw EvalError(format("attribute `startSet' required, at %1%") % pos); throw EvalError(format("attribute startSet required, at %1%") % pos);
state.forceList(*startSet->value, pos); state.forceList(*startSet->value, pos);
ValueList workSet; ValueList workSet;
@ -284,7 +284,7 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar
Bindings::iterator op = Bindings::iterator op =
args[0]->attrs->find(state.symbols.create("operator")); args[0]->attrs->find(state.symbols.create("operator"));
if (op == args[0]->attrs->end()) if (op == args[0]->attrs->end())
throw EvalError(format("attribute `operator' required, at %1%") % pos); throw EvalError(format("attribute operator required, at %1%") % pos);
state.forceValue(*op->value); state.forceValue(*op->value);
/* Construct the closure by applying the operator to element of /* Construct the closure by applying the operator to element of
@ -303,7 +303,7 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar
Bindings::iterator key = Bindings::iterator key =
e->attrs->find(state.symbols.create("key")); e->attrs->find(state.symbols.create("key"));
if (key == e->attrs->end()) if (key == e->attrs->end())
throw EvalError(format("attribute `key' required, at %1%") % pos); throw EvalError(format("attribute key required, at %1%") % pos);
state.forceValue(*key->value); state.forceValue(*key->value);
if (doneKeys.find(key->value) != doneKeys.end()) continue; if (doneKeys.find(key->value) != doneKeys.end()) continue;
@ -333,7 +333,7 @@ static void prim_genericClosure(EvalState & state, const Pos & pos, Value * * ar
static void prim_abort(EvalState & state, const Pos & pos, Value * * args, Value & v) static void prim_abort(EvalState & state, const Pos & pos, Value * * args, Value & v)
{ {
PathSet context; PathSet context;
throw Abort(format("evaluation aborted with the following error message: `%1%'") % throw Abort(format("evaluation aborted with the following error message: %1%") %
state.coerceToString(pos, *args[0], context)); state.coerceToString(pos, *args[0], context));
} }
@ -418,13 +418,13 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
/* Figure out the name first (for stack backtraces). */ /* Figure out the name first (for stack backtraces). */
Bindings::iterator attr = args[0]->attrs->find(state.sName); Bindings::iterator attr = args[0]->attrs->find(state.sName);
if (attr == args[0]->attrs->end()) if (attr == args[0]->attrs->end())
throw EvalError(format("required attribute `name' missing, at %1%") % pos); throw EvalError(format("required attribute name missing, at %1%") % pos);
string drvName; string drvName;
Pos & posDrvName(*attr->pos); Pos & posDrvName(*attr->pos);
try { try {
drvName = state.forceStringNoCtx(*attr->value, pos); drvName = state.forceStringNoCtx(*attr->value, pos);
} catch (Error & e) { } catch (Error & e) {
e.addPrefix(format("while evaluating the derivation attribute `name' at %1%:\n") % posDrvName); e.addPrefix(format("while evaluating the derivation attribute name at %1%:\n") % posDrvName);
throw; throw;
} }
@ -448,7 +448,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
foreach (Bindings::iterator, i, *args[0]->attrs) { foreach (Bindings::iterator, i, *args[0]->attrs) {
if (i->name == state.sIgnoreNulls) continue; if (i->name == state.sIgnoreNulls) continue;
string key = i->name; string key = i->name;
startNest(nest, lvlVomit, format("processing attribute `%1%'") % key); startNest(nest, lvlVomit, format("processing attribute %1%") % key);
try { try {
@ -476,28 +476,28 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
else if (i->name == state.sSystem) drv.platform = s; else if (i->name == state.sSystem) drv.platform = s;
else if (i->name == state.sName) { else if (i->name == state.sName) {
drvName = s; drvName = s;
printMsg(lvlVomit, format("derivation name is `%1%'") % drvName); printMsg(lvlVomit, format("derivation name is %1%") % drvName);
} }
else if (key == "outputHash") outputHash = s; else if (key == "outputHash") outputHash = s;
else if (key == "outputHashAlgo") outputHashAlgo = s; else if (key == "outputHashAlgo") outputHashAlgo = s;
else if (key == "outputHashMode") { else if (key == "outputHashMode") {
if (s == "recursive") outputHashRecursive = true; if (s == "recursive") outputHashRecursive = true;
else if (s == "flat") outputHashRecursive = false; else if (s == "flat") outputHashRecursive = false;
else throw EvalError(format("invalid value `%1%' for `outputHashMode' attribute, at %2%") % s % posDrvName); else throw EvalError(format("invalid value %1% for outputHashMode attribute, at %2%") % s % posDrvName);
} }
else if (key == "outputs") { else if (key == "outputs") {
Strings tmp = tokenizeString<Strings>(s); Strings tmp = tokenizeString<Strings>(s);
outputs.clear(); outputs.clear();
foreach (Strings::iterator, j, tmp) { foreach (Strings::iterator, j, tmp) {
if (outputs.find(*j) != outputs.end()) if (outputs.find(*j) != outputs.end())
throw EvalError(format("duplicate derivation output `%1%', at %2%") % *j % posDrvName); throw EvalError(format("duplicate derivation output %1%, at %2%") % *j % posDrvName);
/* !!! Check whether *j is a valid attribute /* !!! Check whether *j is a valid attribute
name. */ name. */
/* Derivations cannot be named drv, because /* Derivations cannot be named drv, because
then we'd have an attribute drvPath in then we'd have an attribute drvPath in
the resulting set. */ the resulting set. */
if (*j == "drv") if (*j == "drv")
throw EvalError(format("invalid derivation output name `drv', at %1%") % posDrvName); throw EvalError(format("invalid derivation output name drv, at %1%") % posDrvName);
outputs.insert(*j); outputs.insert(*j);
} }
if (outputs.empty()) if (outputs.empty())
@ -506,7 +506,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
} }
} catch (Error & e) { } catch (Error & e) {
e.addPrefix(format("while evaluating the attribute `%1%' of the derivation `%2%' at %3%:\n") e.addPrefix(format("while evaluating the attribute %1% of the derivation %2% at %3%:\n")
% key % drvName % posDrvName); % key % drvName % posDrvName);
throw; throw;
} }
@ -557,14 +557,14 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
/* Do we have all required attributes? */ /* Do we have all required attributes? */
if (drv.builder == "") if (drv.builder == "")
throw EvalError(format("required attribute `builder' missing, at %1%") % posDrvName); throw EvalError(format("required attribute builder missing, at %1%") % posDrvName);
if (drv.platform == "") if (drv.platform == "")
throw EvalError(format("required attribute `system' missing, at %1%") % posDrvName); throw EvalError(format("required attribute system missing, at %1%") % posDrvName);
/* Check whether the derivation name is valid. */ /* Check whether the derivation name is valid. */
checkStoreName(drvName); checkStoreName(drvName);
if (isDerivation(drvName)) if (isDerivation(drvName))
throw EvalError(format("derivation names are not allowed to end in `%1%', at %2%") throw EvalError(format("derivation names are not allowed to end in %1%, at %2%")
% drvExtension % posDrvName); % drvExtension % posDrvName);
if (outputHash != "") { if (outputHash != "") {
@ -574,7 +574,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
HashType ht = parseHashType(outputHashAlgo); HashType ht = parseHashType(outputHashAlgo);
if (ht == htUnknown) if (ht == htUnknown)
throw EvalError(format("unknown hash algorithm `%1%', at %2%") % outputHashAlgo % posDrvName); throw EvalError(format("unknown hash algorithm %1%, at %2%") % outputHashAlgo % posDrvName);
Hash h = parseHash16or32(ht, outputHash); Hash h = parseHash16or32(ht, outputHash);
outputHash = printHash(h); outputHash = printHash(h);
if (outputHashRecursive) outputHashAlgo = "r:" + outputHashAlgo; if (outputHashRecursive) outputHashAlgo = "r:" + outputHashAlgo;
@ -610,7 +610,7 @@ static void prim_derivationStrict(EvalState & state, const Pos & pos, Value * *
/* Write the resulting term into the Nix store directory. */ /* Write the resulting term into the Nix store directory. */
Path drvPath = writeDerivation(*store, drv, drvName, state.repair); Path drvPath = writeDerivation(*store, drv, drvName, state.repair);
printMsg(lvlChatty, format("instantiated `%1%' -> `%2%'") printMsg(lvlChatty, format("instantiated %1% -> %2%")
% drvName % drvPath); % drvName % drvPath);
/* Optimisation, but required in read-only mode! because in that /* Optimisation, but required in read-only mode! because in that
@ -659,7 +659,7 @@ static void prim_storePath(EvalState & state, const Pos & pos, Value * * args, V
e.g. nix-push does the right thing. */ e.g. nix-push does the right thing. */
if (!isStorePath(path)) path = canonPath(path, true); if (!isStorePath(path)) path = canonPath(path, true);
if (!isInStore(path)) if (!isInStore(path))
throw EvalError(format("path `%1%' is not in the Nix store, at %2%") % path % pos); throw EvalError(format("path %1% is not in the Nix store, at %2%") % path % pos);
Path path2 = toStorePath(path); Path path2 = toStorePath(path);
if (!settings.readOnlyMode) if (!settings.readOnlyMode)
store->ensurePath(path2); store->ensurePath(path2);
@ -673,7 +673,7 @@ static void prim_pathExists(EvalState & state, const Pos & pos, Value * * args,
PathSet context; PathSet context;
Path path = state.coerceToPath(pos, *args[0], context); Path path = state.coerceToPath(pos, *args[0], context);
if (!context.empty()) if (!context.empty())
throw EvalError(format("string `%1%' cannot refer to other paths, at %2%") % path % pos); throw EvalError(format("string %1% cannot refer to other paths, at %2%") % path % pos);
mkBool(v, pathExists(path)); mkBool(v, pathExists(path));
} }
@ -704,7 +704,7 @@ static void prim_readFile(EvalState & state, const Pos & pos, Value * * args, Va
PathSet context; PathSet context;
Path path = state.coerceToPath(pos, *args[0], context); Path path = state.coerceToPath(pos, *args[0], context);
if (!context.empty()) if (!context.empty())
throw EvalError(format("string `%1%' cannot refer to other paths, at %2%") % path % pos); throw EvalError(format("string %1% cannot refer to other paths, at %2%") % path % pos);
mkString(v, readFile(path).c_str()); mkString(v, readFile(path).c_str());
} }
@ -729,7 +729,7 @@ static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Va
i = v2.attrs->find(state.symbols.create("path")); i = v2.attrs->find(state.symbols.create("path"));
if (i == v2.attrs->end()) if (i == v2.attrs->end())
throw EvalError(format("attribute `path' missing, at %1%") % pos); throw EvalError(format("attribute path missing, at %1%") % pos);
string path = state.coerceToPath(pos, *i->value, context); string path = state.coerceToPath(pos, *i->value, context);
searchPath.push_back(std::pair<string, Path>(prefix, path)); searchPath.push_back(std::pair<string, Path>(prefix, path));
@ -740,7 +740,7 @@ static void prim_findFile(EvalState & state, const Pos & pos, Value * * args, Va
try { try {
realiseContext(context); realiseContext(context);
} catch (InvalidPathError & e) { } catch (InvalidPathError & e) {
throw EvalError(format("cannot find `%1%', since path `%2%' is not valid, at %3%") throw EvalError(format("cannot find %1%, since path %2% is not valid, at %3%")
% path % e.path % pos); % path % e.path % pos);
} }
@ -799,7 +799,7 @@ static void prim_toFile(EvalState & state, const Pos & pos, Value * * args, Valu
Path path = *i; Path path = *i;
if (path.at(0) == '=') path = string(path, 1); if (path.at(0) == '=') path = string(path, 1);
if (isDerivation(path)) if (isDerivation(path))
throw EvalError(format("in `toFile': the file `%1%' cannot refer to derivation outputs, at %2%") % name % pos); throw EvalError(format("in toFile: the file %1% cannot refer to derivation outputs, at %2%") % name % pos);
refs.insert(path); refs.insert(path);
} }
@ -829,7 +829,7 @@ struct FilterFromExpr : PathFilter
{ {
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) if (lstat(path.c_str(), &st))
throw SysError(format("getting attributes of path `%1%'") % path); throw SysError(format("getting attributes of path %1%") % path);
/* Call the filter function. The first argument is the path, /* Call the filter function. The first argument is the path,
the second is a string indicating the type of the file. */ the second is a string indicating the type of the file. */
@ -859,11 +859,11 @@ static void prim_filterSource(EvalState & state, const Pos & pos, Value * * args
PathSet context; PathSet context;
Path path = state.coerceToPath(pos, *args[1], context); Path path = state.coerceToPath(pos, *args[1], context);
if (!context.empty()) if (!context.empty())
throw EvalError(format("string `%1%' cannot refer to other paths, at %2%") % path % pos); throw EvalError(format("string %1% cannot refer to other paths, at %2%") % path % pos);
state.forceValue(*args[0]); state.forceValue(*args[0]);
if (args[0]->type != tLambda) if (args[0]->type != tLambda)
throw TypeError(format("first argument in call to `filterSource' is not a function but %1%, at %2%") % showType(*args[0]) % pos); throw TypeError(format("first argument in call to filterSource is not a function but %1%, at %2%") % showType(*args[0]) % pos);
FilterFromExpr filter(state, *args[0]); FilterFromExpr filter(state, *args[0]);
@ -906,7 +906,7 @@ void prim_getAttr(EvalState & state, const Pos & pos, Value * * args, Value & v)
// !!! Should we create a symbol here or just do a lookup? // !!! Should we create a symbol here or just do a lookup?
Bindings::iterator i = args[1]->attrs->find(state.symbols.create(attr)); Bindings::iterator i = args[1]->attrs->find(state.symbols.create(attr));
if (i == args[1]->attrs->end()) if (i == args[1]->attrs->end())
throw EvalError(format("attribute `%1%' missing, at %2%") % attr % pos); throw EvalError(format("attribute %1% missing, at %2%") % attr % pos);
// !!! add to stack trace? // !!! add to stack trace?
if (state.countCalls && i->pos) state.attrSelects[*i->pos]++; if (state.countCalls && i->pos) state.attrSelects[*i->pos]++;
state.forceValue(*i->value); state.forceValue(*i->value);
@ -986,14 +986,14 @@ static void prim_listToAttrs(EvalState & state, const Pos & pos, Value * * args,
Bindings::iterator j = v2.attrs->find(state.sName); Bindings::iterator j = v2.attrs->find(state.sName);
if (j == v2.attrs->end()) if (j == v2.attrs->end())
throw TypeError(format("`name' attribute missing in a call to `listToAttrs', at %1%") % pos); throw TypeError(format("name attribute missing in a call to listToAttrs, at %1%") % pos);
string name = state.forceStringNoCtx(*j->value, pos); string name = state.forceStringNoCtx(*j->value, pos);
Symbol sym = state.symbols.create(name); Symbol sym = state.symbols.create(name);
if (seen.find(sym) == seen.end()) { if (seen.find(sym) == seen.end()) {
Bindings::iterator j2 = v2.attrs->find(state.symbols.create(state.sValue)); Bindings::iterator j2 = v2.attrs->find(state.symbols.create(state.sValue));
if (j2 == v2.attrs->end()) if (j2 == v2.attrs->end())
throw TypeError(format("`value' attribute missing in a call to `listToAttrs', at %1%") % pos); throw TypeError(format("value attribute missing in a call to listToAttrs, at %1%") % pos);
v.attrs->push_back(Attr(sym, j2->value, j2->pos)); v.attrs->push_back(Attr(sym, j2->value, j2->pos));
seen.insert(sym); seen.insert(sym);
@ -1039,7 +1039,7 @@ static void prim_functionArgs(EvalState & state, const Pos & pos, Value * * args
{ {
state.forceValue(*args[0]); state.forceValue(*args[0]);
if (args[0]->type != tLambda) if (args[0]->type != tLambda)
throw TypeError(format("`functionArgs' requires a function, at %1%") % pos); throw TypeError(format("functionArgs requires a function, at %1%") % pos);
if (!args[0]->lambda.fun->matchAttrs) { if (!args[0]->lambda.fun->matchAttrs) {
state.mkAttrs(v, 0); state.mkAttrs(v, 0);
@ -1098,7 +1098,7 @@ static void prim_tail(EvalState & state, const Pos & pos, Value * * args, Value
{ {
state.forceList(*args[0], pos); state.forceList(*args[0], pos);
if (args[0]->list.length == 0) if (args[0]->list.length == 0)
throw Error(format("`tail' called on an empty list, at %1%") % pos); throw Error(format("tail called on an empty list, at %1%") % pos);
state.mkList(v, args[0]->list.length - 1); state.mkList(v, args[0]->list.length - 1);
for (unsigned int n = 0; n < v.list.length; ++n) for (unsigned int n = 0; n < v.list.length; ++n)
v.list.elems[n] = args[0]->list.elems[n + 1]; v.list.elems[n] = args[0]->list.elems[n + 1];
@ -1247,7 +1247,7 @@ static void prim_substring(EvalState & state, const Pos & pos, Value * * args, V
PathSet context; PathSet context;
string s = state.coerceToString(pos, *args[2], context); string s = state.coerceToString(pos, *args[2], context);
if (start < 0) throw EvalError(format("negative start position in `substring', at %1%") % pos); if (start < 0) throw EvalError(format("negative start position in substring, at %1%") % pos);
mkString(v, (unsigned int) start >= s.size() ? "" : string(s, start, len), context); mkString(v, (unsigned int) start >= s.size() ? "" : string(s, start, len), context);
} }
@ -1297,7 +1297,7 @@ static void prim_hashString(EvalState & state, const Pos & pos, Value * * args,
string type = state.forceStringNoCtx(*args[0], pos); string type = state.forceStringNoCtx(*args[0], pos);
HashType ht = parseHashType(type); HashType ht = parseHashType(type);
if (ht == htUnknown) if (ht == htUnknown)
throw Error(format("unknown hash type `%1%', at %2%") % type % pos); throw Error(format("unknown hash type %1%, at %2%") % type % pos);
PathSet context; // discarded PathSet context; // discarded
string s = state.forceString(*args[1], context); string s = state.forceString(*args[1], context);

View file

@ -38,7 +38,7 @@ void printGCWarning()
if (!gcWarning) return; if (!gcWarning) return;
static bool haveWarned = false; static bool haveWarned = false;
warnOnce(haveWarned, warnOnce(haveWarned,
"you did not specify `--add-root'; " "you did not specify --add-root; "
"the result might be removed by the garbage collector"); "the result might be removed by the garbage collector");
} }
@ -92,7 +92,7 @@ string getArg(const string & opt,
Strings::iterator & i, const Strings::iterator & end) Strings::iterator & i, const Strings::iterator & end)
{ {
++i; ++i;
if (i == end) throw UsageError(format("`%1%' requires an argument") % opt); if (i == end) throw UsageError(format("%1% requires an argument") % opt);
return *i; return *i;
} }
@ -214,15 +214,15 @@ void parseCmdLine(int argc, char * * argv,
else if (arg == "--no-gc-warning") else if (arg == "--no-gc-warning")
gcWarning = false; gcWarning = false;
else if (arg == "--option") { else if (arg == "--option") {
++i; if (i == args.end()) throw UsageError("`--option' requires two arguments"); ++i; if (i == args.end()) throw UsageError("--option requires two arguments");
string name = *i; string name = *i;
++i; if (i == args.end()) throw UsageError("`--option' requires two arguments"); ++i; if (i == args.end()) throw UsageError("--option requires two arguments");
string value = *i; string value = *i;
settings.set(name, value); settings.set(name, value);
} }
else { else {
if (!parseArg(i, args.end())) if (!parseArg(i, args.end()))
throw UsageError(format("unrecognised option `%1%'") % *i); throw UsageError(format("unrecognised option %1%") % *i);
} }
} }
@ -241,7 +241,7 @@ void showManPage(const string & name)
{ {
restoreSIGPIPE(); restoreSIGPIPE();
execlp("man", "man", name.c_str(), NULL); execlp("man", "man", name.c_str(), NULL);
throw SysError(format("command `man %1%' failed") % name.c_str()); throw SysError(format("command man %1% failed") % name.c_str());
} }
@ -264,13 +264,13 @@ int handleExceptions(const string & programName, std::function<void()> fun)
return e.status; return e.status;
} catch (UsageError & e) { } catch (UsageError & e) {
printMsg(lvlError, printMsg(lvlError,
format(error + " %1%\nTry `%2% --help' for more information.") format(error + " %1%\nTry %2% --help for more information.")
% e.what() % programName); % e.what() % programName);
return 1; return 1;
} catch (BaseError & e) { } catch (BaseError & e) {
printMsg(lvlError, format(error + "%1%%2%") % (settings.showTrace ? e.prefix() : "") % e.msg()); printMsg(lvlError, format(error + "%1%%2%") % (settings.showTrace ? e.prefix() : "") % e.msg());
if (e.prefix() != "" && !settings.showTrace) if (e.prefix() != "" && !settings.showTrace)
printMsg(lvlError, "(use `--show-trace' to show detailed location information)"); printMsg(lvlError, "(use --show-trace to show detailed location information)");
return e.status; return e.status;
} catch (std::bad_alloc & e) { } catch (std::bad_alloc & e) {
printMsg(lvlError, error + "out of memory"); printMsg(lvlError, error + "out of memory");
@ -306,7 +306,7 @@ RunPager::RunPager()
if (dup2(toPager.readSide, STDIN_FILENO) == -1) if (dup2(toPager.readSide, STDIN_FILENO) == -1)
throw SysError("dupping stdin"); throw SysError("dupping stdin");
execl("/bin/sh", "sh", "-c", pager.c_str(), NULL); execl("/bin/sh", "sh", "-c", pager.c_str(), NULL);
throw SysError(format("executing `%1%'") % pager); throw SysError(format("executing %1%") % pager);
}); });
if (dup2(toPager.writeSide, STDOUT_FILENO) == -1) if (dup2(toPager.writeSide, STDOUT_FILENO) == -1)

View file

@ -46,7 +46,7 @@ template<class N> N getIntArg(const string & opt,
Strings::iterator & i, const Strings::iterator & end, bool allowUnit) Strings::iterator & i, const Strings::iterator & end, bool allowUnit)
{ {
++i; ++i;
if (i == end) throw UsageError(format("`%1%' requires an argument") % opt); if (i == end) throw UsageError(format("%1% requires an argument") % opt);
string s = *i; string s = *i;
N multiplier = 1; N multiplier = 1;
if (allowUnit && !s.empty()) { if (allowUnit && !s.empty()) {
@ -56,13 +56,13 @@ template<class N> N getIntArg(const string & opt,
else if (u == 'M') multiplier = 1ULL << 20; else if (u == 'M') multiplier = 1ULL << 20;
else if (u == 'G') multiplier = 1ULL << 30; else if (u == 'G') multiplier = 1ULL << 30;
else if (u == 'T') multiplier = 1ULL << 40; else if (u == 'T') multiplier = 1ULL << 40;
else throw UsageError(format("invalid unit specifier `%1%'") % u); else throw UsageError(format("invalid unit specifier %1%") % u);
s.resize(s.size() - 1); s.resize(s.size() - 1);
} }
} }
N n; N n;
if (!string2Int(s, n)) if (!string2Int(s, n))
throw UsageError(format("`%1%' requires an integer argument") % opt); throw UsageError(format("%1% requires an integer argument") % opt);
return n * multiplier; return n * multiplier;
} }

View file

@ -322,7 +322,7 @@ void Goal::waiteeDone(GoalPtr waitee, ExitCode result)
assert(waitees.find(waitee) != waitees.end()); assert(waitees.find(waitee) != waitees.end());
waitees.erase(waitee); waitees.erase(waitee);
trace(format("waitee `%1%' done; %2% left") % trace(format("waitee %1% done; %2% left") %
waitee->name % waitees.size()); waitee->name % waitees.size());
if (result == ecFailed || result == ecNoSubstituters || result == ecIncompleteClosure) ++nrFailed; if (result == ecFailed || result == ecNoSubstituters || result == ecIncompleteClosure) ++nrFailed;
@ -395,7 +395,7 @@ static void commonChildInit(Pipe & logPipe)
/* Reroute stdin to /dev/null. */ /* Reroute stdin to /dev/null. */
int fdDevNull = open(pathNullDevice.c_str(), O_RDWR); int fdDevNull = open(pathNullDevice.c_str(), O_RDWR);
if (fdDevNull == -1) if (fdDevNull == -1)
throw SysError(format("cannot open `%1%'") % pathNullDevice); throw SysError(format("cannot open %1%") % pathNullDevice);
if (dup2(fdDevNull, STDIN_FILENO) == -1) if (dup2(fdDevNull, STDIN_FILENO) == -1)
throw SysError("cannot dup null device into stdin"); throw SysError("cannot dup null device into stdin");
close(fdDevNull); close(fdDevNull);
@ -475,29 +475,29 @@ void UserLock::acquire()
/* Get the members of the build-users-group. */ /* Get the members of the build-users-group. */
struct group * gr = getgrnam(settings.buildUsersGroup.c_str()); struct group * gr = getgrnam(settings.buildUsersGroup.c_str());
if (!gr) if (!gr)
throw Error(format("the group `%1%' specified in `build-users-group' does not exist") throw Error(format("the group %1% specified in build-users-group does not exist")
% settings.buildUsersGroup); % settings.buildUsersGroup);
gid = gr->gr_gid; gid = gr->gr_gid;
/* Copy the result of getgrnam. */ /* Copy the result of getgrnam. */
Strings users; Strings users;
for (char * * p = gr->gr_mem; *p; ++p) { for (char * * p = gr->gr_mem; *p; ++p) {
debug(format("found build user `%1%'") % *p); debug(format("found build user %1%") % *p);
users.push_back(*p); users.push_back(*p);
} }
if (users.empty()) if (users.empty())
throw Error(format("the build users group `%1%' has no members") throw Error(format("the build users group %1% has no members")
% settings.buildUsersGroup); % settings.buildUsersGroup);
/* Find a user account that isn't currently in use for another /* Find a user account that isn't currently in use for another
build. */ build. */
foreach (Strings::iterator, i, users) { foreach (Strings::iterator, i, users) {
debug(format("trying user `%1%'") % *i); debug(format("trying user %1%") % *i);
struct passwd * pw = getpwnam(i->c_str()); struct passwd * pw = getpwnam(i->c_str());
if (!pw) if (!pw)
throw Error(format("the user `%1%' in the group `%2%' does not exist") throw Error(format("the user %1% in the group %2% does not exist")
% *i % settings.buildUsersGroup); % *i % settings.buildUsersGroup);
createDirs(settings.nixStateDir + "/userpool"); createDirs(settings.nixStateDir + "/userpool");
@ -510,7 +510,7 @@ void UserLock::acquire()
AutoCloseFD fd = open(fnUserLock.c_str(), O_RDWR | O_CREAT, 0600); AutoCloseFD fd = open(fnUserLock.c_str(), O_RDWR | O_CREAT, 0600);
if (fd == -1) if (fd == -1)
throw SysError(format("opening user lock `%1%'") % fnUserLock); throw SysError(format("opening user lock %1%") % fnUserLock);
closeOnExec(fd); closeOnExec(fd);
if (lockFile(fd, ltWrite, false)) { if (lockFile(fd, ltWrite, false)) {
@ -521,7 +521,7 @@ void UserLock::acquire()
/* Sanity check... */ /* Sanity check... */
if (uid == getuid() || uid == geteuid()) if (uid == getuid() || uid == geteuid())
throw Error(format("the Nix user should not be a member of `%1%'") throw Error(format("the Nix user should not be a member of %1%")
% settings.buildUsersGroup); % settings.buildUsersGroup);
return; return;
@ -529,7 +529,7 @@ void UserLock::acquire()
} }
throw Error(format("all build users are currently in use; " throw Error(format("all build users are currently in use; "
"consider creating additional users and adding them to the `%1%' group") "consider creating additional users and adding them to the %1% group")
% settings.buildUsersGroup); % settings.buildUsersGroup);
} }
@ -597,7 +597,7 @@ HookInstance::HookInstance()
commonChildInit(fromHook); commonChildInit(fromHook);
if (chdir("/") == -1) throw SysError("changing into `/"); if (chdir("/") == -1) throw SysError("changing into /");
/* Dup the communication pipes. */ /* Dup the communication pipes. */
if (dup2(toHook.readSide, STDIN_FILENO) == -1) if (dup2(toHook.readSide, STDIN_FILENO) == -1)
@ -613,7 +613,7 @@ HookInstance::HookInstance()
(format("%1%") % settings.buildTimeout).str().c_str(), (format("%1%") % settings.buildTimeout).str().c_str(),
NULL); NULL);
throw SysError(format("executing `%1%'") % buildHook); throw SysError(format("executing %1%") % buildHook);
}); });
pid.setSeparatePG(true); pid.setSeparatePG(true);
@ -843,7 +843,7 @@ DerivationGoal::DerivationGoal(const Path & drvPath, const StringSet & wantedOut
{ {
this->drvPath = drvPath; this->drvPath = drvPath;
state = &DerivationGoal::init; state = &DerivationGoal::init;
name = (format("building of `%1%'") % drvPath).str(); name = (format("building of %1%") % drvPath).str();
trace("created"); trace("created");
} }
@ -924,7 +924,7 @@ void DerivationGoal::init()
trace("init"); trace("init");
if (settings.readOnlyMode) if (settings.readOnlyMode)
throw Error(format("cannot build derivation `%1%' - no write access to the Nix store") % drvPath); throw Error(format("cannot build derivation %1% - no write access to the Nix store") % drvPath);
/* The first thing to do is to make sure that the derivation /* The first thing to do is to make sure that the derivation
exists. If it doesn't, it may be created through a exists. If it doesn't, it may be created through a
@ -940,7 +940,7 @@ void DerivationGoal::haveDerivation()
trace("loading derivation"); trace("loading derivation");
if (nrFailed != 0) { if (nrFailed != 0) {
printMsg(lvlError, format("cannot build missing derivation `%1%'") % drvPath); printMsg(lvlError, format("cannot build missing derivation %1%") % drvPath);
amDone(ecFailed); amDone(ecFailed);
return; return;
} }
@ -991,7 +991,7 @@ void DerivationGoal::outputsSubstituted()
trace("all outputs substituted (maybe)"); trace("all outputs substituted (maybe)");
if (nrFailed > 0 && nrFailed > nrNoSubstituters + nrIncompleteClosure && !settings.tryFallback) if (nrFailed > 0 && nrFailed > nrNoSubstituters + nrIncompleteClosure && !settings.tryFallback)
throw Error(format("some substitutes for the outputs of derivation `%1%' failed (usually happens due to networking issues); try `--fallback' to build derivation from source ") % drvPath); throw Error(format("some substitutes for the outputs of derivation %1% failed (usually happens due to networking issues); try --fallback to build derivation from source ") % drvPath);
/* If the substitutes form an incomplete closure, then we should /* If the substitutes form an incomplete closure, then we should
build the dependencies of this derivation, but after that, we build the dependencies of this derivation, but after that, we
@ -1016,7 +1016,7 @@ void DerivationGoal::outputsSubstituted()
return; return;
} }
if (buildMode == bmCheck && nrInvalid > 0) if (buildMode == bmCheck && nrInvalid > 0)
throw Error(format("some outputs of `%1%' are not valid, so checking is not possible") % drvPath); throw Error(format("some outputs of %1% are not valid, so checking is not possible") % drvPath);
/* Otherwise, at least one of the output paths could not be /* Otherwise, at least one of the output paths could not be
produced using a substitute. So we have to build instead. */ produced using a substitute. So we have to build instead. */
@ -1072,7 +1072,7 @@ void DerivationGoal::repairClosure()
PathSet broken; PathSet broken;
foreach (PathSet::iterator, i, outputClosure) { foreach (PathSet::iterator, i, outputClosure) {
if (worker.store.pathContentsGood(*i)) continue; if (worker.store.pathContentsGood(*i)) continue;
printMsg(lvlError, format("found corrupted or missing path `%1%' in the output closure of `%2%'") % *i % drvPath); printMsg(lvlError, format("found corrupted or missing path %1% in the output closure of %2%") % *i % drvPath);
Path drvPath2 = outputsToDrv[*i]; Path drvPath2 = outputsToDrv[*i];
if (drvPath2 == "") if (drvPath2 == "")
addWaitee(worker.makeSubstitutionGoal(*i, true)); addWaitee(worker.makeSubstitutionGoal(*i, true));
@ -1093,7 +1093,7 @@ void DerivationGoal::closureRepaired()
{ {
trace("closure repaired"); trace("closure repaired");
if (nrFailed > 0) if (nrFailed > 0)
throw Error(format("some paths in the output closure of derivation `%1%' could not be repaired") % drvPath); throw Error(format("some paths in the output closure of derivation %1% could not be repaired") % drvPath);
amDone(ecSuccess); amDone(ecSuccess);
} }
@ -1104,7 +1104,7 @@ void DerivationGoal::inputsRealised()
if (nrFailed != 0) { if (nrFailed != 0) {
printMsg(lvlError, printMsg(lvlError,
format("cannot build derivation `%1%': %2% dependencies couldn't be built") format("cannot build derivation %1%: %2% dependencies couldn't be built")
% drvPath % nrFailed); % drvPath % nrFailed);
amDone(ecFailed); amDone(ecFailed);
return; return;
@ -1120,7 +1120,7 @@ void DerivationGoal::inputsRealised()
/* The outputs are referenceable paths. */ /* The outputs are referenceable paths. */
foreach (DerivationOutputs::iterator, i, drv.outputs) { foreach (DerivationOutputs::iterator, i, drv.outputs) {
debug(format("building path `%1%'") % i->second.path); debug(format("building path %1%") % i->second.path);
allPaths.insert(i->second.path); allPaths.insert(i->second.path);
} }
@ -1138,7 +1138,7 @@ void DerivationGoal::inputsRealised()
computeFSClosure(worker.store, inDrv.outputs[*j].path, inputPaths); computeFSClosure(worker.store, inDrv.outputs[*j].path, inputPaths);
else else
throw Error( throw Error(
format("derivation `%1%' requires non-existent output `%2%' from input derivation `%3%'") format("derivation %1% requires non-existent output %2% from input derivation %3%")
% drvPath % *j % i->first); % drvPath % *j % i->first);
} }
@ -1206,7 +1206,7 @@ void DerivationGoal::tryToBuild()
goal to sleep until another goal finishes, then try again. */ goal to sleep until another goal finishes, then try again. */
foreach (DerivationOutputs::iterator, i, drv.outputs) foreach (DerivationOutputs::iterator, i, drv.outputs)
if (pathIsLockedByMe(i->second.path)) { if (pathIsLockedByMe(i->second.path)) {
debug(format("putting derivation `%1%' to sleep because `%2%' is locked by another goal") debug(format("putting derivation %1% to sleep because %2% is locked by another goal")
% drvPath % i->second.path); % drvPath % i->second.path);
worker.waitForAnyGoal(shared_from_this()); worker.waitForAnyGoal(shared_from_this());
return; return;
@ -1232,7 +1232,7 @@ void DerivationGoal::tryToBuild()
validPaths = checkPathValidity(true, buildMode == bmRepair); validPaths = checkPathValidity(true, buildMode == bmRepair);
assert(buildMode != bmCheck || validPaths.size() == drv.outputs.size()); assert(buildMode != bmCheck || validPaths.size() == drv.outputs.size());
if (buildMode != bmCheck && validPaths.size() == drv.outputs.size()) { if (buildMode != bmCheck && validPaths.size() == drv.outputs.size()) {
debug(format("skipping build of derivation `%1%', someone beat us to it") % drvPath); debug(format("skipping build of derivation %1%, someone beat us to it") % drvPath);
outputLocks.setDeletion(true); outputLocks.setDeletion(true);
amDone(ecSuccess); amDone(ecSuccess);
return; return;
@ -1248,7 +1248,7 @@ void DerivationGoal::tryToBuild()
Path path = i->second.path; Path path = i->second.path;
if (worker.store.isValidPath(path)) continue; if (worker.store.isValidPath(path)) continue;
if (!pathExists(path)) continue; if (!pathExists(path)) continue;
debug(format("removing invalid path `%1%'") % path); debug(format("removing invalid path %1%") % path);
deletePath(path); deletePath(path);
} }
@ -1326,7 +1326,7 @@ void replaceValidPath(const Path & storePath, const Path tmpPath)
if (pathExists(storePath)) if (pathExists(storePath))
rename(storePath.c_str(), oldPath.c_str()); rename(storePath.c_str(), oldPath.c_str());
if (rename(tmpPath.c_str(), storePath.c_str()) == -1) if (rename(tmpPath.c_str(), storePath.c_str()) == -1)
throw SysError(format("moving `%1%' to `%2%'") % tmpPath % storePath); throw SysError(format("moving %1% to %2%") % tmpPath % storePath);
if (pathExists(oldPath)) if (pathExists(oldPath))
deletePath(oldPath); deletePath(oldPath);
} }
@ -1352,7 +1352,7 @@ void DerivationGoal::buildDone()
status = pid.wait(true); status = pid.wait(true);
} }
debug(format("builder process for `%1%' finished") % drvPath); debug(format("builder process for %1% finished") % drvPath);
/* So the child is gone now. */ /* So the child is gone now. */
worker.childTerminated(savedPid); worker.childTerminated(savedPid);
@ -1409,7 +1409,7 @@ void DerivationGoal::buildDone()
if (diskFull) if (diskFull)
printMsg(lvlError, "note: build failure may have been caused by lack of free disk space"); printMsg(lvlError, "note: build failure may have been caused by lack of free disk space");
throw BuildError(format("builder for `%1%' %2%") throw BuildError(format("builder for %1% %2%")
% drvPath % statusToString(status)); % drvPath % statusToString(status));
} }
@ -1519,12 +1519,12 @@ HookReply DerivationGoal::tryBuildHook()
writeToStderr(s); writeToStderr(s);
} }
debug(format("hook reply is `%1%'") % reply); debug(format("hook reply is %1%") % reply);
if (reply == "decline" || reply == "postpone") if (reply == "decline" || reply == "postpone")
return reply == "decline" ? rpDecline : rpPostpone; return reply == "decline" ? rpDecline : rpPostpone;
else if (reply != "accept") else if (reply != "accept")
throw Error(format("bad hook reply `%1%'") % reply); throw Error(format("bad hook reply %1%") % reply);
printMsg(lvlTalkative, format("using hook to build path(s) %1%") % showPaths(missingPaths)); printMsg(lvlTalkative, format("using hook to build path(s) %1%") % showPaths(missingPaths));
@ -1571,7 +1571,7 @@ HookReply DerivationGoal::tryBuildHook()
void chmod_(const Path & path, mode_t mode) void chmod_(const Path & path, mode_t mode)
{ {
if (chmod(path.c_str(), mode) == -1) if (chmod(path.c_str(), mode) == -1)
throw SysError(format("setting permissions on `%1%'") % path); throw SysError(format("setting permissions on %1%") % path);
} }
@ -1594,7 +1594,7 @@ void DerivationGoal::startBuilder()
if (settings.printBuildTrace) if (settings.printBuildTrace)
printMsg(lvlError, format("@ unsupported-platform %1% %2%") % drvPath % drv.platform); printMsg(lvlError, format("@ unsupported-platform %1% %2%") % drvPath % drv.platform);
throw Error( throw Error(
format("a `%1%' is required to build `%3%', but I am a `%2%'") format("a %1% is required to build %3%, but I am a %2%")
% drv.platform % settings.thisSystem % drvPath); % drv.platform % settings.thisSystem % drvPath);
} }
@ -1674,7 +1674,7 @@ void DerivationGoal::startBuilder()
string s = get(drv.env, "exportReferencesGraph"); string s = get(drv.env, "exportReferencesGraph");
Strings ss = tokenizeString<Strings>(s); Strings ss = tokenizeString<Strings>(s);
if (ss.size() % 2 != 0) if (ss.size() % 2 != 0)
throw BuildError(format("odd number of tokens in `exportReferencesGraph': `%1%'") % s); throw BuildError(format("odd number of tokens in exportReferencesGraph: %1%") % s);
for (Strings::iterator i = ss.begin(); i != ss.end(); ) { for (Strings::iterator i = ss.begin(); i != ss.end(); ) {
string fileName = *i++; string fileName = *i++;
checkStoreName(fileName); /* !!! abuse of this function */ checkStoreName(fileName); /* !!! abuse of this function */
@ -1682,11 +1682,11 @@ void DerivationGoal::startBuilder()
/* Check that the store path is valid. */ /* Check that the store path is valid. */
Path storePath = *i++; Path storePath = *i++;
if (!isInStore(storePath)) if (!isInStore(storePath))
throw BuildError(format("`exportReferencesGraph' contains a non-store path `%1%'") throw BuildError(format("exportReferencesGraph contains a non-store path %1%")
% storePath); % storePath);
storePath = toStorePath(storePath); storePath = toStorePath(storePath);
if (!worker.store.isValidPath(storePath)) if (!worker.store.isValidPath(storePath))
throw BuildError(format("`exportReferencesGraph' contains an invalid path `%1%'") throw BuildError(format("exportReferencesGraph contains an invalid path %1%")
% storePath); % storePath);
/* If there are derivations in the graph, then include their /* If there are derivations in the graph, then include their
@ -1724,7 +1724,7 @@ void DerivationGoal::startBuilder()
/* Change ownership of the temporary build directory. */ /* Change ownership of the temporary build directory. */
if (chown(tmpDir.c_str(), buildUser.getUID(), buildUser.getGID()) == -1) if (chown(tmpDir.c_str(), buildUser.getUID(), buildUser.getGID()) == -1)
throw SysError(format("cannot change ownership of `%1%'") % tmpDir); throw SysError(format("cannot change ownership of %1%") % tmpDir);
/* Check that the Nix store has the appropriate permissions, /* Check that the Nix store has the appropriate permissions,
i.e., owned by root and mode 1775 (sticky bit on so that i.e., owned by root and mode 1775 (sticky bit on so that
@ -1732,13 +1732,13 @@ void DerivationGoal::startBuilder()
outputs of other processes). */ outputs of other processes). */
struct stat st; struct stat st;
if (stat(settings.nixStore.c_str(), &st) == -1) if (stat(settings.nixStore.c_str(), &st) == -1)
throw SysError(format("cannot stat `%1%'") % settings.nixStore); throw SysError(format("cannot stat %1%") % settings.nixStore);
if (!(st.st_mode & S_ISVTX) || if (!(st.st_mode & S_ISVTX) ||
((st.st_mode & S_IRWXG) != S_IRWXG) || ((st.st_mode & S_IRWXG) != S_IRWXG) ||
(st.st_gid != buildUser.getGID())) (st.st_gid != buildUser.getGID()))
throw Error(format( throw Error(format(
"builder does not have write permission to `%2%'; " "builder does not have write permission to %2%; "
"try `chgrp %1% %2%; chmod 1775 %2%'") "try chgrp %1% %2%; chmod 1775 %2%")
% buildUser.getGID() % settings.nixStore); % buildUser.getGID() % settings.nixStore);
} }
@ -1767,7 +1767,7 @@ void DerivationGoal::startBuilder()
/* Clean up the chroot directory automatically. */ /* Clean up the chroot directory automatically. */
autoDelChroot = std::shared_ptr<AutoDelete>(new AutoDelete(chrootRootDir)); autoDelChroot = std::shared_ptr<AutoDelete>(new AutoDelete(chrootRootDir));
printMsg(lvlChatty, format("setting up chroot environment in `%1%'") % chrootRootDir); printMsg(lvlChatty, format("setting up chroot environment in %1%") % chrootRootDir);
/* Create a writable /tmp in the chroot. Many builders need /* Create a writable /tmp in the chroot. Many builders need
this. (Of course they should really respect $TMPDIR this. (Of course they should really respect $TMPDIR
@ -1824,7 +1824,7 @@ void DerivationGoal::startBuilder()
foreach (PathSet::iterator, i, inputPaths) { foreach (PathSet::iterator, i, inputPaths) {
struct stat st; struct stat st;
if (lstat(i->c_str(), &st)) if (lstat(i->c_str(), &st))
throw SysError(format("getting attributes of path `%1%'") % *i); throw SysError(format("getting attributes of path %1%") % *i);
if (S_ISDIR(st.st_mode)) if (S_ISDIR(st.st_mode))
dirsInChroot[*i] = *i; dirsInChroot[*i] = *i;
else { else {
@ -1835,7 +1835,7 @@ void DerivationGoal::startBuilder()
which is quite possible after a `nix-store which is quite possible after a `nix-store
--optimise'. */ --optimise'. */
if (errno != EMLINK) if (errno != EMLINK)
throw SysError(format("linking `%1%' to `%2%'") % p % *i); throw SysError(format("linking %1% to %2%") % p % *i);
StringSink sink; StringSink sink;
dumpPath(*i, sink); dumpPath(*i, sink);
StringSource source(sink.s); StringSource source(sink.s);
@ -1862,7 +1862,7 @@ void DerivationGoal::startBuilder()
else { else {
if (pathExists(homeDir)) if (pathExists(homeDir))
throw Error(format("directory `%1%' exists; please remove it") % homeDir); throw Error(format("directory %1% exists; please remove it") % homeDir);
/* We're not doing a chroot build, but we have some valid /* We're not doing a chroot build, but we have some valid
output paths. Since we can't just overwrite or delete output paths. Since we can't just overwrite or delete
@ -1889,7 +1889,7 @@ void DerivationGoal::startBuilder()
/* Run the builder. */ /* Run the builder. */
printMsg(lvlChatty, format("executing builder `%1%'") % drv.builder); printMsg(lvlChatty, format("executing builder %1%") % drv.builder);
/* Create the log file. */ /* Create the log file. */
Path logFile = openLogFile(); Path logFile = openLogFile();
@ -2004,7 +2004,7 @@ void DerivationGoal::initChild()
vector<string> fields = tokenizeString<vector<string> >(*i, " "); vector<string> fields = tokenizeString<vector<string> >(*i, " ");
string fs = decodeOctalEscaped(fields.at(4)); string fs = decodeOctalEscaped(fields.at(4));
if (mount(0, fs.c_str(), 0, MS_PRIVATE, 0) == -1) if (mount(0, fs.c_str(), 0, MS_PRIVATE, 0) == -1)
throw SysError(format("unable to make filesystem `%1%' private") % fs); throw SysError(format("unable to make filesystem %1% private") % fs);
} }
/* Set up a nearly empty /dev, unless the user asked to /* Set up a nearly empty /dev, unless the user asked to
@ -2038,9 +2038,9 @@ void DerivationGoal::initChild()
Path source = i->second; Path source = i->second;
Path target = chrootRootDir + i->first; Path target = chrootRootDir + i->first;
if (source == "/proc") continue; // backwards compatibility if (source == "/proc") continue; // backwards compatibility
debug(format("bind mounting `%1%' to `%2%'") % source % target); debug(format("bind mounting %1% to %2%") % source % target);
if (stat(source.c_str(), &st) == -1) if (stat(source.c_str(), &st) == -1)
throw SysError(format("getting attributes of path `%1%'") % source); throw SysError(format("getting attributes of path %1%") % source);
if (S_ISDIR(st.st_mode)) if (S_ISDIR(st.st_mode))
createDirs(target); createDirs(target);
else { else {
@ -2048,7 +2048,7 @@ void DerivationGoal::initChild()
writeFile(target, ""); writeFile(target, "");
} }
if (mount(source.c_str(), target.c_str(), "", MS_BIND, 0) == -1) if (mount(source.c_str(), target.c_str(), "", MS_BIND, 0) == -1)
throw SysError(format("bind mount from `%1%' to `%2%' failed") % source % target); throw SysError(format("bind mount from %1% to %2% failed") % source % target);
} }
/* Bind a new instance of procfs on /proc to reflect our /* Bind a new instance of procfs on /proc to reflect our
@ -2085,12 +2085,12 @@ void DerivationGoal::initChild()
doesn't matter, since due to the bind mount tmpDir and doesn't matter, since due to the bind mount tmpDir and
tmpRootDit/tmpDir are the same directories.) */ tmpRootDit/tmpDir are the same directories.) */
if (chroot(chrootRootDir.c_str()) == -1) if (chroot(chrootRootDir.c_str()) == -1)
throw SysError(format("cannot change root directory to `%1%'") % chrootRootDir); throw SysError(format("cannot change root directory to %1%") % chrootRootDir);
} }
#endif #endif
if (chdir(tmpDir.c_str()) == -1) if (chdir(tmpDir.c_str()) == -1)
throw SysError(format("changing into `%1%'") % tmpDir); throw SysError(format("changing into %1%") % tmpDir);
/* Close all other file descriptors. */ /* Close all other file descriptors. */
closeMostFDs(set<int>()); closeMostFDs(set<int>());
@ -2132,7 +2132,7 @@ void DerivationGoal::initChild()
setuid() when run as root sets the real, effective and setuid() when run as root sets the real, effective and
saved UIDs. */ saved UIDs. */
if (buildUser.enabled()) { if (buildUser.enabled()) {
printMsg(lvlChatty, format("switching to user `%1%'") % buildUser.getUser()); printMsg(lvlChatty, format("switching to user %1%") % buildUser.getUser());
if (setgroups(0, 0) == -1) if (setgroups(0, 0) == -1)
throw SysError("cannot clear the set of supplementary groups"); throw SysError("cannot clear the set of supplementary groups");
@ -2163,7 +2163,7 @@ void DerivationGoal::initChild()
/* Execute the program. This should not return. */ /* Execute the program. This should not return. */
execve(program.c_str(), (char * *) &args[0], (char * *) envArr); execve(program.c_str(), (char * *) &args[0], (char * *) envArr);
throw SysError(format("executing `%1%'") % drv.builder); throw SysError(format("executing %1%") % drv.builder);
} catch (std::exception & e) { } catch (std::exception & e) {
writeToStderr("while setting up the build environment: " + string(e.what()) + "\n"); writeToStderr("while setting up the build environment: " + string(e.what()) + "\n");
@ -2187,7 +2187,7 @@ PathSet parseReferenceSpecifiers(const Derivation & drv, string attr)
else if (drv.outputs.find(*i) != drv.outputs.end()) else if (drv.outputs.find(*i) != drv.outputs.end())
result.insert(drv.outputs.find(*i)->second.path); result.insert(drv.outputs.find(*i)->second.path);
else throw BuildError( else throw BuildError(
format("derivation contains an illegal reference specifier `%1%'") format("derivation contains an illegal reference specifier %1%")
% *i); % *i);
} }
return result; return result;
@ -2224,7 +2224,7 @@ void DerivationGoal::registerOutputs()
replaceValidPath(path, actualPath); replaceValidPath(path, actualPath);
else else
if (buildMode != bmCheck && rename(actualPath.c_str(), path.c_str()) == -1) if (buildMode != bmCheck && rename(actualPath.c_str(), path.c_str()) == -1)
throw SysError(format("moving build output `%1%' from the chroot to the Nix store") % path); throw SysError(format("moving build output %1% from the chroot to the Nix store") % path);
} }
if (buildMode != bmCheck) actualPath = path; if (buildMode != bmCheck) actualPath = path;
} else { } else {
@ -2241,9 +2241,9 @@ void DerivationGoal::registerOutputs()
if (lstat(actualPath.c_str(), &st) == -1) { if (lstat(actualPath.c_str(), &st) == -1) {
if (errno == ENOENT) if (errno == ENOENT)
throw BuildError( throw BuildError(
format("builder for `%1%' failed to produce output path `%2%'") format("builder for %1% failed to produce output path %2%")
% drvPath % path); % drvPath % path);
throw SysError(format("getting attributes of path `%1%'") % actualPath); throw SysError(format("getting attributes of path %1%") % actualPath);
} }
#ifndef __CYGWIN__ #ifndef __CYGWIN__
@ -2253,13 +2253,13 @@ void DerivationGoal::registerOutputs()
user. */ user. */
if ((!S_ISLNK(st.st_mode) && (st.st_mode & (S_IWGRP | S_IWOTH))) || if ((!S_ISLNK(st.st_mode) && (st.st_mode & (S_IWGRP | S_IWOTH))) ||
(buildUser.enabled() && st.st_uid != buildUser.getUID())) (buildUser.enabled() && st.st_uid != buildUser.getUID()))
throw BuildError(format("suspicious ownership or permission on `%1%'; rejecting this build output") % path); throw BuildError(format("suspicious ownership or permission on %1%; rejecting this build output") % path);
#endif #endif
/* Apply hash rewriting if necessary. */ /* Apply hash rewriting if necessary. */
bool rewritten = false; bool rewritten = false;
if (!rewritesFromTmp.empty()) { if (!rewritesFromTmp.empty()) {
printMsg(lvlError, format("warning: rewriting hashes in `%1%'; cross fingers") % path); printMsg(lvlError, format("warning: rewriting hashes in %1%; cross fingers") % path);
/* Canonicalise first. This ensures that the path we're /* Canonicalise first. This ensures that the path we're
rewriting doesn't contain a hard link to /etc/shadow or rewriting doesn't contain a hard link to /etc/shadow or
@ -2278,7 +2278,7 @@ void DerivationGoal::registerOutputs()
} }
startNest(nest, lvlTalkative, startNest(nest, lvlTalkative,
format("scanning for references inside `%1%'") % path); format("scanning for references inside %1%") % path);
/* Check that fixed-output derivations produced the right /* Check that fixed-output derivations produced the right
outputs (i.e., the content hash should match the specified outputs (i.e., the content hash should match the specified
@ -2293,14 +2293,14 @@ void DerivationGoal::registerOutputs()
execute permission. */ execute permission. */
if (!S_ISREG(st.st_mode) || (st.st_mode & S_IXUSR) != 0) if (!S_ISREG(st.st_mode) || (st.st_mode & S_IXUSR) != 0)
throw BuildError( throw BuildError(
format("output path `%1% should be a non-executable regular file") % path); format("output path %1% should be a non-executable regular file") % path);
} }
/* Check the hash. */ /* Check the hash. */
Hash h2 = recursive ? hashPath(ht, actualPath).first : hashFile(ht, actualPath); Hash h2 = recursive ? hashPath(ht, actualPath).first : hashFile(ht, actualPath);
if (h != h2) if (h != h2)
throw BuildError( throw BuildError(
format("output path `%1%' should have %2% hash `%3%', instead has `%4%'") format("output path %1% should have %2% hash %3%, instead has %4%")
% path % i->second.hashAlgo % printHash16or32(h) % printHash16or32(h2)); % path % i->second.hashAlgo % printHash16or32(h) % printHash16or32(h2));
} }
@ -2319,7 +2319,7 @@ void DerivationGoal::registerOutputs()
if (buildMode == bmCheck) { if (buildMode == bmCheck) {
ValidPathInfo info = worker.store.queryPathInfo(path); ValidPathInfo info = worker.store.queryPathInfo(path);
if (hash.first != info.hash) if (hash.first != info.hash)
throw Error(format("derivation `%2%' may not be deterministic: hash mismatch in output `%1%'") % drvPath % path); throw Error(format("derivation %2% may not be deterministic: hash mismatch in output %1%") % drvPath % path);
continue; continue;
} }
@ -2328,9 +2328,9 @@ void DerivationGoal::registerOutputs()
foreach (PathSet::iterator, i, inputPaths) { foreach (PathSet::iterator, i, inputPaths) {
PathSet::iterator j = references.find(*i); PathSet::iterator j = references.find(*i);
if (j == references.end()) if (j == references.end())
debug(format("unreferenced input: `%1%'") % *i); debug(format("unreferenced input: %1%") % *i);
else else
debug(format("referenced input: `%1%'") % *i); debug(format("referenced input: %1%") % *i);
} }
/* If the derivation specifies an `allowedReferences' /* If the derivation specifies an `allowedReferences'
@ -2341,7 +2341,7 @@ void DerivationGoal::registerOutputs()
PathSet allowed = parseReferenceSpecifiers(drv, get(drv.env, "allowedReferences")); PathSet allowed = parseReferenceSpecifiers(drv, get(drv.env, "allowedReferences"));
foreach (PathSet::iterator, i, references) foreach (PathSet::iterator, i, references)
if (allowed.find(*i) == allowed.end()) if (allowed.find(*i) == allowed.end())
throw BuildError(format("output is not allowed to refer to path `%1%'") % *i); throw BuildError(format("output is not allowed to refer to path %1%") % *i);
} }
worker.store.optimisePath(path); // FIXME: combine with scanForReferences() worker.store.optimisePath(path); // FIXME: combine with scanForReferences()
@ -2385,22 +2385,22 @@ Path DerivationGoal::openLogFile()
Path logFileName = (format("%1%/%2%.bz2") % dir % string(baseName, 2)).str(); Path logFileName = (format("%1%/%2%.bz2") % dir % string(baseName, 2)).str();
AutoCloseFD fd = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666); AutoCloseFD fd = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
if (fd == -1) throw SysError(format("creating log file `%1%'") % logFileName); if (fd == -1) throw SysError(format("creating log file %1%") % logFileName);
closeOnExec(fd); closeOnExec(fd);
if (!(fLogFile = fdopen(fd.borrow(), "w"))) if (!(fLogFile = fdopen(fd.borrow(), "w")))
throw SysError(format("opening file `%1%'") % logFileName); throw SysError(format("opening file %1%") % logFileName);
int err; int err;
if (!(bzLogFile = BZ2_bzWriteOpen(&err, fLogFile, 9, 0, 0))) if (!(bzLogFile = BZ2_bzWriteOpen(&err, fLogFile, 9, 0, 0)))
throw Error(format("cannot open compressed log file `%1%'") % logFileName); throw Error(format("cannot open compressed log file %1%") % logFileName);
return logFileName; return logFileName;
} else { } else {
Path logFileName = (format("%1%/%2%") % dir % string(baseName, 2)).str(); Path logFileName = (format("%1%/%2%") % dir % string(baseName, 2)).str();
fdLogFile = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666); fdLogFile = open(logFileName.c_str(), O_CREAT | O_WRONLY | O_TRUNC, 0666);
if (fdLogFile == -1) throw SysError(format("creating log file `%1%'") % logFileName); if (fdLogFile == -1) throw SysError(format("creating log file %1%") % logFileName);
closeOnExec(fdLogFile); closeOnExec(fdLogFile);
return logFileName; return logFileName;
} }
@ -2430,7 +2430,7 @@ void DerivationGoal::deleteTmpDir(bool force)
if (tmpDir != "") { if (tmpDir != "") {
if (settings.keepFailed && !force) { if (settings.keepFailed && !force) {
printMsg(lvlError, printMsg(lvlError,
format("note: keeping build directory `%2%'") format("note: keeping build directory %2%")
% drvPath % tmpDir); % drvPath % tmpDir);
chmod(tmpDir.c_str(), 0755); chmod(tmpDir.c_str(), 0755);
} }
@ -2495,7 +2495,7 @@ bool DerivationGoal::pathFailed(const Path & path)
if (!worker.store.hasPathFailed(path)) return false; if (!worker.store.hasPathFailed(path)) return false;
printMsg(lvlError, format("builder for `%1%' failed previously (cached)") % path); printMsg(lvlError, format("builder for %1% failed previously (cached)") % path);
if (settings.printBuildTrace) if (settings.printBuildTrace)
printMsg(lvlError, format("@ build-failed %1% - cached") % drvPath); printMsg(lvlError, format("@ build-failed %1% - cached") % drvPath);
@ -2597,7 +2597,7 @@ SubstitutionGoal::SubstitutionGoal(const Path & storePath, Worker & worker, bool
{ {
this->storePath = storePath; this->storePath = storePath;
state = &SubstitutionGoal::init; state = &SubstitutionGoal::init;
name = (format("substitution of `%1%'") % storePath).str(); name = (format("substitution of %1%") % storePath).str();
trace("created"); trace("created");
} }
@ -2640,7 +2640,7 @@ void SubstitutionGoal::init()
} }
if (settings.readOnlyMode) if (settings.readOnlyMode)
throw Error(format("cannot substitute path `%1%' - no write access to the Nix store") % storePath); throw Error(format("cannot substitute path %1% - no write access to the Nix store") % storePath);
subs = settings.substituters; subs = settings.substituters;
@ -2655,7 +2655,7 @@ void SubstitutionGoal::tryNext()
if (subs.size() == 0) { if (subs.size() == 0) {
/* None left. Terminate this goal and let someone else deal /* None left. Terminate this goal and let someone else deal
with it. */ with it. */
debug(format("path `%1%' is required, but there is no substituter that can build it") % storePath); debug(format("path %1% is required, but there is no substituter that can build it") % storePath);
/* Hack: don't indicate failure if there were no substituters. /* Hack: don't indicate failure if there were no substituters.
In that case the calling derivation should just do a In that case the calling derivation should just do a
build. */ build. */
@ -2692,7 +2692,7 @@ void SubstitutionGoal::referencesValid()
trace("all references realised"); trace("all references realised");
if (nrFailed > 0) { if (nrFailed > 0) {
debug(format("some references of path `%1%' could not be realised") % storePath); debug(format("some references of path %1% could not be realised") % storePath);
amDone(nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed); amDone(nrNoSubstituters > 0 || nrIncompleteClosure > 0 ? ecIncompleteClosure : ecFailed);
return; return;
} }
@ -2724,7 +2724,7 @@ void SubstitutionGoal::tryToRun()
first, but let's be defensive). */ first, but let's be defensive). */
outputLock.reset(); // make sure this goal's lock is gone outputLock.reset(); // make sure this goal's lock is gone
if (pathIsLockedByMe(storePath)) { if (pathIsLockedByMe(storePath)) {
debug(format("restarting substitution of `%1%' because it's locked by another goal") debug(format("restarting substitution of %1% because it's locked by another goal")
% storePath); % storePath);
worker.waitForAnyGoal(shared_from_this()); worker.waitForAnyGoal(shared_from_this());
return; /* restart in the tryToRun() state when another goal finishes */ return; /* restart in the tryToRun() state when another goal finishes */
@ -2739,13 +2739,13 @@ void SubstitutionGoal::tryToRun()
/* Check again whether the path is invalid. */ /* Check again whether the path is invalid. */
if (!repair && worker.store.isValidPath(storePath)) { if (!repair && worker.store.isValidPath(storePath)) {
debug(format("store path `%1%' has become valid") % storePath); debug(format("store path %1% has become valid") % storePath);
outputLock->setDeletion(true); outputLock->setDeletion(true);
amDone(ecSuccess); amDone(ecSuccess);
return; return;
} }
printMsg(lvlInfo, format("fetching path `%1%'...") % storePath); printMsg(lvlInfo, format("fetching path %1%...") % storePath);
outPipe.create(); outPipe.create();
logPipe.create(); logPipe.create();
@ -2776,7 +2776,7 @@ void SubstitutionGoal::tryToRun()
execv(sub.c_str(), (char * *) argArr); execv(sub.c_str(), (char * *) argArr);
throw SysError(format("executing `%1%'") % sub); throw SysError(format("executing %1%") % sub);
}); });
pid.setSeparatePG(true); pid.setSeparatePG(true);
@ -2818,11 +2818,11 @@ void SubstitutionGoal::finished()
try { try {
if (!statusOk(status)) if (!statusOk(status))
throw SubstError(format("fetching path `%1%' %2%") throw SubstError(format("fetching path %1% %2%")
% storePath % statusToString(status)); % storePath % statusToString(status));
if (!pathExists(destPath)) if (!pathExists(destPath))
throw SubstError(format("substitute did not produce path `%1%'") % destPath); throw SubstError(format("substitute did not produce path %1%") % destPath);
hash = hashPath(htSHA256, destPath); hash = hashPath(htSHA256, destPath);
@ -2833,11 +2833,11 @@ void SubstitutionGoal::finished()
throw Error(format("bad hash from substituter: %1%") % expectedHashStr); throw Error(format("bad hash from substituter: %1%") % expectedHashStr);
HashType hashType = parseHashType(string(expectedHashStr, 0, n)); HashType hashType = parseHashType(string(expectedHashStr, 0, n));
if (hashType == htUnknown) if (hashType == htUnknown)
throw Error(format("unknown hash algorithm in `%1%'") % expectedHashStr); throw Error(format("unknown hash algorithm in %1%") % expectedHashStr);
Hash expectedHash = parseHash16or32(hashType, string(expectedHashStr, n + 1)); Hash expectedHash = parseHash16or32(hashType, string(expectedHashStr, n + 1));
Hash actualHash = hashType == htSHA256 ? hash.first : hashPath(hashType, destPath).first; Hash actualHash = hashType == htSHA256 ? hash.first : hashPath(hashType, destPath).first;
if (expectedHash != actualHash) if (expectedHash != actualHash)
throw SubstError(format("hash mismatch in downloaded path `%1%': expected %2%, got %3%") throw SubstError(format("hash mismatch in downloaded path %1%: expected %2%, got %3%")
% storePath % printHash(expectedHash) % printHash(actualHash)); % storePath % printHash(expectedHash) % printHash(actualHash));
} }
@ -2876,7 +2876,7 @@ void SubstitutionGoal::finished()
worker.store.markContentsGood(storePath); worker.store.markContentsGood(storePath);
printMsg(lvlChatty, printMsg(lvlChatty,
format("substitution of path `%1%' succeeded") % storePath); format("substitution of path %1% succeeded") % storePath);
if (settings.printBuildTrace) if (settings.printBuildTrace)
printMsg(lvlError, format("@ substituter-succeeded %1%") % storePath); printMsg(lvlError, format("@ substituter-succeeded %1%") % storePath);
@ -3101,7 +3101,7 @@ void Worker::run(const Goals & _topGoals)
waitForInput(); waitForInput();
else { else {
if (awake.empty() && settings.maxBuildJobs == 0) throw Error( if (awake.empty() && settings.maxBuildJobs == 0) throw Error(
"unable to start any build; either increase `--max-jobs' " "unable to start any build; either increase --max-jobs "
"or enable distributed builds"); "or enable distributed builds");
assert(!awake.empty()); assert(!awake.empty());
} }
@ -3307,7 +3307,7 @@ void LocalStore::ensurePath(const Path & path)
worker.run(goals); worker.run(goals);
if (goal->getExitCode() != Goal::ecSuccess) if (goal->getExitCode() != Goal::ecSuccess)
throw Error(format("path `%1%' does not exist and cannot be created") % path, worker.exitStatus()); throw Error(format("path %1% does not exist and cannot be created") % path, worker.exitStatus());
} }
@ -3320,7 +3320,7 @@ void LocalStore::repairPath(const Path & path)
worker.run(goals); worker.run(goals);
if (goal->getExitCode() != Goal::ecSuccess) if (goal->getExitCode() != Goal::ecSuccess)
throw Error(format("cannot repair path `%1%'") % path, worker.exitStatus()); throw Error(format("cannot repair path %1%") % path, worker.exitStatus());
} }

View file

@ -20,7 +20,7 @@ void DerivationOutput::parseHashInfo(bool & recursive, HashType & hashType, Hash
hashType = parseHashType(algo); hashType = parseHashType(algo);
if (hashType == htUnknown) if (hashType == htUnknown)
throw Error(format("unknown hash algorithm `%1%'") % algo); throw Error(format("unknown hash algorithm %1%") % algo);
hash = parseHash(hashType, this->hash); hash = parseHash(hashType, this->hash);
} }
@ -48,7 +48,7 @@ static Path parsePath(std::istream & str)
{ {
string s = parseString(str); string s = parseString(str);
if (s.size() == 0 || s[0] != '/') if (s.size() == 0 || s[0] != '/')
throw FormatError(format("bad path `%1%' in derivation") % s); throw FormatError(format("bad path %1% in derivation") % s);
return s; return s;
} }
@ -117,7 +117,7 @@ Derivation readDerivation(const Path & drvPath)
try { try {
return parseDerivation(readFile(drvPath)); return parseDerivation(readFile(drvPath));
} catch (FormatError & e) { } catch (FormatError & e) {
throw Error(format("error parsing derivation `%1%': %2%") % drvPath % e.msg()); throw Error(format("error parsing derivation %1%: %2%") % drvPath % e.msg());
} }
} }

View file

@ -31,11 +31,11 @@ int LocalStore::openGCLock(LockType lockType)
Path fnGCLock = (format("%1%/%2%") Path fnGCLock = (format("%1%/%2%")
% settings.nixStateDir % gcLockName).str(); % settings.nixStateDir % gcLockName).str();
debug(format("acquiring global GC lock `%1%'") % fnGCLock); debug(format("acquiring global GC lock %1%") % fnGCLock);
AutoCloseFD fdGCLock = open(fnGCLock.c_str(), O_RDWR | O_CREAT, 0600); AutoCloseFD fdGCLock = open(fnGCLock.c_str(), O_RDWR | O_CREAT, 0600);
if (fdGCLock == -1) if (fdGCLock == -1)
throw SysError(format("opening global GC lock `%1%'") % fnGCLock); throw SysError(format("opening global GC lock %1%") % fnGCLock);
closeOnExec(fdGCLock); closeOnExec(fdGCLock);
if (!lockFile(fdGCLock, lockType, false)) { if (!lockFile(fdGCLock, lockType, false)) {
@ -63,7 +63,7 @@ static void makeSymlink(const Path & link, const Path & target)
/* Atomically replace the old one. */ /* Atomically replace the old one. */
if (rename(tempLink.c_str(), link.c_str()) == -1) if (rename(tempLink.c_str(), link.c_str()) == -1)
throw SysError(format("cannot rename `%1%' to `%2%'") throw SysError(format("cannot rename %1% to %2%")
% tempLink % link); % tempLink % link);
} }
@ -99,7 +99,7 @@ Path addPermRoot(StoreAPI & store, const Path & _storePath,
/* Don't clobber the the link if it already exists and doesn't /* Don't clobber the the link if it already exists and doesn't
point to the Nix store. */ point to the Nix store. */
if (pathExists(gcRoot) && (!isLink(gcRoot) || !isInStore(readLink(gcRoot)))) if (pathExists(gcRoot) && (!isLink(gcRoot) || !isInStore(readLink(gcRoot))))
throw Error(format("cannot create symlink `%1%'; already exists") % gcRoot); throw Error(format("cannot create symlink %1%; already exists") % gcRoot);
makeSymlink(gcRoot, storePath); makeSymlink(gcRoot, storePath);
store.addIndirectRoot(gcRoot); store.addIndirectRoot(gcRoot);
} }
@ -110,8 +110,8 @@ Path addPermRoot(StoreAPI & store, const Path & _storePath,
if (string(gcRoot, 0, rootsDir.size() + 1) != rootsDir + "/") if (string(gcRoot, 0, rootsDir.size() + 1) != rootsDir + "/")
throw Error(format( throw Error(format(
"path `%1%' is not a valid garbage collector root; " "path %1% is not a valid garbage collector root; "
"it's not in the directory `%2%'") "it's not in the directory %2%")
% gcRoot % rootsDir); % gcRoot % rootsDir);
} }
@ -131,8 +131,8 @@ Path addPermRoot(StoreAPI & store, const Path & _storePath,
if (roots.find(gcRoot) == roots.end()) if (roots.find(gcRoot) == roots.end())
printMsg(lvlError, printMsg(lvlError,
format( format(
"warning: `%1%' is not in a directory where the garbage collector looks for roots; " "warning: %1% is not in a directory where the garbage collector looks for roots; "
"therefore, `%2%' might be removed by the garbage collector") "therefore, %2% might be removed by the garbage collector")
% gcRoot % storePath); % gcRoot % storePath);
} }
@ -173,14 +173,14 @@ void LocalStore::addTempRoot(const Path & path)
fdGCLock.close(); fdGCLock.close();
debug(format("acquiring read lock on `%1%'") % fnTempRoots); debug(format("acquiring read lock on %1%") % fnTempRoots);
lockFile(fdTempRoots, ltRead, true); lockFile(fdTempRoots, ltRead, true);
/* Check whether the garbage collector didn't get in our /* Check whether the garbage collector didn't get in our
way. */ way. */
struct stat st; struct stat st;
if (fstat(fdTempRoots, &st) == -1) if (fstat(fdTempRoots, &st) == -1)
throw SysError(format("statting `%1%'") % fnTempRoots); throw SysError(format("statting %1%") % fnTempRoots);
if (st.st_size == 0) break; if (st.st_size == 0) break;
/* The garbage collector deleted this file before we could /* The garbage collector deleted this file before we could
@ -192,14 +192,14 @@ void LocalStore::addTempRoot(const Path & path)
/* Upgrade the lock to a write lock. This will cause us to block /* Upgrade the lock to a write lock. This will cause us to block
if the garbage collector is holding our lock. */ if the garbage collector is holding our lock. */
debug(format("acquiring write lock on `%1%'") % fnTempRoots); debug(format("acquiring write lock on %1%") % fnTempRoots);
lockFile(fdTempRoots, ltWrite, true); lockFile(fdTempRoots, ltWrite, true);
string s = path + '\0'; string s = path + '\0';
writeFull(fdTempRoots, (const unsigned char *) s.data(), s.size()); writeFull(fdTempRoots, (const unsigned char *) s.data(), s.size());
/* Downgrade to a read lock. */ /* Downgrade to a read lock. */
debug(format("downgrading to read lock on `%1%'") % fnTempRoots); debug(format("downgrading to read lock on %1%") % fnTempRoots);
lockFile(fdTempRoots, ltRead, true); lockFile(fdTempRoots, ltRead, true);
} }
@ -239,12 +239,12 @@ static void readTempRoots(PathSet & tempRoots, FDs & fds)
for (auto & i : tempRootFiles) { for (auto & i : tempRootFiles) {
Path path = (format("%1%/%2%/%3%") % settings.nixStateDir % tempRootsDir % i.name).str(); Path path = (format("%1%/%2%/%3%") % settings.nixStateDir % tempRootsDir % i.name).str();
debug(format("reading temporary root file `%1%'") % path); debug(format("reading temporary root file %1%") % path);
FDPtr fd(new AutoCloseFD(open(path.c_str(), O_RDWR, 0666))); FDPtr fd(new AutoCloseFD(open(path.c_str(), O_RDWR, 0666)));
if (*fd == -1) { if (*fd == -1) {
/* It's okay if the file has disappeared. */ /* It's okay if the file has disappeared. */
if (errno == ENOENT) continue; if (errno == ENOENT) continue;
throw SysError(format("opening temporary roots file `%1%'") % path); throw SysError(format("opening temporary roots file %1%") % path);
} }
/* This should work, but doesn't, for some reason. */ /* This should work, but doesn't, for some reason. */
@ -255,7 +255,7 @@ static void readTempRoots(PathSet & tempRoots, FDs & fds)
only succeed if the owning process has died. In that case only succeed if the owning process has died. In that case
we don't care about its temporary roots. */ we don't care about its temporary roots. */
if (lockFile(*fd, ltWrite, false)) { if (lockFile(*fd, ltWrite, false)) {
printMsg(lvlError, format("removing stale temporary roots file `%1%'") % path); printMsg(lvlError, format("removing stale temporary roots file %1%") % path);
unlink(path.c_str()); unlink(path.c_str());
writeFull(*fd, (const unsigned char *) "d", 1); writeFull(*fd, (const unsigned char *) "d", 1);
continue; continue;
@ -264,7 +264,7 @@ static void readTempRoots(PathSet & tempRoots, FDs & fds)
/* Acquire a read lock. This will prevent the owning process /* Acquire a read lock. This will prevent the owning process
from upgrading to a write lock, therefore it will block in from upgrading to a write lock, therefore it will block in
addTempRoot(). */ addTempRoot(). */
debug(format("waiting for read lock on `%1%'") % path); debug(format("waiting for read lock on %1%") % path);
lockFile(*fd, ltRead, true); lockFile(*fd, ltRead, true);
/* Read the entire file. */ /* Read the entire file. */
@ -275,7 +275,7 @@ static void readTempRoots(PathSet & tempRoots, FDs & fds)
while ((end = contents.find((char) 0, pos)) != string::npos) { while ((end = contents.find((char) 0, pos)) != string::npos) {
Path root(contents, pos, end - pos); Path root(contents, pos, end - pos);
debug(format("got temporary root `%1%'") % root); debug(format("got temporary root %1%") % root);
assertStorePath(root); assertStorePath(root);
tempRoots.insert(root); tempRoots.insert(root);
pos = end + 1; pos = end + 1;
@ -293,7 +293,7 @@ static void foundRoot(StoreAPI & store,
if (store.isValidPath(storePath)) if (store.isValidPath(storePath))
roots[path] = storePath; roots[path] = storePath;
else else
printMsg(lvlInfo, format("skipping invalid root from `%1%' to `%2%'") % path % storePath); printMsg(lvlInfo, format("skipping invalid root from %1% to %2%") % path % storePath);
} }
@ -323,7 +323,7 @@ static void findRoots(StoreAPI & store, const Path & path, unsigned char type, R
target = absPath(target, dirOf(path)); target = absPath(target, dirOf(path));
if (!pathExists(target)) { if (!pathExists(target)) {
if (isInDir(path, settings.nixStateDir + "/" + gcRootsDir + "/auto")) { if (isInDir(path, settings.nixStateDir + "/" + gcRootsDir + "/auto")) {
printMsg(lvlInfo, format("removing stale link from `%1%' to `%2%'") % path % target); printMsg(lvlInfo, format("removing stale link from %1% to %2%") % path % target);
unlink(path.c_str()); unlink(path.c_str());
} }
} else { } else {
@ -346,7 +346,7 @@ static void findRoots(StoreAPI & store, const Path & path, unsigned char type, R
catch (SysError & e) { catch (SysError & e) {
/* We only ignore permanent failures. */ /* We only ignore permanent failures. */
if (e.errNo == EACCES || e.errNo == ENOENT || e.errNo == ENOTDIR) if (e.errNo == EACCES || e.errNo == ENOENT || e.errNo == ENOTDIR)
printMsg(lvlInfo, format("cannot read potential root `%1%'") % path); printMsg(lvlInfo, format("cannot read potential root %1%") % path);
else else
throw; throw;
} }
@ -373,7 +373,7 @@ static void addAdditionalRoots(StoreAPI & store, PathSet & roots)
if (rootFinder.empty()) return; if (rootFinder.empty()) return;
debug(format("executing `%1%' to find additional roots") % rootFinder); debug(format("executing %1% to find additional roots") % rootFinder);
string result = runProgram(rootFinder); string result = runProgram(rootFinder);
@ -383,7 +383,7 @@ static void addAdditionalRoots(StoreAPI & store, PathSet & roots)
if (isInStore(*i)) { if (isInStore(*i)) {
Path path = toStorePath(*i); Path path = toStorePath(*i);
if (roots.find(path) == roots.end() && store.isValidPath(path)) { if (roots.find(path) == roots.end() && store.isValidPath(path)) {
debug(format("got additional root `%1%'") % path); debug(format("got additional root %1%") % path);
roots.insert(path); roots.insert(path);
} }
} }
@ -448,7 +448,7 @@ void LocalStore::deletePathRecursive(GCState & state, const Path & path)
throw SysError(format("getting status of %1%") % path); throw SysError(format("getting status of %1%") % path);
} }
printMsg(lvlInfo, format("deleting `%1%'") % path); printMsg(lvlInfo, format("deleting %1%") % path);
state.results.paths.insert(path); state.results.paths.insert(path);
@ -463,10 +463,10 @@ void LocalStore::deletePathRecursive(GCState & state, const Path & path)
// size. // size.
state.bytesInvalidated += size; state.bytesInvalidated += size;
if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1) if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1)
throw SysError(format("making `%1%' writable") % path); throw SysError(format("making %1% writable") % path);
Path tmp = state.trashDir + "/" + baseNameOf(path); Path tmp = state.trashDir + "/" + baseNameOf(path);
if (rename(path.c_str(), tmp.c_str())) if (rename(path.c_str(), tmp.c_str()))
throw SysError(format("unable to rename `%1%' to `%2%'") % path % tmp); throw SysError(format("unable to rename %1% to %2%") % path % tmp);
} else } else
deleteGarbage(state, path); deleteGarbage(state, path);
@ -490,7 +490,7 @@ bool LocalStore::canReachRoot(GCState & state, PathSet & visited, const Path & p
} }
if (state.roots.find(path) != state.roots.end()) { if (state.roots.find(path) != state.roots.end()) {
printMsg(lvlDebug, format("cannot delete `%1%' because it's a root") % path); printMsg(lvlDebug, format("cannot delete %1% because it's a root") % path);
state.alive.insert(path); state.alive.insert(path);
return true; return true;
} }
@ -538,7 +538,7 @@ void LocalStore::tryToDelete(GCState & state, const Path & path)
if (path == linksDir || path == state.trashDir) return; if (path == linksDir || path == state.trashDir) return;
startNest(nest, lvlDebug, format("considering whether to delete `%1%'") % path); startNest(nest, lvlDebug, format("considering whether to delete %1%") % path);
if (!isValidPath(path)) { if (!isValidPath(path)) {
/* A lock file belonging to a path that we're building right /* A lock file belonging to a path that we're building right
@ -553,7 +553,7 @@ void LocalStore::tryToDelete(GCState & state, const Path & path)
PathSet visited; PathSet visited;
if (canReachRoot(state, visited, path)) { if (canReachRoot(state, visited, path)) {
printMsg(lvlDebug, format("cannot delete `%1%' because it's still reachable") % path); printMsg(lvlDebug, format("cannot delete %1% because it's still reachable") % path);
} else { } else {
/* No path we visited was a root, so everything is garbage. /* No path we visited was a root, so everything is garbage.
But we only delete path and its referrers here so that But we only delete path and its referrers here so that
@ -574,7 +574,7 @@ void LocalStore::tryToDelete(GCState & state, const Path & path)
void LocalStore::removeUnusedLinks(const GCState & state) void LocalStore::removeUnusedLinks(const GCState & state)
{ {
AutoCloseDir dir = opendir(linksDir.c_str()); AutoCloseDir dir = opendir(linksDir.c_str());
if (!dir) throw SysError(format("opening directory `%1%'") % linksDir); if (!dir) throw SysError(format("opening directory %1%") % linksDir);
long long actualSize = 0, unsharedSize = 0; long long actualSize = 0, unsharedSize = 0;
@ -587,7 +587,7 @@ void LocalStore::removeUnusedLinks(const GCState & state)
struct stat st; struct stat st;
if (lstat(path.c_str(), &st) == -1) if (lstat(path.c_str(), &st) == -1)
throw SysError(format("statting `%1%'") % path); throw SysError(format("statting %1%") % path);
if (st.st_nlink != 1) { if (st.st_nlink != 1) {
unsigned long long size = st.st_blocks * 512ULL; unsigned long long size = st.st_blocks * 512ULL;
@ -596,17 +596,17 @@ void LocalStore::removeUnusedLinks(const GCState & state)
continue; continue;
} }
printMsg(lvlTalkative, format("deleting unused link `%1%'") % path); printMsg(lvlTalkative, format("deleting unused link %1%") % path);
if (unlink(path.c_str()) == -1) if (unlink(path.c_str()) == -1)
throw SysError(format("deleting `%1%'") % path); throw SysError(format("deleting %1%") % path);
state.results.bytesFreed += st.st_blocks * 512; state.results.bytesFreed += st.st_blocks * 512;
} }
struct stat st; struct stat st;
if (stat(linksDir.c_str(), &st) == -1) if (stat(linksDir.c_str(), &st) == -1)
throw SysError(format("statting `%1%'") % linksDir); throw SysError(format("statting %1%") % linksDir);
long long overhead = st.st_blocks * 512ULL; long long overhead = st.st_blocks * 512ULL;
printMsg(lvlInfo, format("note: currently hard linking saves %.2f MiB") printMsg(lvlInfo, format("note: currently hard linking saves %.2f MiB")
@ -677,7 +677,7 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
assertStorePath(*i); assertStorePath(*i);
tryToDelete(state, *i); tryToDelete(state, *i);
if (state.dead.find(*i) == state.dead.end()) if (state.dead.find(*i) == state.dead.end())
throw Error(format("cannot delete path `%1%' since it is still alive") % *i); throw Error(format("cannot delete path %1% since it is still alive") % *i);
} }
} else if (options.maxFreed > 0) { } else if (options.maxFreed > 0) {
@ -690,7 +690,7 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
try { try {
AutoCloseDir dir = opendir(settings.nixStore.c_str()); AutoCloseDir dir = opendir(settings.nixStore.c_str());
if (!dir) throw SysError(format("opening directory `%1%'") % settings.nixStore); if (!dir) throw SysError(format("opening directory %1%") % settings.nixStore);
/* Read the store and immediately delete all paths that /* Read the store and immediately delete all paths that
aren't valid. When using --max-freed etc., deleting aren't valid. When using --max-freed etc., deleting
@ -743,7 +743,7 @@ void LocalStore::collectGarbage(const GCOptions & options, GCResults & results)
fds.clear(); fds.clear();
/* Delete the trash directory. */ /* Delete the trash directory. */
printMsg(lvlInfo, format("deleting `%1%'") % state.trashDir); printMsg(lvlInfo, format("deleting %1%") % state.trashDir);
deleteGarbage(state, state.trashDir); deleteGarbage(state, state.trashDir);
/* Clean up the links directory. */ /* Clean up the links directory. */

View file

@ -102,7 +102,7 @@ void Settings::loadConfFile()
if (tokens.empty()) continue; if (tokens.empty()) continue;
if (tokens.size() < 2 || tokens[1] != "=") if (tokens.size() < 2 || tokens[1] != "=")
throw Error(format("illegal configuration line `%1%' in `%2%'") % line % settingsFile); throw Error(format("illegal configuration line %1% in %2%") % line % settingsFile);
string name = tokens[0]; string name = tokens[0];
@ -198,7 +198,7 @@ void Settings::_get(bool & res, const string & name)
if (i == settings.end()) return; if (i == settings.end()) return;
if (i->second == "true") res = true; if (i->second == "true") res = true;
else if (i->second == "false") res = false; else if (i->second == "false") res = false;
else throw Error(format("configuration option `%1%' should be either `true' or `false', not `%2%'") else throw Error(format("configuration option %1% should be either true or false, not %2%")
% name % i->second); % name % i->second);
} }
@ -225,7 +225,7 @@ template<class N> void Settings::_get(N & res, const string & name)
SettingsMap::iterator i = settings.find(name); SettingsMap::iterator i = settings.find(name);
if (i == settings.end()) return; if (i == settings.end()) return;
if (!string2Int(i->second, res)) if (!string2Int(i->second, res))
throw Error(format("configuration setting `%1%' should have an integer value") % name); throw Error(format("configuration setting %1% should have an integer value") % name);
} }

View file

@ -212,10 +212,10 @@ void checkStoreNotSymlink()
struct stat st; struct stat st;
while (path != "/") { while (path != "/") {
if (lstat(path.c_str(), &st)) if (lstat(path.c_str(), &st))
throw SysError(format("getting status of `%1%'") % path); throw SysError(format("getting status of %1%") % path);
if (S_ISLNK(st.st_mode)) if (S_ISLNK(st.st_mode))
throw Error(format( throw Error(format(
"the path `%1%' is a symlink; " "the path %1% is a symlink; "
"this is not allowed for the Nix store and its parent directories") "this is not allowed for the Nix store and its parent directories")
% path); % path);
path = dirOf(path); path = dirOf(path);
@ -254,22 +254,22 @@ LocalStore::LocalStore(bool reserveSpace)
Path perUserDir = profilesDir + "/per-user"; Path perUserDir = profilesDir + "/per-user";
createDirs(perUserDir); createDirs(perUserDir);
if (chmod(perUserDir.c_str(), 01777) == -1) if (chmod(perUserDir.c_str(), 01777) == -1)
throw SysError(format("could not set permissions on `%1%' to 1777") % perUserDir); throw SysError(format("could not set permissions on %1% to 1777") % perUserDir);
struct group * gr = getgrnam(settings.buildUsersGroup.c_str()); struct group * gr = getgrnam(settings.buildUsersGroup.c_str());
if (!gr) if (!gr)
throw Error(format("the group `%1%' specified in `build-users-group' does not exist") throw Error(format("the group %1% specified in build-users-group does not exist")
% settings.buildUsersGroup); % settings.buildUsersGroup);
struct stat st; struct stat st;
if (stat(settings.nixStore.c_str(), &st)) if (stat(settings.nixStore.c_str(), &st))
throw SysError(format("getting attributes of path `%1%'") % settings.nixStore); throw SysError(format("getting attributes of path %1%") % settings.nixStore);
if (st.st_uid != 0 || st.st_gid != gr->gr_gid || (st.st_mode & ~S_IFMT) != 01775) { if (st.st_uid != 0 || st.st_gid != gr->gr_gid || (st.st_mode & ~S_IFMT) != 01775) {
if (chown(settings.nixStore.c_str(), 0, gr->gr_gid) == -1) if (chown(settings.nixStore.c_str(), 0, gr->gr_gid) == -1)
throw SysError(format("changing ownership of path `%1%'") % settings.nixStore); throw SysError(format("changing ownership of path %1%") % settings.nixStore);
if (chmod(settings.nixStore.c_str(), 01775) == -1) if (chmod(settings.nixStore.c_str(), 01775) == -1)
throw SysError(format("changing permissions on path `%1%'") % settings.nixStore); throw SysError(format("changing permissions on path %1%") % settings.nixStore);
} }
} }
@ -372,7 +372,7 @@ int LocalStore::getSchema()
if (pathExists(schemaPath)) { if (pathExists(schemaPath)) {
string s = readFile(schemaPath); string s = readFile(schemaPath);
if (!string2Int(s, curSchema)) if (!string2Int(s, curSchema))
throw Error(format("`%1%' is corrupt") % schemaPath); throw Error(format("%1% is corrupt") % schemaPath);
} }
return curSchema; return curSchema;
} }
@ -381,13 +381,13 @@ int LocalStore::getSchema()
void LocalStore::openDB(bool create) void LocalStore::openDB(bool create)
{ {
if (access(settings.nixDBPath.c_str(), R_OK | W_OK)) if (access(settings.nixDBPath.c_str(), R_OK | W_OK))
throw SysError(format("Nix database directory `%1%' is not writable") % settings.nixDBPath); throw SysError(format("Nix database directory %1% is not writable") % settings.nixDBPath);
/* Open the Nix database. */ /* Open the Nix database. */
string dbPath = settings.nixDBPath + "/db.sqlite"; string dbPath = settings.nixDBPath + "/db.sqlite";
if (sqlite3_open_v2(dbPath.c_str(), &db.db, if (sqlite3_open_v2(dbPath.c_str(), &db.db,
SQLITE_OPEN_READWRITE | (create ? SQLITE_OPEN_CREATE : 0), 0) != SQLITE_OK) SQLITE_OPEN_READWRITE | (create ? SQLITE_OPEN_CREATE : 0), 0) != SQLITE_OK)
throw Error(format("cannot open Nix database `%1%'") % dbPath); throw Error(format("cannot open Nix database %1%") % dbPath);
if (sqlite3_busy_timeout(db, 60 * 60 * 1000) != SQLITE_OK) if (sqlite3_busy_timeout(db, 60 * 60 * 1000) != SQLITE_OK)
throwSQLiteError(db, "setting timeout"); throwSQLiteError(db, "setting timeout");
@ -511,7 +511,7 @@ static void canonicaliseTimestampAndPermissions(const Path & path, const struct
| 0444 | 0444
| (st.st_mode & S_IXUSR ? 0111 : 0); | (st.st_mode & S_IXUSR ? 0111 : 0);
if (chmod(path.c_str(), mode) == -1) if (chmod(path.c_str(), mode) == -1)
throw SysError(format("changing mode of `%1%' to %2$o") % path % mode); throw SysError(format("changing mode of %1% to %2$o") % path % mode);
} }
} }
@ -529,7 +529,7 @@ static void canonicaliseTimestampAndPermissions(const Path & path, const struct
#else #else
if (!S_ISLNK(st.st_mode) && utimes(path.c_str(), times) == -1) if (!S_ISLNK(st.st_mode) && utimes(path.c_str(), times) == -1)
#endif #endif
throw SysError(format("changing modification time of `%1%'") % path); throw SysError(format("changing modification time of %1%") % path);
} }
} }
@ -538,7 +538,7 @@ void canonicaliseTimestampAndPermissions(const Path & path)
{ {
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) if (lstat(path.c_str(), &st))
throw SysError(format("getting attributes of path `%1%'") % path); throw SysError(format("getting attributes of path %1%") % path);
canonicaliseTimestampAndPermissions(path, st); canonicaliseTimestampAndPermissions(path, st);
} }
@ -549,7 +549,7 @@ static void canonicalisePathMetaData_(const Path & path, uid_t fromUid, InodesSe
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) if (lstat(path.c_str(), &st))
throw SysError(format("getting attributes of path `%1%'") % path); throw SysError(format("getting attributes of path %1%") % path);
/* Really make sure that the path is of a supported type. This /* Really make sure that the path is of a supported type. This
has already been checked in dumpPath(). */ has already been checked in dumpPath(). */
@ -564,7 +564,7 @@ static void canonicalisePathMetaData_(const Path & path, uid_t fromUid, InodesSe
if (fromUid != (uid_t) -1 && st.st_uid != fromUid) { if (fromUid != (uid_t) -1 && st.st_uid != fromUid) {
assert(!S_ISDIR(st.st_mode)); assert(!S_ISDIR(st.st_mode));
if (inodesSeen.find(Inode(st.st_dev, st.st_ino)) == inodesSeen.end()) if (inodesSeen.find(Inode(st.st_dev, st.st_ino)) == inodesSeen.end())
throw BuildError(format("invalid ownership on file `%1%'") % path); throw BuildError(format("invalid ownership on file %1%") % path);
mode_t mode = st.st_mode & ~S_IFMT; mode_t mode = st.st_mode & ~S_IFMT;
assert(S_ISLNK(st.st_mode) || (st.st_uid == geteuid() && (mode == 0444 || mode == 0555) && st.st_mtime == mtimeStore)); assert(S_ISLNK(st.st_mode) || (st.st_uid == geteuid() && (mode == 0444 || mode == 0555) && st.st_mtime == mtimeStore));
return; return;
@ -588,7 +588,7 @@ static void canonicalisePathMetaData_(const Path & path, uid_t fromUid, InodesSe
if (!S_ISLNK(st.st_mode) && if (!S_ISLNK(st.st_mode) &&
chown(path.c_str(), geteuid(), (gid_t) -1) == -1) chown(path.c_str(), geteuid(), (gid_t) -1) == -1)
#endif #endif
throw SysError(format("changing owner of `%1%' to %2%") throw SysError(format("changing owner of %1% to %2%")
% path % geteuid()); % path % geteuid());
} }
@ -608,11 +608,11 @@ void canonicalisePathMetaData(const Path & path, uid_t fromUid, InodesSeen & ino
be a symlink, since we can't change its ownership. */ be a symlink, since we can't change its ownership. */
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) if (lstat(path.c_str(), &st))
throw SysError(format("getting attributes of path `%1%'") % path); throw SysError(format("getting attributes of path %1%") % path);
if (st.st_uid != geteuid()) { if (st.st_uid != geteuid()) {
assert(S_ISLNK(st.st_mode)); assert(S_ISLNK(st.st_mode));
throw Error(format("wrong ownership of top-level store path `%1%'") % path); throw Error(format("wrong ownership of top-level store path %1%") % path);
} }
} }
@ -633,7 +633,7 @@ void LocalStore::checkDerivationOutputs(const Path & drvPath, const Derivation &
if (isFixedOutputDrv(drv)) { if (isFixedOutputDrv(drv)) {
DerivationOutputs::const_iterator out = drv.outputs.find("out"); DerivationOutputs::const_iterator out = drv.outputs.find("out");
if (out == drv.outputs.end()) if (out == drv.outputs.end())
throw Error(format("derivation `%1%' does not have an output named `out'") % drvPath); throw Error(format("derivation %1% does not have an output named out") % drvPath);
bool recursive; HashType ht; Hash h; bool recursive; HashType ht; Hash h;
out->second.parseHashInfo(recursive, ht, h); out->second.parseHashInfo(recursive, ht, h);
@ -641,7 +641,7 @@ void LocalStore::checkDerivationOutputs(const Path & drvPath, const Derivation &
StringPairs::const_iterator j = drv.env.find("out"); StringPairs::const_iterator j = drv.env.find("out");
if (out->second.path != outPath || j == drv.env.end() || j->second != outPath) if (out->second.path != outPath || j == drv.env.end() || j->second != outPath)
throw Error(format("derivation `%1%' has incorrect output `%2%', should be `%3%'") throw Error(format("derivation %1% has incorrect output %2%, should be %3%")
% drvPath % out->second.path % outPath); % drvPath % out->second.path % outPath);
} }
@ -658,7 +658,7 @@ void LocalStore::checkDerivationOutputs(const Path & drvPath, const Derivation &
Path outPath = makeOutputPath(i->first, h, drvName); Path outPath = makeOutputPath(i->first, h, drvName);
StringPairs::const_iterator j = drv.env.find(i->first); StringPairs::const_iterator j = drv.env.find(i->first);
if (i->second.path != outPath || j == drv.env.end() || j->second != outPath) if (i->second.path != outPath || j == drv.env.end() || j->second != outPath)
throw Error(format("derivation `%1%' has incorrect output `%2%', should be `%3%'") throw Error(format("derivation %1% has incorrect output %2%, should be %3%")
% drvPath % i->second.path % outPath); % drvPath % i->second.path % outPath);
} }
} }
@ -680,7 +680,7 @@ unsigned long long LocalStore::addValidPath(const ValidPathInfo & info, bool che
else else
stmtRegisterValidPath.bind(); // null stmtRegisterValidPath.bind(); // null
if (sqlite3_step(stmtRegisterValidPath) != SQLITE_DONE) if (sqlite3_step(stmtRegisterValidPath) != SQLITE_DONE)
throwSQLiteError(db, format("registering valid path `%1%' in database") % info.path); throwSQLiteError(db, format("registering valid path %1% in database") % info.path);
unsigned long long id = sqlite3_last_insert_rowid(db); unsigned long long id = sqlite3_last_insert_rowid(db);
/* If this is a derivation, then store the derivation outputs in /* If this is a derivation, then store the derivation outputs in
@ -703,7 +703,7 @@ unsigned long long LocalStore::addValidPath(const ValidPathInfo & info, bool che
stmtAddDerivationOutput.bind(i->first); stmtAddDerivationOutput.bind(i->first);
stmtAddDerivationOutput.bind(i->second.path); stmtAddDerivationOutput.bind(i->second.path);
if (sqlite3_step(stmtAddDerivationOutput) != SQLITE_DONE) if (sqlite3_step(stmtAddDerivationOutput) != SQLITE_DONE)
throwSQLiteError(db, format("adding derivation output for `%1%' in database") % info.path); throwSQLiteError(db, format("adding derivation output for %1% in database") % info.path);
} }
} }
@ -728,7 +728,7 @@ void LocalStore::registerFailedPath(const Path & path)
stmtRegisterFailedPath.bind(path); stmtRegisterFailedPath.bind(path);
stmtRegisterFailedPath.bind(time(0)); stmtRegisterFailedPath.bind(time(0));
if (sqlite3_step(stmtRegisterFailedPath) != SQLITE_DONE) if (sqlite3_step(stmtRegisterFailedPath) != SQLITE_DONE)
throwSQLiteError(db, format("registering failed path `%1%'") % path); throwSQLiteError(db, format("registering failed path %1%") % path);
} end_retry_sqlite; } end_retry_sqlite;
} }
@ -776,7 +776,7 @@ void LocalStore::clearFailedPaths(const PathSet & paths)
SQLiteStmtUse use(stmtClearFailedPath); SQLiteStmtUse use(stmtClearFailedPath);
stmtClearFailedPath.bind(*i); stmtClearFailedPath.bind(*i);
if (sqlite3_step(stmtClearFailedPath) != SQLITE_DONE) if (sqlite3_step(stmtClearFailedPath) != SQLITE_DONE)
throwSQLiteError(db, format("clearing failed path `%1%' in database") % *i); throwSQLiteError(db, format("clearing failed path %1% in database") % *i);
} }
txn.commit(); txn.commit();
@ -788,11 +788,11 @@ Hash parseHashField(const Path & path, const string & s)
{ {
string::size_type colon = s.find(':'); string::size_type colon = s.find(':');
if (colon == string::npos) if (colon == string::npos)
throw Error(format("corrupt hash `%1%' in valid-path entry for `%2%'") throw Error(format("corrupt hash %1% in valid-path entry for %2%")
% s % path); % s % path);
HashType ht = parseHashType(string(s, 0, colon)); HashType ht = parseHashType(string(s, 0, colon));
if (ht == htUnknown) if (ht == htUnknown)
throw Error(format("unknown hash type `%1%' in valid-path entry for `%2%'") throw Error(format("unknown hash type %1% in valid-path entry for %2%")
% string(s, 0, colon) % path); % string(s, 0, colon) % path);
return parseHash(ht, string(s, colon + 1)); return parseHash(ht, string(s, colon + 1));
} }
@ -813,7 +813,7 @@ ValidPathInfo LocalStore::queryPathInfo(const Path & path)
stmtQueryPathInfo.bind(path); stmtQueryPathInfo.bind(path);
int r = sqlite3_step(stmtQueryPathInfo); int r = sqlite3_step(stmtQueryPathInfo);
if (r == SQLITE_DONE) throw Error(format("path `%1%' is not valid") % path); if (r == SQLITE_DONE) throw Error(format("path %1% is not valid") % path);
if (r != SQLITE_ROW) throwSQLiteError(db, "querying path in database"); if (r != SQLITE_ROW) throwSQLiteError(db, "querying path in database");
info.id = sqlite3_column_int(stmtQueryPathInfo, 0); info.id = sqlite3_column_int(stmtQueryPathInfo, 0);
@ -842,7 +842,7 @@ ValidPathInfo LocalStore::queryPathInfo(const Path & path)
} }
if (r != SQLITE_DONE) if (r != SQLITE_DONE)
throwSQLiteError(db, format("error getting references of `%1%'") % path); throwSQLiteError(db, format("error getting references of %1%") % path);
return info; return info;
} end_retry_sqlite; } end_retry_sqlite;
@ -861,7 +861,7 @@ void LocalStore::updatePathInfo(const ValidPathInfo & info)
stmtUpdatePathInfo.bind("sha256:" + printHash(info.hash)); stmtUpdatePathInfo.bind("sha256:" + printHash(info.hash));
stmtUpdatePathInfo.bind(info.path); stmtUpdatePathInfo.bind(info.path);
if (sqlite3_step(stmtUpdatePathInfo) != SQLITE_DONE) if (sqlite3_step(stmtUpdatePathInfo) != SQLITE_DONE)
throwSQLiteError(db, format("updating info of path `%1%' in database") % info.path); throwSQLiteError(db, format("updating info of path %1% in database") % info.path);
} }
@ -871,7 +871,7 @@ unsigned long long LocalStore::queryValidPathId(const Path & path)
stmtQueryPathInfo.bind(path); stmtQueryPathInfo.bind(path);
int res = sqlite3_step(stmtQueryPathInfo); int res = sqlite3_step(stmtQueryPathInfo);
if (res == SQLITE_ROW) return sqlite3_column_int(stmtQueryPathInfo, 0); if (res == SQLITE_ROW) return sqlite3_column_int(stmtQueryPathInfo, 0);
if (res == SQLITE_DONE) throw Error(format("path `%1%' is not valid") % path); if (res == SQLITE_DONE) throw Error(format("path %1% is not valid") % path);
throwSQLiteError(db, "querying path in database"); throwSQLiteError(db, "querying path in database");
} }
@ -950,7 +950,7 @@ void LocalStore::queryReferrers_(const Path & path, PathSet & referrers)
} }
if (r != SQLITE_DONE) if (r != SQLITE_DONE)
throwSQLiteError(db, format("error getting references of `%1%'") % path); throwSQLiteError(db, format("error getting references of %1%") % path);
} }
@ -986,7 +986,7 @@ PathSet LocalStore::queryValidDerivers(const Path & path)
} }
if (r != SQLITE_DONE) if (r != SQLITE_DONE)
throwSQLiteError(db, format("error getting valid derivers of `%1%'") % path); throwSQLiteError(db, format("error getting valid derivers of %1%") % path);
return derivers; return derivers;
} end_retry_sqlite; } end_retry_sqlite;
@ -1008,7 +1008,7 @@ PathSet LocalStore::queryDerivationOutputs(const Path & path)
} }
if (r != SQLITE_DONE) if (r != SQLITE_DONE)
throwSQLiteError(db, format("error getting outputs of `%1%'") % path); throwSQLiteError(db, format("error getting outputs of %1%") % path);
return outputs; return outputs;
} end_retry_sqlite; } end_retry_sqlite;
@ -1030,7 +1030,7 @@ StringSet LocalStore::queryDerivationOutputNames(const Path & path)
} }
if (r != SQLITE_DONE) if (r != SQLITE_DONE)
throwSQLiteError(db, format("error getting output names of `%1%'") % path); throwSQLiteError(db, format("error getting output names of %1%") % path);
return outputNames; return outputNames;
} end_retry_sqlite; } end_retry_sqlite;
@ -1073,7 +1073,7 @@ void LocalStore::startSubstituter(const Path & substituter, RunningSubstituter &
{ {
if (run.disabled || run.pid != -1) return; if (run.disabled || run.pid != -1) return;
debug(format("starting substituter program `%1%'") % substituter); debug(format("starting substituter program %1%") % substituter);
Pipe toPipe, fromPipe, errorPipe; Pipe toPipe, fromPipe, errorPipe;
@ -1091,7 +1091,7 @@ void LocalStore::startSubstituter(const Path & substituter, RunningSubstituter &
if (dup2(errorPipe.writeSide, STDERR_FILENO) == -1) if (dup2(errorPipe.writeSide, STDERR_FILENO) == -1)
throw SysError("dupping stderr"); throw SysError("dupping stderr");
execl(substituter.c_str(), substituter.c_str(), "--query", NULL); execl(substituter.c_str(), substituter.c_str(), "--query", NULL);
throw SysError(format("executing `%1%'") % substituter); throw SysError(format("executing %1%") % substituter);
}); });
run.program = baseNameOf(substituter); run.program = baseNameOf(substituter);
@ -1150,7 +1150,7 @@ string LocalStore::getLineFromSubstituter(RunningSubstituter & run)
if (errno == EINTR) continue; if (errno == EINTR) continue;
throw SysError("reading from substituter's stderr"); throw SysError("reading from substituter's stderr");
} }
if (n == 0) throw EndOfFile(format("substituter `%1%' died unexpectedly") % run.program); if (n == 0) throw EndOfFile(format("substituter %1% died unexpectedly") % run.program);
err.append(buf, n); err.append(buf, n);
string::size_type p; string::size_type p;
while ((p = err.find('\n')) != string::npos) { while ((p = err.find('\n')) != string::npos) {
@ -1227,7 +1227,7 @@ void LocalStore::querySubstitutablePathInfos(const Path & substituter,
Path path = getLineFromSubstituter(run); Path path = getLineFromSubstituter(run);
if (path == "") break; if (path == "") break;
if (paths.find(path) == paths.end()) if (paths.find(path) == paths.end())
throw Error(format("got unexpected path `%1%' from substituter") % path); throw Error(format("got unexpected path %1% from substituter") % path);
paths.erase(path); paths.erase(path);
SubstitutablePathInfo & info(infos[path]); SubstitutablePathInfo & info(infos[path]);
info.deriver = getLineFromSubstituter(run); info.deriver = getLineFromSubstituter(run);
@ -1321,7 +1321,7 @@ void LocalStore::registerValidPaths(const ValidPathInfos & infos)
there are no referrers. */ there are no referrers. */
void LocalStore::invalidatePath(const Path & path) void LocalStore::invalidatePath(const Path & path)
{ {
debug(format("invalidating path `%1%'") % path); debug(format("invalidating path %1%") % path);
drvHashes.erase(path); drvHashes.erase(path);
@ -1330,7 +1330,7 @@ void LocalStore::invalidatePath(const Path & path)
stmtInvalidatePath.bind(path); stmtInvalidatePath.bind(path);
if (sqlite3_step(stmtInvalidatePath) != SQLITE_DONE) if (sqlite3_step(stmtInvalidatePath) != SQLITE_DONE)
throwSQLiteError(db, format("invalidating path `%1%' in database") % path); throwSQLiteError(db, format("invalidating path %1% in database") % path);
/* Note that the foreign key constraints on the Refs table take /* Note that the foreign key constraints on the Refs table take
care of deleting the references entries for `path'. */ care of deleting the references entries for `path'. */
@ -1396,7 +1396,7 @@ Path LocalStore::addToStore(const Path & _srcPath,
bool recursive, HashType hashAlgo, PathFilter & filter, bool repair) bool recursive, HashType hashAlgo, PathFilter & filter, bool repair)
{ {
Path srcPath(absPath(_srcPath)); Path srcPath(absPath(_srcPath));
debug(format("adding `%1%' to the store") % srcPath); debug(format("adding %1% to the store") % srcPath);
/* Read the whole path into memory. This is not a very scalable /* Read the whole path into memory. This is not a very scalable
method for very large paths, but `copyPath' is mainly used for method for very large paths, but `copyPath' is mainly used for
@ -1475,9 +1475,9 @@ static void checkSecrecy(const Path & path)
{ {
struct stat st; struct stat st;
if (stat(path.c_str(), &st)) if (stat(path.c_str(), &st))
throw SysError(format("getting status of `%1%'") % path); throw SysError(format("getting status of %1%") % path);
if ((st.st_mode & (S_IRWXG | S_IRWXO)) != 0) if ((st.st_mode & (S_IRWXG | S_IRWXO)) != 0)
throw Error(format("file `%1%' should be secret (inaccessible to everybody else)!") % path); throw Error(format("file %1% should be secret (inaccessible to everybody else)!") % path);
} }
@ -1486,10 +1486,10 @@ void LocalStore::exportPath(const Path & path, bool sign,
{ {
assertStorePath(path); assertStorePath(path);
printMsg(lvlInfo, format("exporting path `%1%'") % path); printMsg(lvlInfo, format("exporting path %1%") % path);
if (!isValidPath(path)) if (!isValidPath(path))
throw Error(format("path `%1%' is not valid") % path); throw Error(format("path %1% is not valid") % path);
HashAndWriteSink hashAndWriteSink(sink); HashAndWriteSink hashAndWriteSink(sink);
@ -1501,7 +1501,7 @@ void LocalStore::exportPath(const Path & path, bool sign,
Hash hash = hashAndWriteSink.currentHash(); Hash hash = hashAndWriteSink.currentHash();
Hash storedHash = queryPathHash(path); Hash storedHash = queryPathHash(path);
if (hash != storedHash && storedHash != Hash(storedHash.type)) if (hash != storedHash && storedHash != Hash(storedHash.type))
throw Error(format("hash of path `%1%' has changed from `%2%' to `%3%'!") % path throw Error(format("hash of path %1% has changed from %2% to %3%!") % path
% printHash(storedHash) % printHash(hash)); % printHash(storedHash) % printHash(hash));
writeInt(EXPORT_MAGIC, hashAndWriteSink); writeInt(EXPORT_MAGIC, hashAndWriteSink);
@ -1608,7 +1608,7 @@ Path LocalStore::importPath(bool requireSignature, Source & source)
bool haveSignature = readInt(hashAndReadSource) == 1; bool haveSignature = readInt(hashAndReadSource) == 1;
if (requireSignature && !haveSignature) if (requireSignature && !haveSignature)
throw Error(format("imported archive of `%1%' lacks a signature") % dstPath); throw Error(format("imported archive of %1% lacks a signature") % dstPath);
if (haveSignature) { if (haveSignature) {
string signature = readString(hashAndReadSource); string signature = readString(hashAndReadSource);
@ -1659,7 +1659,7 @@ Path LocalStore::importPath(bool requireSignature, Source & source)
if (pathExists(dstPath)) deletePath(dstPath); if (pathExists(dstPath)) deletePath(dstPath);
if (rename(unpacked.c_str(), dstPath.c_str()) == -1) if (rename(unpacked.c_str(), dstPath.c_str()) == -1)
throw SysError(format("cannot move `%1%' to `%2%'") throw SysError(format("cannot move %1% to %2%")
% unpacked % dstPath); % unpacked % dstPath);
canonicalisePathMetaData(dstPath, -1); canonicalisePathMetaData(dstPath, -1);
@ -1692,7 +1692,7 @@ Paths LocalStore::importPaths(bool requireSignature, Source & source)
while (true) { while (true) {
unsigned long long n = readLongLong(source); unsigned long long n = readLongLong(source);
if (n == 0) break; if (n == 0) break;
if (n != 1) throw Error("input doesn't look like something created by `nix-store --export'"); if (n != 1) throw Error("input doesn't look like something created by nix-store --export");
res.push_back(importPath(requireSignature, source)); res.push_back(importPath(requireSignature, source));
} }
return res; return res;
@ -1710,7 +1710,7 @@ void LocalStore::invalidatePathChecked(const Path & path)
PathSet referrers; queryReferrers_(path, referrers); PathSet referrers; queryReferrers_(path, referrers);
referrers.erase(path); /* ignore self-references */ referrers.erase(path); /* ignore self-references */
if (!referrers.empty()) if (!referrers.empty())
throw PathInUse(format("cannot delete path `%1%' because it is in use by %2%") throw PathInUse(format("cannot delete path %1% because it is in use by %2%")
% path % showPaths(referrers)); % path % showPaths(referrers));
invalidatePath(path); invalidatePath(path);
} }
@ -1755,12 +1755,12 @@ bool LocalStore::verifyStore(bool checkContents, bool repair)
ValidPathInfo info = queryPathInfo(*i); ValidPathInfo info = queryPathInfo(*i);
/* Check the content hash (optionally - slow). */ /* Check the content hash (optionally - slow). */
printMsg(lvlTalkative, format("checking contents of `%1%'") % *i); printMsg(lvlTalkative, format("checking contents of %1%") % *i);
HashResult current = hashPath(info.hash.type, *i); HashResult current = hashPath(info.hash.type, *i);
if (info.hash != nullHash && info.hash != current.first) { if (info.hash != nullHash && info.hash != current.first) {
printMsg(lvlError, format("path `%1%' was modified! " printMsg(lvlError, format("path %1% was modified! "
"expected hash `%2%', got `%3%'") "expected hash %2%, got %3%")
% *i % printHash(info.hash) % printHash(current.first)); % *i % printHash(info.hash) % printHash(current.first));
if (repair) repairPath(*i); else errors = true; if (repair) repairPath(*i); else errors = true;
} else { } else {
@ -1769,14 +1769,14 @@ bool LocalStore::verifyStore(bool checkContents, bool repair)
/* Fill in missing hashes. */ /* Fill in missing hashes. */
if (info.hash == nullHash) { if (info.hash == nullHash) {
printMsg(lvlError, format("fixing missing hash on `%1%'") % *i); printMsg(lvlError, format("fixing missing hash on %1%") % *i);
info.hash = current.first; info.hash = current.first;
update = true; update = true;
} }
/* Fill in missing narSize fields (from old stores). */ /* Fill in missing narSize fields (from old stores). */
if (info.narSize == 0) { if (info.narSize == 0) {
printMsg(lvlError, format("updating size field on `%1%' to %2%") % *i % current.second); printMsg(lvlError, format("updating size field on %1% to %2%") % *i % current.second);
info.narSize = current.second; info.narSize = current.second;
update = true; update = true;
} }
@ -1810,7 +1810,7 @@ void LocalStore::verifyPath(const Path & path, const PathSet & store,
done.insert(path); done.insert(path);
if (!isStorePath(path)) { if (!isStorePath(path)) {
printMsg(lvlError, format("path `%1%' is not in the Nix store") % path); printMsg(lvlError, format("path %1% is not in the Nix store") % path);
invalidatePath(path); invalidatePath(path);
return; return;
} }
@ -1828,10 +1828,10 @@ void LocalStore::verifyPath(const Path & path, const PathSet & store,
} }
if (canInvalidate) { if (canInvalidate) {
printMsg(lvlError, format("path `%1%' disappeared, removing from database...") % path); printMsg(lvlError, format("path %1% disappeared, removing from database...") % path);
invalidatePath(path); invalidatePath(path);
} else { } else {
printMsg(lvlError, format("path `%1%' disappeared, but it still has valid referrers!") % path); printMsg(lvlError, format("path %1% disappeared, but it still has valid referrers!") % path);
if (repair) if (repair)
try { try {
repairPath(path); repairPath(path);
@ -1853,7 +1853,7 @@ bool LocalStore::pathContentsGood(const Path & path)
{ {
std::map<Path, bool>::iterator i = pathContentsGoodCache.find(path); std::map<Path, bool>::iterator i = pathContentsGoodCache.find(path);
if (i != pathContentsGoodCache.end()) return i->second; if (i != pathContentsGoodCache.end()) return i->second;
printMsg(lvlInfo, format("checking path `%1%'...") % path); printMsg(lvlInfo, format("checking path %1%...") % path);
ValidPathInfo info = queryPathInfo(path); ValidPathInfo info = queryPathInfo(path);
bool res; bool res;
if (!pathExists(path)) if (!pathExists(path))
@ -1864,7 +1864,7 @@ bool LocalStore::pathContentsGood(const Path & path)
res = info.hash == nullHash || info.hash == current.first; res = info.hash == nullHash || info.hash == current.first;
} }
pathContentsGoodCache[path] = res; pathContentsGoodCache[path] = res;
if (!res) printMsg(lvlError, format("path `%1%' is corrupted or missing!") % path); if (!res) printMsg(lvlError, format("path %1% is corrupted or missing!") % path);
return res; return res;
} }
@ -1895,7 +1895,7 @@ ValidPathInfo LocalStore::queryPathInfoOld(const Path & path)
string baseName = baseNameOf(path); string baseName = baseNameOf(path);
Path infoFile = (format("%1%/info/%2%") % settings.nixDBPath % baseName).str(); Path infoFile = (format("%1%/info/%2%") % settings.nixDBPath % baseName).str();
if (!pathExists(infoFile)) if (!pathExists(infoFile))
throw Error(format("path `%1%' is not valid") % path); throw Error(format("path %1% is not valid") % path);
string info = readFile(infoFile); string info = readFile(infoFile);
/* Parse it. */ /* Parse it. */
@ -1904,7 +1904,7 @@ ValidPathInfo LocalStore::queryPathInfoOld(const Path & path)
foreach (Strings::iterator, i, lines) { foreach (Strings::iterator, i, lines) {
string::size_type p = i->find(':'); string::size_type p = i->find(':');
if (p == string::npos) if (p == string::npos)
throw Error(format("corrupt line in `%1%': %2%") % infoFile % *i); throw Error(format("corrupt line in %1%: %2%") % infoFile % *i);
string name(*i, 0, p); string name(*i, 0, p);
string value(*i, p + 2); string value(*i, p + 2);
if (name == "References") { if (name == "References") {
@ -1978,7 +1978,7 @@ static void makeMutable(const Path & path)
AutoCloseFD fd = open(path.c_str(), O_RDONLY | O_NOFOLLOW); AutoCloseFD fd = open(path.c_str(), O_RDONLY | O_NOFOLLOW);
if (fd == -1) { if (fd == -1) {
if (errno == ELOOP) return; // it's a symlink if (errno == ELOOP) return; // it's a symlink
throw SysError(format("opening file `%1%'") % path); throw SysError(format("opening file %1%") % path);
} }
unsigned int flags = 0, old; unsigned int flags = 0, old;

View file

@ -63,7 +63,7 @@ Path findOutput(const Derivation & drv, string id)
{ {
foreach (DerivationOutputs::const_iterator, i, drv.outputs) foreach (DerivationOutputs::const_iterator, i, drv.outputs)
if (i->first == id) return i->second.path; if (i->first == id) return i->second.path;
throw Error(format("derivation has no output `%1%'") % id); throw Error(format("derivation has no output %1%") % id);
} }
@ -186,7 +186,7 @@ static void dfsVisit(StoreAPI & store, const PathSet & paths,
PathSet & parents) PathSet & parents)
{ {
if (parents.find(path) != parents.end()) if (parents.find(path) != parents.end())
throw BuildError(format("cycle detected in the references of `%1%'") % path); throw BuildError(format("cycle detected in the references of %1%") % path);
if (visited.find(path) != visited.end()) return; if (visited.find(path) != visited.end()) return;
visited.insert(path); visited.insert(path);

View file

@ -18,9 +18,9 @@ static void makeWritable(const Path & path)
{ {
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) if (lstat(path.c_str(), &st))
throw SysError(format("getting attributes of path `%1%'") % path); throw SysError(format("getting attributes of path %1%") % path);
if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1) if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1)
throw SysError(format("changing writability of `%1%'") % path); throw SysError(format("changing writability of %1%") % path);
} }
@ -46,7 +46,7 @@ LocalStore::InodeHash LocalStore::loadInodeHash()
InodeHash inodeHash; InodeHash inodeHash;
AutoCloseDir dir = opendir(linksDir.c_str()); AutoCloseDir dir = opendir(linksDir.c_str());
if (!dir) throw SysError(format("opening directory `%1%'") % linksDir); if (!dir) throw SysError(format("opening directory %1%") % linksDir);
struct dirent * dirent; struct dirent * dirent;
while (errno = 0, dirent = readdir(dir)) { /* sic */ while (errno = 0, dirent = readdir(dir)) { /* sic */
@ -54,7 +54,7 @@ LocalStore::InodeHash LocalStore::loadInodeHash()
// We don't care if we hit non-hash files, anything goes // We don't care if we hit non-hash files, anything goes
inodeHash.insert(dirent->d_ino); inodeHash.insert(dirent->d_ino);
} }
if (errno) throw SysError(format("reading directory `%1%'") % linksDir); if (errno) throw SysError(format("reading directory %1%") % linksDir);
printMsg(lvlTalkative, format("loaded %1% hash inodes") % inodeHash.size()); printMsg(lvlTalkative, format("loaded %1% hash inodes") % inodeHash.size());
@ -67,14 +67,14 @@ Strings LocalStore::readDirectoryIgnoringInodes(const Path & path, const InodeHa
Strings names; Strings names;
AutoCloseDir dir = opendir(path.c_str()); AutoCloseDir dir = opendir(path.c_str());
if (!dir) throw SysError(format("opening directory `%1%'") % path); if (!dir) throw SysError(format("opening directory %1%") % path);
struct dirent * dirent; struct dirent * dirent;
while (errno = 0, dirent = readdir(dir)) { /* sic */ while (errno = 0, dirent = readdir(dir)) { /* sic */
checkInterrupt(); checkInterrupt();
if (inodeHash.count(dirent->d_ino)) { if (inodeHash.count(dirent->d_ino)) {
printMsg(lvlDebug, format("`%1%' is already linked") % dirent->d_name); printMsg(lvlDebug, format("%1% is already linked") % dirent->d_name);
continue; continue;
} }
@ -82,7 +82,7 @@ Strings LocalStore::readDirectoryIgnoringInodes(const Path & path, const InodeHa
if (name == "." || name == "..") continue; if (name == "." || name == "..") continue;
names.push_back(name); names.push_back(name);
} }
if (errno) throw SysError(format("reading directory `%1%'") % path); if (errno) throw SysError(format("reading directory %1%") % path);
return names; return names;
} }
@ -94,7 +94,7 @@ void LocalStore::optimisePath_(OptimiseStats & stats, const Path & path, InodeHa
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) if (lstat(path.c_str(), &st))
throw SysError(format("getting attributes of path `%1%'") % path); throw SysError(format("getting attributes of path %1%") % path);
if (S_ISDIR(st.st_mode)) { if (S_ISDIR(st.st_mode)) {
Strings names = readDirectoryIgnoringInodes(path, inodeHash); Strings names = readDirectoryIgnoringInodes(path, inodeHash);
@ -115,13 +115,13 @@ void LocalStore::optimisePath_(OptimiseStats & stats, const Path & path, InodeHa
NixOS (example: $fontconfig/var/cache being modified). Skip NixOS (example: $fontconfig/var/cache being modified). Skip
those files. FIXME: check the modification time. */ those files. FIXME: check the modification time. */
if (S_ISREG(st.st_mode) && (st.st_mode & S_IWUSR)) { if (S_ISREG(st.st_mode) && (st.st_mode & S_IWUSR)) {
printMsg(lvlError, format("skipping suspicious writable file `%1%'") % path); printMsg(lvlError, format("skipping suspicious writable file %1%") % path);
return; return;
} }
/* This can still happen on top-level files */ /* This can still happen on top-level files */
if (st.st_nlink > 1 && inodeHash.count(st.st_ino)) { if (st.st_nlink > 1 && inodeHash.count(st.st_ino)) {
printMsg(lvlDebug, format("`%1%' is already linked, with %2% other file(s).") % path % (st.st_nlink - 2)); printMsg(lvlDebug, format("%1% is already linked, with %2% other file(s).") % path % (st.st_nlink - 2));
return; return;
} }
@ -135,7 +135,7 @@ void LocalStore::optimisePath_(OptimiseStats & stats, const Path & path, InodeHa
contents of the symlink (i.e. the result of readlink()), not contents of the symlink (i.e. the result of readlink()), not
the contents of the target (which may not even exist). */ the contents of the target (which may not even exist). */
Hash hash = hashPath(htSHA256, path).first; Hash hash = hashPath(htSHA256, path).first;
printMsg(lvlDebug, format("`%1%' has hash `%2%'") % path % printHash(hash)); printMsg(lvlDebug, format("%1% has hash %2%") % path % printHash(hash));
/* Check if this is a known hash. */ /* Check if this is a known hash. */
Path linkPath = linksDir + "/" + printHash32(hash); Path linkPath = linksDir + "/" + printHash32(hash);
@ -147,7 +147,7 @@ void LocalStore::optimisePath_(OptimiseStats & stats, const Path & path, InodeHa
return; return;
} }
if (errno != EEXIST) if (errno != EEXIST)
throw SysError(format("cannot link `%1%' to `%2%'") % linkPath % path); throw SysError(format("cannot link %1% to %2%") % linkPath % path);
/* Fall through if another process created linkPath before /* Fall through if another process created linkPath before
we did. */ we did. */
} }
@ -156,14 +156,14 @@ void LocalStore::optimisePath_(OptimiseStats & stats, const Path & path, InodeHa
current file with a hard link to that file. */ current file with a hard link to that file. */
struct stat stLink; struct stat stLink;
if (lstat(linkPath.c_str(), &stLink)) if (lstat(linkPath.c_str(), &stLink))
throw SysError(format("getting attributes of path `%1%'") % linkPath); throw SysError(format("getting attributes of path %1%") % linkPath);
if (st.st_ino == stLink.st_ino) { if (st.st_ino == stLink.st_ino) {
printMsg(lvlDebug, format("`%1%' is already linked to `%2%'") % path % linkPath); printMsg(lvlDebug, format("%1% is already linked to %2%") % path % linkPath);
return; return;
} }
printMsg(lvlTalkative, format("linking `%1%' to `%2%'") % path % linkPath); printMsg(lvlTalkative, format("linking %1% to %2%") % path % linkPath);
/* Make the containing directory writable, but only if it's not /* Make the containing directory writable, but only if it's not
the store itself (we don't want or need to mess with its the store itself (we don't want or need to mess with its
@ -184,26 +184,26 @@ void LocalStore::optimisePath_(OptimiseStats & stats, const Path & path, InodeHa
systems). This is likely to happen with empty files. systems). This is likely to happen with empty files.
Just shrug and ignore. */ Just shrug and ignore. */
if (st.st_size) if (st.st_size)
printMsg(lvlInfo, format("`%1%' has maximum number of links") % linkPath); printMsg(lvlInfo, format("%1% has maximum number of links") % linkPath);
return; return;
} }
throw SysError(format("cannot link `%1%' to `%2%'") % tempLink % linkPath); throw SysError(format("cannot link %1% to %2%") % tempLink % linkPath);
} }
/* Atomically replace the old file with the new hard link. */ /* Atomically replace the old file with the new hard link. */
if (rename(tempLink.c_str(), path.c_str()) == -1) { if (rename(tempLink.c_str(), path.c_str()) == -1) {
if (unlink(tempLink.c_str()) == -1) if (unlink(tempLink.c_str()) == -1)
printMsg(lvlError, format("unable to unlink `%1%'") % tempLink); printMsg(lvlError, format("unable to unlink %1%") % tempLink);
if (errno == EMLINK) { if (errno == EMLINK) {
/* Some filesystems generate too many links on the rename, /* Some filesystems generate too many links on the rename,
rather than on the original link. (Probably it rather than on the original link. (Probably it
temporarily increases the st_nlink field before temporarily increases the st_nlink field before
decreasing it again.) */ decreasing it again.) */
if (st.st_size) if (st.st_size)
printMsg(lvlInfo, format("`%1%' has maximum number of links") % linkPath); printMsg(lvlInfo, format("%1% has maximum number of links") % linkPath);
return; return;
} }
throw SysError(format("cannot rename `%1%' to `%2%'") % tempLink % path); throw SysError(format("cannot rename %1% to %2%") % tempLink % path);
} }
stats.filesLinked++; stats.filesLinked++;
@ -220,7 +220,7 @@ void LocalStore::optimiseStore(OptimiseStats & stats)
foreach (PathSet::iterator, i, paths) { foreach (PathSet::iterator, i, paths) {
addTempRoot(*i); addTempRoot(*i);
if (!isValidPath(*i)) continue; /* path was GC'ed, probably */ if (!isValidPath(*i)) continue; /* path was GC'ed, probably */
startNest(nest, lvlChatty, format("hashing files in `%1%'") % *i); startNest(nest, lvlChatty, format("hashing files in %1%") % *i);
optimisePath_(stats, *i, inodeHash); optimisePath_(stats, *i, inodeHash);
} }
} }

View file

@ -18,7 +18,7 @@ int openLockFile(const Path & path, bool create)
fd = open(path.c_str(), O_RDWR | (create ? O_CREAT : 0), 0600); fd = open(path.c_str(), O_RDWR | (create ? O_CREAT : 0), 0600);
if (fd == -1 && (create || errno != ENOENT)) if (fd == -1 && (create || errno != ENOENT))
throw SysError(format("opening lock file `%1%'") % path); throw SysError(format("opening lock file %1%") % path);
closeOnExec(fd); closeOnExec(fd);
@ -109,7 +109,7 @@ bool PathLocks::lockPaths(const PathSet & _paths,
Path path = *i; Path path = *i;
Path lockPath = path + ".lock"; Path lockPath = path + ".lock";
debug(format("locking path `%1%'") % path); debug(format("locking path %1%") % path);
if (lockedPaths.find(lockPath) != lockedPaths.end()) if (lockedPaths.find(lockPath) != lockedPaths.end())
throw Error("deadlock: trying to re-acquire self-held lock"); throw Error("deadlock: trying to re-acquire self-held lock");
@ -134,19 +134,19 @@ bool PathLocks::lockPaths(const PathSet & _paths,
} }
} }
debug(format("lock acquired on `%1%'") % lockPath); debug(format("lock acquired on %1%") % lockPath);
/* Check that the lock file hasn't become stale (i.e., /* Check that the lock file hasn't become stale (i.e.,
hasn't been unlinked). */ hasn't been unlinked). */
struct stat st; struct stat st;
if (fstat(fd, &st) == -1) if (fstat(fd, &st) == -1)
throw SysError(format("statting lock file `%1%'") % lockPath); throw SysError(format("statting lock file %1%") % lockPath);
if (st.st_size != 0) if (st.st_size != 0)
/* This lock file has been unlinked, so we're holding /* This lock file has been unlinked, so we're holding
a lock on a deleted file. This means that other a lock on a deleted file. This means that other
processes may create and acquire a lock on processes may create and acquire a lock on
`lockPath', and proceed. So we must retry. */ `lockPath', and proceed. So we must retry. */
debug(format("open lock file `%1%' has become stale") % lockPath); debug(format("open lock file %1% has become stale") % lockPath);
else else
break; break;
} }
@ -174,9 +174,9 @@ void PathLocks::unlock()
lockedPaths.erase(i->second); lockedPaths.erase(i->second);
if (close(i->first) == -1) if (close(i->first) == -1)
printMsg(lvlError, printMsg(lvlError,
format("error (ignored): cannot close lock file on `%1%'") % i->second); format("error (ignored): cannot close lock file on %1%") % i->second);
debug(format("lock released on `%1%'") % i->second); debug(format("lock released on %1%") % i->second);
} }
fds.clear(); fds.clear();

View file

@ -37,7 +37,7 @@ static void search(const unsigned char * s, unsigned int len,
if (!match) continue; if (!match) continue;
string ref((const char *) s + i, refLength); string ref((const char *) s + i, refLength);
if (hashes.find(ref) != hashes.end()) { if (hashes.find(ref) != hashes.end()) {
debug(format("found reference to `%1%' at offset `%2%'") debug(format("found reference to %1% at offset %2%")
% ref % i); % ref % i);
seen.insert(ref); seen.insert(ref);
hashes.erase(ref); hashes.erase(ref);
@ -93,7 +93,7 @@ PathSet scanForReferences(const string & path,
string baseName = baseNameOf(*i); string baseName = baseNameOf(*i);
string::size_type pos = baseName.find('-'); string::size_type pos = baseName.find('-');
if (pos == string::npos) if (pos == string::npos)
throw Error(format("bad reference `%1%'") % *i); throw Error(format("bad reference %1%") % *i);
string s = string(baseName, 0, pos); string s = string(baseName, 0, pos);
assert(s.size() == refLength); assert(s.size() == refLength);
assert(backMap.find(s) == backMap.end()); assert(backMap.find(s) == backMap.end());

View file

@ -55,7 +55,7 @@ void RemoteStore::openConnection(bool reserveSpace)
us. */ us. */
connectToDaemon(); connectToDaemon();
else else
throw Error(format("invalid setting for NIX_REMOTE, `%1%'") % remoteMode); throw Error(format("invalid setting for NIX_REMOTE, %1%") % remoteMode);
from.fd = fdSocket; from.fd = fdSocket;
to.fd = fdSocket; to.fd = fdSocket;
@ -116,12 +116,12 @@ void RemoteStore::connectToDaemon()
struct sockaddr_un addr; struct sockaddr_un addr;
addr.sun_family = AF_UNIX; addr.sun_family = AF_UNIX;
if (socketPathRel.size() >= sizeof(addr.sun_path)) if (socketPathRel.size() >= sizeof(addr.sun_path))
throw Error(format("socket path `%1%' is too long") % socketPathRel); throw Error(format("socket path %1% is too long") % socketPathRel);
using namespace std; using namespace std;
strcpy(addr.sun_path, socketPathRel.c_str()); strcpy(addr.sun_path, socketPathRel.c_str());
if (connect(fdSocket, (struct sockaddr *) &addr, sizeof(addr)) == -1) if (connect(fdSocket, (struct sockaddr *) &addr, sizeof(addr)) == -1)
throw SysError(format("cannot connect to daemon at `%1%'") % socketPath); throw SysError(format("cannot connect to daemon at %1%") % socketPath);
if (fchdir(fdPrevDir) == -1) if (fchdir(fdPrevDir) == -1)
throw SysError("couldn't change back to previous directory"); throw SysError("couldn't change back to previous directory");

View file

@ -32,14 +32,14 @@ bool isStorePath(const Path & path)
void assertStorePath(const Path & path) void assertStorePath(const Path & path)
{ {
if (!isStorePath(path)) if (!isStorePath(path))
throw Error(format("path `%1%' is not in the Nix store") % path); throw Error(format("path %1% is not in the Nix store") % path);
} }
Path toStorePath(const Path & path) Path toStorePath(const Path & path)
{ {
if (!isInStore(path)) if (!isInStore(path))
throw Error(format("path `%1%' is not in the Nix store") % path); throw Error(format("path %1% is not in the Nix store") % path);
Path::size_type slash = path.find('/', settings.nixStore.size() + 1); Path::size_type slash = path.find('/', settings.nixStore.size() + 1);
if (slash == Path::npos) if (slash == Path::npos)
return path; return path;
@ -57,7 +57,7 @@ Path followLinksToStore(const Path & _path)
path = absPath(target, dirOf(path)); path = absPath(target, dirOf(path));
} }
if (!isInStore(path)) if (!isInStore(path))
throw Error(format("path `%1%' is not in the Nix store") % path); throw Error(format("path %1% is not in the Nix store") % path);
return path; return path;
} }
@ -81,14 +81,14 @@ void checkStoreName(const string & name)
/* Disallow names starting with a dot for possible security /* Disallow names starting with a dot for possible security
reasons (e.g., "." and ".."). */ reasons (e.g., "." and ".."). */
if (string(name, 0, 1) == ".") if (string(name, 0, 1) == ".")
throw Error(format("illegal name: `%1%'") % name); throw Error(format("illegal name: %1%") % name);
foreach (string::const_iterator, i, name) foreach (string::const_iterator, i, name)
if (!((*i >= 'A' && *i <= 'Z') || if (!((*i >= 'A' && *i <= 'Z') ||
(*i >= 'a' && *i <= 'z') || (*i >= 'a' && *i <= 'z') ||
(*i >= '0' && *i <= '9') || (*i >= '0' && *i <= '9') ||
validChars.find(*i) != string::npos)) validChars.find(*i) != string::npos))
{ {
throw Error(format("invalid character `%1%' in name `%2%'") throw Error(format("invalid character %1% in name %2%")
% *i % name); % *i % name);
} }
} }
@ -288,7 +288,7 @@ string showPaths(const PathSet & paths)
string s; string s;
foreach (PathSet::const_iterator, i, paths) { foreach (PathSet::const_iterator, i, paths) {
if (s.size() != 0) s += ", "; if (s.size() != 0) s += ", ";
s += "`" + *i + "'"; s += "" + *i + "";
} }
return s; return s;
} }

View file

@ -43,7 +43,7 @@ static void dumpContents(const Path & path, size_t size,
writeLongLong(size, sink); writeLongLong(size, sink);
AutoCloseFD fd = open(path.c_str(), O_RDONLY); AutoCloseFD fd = open(path.c_str(), O_RDONLY);
if (fd == -1) throw SysError(format("opening file `%1%'") % path); if (fd == -1) throw SysError(format("opening file %1%") % path);
unsigned char buf[65536]; unsigned char buf[65536];
size_t left = size; size_t left = size;
@ -63,7 +63,7 @@ static void dump(const Path & path, Sink & sink, PathFilter & filter)
{ {
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) if (lstat(path.c_str(), &st))
throw SysError(format("getting attributes of path `%1%'") % path); throw SysError(format("getting attributes of path %1%") % path);
writeString("(", sink); writeString("(", sink);
@ -89,11 +89,11 @@ static void dump(const Path & path, Sink & sink, PathFilter & filter)
string name(i.name); string name(i.name);
size_t pos = i.name.find(caseHackSuffix); size_t pos = i.name.find(caseHackSuffix);
if (pos != string::npos) { if (pos != string::npos) {
printMsg(lvlDebug, format("removing case hack suffix from `%1%'") % (path + "/" + i.name)); printMsg(lvlDebug, format("removing case hack suffix from %1%") % (path + "/" + i.name));
name.erase(pos); name.erase(pos);
} }
if (unhacked.find(name) != unhacked.end()) if (unhacked.find(name) != unhacked.end())
throw Error(format("file name collision in between `%1%' and `%2%'") throw Error(format("file name collision in between %1% and %2%")
% (path + "/" + unhacked[name]) % (path + "/" + i.name)); % (path + "/" + unhacked[name]) % (path + "/" + i.name));
unhacked[name] = i.name; unhacked[name] = i.name;
} else } else
@ -118,7 +118,7 @@ static void dump(const Path & path, Sink & sink, PathFilter & filter)
writeString(readLink(path), sink); writeString(readLink(path), sink);
} }
else throw Error(format("file `%1%' has an unsupported type") % path); else throw Error(format("file %1% has an unsupported type") % path);
writeString(")", sink); writeString(")", sink);
} }
@ -247,14 +247,14 @@ static void parse(ParseSink & sink, Source & source, const Path & path)
} else if (s == "name") { } else if (s == "name") {
name = readString(source); name = readString(source);
if (name.empty() || name == "." || name == ".." || name.find('/') != string::npos || name.find((char) 0) != string::npos) if (name.empty() || name == "." || name == ".." || name.find('/') != string::npos || name.find((char) 0) != string::npos)
throw Error(format("NAR contains invalid file name `%1%'") % name); throw Error(format("NAR contains invalid file name %1%") % name);
if (name <= prevName) if (name <= prevName)
throw Error("NAR directory is not sorted"); throw Error("NAR directory is not sorted");
prevName = name; prevName = name;
if (useCaseHack) { if (useCaseHack) {
auto i = names.find(name); auto i = names.find(name);
if (i != names.end()) { if (i != names.end()) {
printMsg(lvlDebug, format("case collision between `%1%' and `%2%'") % i->first % name); printMsg(lvlDebug, format("case collision between %1% and %2%") % i->first % name);
name += caseHackSuffix; name += caseHackSuffix;
name += int2String(++i->second); name += int2String(++i->second);
} else } else
@ -303,7 +303,7 @@ struct RestoreSink : ParseSink
{ {
Path p = dstPath + path; Path p = dstPath + path;
if (mkdir(p.c_str(), 0777) == -1) if (mkdir(p.c_str(), 0777) == -1)
throw SysError(format("creating directory `%1%'") % p); throw SysError(format("creating directory %1%") % p);
}; };
void createRegularFile(const Path & path) void createRegularFile(const Path & path)
@ -311,7 +311,7 @@ struct RestoreSink : ParseSink
Path p = dstPath + path; Path p = dstPath + path;
fd.close(); fd.close();
fd = open(p.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0666); fd = open(p.c_str(), O_CREAT | O_EXCL | O_WRONLY, 0666);
if (fd == -1) throw SysError(format("creating file `%1%'") % p); if (fd == -1) throw SysError(format("creating file %1%") % p);
} }
void isExecutable() void isExecutable()

View file

@ -89,11 +89,11 @@ Hash parseHash(HashType ht, const string & s)
{ {
Hash hash(ht); Hash hash(ht);
if (s.length() != hash.hashSize * 2) if (s.length() != hash.hashSize * 2)
throw Error(format("invalid hash `%1%'") % s); throw Error(format("invalid hash %1%") % s);
for (unsigned int i = 0; i < hash.hashSize; i++) { for (unsigned int i = 0; i < hash.hashSize; i++) {
string s2(s, i * 2, 2); string s2(s, i * 2, 2);
if (!isxdigit(s2[0]) || !isxdigit(s2[1])) if (!isxdigit(s2[0]) || !isxdigit(s2[1]))
throw Error(format("invalid hash `%1%'") % s); throw Error(format("invalid hash %1%") % s);
std::istringstream str(s2); std::istringstream str(s2);
int n; int n;
str >> std::hex >> n; str >> std::hex >> n;
@ -200,10 +200,10 @@ Hash parseHash32(HashType ht, const string & s)
for (digit = 0; digit < base32Chars.size(); ++digit) /* !!! slow */ for (digit = 0; digit < base32Chars.size(); ++digit) /* !!! slow */
if (chars[digit] == c) break; if (chars[digit] == c) break;
if (digit >= 32) if (digit >= 32)
throw Error(format("invalid base-32 hash `%1%'") % s); throw Error(format("invalid base-32 hash %1%") % s);
if (mul(hash.hash, 32, hash.hashSize) || if (mul(hash.hash, 32, hash.hashSize) ||
add(hash.hash, digit, hash.hashSize)) add(hash.hash, digit, hash.hashSize))
throw Error(format("base-32 hash `%1%' is too large") % s); throw Error(format("base-32 hash %1% is too large") % s);
} }
return hash; return hash;
@ -220,7 +220,7 @@ Hash parseHash16or32(HashType ht, const string & s)
/* base-32 representation */ /* base-32 representation */
hash = parseHash32(ht, s); hash = parseHash32(ht, s);
else else
throw Error(format("hash `%1%' has wrong length for hash type `%2%'") throw Error(format("hash %1% has wrong length for hash type %2%")
% s % printHashType(ht)); % s % printHashType(ht));
return hash; return hash;
} }
@ -290,13 +290,13 @@ Hash hashFile(HashType ht, const Path & path)
start(ht, ctx); start(ht, ctx);
AutoCloseFD fd = open(path.c_str(), O_RDONLY); AutoCloseFD fd = open(path.c_str(), O_RDONLY);
if (fd == -1) throw SysError(format("opening file `%1%'") % path); if (fd == -1) throw SysError(format("opening file %1%") % path);
unsigned char buf[8192]; unsigned char buf[8192];
ssize_t n; ssize_t n;
while ((n = read(fd, buf, sizeof(buf)))) { while ((n = read(fd, buf, sizeof(buf)))) {
checkInterrupt(); checkInterrupt();
if (n == -1) throw SysError(format("reading file `%1%'") % path); if (n == -1) throw SysError(format("reading file %1%") % path);
update(ht, ctx, buf, n); update(ht, ctx, buf, n);
} }

View file

@ -84,7 +84,7 @@ Path canonPath(const Path & path, bool resolveSymlinks)
string s; string s;
if (path[0] != '/') if (path[0] != '/')
throw Error(format("not an absolute path: `%1%'") % path); throw Error(format("not an absolute path: %1%") % path);
string::const_iterator i = path.begin(), end = path.end(); string::const_iterator i = path.begin(), end = path.end();
string temp; string temp;
@ -120,7 +120,7 @@ Path canonPath(const Path & path, bool resolveSymlinks)
the symlink target might contain new symlinks). */ the symlink target might contain new symlinks). */
if (resolveSymlinks && isLink(s)) { if (resolveSymlinks && isLink(s)) {
if (++followCount >= maxFollow) if (++followCount >= maxFollow)
throw Error(format("infinite symlink recursion in path `%1%'") % path); throw Error(format("infinite symlink recursion in path %1%") % path);
temp = absPath(readLink(s), dirOf(s)) temp = absPath(readLink(s), dirOf(s))
+ string(i, end); + string(i, end);
i = temp.begin(); /* restart */ i = temp.begin(); /* restart */
@ -139,7 +139,7 @@ Path dirOf(const Path & path)
{ {
Path::size_type pos = path.rfind('/'); Path::size_type pos = path.rfind('/');
if (pos == string::npos) if (pos == string::npos)
throw Error(format("invalid file name `%1%'") % path); throw Error(format("invalid file name %1%") % path);
return pos == 0 ? "/" : Path(path, 0, pos); return pos == 0 ? "/" : Path(path, 0, pos);
} }
@ -148,7 +148,7 @@ string baseNameOf(const Path & path)
{ {
Path::size_type pos = path.rfind('/'); Path::size_type pos = path.rfind('/');
if (pos == string::npos) if (pos == string::npos)
throw Error(format("invalid file name `%1%'") % path); throw Error(format("invalid file name %1%") % path);
return string(path, pos + 1); return string(path, pos + 1);
} }
@ -166,7 +166,7 @@ struct stat lstat(const Path & path)
{ {
struct stat st; struct stat st;
if (lstat(path.c_str(), &st)) if (lstat(path.c_str(), &st))
throw SysError(format("getting status of `%1%'") % path); throw SysError(format("getting status of %1%") % path);
return st; return st;
} }
@ -188,10 +188,10 @@ Path readLink(const Path & path)
checkInterrupt(); checkInterrupt();
struct stat st = lstat(path); struct stat st = lstat(path);
if (!S_ISLNK(st.st_mode)) if (!S_ISLNK(st.st_mode))
throw Error(format("`%1%' is not a symlink") % path); throw Error(format("%1% is not a symlink") % path);
char buf[st.st_size]; char buf[st.st_size];
if (readlink(path.c_str(), buf, st.st_size) != st.st_size) if (readlink(path.c_str(), buf, st.st_size) != st.st_size)
throw SysError(format("reading symbolic link `%1%'") % path); throw SysError(format("reading symbolic link %1%") % path);
return string(buf, st.st_size); return string(buf, st.st_size);
} }
@ -209,7 +209,7 @@ DirEntries readDirectory(const Path & path)
entries.reserve(64); entries.reserve(64);
AutoCloseDir dir = opendir(path.c_str()); AutoCloseDir dir = opendir(path.c_str());
if (!dir) throw SysError(format("opening directory `%1%'") % path); if (!dir) throw SysError(format("opening directory %1%") % path);
struct dirent * dirent; struct dirent * dirent;
while (errno = 0, dirent = readdir(dir)) { /* sic */ while (errno = 0, dirent = readdir(dir)) { /* sic */
@ -218,7 +218,7 @@ DirEntries readDirectory(const Path & path)
if (name == "." || name == "..") continue; if (name == "." || name == "..") continue;
entries.emplace_back(name, dirent->d_ino, dirent->d_type); entries.emplace_back(name, dirent->d_ino, dirent->d_type);
} }
if (errno) throw SysError(format("reading directory `%1%'") % path); if (errno) throw SysError(format("reading directory %1%") % path);
return entries; return entries;
} }
@ -242,7 +242,7 @@ string readFile(const Path & path, bool drain)
{ {
AutoCloseFD fd = open(path.c_str(), O_RDONLY); AutoCloseFD fd = open(path.c_str(), O_RDONLY);
if (fd == -1) if (fd == -1)
throw SysError(format("opening file `%1%'") % path); throw SysError(format("opening file %1%") % path);
return drain ? drainFD(fd) : readFile(fd); return drain ? drainFD(fd) : readFile(fd);
} }
@ -251,7 +251,7 @@ void writeFile(const Path & path, const string & s)
{ {
AutoCloseFD fd = open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0666); AutoCloseFD fd = open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT, 0666);
if (fd == -1) if (fd == -1)
throw SysError(format("opening file `%1%'") % path); throw SysError(format("opening file %1%") % path);
writeFull(fd, (unsigned char *) s.data(), s.size()); writeFull(fd, (unsigned char *) s.data(), s.size());
} }
@ -298,7 +298,7 @@ static void _deletePath(const Path & path, unsigned long long & bytesFreed)
/* Make the directory writable. */ /* Make the directory writable. */
if (!(st.st_mode & S_IWUSR)) { if (!(st.st_mode & S_IWUSR)) {
if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1) if (chmod(path.c_str(), st.st_mode | S_IWUSR) == -1)
throw SysError(format("making `%1%' writable") % path); throw SysError(format("making %1% writable") % path);
} }
for (auto & i : readDirectory(path)) for (auto & i : readDirectory(path))
@ -306,7 +306,7 @@ static void _deletePath(const Path & path, unsigned long long & bytesFreed)
} }
if (remove(path.c_str()) == -1) if (remove(path.c_str()) == -1)
throw SysError(format("cannot unlink `%1%'") % path); throw SysError(format("cannot unlink %1%") % path);
} }
@ -320,7 +320,7 @@ void deletePath(const Path & path)
void deletePath(const Path & path, unsigned long long & bytesFreed) void deletePath(const Path & path, unsigned long long & bytesFreed)
{ {
startNest(nest, lvlDebug, startNest(nest, lvlDebug,
format("recursively deleting path `%1%'") % path); format("recursively deleting path %1%") % path);
bytesFreed = 0; bytesFreed = 0;
_deletePath(path, bytesFreed); _deletePath(path, bytesFreed);
} }
@ -357,11 +357,11 @@ Path createTempDir(const Path & tmpRoot, const Path & prefix,
"wheel", then "tar" will fail to unpack archives that "wheel", then "tar" will fail to unpack archives that
have the setgid bit set on directories. */ have the setgid bit set on directories. */
if (chown(tmpDir.c_str(), (uid_t) -1, getegid()) != 0) if (chown(tmpDir.c_str(), (uid_t) -1, getegid()) != 0)
throw SysError(format("setting group of directory `%1%'") % tmpDir); throw SysError(format("setting group of directory %1%") % tmpDir);
return tmpDir; return tmpDir;
} }
if (errno != EEXIST) if (errno != EEXIST)
throw SysError(format("creating directory `%1%'") % tmpDir); throw SysError(format("creating directory %1%") % tmpDir);
} }
} }
@ -375,12 +375,12 @@ Paths createDirs(const Path & path)
if (lstat(path.c_str(), &st) == -1) { if (lstat(path.c_str(), &st) == -1) {
created = createDirs(dirOf(path)); created = createDirs(dirOf(path));
if (mkdir(path.c_str(), 0777) == -1 && errno != EEXIST) if (mkdir(path.c_str(), 0777) == -1 && errno != EEXIST)
throw SysError(format("creating directory `%1%'") % path); throw SysError(format("creating directory %1%") % path);
st = lstat(path); st = lstat(path);
created.push_back(path); created.push_back(path);
} }
if (!S_ISDIR(st.st_mode)) throw Error(format("`%1%' is not a directory") % path); if (!S_ISDIR(st.st_mode)) throw Error(format("%1% is not a directory") % path);
return created; return created;
} }
@ -389,7 +389,7 @@ Paths createDirs(const Path & path)
void createSymlink(const Path & target, const Path & link) void createSymlink(const Path & target, const Path & link)
{ {
if (symlink(target.c_str(), link.c_str())) if (symlink(target.c_str(), link.c_str()))
throw SysError(format("creating symlink from `%1%' to `%2%'") % link % target); throw SysError(format("creating symlink from %1% to %2%") % link % target);
} }
@ -560,7 +560,7 @@ AutoDelete::~AutoDelete()
deletePath(path); deletePath(path);
else { else {
if (remove(path.c_str()) == -1) if (remove(path.c_str()) == -1)
throw SysError(format("cannot unlink `%1%'") % path); throw SysError(format("cannot unlink %1%") % path);
} }
} }
} catch (...) { } catch (...) {
@ -801,7 +801,7 @@ void Pid::setKillSignal(int signal)
void killUser(uid_t uid) void killUser(uid_t uid)
{ {
debug(format("killing all processes running under uid `%1%'") % uid); debug(format("killing all processes running under uid %1%") % uid);
assert(uid != 0); /* just to be safe... */ assert(uid != 0); /* just to be safe... */
@ -827,7 +827,7 @@ void killUser(uid_t uid)
#endif #endif
if (errno == ESRCH) break; /* no more processes */ if (errno == ESRCH) break; /* no more processes */
if (errno != EINTR) if (errno != EINTR)
throw SysError(format("cannot kill processes for uid `%1%'") % uid); throw SysError(format("cannot kill processes for uid %1%") % uid);
} }
_exit(0); _exit(0);
@ -835,7 +835,7 @@ void killUser(uid_t uid)
int status = pid.wait(true); int status = pid.wait(true);
if (status != 0) if (status != 0)
throw Error(format("cannot kill processes for uid `%1%': %2%") % uid % statusToString(status)); throw Error(format("cannot kill processes for uid %1%: %2%") % uid % statusToString(status));
/* !!! We should really do some check to make sure that there are /* !!! We should really do some check to make sure that there are
no processes left running under `uid', but there is no portable no processes left running under `uid', but there is no portable
@ -893,7 +893,7 @@ string runProgram(Path program, bool searchPath, const Strings & args)
else else
execv(program.c_str(), (char * *) &cargs[0]); execv(program.c_str(), (char * *) &cargs[0]);
throw SysError(format("executing `%1%'") % program); throw SysError(format("executing %1%") % program);
}); });
pipe.writeSide.close(); pipe.writeSide.close();
@ -903,7 +903,7 @@ string runProgram(Path program, bool searchPath, const Strings & args)
/* Wait for the child to finish. */ /* Wait for the child to finish. */
int status = pid.wait(true); int status = pid.wait(true);
if (!statusOk(status)) if (!statusOk(status))
throw ExecError(format("program `%1%' %2%") throw ExecError(format("program %1% %2%")
% program % statusToString(status)); % program % statusToString(status));
return result; return result;
@ -1046,7 +1046,7 @@ void expect(std::istream & str, const string & s)
char s2[s.size()]; char s2[s.size()];
str.read(s2, s.size()); str.read(s2, s.size());
if (string(s2, s.size()) != s) if (string(s2, s.size()) != s)
throw FormatError(format("expected string `%1%'") % s); throw FormatError(format("expected string %1%") % s);
} }

View file

@ -548,7 +548,7 @@ static void processConnection(bool trusted)
/* Prevent users from doing something very dangerous. */ /* Prevent users from doing something very dangerous. */
if (geteuid() == 0 && if (geteuid() == 0 &&
querySetting("build-users-group", "") == "") querySetting("build-users-group", "") == "")
throw Error("if you run `nix-daemon' as root, then you MUST set `build-users-group'!"); throw Error("if you run nix-daemon as root, then you MUST set build-users-group!");
#endif #endif
/* Open the store. */ /* Open the store. */
@ -683,7 +683,7 @@ static void daemonLoop(char * * argv)
struct sockaddr_un addr; struct sockaddr_un addr;
addr.sun_family = AF_UNIX; addr.sun_family = AF_UNIX;
if (socketPathRel.size() >= sizeof(addr.sun_path)) if (socketPathRel.size() >= sizeof(addr.sun_path))
throw Error(format("socket path `%1%' is too long") % socketPathRel); throw Error(format("socket path %1% is too long") % socketPathRel);
strcpy(addr.sun_path, socketPathRel.c_str()); strcpy(addr.sun_path, socketPathRel.c_str());
unlink(socketPath.c_str()); unlink(socketPath.c_str());
@ -695,12 +695,12 @@ static void daemonLoop(char * * argv)
int res = bind(fdSocket, (struct sockaddr *) &addr, sizeof(addr)); int res = bind(fdSocket, (struct sockaddr *) &addr, sizeof(addr));
umask(oldMode); umask(oldMode);
if (res == -1) if (res == -1)
throw SysError(format("cannot bind to socket `%1%'") % socketPath); throw SysError(format("cannot bind to socket %1%") % socketPath);
chdir("/"); /* back to the root */ chdir("/"); /* back to the root */
if (listen(fdSocket, 5) == -1) if (listen(fdSocket, 5) == -1)
throw SysError(format("cannot listen on socket `%1%'") % socketPath); throw SysError(format("cannot listen on socket %1%") % socketPath);
} }
closeOnExec(fdSocket); closeOnExec(fdSocket);
@ -752,7 +752,7 @@ static void daemonLoop(char * * argv)
trusted = true; trusted = true;
if (!trusted && !matchUser(user, group, allowedUsers)) if (!trusted && !matchUser(user, group, allowedUsers))
throw Error(format("user `%1%' is not allowed to connect to the Nix daemon") % user); throw Error(format("user %1% is not allowed to connect to the Nix daemon") % user);
printMsg(lvlInfo, format((string) "accepted connection from pid %1%, user %2%" printMsg(lvlInfo, format((string) "accepted connection from pid %1%, user %2%"
+ (trusted ? " (trusted)" : "")) % clientPid % user); + (trusted ? " (trusted)" : "")) % clientPid % user);

View file

@ -69,7 +69,7 @@ static string needArg(Strings::iterator & i,
Strings & args, const string & arg) Strings & args, const string & arg)
{ {
if (i == args.end()) throw UsageError( if (i == args.end()) throw UsageError(
format("`%1%' requires an argument") % arg); format("%1% requires an argument") % arg);
return *i++; return *i++;
} }
@ -123,7 +123,7 @@ static void getAllExprs(EvalState & state,
if (hasSuffix(attrName, ".nix")) if (hasSuffix(attrName, ".nix"))
attrName = string(attrName, 0, attrName.size() - 4); attrName = string(attrName, 0, attrName.size() - 4);
if (attrs.find(attrName) != attrs.end()) { if (attrs.find(attrName) != attrs.end()) {
printMsg(lvlError, format("warning: name collision in input Nix expressions, skipping `%1%'") % path2); printMsg(lvlError, format("warning: name collision in input Nix expressions, skipping %1%") % path2);
continue; continue;
} }
attrs.insert(attrName); attrs.insert(attrName);
@ -146,7 +146,7 @@ static void loadSourceExpr(EvalState & state, const Path & path, Value & v)
{ {
struct stat st; struct stat st;
if (stat(path.c_str(), &st) == -1) if (stat(path.c_str(), &st) == -1)
throw SysError(format("getting information about `%1%'") % path); throw SysError(format("getting information about %1%") % path);
if (isNixExpr(path, st)) { if (isNixExpr(path, st)) {
state.evalFile(path, v); state.evalFile(path, v);
@ -232,7 +232,7 @@ static void checkSelectorUse(DrvNames & selectors)
/* Check that all selectors have been used. */ /* Check that all selectors have been used. */
foreach (DrvNames::iterator, i, selectors) foreach (DrvNames::iterator, i, selectors)
if (i->hits == 0 && i->fullName != "*") if (i->hits == 0 && i->fullName != "*")
throw Error(format("selector `%1%' matches no derivations") % i->fullName); throw Error(format("selector %1% matches no derivations") % i->fullName);
} }
@ -303,7 +303,7 @@ static DrvInfos filterBySelector(EvalState & state, const DrvInfos & allElems,
for (Newest::iterator j = newest.begin(); j != newest.end(); ++j) { for (Newest::iterator j = newest.begin(); j != newest.end(); ++j) {
if (multiple.find(j->second.first.name) != multiple.end()) if (multiple.find(j->second.first.name) != multiple.end())
printMsg(lvlInfo, printMsg(lvlInfo,
format("warning: there are multiple derivations named `%1%'; using the first one") format("warning: there are multiple derivations named %1%; using the first one")
% j->second.first.name); % j->second.first.name);
matches.push_back(j->second); matches.push_back(j->second);
} }
@ -494,13 +494,13 @@ static void installDerivations(Globals & globals,
if (!globals.preserveInstalled && if (!globals.preserveInstalled &&
newNames.find(drvName.name) != newNames.end() && newNames.find(drvName.name) != newNames.end() &&
!keep(*i)) !keep(*i))
printMsg(lvlInfo, format("replacing old `%1%'") % i->name); printMsg(lvlInfo, format("replacing old %1%") % i->name);
else else
allElems.push_back(*i); allElems.push_back(*i);
} }
foreach (DrvInfos::iterator, i, newElems) foreach (DrvInfos::iterator, i, newElems)
printMsg(lvlInfo, format("installing `%1%'") % i->name); printMsg(lvlInfo, format("installing %1%") % i->name);
} }
printMissing(*globals.state, newElems); printMissing(*globals.state, newElems);
@ -522,7 +522,7 @@ static void opInstall(Globals & globals, Strings opFlags, Strings opArgs)
globals.preserveInstalled = true; globals.preserveInstalled = true;
else if (arg == "--remove-all" || arg == "-r") else if (arg == "--remove-all" || arg == "-r")
globals.removeAll = true; globals.removeAll = true;
else throw UsageError(format("unknown flag `%1%'") % arg); else throw UsageError(format("unknown flag %1%") % arg);
} }
installDerivations(globals, opArgs, globals.profile); installDerivations(globals, opArgs, globals.profile);
@ -599,13 +599,13 @@ static void upgradeDerivations(Globals & globals,
bestElem->queryOutPath()) bestElem->queryOutPath())
{ {
printMsg(lvlInfo, printMsg(lvlInfo,
format("upgrading `%1%' to `%2%'") format("upgrading %1% to %2%")
% i->name % bestElem->name); % i->name % bestElem->name);
newElems.push_back(*bestElem); newElems.push_back(*bestElem);
} else newElems.push_back(*i); } else newElems.push_back(*i);
} catch (Error & e) { } catch (Error & e) {
e.addPrefix(format("while trying to find an upgrade for `%1%':\n") % i->name); e.addPrefix(format("while trying to find an upgrade for %1%:\n") % i->name);
throw; throw;
} }
} }
@ -630,7 +630,7 @@ static void opUpgrade(Globals & globals, Strings opFlags, Strings opArgs)
else if (arg == "--leq") upgradeType = utLeq; else if (arg == "--leq") upgradeType = utLeq;
else if (arg == "--eq") upgradeType = utEq; else if (arg == "--eq") upgradeType = utEq;
else if (arg == "--always") upgradeType = utAlways; else if (arg == "--always") upgradeType = utAlways;
else throw UsageError(format("unknown flag `%1%'") % arg); else throw UsageError(format("unknown flag %1%") % arg);
} }
upgradeDerivations(globals, opArgs, upgradeType); upgradeDerivations(globals, opArgs, upgradeType);
@ -649,9 +649,9 @@ static void setMetaFlag(EvalState & state, DrvInfo & drv,
static void opSetFlag(Globals & globals, Strings opFlags, Strings opArgs) static void opSetFlag(Globals & globals, Strings opFlags, Strings opArgs)
{ {
if (opFlags.size() > 0) if (opFlags.size() > 0)
throw UsageError(format("unknown flag `%1%'") % opFlags.front()); throw UsageError(format("unknown flag %1%") % opFlags.front());
if (opArgs.size() < 2) if (opArgs.size() < 2)
throw UsageError("not enough arguments to `--set-flag'"); throw UsageError("not enough arguments to --set-flag");
Strings::iterator arg = opArgs.begin(); Strings::iterator arg = opArgs.begin();
string flagName = *arg++; string flagName = *arg++;
@ -668,7 +668,7 @@ static void opSetFlag(Globals & globals, Strings opFlags, Strings opArgs)
DrvName drvName(i->name); DrvName drvName(i->name);
foreach (DrvNames::iterator, j, selectors) foreach (DrvNames::iterator, j, selectors)
if (j->matches(drvName)) { if (j->matches(drvName)) {
printMsg(lvlInfo, format("setting flag on `%1%'") % i->name); printMsg(lvlInfo, format("setting flag on %1%") % i->name);
j->hits++; j->hits++;
setMetaFlag(*globals.state, *i, flagName, flagValue); setMetaFlag(*globals.state, *i, flagName, flagValue);
break; break;
@ -689,7 +689,7 @@ static void opSet(Globals & globals, Strings opFlags, Strings opArgs)
for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) { for (Strings::iterator i = opFlags.begin(); i != opFlags.end(); ) {
string arg = *i++; string arg = *i++;
if (parseInstallSourceOptions(globals, i, opFlags, arg)) ; if (parseInstallSourceOptions(globals, i, opFlags, arg)) ;
else throw UsageError(format("unknown flag `%1%'") % arg); else throw UsageError(format("unknown flag %1%") % arg);
} }
DrvInfos elems; DrvInfos elems;
@ -736,7 +736,7 @@ static void uninstallDerivations(Globals & globals, Strings & selectors,
if ((isPath(*j) && i->queryOutPath() == followLinksToStorePath(*j)) if ((isPath(*j) && i->queryOutPath() == followLinksToStorePath(*j))
|| DrvName(*j).matches(drvName)) || DrvName(*j).matches(drvName))
{ {
printMsg(lvlInfo, format("uninstalling `%1%'") % i->name); printMsg(lvlInfo, format("uninstalling %1%") % i->name);
found = true; found = true;
break; break;
} }
@ -754,7 +754,7 @@ static void uninstallDerivations(Globals & globals, Strings & selectors,
static void opUninstall(Globals & globals, Strings opFlags, Strings opArgs) static void opUninstall(Globals & globals, Strings opFlags, Strings opArgs)
{ {
if (opFlags.size() > 0) if (opFlags.size() > 0)
throw UsageError(format("unknown flag `%1%'") % opFlags.front()); throw UsageError(format("unknown flag %1%") % opFlags.front());
uninstallDerivations(globals, opArgs, globals.profile); uninstallDerivations(globals, opArgs, globals.profile);
} }
@ -864,7 +864,7 @@ static void queryJSON(Globals & globals, vector<DrvInfo> & elems)
metaObj.attr(*j); metaObj.attr(*j);
Value * v = i->queryMeta(*j); Value * v = i->queryMeta(*j);
if (!v) { if (!v) {
printMsg(lvlError, format("derivation `%1%' has invalid meta attribute `%2%'") % i->name % *j); printMsg(lvlError, format("derivation %1% has invalid meta attribute %2%") % i->name % *j);
cout << "null"; cout << "null";
} else { } else {
PathSet context; PathSet context;
@ -914,7 +914,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
else if (arg == "--attr" || arg == "-A") else if (arg == "--attr" || arg == "-A")
attrPath = needArg(i, opFlags, arg); attrPath = needArg(i, opFlags, arg);
else else
throw UsageError(format("unknown flag `%1%'") % arg); throw UsageError(format("unknown flag %1%") % arg);
} }
@ -963,7 +963,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
try { try {
paths.insert(i->queryOutPath()); paths.insert(i->queryOutPath());
} catch (AssertionError & e) { } catch (AssertionError & e) {
printMsg(lvlTalkative, format("skipping derivation named `%1%' which gives an assertion failure") % i->name); printMsg(lvlTalkative, format("skipping derivation named %1% which gives an assertion failure") % i->name);
i->setFailed(); i->setFailed();
} }
validPaths = store->queryValidPaths(paths); validPaths = store->queryValidPaths(paths);
@ -986,7 +986,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
try { try {
if (i->hasFailed()) continue; if (i->hasFailed()) continue;
startNest(nest, lvlDebug, format("outputting query result `%1%'") % i->attrPath); startNest(nest, lvlDebug, format("outputting query result %1%") % i->attrPath);
if (globals.prebuiltOnly && if (globals.prebuiltOnly &&
validPaths.find(i->queryOutPath()) == validPaths.end() && validPaths.find(i->queryOutPath()) == validPaths.end() &&
@ -1107,7 +1107,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
attrs2["name"] = *j; attrs2["name"] = *j;
Value * v = i->queryMeta(*j); Value * v = i->queryMeta(*j);
if (!v) if (!v)
printMsg(lvlError, format("derivation `%1%' has invalid meta attribute `%2%'") % i->name % *j); printMsg(lvlError, format("derivation %1% has invalid meta attribute %2%") % i->name % *j);
else { else {
if (v->type == tString) { if (v->type == tString) {
attrs2["type"] = "string"; attrs2["type"] = "string";
@ -1142,9 +1142,9 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
cout.flush(); cout.flush();
} catch (AssertionError & e) { } catch (AssertionError & e) {
printMsg(lvlTalkative, format("skipping derivation named `%1%' which gives an assertion failure") % i->name); printMsg(lvlTalkative, format("skipping derivation named %1% which gives an assertion failure") % i->name);
} catch (Error & e) { } catch (Error & e) {
e.addPrefix(format("while querying the derivation named `%1%':\n") % i->name); e.addPrefix(format("while querying the derivation named %1%:\n") % i->name);
throw; throw;
} }
} }
@ -1156,7 +1156,7 @@ static void opQuery(Globals & globals, Strings opFlags, Strings opArgs)
static void opSwitchProfile(Globals & globals, Strings opFlags, Strings opArgs) static void opSwitchProfile(Globals & globals, Strings opFlags, Strings opArgs)
{ {
if (opFlags.size() > 0) if (opFlags.size() > 0)
throw UsageError(format("unknown flag `%1%'") % opFlags.front()); throw UsageError(format("unknown flag %1%") % opFlags.front());
if (opArgs.size() != 1) if (opArgs.size() != 1)
throw UsageError(format("exactly one argument expected")); throw UsageError(format("exactly one argument expected"));
@ -1204,7 +1204,7 @@ static void switchGeneration(Globals & globals, int dstGen)
static void opSwitchGeneration(Globals & globals, Strings opFlags, Strings opArgs) static void opSwitchGeneration(Globals & globals, Strings opFlags, Strings opArgs)
{ {
if (opFlags.size() > 0) if (opFlags.size() > 0)
throw UsageError(format("unknown flag `%1%'") % opFlags.front()); throw UsageError(format("unknown flag %1%") % opFlags.front());
if (opArgs.size() != 1) if (opArgs.size() != 1)
throw UsageError(format("exactly one argument expected")); throw UsageError(format("exactly one argument expected"));
@ -1219,7 +1219,7 @@ static void opSwitchGeneration(Globals & globals, Strings opFlags, Strings opArg
static void opRollback(Globals & globals, Strings opFlags, Strings opArgs) static void opRollback(Globals & globals, Strings opFlags, Strings opArgs)
{ {
if (opFlags.size() > 0) if (opFlags.size() > 0)
throw UsageError(format("unknown flag `%1%'") % opFlags.front()); throw UsageError(format("unknown flag %1%") % opFlags.front());
if (opArgs.size() != 0) if (opArgs.size() != 0)
throw UsageError(format("no arguments expected")); throw UsageError(format("no arguments expected"));
@ -1230,7 +1230,7 @@ static void opRollback(Globals & globals, Strings opFlags, Strings opArgs)
static void opListGenerations(Globals & globals, Strings opFlags, Strings opArgs) static void opListGenerations(Globals & globals, Strings opFlags, Strings opArgs)
{ {
if (opFlags.size() > 0) if (opFlags.size() > 0)
throw UsageError(format("unknown flag `%1%'") % opFlags.front()); throw UsageError(format("unknown flag %1%") % opFlags.front());
if (opArgs.size() != 0) if (opArgs.size() != 0)
throw UsageError(format("no arguments expected")); throw UsageError(format("no arguments expected"));
@ -1267,7 +1267,7 @@ static void deleteGeneration2(Globals & globals, unsigned int gen)
static void opDeleteGenerations(Globals & globals, Strings opFlags, Strings opArgs) static void opDeleteGenerations(Globals & globals, Strings opFlags, Strings opArgs)
{ {
if (opFlags.size() > 0) if (opFlags.size() > 0)
throw UsageError(format("unknown flag `%1%'") % opFlags.front()); throw UsageError(format("unknown flag %1%") % opFlags.front());
PathLocks lock; PathLocks lock;
lockProfile(lock, globals.profile); lockProfile(lock, globals.profile);
@ -1288,7 +1288,7 @@ static void opDeleteGenerations(Globals & globals, Strings opFlags, Strings opAr
int days; int days;
if (!string2Int(strDays, days) || days < 1) if (!string2Int(strDays, days) || days < 1)
throw UsageError(format("invalid number of days specifier `%1%'") % *i); throw UsageError(format("invalid number of days specifier %1%") % *i);
oldTime = curTime - days * 24 * 3600; oldTime = curTime - days * 24 * 3600;
@ -1307,7 +1307,7 @@ static void opDeleteGenerations(Globals & globals, Strings opFlags, Strings opAr
} else { } else {
int n; int n;
if (!string2Int(*i, n) || n < 0) if (!string2Int(*i, n) || n < 0)
throw UsageError(format("invalid generation specifier `%1%'") % *i); throw UsageError(format("invalid generation specifier %1%") % *i);
bool found = false; bool found = false;
for (Generations::iterator j = gens.begin(); j != gens.end(); ++j) { for (Generations::iterator j = gens.begin(); j != gens.end(); ++j) {
if (j->number == n) { if (j->number == n) {

View file

@ -50,7 +50,7 @@ Generations findGenerations(Path profile, int & curGen)
gen.number = n; gen.number = n;
struct stat st; struct stat st;
if (lstat(gen.path.c_str(), &st) != 0) if (lstat(gen.path.c_str(), &st) != 0)
throw SysError(format("statting `%1%'") % gen.path); throw SysError(format("statting %1%") % gen.path);
gen.creationTime = st.st_mtime; gen.creationTime = st.st_mtime;
gens.push_back(gen); gens.push_back(gen);
} }
@ -99,7 +99,7 @@ Path createGeneration(Path profile, Path outPath)
static void removeFile(const Path & path) static void removeFile(const Path & path)
{ {
if (remove(path.c_str()) == -1) if (remove(path.c_str()) == -1)
throw SysError(format("cannot unlink `%1%'") % path); throw SysError(format("cannot unlink %1%") % path);
} }
@ -125,14 +125,14 @@ void switchLink(Path link, Path target)
file-not-found or other error condition. This is sufficient to file-not-found or other error condition. This is sufficient to
atomically switch user environments. */ atomically switch user environments. */
if (rename(tmp.c_str(), link.c_str()) != 0) if (rename(tmp.c_str(), link.c_str()) != 0)
throw SysError(format("renaming `%1%' to `%2%'") % tmp % link); throw SysError(format("renaming %1% to %2%") % tmp % link);
} }
void lockProfile(PathLocks & lock, const Path & profile) void lockProfile(PathLocks & lock, const Path & profile)
{ {
lock.lockPaths(singleton<PathSet>(profile), lock.lockPaths(singleton<PathSet>(profile),
(format("waiting for lock on profile `%1%'") % profile).str()); (format("waiting for lock on profile %1%") % profile).str());
lock.setDeletion(true); lock.setDeletion(true);
} }

View file

@ -136,7 +136,7 @@ bool createUserEnv(EvalState & state, DrvInfos & elems,
Path lockTokenCur = optimisticLockProfile(profile); Path lockTokenCur = optimisticLockProfile(profile);
if (lockToken != lockTokenCur) { if (lockToken != lockTokenCur) {
printMsg(lvlError, format("profile `%1%' changed while we were busy; restarting") % profile); printMsg(lvlError, format("profile %1% changed while we were busy; restarting") % profile);
return false; return false;
} }

View file

@ -31,7 +31,7 @@ int main(int argc, char * * argv)
string s = getArg(*arg, arg, end); string s = getArg(*arg, arg, end);
ht = parseHashType(s); ht = parseHashType(s);
if (ht == htUnknown) if (ht == htUnknown)
throw UsageError(format("unknown hash type `%1%'") % s); throw UsageError(format("unknown hash type %1%") % s);
} }
else if (*arg == "--to-base16") op = opTo16; else if (*arg == "--to-base16") op = opTo16;
else if (*arg == "--to-base32") op = opTo32; else if (*arg == "--to-base32") op = opTo32;

View file

@ -73,7 +73,7 @@ void processExpr(EvalState & state, const Strings & attrPaths,
/* What output do we want? */ /* What output do we want? */
string outputName = i->queryOutputName(); string outputName = i->queryOutputName();
if (outputName == "") if (outputName == "")
throw Error(format("derivation `%1%' lacks an `outputName' attribute ") % drvPath); throw Error(format("derivation %1% lacks an outputName attribute ") % drvPath);
if (gcRoot == "") if (gcRoot == "")
printGCWarning(); printGCWarning();
@ -168,7 +168,7 @@ int main(int argc, char * * argv)
if (findFile) { if (findFile) {
foreach (Strings::iterator, i, files) { foreach (Strings::iterator, i, files) {
Path p = state.findFile(*i); Path p = state.findFile(*i);
if (p == "") throw Error(format("unable to find `%1%'") % *i); if (p == "") throw Error(format("unable to find %1%") % *i);
std::cout << p << std::endl; std::cout << p << std::endl;
} }
return; return;

View file

@ -77,7 +77,7 @@ void printClosure(const Path & nePath, const StoreExpr & fs)
ClosureElems::const_iterator elem = fs.closure.elems.find(path); ClosureElems::const_iterator elem = fs.closure.elems.find(path);
if (elem == fs.closure.elems.end()) if (elem == fs.closure.elems.end())
throw Error(format("bad closure, missing path `%1%'") % path); throw Error(format("bad closure, missing path %1%") % path);
for (StringSet::const_iterator i = elem->second.refs.begin(); for (StringSet::const_iterator i = elem->second.refs.begin();
i != elem->second.refs.end(); ++i) i != elem->second.refs.end(); ++i)

View file

@ -48,7 +48,7 @@ static Path useDeriver(Path path)
if (!isDerivation(path)) { if (!isDerivation(path)) {
path = store->queryDeriver(path); path = store->queryDeriver(path);
if (path == "") if (path == "")
throw Error(format("deriver of path `%1%' is not known") % path); throw Error(format("deriver of path %1% is not known") % path);
} }
return path; return path;
} }
@ -72,7 +72,7 @@ static PathSet realisePath(Path path, bool build = true)
foreach (StringSet::iterator, j, p.second) { foreach (StringSet::iterator, j, p.second) {
DerivationOutputs::iterator i = drv.outputs.find(*j); DerivationOutputs::iterator i = drv.outputs.find(*j);
if (i == drv.outputs.end()) if (i == drv.outputs.end())
throw Error(format("derivation `%1%' does not have an output named `%2%'") % p.first % *j); throw Error(format("derivation %1% does not have an output named %2%") % p.first % *j);
Path outPath = i->second.path; Path outPath = i->second.path;
if (gcRoot == "") if (gcRoot == "")
printGCWarning(); printGCWarning();
@ -89,7 +89,7 @@ static PathSet realisePath(Path path, bool build = true)
else { else {
if (build) store->ensurePath(path); if (build) store->ensurePath(path);
else if (!store->isValidPath(path)) throw Error(format("path `%1%' does not exist and cannot be created") % path); else if (!store->isValidPath(path)) throw Error(format("path %1% does not exist and cannot be created") % path);
if (gcRoot == "") if (gcRoot == "")
printGCWarning(); printGCWarning();
else { else {
@ -115,7 +115,7 @@ static void opRealise(Strings opFlags, Strings opArgs)
else if (*i == "--repair") buildMode = bmRepair; else if (*i == "--repair") buildMode = bmRepair;
else if (*i == "--check") buildMode = bmCheck; else if (*i == "--check") buildMode = bmCheck;
else if (*i == "--ignore-unknown") ignoreUnknown = true; else if (*i == "--ignore-unknown") ignoreUnknown = true;
else throw UsageError(format("unknown flag `%1%'") % *i); else throw UsageError(format("unknown flag %1%") % *i);
Paths paths; Paths paths;
foreach (Strings::iterator, i, opArgs) { foreach (Strings::iterator, i, opArgs) {
@ -172,7 +172,7 @@ static void opAddFixed(Strings opFlags, Strings opArgs)
for (Strings::iterator i = opFlags.begin(); for (Strings::iterator i = opFlags.begin();
i != opFlags.end(); ++i) i != opFlags.end(); ++i)
if (*i == "--recursive") recursive = true; if (*i == "--recursive") recursive = true;
else throw UsageError(format("unknown flag `%1%'") % *i); else throw UsageError(format("unknown flag %1%") % *i);
if (opArgs.empty()) if (opArgs.empty())
throw UsageError("first argument must be hash algorithm"); throw UsageError("first argument must be hash algorithm");
@ -193,10 +193,10 @@ static void opPrintFixedPath(Strings opFlags, Strings opArgs)
for (Strings::iterator i = opFlags.begin(); for (Strings::iterator i = opFlags.begin();
i != opFlags.end(); ++i) i != opFlags.end(); ++i)
if (*i == "--recursive") recursive = true; if (*i == "--recursive") recursive = true;
else throw UsageError(format("unknown flag `%1%'") % *i); else throw UsageError(format("unknown flag %1%") % *i);
if (opArgs.size() != 3) if (opArgs.size() != 3)
throw UsageError(format("`--print-fixed-path' requires three arguments")); throw UsageError(format("--print-fixed-path requires three arguments"));
Strings::iterator i = opArgs.begin(); Strings::iterator i = opArgs.begin();
HashType hashAlgo = parseHashType(*i++); HashType hashAlgo = parseHashType(*i++);
@ -297,7 +297,7 @@ static void opQuery(Strings opFlags, Strings opArgs)
else if (*i == "--use-output" || *i == "-u") useOutput = true; else if (*i == "--use-output" || *i == "-u") useOutput = true;
else if (*i == "--force-realise" || *i == "--force-realize" || *i == "-f") forceRealise = true; else if (*i == "--force-realise" || *i == "--force-realize" || *i == "-f") forceRealise = true;
else if (*i == "--include-outputs") includeOutputs = true; else if (*i == "--include-outputs") includeOutputs = true;
else throw UsageError(format("unknown flag `%1%'") % *i); else throw UsageError(format("unknown flag %1%") % *i);
switch (query) { switch (query) {
@ -347,7 +347,7 @@ static void opQuery(Strings opFlags, Strings opArgs)
Derivation drv = derivationFromPath(*store, path); Derivation drv = derivationFromPath(*store, path);
StringPairs::iterator j = drv.env.find(bindingName); StringPairs::iterator j = drv.env.find(bindingName);
if (j == drv.env.end()) if (j == drv.env.end())
throw Error(format("derivation `%1%' has no environment binding named `%2%'") throw Error(format("derivation %1% has no environment binding named %2%")
% path % bindingName); % path % bindingName);
cout << format("%1%\n") % j->second; cout << format("%1%\n") % j->second;
} }
@ -434,7 +434,7 @@ static string shellEscape(const string & s)
static void opPrintEnv(Strings opFlags, Strings opArgs) static void opPrintEnv(Strings opFlags, Strings opArgs)
{ {
if (!opFlags.empty()) throw UsageError("unknown flag"); if (!opFlags.empty()) throw UsageError("unknown flag");
if (opArgs.size() != 1) throw UsageError("`--print-env' requires one derivation store path"); if (opArgs.size() != 1) throw UsageError("--print-env requires one derivation store path");
Path drvPath = opArgs.front(); Path drvPath = opArgs.front();
Derivation drv = derivationFromPath(*store, drvPath); Derivation drv = derivationFromPath(*store, drvPath);
@ -487,15 +487,15 @@ static void opReadLog(Strings opFlags, Strings opArgs)
AutoCloseFD fd = open(logBz2Path.c_str(), O_RDONLY); AutoCloseFD fd = open(logBz2Path.c_str(), O_RDONLY);
FILE * f = 0; FILE * f = 0;
if (fd == -1 || (f = fdopen(fd.borrow(), "r")) == 0) if (fd == -1 || (f = fdopen(fd.borrow(), "r")) == 0)
throw SysError(format("opening file `%1%'") % logBz2Path); throw SysError(format("opening file %1%") % logBz2Path);
int err; int err;
BZFILE * bz = BZ2_bzReadOpen(&err, f, 0, 0, 0, 0); BZFILE * bz = BZ2_bzReadOpen(&err, f, 0, 0, 0, 0);
if (!bz) throw Error(format("cannot open bzip2 file `%1%'") % logBz2Path); if (!bz) throw Error(format("cannot open bzip2 file %1%") % logBz2Path);
unsigned char buf[128 * 1024]; unsigned char buf[128 * 1024];
do { do {
int n = BZ2_bzRead(&err, bz, buf, sizeof(buf)); int n = BZ2_bzRead(&err, bz, buf, sizeof(buf));
if (err != BZ_OK && err != BZ_STREAM_END) if (err != BZ_OK && err != BZ_STREAM_END)
throw Error(format("error reading bzip2 file `%1%'") % logBz2Path); throw Error(format("error reading bzip2 file %1%") % logBz2Path);
writeFull(STDOUT_FILENO, buf, n); writeFull(STDOUT_FILENO, buf, n);
} while (err != BZ_STREAM_END); } while (err != BZ_STREAM_END);
BZ2_bzReadClose(&err, bz); BZ2_bzReadClose(&err, bz);
@ -522,7 +522,7 @@ static void opReadLog(Strings opFlags, Strings opArgs)
} }
} }
if (!found) throw Error(format("build log of derivation `%1%' is not available") % path); if (!found) throw Error(format("build log of derivation %1% is not available") % path);
} }
} }
@ -580,7 +580,7 @@ static void opRegisterValidity(Strings opFlags, Strings opArgs)
i != opFlags.end(); ++i) i != opFlags.end(); ++i)
if (*i == "--reregister") reregister = true; if (*i == "--reregister") reregister = true;
else if (*i == "--hash-given") hashGiven = true; else if (*i == "--hash-given") hashGiven = true;
else throw UsageError(format("unknown flag `%1%'") % *i); else throw UsageError(format("unknown flag %1%") % *i);
if (!opArgs.empty()) throw UsageError("no arguments expected"); if (!opArgs.empty()) throw UsageError("no arguments expected");
@ -595,7 +595,7 @@ static void opCheckValidity(Strings opFlags, Strings opArgs)
for (Strings::iterator i = opFlags.begin(); for (Strings::iterator i = opFlags.begin();
i != opFlags.end(); ++i) i != opFlags.end(); ++i)
if (*i == "--print-invalid") printInvalid = true; if (*i == "--print-invalid") printInvalid = true;
else throw UsageError(format("unknown flag `%1%'") % *i); else throw UsageError(format("unknown flag %1%") % *i);
for (Strings::iterator i = opArgs.begin(); for (Strings::iterator i = opArgs.begin();
i != opArgs.end(); ++i) i != opArgs.end(); ++i)
@ -605,7 +605,7 @@ static void opCheckValidity(Strings opFlags, Strings opArgs)
if (printInvalid) if (printInvalid)
cout << format("%1%\n") % path; cout << format("%1%\n") % path;
else else
throw Error(format("path `%1%' is not valid") % path); throw Error(format("path %1% is not valid") % path);
} }
} }
} }
@ -651,7 +651,7 @@ static void opGC(Strings opFlags, Strings opArgs)
long long maxFreed = getIntArg<long long>(*i, i, opFlags.end(), true); long long maxFreed = getIntArg<long long>(*i, i, opFlags.end(), true);
options.maxFreed = maxFreed >= 0 ? maxFreed : 0; options.maxFreed = maxFreed >= 0 ? maxFreed : 0;
} }
else throw UsageError(format("bad sub-operation `%1%' in GC") % *i); else throw UsageError(format("bad sub-operation %1% in GC") % *i);
if (!opArgs.empty()) throw UsageError("no arguments expected"); if (!opArgs.empty()) throw UsageError("no arguments expected");
@ -682,7 +682,7 @@ static void opDelete(Strings opFlags, Strings opArgs)
foreach (Strings::iterator, i, opFlags) foreach (Strings::iterator, i, opFlags)
if (*i == "--ignore-liveness") options.ignoreLiveness = true; if (*i == "--ignore-liveness") options.ignoreLiveness = true;
else throw UsageError(format("unknown flag `%1%'") % *i); else throw UsageError(format("unknown flag %1%") % *i);
foreach (Strings::iterator, i, opArgs) foreach (Strings::iterator, i, opArgs)
options.pathsToDelete.insert(followLinksToStorePath(*i)); options.pathsToDelete.insert(followLinksToStorePath(*i));
@ -724,7 +724,7 @@ static void opExport(Strings opFlags, Strings opArgs)
for (Strings::iterator i = opFlags.begin(); for (Strings::iterator i = opFlags.begin();
i != opFlags.end(); ++i) i != opFlags.end(); ++i)
if (*i == "--sign") sign = true; if (*i == "--sign") sign = true;
else throw UsageError(format("unknown flag `%1%'") % *i); else throw UsageError(format("unknown flag %1%") % *i);
FdSink sink(STDOUT_FILENO); FdSink sink(STDOUT_FILENO);
Paths sorted = topoSortPaths(*store, PathSet(opArgs.begin(), opArgs.end())); Paths sorted = topoSortPaths(*store, PathSet(opArgs.begin(), opArgs.end()));
@ -738,7 +738,7 @@ static void opImport(Strings opFlags, Strings opArgs)
bool requireSignature = false; bool requireSignature = false;
foreach (Strings::iterator, i, opFlags) foreach (Strings::iterator, i, opFlags)
if (*i == "--require-signature") requireSignature = true; if (*i == "--require-signature") requireSignature = true;
else throw UsageError(format("unknown flag `%1%'") % *i); else throw UsageError(format("unknown flag %1%") % *i);
if (!opArgs.empty()) throw UsageError("no arguments expected"); if (!opArgs.empty()) throw UsageError("no arguments expected");
@ -774,7 +774,7 @@ static void opVerify(Strings opFlags, Strings opArgs)
i != opFlags.end(); ++i) i != opFlags.end(); ++i)
if (*i == "--check-contents") checkContents = true; if (*i == "--check-contents") checkContents = true;
else if (*i == "--repair") repair = true; else if (*i == "--repair") repair = true;
else throw UsageError(format("unknown flag `%1%'") % *i); else throw UsageError(format("unknown flag %1%") % *i);
if (ensureLocalStore().verifyStore(checkContents, repair)) { if (ensureLocalStore().verifyStore(checkContents, repair)) {
printMsg(lvlError, "warning: not all errors were fixed"); printMsg(lvlError, "warning: not all errors were fixed");
@ -793,12 +793,12 @@ static void opVerifyPath(Strings opFlags, Strings opArgs)
foreach (Strings::iterator, i, opArgs) { foreach (Strings::iterator, i, opArgs) {
Path path = followLinksToStorePath(*i); Path path = followLinksToStorePath(*i);
printMsg(lvlTalkative, format("checking path `%1%'...") % path); printMsg(lvlTalkative, format("checking path %1%...") % path);
ValidPathInfo info = store->queryPathInfo(path); ValidPathInfo info = store->queryPathInfo(path);
HashResult current = hashPath(info.hash.type, path); HashResult current = hashPath(info.hash.type, path);
if (current.first != info.hash) { if (current.first != info.hash) {
printMsg(lvlError, printMsg(lvlError,
format("path `%1%' was modified! expected hash `%2%', got `%3%'") format("path %1% was modified! expected hash %2%, got %3%")
% path % printHash(info.hash) % printHash(current.first)); % path % printHash(info.hash) % printHash(current.first));
status = 1; status = 1;
} }
@ -873,7 +873,7 @@ static void opServe(Strings opFlags, Strings opArgs)
bool writeAllowed = false; bool writeAllowed = false;
foreach (Strings::iterator, i, opFlags) foreach (Strings::iterator, i, opFlags)
if (*i == "--write") writeAllowed = true; if (*i == "--write") writeAllowed = true;
else throw UsageError(format("unknown flag `%1%'") % *i); else throw UsageError(format("unknown flag %1%") % *i);
if (!opArgs.empty()) throw UsageError("no arguments expected"); if (!opArgs.empty()) throw UsageError("no arguments expected");

View file

@ -1,2 +1,2 @@
echo "\`timeout' builder entering an infinite loop" echo "timeout builder entering an infinite loop"
while true ; do echo -n .; done while true ; do echo -n .; done

View file

@ -5,7 +5,7 @@ source common.sh
failed=0 failed=0
messages="`nix-build -Q timeout.nix --timeout 2 2>&1 || failed=1`" messages="`nix-build -Q timeout.nix --timeout 2 2>&1 || failed=1`"
if [ $failed -ne 0 ]; then if [ $failed -ne 0 ]; then
echo "error: \`nix-store' succeeded; should have timed out" echo "error: nix-store succeeded; should have timed out"
exit 1 exit 1
fi fi