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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

use move_deps::{
    move_binary_format::{compatibility::Compatibility, normalized::Module, CompiledModule},
    move_command_line_common::files::{
        extension_equals, find_filenames, MOVE_COMPILED_EXTENSION, MOVE_ERROR_DESC_EXTENSION,
    },
    move_compiler::compiled_unit::{CompiledUnit, NamedCompiledModule},
    move_core_types::language_storage::ModuleId,
    move_package::{BuildConfig, ModelConfig},
};
use std::{
    collections::BTreeMap,
    fs::{create_dir_all, remove_dir_all, File},
    io::Read,
    path::{Path, PathBuf},
};
use structopt::*;

pub const CORE_FRAMEWORK_RELEASE_SUFFIX: &str = "framework";
pub const TOKEN_RELEASE_SUFFIX: &str = "token";

/// Options to configure the generation of a release.
#[derive(Debug, StructOpt, Clone)]
#[structopt(
    name = "Aptos Frameworks",
    about = "Release CLI for Aptos frameworks",
    author = "Aptos",
    rename_all = "kebab-case"
)]
pub struct ReleaseOptions {
    #[structopt(long = "no-check-linking-layout-compatibility")]
    pub no_check_layout_compatibility: bool,
    #[structopt(long = "no-build-docs")]
    pub no_build_docs: bool,
    #[structopt(long = "with-diagram")]
    pub with_diagram: bool,
    #[structopt(long = "no-script-builder")]
    pub no_script_builder: bool,
    #[structopt(long = "no-script-abi")]
    pub no_script_abis: bool,
    #[structopt(long = "no-errmap")]
    pub no_errmap: bool,
    #[structopt(
        long = "package",
        default_value = "aptos-framework",
        parse(from_os_str)
    )]
    pub package: PathBuf,
    #[structopt(long = "output", default_value = "current", parse(from_os_str))]
    pub output: PathBuf,
}

impl Default for ReleaseOptions {
    fn default() -> Self {
        Self {
            no_build_docs: true,
            package: PathBuf::from("aptos-framework"),
            no_check_layout_compatibility: false,
            with_diagram: false,
            no_script_abis: true,
            no_script_builder: true,
            no_errmap: true,
            output: PathBuf::from("current"),
        }
    }
}

impl ReleaseOptions {
    pub fn create_release(&self) {
        let output_path = self
            .package
            .join("releases")
            .join("artifacts")
            .join(&self.output);

        let mut old_module_apis = None;
        if !self.no_check_layout_compatibility {
            old_module_apis = extract_old_apis(&output_path);
        }

        if output_path.exists() {
            std::fs::remove_dir_all(&output_path).unwrap();
        }
        std::fs::create_dir_all(output_path.parent().unwrap()).unwrap();

        let build_config = move_deps::move_package::BuildConfig {
            generate_docs: !self.no_build_docs,
            generate_abis: !self.no_script_abis,
            install_dir: Some(output_path.clone()),
            ..Default::default()
        };

        let package_path = Path::new(std::env!("CARGO_MANIFEST_DIR")).join(&self.package);

        let compiled_package = build_config
            .clone()
            .compile_package(&package_path, &mut std::io::stdout())
            .unwrap();

        if !self.no_check_layout_compatibility {
            println!("Checking layout compatibility");
            if let Some(old_module_apis) = old_module_apis {
                let new_modules =
                    compiled_package
                        .all_compiled_units()
                        .filter_map(|unit| match unit {
                            CompiledUnit::Module(NamedCompiledModule { module, .. }) => {
                                Some(module)
                            }
                            CompiledUnit::Script(_) => None,
                        });
                check_api_compatibility(&old_module_apis, new_modules);
            }
        }

        if !self.no_errmap {
            println!("Generating error map");
            generate_error_map(&package_path, &output_path, build_config)
        }

        if !self.no_script_builder {
            println!("Generating script builders");
            let abi_paths: Vec<&Path> = vec![&output_path];
            generate_script_builder(&output_path.join("aptos_sdk_builder.rs"), &abi_paths[..])
        }
    }
}

fn recreate_dir(dir_path: impl AsRef<Path>) {
    let dir_path = dir_path.as_ref();
    remove_dir_all(&dir_path).unwrap_or(());
    create_dir_all(&dir_path).unwrap();
}

fn generate_error_map(package_path: &Path, output_path: &Path, build_config: BuildConfig) {
    let mut errmap_path = output_path
        .join("error_description")
        .join("error_description");
    errmap_path.set_extension(MOVE_ERROR_DESC_EXTENSION);

    recreate_dir(&errmap_path.parent().unwrap());

    let errmap_options = move_deps::move_errmapgen::ErrmapOptions {
        output_file: errmap_path.to_string_lossy().to_string(),
        ..Default::default()
    };

    let model = build_config
        .move_model_for_package(
            package_path,
            ModelConfig {
                target_filter: None,
                all_files_as_targets: true,
            },
        )
        .unwrap();

    let mut emapgen = move_deps::move_errmapgen::ErrmapGen::new(&model, &errmap_options);
    emapgen.gen();
    emapgen.save_result();
}

fn generate_script_builder(output_path: impl AsRef<Path>, abi_paths: &[&Path]) {
    let output_path = output_path.as_ref();

    let abis: Vec<_> = abi_paths
        .iter()
        .flat_map(|path| {
            aptos_sdk_builder::read_abis(&[path])
                .unwrap_or_else(|_| panic!("Failed to read ABIs at {}", path.to_string_lossy()))
        })
        .collect();

    {
        let mut file = std::fs::File::create(output_path)
            .expect("Failed to open file for Rust script build generation");
        aptos_sdk_builder::rust::output(&mut file, &abis, /* local types */ true)
            .expect("Failed to generate Rust builders");
    }

    std::process::Command::new("rustfmt")
        .arg("--config")
        .arg("imports_granularity=crate")
        .arg(output_path)
        .status()
        .expect("Failed to run rustfmt on generated code");
}

fn extract_old_apis(package_path: impl AsRef<Path>) -> Option<BTreeMap<ModuleId, Module>> {
    let modules_path = package_path.as_ref();

    if !modules_path.is_dir() {
        eprintln!(
            "Warning: failed to extract old module APIs -- path \"{}\" is not a directory",
            modules_path.to_string_lossy()
        );
        return None;
    }
    let mut old_module_apis = BTreeMap::new();
    let files = find_filenames(&[modules_path], |p| {
        extension_equals(p, MOVE_COMPILED_EXTENSION)
    })
    .unwrap();
    for f in files {
        let mut bytes = Vec::new();
        File::open(f)
            .expect("Failed to open module bytecode file")
            .read_to_end(&mut bytes)
            .expect("Failed to read module bytecode file");
        let m = CompiledModule::deserialize(&bytes).expect("Failed to deserialize module bytecode");
        old_module_apis.insert(m.self_id(), Module::new(&m));
    }
    Some(old_module_apis)
}

fn check_api_compatibility<'a, I>(old: &BTreeMap<ModuleId, Module>, new: I)
where
    I: Iterator<Item = &'a CompiledModule>,
{
    let mut is_linking_layout_compatible = true;
    for module in new {
        // extract new linking/layout API and check compatibility with old
        let new_module_id = module.self_id();
        if let Some(old_api) = old.get(&new_module_id) {
            let new_api = Module::new(module);
            let compatibility = Compatibility::check(old_api, &new_api);
            if is_linking_layout_compatible && !compatibility.is_fully_compatible() {
                println!("Found linking/layout-incompatible change:");
                is_linking_layout_compatible = false
            }
            if !compatibility.struct_and_function_linking {
                eprintln!("Linking API for structs/functions of module {} has changed. Need to redeploy all dependent modules.", new_module_id.name())
            }
            if !compatibility.struct_layout {
                eprintln!("Layout API for structs of module {} has changed. Need to do a data migration of published structs", new_module_id.name())
            }
        }
    }
}