@@ -1,494 +0,0 @@
1−# Code for buildRustCrate, a Nix function that builds Rust code, just
2−# like Cargo, but using Nix instead.
3−#
4−# This can be useful for deploying packages with NixOps, and to share
5−# binary dependencies between projects.
6−
7−{ lib, stdenv, defaultCrateOverrides, fetchCrate, ncurses, rustc }:
8−
9−let makeDeps = dependencies:
10− (lib.concatMapStringsSep " " (dep:
11− let extern = lib.strings.replaceStrings ["-"] ["_"] dep.libName; in
12− (if dep.crateType == "lib" then
13− " --extern ${extern}=${dep.out}/lib/lib${extern}-${dep.metadata}.rlib"
14− else
15− " --extern ${extern}=${dep.out}/lib/lib${extern}-${dep.metadata}${stdenv.hostPlatform.extensions.sharedLibrary}")
16− ) dependencies);
17−
18− # This doesn't appear to be officially documented anywhere yet.
19− # See https://github.com/rust-lang-nursery/rust-forge/issues/101.
20− target_os = if stdenv.hostPlatform.isDarwin
21− then "macos"
22− else stdenv.hostPlatform.parsed.kernel.name;
23−
24− echo_build_heading = colors: ''
25− echo_build_heading() {
26− start=""
27− end=""
28− if [[ "${colors}" == "always" ]]; then
29− start="$(printf '\033[0;1;32m')" #set bold, and set green.
30− end="$(printf '\033[0m')" #returns to "normal"
31− fi
32− if (( $# == 1 )); then
33− echo "$start""Building $1""$end"
34− else
35− echo "$start""Building $1 ($2)""$end"
36− fi
37− }
38− '';
39− noisily = colors: verbose: ''
40− noisily() {
41− start=""
42− end=""
43− if [[ "${colors}" == "always" ]]; then
44− start="$(printf '\033[0;1;32m')" #set bold, and set green.
45− end="$(printf '\033[0m')" #returns to "normal"
46− fi
47− ${lib.optionalString verbose ''
48− echo -n "$start"Running "$end"
49− echo $@
50− ''}
51− $@
52− }
53− '';
54−
55− configureCrate =
56− { crateName, crateVersion, crateAuthors, build, libName, crateFeatures, colors, libPath, release, buildDependencies, completeDeps, completeBuildDeps, verbose, workspace_member, extraLinkFlags }:
57− let version_ = lib.splitString "-" crateVersion;
58− versionPre = if lib.tail version_ == [] then "" else builtins.elemAt version_ 1;
59− version = lib.splitString "." (lib.head version_);
60− rustcOpts = (if release then "-C opt-level=3" else "-C debuginfo=2");
61− buildDeps = makeDeps buildDependencies;
62− authors = lib.concatStringsSep ":" crateAuthors;
63− optLevel = if release then 3 else 0;
64− completeDepsDir = lib.concatStringsSep " " completeDeps;
65− completeBuildDepsDir = lib.concatStringsSep " " completeBuildDeps;
66− in ''
67− cd ${workspace_member}
68− runHook preConfigure
69− ${echo_build_heading colors}
70− ${noisily colors verbose}
71− symlink_dependency() {
72− # $1 is the nix-store path of a dependency
73− # $2 is the target path
74− i=$1
75− ln -s -f $i/lib/*.rlib $2 #*/
76− ln -s -f $i/lib/*.so $i/lib/*.dylib $2 #*/
77− if [ -e "$i/lib/link" ]; then
78− cat $i/lib/link >> target/link
79− cat $i/lib/link >> target/link.final
80− fi
81− if [ -e $i/env ]; then
82− source $i/env
83− fi
84− }
85−
86− mkdir -p target/{deps,lib,build,buildDeps}
87− chmod uga+w target -R
88− echo ${extraLinkFlags} > target/link
89− echo ${extraLinkFlags} > target/link.final
90− for i in ${completeDepsDir}; do
91− symlink_dependency $i target/deps
92− done
93− for i in ${completeBuildDepsDir}; do
94− symlink_dependency $i target/buildDeps
95− done
96− if [[ -e target/link ]]; then
97− sort -u target/link > target/link.sorted
98− mv target/link.sorted target/link
99− sort -u target/link.final > target/link.final.sorted
100− mv target/link.final.sorted target/link.final
101− tr '\n' ' ' < target/link > target/link_
102− fi
103− EXTRA_BUILD=""
104− BUILD_OUT_DIR=""
105− export CARGO_PKG_NAME=${crateName}
106− export CARGO_PKG_VERSION=${crateVersion}
107− export CARGO_PKG_AUTHORS="${authors}"
108−
109− export CARGO_CFG_TARGET_ARCH=${stdenv.hostPlatform.parsed.cpu.name}
110− export CARGO_CFG_TARGET_OS=${target_os}
111− export CARGO_CFG_TARGET_FAMILY="unix"
112− export CARGO_CFG_UNIX=1
113− export CARGO_CFG_TARGET_ENV="gnu"
114− export CARGO_CFG_TARGET_ENDIAN=${if stdenv.hostPlatform.parsed.cpu.significantByte.name == "littleEndian" then "little" else "big"}
115− export CARGO_CFG_TARGET_POINTER_WIDTH=${toString stdenv.hostPlatform.parsed.cpu.bits}
116− export CARGO_CFG_TARGET_VENDOR=${stdenv.hostPlatform.parsed.vendor.name}
117−
118− export CARGO_MANIFEST_DIR="."
119− export DEBUG="${toString (!release)}"
120− export OPT_LEVEL="${toString optLevel}"
121− export TARGET="${stdenv.hostPlatform.config}"
122− export HOST="${stdenv.hostPlatform.config}"
123− export PROFILE=${if release then "release" else "debug"}
124− export OUT_DIR=$(pwd)/target/build/${crateName}.out
125− export CARGO_PKG_VERSION_MAJOR=${builtins.elemAt version 0}
126− export CARGO_PKG_VERSION_MINOR=${builtins.elemAt version 1}
127− export CARGO_PKG_VERSION_PATCH=${builtins.elemAt version 2}
128− if [[ -n "${versionPre}" ]]; then
129− export CARGO_PKG_VERSION_PRE="${versionPre}"
130− fi
131−
132− BUILD=""
133− if [[ ! -z "${build}" ]] ; then
134− BUILD=${build}
135− elif [[ -e "build.rs" ]]; then
136− BUILD="build.rs"
137− fi
138− if [[ ! -z "$BUILD" ]] ; then
139− echo_build_heading "$BUILD" ${libName}
140− mkdir -p target/build/${crateName}
141− EXTRA_BUILD_FLAGS=""
142− if [ -e target/link_ ]; then
143− EXTRA_BUILD_FLAGS=$(cat target/link_)
144− fi
145− if [ -e target/link.build ]; then
146− EXTRA_BUILD_FLAGS="$EXTRA_BUILD_FLAGS $(cat target/link.build)"
147− fi
148− noisily rustc --crate-name build_script_build $BUILD --crate-type bin ${rustcOpts} \
149− ${crateFeatures} --out-dir target/build/${crateName} --emit=dep-info,link \
150− -L dependency=target/buildDeps ${buildDeps} --cap-lints allow $EXTRA_BUILD_FLAGS --color ${colors}
151−
152− mkdir -p target/build/${crateName}.out
153− export RUST_BACKTRACE=1
154− BUILD_OUT_DIR="-L $OUT_DIR"
155− mkdir -p $OUT_DIR
156− target/build/${crateName}/build_script_build > target/build/${crateName}.opt
157− set +e
158− EXTRA_BUILD=$(sed -n "s/^cargo:rustc-flags=\(.*\)/\1/p" target/build/${crateName}.opt | tr '\n' ' ' | sort -u)
159− EXTRA_FEATURES=$(sed -n "s/^cargo:rustc-cfg=\(.*\)/--cfg \1/p" target/build/${crateName}.opt | tr '\n' ' ')
160− EXTRA_LINK=$(sed -n "s/^cargo:rustc-link-lib=\(.*\)/\1/p" target/build/${crateName}.opt | tr '\n' ' ' | sort -u)
161− EXTRA_LINK_SEARCH=$(sed -n "s/^cargo:rustc-link-search=\(.*\)/\1/p" target/build/${crateName}.opt | tr '\n' ' ' | sort -u)
162−
163− for env in $(sed -n "s/^cargo:rustc-env=\(.*\)/\1/p" target/build/${crateName}.opt); do
164− export $env
165− done
166−
167− CRATENAME=$(echo ${crateName} | sed -e "s/\(.*\)-sys$/\U\1/")
168− grep -P "^cargo:(?!(rustc-|warning=|rerun-if-changed=|rerun-if-env-changed))" target/build/${crateName}.opt \
169− | sed -e "s/cargo:\([^=]*\)=\(.*\)/export DEP_$(echo $CRATENAME)_\U\1\E=\2/" > target/env
170−
171− set -e
172− if [[ -n "$(ls target/build/${crateName}.out)" ]]; then
173−
174− if [[ -e "${libPath}" ]]; then
175− cp -r target/build/${crateName}.out/* $(dirname ${libPath}) #*/
176− else
177− cp -r target/build/${crateName}.out/* src #*/
178− fi
179− fi
180− fi
181− runHook postConfigure
182− '';
183−
184− buildCrate = { crateName,
185− dependencies,
186− crateFeatures, libName, release, libPath,
187− crateType, metadata, crateBin, finalBins,
188− extraRustcOpts, verbose, colors }:
189−
190− let deps = makeDeps dependencies;
191− rustcOpts =
192− lib.lists.foldl' (opts: opt: opts + " " + opt)
193− (if release then "-C opt-level=3" else "-C debuginfo=2")
194− (["-C codegen-units=1"] ++ extraRustcOpts);
195− rustcMeta = "-C metadata=${metadata} -C extra-filename=-${metadata}";
196− in ''
197− runHook preBuild
198− norm=""
199− bold=""
200− green=""
201− boldgreen=""
202− if [[ "${colors}" == "always" ]]; then
203− norm="$(printf '\033[0m')" #returns to "normal"
204− bold="$(printf '\033[0;1m')" #set bold
205− green="$(printf '\033[0;32m')" #set green
206− boldgreen="$(printf '\033[0;1;32m')" #set bold, and set green.
207− fi
208− ${echo_build_heading colors}
209− ${noisily colors verbose}
210−
211− build_lib() {
212− lib_src=$1
213− echo_build_heading $lib_src ${libName}
214−
215− noisily rustc --crate-name $CRATE_NAME $lib_src --crate-type ${crateType} \
216− ${rustcOpts} ${rustcMeta} ${crateFeatures} --out-dir target/lib \
217− --emit=dep-info,link -L dependency=target/deps ${deps} --cap-lints allow \
218− $BUILD_OUT_DIR $EXTRA_BUILD $EXTRA_FEATURES --color ${colors}
219−
220− EXTRA_LIB=" --extern $CRATE_NAME=target/lib/lib$CRATE_NAME-${metadata}.rlib"
221− if [ -e target/deps/lib$CRATE_NAME-${metadata}${stdenv.hostPlatform.extensions.sharedLibrary} ]; then
222− EXTRA_LIB="$EXTRA_LIB --extern $CRATE_NAME=target/lib/lib$CRATE_NAME-${metadata}${stdenv.hostPlatform.extensions.sharedLibrary}"
223− fi
224− }
225−
226− build_bin() {
227− crate_name=$1
228− crate_name_=$(echo $crate_name | sed -e "s/-/_/g")
229− main_file=""
230− if [[ ! -z $2 ]]; then
231− main_file=$2
232− fi
233− echo_build_heading $@
234− noisily rustc --crate-name $crate_name_ $main_file --crate-type bin ${rustcOpts}\
235− ${crateFeatures} --out-dir target/bin --emit=dep-info,link -L dependency=target/deps \
236− $LINK ${deps}$EXTRA_LIB --cap-lints allow \
237− $BUILD_OUT_DIR $EXTRA_BUILD $EXTRA_FEATURES --color ${colors}
238− if [ "$crate_name_" != "$crate_name" ]; then
239− mv target/bin/$crate_name_ target/bin/$crate_name
240− fi
241− }
242−
243−
244− EXTRA_LIB=""
245− CRATE_NAME=$(echo ${libName} | sed -e "s/-/_/g")
246−
247− if [[ -e target/link_ ]]; then
248− EXTRA_BUILD="$(cat target/link_) $EXTRA_BUILD"
249− fi
250−
251− if [[ -e "${libPath}" ]]; then
252− build_lib ${libPath}
253− elif [[ -e src/lib.rs ]]; then
254− build_lib src/lib.rs
255− elif [[ -e src/${libName}.rs ]]; then
256− build_lib src/${libName}.rs
257− fi
258−
259− echo "$EXTRA_LINK_SEARCH" | while read i; do
260− if [[ ! -z "$i" ]]; then
261− for lib in $i; do
262− echo "-L $lib" >> target/link
263− L=$(echo $lib | sed -e "s#$(pwd)/target/build#$out/lib#")
264− echo "-L $L" >> target/link.final
265− done
266− fi
267− done
268− echo "$EXTRA_LINK" | while read i; do
269− if [[ ! -z "$i" ]]; then
270− for lib in $i; do
271− echo "-l $lib" >> target/link
272− echo "-l $lib" >> target/link.final
273− done
274− fi
275− done
276−
277− if [[ -e target/link ]]; then
278− sort -u target/link.final > target/link.final.sorted
279− mv target/link.final.sorted target/link.final
280− sort -u target/link > target/link.sorted
281− mv target/link.sorted target/link
282−
283− tr '\n' ' ' < target/link > target/link_
284− LINK=$(cat target/link_)
285− fi
286−
287− mkdir -p target/bin
288− printf "%s\n" "${crateBin}" | head -n1 | tr -s ',' '\n' | while read -r BIN_NAME BIN_PATH; do
289− # filter empty entries / empty "lines"
290− if [[ -z "$BIN_NAME" ]]; then
291− continue
292− fi
293−
294− if [[ -z "$BIN_PATH" ]]; then
295− # heuristic to "guess" the correct source file as found in cargo:
296− # https://github.com/rust-lang/cargo/blob/90fc9f620190d5fa3c80b0c8c65a1e1361e6b8ae/src/cargo/util/toml/targets.rs#L308-L325
297−
298− # the first two cases are the "new" default IIRC
299− BIN_NAME_=$(echo $BIN_NAME | sed -e 's/-/_/g')
300− FILES="src/bin/$BIN_NAME_.rs src/bin/$BIN_NAME_/main.rs src/bin/main.rs src/main.rs"
301−
302− if ! [ -e "${libPath}" -o -e src/lib.rs -o -e "src/${libName}.rs" ]; then
303− # if this is not a library the following path is also valid
304− FILES="src/$BIN_NAME_.rs $FILES"
305− fi
306−
307− echo $FILES
308− for file in $FILES;
309− do
310− echo "checking file $file"
311− # first file that exists wins
312− if [[ -e "$file" ]]; then
313− BIN_PATH="$file"
314− break
315− fi
316− done
317−
318− if [[ -z "$BIN_PATH" ]]; then
319− echo "failed to find file for binary target: $BIN_NAME" >&2
320− exit 1
321− fi
322− fi
323− build_bin $BIN_NAME $BIN_PATH
324− done
325−
326−
327− ${lib.optionalString (crateBin == "") ''
328− if [[ -e src/main.rs ]]; then
329− build_bin ${crateName} src/main.rs
330− fi
331− for i in src/bin/*.rs; do #*/
332− build_bin "$(basename $i .rs)" "$i"
333− done
334− ''}
335− # Remove object files to avoid "wrong ELF type"
336− find target -type f -name "*.o" -print0 | xargs -0 rm -f
337− '' + finalBins + ''
338− runHook postBuild
339− '';
340−
341− installCrate = crateName: metadata: ''
342− runHook preInstall
343− mkdir -p $out
344− if [[ -s target/env ]]; then
345− cp target/env $out/env
346− fi
347− if [[ -s target/link.final ]]; then
348− mkdir -p $out/lib
349− cp target/link.final $out/lib/link
350− fi
351− if [[ "$(ls -A target/lib)" ]]; then
352− mkdir -p $out/lib
353− cp target/lib/* $out/lib #*/
354− for lib in $out/lib/*.so $out/lib/*.dylib; do #*/
355− ln -s $lib $(echo $lib | sed -e "s/-${metadata}//")
356− done
357− fi
358− if [[ "$(ls -A target/build)" ]]; then # */
359− mkdir -p $out/lib
360− cp -r target/build/* $out/lib # */
361− fi
362− if [[ "$(ls -A target/bin)" ]]; then
363− mkdir -p $out/bin
364− cp -P target/bin/* $out/bin # */
365− fi
366− runHook postInstall
367− '';
368−in
369−
370−crate_: lib.makeOverridable ({ rust, release, verbose, features, buildInputs, crateOverrides,
371− dependencies, buildDependencies,
372− extraRustcOpts,
373− preUnpack, postUnpack, prePatch, patches, postPatch,
374− preConfigure, postConfigure, preBuild, postBuild, preInstall, postInstall }:
375−
376−let crate = crate_ // (lib.attrByPath [ crate_.crateName ] (attr: {}) crateOverrides crate_);
377− dependencies_ = dependencies;
378− buildDependencies_ = buildDependencies;
379− processedAttrs = [
380− "src" "buildInputs" "crateBin" "crateLib" "libName" "libPath"
381− "buildDependencies" "dependencies" "features"
382− "crateName" "version" "build" "authors" "colors"
383− ];
384− extraDerivationAttrs = lib.filterAttrs (n: v: ! lib.elem n processedAttrs) crate;
385− buildInputs_ = buildInputs;
386−in
387−stdenv.mkDerivation (rec {
388−
389− inherit (crate) crateName;
390− inherit preUnpack postUnpack prePatch patches postPatch preConfigure postConfigure preBuild postBuild preInstall postInstall;
391−
392− src = if lib.hasAttr "src" crate then
393− crate.src
394− else
395− fetchCrate { inherit (crate) crateName version sha256; };
396− name = "rust_${crate.crateName}-${crate.version}";
397− buildInputs = [ rust ncurses ] ++ (crate.buildInputs or []) ++ buildInputs_;
398− dependencies =
399− builtins.map
400− (dep: dep.override { rust = rust; release = release; verbose = verbose; crateOverrides = crateOverrides; })
401− dependencies_;
402−
403− buildDependencies =
404− builtins.map
405− (dep: dep.override { rust = rust; release = release; verbose = verbose; crateOverrides = crateOverrides; })
406− buildDependencies_;
407−
408− completeDeps = lib.lists.unique (dependencies ++ lib.lists.concatMap (dep: dep.completeDeps) dependencies);
409− completeBuildDeps = lib.lists.unique (
410− buildDependencies
411− ++ lib.lists.concatMap (dep: dep.completeBuildDeps ++ dep.completeDeps) buildDependencies
412− );
413−
414− crateFeatures = if crate ? features then
415− lib.concatMapStringsSep " " (f: "--cfg feature=\\\"${f}\\\"") (crate.features ++ features) #"
416− else "";
417−
418− libName = if crate ? libName then crate.libName else crate.crateName;
419− libPath = if crate ? libPath then crate.libPath else "";
420−
421− depsMetadata = builtins.foldl' (str: dep: str + dep.metadata) "" (dependencies ++ buildDependencies);
422− metadata = builtins.substring 0 10 (builtins.hashString "sha256" (crateName + "-" + crateVersion + "___" + toString crateFeatures + "___" + depsMetadata ));
423−
424− crateBin = if crate ? crateBin then
425− builtins.foldl' (bins: bin: let
426− _name = (if bin ? name then bin.name else crateName);
427− name = lib.strings.replaceStrings ["-"] ["_"] _name;
428− path = if bin ? path then bin.path else "";
429− in
430− bins + (if bin == "" then "" else ",") + "${name} ${path}"
431−
432− ) "" crate.crateBin
433− else "";
434−
435− finalBins = if crate ? crateBin then
436− builtins.foldl' (bins: bin:
437− let name = lib.strings.replaceStrings ["-"] ["_"]
438− (if bin ? name then bin.name else crateName);
439− new_name = if bin ? name then bin.name else crateName;
440− in
441− if name == new_name then bins else
442− (bins + "mv target/bin/${name} target/bin/${new_name};")
443−
444− ) "" crate.crateBin
445− else "";
446−
447− build = crate.build or "";
448− workspace_member = crate.workspace_member or ".";
449− crateVersion = crate.version;
450− crateAuthors = if crate ? authors && lib.isList crate.authors then crate.authors else [];
451− crateType =
452− if lib.attrByPath ["procMacro"] false crate then "proc-macro" else
453− if lib.attrByPath ["plugin"] false crate then "dylib" else
454− (crate.type or "lib");
455− colors = lib.attrByPath [ "colors" ] "always" crate;
456− extraLinkFlags = builtins.concatStringsSep " " (crate.extraLinkFlags or []);
457− configurePhase = configureCrate {
458− inherit crateName buildDependencies completeDeps completeBuildDeps
459− crateFeatures libName build workspace_member release libPath crateVersion
460− extraLinkFlags
461− crateAuthors verbose colors;
462− };
463− extraRustcOpts = if crate ? extraRustcOpts then crate.extraRustcOpts else [];
464− buildPhase = buildCrate {
465− inherit crateName dependencies
466− crateFeatures libName release libPath crateType
467− metadata crateBin finalBins verbose colors
468− extraRustcOpts;
469− };
470− installPhase = installCrate crateName metadata;
471−
472−} // extraDerivationAttrs
473−)) {
474− rust = rustc;
475− release = crate_.release or true;
476− verbose = crate_.verbose or true;
477− extraRustcOpts = [];
478− features = [];
479− buildInputs = [];
480− crateOverrides = defaultCrateOverrides;
481− preUnpack = crate_.preUnpack or "";
482− postUnpack = crate_.postUnpack or "";
483− prePatch = crate_.prePatch or "";
484− patches = crate_.patches or [];
485− postPatch = crate_.postPatch or "";
486− preConfigure = crate_.preConfigure or "";
487− postConfigure = crate_.postConfigure or "";
488− preBuild = crate_.preBuild or "";
489− postBuild = crate_.postBuild or "";
490− preInstall = crate_.preInstall or "";
491− postInstall = crate_.postInstall or "";
492− dependencies = crate_.dependencies or [];
493− buildDependencies = crate_.buildDependencies or [];
494−}