-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathmod.rs
More file actions
222 lines (193 loc) · 7.13 KB
/
mod.rs
File metadata and controls
222 lines (193 loc) · 7.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
use indoc::formatdoc;
use std::collections::{BTreeMap, BTreeSet};
use crate::nixpacks::plan::phase::{Phase, Phases};
pub mod pkg;
// This line is automatically updated.
// Last Modified: 2023-09-17 17:13:39 UTC+0000
// https://github.com/NixOS/nixpkgs/commit/5148520bfab61f99fd25fb9ff7bfbb50dad3c9db
pub const NIXPKGS_ARCHIVE: &str = "5148520bfab61f99fd25fb9ff7bfbb50dad3c9db";
// Version of the Nix archive that uses OpenSSL 1.1
pub const NIXPACKS_ARCHIVE_LEGACY_OPENSSL: &str = "a0b7e70db7a55088d3de0cc370a59f9fbcc906c3";
/// Contains all the data needed to generate a Nix expression file for installing Nix dependencies.
#[derive(Eq, PartialEq, Default, Debug, Clone)]
struct NixGroup {
archive: Option<String>,
pkgs: Vec<String>,
libs: Vec<String>,
overlays: Vec<String>,
files: Vec<String>,
}
/// Collect all Nix packages based on the nixpkgs revision they should be fetched from.
fn group_nix_packages_by_archive(phases: &[Phase]) -> Vec<NixGroup> {
let mut archive_to_packages: BTreeMap<Option<String>, NixGroup> = BTreeMap::new();
let groups = phases
.iter()
.filter(|phase| phase.uses_nix())
.map(|phase| NixGroup {
archive: phase.nixpkgs_archive.clone(),
pkgs: phase.nix_pkgs.clone().unwrap_or_default(),
libs: phase.nix_libs.clone().unwrap_or_default(),
overlays: phase.nix_overlays.clone().unwrap_or_default(),
files: phase.only_include_files.clone().unwrap_or_default(),
});
for g in groups {
match archive_to_packages.get_mut(&g.archive) {
Some(group) => {
group.pkgs.extend(g.pkgs);
group.libs.extend(g.libs);
group.overlays.extend(g.overlays);
group.files.extend(g.files);
}
None => {
archive_to_packages.insert(g.archive.clone(), g);
}
}
}
archive_to_packages
.values()
.map(std::clone::Clone::clone)
.collect()
}
/// Turn the Nix dependencies for each phase into a Nix expression that installs them.
pub fn create_nix_expressions_for_phases(phases: &Phases) -> BTreeMap<String, String> {
let archive_to_packages = group_nix_packages_by_archive(
&phases
.values()
.map(std::clone::Clone::clone)
.collect::<Vec<_>>(),
);
archive_to_packages
.iter()
.fold(BTreeMap::new(), |mut acc, g| {
acc.insert(nix_file_name(&g.archive), nix_expression_for_group(g));
acc
})
}
/// Generates the filenames for all the Nix expressions used to install Nix dependencies for each phase.
pub fn nix_file_names_for_phases(phases: &Phases) -> Vec<String> {
let archives = phases
.values()
.filter(|p| p.uses_nix())
.map(|p| p.nixpkgs_archive.clone())
.collect::<BTreeSet<_>>();
archives.iter().map(nix_file_name).collect()
}
/// Returns all the Nix expression files used to install Nix dependencies for each phase.
pub fn setup_files_for_phases(phases: &Phases) -> Vec<String> {
let groups = group_nix_packages_by_archive(
&phases
.values()
.map(std::clone::Clone::clone)
.collect::<Vec<_>>(),
);
groups.iter().fold(Vec::new(), |mut acc, g| {
acc.extend(g.files.clone());
acc
})
}
/// Generates the filename for each Nix expression file.
fn nix_file_name(archive: &Option<String>) -> String {
match archive {
Some(archive) => format!("nixpkgs-{archive}.nix"),
None => "nixpkgs.nix".to_string(),
}
}
/// Generates an expression that installs Nix packages in the container environment and makes them available in PATH.
fn nix_expression_for_group(group: &NixGroup) -> String {
let archive = group
.archive
.clone()
.unwrap_or_else(|| NIXPKGS_ARCHIVE.to_string());
let mut pkgs = group.pkgs.clone();
pkgs.sort();
let pkgs = pkgs.join(" ");
let mut libs = group.libs.clone();
libs.sort();
let libs = libs.join(" ");
let overlays_string = group
.overlays
.iter()
.map(|url| format!("(import (builtins.fetchTarball \"{url}\"))"))
.collect::<Vec<String>>()
.join("\n");
let pkg_import = format!(
"import (fetchTarball \"https://github.com/NixOS/nixpkgs/archive/{archive}.tar.gz\")"
);
// If the openssl library is added, set the OPENSSL_DIR and OPENSSL_LIB_DIR environment variables
// In the future, we will probably want a generic way for providers to set variables based off Nix package locations
let openssl_dirs =
if let Some(openssl_lib) = group.libs.iter().find(|lib| lib.contains("openssl")) {
formatdoc! {"
export OPENSSL_DIR=\"${{{openssl_lib}.dev}}\"
export OPENSSL_LIB_DIR=\"${{{openssl_lib}.out}}/lib\"
"}
} else {
String::new()
};
let name = format!("{archive}-env");
let nix_expression = formatdoc! {"
{{ }}:
let pkgs = {} {{ overlays = [ {} ]; }};
in with pkgs;
let
APPEND_LIBRARY_PATH = \"${{lib.makeLibraryPath [ {} ] }}\";
myLibraries = writeText \"libraries\" ''
export LD_LIBRARY_PATH=\"${{APPEND_LIBRARY_PATH}}:$LD_LIBRARY_PATH\"
{}
'';
in
buildEnv {{
name = \"{name}\";
paths = [
(runCommand \"{name}\" {{ }} ''
mkdir -p $out/etc/profile.d
cp ${{myLibraries}} $out/etc/profile.d/{name}.sh
'')
{}
];
}}
",
pkg_import,
overlays_string,
libs,
openssl_dirs,
pkgs,
name=name,
};
nix_expression
}
#[cfg(test)]
mod tests {
use super::{pkg::Pkg, *};
#[test]
fn test_group_nix_packages_by_archive() {
let mut setup1 = Phase::setup(Some(vec![Pkg::new("foo"), Pkg::new("bar")]));
setup1.add_pkgs_libs(vec!["lib1".to_string()]);
setup1.add_file_dependency("test-file".to_string());
let mut setup2 = Phase::setup(Some(vec![Pkg::new("hello"), Pkg::new("world")]));
setup2.nixpkgs_archive = Some("archive2".to_string());
let setup3 = Phase::setup(Some(vec![Pkg::new("baz")]));
let groups = group_nix_packages_by_archive(&vec![setup1, setup2, setup3]);
assert_eq!(groups.len(), 2);
assert_eq!(
groups[0],
NixGroup {
archive: None,
pkgs: vec!["foo".to_string(), "bar".to_string(), "baz".to_string()],
libs: vec!["lib1".to_string()],
overlays: vec![],
files: vec!["test-file".to_string()]
}
);
assert_eq!(
groups[1],
NixGroup {
archive: Some("archive2".to_string()),
pkgs: vec!["hello".to_string(), "world".to_string()],
libs: vec![],
overlays: vec![],
files: vec![]
}
);
}
}