-
Notifications
You must be signed in to change notification settings - Fork 3
/
mod.rs
1663 lines (1484 loc) · 52.9 KB
/
mod.rs
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
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
extern crate slog;
extern crate slog_term;
use slog::*;
use std::collections::HashMap;
use std::fs::{self};
use std::io::{self};
use std::path::Path;
extern crate regex;
use regex::Regex;
use walkdir::{DirEntry, WalkDir};
extern crate adr_config;
use adr_config::config::AdrToolConfig;
use chrono::prelude::*;
fn get_logger() -> slog::Logger {
let cfg: AdrToolConfig = adr_config::config::get_config();
let decorator = slog_term::TermDecorator::new().build();
let drain = slog_term::FullFormat::new(decorator).build().fuse();
let drain = slog_async::Async::new(drain).build().fuse();
let drain = slog::LevelFilter::new(
drain,
Level::from_usize(cfg.log_level).unwrap_or(Level::Debug),
)
.fuse();
slog::Logger::root(drain, o!())
}
/// Creates the file (based on template file). Returns true if file is created, false if not (e.g. target file already exists...)
///
/// # Arguments
///
/// * `cfg` - The whole config object
/// * `title`- the title of the ADR (specified by the user)
/// *
///
pub fn create_adr(cfg: AdrToolConfig, path: Option<&str>, title: &str) -> io::Result<bool> {
let adr_template_dir = &cfg.adr_template_dir.as_str();
let adr_template_file = &cfg.adr_template_file.as_str();
let path_to_template = Path::new(adr_template_dir);
let path_to_template = path_to_template.join(adr_template_file);
let path_to_template = path_to_template.as_path();
let src_dir = Path::new(&cfg.adr_src_dir);
//specify last seq_id , the rest of the config (use_prefix and width can be get from the method)
let name = match format_decision_name(cfg.clone(), title) {
Ok(name) => name,
Err(_why) => panic!("Problem while formatting name [{}]", title),
};
let target_path = match path {
None => src_dir.join(format!("{}.adoc", name)),
Some(val) => {
std::fs::create_dir_all(src_dir.join(val)).unwrap();
src_dir.join(val).join(format!("{}.adoc", name))
}
};
let is_target_file = target_path.is_file();
if !is_target_file {
if path_to_template.exists() {
match fs::copy(path_to_template, &target_path) {
Ok(_val) => debug!(
get_logger(),
"Copy template file from [{:?}] to [{:?}]", &path_to_template, &target_path
),
Err(_why) => error!(
get_logger(),
"Unable to copy template from [{:?}] to [{:?}]",
&path_to_template,
&target_path
),
};
//build the Adr (and force the parsing)
let mut new_adr = match build_adr(Path::new(&cfg.adr_src_dir), &target_path) {
Ok(adr) => adr,
Err(why) => {
error!(
get_logger(),
"Got error [{:?}] while getting ADR [{:?}]", why, target_path
);
panic!();
}
};
new_adr.update_title(title);
debug!(get_logger(), "Want to create ADR {:?}", &target_path);
match fs::write(&target_path, new_adr.content) {
Ok(_val) => info!(get_logger(), "New ADR [{:?}] created", target_path),
Err(why) => {
error!(
get_logger(),
"Unable to create ADR [{:?}] - error [{:?}]", target_path, why
);
}
};
//
} else {
error!(
get_logger(),
"[{}] was not found",
path_to_template.to_string_lossy()
);
}
} else {
error!(
get_logger(),
"Decision already exists. Please use another name",
);
}
Ok(!is_target_file)
}
fn get_seq_id_from_name(name: &str) -> Result<usize> {
lazy_static! {
static ref RE: Regex = Regex::new(r"^(\d+)-{1}").unwrap();
}
let mut id: usize = 0;
if let Some(cap) = RE.captures(name) {
debug!(get_logger(), "found first match [{}]", cap[1].to_string());
id = cap[1].to_string().parse().unwrap();
} else {
debug!(get_logger(), "Unable to extract_seq_id from [{}]", name);
}
Ok(id)
}
fn get_last_seq_id(adrs: Vec<Adr>) -> usize {
match get_seq_id_from_name(&adrs[adrs.len() - 1].file_name) {
Ok(val) => {
val
},
Err(why) => {
error!(get_logger(), "got the following issue {:?}", why);
0
}
}
}
fn sort_by_id(mut adrs: Vec<Adr>) -> Vec<Adr> {
adrs.sort_by(|a, b| a.file_id.cmp(&b.file_id));
adrs
}
fn format_decision_name(cfg: AdrToolConfig, name: &str) -> Result<String> {
let mut prefix = String::new();
if cfg.use_id_prefix {
let adr_vec = list_all_adr(Path::new(cfg.adr_src_dir.as_str())).unwrap();
let last_seq_id = get_last_seq_id(adr_vec);
prefix = format!("{:0>width$}-", last_seq_id + 1, width = cfg.id_prefix_width); //"{:0width$}", x, width = width
debug!(get_logger(), "got seq number [{}]", prefix);
}
let name = name.to_ascii_lowercase();
let name = name.replace(" ", "-");
let name = format!("{}{}", prefix, name);
Ok(name.to_string())
}
fn is_ok(entry: &DirEntry) -> bool {
let metadata = entry.metadata().unwrap();
let is_dir = metadata.is_dir();
let is_hidden = entry
.file_name()
.to_str()
.map(|s| s.starts_with("."))
.unwrap_or(false);
let is_adoc = entry
.file_name()
.to_str()
.map(|s| s.ends_with(".adoc"))
.unwrap_or(false);
(is_dir && !is_hidden) || (is_adoc && !is_hidden)
}
pub fn get_tags_popularity(base_path: &Path) -> Result<HashMap<String, u32>> {
let mut popularity: HashMap<String, u32> = HashMap::new();
for adr in list_all_adr(base_path)? {
for tag in adr.tags_array.iter() {
popularity
.entry(tag.to_string())
.and_modify(|e| *e += 1)
.or_insert(1);
}
}
Ok(popularity)
}
pub fn list_all_adr(dir: &Path) -> io::Result<Vec<Adr>> {
let mut results = std::vec::Vec::new();
if dir.is_dir() {
let walker = WalkDir::new(dir).follow_links(true).into_iter();
for entry in walker.filter_entry(|e| is_ok(e)) {
let entry = entry?;
debug!(get_logger(), "got file [{:?}]", entry.path());
let metadata = entry.metadata().unwrap();
if metadata.is_file() {
match build_adr(dir, entry.path()) {
Ok(adr) => {
results.push(adr);
}
Err(_why) => {
debug!(get_logger(), "Unable to read file [{:?}]", entry.path());
}
};
}
}
}
results = sort_by_id(results);
Ok(results)
}
/// Given a complete `full_path` to a file, returns the difference compared to `base_path`.
///
/// # Arguments
///
/// * `base_path` - The root directory where are all the ADRs. This is typically AdrToolConfig.adr_root_dir
/// * `file_path` - The full path of the file
///
/// # Example
///
/// ```
/// use adr_core::adr_repo::split_path;
///
/// let adr = split_path(std::path::Path::new("/tmp/adrs/"), std::path::Path::new("/tmp/adrs/my-sub-dir/my-decision.adoc"));
/// assert_eq!(adr.0, std::path::Path::new("/tmp/adrs/"));
/// assert_eq!(adr.1, std::path::Path::new("my-sub-dir/my-decision.adoc"));
/// ```
///
pub fn split_path<'a>(base_path: &'a Path, full_path: &'a Path) -> (&'a Path, &'a Path) {
debug!(
get_logger(),
"Want to split_path[{:?}] and [{:?}] ", base_path, full_path
);
match full_path.starts_with(base_path) {
true => (
base_path,
full_path.strip_prefix(base_path).unwrap_or(full_path),
),
false => (base_path, full_path),
}
}
/// Build an ADR object given the provided arguments. Inside the ADR struct `full_path` will be splitted into `file_path` and `base_path`
///
/// # Arguments
///
/// * `base_path` - The root directory where are all the ADRs. This is typically AdrToolConfig.adr_root_dir
/// * `file_path` - The full path of the file
///
/// # Example
///
/// ```
/// use adr_core::adr_repo::build_adr;
/// let adr = build_adr(std::path::Path::new("/tmp/adrs/"), std::path::Path::new("/tmp/adrs/my-sub-dir/my-decision.adoc"));
/// ```
pub fn build_adr(base_path: &Path, full_path: &Path) -> io::Result<Adr> {
debug!(
get_logger(),
"Want to create ADR from [{}] ",
full_path.display()
);
let content = fs::read_to_string(full_path)?;
//build the adr
let splitted_file_path = split_path(base_path, full_path);
let adr = Adr::from(
String::from(splitted_file_path.0.to_str().unwrap()),
String::from(splitted_file_path.1.to_str().unwrap()),
content,
);
Ok(adr)
}
pub fn transition_to_decided(base_path: &Path, file_path: &str) -> io::Result<bool> {
transition_to(TransitionStatus::DECIDED, base_path, file_path, "")
}
pub fn transition_to_superseded_by(
base_path: &Path,
file_path: &str,
by: &str,
) -> io::Result<bool> {
transition_to(TransitionStatus::SUPERSEDED, base_path, file_path, by)
}
pub fn transition_to_completed_by(base_path: &Path, file_path: &str, by: &str) -> io::Result<bool> {
transition_to(TransitionStatus::COMPLETED, base_path, file_path, by)
}
pub fn transition_to_obsoleted(base_path: &Path, file_path: &str) -> io::Result<bool> {
transition_to(TransitionStatus::CANCELLED, base_path, file_path, "")
}
pub fn transition_to(
transition: TransitionStatus,
base_path: &Path,
from_path: &str,
by_path: &str,
) -> io::Result<bool> {
let mut from_adr = match build_adr(base_path, Path::new(from_path)) {
Ok(adr) => adr,
Err(why) => {
error!(
get_logger(),
"Got error [{:?}] while getting ADR [{}]", why, from_path
);
panic!();
}
};
let from_old_status = from_adr.status.as_str();
//if transition has been declined, we can stop here
match from_adr.update_status(transition) {
true => {
debug!(
get_logger(),
"ADR [{}] has a new status [{}]",
from_adr.path().as_str(),
from_adr.status.as_str()
);
let transition_adr = |adr: &Adr, path: &str, old_status: &str| -> io::Result<bool> {
match fs::write(path, &adr.content) {
Ok(_) => {
info!(
get_logger(),
"Transitioned [{}] from [{}] to [{}]",
adr.path().as_str(),
old_status,
adr.status.as_str()
);
Ok(true)
}
Err(_) => Ok(false),
}
};
match by_path.is_empty() {
true => transition_adr(&from_adr, from_path, from_old_status),
false => {
let mut by_adr = build_adr(base_path, Path::new(by_path))?;
let by_old_status = by_adr.status.as_str();
//if transition has been declined, we can stop here
match by_adr.update_status(TransitionStatus::revert(transition)) {
true => {
from_adr.add_reference(format!("{}", by_adr.file_name).as_str());
by_adr.add_reference(format!("{}", from_adr.file_name).as_str());
Ok(transition_adr(&from_adr, from_path, from_old_status)?
== transition_adr(&by_adr, by_path, by_old_status)?)
}
false => {
error!(get_logger(), "ADR [{}] cannot be transitioned to [{:?}] - Status of [{:?}] is not [{:?}]", from_path, transition, by_path, TransitionStatus::DECIDED);
Ok(false)
}
}
}
}
}
false => {
error!(
get_logger(),
"ADR [{}] cannot be transitioned to [{:?}]", from_path, transition
);
Ok(false)
}
}
}
#[derive(Debug, Default)]
pub struct Adr {
//pub path: String, //the path from config.adr_root_dir (which is user dependant)
pub file_id: usize,
pub file_name: String,
pub file_path: String,
pub base_path: String,
pub content: String,
pub title: String,
pub date: String,
pub status: Status,
pub state: AdrState,
pub tags: String,
pub tags_array: Vec<String>,
}
impl Adr {
fn new() -> Adr {
Adr {
file_id: 0,
file_name: String::new(),
file_path: String::new(),
base_path: String::new(),
content: String::new(),
title: String::new(),
date: String::new(),
status: Status::default(),
state: AdrState::default(),
tags: String::new(),
tags_array: Vec::new(),
}
}
pub fn from(base_path: String, file_path: String, content: String) -> Adr {
let mut adr = Adr::new();
lazy_static! {
static ref RE_TITLE: Regex = Regex::new(r"= (.+)").unwrap();
static ref RE_STATUS: Regex = Regex::new(r"\{(.+)\}").unwrap();
static ref RE_DATE: Regex = Regex::new(r"([0-9]{4}-[0-9]{2}-[0-9]{2})").unwrap();
}
//set file/path properties
adr.base_path = base_path;
adr.file_path = file_path;
adr.file_name = match Path::new(&adr.file_path)
.file_name()
.unwrap()
.to_os_string()
.into_string()
{
Ok(name) => name,
Err(err) => panic!("Unexpected Error: {:?}", err),
};
adr.file_id = get_seq_id_from_name(&adr.file_name).unwrap();
//set title/content
adr.content = content;
adr.title = match RE_TITLE.captures(&adr.content) {
Some(val) => val[1].to_string(),
None => {
error!(
get_logger(),
"Unable to get title from base_path [{}] and file_path [{}]",
adr.base_path,
adr.file_path
);
"None".to_string()
}
};
//set date
adr.date = match RE_DATE.captures(&adr.content) {
Some(val) => val[1].trim().to_string(),
None => {
debug!(
get_logger(),
"Unable to get date from base_path [{}] and file_path [{}]",
adr.base_path,
adr.file_path
);
"None".to_string()
}
};
//set tags/tags_array
let tags = Adr::get_tags(&adr.content);
adr.tags = tags.0;
adr.tags_array = tags.1;
//set status/state
adr.status = Status::from_str(match RE_STATUS.captures(&adr.content) {
Some(val) => val[1].trim().to_string(),
None => {
debug!(
get_logger(),
"Unable to get status from base_path [{}] and file_path [{}]",
adr.base_path,
adr.file_path
);
"None".to_string()
}
});
adr.state = AdrState {
status: adr.status.clone(),
};
adr
}
pub fn path(&self) -> String {
let full_path = Path::new(self.base_path.as_str()).join(self.file_path.as_str());
return format!("{}", full_path.display());
}
pub fn get_tags(val: &String) -> (String, Vec<String>) {
lazy_static! {
static ref RE_TAGS: Regex = Regex::new(r"(\[tags]\#([^#]+)\#)").unwrap();
}
let mut tags_str = String::from("");
for cap in RE_TAGS.captures_iter(val) {
use std::fmt::Write;
write!(tags_str, "#{} ", &cap[2]).unwrap();
}
let tags = tags_str
.split('#')
.filter(|s| s.len() > 0)
.map(|s| s.to_string())
.collect();
(tags_str, tags)
}
pub fn update_status(&mut self, transition: TransitionStatus) -> bool {
let current_status = format!("{{{status}}}", status = self.status.as_str()); //you escape { with a { and final status is {wip} o_O
let mut state = self.state;
let has_been_modified = state.transition(transition);
debug!(get_logger(), "Want transition [{:?}] - Adr State transitioned from [{:?}] to [{:?}] - has been modified [{:?}]", transition, self.state, state, has_been_modified);
if has_been_modified {
let new_status = format!("{{{status}}}", status = state.status.as_str());
debug!(get_logger(), "Transitioned to [{}]", state.status.as_str());
self.content = self
.content
.replace(current_status.as_str(), new_status.as_str());
self.status = state.status;
self.state = state;
self.update_date(Utc::now().date_naive());
has_been_modified
} else {
debug!(get_logger(), "Transition has been declined");
false
}
}
pub fn add_reference(&mut self, adr_title: &str) {
let current_status = format!("{{{status}}}", status = self.status.as_str()); //you escape { with a { and final status is {wip} o_O
let new_status = format!(
"{updated_by} {by}",
updated_by = current_status.as_str(),
by = adr_title
);
debug!(
get_logger(),
"Want to add reference - current status [{:?}] - new status [{:?}]",
current_status,
new_status
);
self.content = self
.content
.replace(current_status.as_str(), new_status.as_str());
}
pub fn update_date(&mut self, today: NaiveDate) {
let new_date = today.format("%Y-%m-%d").to_string();
debug!(get_logger(), "Want to update ADR to date [{}]", new_date);
self.date = new_date;
let re = Regex::new(r"(\d{4})-(\d{2})-(\d{2})").unwrap();
self.content = re
.replace(self.content.as_str(), self.date.as_str())
.as_ref()
.to_owned();
}
pub fn update_title(&mut self, title: &str) {
let new_title = "".to_owned() + title;
self.content = self
.content
.replacen(self.title.as_str(), new_title.as_str(), 1);
self.title = new_title;
}
}
impl Clone for Adr {
fn clone(&self) -> Adr {
Adr {
file_id: self.file_id.clone(),
file_name: String::from(self.file_name.as_str()),
file_path: String::from(self.file_path.as_str()),
base_path: String::from(self.base_path.as_str()),
content: String::from(self.content.as_str()),
title: String::from(self.title.as_str()),
date: String::from(self.date.as_str()),
tags: String::from(self.tags.as_str()),
tags_array: self.tags_array.clone(),
status: self.state.status.clone(),
state: self.state.clone(),
}
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum TransitionStatus {
DECIDED,
COMPLETED,
COMPLETES,
SUPERSEDED,
SUPERSEDES,
CANCELLED,
NONE,
}
impl TransitionStatus {
fn revert(transition: TransitionStatus) -> TransitionStatus {
match transition {
TransitionStatus::COMPLETED => TransitionStatus::COMPLETES,
TransitionStatus::COMPLETES => TransitionStatus::COMPLETED,
TransitionStatus::SUPERSEDED => TransitionStatus::SUPERSEDES,
TransitionStatus::SUPERSEDES => TransitionStatus::SUPERSEDED,
_ => transition,
}
}
pub fn as_str(&self) -> &'static str {
match *self {
TransitionStatus::DECIDED => "decided",
TransitionStatus::COMPLETED => "completed",
TransitionStatus::COMPLETES => "completes",
TransitionStatus::SUPERSEDED => "superseded",
TransitionStatus::SUPERSEDES => "supersedes",
TransitionStatus::CANCELLED => "cancelled",
_ => "none",
}
}
pub fn from_str(val: String) -> TransitionStatus {
match val.as_str() {
"decided" => TransitionStatus::DECIDED,
"completed" => TransitionStatus::COMPLETED,
"completes" => TransitionStatus::COMPLETES,
"superseded" => TransitionStatus::SUPERSEDED,
"supersedes" => TransitionStatus::SUPERSEDES,
"cancelled" => TransitionStatus::CANCELLED,
_ => TransitionStatus::NONE,
}
}
}
#[derive(Debug, PartialEq, Copy, Clone)]
pub enum Status {
WIP,
DECIDED,
COMPLETED,
COMPLETES,
SUPERSEDED,
SUPERSEDES,
CANCELLED,
NONE,
}
impl Default for Status {
fn default() -> Self {
Status::WIP
}
}
impl Status {
pub fn as_str(&self) -> &'static str {
match *self {
Status::WIP => "wip",
Status::DECIDED => "decided",
Status::COMPLETED => "completed",
Status::COMPLETES => "completes",
Status::SUPERSEDED => "superseded",
Status::SUPERSEDES => "supersedes",
Status::CANCELLED => "obsoleted",
Status::NONE => "unknown",
}
}
pub fn from_str(val: String) -> Status {
match val.as_str() {
"wip" => Status::WIP,
"decided" => Status::DECIDED,
"completed" => Status::COMPLETED,
"completes" => Status::COMPLETES,
"superseded" => Status::SUPERSEDED,
"supersedes" => Status::SUPERSEDES,
"obsoleted" => Status::CANCELLED,
_ => Status::NONE,
}
}
}
pub trait State {
fn transition(&mut self, transition: TransitionStatus) -> bool;
fn build(status: Status) -> AdrState;
}
#[derive(Debug, Copy, Clone)]
pub struct AdrState {
status: Status,
}
impl Default for AdrState {
fn default() -> Self {
AdrState {
status: Status::WIP,
}
}
}
impl State for AdrState {
fn transition(&mut self, transition: TransitionStatus) -> bool {
let current_state = self.status.as_str();
let current_status = &self.status;
let mut has_been_modified = true;
let next_status = match current_status {
Status::WIP => match transition {
TransitionStatus::DECIDED => {
self.status = Status::DECIDED;
Status::DECIDED
}
TransitionStatus::CANCELLED => {
self.status = Status::CANCELLED;
Status::CANCELLED
}
_ => {
has_been_modified = false;
Status::WIP
}
},
Status::DECIDED => match transition {
TransitionStatus::COMPLETED => {
self.status = Status::COMPLETED;
Status::COMPLETED
}
TransitionStatus::COMPLETES => {
self.status = Status::COMPLETES;
Status::COMPLETES
}
TransitionStatus::CANCELLED => {
self.status = Status::CANCELLED;
Status::CANCELLED
}
TransitionStatus::SUPERSEDED => {
self.status = Status::SUPERSEDED;
Status::SUPERSEDED
}
TransitionStatus::SUPERSEDES => {
self.status = Status::SUPERSEDES;
Status::SUPERSEDES
}
_ => {
has_been_modified = false;
Status::DECIDED
}
},
Status::COMPLETED => match transition {
TransitionStatus::SUPERSEDED => {
self.status = Status::SUPERSEDED;
Status::SUPERSEDED
}
TransitionStatus::CANCELLED => {
self.status = Status::CANCELLED;
Status::CANCELLED
}
_ => {
has_been_modified = false;
Status::COMPLETED
}
},
Status::COMPLETES => match transition {
TransitionStatus::CANCELLED => {
self.status = Status::CANCELLED;
Status::CANCELLED
}
TransitionStatus::SUPERSEDED => {
self.status = Status::SUPERSEDED;
Status::SUPERSEDED
}
_ => {
has_been_modified = false;
Status::COMPLETES
}
},
Status::SUPERSEDED => match transition {
TransitionStatus::CANCELLED => {
self.status = Status::CANCELLED;
Status::CANCELLED
}
_ => {
has_been_modified = false;
Status::SUPERSEDED
}
},
Status::SUPERSEDES => match transition {
TransitionStatus::CANCELLED => {
self.status = Status::CANCELLED;
Status::CANCELLED
}
_ => {
has_been_modified = false;
Status::SUPERSEDES
}
},
Status::CANCELLED => match transition {
_ => {
has_been_modified = false;
Status::CANCELLED
}
},
_ => {
has_been_modified = false;
Status::NONE
}
};
self.status = next_status;
debug!(
get_logger(),
"transition [{:?}] has been called from [{:?}] to [{:?}]",
transition,
current_state,
self.status
);
has_been_modified
}
fn build(status: Status) -> AdrState {
AdrState { status: status }
}
}
impl std::cmp::PartialEq for AdrState {
fn eq(&self, other: &Self) -> bool {
self.status == other.status
}
}
#[cfg(test)]
mod tests {
extern crate tempdir;
use std::path::PathBuf;
use tempdir::TempDir;
use crate::adr_repo::*;
const ADOC_TMPL_NOTAG: &str = ":docinfo1:
:wip: pass:quotes[[.label.wip]#In Progress#]
:decided: pass:q[[.label.decided]#Decided#]
:completed: pass:q[[.label.updated]#Completed By#]
:completes: pass:q[[.label.updated]#Completes#]
:supersedes: pass:q[[.label.updated]#Supersedes#]
:superseded: pass:q[[.label.obsoleted]#Superseded By#]
:obsoleted: pass:q[[.label.obsoleted]#Obsolete#]
= short title of solved problem and solution
*Status:* {decided} *Date:* 2019-10-28
...";
const ADOC_TMPL_TAG: &str = ":docinfo1:
:wip: pass:quotes[[.label.wip]#In Progress#]
:decided: pass:q[[.label.decided]#Decided#]
:completed: pass:q[[.label.updated]#Completed By#]
:completes: pass:q[[.label.updated]#Completes#]
:supersedes: pass:q[[.label.updated]#Supersedes#]
:superseded: pass:q[[.label.obsoleted]#Superseded By#]
:obsoleted: pass:q[[.label.obsoleted]#Obsolete#]
= short title of solved problem and solution
*Status:* {wip} *Date:* 2019-10-28
[tags]#tag1# [tags]#tag2# [tags]#tag3#
...";
#[test]
fn test_adr_update_status() {
let mut adr_sut = Adr::new();
adr_sut.file_name = String::from("/a");
adr_sut.base_path = String::from("/tmp/n");
adr_sut.file_path = String::from("/a");
adr_sut.content = String::from("== ADR-MVA-507 Decide about ...\n\n*Status:* {wip} *Date:* 2019-10-28\n\n[cols=\",\",options=...");
adr_sut.title = String::from("String::from(self.title.as_str())");
adr_sut.date = String::from("2023-10-28");
let update_true = adr_sut.update_status(TransitionStatus::DECIDED);
assert_eq!(adr_sut.status, Status::DECIDED);
assert_eq!(
adr_sut.state,
AdrState {
status: Status::DECIDED
}
);
assert_eq!(adr_sut.content.contains(Status::DECIDED.as_str()), true);
assert_eq!(update_true, true);
}
#[test]
fn test_adr_add_reference() {
let mut adr_sut = Adr::new();
adr_sut.file_name = String::from("/a");
adr_sut.base_path = String::from("/tmp/n");
adr_sut.file_path = String::from("/a");
adr_sut.content = String::from("== ADR-MVA-507 Decide about ...\n\n*Status:* {decided} *Date:* 2019-10-28\n\n[cols=\",\",options=...");
adr_sut.title = String::from("String::from(self.title.as_str())");
adr_sut.date = String::from("2023-10-28");
adr_sut.status = Status::DECIDED;
adr_sut.state = AdrState {
status: Status::DECIDED,
};
adr_sut.add_reference("by adr-num-123");
assert_eq!(adr_sut.status, Status::DECIDED);
assert_eq!(
adr_sut.state,
AdrState {
status: Status::DECIDED
}
);
let expected_status = "{decided} by adr-num-123 *Date:* 2019-10-28";
assert_eq!(adr_sut.content.contains(expected_status), true);
}
#[test]
fn test_state_machine() {
let mut state = super::AdrState::build(super::Status::WIP);
assert_eq!(
state,
super::AdrState {
status: super::Status::WIP
}
);
state.transition(super::TransitionStatus::COMPLETED);
assert_eq!(
state,
super::AdrState {
status: super::Status::WIP
}
);
state.transition(super::TransitionStatus::DECIDED);
assert_eq!(
state,
super::AdrState {
status: super::Status::DECIDED
}
);
state.transition(super::TransitionStatus::SUPERSEDED);
assert_eq!(
state,
super::AdrState {
status: super::Status::SUPERSEDED
}
);
state.transition(super::TransitionStatus::CANCELLED);
assert_eq!(
state,
super::AdrState {
status: super::Status::CANCELLED
}
);
}
#[test]
fn test_state_machine_2() {
let mut state = super::AdrState::build(super::Status::WIP);
assert_eq!(
state,
super::AdrState {
status: super::Status::WIP
}
);
state.transition(super::TransitionStatus::SUPERSEDED);
assert_eq!(
state,
super::AdrState {
status: super::Status::WIP
}
);
state.transition(super::TransitionStatus::DECIDED);
assert_eq!(
state,
super::AdrState {
status: super::Status::DECIDED
}
);