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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
#![deny(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications
)]
use anyhow::{bail, Context, Result};
use chrono::naive::NaiveDate;
use glob::glob;
use indexmap::IndexMap;
use log::warn;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::str::FromStr;
#[derive(Debug)]
pub struct Repository {
path: PathBuf,
pub description: RootDescription,
}
impl Repository {
pub fn open<P: AsRef<Path>>(path: P) -> Result<Self> {
Ok(Repository {
path: path.as_ref().to_path_buf(),
description: RootDescription::load_from_file(
Self::initial_brevdash_toml_path(path),
)?,
})
}
pub fn create<P: AsRef<Path>>(
path: P,
description: RootDescription,
) -> Result<Self> {
let r = Repository {
path: path.as_ref().to_path_buf(),
description,
};
r.store_description()?;
Ok(r)
}
pub fn store_description(&self) -> Result<()> {
self.description.store_to_file(self.brevdash_toml_path())
}
fn initial_brevdash_toml_path<P: AsRef<Path>>(p: P) -> PathBuf {
p.as_ref().join("brevdash.toml")
}
fn project_dir_path(&self, project_id: &str) -> PathBuf {
self.path.join(project_id)
}
fn project_toml_file_path(&self, project_id: &str) -> PathBuf {
self.project_dir_path(project_id).join("project.toml")
}
fn project_datapoint_directory_path(
&self,
project_id: &str,
date: NaiveDate,
) -> PathBuf {
self.project_dir_path(project_id)
.join(date.format("%Y-%m-%d").to_string())
}
fn project_datapoint_toml_file_path(
&self,
project_id: &str,
date: NaiveDate,
) -> PathBuf {
self.project_datapoint_directory_path(project_id, date)
.join("datapoint.toml")
}
pub fn project_datapoint_artifacts_directory_path(
&self,
project_id: &str,
date: NaiveDate,
) -> PathBuf {
self.project_datapoint_directory_path(project_id, date)
.join("artifacts")
}
pub fn project_datapoint_characteristic_artifacts_directory_path(
&self,
project_id: &str,
date: NaiveDate,
characteristic_id: &str,
) -> PathBuf {
self.project_datapoint_artifacts_directory_path(project_id, date)
.join(characteristic_id)
}
pub fn project_datapoint_characteristic_artifact_path(
&self,
project_id: &str,
date: NaiveDate,
characteristic_id: &str,
artifact_relative_path: &Path,
) -> PathBuf {
self.project_datapoint_characteristic_artifacts_directory_path(
project_id,
date,
characteristic_id,
)
.join(artifact_relative_path)
}
fn brevdash_toml_path(&self) -> PathBuf {
self.path.join("brevdash.toml")
}
fn extract_project_id(
project_toml_file_path: &Path,
) -> Result<String> {
let project_path =
project_toml_file_path.parent().with_context(|| {
format!(
"Couldn't extract parent directory of {:?}",
project_toml_file_path
)
})?;
let project_path_name_raw =
project_path.file_name().with_context(|| {
format!(
"Couldn't extract directory name of {:?}",
project_path
)
})?;
Ok(project_path_name_raw
.to_str()
.with_context(|| {
format!(
"Couldn't get project directory name, \
possibly invalid UTF-8: {:?}",
project_path_name_raw
)
})?
.to_string())
}
pub fn load_project_ids(&self) -> Result<Vec<String>> {
let pattern = format!("{}/*/project.toml", self.path.as_str()?);
let mut ids = Vec::new();
for entry in glob(&pattern).with_context(|| {
format!("Failed to read glob pattern {:?}", pattern)
})? {
match entry {
Ok(path) => match Self::extract_project_id(&path) {
Ok(id) => ids.push(id),
Err(e) => warn!("{:?}", e),
},
Err(e) => warn!("{:?}", e),
}
}
Ok(ids)
}
pub fn has_project(&self, project_id: &str) -> bool {
self.project_toml_file_path(project_id).exists()
}
pub fn store_project_description(
&self,
project_id: &str,
description: &ProjectDescription,
) -> Result<()> {
let project_dir_path = self.project_dir_path(&project_id);
std::fs::create_dir_all(&project_dir_path).with_context(|| {
format!(
"Couldn't create project directory {:?}",
project_dir_path
)
})?;
description.store_to_file(self.project_toml_file_path(project_id))
}
pub fn load_project_description(
&self,
project_id: &str,
) -> Result<ProjectDescription> {
ProjectDescription::load_from_file(
&self.project_toml_file_path(project_id),
)
}
pub fn load_project_descriptions(
&self,
) -> Result<BTreeMap<String, ProjectDescription>> {
let mut descriptions = BTreeMap::new();
for project_id in self.load_project_ids()?.into_iter() {
let description =
self.load_project_description(&project_id)?;
descriptions.insert(project_id, description);
}
Ok(descriptions)
}
pub fn project_has_datapoint_date(
&self,
project_id: &str,
date: NaiveDate,
) -> bool {
self.project_datapoint_toml_file_path(project_id, date)
.exists()
}
pub fn load_project_datapoint_dates(
&self,
project_id: &str,
) -> Result<Vec<NaiveDate>> {
let pattern = format!(
"{}/[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/datapoint.toml",
self.project_dir_path(project_id).as_str()?
);
let mut dates = Vec::new();
for entry in glob(&pattern).with_context(|| {
format!("Failed to read glob pattern {:?}", pattern)
})? {
match entry {
Ok(path) => {
let full_date_path =
path.parent().with_context(|| {
format!(
"Couldn't get parent of file {:?}",
path
)
})?;
let date_raw =
full_date_path.file_name().with_context(|| {
format!(
"Couldn't get file name of {:?}",
full_date_path
)
})?;
let date_str = date_raw
.to_str()
.with_context(|| {
format!(
"Couldn't get file path string, \
possibly invalid UTF-8: {:?}",
path
)
})?
.to_string();
let date =
NaiveDate::parse_from_str(&date_str, "%Y-%m-%d")?;
dates.push(date);
}
Err(e) => {
warn!("{:?}", e);
}
}
}
Ok(dates)
}
pub fn store_project_datapoint(
&self,
project_id: &str,
date: NaiveDate,
datapoint: &DataPoint,
) -> Result<()> {
let project_toml_file_path =
self.project_toml_file_path(project_id);
if !project_toml_file_path.exists() {
bail!(
"Attempting to store datapoint for project \
{:?}, but no project.toml file is present",
project_id
);
}
let project_datapoint_directory_path =
self.project_datapoint_directory_path(project_id, date);
std::fs::create_dir_all(&project_datapoint_directory_path)
.with_context(|| {
format!(
"Couldn't create datapoint directory {:?}",
project_datapoint_directory_path
)
})?;
datapoint.store_to_file(
self.project_datapoint_toml_file_path(project_id, date),
)
}
pub fn load_project_datapoint(
&self,
project_id: &str,
date: NaiveDate,
) -> Result<DataPoint> {
DataPoint::load_from_file(
&self.project_datapoint_toml_file_path(project_id, date),
)
}
pub fn load_project_datapoints(
&self,
project_id: &str,
) -> Result<BTreeMap<NaiveDate, DataPoint>> {
let mut datapoints = BTreeMap::new();
for date in
self.load_project_datapoint_dates(project_id)?.into_iter()
{
let datapoint =
self.load_project_datapoint(project_id, date)?;
datapoints.insert(date, datapoint);
}
Ok(datapoints)
}
}
trait LoadFromFile: Sized {
fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self>;
}
impl<T: serde::de::DeserializeOwned> LoadFromFile for T {
fn load_from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
let path = path.as_ref();
let s = std::fs::read_to_string(path).with_context(|| {
format!("Couldn't open file {:?}", path.to_path_buf())
})?;
let t: T = toml::from_str(&s).with_context(|| {
format!("Couldn't read file: {:?}", path.to_path_buf())
})?;
Ok(t)
}
}
trait StoreToFile {
fn store_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()>;
}
impl<T: Serialize> StoreToFile for T {
fn store_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
let path = path.as_ref();
let s = toml::to_string(&self).with_context(|| {
format!(
"Couldn't serialize data for file {:?}",
path.to_path_buf()
)
})?;
std::fs::write(&path, s).with_context(|| {
format!("Couldn't write file {:?}", path.to_path_buf())
})?;
Ok(())
}
}
trait PathAsStr {
fn as_str(&self) -> Result<&str>;
}
impl<P: AsRef<Path>> PathAsStr for P {
fn as_str(&self) -> Result<&str> {
let p = self.as_ref();
p.to_str().with_context(|| {
format!("Couldn't get path, possibly invalid UTF-8: {:?}", p)
})
}
}
pub type DataPoint = BTreeMap<String, DataEntry>;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct DataEntry {
pub value: DataValue,
#[serde(
default = "Default::default",
skip_serializing_if = "Vec::is_empty"
)]
pub artifacts: Vec<PathBuf>,
}
#[derive(Copy, Clone, Debug, Serialize, Deserialize)]
#[serde(untagged)]
pub enum DataValue {
Boolean(bool),
Integer(i64),
}
impl FromStr for DataValue {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if let Ok(v) = s.parse::<bool>() {
Ok(DataValue::Boolean(v))
} else if let Ok(v) = s.parse::<i64>() {
Ok(DataValue::Integer(v))
} else {
bail!("Couldn't parse argument {:?}", s);
}
}
}
impl DataValue {
pub fn unwrap_boolean(&self) -> bool {
self.boolean().unwrap()
}
pub fn unwrap_integer(&self) -> i64 {
self.integer().unwrap()
}
pub fn boolean(&self) -> Option<bool> {
if let DataValue::Boolean(v) = *self {
Some(v)
} else {
None
}
}
pub fn integer(&self) -> Option<i64> {
if let DataValue::Integer(v) = *self {
Some(v)
} else {
None
}
}
pub fn datatype(&self) -> DataType {
match self {
DataValue::Integer(_) => DataType::Integer,
DataValue::Boolean(_) => DataType::Boolean,
}
}
}
#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum DataType {
Boolean,
Integer,
}
impl FromStr for DataType {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"boolean" => Ok(DataType::Boolean),
"integer" => Ok(DataType::Integer),
s => bail!("Couldn't parse argument {:?}", s),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CharacteristicDescription {
pub datatype: DataType,
pub name: String,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct RootDescription {
pub name: String,
pub characteristics: IndexMap<String, CharacteristicDescription>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ProjectDescription {
pub name: String,
#[serde(
default = "Default::default",
skip_serializing_if = "String::is_empty"
)]
pub description: String,
#[serde(
default = "Default::default",
skip_serializing_if = "String::is_empty"
)]
pub website: String,
#[serde(
default = "Default::default",
skip_serializing_if = "String::is_empty"
)]
pub vcs: String,
}