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
|
use crate::{EntityType, Specifier};
use anyhow::{anyhow, Context, Result};
use fatcat_openapi::models;
use lazy_static::lazy_static;
use log::{self, info};
use regex::Regex;
use std::io::{BufRead, Read};
use std::path::PathBuf;
use std::str::FromStr;
#[derive(Debug, PartialEq, Clone)]
pub struct Mutation {
field: String,
value: Option<String>,
}
impl FromStr for Mutation {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
// first try simple entity prefixes
lazy_static! {
static ref MUTATE_ENTITY_RE: Regex = Regex::new(r"^([a-z_]+)=(.*)$").unwrap();
}
if let Some(captures) = MUTATE_ENTITY_RE.captures(s) {
return Ok(Mutation {
field: captures[1].to_string(),
value: match &captures[2] {
"" => None,
val => Some(val.to_string()),
},
});
}
Err(anyhow!("not a field mutation: {}", s))
}
}
/*
* Goal is to have traits around API entities. Things we'll want to do on concrete entities:
*
* - print, or pretty-print, as JSON or TOML
* - get fcid (or, self-specifier)
* - update (mutate or return copy) fields based on parameters
* - update self to remote API
*
* Methods that might return trait objects:
*
* - get by specifier
*/
pub trait ApiEntityModel: ApiModelSer + ApiModelIdent + ApiModelMutate {}
impl ApiEntityModel for models::ReleaseEntity {}
impl ApiEntityModel for models::ContainerEntity {}
impl ApiEntityModel for models::CreatorEntity {}
impl ApiEntityModel for models::WorkEntity {}
impl ApiEntityModel for models::FileEntity {}
impl ApiEntityModel for models::FilesetEntity {}
impl ApiEntityModel for models::WebcaptureEntity {}
impl ApiEntityModel for models::Editor {}
impl ApiEntityModel for models::Editgroup {}
impl ApiEntityModel for models::ChangelogEntry {}
pub fn read_entity_file(input_path: Option<PathBuf>) -> Result<String> {
// treat "-" as "use stdin"
let input_path = match input_path {
Some(s) if s.to_string_lossy() == "-" => None,
_ => input_path,
};
match input_path {
None => {
let mut line = String::new();
std::io::stdin().read_line(&mut line)?;
Ok(line)
}
Some(path) if path.extension().map(|v| v.to_str()) == Some(Some("toml")) => {
info!("reading {:?} as TOML", path);
// as a hack, read TOML but then serialize it back to JSON
let mut contents = String::new();
let mut input_file =
std::fs::File::open(path).context("reading entity from TOML file")?;
input_file.read_to_string(&mut contents)?;
let value: toml::Value = contents.parse().context("parsing TOML file")?;
Ok(serde_json::to_string(&value)?)
}
Some(path) => {
let mut line = String::new();
let input_file = std::fs::File::open(path)?;
let mut buffered = std::io::BufReader::new(input_file);
buffered.read_line(&mut line)?;
Ok(line)
}
}
}
pub fn entity_model_from_json_str(
entity_type: EntityType,
json_str: &str,
) -> Result<Box<dyn ApiEntityModel>> {
match entity_type {
EntityType::Release => Ok(Box::new(serde_json::from_str::<models::ReleaseEntity>(
&json_str,
)?)),
EntityType::Work => Ok(Box::new(serde_json::from_str::<models::WorkEntity>(
&json_str,
)?)),
EntityType::Container => Ok(Box::new(serde_json::from_str::<models::ContainerEntity>(
&json_str,
)?)),
EntityType::Creator => Ok(Box::new(serde_json::from_str::<models::CreatorEntity>(
&json_str,
)?)),
EntityType::File => Ok(Box::new(serde_json::from_str::<models::FileEntity>(
&json_str,
)?)),
EntityType::FileSet => Ok(Box::new(serde_json::from_str::<models::FilesetEntity>(
&json_str,
)?)),
EntityType::WebCapture => Ok(Box::new(serde_json::from_str::<models::WebcaptureEntity>(
&json_str,
)?)),
}
}
pub trait ApiModelSer {
fn to_json_string(&self) -> Result<String>;
fn to_json_value(&self) -> Result<serde_json::Value>;
fn to_toml_string(&self) -> Result<String>;
}
impl<T: serde::Serialize> ApiModelSer for T {
fn to_json_string(&self) -> Result<String> {
Ok(serde_json::to_string(self)?)
}
fn to_json_value(&self) -> Result<serde_json::Value> {
Ok(serde_json::to_value(self)?)
}
fn to_toml_string(&self) -> Result<String> {
Ok(toml::Value::try_from(self)?.to_string())
}
}
pub trait ApiModelIdent {
fn specifier(&self) -> Specifier;
}
macro_rules! generic_entity_specifier {
($specifier_type:ident) => {
fn specifier(&self) -> Specifier {
if let Some(fcid) = &self.ident {
Specifier::$specifier_type(fcid.to_string())
} else {
panic!("expected full entity")
}
}
};
}
impl ApiModelIdent for models::ReleaseEntity {
generic_entity_specifier!(Release);
}
impl ApiModelIdent for models::ContainerEntity {
generic_entity_specifier!(Container);
}
impl ApiModelIdent for models::CreatorEntity {
generic_entity_specifier!(Creator);
}
impl ApiModelIdent for models::WorkEntity {
generic_entity_specifier!(Work);
}
impl ApiModelIdent for models::FileEntity {
generic_entity_specifier!(File);
}
impl ApiModelIdent for models::FilesetEntity {
generic_entity_specifier!(FileSet);
}
impl ApiModelIdent for models::WebcaptureEntity {
generic_entity_specifier!(WebCapture);
}
impl ApiModelIdent for models::ChangelogEntry {
fn specifier(&self) -> Specifier {
Specifier::Changelog(self.index)
}
}
impl ApiModelIdent for models::Editgroup {
fn specifier(&self) -> Specifier {
if let Some(fcid) = &self.editgroup_id {
Specifier::Editgroup(fcid.to_string())
} else {
panic!("expected full entity")
}
}
}
impl ApiModelIdent for models::Editor {
fn specifier(&self) -> Specifier {
if let Some(fcid) = &self.editor_id {
Specifier::Editor(fcid.to_string())
} else {
panic!("expected full entity")
}
}
}
pub trait ApiModelMutate {
fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<()>;
}
impl ApiModelMutate for models::ReleaseEntity {
fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<()> {
for m in mutations {
match (m.field.as_str(), m.value) {
("title", val) => {
self.title = val;
}
("subtitle", val) => {
self.subtitle = val;
}
("container_id", val) => {
self.container_id = val;
}
("work_id", val) => {
self.work_id = val;
}
("release_type", val) => {
self.release_type = val;
}
("release_stage", val) => {
self.release_stage = val;
}
("withdrawn_status", val) => {
self.withdrawn_status = val;
}
("license_slug", val) => {
self.license_slug = val;
}
("volume", val) => {
self.volume = val;
}
("issue", val) => {
self.issue = val;
}
("number", val) => {
self.number = val;
}
("publisher", val) => {
self.publisher = val;
}
("language", val) => {
self.language = val;
}
(field, _) => unimplemented!("setting field {} on a release", field),
}
}
Ok(())
}
}
impl ApiModelMutate for models::ContainerEntity {
fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<()> {
for m in mutations {
match (m.field.as_str(), m.value) {
("name", val) => {
self.name = val;
}
("container_type", val) => {
self.container_type = val;
}
("publisher", val) => {
self.publisher = val;
}
("issnl", val) => {
self.issnl = val;
}
(field, _) => unimplemented!("setting field {} on a container", field),
}
}
Ok(())
}
}
impl ApiModelMutate for models::CreatorEntity {
fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<()> {
for m in mutations {
match (m.field.as_str(), m.value) {
("display_name", val) => {
self.display_name = val;
}
("given_name", val) => {
self.given_name = val;
}
("surname", val) => {
self.surname = val;
}
(field, _) => unimplemented!("setting field {} on a creator", field),
}
}
Ok(())
}
}
impl ApiModelMutate for models::WorkEntity {
fn mutate(&mut self, _mutations: Vec<Mutation>) -> Result<()> {
unimplemented!("mutations")
}
}
impl ApiModelMutate for models::FileEntity {
fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<()> {
for m in mutations {
match (m.field.as_str(), m.value) {
("size", Some(val)) => {
self.size = Some(i64::from_str(&val)?);
}
("size", None) => {
self.size = None;
}
("md5", val) => {
self.md5 = val;
}
("sha1", val) => {
self.sha1 = val;
}
("sha256", val) => {
self.sha256 = val;
}
("mimetype", val) => {
self.mimetype = val;
}
(field, _) => unimplemented!("setting field {} on a file", field),
}
}
Ok(())
}
}
impl ApiModelMutate for models::FilesetEntity {
fn mutate(&mut self, _mutations: Vec<Mutation>) -> Result<()> {
unimplemented!("mutations")
}
}
impl ApiModelMutate for models::WebcaptureEntity {
fn mutate(&mut self, _mutations: Vec<Mutation>) -> Result<()> {
unimplemented!("mutations")
}
}
impl ApiModelMutate for models::Editor {
fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<()> {
for m in mutations {
match (m.field.as_str(), m.value) {
("username", Some(val)) => {
self.username = val;
}
(field, _) => unimplemented!("setting field {} on an editor", field),
}
}
Ok(())
}
}
impl ApiModelMutate for models::Editgroup {
fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<()> {
for m in mutations {
match (m.field.as_str(), m.value) {
("description", val) => {
self.description = val;
}
(field, _) => unimplemented!("setting field {} on an editgroup", field),
}
}
Ok(())
}
}
impl ApiModelMutate for models::ChangelogEntry {
fn mutate(&mut self, _mutations: Vec<Mutation>) -> Result<()> {
unimplemented!("mutations")
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mutation_from_str() -> () {
assert!(Mutation::from_str("release_asdf").is_err());
assert_eq!(
Mutation::from_str("title=blah").unwrap(),
Mutation {
field: "title".to_string(),
value: Some("blah".to_string())
}
);
assert_eq!(
Mutation::from_str("title=").unwrap(),
Mutation {
field: "title".to_string(),
value: None
}
);
assert_eq!(
Mutation::from_str("title=string with spaces and stuff").unwrap(),
Mutation {
field: "title".to_string(),
value: Some("string with spaces and stuff".to_string())
}
);
}
}
|