shulkerscript-cli 0.1.0

Command line tool to compile Shulkerscript projects
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
use std::{
    borrow::Cow,
    fmt::Display,
    fs,
    path::{Path, PathBuf},
};

use anyhow::Result;
use clap::ValueEnum;
use git2::{
    IndexAddOption as GitIndexAddOption, Repository as GitRepository, Signature as GitSignature,
};
use inquire::validator::Validation;
use path_absolutize::Absolutize;

use crate::{
    config::{PackConfig, ProjectConfig},
    error::Error,
    terminal_output::{print_error, print_info, print_success},
};

#[derive(Debug, clap::Args, Clone)]
pub struct InitArgs {
    /// The path of the folder to initialize in.
    #[arg(default_value = ".")]
    pub path: PathBuf,
    /// The name of the project.
    #[arg(short, long)]
    pub name: Option<String>,
    /// The description of the project.
    #[arg(short, long)]
    pub description: Option<String>,
    /// The pack format version.
    #[arg(short, long, value_name = "FORMAT", visible_alias = "format")]
    pub pack_format: Option<u8>,
    /// The path of the icon file.
    #[arg(short, long = "icon", value_name = "PATH")]
    pub icon_path: Option<PathBuf>,
    /// Force initialization even if the directory is not empty.
    #[arg(short, long)]
    pub force: bool,
    /// The version control system to initialize. [default: git]
    #[arg(long)]
    pub vcs: Option<VersionControlSystem>,
    /// Enable verbose output.
    #[arg(short, long)]
    pub verbose: bool,
    /// Enable batch mode.
    ///
    /// In batch mode, the command will not prompt the user for input and
    /// will use the default values instead if possible or fail.
    #[arg(long)]
    pub batch: bool,
}

#[derive(Debug, Clone, Copy, Default, ValueEnum)]
pub enum VersionControlSystem {
    #[default]
    Git,
    None,
}

impl Display for VersionControlSystem {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            VersionControlSystem::Git => write!(f, "git"),
            VersionControlSystem::None => write!(f, "none"),
        }
    }
}

pub fn init(args: &InitArgs) -> Result<()> {
    if args.batch {
        initialize_batch(args)
    } else {
        initialize_interactive(args)
    }
}

fn initialize_batch(args: &InitArgs) -> Result<()> {
    let verbose = args.verbose;
    let force = args.force;
    let path = args.path.as_path();
    let description = args.description.as_deref();
    let pack_format = args.pack_format;
    let vcs = args.vcs.unwrap_or(VersionControlSystem::Git);

    if !path.exists() {
        if force {
            fs::create_dir_all(path)?;
        } else {
            print_error("The specified path does not exist.");
            Err(Error::PathNotFoundError(path.to_path_buf()))?;
        }
    } else if !path.is_dir() {
        print_error("The specified path is not a directory.");
        Err(Error::NotDirectoryError(path.to_path_buf()))?;
    } else if !force && path.read_dir()?.next().is_some() {
        print_error("The specified directory is not empty.");
        Err(Error::NonEmptyDirectoryError(path.to_path_buf()))?;
    }

    let name = args
        .name
        .as_deref()
        .or_else(|| path.file_name().and_then(|os| os.to_str()));

    print_info("Initializing a new Shulkerscript project in batch mode...");

    // Create the pack.toml file
    create_pack_config(verbose, path, name, description, pack_format)?;

    // Create the pack.png file
    create_pack_png(path, args.icon_path.as_deref(), verbose)?;

    // Create the src directory
    let src_path = path.join("src");
    create_dir(&src_path, verbose)?;

    // Create the main.shu file
    create_main_file(
        path,
        &name_to_namespace(name.unwrap_or(PackConfig::DEFAULT_NAME)),
        verbose,
    )?;

    // Initialize the version control system
    initalize_vcs(path, vcs, verbose)?;

    print_success("Project initialized successfully.");

    Ok(())
}

fn initialize_interactive(args: &InitArgs) -> Result<()> {
    const ABORT_MSG: &str = "Project initialization interrupted. Aborting...";

    let verbose = args.verbose;
    let force = args.force;
    let path = args.path.as_path();
    let description = args.description.as_deref();
    let pack_format = args.pack_format;

    if !path.exists() {
        if force {
            fs::create_dir_all(path)?;
        } else {
            match inquire::Confirm::new(
                "The specified path does not exist. Do you want to create it?",
            )
            .with_default(true)
            .prompt()
            {
                Ok(true) => fs::create_dir_all(path)?,
                Ok(false) | Err(_) => {
                    print_info(ABORT_MSG);
                    return Err(inquire::InquireError::OperationCanceled.into());
                }
            }
        }
    } else if !path.is_dir() {
        print_error("The specified path is not a directory.");
        Err(Error::NotDirectoryError(path.to_path_buf()))?
    } else if !force && path.read_dir()?.next().is_some() {
        match inquire::Confirm::new(
            "The specified directory is not empty. Do you want to continue?",
        )
        .with_default(false)
        .with_help_message("This may overwrite existing files in the directory.")
        .prompt()
        {
            Ok(false) | Err(_) => {
                print_info(ABORT_MSG);
                return Err(inquire::InquireError::OperationCanceled.into());
            }
            Ok(true) => {}
        }
    }

    let mut interrupted = false;

    let name = args.name.as_deref().map(Cow::Borrowed).or_else(|| {
        let default = path
            .file_name()
            .and_then(|os| os.to_str())
            .unwrap_or(PackConfig::DEFAULT_NAME);

        match inquire::Text::new("Enter the name of the project:")
            .with_help_message("This will be the name of your datapack folder/zip file")
            .with_default(default)
            .prompt()
        {
            Ok(res) => Some(Cow::Owned(res)),
            Err(_) => {
                interrupted = true;
                None
            }
        }
        .or_else(|| {
            path.file_name()
                .and_then(|os| os.to_str().map(Cow::Borrowed))
        })
    });

    if interrupted {
        print_info(ABORT_MSG);
        return Err(inquire::InquireError::OperationCanceled.into());
    }

    let description = description.map(Cow::Borrowed).or_else(||  {
        match inquire::Text::new("Enter the description of the project:")
            .with_help_message("This will be the description of your datapack, visible in the datapack selection screen")
            .with_default(PackConfig::DEFAULT_DESCRIPTION)
            .prompt() {
                Ok(res) => Some(Cow::Owned(res)),
                Err(_) => {
                    interrupted = true;
                    None
                }
            }
    });

    if interrupted {
        print_info(ABORT_MSG);
        return Err(inquire::InquireError::OperationCanceled.into());
    }

    let pack_format = pack_format.or_else(|| {
        match inquire::Text::new("Enter the pack format:")
            .with_help_message("This will determine the Minecraft version compatible with your pack, find more on the Minecraft wiki")
            .with_default(PackConfig::DEFAULT_PACK_FORMAT.to_string().as_str())
            .with_validator(|v: &str| Ok(
                v.parse::<u8>()
                .map(|_| Validation::Valid)
                .unwrap_or(Validation::Invalid(
                    inquire::validator::ErrorMessage::Custom("Invalid pack format".to_string())))))
            .prompt() {
                Ok(res) => res.parse().ok(),
                Err(_) => {
                    interrupted = true;
                    None
                }
            }
    });

    if interrupted {
        print_info(ABORT_MSG);
        return Err(inquire::InquireError::OperationCanceled.into());
    }

    let vcs = args.vcs.unwrap_or_else(|| {
        match inquire::Select::new(
            "Select the version control system:",
            vec![VersionControlSystem::Git, VersionControlSystem::None],
        )
        .with_help_message("This will initialize a version control system")
        .prompt()
        {
            Ok(res) => res,
            Err(_) => {
                interrupted = true;
                VersionControlSystem::Git
            }
        }
    });

    if interrupted {
        print_info(ABORT_MSG);
        return Err(inquire::InquireError::OperationCanceled.into());
    }

    let icon_path = args.icon_path.as_deref().map(Cow::Borrowed).or_else(|| {
        let autocompleter = crate::util::PathAutocomplete::new();
        match inquire::Text::new("Enter the path of the icon file:")
            .with_help_message(
                "This will be the icon of your datapack, visible in the datapack selection screen [use \"-\" for default]",
            )
            .with_autocomplete(autocompleter)
            .with_validator(|s: &str| {
                if s == "-" {
                    Ok(Validation::Valid)
                } else {
                    let path = Path::new(s);
                    if path.exists() && path.is_file() && path.extension().is_some_and(|ext| ext == "png") {
                        Ok(Validation::Valid)
                    } else {
                        Ok(Validation::Invalid(
                            inquire::validator::ErrorMessage::Custom("Invalid file path. Path must exist and point to a png".to_string()),
                        ))
                    }
                }
            })
            .with_default("-")
            .prompt()
        {
            Ok(res) if &res == "-" => None,
            Ok(res) => Some(Cow::Owned(PathBuf::from(res))),
            Err(_) => {
                interrupted = true;
                None
            }
        }
    });

    if interrupted {
        print_info(ABORT_MSG);
        return Err(inquire::InquireError::OperationCanceled.into());
    }

    print_info("Initializing a new Shulkerscript project...");

    // Create the pack.toml file
    create_pack_config(
        verbose,
        path,
        name.as_deref(),
        description.as_deref(),
        pack_format,
    )?;

    // Create the pack.png file
    create_pack_png(path, icon_path.as_deref(), verbose)?;

    // Create the src directory
    let src_path = path.join("src");
    create_dir(&src_path, verbose)?;

    // Create the main.shu file
    create_main_file(
        path,
        &name_to_namespace(&name.unwrap_or(Cow::Borrowed("shulkerscript-pack"))),
        verbose,
    )?;

    // Initialize the version control system
    initalize_vcs(path, vcs, verbose)?;

    print_success("Project initialized successfully.");

    Ok(())
}

fn create_pack_config(
    verbose: bool,
    base_path: &Path,
    name: Option<&str>,
    description: Option<&str>,
    pack_format: Option<u8>,
) -> Result<()> {
    let path = base_path.join("pack.toml");

    // Load the default config
    let mut content = ProjectConfig::default();
    // Override the default values with the provided ones
    if let Some(name) = name {
        content.pack.name = name.to_string();
    }
    if let Some(description) = description {
        content.pack.description = description.to_string();
    }
    if let Some(pack_format) = pack_format {
        content.pack.pack_format = pack_format;
    }

    fs::write(&path, toml::to_string_pretty(&content)?)?;
    if verbose {
        print_info(format!(
            "Created pack.toml file at {}.",
            path.absolutize()?.display()
        ));
    }
    Ok(())
}

fn create_dir(path: &Path, verbose: bool) -> std::io::Result<()> {
    if !path.exists() {
        fs::create_dir(path)?;
        if verbose {
            print_info(format!(
                "Created directory at {}.",
                path.absolutize()?.display()
            ));
        }
    }
    Ok(())
}

fn create_gitignore(path: &Path, verbose: bool) -> std::io::Result<()> {
    let gitignore = path.join(".gitignore");
    fs::write(&gitignore, "/dist\n")?;
    if verbose {
        print_info(format!(
            "Created .gitignore file at {}.",
            gitignore.absolutize()?.display()
        ));
    }
    Ok(())
}

fn create_pack_png(
    project_path: &Path,
    icon_path: Option<&Path>,
    verbose: bool,
) -> std::io::Result<()> {
    let pack_png = project_path.join("pack.png");
    if let Some(icon_path) = icon_path {
        fs::copy(icon_path, &pack_png)?;
        if verbose {
            print_info(format!(
                "Copied pack.png file from {} to {}.",
                icon_path.absolutize()?.display(),
                pack_png.absolutize()?.display()
            ));
        }
    } else {
        fs::write(&pack_png, include_bytes!("../../assets/default-icon.png"))?;
        if verbose {
            print_info(format!(
                "Created pack.png file at {}.",
                pack_png.absolutize()?.display()
            ));
        }
    }
    Ok(())
}

fn create_main_file(path: &Path, namespace: &str, verbose: bool) -> std::io::Result<()> {
    let main_file = path.join("src").join("main.shu");
    fs::write(
        &main_file,
        format!(
            include_str!("../../assets/default-main.shu"),
            namespace = namespace
        ),
    )?;
    if verbose {
        print_info(format!(
            "Created main.shu file at {}.",
            main_file.absolutize()?.display()
        ));
    }
    Ok(())
}

fn initalize_vcs(path: &Path, vcs: VersionControlSystem, verbose: bool) -> Result<()> {
    match vcs {
        VersionControlSystem::None => Ok(()),
        VersionControlSystem::Git => {
            if verbose {
                print_info("Initializing a new Git repository...");
            }
            // Initalize the Git repository
            let repo = GitRepository::init(path)?;
            repo.add_ignore_rule("/dist")?;

            // Create the .gitignore file
            create_gitignore(path, verbose)?;

            // Create the initial commit
            let mut index = repo.index()?;
            let oid = index.write_tree()?;
            let tree = repo.find_tree(oid)?;
            let signature = repo
                .signature()
                .unwrap_or(GitSignature::now("Shulkerscript CLI", "cli@shulkerscript")?);
            repo.commit(
                Some("HEAD"),
                &signature,
                &signature,
                "Inital commit",
                &tree,
                &[],
            )?;

            // Create the second commit with the template files
            let mut index = repo.index()?;
            index.add_all(["."].iter(), GitIndexAddOption::DEFAULT, None)?;
            index.write()?;
            let oid = index.write_tree()?;
            let tree = repo.find_tree(oid)?;
            let parent = repo.head()?.peel_to_commit()?;
            repo.commit(
                Some("HEAD"),
                &signature,
                &signature,
                "Add template files",
                &tree,
                &[&parent],
            )?;

            print_info("Initialized a new Git repository.");

            Ok(())
        }
    }
}

fn name_to_namespace(name: &str) -> String {
    const VALID_CHARS: &str = "0123456789abcdefghijklmnopqrstuvwxyz_-.";

    name.to_lowercase()
        .chars()
        .filter_map(|c| {
            if VALID_CHARS.contains(c) {
                Some(c)
            } else if c.is_ascii_uppercase() {
                Some(c.to_ascii_lowercase())
            } else if c.is_ascii_punctuation() {
                Some('-')
            } else if c.is_ascii_whitespace() {
                Some('_')
            } else {
                None
            }
        })
        .collect()
}