wasmer_cli/commands/journal/
import.rs

1use std::{io::ErrorKind, path::PathBuf};
2
3use clap::Parser;
4use wasmer_wasix::journal::{JournalEntry, LogFileJournal, WritableJournal};
5
6use crate::commands::CliCommand;
7
8/// Imports events into a journal file. Events are streamed as JSON
9/// objects into `stdin`
10#[derive(Debug, Parser)]
11pub struct CmdJournalImport {
12    /// Path to the journal that will be printed
13    #[clap(index = 1)]
14    journal_path: PathBuf,
15}
16
17impl CliCommand for CmdJournalImport {
18    type Output = ();
19
20    fn run(self) -> Result<(), anyhow::Error> {
21        // Erase the journal file at the path and reopen it
22        if self.journal_path.exists() {
23            std::fs::remove_file(&self.journal_path)?;
24        }
25        let journal = LogFileJournal::new(self.journal_path)?;
26
27        // Read all the events from `stdin`, deserialize them and save them to the journal
28        let stdin = std::io::stdin();
29        let mut lines = String::new();
30        let mut line = String::new();
31        loop {
32            // Read until the end marker
33            loop {
34                line.clear();
35                match stdin.read_line(&mut line) {
36                    Ok(0) => return Ok(()),
37                    Ok(_) => {
38                        lines.push_str(&line);
39                        if line.trim_end() == "}" {
40                            break;
41                        }
42                    }
43                    Err(err) if err.kind() == ErrorKind::UnexpectedEof => return Ok(()),
44                    Err(err) => return Err(err.into()),
45                }
46            }
47
48            let record = serde_json::from_str::<JournalEntry<'static>>(&lines)?;
49            println!("{record}");
50            journal.write(record)?;
51            lines.clear();
52        }
53    }
54}