soroban_cli/commands/contract/
init.rs

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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
use std::borrow::Cow;
use std::{
    fs::{create_dir_all, metadata, write, Metadata},
    io,
    path::{Path, PathBuf},
    str,
};

use clap::Parser;
use rust_embed::RustEmbed;

use crate::{commands::global, error_on_use_of_removed_arg, print, utils};

const EXAMPLE_REMOVAL_NOTICE: &str = "Adding examples via cli is no longer supported. \
You can still clone examples from the repo https://github.com/stellar/soroban-examples";
const FRONTEND_EXAMPLE_REMOVAL_NOTICE: &str = "Using frontend template via cli is no longer \
supported. You can search for frontend templates using github tags, \
such as `soroban-template` or `soroban-frontend-template`";

#[derive(Parser, Debug, Clone)]
#[group(skip)]
pub struct Cmd {
    pub project_path: String,

    #[arg(
        long,
        default_value = "hello-world",
        long_help = "An optional flag to specify a new contract's name."
    )]
    pub name: String,

    // TODO: remove in future version (23+) https://github.com/stellar/stellar-cli/issues/1586
    #[arg(
        short,
        long,
        hide = true,
        display_order = 100,
        value_parser = error_on_use_of_removed_arg!(String, EXAMPLE_REMOVAL_NOTICE)
    )]
    pub with_example: Option<String>,

    // TODO: remove in future version (23+) https://github.com/stellar/stellar-cli/issues/1586
    #[arg(
        long,
        hide = true,
        display_order = 100,
        value_parser = error_on_use_of_removed_arg!(String, FRONTEND_EXAMPLE_REMOVAL_NOTICE),
    )]
    pub frontend_template: Option<String>,

    #[arg(long, long_help = "Overwrite all existing files.")]
    pub overwrite: bool,
}

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("{0}: {1}")]
    Io(String, io::Error),

    #[error(transparent)]
    Std(#[from] std::io::Error),

    #[error("failed to convert bytes to string: {0}")]
    ConvertBytesToString(#[from] str::Utf8Error),

    #[error("contract package already exists: {0}")]
    AlreadyExists(String),

    #[error("provided project path exists and is not a directory")]
    PathExistsNotDir,

    #[error("provided project path exists and is not a cargo workspace root directory. Hint: run init on an empty or non-existing directory"
    )]
    PathExistsNotCargoProject,
}

impl Cmd {
    #[allow(clippy::unused_self)]
    pub fn run(&self, global_args: &global::Args) -> Result<(), Error> {
        let runner = Runner {
            args: self.clone(),
            print: print::Print::new(global_args.quiet),
        };

        runner.run()
    }
}

#[derive(RustEmbed)]
#[folder = "src/utils/contract-workspace-template"]
struct WorkspaceTemplateFiles;

#[derive(RustEmbed)]
#[folder = "src/utils/contract-template"]
struct ContractTemplateFiles;

struct Runner {
    args: Cmd,
    print: print::Print,
}

impl Runner {
    fn run(&self) -> Result<(), Error> {
        let project_path = PathBuf::from(&self.args.project_path);
        self.print
            .infoln(format!("Initializing workspace at {project_path:?}"));

        // create a project dir, and copy the contents of the base template (contract-init-template) into it
        Self::create_dir_all(&project_path)?;
        self.copy_template_files(
            project_path.as_path(),
            &mut WorkspaceTemplateFiles::iter(),
            WorkspaceTemplateFiles::get,
        )?;

        let contract_path = project_path.join("contracts").join(&self.args.name);
        self.print
            .infoln(format!("Initializing contract at {contract_path:?}"));

        Self::create_dir_all(contract_path.as_path())?;
        self.copy_template_files(
            contract_path.as_path(),
            &mut ContractTemplateFiles::iter(),
            ContractTemplateFiles::get,
        )?;

        Ok(())
    }

    fn copy_template_files(
        &self,
        root_path: &Path,
        files: &mut dyn Iterator<Item = Cow<str>>,
        getter: fn(&str) -> Option<rust_embed::EmbeddedFile>,
    ) -> Result<(), Error> {
        for item in &mut *files {
            let mut to = root_path.join(item.as_ref());
            // We need to include the Cargo.toml file as Cargo.toml.removeextension in the template
            // so that it will be included the package. This is making sure that the Cargo file is
            // written as Cargo.toml in the new project. This is a workaround for this issue:
            // https://github.com/rust-lang/cargo/issues/8597.
            let item_path = Path::new(item.as_ref());
            let is_toml = item_path.file_name().unwrap() == "Cargo.toml.removeextension";
            if is_toml {
                let item_parent_path = item_path.parent().unwrap();
                to = root_path.join(item_parent_path).join("Cargo.toml");
            }

            let exists = Self::file_exists(&to);
            if exists && !self.args.overwrite {
                self.print
                    .infoln(format!("Skipped creating {to:?} as it already exists"));
                continue;
            }

            Self::create_dir_all(to.parent().unwrap())?;

            let Some(file) = getter(item.as_ref()) else {
                self.print
                    .warnln(format!("Failed to read file: {}", item.as_ref()));
                continue;
            };

            let mut file_contents = str::from_utf8(file.data.as_ref())
                .map_err(Error::ConvertBytesToString)?
                .to_string();

            if is_toml {
                let new_content = file_contents.replace("%contract-template%", &self.args.name);
                file_contents = new_content;
            }

            if exists {
                self.print
                    .plusln(format!("Writing {to:?} (overwriting existing file)"));
            } else {
                self.print.plusln(format!("Writing {to:?}"));
            }
            Self::write(&to, &file_contents)?;
        }

        Ok(())
    }

    fn file_exists(file_path: &Path) -> bool {
        metadata(file_path)
            .as_ref()
            .map(Metadata::is_file)
            .unwrap_or(false)
    }

    fn create_dir_all(path: &Path) -> Result<(), Error> {
        create_dir_all(path).map_err(|e| Error::Io(format!("creating directory: {path:?}"), e))
    }

    fn write(path: &Path, contents: &str) -> Result<(), Error> {
        write(path, contents).map_err(|e| Error::Io(format!("writing file: {path:?}"), e))
    }
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::fs::read_to_string;

    use itertools::Itertools;

    use super::*;

    const TEST_PROJECT_NAME: &str = "test-project";

    #[test]
    fn test_init() {
        let temp_dir = tempfile::tempdir().unwrap();
        let project_dir = temp_dir.path().join(TEST_PROJECT_NAME);
        let runner = Runner {
            args: Cmd {
                project_path: project_dir.to_string_lossy().to_string(),
                name: "hello_world".to_string(),
                with_example: None,
                frontend_template: None,
                overwrite: false,
            },
            print: print::Print::new(false),
        };
        runner.run().unwrap();

        assert_base_template_files_exist(&project_dir);

        assert_contract_files_exist(&project_dir, "hello_world");
        assert_excluded_paths_do_not_exist(&project_dir);

        assert_contract_cargo_file_is_well_formed(&project_dir, "hello_world");
        assert_excluded_paths_do_not_exist(&project_dir);

        let runner = Runner {
            args: Cmd {
                project_path: project_dir.to_string_lossy().to_string(),
                name: "contract2".to_string(),
                with_example: None,
                frontend_template: None,
                overwrite: false,
            },
            print: print::Print::new(false),
        };
        runner.run().unwrap();

        assert_contract_files_exist(&project_dir, "contract2");
        assert_excluded_paths_do_not_exist(&project_dir);

        assert_contract_cargo_file_is_well_formed(&project_dir, "contract2");
        assert_excluded_paths_do_not_exist(&project_dir);

        temp_dir.close().unwrap();
    }

    // test helpers
    fn assert_base_template_files_exist(project_dir: &Path) {
        let expected_paths = ["contracts", "Cargo.toml", "README.md"];
        for path in &expected_paths {
            assert!(project_dir.join(path).exists());
        }
    }

    fn assert_contract_files_exist(project_dir: &Path, contract_name: &str) {
        let contract_dir = project_dir.join("contracts").join(contract_name);

        assert!(contract_dir.exists());
        assert!(contract_dir.as_path().join("Cargo.toml").exists());
        assert!(contract_dir.as_path().join("src").join("lib.rs").exists());
        assert!(contract_dir.as_path().join("src").join("test.rs").exists());
    }

    fn assert_contract_cargo_file_is_well_formed(project_dir: &Path, contract_name: &str) {
        let contract_dir = project_dir.join("contracts").join(contract_name);
        let cargo_toml_path = contract_dir.as_path().join("Cargo.toml");
        let cargo_toml_str = read_to_string(cargo_toml_path.clone()).unwrap();
        let doc: toml_edit::DocumentMut = cargo_toml_str.parse().unwrap();
        assert!(
            doc.get("dependencies")
                .unwrap()
                .get("soroban-sdk")
                .unwrap()
                .get("workspace")
                .unwrap()
                .as_bool()
                .unwrap(),
            "expected [dependencies.soroban-sdk] to be a workspace dependency"
        );
        assert!(
            doc.get("dev-dependencies")
                .unwrap()
                .get("soroban-sdk")
                .unwrap()
                .get("workspace")
                .unwrap()
                .as_bool()
                .unwrap(),
            "expected [dev-dependencies.soroban-sdk] to be a workspace dependency"
        );
        assert_ne!(
            0,
            doc.get("dev-dependencies")
                .unwrap()
                .get("soroban-sdk")
                .unwrap()
                .get("features")
                .unwrap()
                .as_array()
                .unwrap()
                .len(),
            "expected [dev-dependencies.soroban-sdk] to have a features list"
        );
        assert!(
            doc.get("dev_dependencies").is_none(),
            "erroneous 'dev_dependencies' section"
        );
        assert_eq!(
            doc.get("lib")
                .unwrap()
                .get("crate-type")
                .unwrap()
                .as_array()
                .unwrap()
                .get(0)
                .unwrap()
                .as_str()
                .unwrap(),
            "cdylib",
            "expected [lib.crate-type] to be 'cdylib'"
        );
    }

    fn assert_excluded_paths_do_not_exist(project_dir: &Path) {
        let base_excluded_paths = [".git", ".github", "Makefile", ".vscode", "target"];
        for path in &base_excluded_paths {
            let filepath = project_dir.join(path);
            assert!(!filepath.exists(), "{filepath:?} should not exist");
        }
        let contract_excluded_paths = ["target", "Cargo.lock"];
        let contract_dirs = fs::read_dir(project_dir.join("contracts"))
            .unwrap()
            .map(|entry| entry.unwrap().path());
        contract_dirs
            .cartesian_product(contract_excluded_paths.iter())
            .for_each(|(contract_dir, excluded_path)| {
                let filepath = contract_dir.join(excluded_path);
                assert!(!filepath.exists(), "{filepath:?} should not exist");
            });
    }
}