Skip to main content

libupdated_macros/
lib.rs

1// SPDX-License-Identifier: MIT
2// SPDX-FileCopyrightText: <text>
3// Copyright(c) 2026 Liebherr-Digital Development Center GmbH
4// Written by Thomas Witte <thomas.witte@liebherr.com>
5// </text>
6
7use proc_macro::TokenStream;
8use quote::quote;
9use syn::{ItemFn, parse_macro_input};
10
11/// Helper macro to register a workflow by name. Updated can select a registered workflow at run-time.
12/// Currently, you must force linkage to the crate that contains the workflow function by declaring `extern crate <your workflow crate>;`
13/// in updated's main.rs. Otherwise, the linker will skip the dependency as its symbols seem to be unused.
14#[proc_macro_attribute]
15pub fn workflow(args: TokenStream, input: TokenStream) -> TokenStream {
16    // parse the annotated function
17    let input = parse_macro_input!(input as ItemFn);
18    let is_exiting = args.to_string() == "exiting";
19
20    let ItemFn {
21        attrs,
22        vis,
23        sig,
24        block,
25    } = input;
26
27    // get the name of the function
28    let function_identifier = sig.ident.clone();
29
30    if is_exiting {
31        quote! (
32            // register the function with the inventory crate
33            libupdated::inventory::submit! {
34                libupdated::update_workflow::WorkflowPlugin::new(stringify!(#function_identifier), |config| -> libupdated::BoxFuture<'static, Result<std::process::ExitCode, WorkflowError>> {
35                    Box::pin(#function_identifier(config))
36                })
37            }
38
39            // output the original function unchanged
40            #(#attrs)* #vis #sig #block
41        ).into()
42    } else {
43        // if the workflow is not exiting, we wrap it in a function that returns an ExitCode
44        quote! (
45            // register the function with the inventory crate
46            libupdated::inventory::submit! {
47                libupdated::update_workflow::WorkflowPlugin::new(stringify!(#function_identifier), |config| -> libupdated::BoxFuture<'static, Result<std::process::ExitCode, WorkflowError>> {
48                    async fn wrapper_function(config: HashMap<String, String>) -> Result<std::process::ExitCode, WorkflowError> {
49                        #function_identifier(config).await?;
50                        Ok(std::process::ExitCode::SUCCESS)
51                    }
52
53                    Box::pin(wrapper_function(config))
54                })
55            }
56
57            // output the original function unchanged
58            #(#attrs)* #vis #sig #block
59        ).into()
60    }
61}