cargo-pgx 0.7.0

Cargo subcommand for 'pgx' to make Postgres extension development easy
/*
Portions Copyright 2019-2021 ZomboDB, LLC.
Portions Copyright 2021-2022 Technology Concepts & Design, Inc. <support@tcdi.com>

All rights reserved.

Use of this source code is governed by the MIT license that can be found in the LICENSE file.
*/
use std::collections::HashSet;
use std::fs::File;
use std::io::Write;
use std::path::Path;
use syn::{parse_quote, Ident, Item};

/// A utility structure which can generate 'stubs' of the bindings generated by `pgx-pg-sys`'s build script.
///
/// These stubs can be built.
///
/// For example, this is used by `cargo-pgx` and then `dlopen`'d before the extension for SQL generation.
pub struct PgxPgSysStub {
    stub_file: syn::File,
}

const SYMBOL_SKIP_LIST: [&str; 2] = ["_fini", "_init"];

impl PgxPgSysStub {
    #[tracing::instrument(level = "error", skip_all, fields(symbols = %symbols.len()))]
    pub fn from_symbols(symbols: &HashSet<String>) -> eyre::Result<Self> {
        let mut items = Vec::with_capacity(symbols.len());
        for symbol in symbols.iter().filter(|v| !SYMBOL_SKIP_LIST.contains(&v.as_ref())) {
            match stub_for_symbol(symbol) {
                Ok(stub) => items.push(stub),
                Err(_e) => tracing::trace!(%symbol, "Skipping, not a valid Rust ident"),
            }
        }

        let stub_file = syn::File { shebang: None, attrs: Default::default(), items };

        Ok(Self { stub_file })
    }

    #[tracing::instrument(level = "error", skip_all, fields(pgx_pg_sys_stub = %pgx_pg_sys_stub.as_ref().display()))]
    pub fn write_to_file(&self, pgx_pg_sys_stub: impl AsRef<Path>) -> eyre::Result<()> {
        let pgx_pg_sys_stub = pgx_pg_sys_stub.as_ref();
        if let Some(parent) = pgx_pg_sys_stub.parent() {
            std::fs::create_dir_all(parent)?;
        }
        let mut output_file = File::create(pgx_pg_sys_stub)?;
        let content = prettyplease::unparse(&self.stub_file);
        output_file.write_all(content.as_bytes())?;
        Ok(())
    }
}

#[tracing::instrument]
fn stub_for_symbol(name: &str) -> eyre::Result<Item> {
    let ident = syn::parse_str::<Ident>(name)?;
    let item_fn: syn::ItemFn = parse_quote! {
        #[allow(dead_code)]
        #[allow(non_snake_case)]
        #[no_mangle]
        extern "C" fn #ident() {
            unimplemented!(concat!(stringify!(#name), " is stubbed and cannot be used right now."));
        }
    };
    Ok(Item::Fn(item_fn))
}