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
extern crate proc_macro;

use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use std::{
    env,
    fmt::Display,
    fs,
    path::{Path, PathBuf},
};

fn git_sbp_url(sub_uri: &impl ToString) -> String {
    format!(
        "https://raw.githubusercontent.com/devraymondsh/{}/v{}/single-binary-producer/{}",
        env::var("CARGO_PKG_NAME").unwrap(),
        env::var("CARGO_PKG_VERSION").unwrap(),
        sub_uri.to_string()
    )
}
fn sbp_download_and_write(sub_uri: &(impl ToString + Display)) -> String {
    let out_dir = env::var("OUT_DIR").unwrap();
    let contents = String::from_utf8_lossy(
        &reqwest::blocking::get(git_sbp_url(sub_uri))
            .unwrap()
            .bytes()
            .unwrap(),
    )
    .to_string();

    fs::create_dir_all(format!("{}/sbp/src", out_dir)).unwrap();

    let file_path = format!("{}/sbp/{}", out_dir, sub_uri);
    fs::write(&file_path, contents).unwrap();

    file_path
}

const MAIN_RS_ORIGINAL_PATH: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../single-binary-producer/src/main.rs"
);
const CARGO_TOML_ORIGINAL_PATH: &str = concat!(
    env!("CARGO_MANIFEST_DIR"),
    "/../single-binary-producer/Cargo.toml"
);

fn get_main_rs_path() -> String {
    if PathBuf::from(MAIN_RS_ORIGINAL_PATH).exists() {
        String::from(MAIN_RS_ORIGINAL_PATH)
    } else {
        sbp_download_and_write(&"src/main.rs")
    }
}
fn get_cargo_toml_path() -> String {
    if PathBuf::from(CARGO_TOML_ORIGINAL_PATH).exists() {
        String::from(CARGO_TOML_ORIGINAL_PATH)
    } else {
        sbp_download_and_write(&"Cargo.toml")
    }
}
fn quote(dir: impl AsRef<Path> + ToTokens) -> TokenStream {
    quote! {
        std::include_str!(#dir)
    }
    .into()
}

#[proc_macro]
pub fn get_sbp_main_rs(_input: TokenStream) -> TokenStream {
    let dir = get_main_rs_path();

    quote(dir)
}

#[proc_macro]
pub fn get_sbp_cargo_toml(_input: TokenStream) -> TokenStream {
    let dir = get_cargo_toml_path();

    quote(dir)
}