-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathnew.rs
329 lines (314 loc) · 12 KB
/
new.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
// SPDX-FileCopyrightText: 2023 Joep Meindertsma <[email protected]>
//
// SPDX-License-Identifier: MIT
//! Creating a new resource. Provides prompting logic
use crate::{CLIResult, Context};
use atomic_lib::mapping;
use atomic_lib::{
datatype::DataType,
errors::AtomicResult,
schema::{Class, Property},
Resource, Storelike, Value,
};
use colored::Colorize;
use promptly::prompt_opt;
use regex::Regex;
use std::time::{SystemTime, UNIX_EPOCH};
/// Create a new instance of some class through a series of prompts, adds it to the store
pub fn new(context: &mut Context) -> AtomicResult<()> {
let class_input = context
.matches
.subcommand_matches("new")
.unwrap()
.get_one::<&str>("class")
.expect("Add a class value");
let class_url = context
.mapping
.lock()
.unwrap()
.try_mapping_or_url(class_input)
.unwrap();
let class = context.store.get_class(&class_url)?;
println!("Enter a new {}: {}", class.shortname, class.description);
let (resource, _bookmark) = prompt_instance(context, &class, None)?;
println!(
"Succesfully created a new {}: subject: {}",
class.shortname,
resource.get_subject()
);
Ok(())
}
/// Lets the user enter an instance of an Atomic Class through multiple prompts.
/// Adds the Resource to the store, and writes to disk.
/// Returns the Resource, its URL and its Bookmark.
fn prompt_instance(
context: &Context,
class: &Class,
preferred_shortname: Option<String>,
) -> CLIResult<(Resource, Option<String>)> {
// Not sure about the best way t
// The Path is the thing at the end of the URL, from the domain
// Here I set some (kind of) random numbers.
// I think URL generation could be better, though. Perhaps use a
let path = SystemTime::now().duration_since(UNIX_EPOCH)?.subsec_nanos();
let write_ctx = context.get_write_context();
let mut subject = format!("{}/{}", write_ctx.server, path);
if let Some(sn) = &preferred_shortname {
subject = format!("{}/{}-{}", write_ctx.server, path, sn);
}
let mut new_resource: Resource = Resource::new(subject.clone());
new_resource.set_propval(
"https://atomicdata.dev/properties/isA".into(),
Value::from(vec![class.subject.clone()]),
&context.store,
)?;
for prop_subject in &class.requires {
let field = context.store.get_property(prop_subject)?;
if field.subject == atomic_lib::urls::SHORTNAME && preferred_shortname.clone().is_some() {
new_resource.set_propval_string(
field.subject.clone(),
&preferred_shortname.clone().unwrap(),
&context.store,
)?;
println!(
"Shortname set to {}",
preferred_shortname.clone().unwrap().bold().green()
);
continue;
}
println!("{}: {}", field.shortname.bold().blue(), field.description);
// In multiple Properties, the shortname field is required.
// A preferred shortname can be passed into this function
let mut input = prompt_field(&field, false, context)?;
loop {
if let Some(i) = input {
new_resource.set_propval_string(field.subject.clone(), &i, &context.store)?;
break;
} else {
println!("Required field, please enter a value.");
input = prompt_field(&field, false, context)?;
}
}
}
for prop_subject in &class.recommends {
let field = context.store.get_property(prop_subject)?;
println!("{}: {}", field.shortname.bold().blue(), field.description);
let input = prompt_field(&field, true, context)?;
if let Some(i) = input {
new_resource.set_propval_string(field.subject.clone(), &i, &context.store)?;
}
}
new_resource.save(&context.store)?;
println!("{} created with URL: {}", &class.shortname, &subject);
let map = prompt_bookmark(&mut context.mapping.lock().unwrap(), &subject);
context
.mapping
.lock()
.unwrap()
.write_mapping_to_disk(&context.user_mapping_path);
Ok((new_resource, map))
}
// Checks the property and its datatype, and issues a prompt that performs validation.
fn prompt_field(
property: &Property,
optional: bool,
context: &Context,
) -> CLIResult<Option<String>> {
let mut input: Option<String> = None;
let msg_appendix: &str = if optional {
" (optional)"
} else {
" (required)"
};
match &property.data_type {
DataType::String | DataType::Markdown => {
let msg = format!("string{}", msg_appendix);
input = prompt_opt(msg)?;
return Ok(input);
}
DataType::Slug => {
let msg = format!("slug{}", msg_appendix);
input = prompt_opt(msg)?;
let re = Regex::new(atomic_lib::values::SLUG_REGEX)?;
match input {
Some(slug) => {
if re.is_match(&slug) {
return Ok(Some(slug));
}
println!("Only letters, numbers and dashes - no spaces or special characters.");
return Ok(None);
}
None => return Ok(None),
}
}
DataType::Integer => {
let msg = format!("integer{}", msg_appendix);
let number: Option<u32> = prompt_opt(msg)?;
match number {
Some(nr) => {
input = Some(nr.to_string());
}
None => return Ok(None),
}
}
DataType::Float => {
let msg = format!("float{}", msg_appendix);
let number: Option<f64> = prompt_opt(msg)?;
match number {
Some(nr) => {
input = Some(nr.to_string());
}
None => return Ok(None),
}
}
DataType::Date => {
let msg = format!("date YYYY-MM-DD{}", msg_appendix);
let date: Option<String> = prompt_opt(msg).unwrap();
let re = Regex::new(atomic_lib::values::DATE_REGEX).unwrap();
match date {
Some(date_val) => {
if re.is_match(&date_val) {
input = Some(date_val);
return Ok(input);
}
println!("Not a valid date.");
return Ok(None);
}
None => return Ok(None),
}
}
DataType::AtomicUrl => loop {
let msg = format!("URL{}", msg_appendix);
let classtype = &property.class_type;
if classtype.is_some() {
let class = context
.store
.get_class(&String::from(classtype.as_ref().unwrap()))?;
println!(
"Enter the URL of a {} (an instance of a {})",
class.shortname, class.subject
)
}
let url: Option<String> = prompt_opt(msg).unwrap();
// If a classtype is present, the given URL must be an instance of that Class
if let Some(u) = url {
// TODO: Check if string or if map
input = context.mapping.lock().unwrap().try_mapping_or_url(&u);
match input {
Some(url) => return Ok(Some(url)),
None => {
println!("Shortname not found, try again.");
return Ok(None);
}
}
}
},
DataType::ResourceArray => loop {
let msg = format!(
"resource array - Add the URLs or Shortnames, separated by spacebars{}",
msg_appendix
);
let option_string: Option<String> = prompt_opt(msg).unwrap();
match option_string {
Some(string) => {
let string_items = string.split(' ');
let mut urls: Vec<String> = Vec::new();
let length = string_items.clone().count();
for item in string_items {
let mapping_match = context
.mapping
.lock()
.unwrap()
.try_mapping_or_url(item)
.clone();
match mapping_match {
Some(url) => {
urls.push(url);
}
None => {
let class = &context.store.get_class(&property.class_type.clone().expect("At this moment, this CLI only supports Properties that have a class-type."))?.clone();
println!(
"Define the {} named {}",
class.shortname,
item.bold().green(),
);
let (resource, _shortname) =
prompt_instance(context, class, Some(item.into()))?;
urls.push(resource.get_subject().clone());
continue;
}
}
}
if length == urls.len() {
input = Some(atomic_lib::serialize::serialize_json_array(&urls).unwrap());
break;
}
}
None => break,
}
},
DataType::Timestamp => {
let msg = format!("timestamp{}", msg_appendix);
let number: Option<u64> = prompt_opt(msg)?;
match number {
Some(nr) => {
input = Some(nr.to_string());
}
None => return Ok(None),
}
}
DataType::Unsupported(unsup) => {
let msg = format!(
"unsupported datatype {}, defaulting to string{}",
unsup, msg_appendix
);
let string: Option<String> = prompt_opt(msg)?;
match string {
Some(nr) => {
input = Some(nr);
}
None => return Ok(None),
}
}
DataType::Boolean => {
let msg = format!("boolean{}", msg_appendix);
let number: Option<bool> = prompt_opt(msg)?;
match number {
Some(nr) => {
if nr {
return Ok(Some("true".to_string()));
}
return Ok(Some("false".to_string()));
}
None => return Ok(None),
}
}
};
Ok(input)
}
// Asks for and saves the bookmark. Returns the shortname.
fn prompt_bookmark(mapping: &mut mapping::Mapping, subject: &str) -> Option<String> {
let re = Regex::new(atomic_lib::values::SLUG_REGEX).unwrap();
let mut shortname: Option<String> = prompt_opt("Local Bookmark (optional)").unwrap();
loop {
match shortname.as_ref() {
Some(sn) => {
if mapping.contains_key(sn) {
let msg = format!(
"You're already using that shortname for {:?}, try something else",
mapping.get(sn).unwrap()
);
shortname = prompt_opt(msg).unwrap();
} else if re.is_match(sn.as_str()) {
mapping.insert(sn.into(), subject.into());
return Some(String::from(sn));
} else {
shortname =
prompt_opt("Not a valid bookmark, only use letters, numbers, and '-'")
.unwrap();
}
}
None => return None,
}
}
}