forc/ops/
forc_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
use crate::cli::InitCommand;
use crate::utils::{defaults, program_type::ProgramType};
use anyhow::Context;
use forc_util::{forc_result_bail, validate_project_name, ForcResult};
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use sway_utils::constants;
use tracing::{debug, info};

#[derive(Debug)]
enum InitType {
    Package(ProgramType),
    Workspace,
}

fn print_welcome_message() {
    let read_the_docs = format!(
        "Read the Docs:\n- {}\n- {}\n- {}\n- {}",
        "Sway Book: https://docs.fuel.network/docs/sway",
        "Forc Book: https://docs.fuel.network/docs/forc",
        "Rust SDK Book: https://docs.fuel.network/docs/fuels-rs",
        "TypeScript SDK: https://docs.fuel.network/docs/fuels-ts"
    );

    let join_the_community = format!(
        "Join the Community:\n- Follow us {}
- Ask questions on {}",
        "@SwayLang: https://twitter.com/SwayLang", "Discourse: https://forum.fuel.network/"
    );

    let report_bugs = format!(
        "Report Bugs:\n- {}",
        "Sway Issues: https://github.com/FuelLabs/sway/issues/new"
    );

    let try_forc = "To compile, use `forc build`, and to run tests use `forc test`";

    info!(
        "\n{}\n\n----\n\n{}\n\n{}\n\n{}\n\n",
        try_forc, read_the_docs, join_the_community, report_bugs
    );
}

pub fn init(command: InitCommand) -> ForcResult<()> {
    let project_dir = match &command.path {
        Some(p) => PathBuf::from(p),
        None => {
            std::env::current_dir().context("Failed to get current directory for forc init.")?
        }
    };

    if !project_dir.is_dir() {
        forc_result_bail!(format!(
            "'{}' is not a valid directory.",
            project_dir.display()
        ),);
    }

    if project_dir.join(constants::MANIFEST_FILE_NAME).exists() {
        forc_result_bail!(
            "'{}' already includes a Forc.toml file.",
            project_dir.display()
        );
    }

    debug!(
        "\nUsing project directory at {}",
        project_dir.canonicalize()?.display()
    );

    let project_name = match command.name {
        Some(name) => name,
        None => project_dir
            .file_stem()
            .context("Failed to infer project name from directory name.")?
            .to_string_lossy()
            .into_owned(),
    };

    validate_project_name(&project_name)?;

    let init_type = match (
        command.contract,
        command.script,
        command.predicate,
        command.library,
        command.workspace,
    ) {
        (_, false, false, false, false) => InitType::Package(ProgramType::Contract),
        (false, true, false, false, false) => InitType::Package(ProgramType::Script),
        (false, false, true, false, false) => InitType::Package(ProgramType::Predicate),
        (false, false, false, true, false) => InitType::Package(ProgramType::Library),
        (false, false, false, false, true) => InitType::Workspace,
        _ => {
            forc_result_bail!(
                "Multiple types detected, please specify only one initialization type: \
        \n Possible Types:\n - contract\n - script\n - predicate\n - library\n - workspace"
            )
        }
    };

    // Make a new directory for the project
    let dir_to_create = match init_type {
        InitType::Package(_) => project_dir.join("src"),
        InitType::Workspace => project_dir.clone(),
    };
    fs::create_dir_all(dir_to_create)?;

    // Insert default manifest file
    match init_type {
        InitType::Workspace => fs::write(
            Path::new(&project_dir).join(constants::MANIFEST_FILE_NAME),
            defaults::default_workspace_manifest(),
        )?,
        InitType::Package(ProgramType::Library) => fs::write(
            Path::new(&project_dir).join(constants::MANIFEST_FILE_NAME),
            // Library names cannot have `-` in them because the Sway compiler does not allow that.
            // Even though this is technically not a problem in the toml file, we replace `-` with
            // `_` here as well so that the library name in the Sway file matches the one in
            // `Forc.toml`
            defaults::default_pkg_manifest(&project_name.replace('-', "_"), constants::LIB_ENTRY),
        )?,
        _ => fs::write(
            Path::new(&project_dir).join(constants::MANIFEST_FILE_NAME),
            defaults::default_pkg_manifest(&project_name, constants::MAIN_ENTRY),
        )?,
    }

    match init_type {
        InitType::Package(ProgramType::Contract) => fs::write(
            Path::new(&project_dir)
                .join("src")
                .join(constants::MAIN_ENTRY),
            defaults::default_contract(),
        )?,
        InitType::Package(ProgramType::Script) => fs::write(
            Path::new(&project_dir)
                .join("src")
                .join(constants::MAIN_ENTRY),
            defaults::default_script(),
        )?,
        InitType::Package(ProgramType::Library) => fs::write(
            Path::new(&project_dir)
                .join("src")
                .join(constants::LIB_ENTRY),
            // Library names cannot have `-` in them because the Sway compiler does not allow that
            defaults::default_library(),
        )?,
        InitType::Package(ProgramType::Predicate) => fs::write(
            Path::new(&project_dir)
                .join("src")
                .join(constants::MAIN_ENTRY),
            defaults::default_predicate(),
        )?,
        _ => {}
    }

    // Ignore default `out` and `target` directories created by forc and cargo.
    let gitignore_path = Path::new(&project_dir).join(".gitignore");
    // Append to existing gitignore if it exists otherwise create a new one.
    let mut gitignore_file = fs::OpenOptions::new()
        .append(true)
        .create(true)
        .open(&gitignore_path)?;
    gitignore_file.write_all(defaults::default_gitignore().as_bytes())?;

    debug!(
        "\nCreated .gitignore at {}",
        gitignore_path.canonicalize()?.display()
    );

    debug!("\nSuccessfully created {init_type:?}: {project_name}",);

    print_welcome_message();

    Ok(())
}