aboutsummaryrefslogtreecommitdiffstats
path: root/rust/fatcat-cli/src/entities.rs
blob: 907061c0f12281a0f8a65edf1e45f4c474ecca97 (plain)
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

use std::str::FromStr;
use anyhow::{Result, anyhow, Context};
use lazy_static::lazy_static;
use regex::Regex;
use toml;
use serde_json;
use serde;
use fatcat_openapi::models;
use crate::Specifier;


#[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) {
            // XXX: Some() vs None for value
            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 trait ApiModelSer {
    fn to_json_string(&self) -> Result<String>;
    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_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; },
                (field, _) => unimplemented!("setting field {} on a release", field),
            }
        }
        Ok(())
    }
}

impl ApiModelMutate for models::ContainerEntity {
    fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<()> {
        unimplemented!("mutations")
    }
}

impl ApiModelMutate for models::CreatorEntity {
    fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<()> {
        unimplemented!("mutations")
    }
}

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<()> {
        unimplemented!("mutations")
    }
}

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<()> {
        unimplemented!("mutations")
    }
}

impl ApiModelMutate for models::Editgroup {
    fn mutate(&mut self, mutations: Vec<Mutation>) -> Result<()> {
        unimplemented!("mutations")
    }
}

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()) });
    }

}