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
use cargo_util::ProcessBuilder;
use colored::Colorize;
use std::path::PathBuf;

use support_common::error::BridgerError;

use crate::external;
use crate::external::execute::ISubcommandExecutor;
use crate::external::types::CompileChannel;

/// Compile source code and execute binary
#[derive(Clone, Debug)]
pub struct CompileSourceExecutor {
    command: String,
    args: Vec<String>,
    channel: CompileChannel,
    toolchain_version: Option<String>,
}

impl CompileSourceExecutor {
    pub fn new(
        command: String,
        args: Vec<String>,
        channel: CompileChannel,
        toolchain_version: Option<String>,
    ) -> Self {
        Self {
            command,
            args,
            channel,
            toolchain_version,
        }
    }
}

impl ISubcommandExecutor for CompileSourceExecutor {
    fn execute(&self, _path: Option<String>) -> color_eyre::Result<()> {
        self.try_compile_and_execute()?;
        Ok(())
    }
}

impl CompileSourceExecutor {
    fn try_compile_and_execute(&self) -> color_eyre::Result<()> {
        let path_exe = std::env::current_exe()?
            .parent()
            .ok_or_else(|| {
                BridgerError::Subcommand("Can not get the binary path for bridger".to_string())
            })?
            .join("");
        tracing::trace!(target: "bridger", "The execute path is: {}", path_exe.display());

        let mut exists = false;
        for prefix in support_common::constants::ALLOW_BINARY_PREFIX {
            let mut path_bridge = path_exe.join("../../../bridges").join(&self.command);
            tracing::trace!(target: "bridger", "Try detect binary for path: {}", path_bridge.display());
            let full_command = format!("{}{}", prefix, self.command);
            if !path_bridge.exists() {
                path_bridge = path_exe.join("../../../bridges").join(&full_command);
                if !path_bridge.exists() {
                    continue;
                }
            }
            if let Err(e) = self.try_compile_and_execute_with_command(path_bridge, full_command) {
                if let Some(BridgerError::Subcommand(msg)) = e.downcast_ref() {
                    tracing::error!(target: "bridger", "{}", msg);
                    continue;
                }
            }
            exists = true;
            break;
        }
        if !exists {
            return Err(BridgerError::UnsupportExternal(format!(
                "Not support this subcommand: {}",
                self.command
            ))
            .into());
        }
        Ok(())
    }

    fn try_compile_and_execute_with_command(
        &self,
        path_bridge: PathBuf,
        command: impl AsRef<str>,
    ) -> color_eyre::Result<()> {
        let command = command.as_ref();
        tracing::info!(
            target: "bridger",
            "Try compile {} in path: {}",
            &command.blue(),
            path_bridge.display()
        );
        let mut args = Vec::<String>::new();
        if let Some(toolchain) = &self.toolchain_version {
            args.push(format!("+{}", toolchain));
        }
        args.push("build".to_string());
        if self.channel == CompileChannel::Release {
            let name = format!("--{}", self.channel.name());
            args.push(name);
        }
        args.push("-p".to_string());
        args.push(command.to_string());
        let args = args.as_slice();

        let mut builder_cargo = ProcessBuilder::new("cargo");
        builder_cargo.args(args).cwd(&path_bridge);

        tracing::info!(
            target: "bridger",
            "Execute `{} {}` in path: {}",
            "cargo".green(),
            args.join(" ").green(),
            path_bridge.display()
        );
        if let Err(e) = builder_cargo.exec() {
            return Err(BridgerError::Process(
                "cargo".to_string(),
                args.join(" "),
                format!("{:?}", e),
            )
            .into());
        }

        // when compiled success, prepare execute this binary

        let base_path = path_bridge.join("target").join(self.channel.name());
        let platform_command = if cfg!(windows) {
            format!("{}.exe", &command)
        } else {
            command.to_string()
        };
        let path_binary = base_path.join(&platform_command);
        if !path_binary.exists() {
            return Err(BridgerError::Subcommand(format!(
                "The command {} not found in path: {}",
                &platform_command,
                base_path.display()
            ))
            .into());
        }

        external::provider::common::execute_binary(
            command.to_string(),
            path_binary,
            self.args.clone(),
            path_bridge,
        )
    }
}