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
//! An [Automaat] processor to print a string output.
//!
//! Using this crate in your Automaat workflow allows you to return the string
//! provided to the processor's configuration.
//!
//! On its own, this is not very useful, but combined with an application like
//! [Automaat Server], you can allow pipelines to configure this processor on
//! runtime, and relay the output to the end-user.
//!
//! [Automaat]: automaat_core
//! [Automaat Server]: https://docs.rs/automaat-server
//!
//! # Examples
//!
//! Configure the processor with a string, and capture that same value as the
//! output of the processor.
//!
//! This processor is infallible (see [`Void`]), so unwrapping the returned
//! value **will never panic**.
//!
//! ```rust
//! # fn main() -> Result<(), Box<std::error::Error>> {
//! use automaat_core::{Context, Processor};
//! use automaat_processor_print_output::PrintOutput;
//!
//! let context = Context::new()?;
//! let hello = "hello world".to_owned();
//!
//! let processor = PrintOutput {
//!   output: hello.clone(),
//! };
//!
//! let output = processor.run(&context).unwrap();
//!
//! assert_eq!(output, Some(hello));
//! #     Ok(())
//! # }
//! ```
//!
//! # Package Features
//!
//! * `juniper` – creates a set of objects to be used in GraphQL-based
//!   requests/responses.
#![deny(
    clippy::all,
    clippy::cargo,
    clippy::nursery,
    clippy::pedantic,
    deprecated_in_future,
    future_incompatible,
    missing_docs,
    nonstandard_style,
    rust_2018_idioms,
    rustdoc,
    warnings,
    unused_results,
    unused_qualifications,
    unused_lifetimes,
    unused_import_braces,
    unsafe_code,
    unreachable_pub,
    trivial_casts,
    trivial_numeric_casts,
    missing_debug_implementations,
    missing_copy_implementations
)]
#![warn(variant_size_differences)]
#![allow(clippy::multiple_crate_versions, missing_doc_code_examples)]
#![doc(html_root_url = "https://docs.rs/automaat-processor-print-output/0.1.0")]

use automaat_core::{Context, Processor};
use serde::{Deserialize, Serialize};
use std::{error, fmt};

/// The processor configuration.
#[cfg_attr(feature = "juniper", derive(juniper::GraphQLObject))]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PrintOutput {
    /// The string that is returned by the processor when [`PrintOutput#run`] is
    /// called.
    pub output: String,
}

/// The GraphQL [Input Object][io] used to initialize the processor via an API.
///
/// [`PrintOutput`] implements `From<Input>`, so you can directly initialize the
/// processor using this type.
///
/// _requires the `juniper` package feature to be enabled_
///
/// [io]: https://graphql.github.io/graphql-spec/June2018/#sec-Input-Objects
#[cfg(feature = "juniper")]
#[cfg_attr(feature = "juniper", derive(juniper::GraphQLInputObject))]
#[graphql(name = "PrintOutputInput")]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct Input {
    output: String,
}

#[cfg(feature = "juniper")]
impl From<Input> for PrintOutput {
    fn from(input: Input) -> Self {
        Self {
            output: input.output,
        }
    }
}

impl<'a> Processor<'a> for PrintOutput {
    const NAME: &'static str = "Print Output";

    type Error = Void;
    type Output = String;

    /// Print the output as defined by the processor configuration.
    ///
    /// The repository will be cloned in the [`Context`]
    /// workspace, optionally in a child `path`.
    ///
    /// # Output
    ///
    /// If the input value is an empty string (`""`), this processor returns
    /// `None`. In all other cases, `Some` is returned, containing the
    /// [`PrintOutput::output`] value.
    ///
    /// # Errors
    ///
    /// This processor is infallible, it will never return the error variant of
    /// the result.
    ///
    /// **Calling [`Result::unwrap`] on the returned value will never panic**.
    ///
    /// [`Context`]: automaat_core::Context
    fn run(&self, _context: &Context) -> Result<Option<Self::Output>, Self::Error> {
        let output = match self.output.as_ref() {
            "" => None,
            string => Some(string.to_owned()),
        };

        Ok(output)
    }
}

/// This is an enum without a variant, and can therefor never exist as a value
/// on runtime. This is also known as an _uninhabited type_, it statically
/// proofs that [`Processor::run`] and [`Processor::validate`] are infallible
/// for [`PrintOutput`].
///
/// Read more about this pattern [in this blog post][b].
///
/// [b]: https://smallcultfollowing.com/babysteps/blog/2018/08/13/never-patterns-exhaustive-matching-and-uninhabited-types-oh-my/
#[derive(Clone, Copy, Debug)]
#[allow(clippy::empty_enum)]
pub enum Void {}

impl fmt::Display for Void {
    fn fmt(&self, _: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {}
    }
}

impl error::Error for Void {
    fn cause(&self) -> Option<&dyn error::Error> {
        match *self {}
    }
}

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

    mod run {
        use super::*;

        #[test]
        fn empty_output() {
            let processor = PrintOutput {
                output: "".to_owned(),
            };

            let context = Context::new().unwrap();
            let output = processor.run(&context).unwrap();

            assert!(output.is_none())
        }

        #[test]
        fn string_output() {
            let processor = PrintOutput {
                output: "hello".to_owned(),
            };

            let context = Context::new().unwrap();
            let output = processor.run(&context).unwrap();

            assert_eq!(output, Some("hello".to_owned()))
        }
    }

    mod validate {
        use super::*;

        #[test]
        fn empty_output() {
            let processor = PrintOutput {
                output: "".to_owned(),
            };

            processor.validate().unwrap()
        }

        #[test]
        fn string_output() {
            let processor = PrintOutput {
                output: "hello".to_owned(),
            };

            processor.validate().unwrap()
        }
    }

    #[test]
    fn test_readme_deps() {
        version_sync::assert_markdown_deps_updated!("README.md");
    }

    #[test]
    fn test_html_root_url() {
        version_sync::assert_html_root_url_updated!("src/lib.rs");
    }
}