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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
use serde_json;
use chrono::UTC;
use rand;
use std::path::{Path, PathBuf};
use std::fs::File;
use std::io::prelude::*;
use std::collections::{HashMap, BTreeMap};
use std::collections::BTreeSet;
use std::fmt;
use super::{CliError, LalResult, input};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Container {
pub name: String,
pub tag: String,
}
impl Container {
pub fn latest(name: &str) -> Self {
Container {
name: name.into(),
tag: "latest".into(),
}
}
}
impl fmt::Display for Container {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}:{}", self.name, self.tag) }
}
impl Default for Container {
fn default() -> Self {
Container {
name: "ubuntu".into(),
tag: "xenial".into(),
}
}
}
impl Container {
pub fn new(container: &str) -> Container {
let split: Vec<&str> = container.split(':').collect();
let tag = if split.len() == 2 { split[1] } else { "latest" };
let cname = if split.len() == 2 { split[0] } else { container };
Container {
name: cname.into(),
tag: tag.into(),
}
}
}
#[allow(non_snake_case)]
#[derive(Serialize, Deserialize, Debug)]
pub struct Lockfile {
pub name: String,
pub config: String,
pub container: Container,
pub environment: String,
pub defaultEnv: Option<String>,
pub sha: Option<String>,
pub version: String,
pub tool: String,
pub built: Option<String>,
pub dependencies: BTreeMap<String, Lockfile>,
}
impl Default for Lockfile {
fn default() -> Self { Lockfile::new("templock", &Container::default(), "none", None, None) }
}
impl Lockfile {
pub fn new(
name: &str,
container: &Container,
env: &str,
v: Option<String>,
build_cfg: Option<&str>,
) -> Self {
let def_version = format!("EXPERIMENTAL-{:x}", rand::random::<u64>());
let time = UTC::now();
Lockfile {
name: name.to_string(),
version: v.unwrap_or(def_version),
config: build_cfg.unwrap_or("release").to_string(),
container: container.clone(),
tool: env!("CARGO_PKG_VERSION").to_string(),
built: Some(time.format("%Y-%m-%d %H:%M:%S").to_string()),
defaultEnv: Some(env.into()),
environment: env.into(),
dependencies: BTreeMap::new(),
sha: None,
}
}
pub fn from_path(lock_path: &PathBuf, name: &str) -> LalResult<Self> {
if !lock_path.exists() {
return Err(CliError::MissingLockfile(name.to_string()));
}
let mut lock_str = String::new();
File::open(lock_path)?.read_to_string(&mut lock_str)?;
Ok(serde_json::from_str(&lock_str)?)
}
pub fn release_build() -> LalResult<Self> {
let lpath = Path::new("ARTIFACT").join("lockfile.json");
Ok(Lockfile::from_path(&lpath, "release build")?)
}
fn from_input_component(component: &str) -> LalResult<Self> {
let lock_path = Path::new("./INPUT").join(component).join("lockfile.json");
Ok(Lockfile::from_path(&lock_path, component)?)
}
pub fn populate_from_input(mut self) -> LalResult<Self> {
debug!("Reading all lockfiles");
let deps = input::analyze()?;
for name in deps.keys() {
trace!("Populating lockfile with {}", name);
let deplock = Lockfile::from_input_component(name)?;
self.dependencies.insert(name.clone(), deplock);
}
Ok(self)
}
pub fn set_default_env(mut self, default: String) -> Self {
self.defaultEnv = Some(default);
self
}
pub fn attach_revision_id(mut self, sha: Option<String>) -> Self {
self.sha = sha;
self
}
pub fn set_name(mut self, name: &str) -> Self {
self.name = name.into();
self
}
pub fn write(&self, pth: &Path) -> LalResult<()> {
let encoded = serde_json::to_string_pretty(self)?;
let mut f = File::create(pth)?;
write!(f, "{}\n", encoded)?;
debug!("Wrote lockfile {}: \n{}", pth.display(), encoded);
Ok(())
}
}
pub type ValueUsage = HashMap<String, BTreeSet<String>>;
impl Lockfile {
fn get_value(&self, key: &str) -> String {
if key == "version" {
self.version.clone()
} else if key == "environment" {
self.environment.clone()
} else {
unreachable!("Only using get_value internally");
}
}
fn find_all_values(&self, key: &str) -> ValueUsage {
let mut acc = HashMap::new();
for (main_name, dep) in &self.dependencies {
if !acc.contains_key(main_name) {
acc.insert(main_name.clone(), BTreeSet::new());
}
{
let first_value_set = acc.get_mut(main_name).unwrap();
first_value_set.insert(dep.get_value(key));
}
trace!("Recursing into deps for {}, acc is {:?}", main_name, acc);
for (name, value_set) in dep.find_all_values(key) {
trace!("Found {} for for {} under {} as {:?}",
key,
name,
main_name,
value_set);
if !acc.contains_key(&name) {
acc.insert(name.clone(), BTreeSet::new());
}
let full_value_set = acc.get_mut(&name).unwrap();
for value in value_set {
full_value_set.insert(value);
}
}
}
acc
}
pub fn find_all_dependency_versions(&self) -> ValueUsage { self.find_all_values("version") }
pub fn find_all_environments(&self) -> ValueUsage { self.find_all_values("environment") }
pub fn find_all_dependency_names(&self) -> ValueUsage {
let mut acc = HashMap::new();
acc.entry(self.name.clone())
.or_insert_with(|| self.dependencies.keys().cloned().collect());
for dep in self.dependencies.values() {
for (n, d) in dep.find_all_dependency_names() {
acc.entry(n).or_insert(d);
}
}
acc
}
}
impl Lockfile {
pub fn get_reverse_deps(&self) -> ValueUsage {
let mut acc = HashMap::new();
if !acc.contains_key(&self.name) {
acc.insert(self.name.clone(), BTreeSet::new());
}
for (main_name, dep) in &self.dependencies {
if !acc.contains_key(&dep.name) {
acc.insert(dep.name.clone(), BTreeSet::new());
}
{
let first_value_set = acc.get_mut(&dep.name).unwrap();
first_value_set.insert(self.name.clone());
}
trace!("Recursing into deps for {}, acc is {:?}", main_name, acc);
for (name, value_set) in dep.get_reverse_deps() {
trace!("Found revdeps for {} as {:?}", name, value_set);
if !acc.contains_key(&name) {
acc.insert(name.clone(), BTreeSet::new());
}
let full_value_set = acc.get_mut(&name).unwrap();
for value in value_set {
full_value_set.insert(value);
}
}
}
acc
}
pub fn get_reverse_deps_transitively_for(&self, component: String) -> BTreeSet<String> {
let revdeps = self.get_reverse_deps();
trace!("Got rev deps: {:?}", revdeps);
let mut res = BTreeSet::new();
if !revdeps.contains_key(&component) {
warn!("Could not find {} in the dependency tree for {}",
component,
self.name);
return res;
}
let mut current_cycle = vec![component];
while !current_cycle.is_empty() {
let mut next_cycle = vec![];
for name in current_cycle {
for dep in &revdeps[&name] {
res.insert(dep.clone());
next_cycle.push(dep.clone());
}
}
current_cycle = next_cycle;
}
res
}
}