quilt-rs 0.9.1

Rust library for accessing Quilt data packages.
Documentation
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
use quilt_rs::lineage::CommitState;
use quilt_rs::uri::Namespace;

use crate::cli::model::Commands;
use crate::cli::output::Std;
use crate::cli::Error;

#[derive(Clone, Debug)]
pub struct Input {
    pub message: String,
    pub namespace: Namespace,
    pub user_meta: Option<quilt_rs::manifest::JsonObject>,
    pub workflow: Option<String>,
}

#[derive(Debug)]
pub struct Output {
    pub commit: CommitState,
}

impl std::fmt::Display for Output {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, r##"New commit "{}" created"##, self.commit.hash)
    }
}

pub async fn command(m: impl Commands, args: Input) -> Std {
    match m.commit(args).await {
        Ok(output) => Std::Out(output.to_string()),
        Err(err) => Std::Err(err),
    }
}

async fn commit_package(
    local_domain: &quilt_rs::LocalDomain,
    namespace: Namespace,
    message: String,
    user_meta: Option<quilt_rs::manifest::JsonObject>,
    workflow_id: Option<String>,
) -> Result<CommitState, Error> {
    match local_domain.get_installed_package(&namespace).await? {
        Some(installed_package) => {
            let workflow = installed_package.resolve_workflow(workflow_id).await?;
            Ok(installed_package
                .commit(message, user_meta, workflow)
                .await?)
        }
        None => Err(Error::NamespaceNotFound(namespace)),
    }
}

pub async fn model(
    local_domain: &quilt_rs::LocalDomain,
    Input {
        message,
        namespace,
        user_meta,
        workflow,
    }: Input,
) -> Result<Output, Error> {
    let commit = commit_package(local_domain, namespace, message, user_meta, workflow).await?;
    Ok(Output { commit })
}

#[cfg(test)]
mod tests {
    use super::*;

    use std::path::PathBuf;

    use test_log::test;

    use crate::cli::model::install_package_into_temp_dir;

    use quilt_rs::io::storage::LocalStorage;
    use quilt_rs::io::storage::Storage;

    /// Verify the commit of that package:
    ///  * workflow/config.yml exists
    ///  * workflow id is not set
    ///  * no files to commit,
    #[test(tokio::test)]
    async fn test_commit_package_with_message_and_null_workflow() -> Result<(), Error> {
        use crate::cli::fixtures::packages::workflow_null as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        {
            let local_domain = m.get_local_domain();

            let output = model(
                local_domain,
                Input {
                    message: pkg::MESSAGE.to_string(),
                    namespace: pkg::NAMESPACE.into(),
                    user_meta: None,
                    workflow: None,
                },
            )
            .await?;

            assert_eq!(output.commit.hash, pkg::TOP_HASH);
        }

        Ok(())
    }

    #[test(tokio::test)]
    async fn test_commit_package_with_workflow_and_meta() -> Result<(), Error> {
        use crate::cli::fixtures::packages::my_workflow as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        {
            let local_domain = m.get_local_domain();

            let output = model(
                local_domain,
                Input {
                    message: pkg::MESSAGE.to_string(),
                    namespace: pkg::NAMESPACE.into(),
                    user_meta: Some(
                        serde_json::json!({
                            "Date": "2025-12-31",
                            "Name": "Foo",
                            "Owner": "Kevin",
                            "Type": "NGS"
                        })
                        .as_object()
                        .unwrap()
                        .clone(),
                    ),
                    workflow: Some("my-workflow".to_string()),
                },
            )
            .await?;

            assert_eq!(output.commit.hash, pkg::TOP_HASH);
        }

        Ok(())
    }

    /// Verify the commit of that package:
    ///  * workflow/config.yml DOESN'T exists
    ///  * workflow id is not set
    ///  * no files to commit,
    #[test(tokio::test)]
    async fn test_commit_package_with_message_only() -> Result<(), Error> {
        use crate::cli::fixtures::packages::no_workflows_message_only as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        {
            let local_domain = m.get_local_domain();

            let output = model(
                local_domain,
                Input {
                    message: pkg::MESSAGE.to_string(),
                    namespace: pkg::NAMESPACE.into(),
                    user_meta: None,
                    workflow: None,
                },
            )
            .await?;

            assert_eq!(output.commit.hash, pkg::TOP_HASH);
        }

        Ok(())
    }

    #[test(tokio::test)]
    async fn test_throwing_error_when_workflow_set_but_no_workflows_config() -> Result<(), Error> {
        use crate::cli::fixtures::packages::no_workflows_message_only as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        {
            let local_domain = m.get_local_domain();

            let output = model(
                local_domain,
                Input {
                    message: pkg::MESSAGE.to_string(),
                    namespace: pkg::NAMESPACE.into(),
                    user_meta: None,
                    workflow: Some("Anything".to_string()),
                },
            )
            .await;

            assert_eq!(
                output.unwrap_err().to_string(),
                r#"quilt_rs error: Workflow error: There is no workflows config, but the workflow "Anything" is set"#
            );
        }

        Ok(())
    }

    #[test(tokio::test)]
    async fn test_commit_package_with_meta_only() -> Result<(), Error> {
        use crate::cli::fixtures::packages::no_workflows_with_meta as pkg;

        let uri = pkg::URI;
        let (m, _installed_package, _tempdir) = install_package_into_temp_dir(uri).await?;
        {
            let local_domain = m.get_local_domain();

            let output = model(
                local_domain,
                Input {
                    message: "Initial".to_string(),
                    namespace: pkg::NAMESPACE.into(),
                    user_meta: Some(
                        serde_json::json!({
                            // NOTE: will be sorted
                            "C": "D",
                            "c": "d",
                            "a": "b",
                            "A": "B",
                            "e": 123,
                            "f": null
                        })
                        .as_object()
                        .unwrap()
                        .clone(),
                    ),
                    workflow: None,
                },
            )
            .await?;

            assert_eq!(output.commit.hash, pkg::TOP_HASH);
        }

        Ok(())
    }

    #[test(tokio::test)]
    async fn test_model() -> Result<(), Error> {
        let uri = "quilt+s3://udp-spec#package=spec/quilt-rs@11c5f6dbd1bf1d8675c18aaaa963b2f0dced2f892c7406fa36c9cd17d3d31b73";

        // TODO: commit is not-modified when we commit the same file (timestamp.txt)
        // TODO: commit is modified when we modify a file (README.md)
        // let readme_logical_key = PathBuf::from("READ ME.md");
        let timestamp_logical_key = PathBuf::from("timestamp.txt");

        let (m, installed_package, _temp_dir) = install_package_into_temp_dir(uri).await?;

        let first_input = Input {
            message: "Test message".to_string(),
            namespace: ("spec", "quilt-rs").into(),
            user_meta: None,
            workflow: None,
        };
        let hash_for_initial_test_commit =
            "d6e62c3c43ddd30447d99eede1c7280c017b15cc716037b74af7bb5230fbb61a";

        {
            let local_domain = m.get_local_domain();

            let output = model(local_domain, first_input.clone())
                .await
                .expect("Failed to commit");

            assert_eq!(
                format!("{}", output),
                format!("New commit \"{}\" created", hash_for_initial_test_commit)
            );
        }

        {
            let local_domain = m.get_local_domain();
            let second_commit = model(local_domain, first_input)
                .await
                .expect("Failed to commit second commit which is identical to the first one");

            assert_eq!(second_commit.commit.hash, hash_for_initial_test_commit);
            assert_eq!(
                second_commit.commit.prev_hashes,
                vec![hash_for_initial_test_commit]
            );
        }

        {
            let local_domain = m.get_local_domain();
            let third_commit = model(
                local_domain,
                Input {
                    message: "New commit message".to_string(),
                    namespace: ("spec", "quilt-rs").into(),
                    user_meta: Some(
                        serde_json::json!({"key": "value"})
                            .as_object()
                            .unwrap()
                            .clone(),
                    ),
                    workflow: None,
                },
            )
            .await
            .expect("Failed to commit third commit different from the first one");

            assert_eq!(
                third_commit.commit.hash,
                "e2a86408670c7a33f78758d72166333e4a96b6aadbb3b03d25fd6e209dc6e0b3"
            );
            assert_eq!(
                third_commit.commit.prev_hashes,
                vec![hash_for_initial_test_commit, hash_for_initial_test_commit]
            );
        }

        {
            let local_domain = m.get_local_domain();
            let not_found = model(
                local_domain,
                Input {
                    message: "Anything".to_string(),
                    namespace: ("a", "b").into(),
                    user_meta: None,
                    workflow: None,
                },
            )
            .await;

            assert_eq!(not_found.unwrap_err().to_string(), "Package a/b not found");
        }

        let working_dir = installed_package.working_folder();
        let storage = LocalStorage::new();
        storage
            .write_file(working_dir.join(timestamp_logical_key), b"1697916638")
            .await
            .expect("Failed to write timestamp.txt to the installed package working directory");
        {
            let local_domain = m.get_local_domain();
            let commit_the_same_file = model(
                local_domain,
                Input {
                    message: "Test message".to_string(),
                    namespace: ("spec", "quilt-rs").into(),
                    user_meta: None,
                    workflow: None,
                },
            )
            .await
            .expect("Failed to commit the same file ensuring the commit hash will persist");
            assert_eq!(
                commit_the_same_file.commit.hash,
                hash_for_initial_test_commit
            );
        }

        Ok(())
    }

    /// Verifies that valid command returns correct output after committing a new version
    /// which is the same as the previous one because message and user_meta left the same.
    #[test(tokio::test)]
    async fn test_valid_command() -> Result<(), Error> {
        use crate::cli::fixtures::packages::workflow_null as pkg;

        let uri = pkg::URI;
        let (m, _, _temp_dir) = install_package_into_temp_dir(uri).await?;

        if let Std::Out(output) = command(
            m,
            Input {
                message: pkg::MESSAGE.to_string(),
                namespace: pkg::NAMESPACE.into(),
                user_meta: None,
                workflow: None,
            },
        )
        .await
        {
            assert_eq!(
                output,
                r#"New commit "095017e53f4c8e0a07c82e562d088aa0e0f7a9ecaf2dce74a7607fac9085e98f" created"#
            );
        } else {
            return Err(Error::Test("Failed to commit".to_string()));
        }

        Ok(())
    }

    /// Verifies that invalid command returns appropriate error when package is not installed
    #[test(tokio::test)]
    async fn test_invalid_command() -> Result<(), Error> {
        use crate::cli::fixtures::packages::workflow_null as pkg;

        let uri = pkg::URI;
        let (m, _, _) = install_package_into_temp_dir(uri).await?;

        if let Std::Err(error) = command(
            m,
            Input {
                message: "Any message".to_string(),
                namespace: ("in", "valid").into(),
                user_meta: None,
                workflow: None,
            },
        )
        .await
        {
            assert_eq!(error.to_string(), "Package in/valid not found");
        } else {
            return Err(Error::Test("Expected package not found error".to_string()));
        }

        Ok(())
    }
}