sails-cli 2.0.0

CLI tools the Sails framework
Documentation
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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
use crate::utils::{self, OutputExt};
use anyhow::{Context, Result, bail};
use askama::Template;
use chrono::{Datelike, Utc};
use convert_case::{Case, Casing};
use sails_sol_gen::{LICENSE_IDENTIFIER, SOLIDITY_VERSION, SolidityFile};
use std::{
    env,
    fmt::Display,
    fs::{self, File},
    io::Write,
    path::{Path, PathBuf},
    process::{Command, Stdio},
};

const FORGE_STD_VERSION: &str = "1.16.2";
const EVM_VERSION: &str = "cancun";
const ICON_CONFIG: &str = "📋";
const ICON_WORKSPACE: &str = "📜";
const ICON_DEPENDENCIES: &str = "📦";
const ICON_FORMAT: &str = "✨";
const ICON_DONE: &str = "✅";

#[derive(Template)]
#[template(path = "forge/.github/workflows/test.askama")]
struct TestWorkflow {
    git_branch_name: String,
}

#[derive(Template)]
#[template(path = "forge/vscode/settings.askama")]
struct VsCodeSettings {
    solidity_version: String,
}

// TODO: script, src, test

#[derive(Template)]
#[template(path = "forge/script/AbiScript.askama")]
struct AbiScript {
    license_identifier: String,
    solidity_version: String,
    contract_name: String,
    contract_name_camel_case: String,
}

#[derive(Template)]
#[template(path = "forge/script/CallerScript.askama")]
struct CallerScript {
    license_identifier: String,
    solidity_version: String,
    contract_name: String,
    contract_name_camel_case: String,
}

#[derive(Template)]
#[template(path = "forge/test/AbiTest.askama")]
struct AbiTest {
    license_identifier: String,
    solidity_version: String,
    contract_name: String,
    contract_name_camel_case: String,
}

#[derive(Template)]
#[template(path = "forge/test/CallerTest.askama")]
struct CallerTest {
    license_identifier: String,
    solidity_version: String,
    contract_name: String,
    contract_name_camel_case: String,
}

#[derive(Template)]
#[template(path = "forge/env_example.askama")]
struct RootEnvExample {
    contract_name: String,
}

#[derive(Template)]
#[template(path = "forge/foundry.askama")]
struct RootFoundry {
    forge_std_version: String,
    evm_version: String,
    solidity_version: String,
}

#[derive(Template)]
#[template(path = "forge/gitignore.askama")]
struct RootGitignore;

#[derive(Template)]
#[template(path = "forge/license.askama")]
struct RootLicense {
    copyright_year: String,
    package_author: String,
}

#[derive(Template)]
#[template(path = "forge/readme.askama")]
struct RootReadme {
    contract_name: String,
    contract_name_kebab_case: String,
    github_username: String,
}

#[derive(Template)]
#[template(path = "forge/remappings.askama")]
struct RootRemappings {
    forge_std_version: String,
}

pub enum SolidityGeneratorOutputType {
    SingleSolidity,
    ForgeProject,
}

pub struct SolidityGenerator {
    idl_path: PathBuf,
    target_dir: PathBuf,
    contract_name: Option<String>,
    package_author: String,
    github_username: String,
    offline: bool,
    output_type: SolidityGeneratorOutputType,
}

impl SolidityGenerator {
    const DEFAULT_AUTHOR: &str = "Gear Technologies";
    const DEFAULT_GITHUB_USERNAME: &str = "gear-tech";

    pub fn new(
        idl_path: PathBuf,
        target_dir: Option<PathBuf>,
        contract_name: Option<String>,
        author: Option<String>,
        username: Option<String>,
        offline: bool,
        output_type: SolidityGeneratorOutputType,
    ) -> Self {
        let package_author = author.unwrap_or_else(|| Self::DEFAULT_AUTHOR.to_string());
        let github_username = username.unwrap_or_else(|| Self::DEFAULT_GITHUB_USERNAME.to_string());
        Self {
            idl_path,
            target_dir: target_dir.unwrap_or_default(),
            contract_name,
            package_author,
            github_username,
            offline,
            output_type,
        }
    }

    fn test_workflow(&self, git_branch_name: &str) -> TestWorkflow {
        TestWorkflow {
            git_branch_name: git_branch_name.into(),
        }
    }

    fn vscode_settings(&self) -> VsCodeSettings {
        VsCodeSettings {
            solidity_version: SOLIDITY_VERSION.into(),
        }
    }

    // TODO: script, src, test

    fn abi_script(&self, contract_name: &str, contract_name_camel_case: &str) -> AbiScript {
        AbiScript {
            license_identifier: LICENSE_IDENTIFIER.into(),
            solidity_version: SOLIDITY_VERSION.into(),
            contract_name: contract_name.into(),
            contract_name_camel_case: contract_name_camel_case.into(),
        }
    }

    fn caller_script(&self, contract_name: &str, contract_name_camel_case: &str) -> CallerScript {
        CallerScript {
            license_identifier: LICENSE_IDENTIFIER.into(),
            solidity_version: SOLIDITY_VERSION.into(),
            contract_name: contract_name.into(),
            contract_name_camel_case: contract_name_camel_case.into(),
        }
    }

    fn abi_test(&self, contract_name: &str, contract_name_camel_case: &str) -> AbiTest {
        AbiTest {
            license_identifier: LICENSE_IDENTIFIER.into(),
            solidity_version: SOLIDITY_VERSION.into(),
            contract_name: contract_name.into(),
            contract_name_camel_case: contract_name_camel_case.into(),
        }
    }

    fn caller_test(&self, contract_name: &str, contract_name_camel_case: &str) -> CallerTest {
        CallerTest {
            license_identifier: LICENSE_IDENTIFIER.into(),
            solidity_version: SOLIDITY_VERSION.into(),
            contract_name: contract_name.into(),
            contract_name_camel_case: contract_name_camel_case.into(),
        }
    }

    fn root_env_example(&self, contract_name: &str) -> RootEnvExample {
        RootEnvExample {
            contract_name: contract_name.into(),
        }
    }

    fn root_foundry(&self) -> RootFoundry {
        RootFoundry {
            forge_std_version: FORGE_STD_VERSION.into(),
            evm_version: EVM_VERSION.into(),
            solidity_version: SOLIDITY_VERSION.into(),
        }
    }

    fn root_gitignore(&self) -> RootGitignore {
        RootGitignore
    }

    fn root_license(&self) -> RootLicense {
        RootLicense {
            copyright_year: Utc::now().year().to_string(),
            package_author: self.package_author.clone(),
        }
    }

    fn root_readme(&self, contract_name: &str, contract_name_kebab_case: &str) -> RootReadme {
        RootReadme {
            contract_name: contract_name.into(),
            contract_name_kebab_case: contract_name_kebab_case.into(),
            github_username: self.github_username.clone(),
        }
    }

    fn root_remappings(&self) -> RootRemappings {
        RootRemappings {
            forge_std_version: FORGE_STD_VERSION.into(),
        }
    }

    pub fn generate(self) -> Result<()> {
        let idl_content = fs::read_to_string(&self.idl_path)?;
        let filename: String = if let Some(stem) = self.idl_path.file_stem() {
            stem.to_string_lossy().into()
        } else {
            bail!("No filename found");
        };
        let contract_name = self.contract_name.clone().unwrap_or(filename.to_string());

        println!("⛵ Creating bindings for Solidity...");
        self.print_config(&contract_name);

        match self.output_type {
            SolidityGeneratorOutputType::SingleSolidity => {
                self.generate_single_solidity(&idl_content, &contract_name.to_case(Case::Pascal))?
            }
            SolidityGeneratorOutputType::ForgeProject => {
                self.generate_forge_project(&idl_content, &contract_name.to_case(Case::Kebab))?
            }
        }

        Ok(())
    }

    fn print_config(&self, contract_name: &str) {
        let print_field = |label: &str, value: &dyn Display| {
            println!("   {label:<10} {value}");
        };

        println!("{ICON_CONFIG} Solidity config:");
        print_field("idl:", &self.idl_path.display());
        if self.target_dir.as_os_str().is_empty() {
            print_field("path:", &"none");
        } else {
            print_field("path:", &self.target_dir.display());
        }
        print_field("contract:", &contract_name);
        print_field("author:", &self.package_author);
        print_field("username:", &self.github_username);
        print_field("offline:", &self.offline);
        match self.output_type {
            SolidityGeneratorOutputType::SingleSolidity => {
                print_field("output:", &"single Solidity file");
            }
            SolidityGeneratorOutputType::ForgeProject => {
                print_field("output:", &"Forge project");
            }
        }
    }

    fn generate_single_solidity(&self, idl_content: &str, contract_name: &str) -> Result<()> {
        let data = sails_sol_gen::generate_solidity_contract(
            contract_name,
            idl_content,
            SolidityFile::SingleFile,
        )?;
        let target_file = self.target_dir.join(format!("{contract_name}.sol"));

        fs::write(&target_file, data)?;

        println!(
            "Generated single Solidity file: {target_file}",
            target_file = target_file.display()
        );

        Ok(())
    }

    fn generate_forge_project(
        &self,
        idl_content: &str,
        contract_name_kebab_case: &str,
    ) -> Result<()> {
        println!("{ICON_WORKSPACE} [1/3] Initializing workspace...");
        let project_dir = self.generate_root(idl_content, contract_name_kebab_case)?;

        println!("{ICON_DEPENDENCIES} [2/3] Installing dependencies...");
        self.install(&project_dir)?;

        println!("{ICON_FORMAT} [3/3] Formatting workspace...");
        self.fmt(&project_dir)?;

        println!("{ICON_DONE} Done.");

        Ok(())
    }

    fn generate_root(&self, idl_content: &str, contract_name_kebab_case: &str) -> Result<PathBuf> {
        let contract_name_pascal_case = contract_name_kebab_case.to_case(Case::Pascal);
        let contract_name_camel_case = contract_name_kebab_case.to_case(Case::Camel);

        let project_dir = self.target_dir.join(contract_name_kebab_case);
        if project_dir.exists() {
            bail!("Target directory already exists: {}", project_dir.display());
        }
        fs::create_dir_all(&project_dir)?;

        let project_dir = project_dir
            .canonicalize()
            .context("Failed to canonicalize project directory")?;
        let path = &project_dir;

        git_init(path)?;

        let git_branch_name = utils::git_show_current_branch(path)?;
        println!("   git branch: {git_branch_name}");

        fs::create_dir_all(test_workflow_dir_path(path))?;
        let mut test_workflow_yml = File::create(test_workflow_path(path))?;
        self.test_workflow(&git_branch_name)
            .write_into(&mut test_workflow_yml)?;

        fs::create_dir_all(vscode_dir_path(path))?;
        let mut vscode_settings_json = File::create(vscode_settings_path(path))?;
        self.vscode_settings()
            .write_into(&mut vscode_settings_json)?;

        // TODO: script, src, test

        fs::create_dir_all(script_dir_path(path))?;

        let mut abi_script_sol =
            File::create(abi_script_sol_path(path, &contract_name_pascal_case))?;
        self.abi_script(&contract_name_pascal_case, &contract_name_camel_case)
            .write_into(&mut abi_script_sol)?;

        let mut caller_script_sol =
            File::create(caller_script_sol_path(path, &contract_name_pascal_case))?;
        self.caller_script(&contract_name_pascal_case, &contract_name_camel_case)
            .write_into(&mut caller_script_sol)?;

        fs::create_dir_all(src_dir_path(path))?;

        let mut solidity_interface_file = File::create(solidity_interface_file_path(
            path,
            &contract_name_pascal_case,
        ))?;
        let solidity_interface_file_content = sails_sol_gen::generate_solidity_contract(
            &contract_name_pascal_case,
            idl_content,
            SolidityFile::InterfaceFile,
        )?;
        solidity_interface_file.write_all(&solidity_interface_file_content)?;

        let mut solidity_abi_interface_file = File::create(solidity_abi_interface_file_path(
            path,
            &contract_name_pascal_case,
        ))?;
        let solidity_abi_interface_file_content = sails_sol_gen::generate_solidity_contract(
            &contract_name_pascal_case,
            idl_content,
            SolidityFile::AbiInterfaceFile,
        )?;
        solidity_abi_interface_file.write_all(&solidity_abi_interface_file_content)?;

        let mut solidity_callbacks_interface_file = File::create(
            solidity_callbacks_interface_file_path(path, &contract_name_pascal_case),
        )?;
        let solidity_callbacks_interface_file_content = sails_sol_gen::generate_solidity_contract(
            &contract_name_pascal_case,
            idl_content,
            SolidityFile::CallbacksInterfaceFile,
        )?;
        solidity_callbacks_interface_file.write_all(&solidity_callbacks_interface_file_content)?;

        let mut solidity_caller_file =
            File::create(solidity_caller_file_path(path, &contract_name_pascal_case))?;
        let solidity_caller_file_content = sails_sol_gen::generate_solidity_contract(
            &contract_name_pascal_case,
            idl_content,
            SolidityFile::CallerFile,
        )?;
        solidity_caller_file.write_all(&solidity_caller_file_content)?;

        fs::create_dir_all(test_dir_path(path))?;

        let mut test_abi_test_sol =
            File::create(test_abi_test_sol_path(path, &contract_name_pascal_case))?;
        self.abi_test(&contract_name_pascal_case, &contract_name_camel_case)
            .write_into(&mut test_abi_test_sol)?;

        let mut test_caller_test_sol =
            File::create(test_caller_test_sol_path(path, &contract_name_pascal_case))?;
        self.caller_test(&contract_name_pascal_case, &contract_name_camel_case)
            .write_into(&mut test_caller_test_sol)?;

        let mut root_env_example = File::create(env_example_path(path))?;
        self.root_env_example(&contract_name_pascal_case)
            .write_into(&mut root_env_example)?;

        let mut foundry_toml = File::create(foundry_path(path))?;
        self.root_foundry().write_into(&mut foundry_toml)?;

        let mut gitignore = File::create(gitignore_path(path))?;
        self.root_gitignore().write_into(&mut gitignore)?;

        let mut license = File::create(license_path(path))?;
        self.root_license().write_into(&mut license)?;

        let mut readme = File::create(readme_path(path))?;
        self.root_readme(&contract_name_pascal_case, contract_name_kebab_case)
            .write_into(&mut readme)?;

        let mut remappings = File::create(remappings_path(path))?;
        self.root_remappings().write_into(&mut remappings)?;

        Ok(project_dir)
    }

    fn install<P: AsRef<Path>>(&self, project_dir: P) -> Result<()> {
        let path = &project_dir;

        if !self.offline {
            forge_soldeer_install(path)?;
        }

        Ok(())
    }

    fn fmt<P: AsRef<Path>>(&self, project_dir: P) -> Result<()> {
        let path = &project_dir;
        forge_fmt(path)
    }
}

fn forge_soldeer_install<P: AsRef<Path>>(dir: P) -> Result<()> {
    let forge_command = forge_command();
    let mut cmd = Command::new(forge_command);
    cmd.current_dir(dir)
        .stdout(Stdio::piped())
        .arg("soldeer")
        .arg("install");

    let _ = cmd
        .output()?
        .exit_result()
        .context("failed to install soldeer packages")?;

    Ok(())
}

fn forge_fmt<P: AsRef<Path>>(dir: P) -> Result<()> {
    let forge_command = forge_command();
    let mut cmd = Command::new(forge_command);
    cmd.current_dir(dir).stdout(Stdio::piped()).arg("fmt");

    let _ = cmd
        .output()?
        .exit_result()
        .context("failed to format the project")?;

    Ok(())
}

fn git_init<P: AsRef<Path>>(target_dir: P) -> Result<()> {
    let git_command = utils::git_command();
    let mut cmd = Command::new(git_command);
    cmd.stdout(Stdio::piped())
        .arg("-C")
        .arg(target_dir.as_ref())
        .arg("init");

    let _ = cmd
        .output()?
        .exit_result()
        .context("failed to initialize git repository")?;

    Ok(())
}

fn test_workflow_dir_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join(".github/workflows")
}

fn test_workflow_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join(".github/workflows/test.yml")
}

fn vscode_dir_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join(".vscode")
}

fn vscode_settings_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join(".vscode/settings.json")
}

// TODO: script, src, test

fn script_dir_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join("script")
}

fn abi_script_sol_path<P: AsRef<Path>>(path: P, contract_name: &str) -> PathBuf {
    path.as_ref()
        .join("script")
        .join(format!("{contract_name}Abi.s.sol"))
}

fn caller_script_sol_path<P: AsRef<Path>>(path: P, contract_name: &str) -> PathBuf {
    path.as_ref()
        .join("script")
        .join(format!("{contract_name}Caller.s.sol"))
}

fn src_dir_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join("src")
}

fn solidity_interface_file_path<P: AsRef<Path>>(path: P, contract_name: &str) -> PathBuf {
    path.as_ref()
        .join("src")
        .join(format!("I{contract_name}.sol"))
}

fn solidity_abi_interface_file_path<P: AsRef<Path>>(path: P, contract_name: &str) -> PathBuf {
    path.as_ref()
        .join("src")
        .join(format!("{contract_name}Abi.sol"))
}

fn solidity_callbacks_interface_file_path<P: AsRef<Path>>(path: P, contract_name: &str) -> PathBuf {
    path.as_ref()
        .join("src")
        .join(format!("I{contract_name}Callbacks.sol"))
}

fn solidity_caller_file_path<P: AsRef<Path>>(path: P, contract_name: &str) -> PathBuf {
    path.as_ref()
        .join("src")
        .join(format!("{contract_name}Caller.sol"))
}

fn test_dir_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join("test")
}

fn test_abi_test_sol_path<P: AsRef<Path>>(path: P, contract_name: &str) -> PathBuf {
    path.as_ref()
        .join("test")
        .join(format!("{contract_name}Abi.t.sol"))
}

fn test_caller_test_sol_path<P: AsRef<Path>>(path: P, contract_name: &str) -> PathBuf {
    path.as_ref()
        .join("test")
        .join(format!("{contract_name}Caller.t.sol"))
}

fn env_example_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join(".env.example")
}

fn foundry_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join("foundry.toml")
}

fn gitignore_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join(".gitignore")
}

fn license_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join("LICENSE")
}

fn readme_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join("README.md")
}

fn remappings_path<P: AsRef<Path>>(path: P) -> PathBuf {
    path.as_ref().join("remappings.txt")
}

fn forge_command() -> String {
    env::var("FORGE").unwrap_or("forge".into())
}