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
// Copyright (c) The Diem Core Contributors
// SPDX-License-Identifier: Apache-2.0

use crate::Result;
use anyhow::{bail, Context};
use serde::Deserialize;
use std::{
    env, fs,
    io::{self, Write},
    path::{Path, PathBuf},
    process::Command,
};
use tempfile::NamedTempFile;

#[derive(Deserialize)]
pub struct Metadata {
    pub target_directory: PathBuf,
    pub workspace_root: PathBuf,
}

pub fn metadata() -> Result<Metadata> {
    let output = Command::new("cargo")
        .arg("metadata")
        .arg("--no-deps")
        .arg("--format-version=1")
        .output()
        .context("Failed to query cargo metadata")?;

    serde_json::from_slice(&output.stdout).map_err(Into::into)
}

/// Get the diem node binary from the current working directory
pub fn get_diem_node_binary_from_worktree() -> Result<(String, PathBuf)> {
    let metadata = metadata()?;
    let mut revision = git_rev_parse(&metadata, "HEAD")?;
    if git_is_worktree_dirty()? {
        revision.push_str("-dirty");
    }

    let bin_path = cargo_build_diem_node(&metadata.workspace_root, &metadata.target_directory)?;

    Ok((revision, bin_path))
}

/// This function will attempt to build the diem-node binary at an arbitrary revision.
/// Using the `target/forge` as a working directory it will do the following:
///     1. Look for a binary named `diem-node--<revision>`, if it already exists return it
///     2. If the binary doesn't exist check out the revision to `target/forge/revision` by doing
///        `git archive --format=tar <revision> | tar x`
///     3. Using the `target/forge/target` directory as a cargo artifact directory, build the
///        binary and then move it to `target/forge/diem-node--<revision>`
pub fn get_diem_node_binary_at_revision(revision: &str) -> Result<(String, PathBuf)> {
    let metadata = metadata()?;
    let forge_directory = metadata.target_directory.join("forge");
    let revision = git_rev_parse(&metadata, format!("{}^{{commit}}", revision))?;
    let checkout_dir = forge_directory.join(&revision);
    let forge_target_directory = forge_directory.join("target");
    let diem_node_bin = forge_directory.join(format!(
        "diem-node--{}{}",
        revision,
        env::consts::EXE_SUFFIX
    ));

    if diem_node_bin.exists() {
        return Ok((revision, diem_node_bin));
    }

    fs::create_dir_all(&forge_target_directory)?;

    checkout_revision(&metadata, &revision, &checkout_dir)?;

    fs::rename(
        cargo_build_diem_node(&checkout_dir, &forge_target_directory)?,
        &diem_node_bin,
    )?;

    let _ = fs::remove_dir_all(&checkout_dir);

    Ok((revision, diem_node_bin))
}

fn git_rev_parse<R: AsRef<str>>(metadata: &Metadata, rev: R) -> Result<String> {
    let rev = rev.as_ref();
    let output = Command::new("git")
        .current_dir(&metadata.workspace_root)
        .arg("rev-parse")
        .arg(rev)
        .output()
        .context("Failed to parse revision")?;
    if output.status.success() {
        String::from_utf8(output.stdout)
            .map(|s| s.trim().to_owned())
            .map_err(Into::into)
    } else {
        bail!("Failed to parse revision: {}", rev);
    }
}

// Determine if the worktree is dirty
fn git_is_worktree_dirty() -> Result<bool> {
    Command::new("git")
        .args(&["diff-index", "--name-only", "HEAD", "--"])
        .output()
        .context("Failed to determine if the worktree is dirty")
        .map(|output| !output.stdout.is_empty())
}

/// Attempt to query the local git repository's remotes for the one that points to the upstream
/// diem/diem repository, falling back to "origin" if unable to locate the remote
pub fn git_get_upstream_remote() -> Result<String> {
    let output = Command::new("sh")
        .arg("-c")
        .arg("git remote -v | grep \"https://github.com/diem/diem.* (fetch)\" | cut -f1")
        .output()
        .context("Failed to get upstream remote")?;

    if output.status.success() {
        let remote = String::from_utf8(output.stdout).map(|s| s.trim().to_owned())?;

        // If its empty, fall back to "origin"
        if remote.is_empty() {
            Ok("origin".into())
        } else {
            Ok(remote)
        }
    } else {
        Ok("origin".into())
    }
}

pub fn git_merge_base<R: AsRef<str>>(rev: R) -> Result<String> {
    let rev = rev.as_ref();
    let output = Command::new("git")
        .arg("merge-base")
        .arg("HEAD")
        .arg(rev)
        .output()
        .context("Failed to find merge base")?;
    if output.status.success() {
        String::from_utf8(output.stdout)
            .map(|s| s.trim().to_owned())
            .map_err(Into::into)
    } else {
        bail!("Failed to find merge base between: {} and HEAD", rev);
    }
}

fn cargo_build_diem_node<D, T>(directory: D, target_directory: T) -> Result<PathBuf>
where
    D: AsRef<Path>,
    T: AsRef<Path>,
{
    let target_directory = target_directory.as_ref();
    let directory = directory.as_ref();
    let output = Command::new("cargo")
        .current_dir(directory)
        .env("CARGO_TARGET_DIR", target_directory)
        .args(&["build", "--bin=diem-node", "--features=failpoints"])
        .output()
        .context("Failed to build diem-node")?;

    if output.status.success() {
        let bin_path =
            target_directory.join(format!("debug/{}{}", "diem-node", env::consts::EXE_SUFFIX));
        if !bin_path.exists() {
            bail!(
                "Can't find binary diem-node at expected path {:?}",
                bin_path
            );
        }

        Ok(bin_path)
    } else {
        io::stderr().write_all(&output.stderr)?;

        bail!(
            "Failed to build diem-node: 'cd {} && CARGO_TARGET_DIR={} cargo build --bin=diem-node",
            directory.display(),
            target_directory.display(),
        );
    }
}

fn checkout_revision(metadata: &Metadata, revision: &str, to: &Path) -> Result<()> {
    fs::create_dir_all(to)?;

    let archive_file = NamedTempFile::new()?.into_temp_path();

    let output = Command::new("git")
        .current_dir(&metadata.workspace_root)
        .arg("archive")
        .arg("--format=tar")
        .arg("--output")
        .arg(&archive_file)
        .arg(&revision)
        .output()
        .context("Failed to run git archive")?;
    if !output.status.success() {
        bail!("Failed to run git archive");
    }

    let output = Command::new("tar")
        .current_dir(to)
        .arg("xf")
        .arg(&archive_file)
        .output()
        .context("Failed to run tar")?;

    if !output.status.success() {
        bail!("Failed to run tar");
    }

    Ok(())
}