← back to jhughes-dev__Minecraft-Mod-Starter

Function bodies 106 total

All specs Real LLM only Function bodies
validate_time_of_day function · rust · L289-L303 (15 LOC)
cli/src/global_config.rs
fn validate_time_of_day(value: &str) -> Result<()> {
    let lower = value.to_lowercase();
    match lower.as_str() {
        "noon" | "day" | "midnight" | "night" | "sunrise" | "sunset" => Ok(()),
        _ => {
            // Accept raw tick number
            value.parse::<u32>().map_err(|_| {
                McmodError::Other(format!(
                    "Invalid time '{value}': must be noon/day/midnight/night/sunrise/sunset or a tick number"
                ))
            })?;
            Ok(())
        }
    }
}
time_to_tick function · rust · L306-L314 (9 LOC)
cli/src/global_config.rs
pub fn time_to_tick(time: &str) -> &str {
    match time.to_lowercase().as_str() {
        "noon" | "day" => "day",
        "midnight" | "night" => "midnight",
        "sunrise" => "23000",
        "sunset" => "12000",
        _ => time, // raw tick number passed through
    }
}
install_dir function · rust · L319-L346 (28 LOC)
cli/src/global_config.rs
pub fn install_dir() -> Result<PathBuf> {
    #[cfg(target_os = "windows")]
    {
        if let Ok(local) = std::env::var("LOCALAPPDATA") {
            return Ok(PathBuf::from(local).join("mcmod"));
        }
    }

    #[cfg(not(target_os = "windows"))]
    {
        if let Ok(home) = std::env::var("HOME") {
            return Ok(PathBuf::from(home).join(".local").join("bin"));
        }
    }

    let home = std::env::var("HOME")
        .or_else(|_| std::env::var("USERPROFILE"))
        .map_err(|_| McmodError::Other("Could not determine home directory".to_string()))?;

    #[cfg(target_os = "windows")]
    {
        Ok(PathBuf::from(&home).join("AppData").join("Local").join("mcmod"))
    }
    #[cfg(not(target_os = "windows"))]
    {
        Ok(PathBuf::from(&home).join(".local").join("bin"))
    }
}
install_path function · rust · L349-L356 (8 LOC)
cli/src/global_config.rs
pub fn install_path() -> Result<PathBuf> {
    let dir = install_dir()?;
    if cfg!(target_os = "windows") {
        Ok(dir.join("mcmod.exe"))
    } else {
        Ok(dir.join("mcmod"))
    }
}
is_on_path function · rust · L359-L369 (11 LOC)
cli/src/global_config.rs
pub fn is_on_path(dir: &Path) -> bool {
    if let Ok(path_var) = std::env::var("PATH") {
        let separator = if cfg!(target_os = "windows") { ';' } else { ':' };
        for entry in path_var.split(separator) {
            if Path::new(entry) == dir {
                return true;
            }
        }
    }
    false
}
copy_options_to function · rust · L373-L383 (11 LOC)
cli/src/global_config.rs
pub fn copy_options_to(dest: &Path, config: &GlobalConfig) -> Result<()> {
    if dest.exists() {
        return Ok(());
    }
    let content = config.render_options_txt();
    if let Some(parent) = dest.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(dest, content)?;
    Ok(())
}
mc_version_to_pack_format function · rust · L387-L414 (28 LOC)
cli/src/global_config.rs
fn mc_version_to_pack_format(mc_version: &str) -> (u32, u32) {
    match mc_version {
        "1.21" | "1.21.1" => (48, 0),
        "1.21.2" | "1.21.3" => (57, 0),
        "1.21.4" => (61, 0),
        "1.21.5" => (71, 0),
        "1.21.6" => (80, 0),
        "1.21.7" | "1.21.8" => (81, 0),
        "1.21.9" | "1.21.10" => (88, 0),
        "1.21.11" => (94, 1),
        _ => {
            // For unknown versions, try to guess based on the minor version number.
            // Parse the third component if present.
            let parts: Vec<&str> = mc_version.splitn(3, '.').collect();
            if parts.len() == 3 {
                if let Ok(minor) = parts[2].parse::<u32>() {
                    if minor >= 11 {
                        return (94, 1); // latest known
                    } else if minor >= 9 {
                        return (88, 0);
                    }
                }
            }
            // Default fallback to 1.21.4's format
            (61, 0)
        }
    }
}
If a scraper extracted this row, it came from Repobility (https://repobility.com)
render_pack_mcmeta function · rust · L424-L443 (20 LOC)
cli/src/global_config.rs
fn render_pack_mcmeta(mc_version: &str) -> String {
    let (major, minor) = mc_version_to_pack_format(mc_version);
    if uses_new_pack_format(mc_version) {
        // 1.21.9+ uses min_format/max_format alongside pack_format
        if minor > 0 {
            format!(
                "{{\n  \"pack\": {{\n    \"pack_format\": [{major}, {minor}],\n    \"min_format\": [{major}, 0],\n    \"max_format\": [{major}, {minor}],\n    \"description\": \"Dev defaults (generated by mcmod)\"\n  }}\n}}\n"
            )
        } else {
            format!(
                "{{\n  \"pack\": {{\n    \"pack_format\": {major},\n    \"min_format\": {major},\n    \"max_format\": {major},\n    \"description\": \"Dev defaults (generated by mcmod)\"\n  }}\n}}\n"
            )
        }
    } else {
        // Pre-1.21.9 uses only pack_format
        format!(
            "{{\n  \"pack\": {{\n    \"pack_format\": {major},\n    \"description\": \"Dev defaults (generated by mcmod)\"\n  }}\n}}\n"
        )
    }
}
write_dev_datapack function · rust · L448-L486 (39 LOC)
cli/src/global_config.rs
pub fn write_dev_datapack(project_dir: &Path, config: &GlobalConfig, mc_version: &str) -> Result<()> {
    let pack_dir = project_dir.join("run/world/datapacks/dev-defaults");

    // pack.mcmeta — version-aware format
    crate::util::write_file(
        &pack_dir.join("pack.mcmeta"),
        &render_pack_mcmeta(mc_version),
    )?;

    // load function tag — runs dev:init on world load
    crate::util::write_file(
        &pack_dir.join("data/minecraft/tags/function/load.json"),
        "{\n  \"values\": [\n    \"dev:init\"\n  ]\n}\n",
    )?;

    // init.mcfunction — generated from gamerule config
    let mut commands = Vec::new();

    if let Some(v) = config.gamerules.do_daylight_cycle {
        commands.push(format!("gamerule doDaylightCycle {v}"));
    }
    if let Some(v) = config.gamerules.do_weather_cycle {
        commands.push(format!("gamerule doWeatherCycle {v}"));
    }
    if let Some(ref time) = config.gamerules.time_of_day {
        commands.push(format!("time set {
test_normalize_key_options function · rust · L499-L506 (8 LOC)
cli/src/global_config.rs
    fn test_normalize_key_options() {
        assert_eq!(normalize_key("fullscreen"), "options.fullscreen");
        assert_eq!(normalize_key("pauseOnLostFocus"), "options.pause_on_lost_focus");
        assert_eq!(normalize_key("pause_on_lost_focus"), "options.pause_on_lost_focus");
        assert_eq!(normalize_key("autoJump"), "options.auto_jump");
        assert_eq!(normalize_key("auto_jump"), "options.auto_jump");
        assert_eq!(normalize_key("gamma"), "options.gamma");
    }
test_normalize_key_gamerules function · rust · L509-L515 (7 LOC)
cli/src/global_config.rs
    fn test_normalize_key_gamerules() {
        assert_eq!(normalize_key("doDaylightCycle"), "gamerules.do_daylight_cycle");
        assert_eq!(normalize_key("do_daylight_cycle"), "gamerules.do_daylight_cycle");
        assert_eq!(normalize_key("doWeatherCycle"), "gamerules.do_weather_cycle");
        assert_eq!(normalize_key("timeOfDay"), "gamerules.time_of_day");
        assert_eq!(normalize_key("time_of_day"), "gamerules.time_of_day");
    }
test_parse_bool function · rust · L518-L526 (9 LOC)
cli/src/global_config.rs
    fn test_parse_bool() {
        assert!(parse_bool("true").unwrap());
        assert!(parse_bool("yes").unwrap());
        assert!(parse_bool("1").unwrap());
        assert!(!parse_bool("false").unwrap());
        assert!(!parse_bool("no").unwrap());
        assert!(!parse_bool("0").unwrap());
        assert!(parse_bool("maybe").is_err());
    }
test_validate_time_of_day function · rust · L529-L538 (10 LOC)
cli/src/global_config.rs
    fn test_validate_time_of_day() {
        assert!(validate_time_of_day("noon").is_ok());
        assert!(validate_time_of_day("day").is_ok());
        assert!(validate_time_of_day("midnight").is_ok());
        assert!(validate_time_of_day("night").is_ok());
        assert!(validate_time_of_day("sunrise").is_ok());
        assert!(validate_time_of_day("sunset").is_ok());
        assert!(validate_time_of_day("6000").is_ok());
        assert!(validate_time_of_day("banana").is_err());
    }
test_time_to_tick function · rust · L541-L549 (9 LOC)
cli/src/global_config.rs
    fn test_time_to_tick() {
        assert_eq!(time_to_tick("noon"), "day");
        assert_eq!(time_to_tick("day"), "day");
        assert_eq!(time_to_tick("midnight"), "midnight");
        assert_eq!(time_to_tick("night"), "midnight");
        assert_eq!(time_to_tick("sunrise"), "23000");
        assert_eq!(time_to_tick("sunset"), "12000");
        assert_eq!(time_to_tick("6000"), "6000");
    }
test_render_options_txt_defaults function · rust · L552-L562 (11 LOC)
cli/src/global_config.rs
    fn test_render_options_txt_defaults() {
        let config = GlobalConfig::default();
        let txt = config.render_options_txt();
        assert!(txt.contains("lang:en_us"));
        assert!(txt.contains("fullscreen:true"));
        assert!(txt.contains("pauseOnLostFocus:false"));
        assert!(txt.contains("autoJump:false"));
        assert!(txt.contains("reducedDebugInfo:false"));
        // gamma not set by default, should not appear
        assert!(!txt.contains("gamma:"));
    }
All rows scored by the Repobility analyzer (https://repobility.com)
test_render_options_txt_custom function · rust · L565-L572 (8 LOC)
cli/src/global_config.rs
    fn test_render_options_txt_custom() {
        let mut config = GlobalConfig::default();
        config.options.fullscreen = Some(false);
        config.options.gamma = Some(1.5);
        let txt = config.render_options_txt();
        assert!(txt.contains("fullscreen:false"));
        assert!(txt.contains("gamma:1.5"));
    }
test_default_config_deserializes_from_empty function · rust · L575-L582 (8 LOC)
cli/src/global_config.rs
    fn test_default_config_deserializes_from_empty() {
        let config: GlobalConfig = toml::from_str("").unwrap();
        // Should get defaults for options and gamerules
        assert_eq!(config.options.fullscreen, Some(true));
        assert_eq!(config.options.pause_on_lost_focus, Some(false));
        assert_eq!(config.gamerules.do_daylight_cycle, Some(false));
        assert_eq!(config.gamerules.time_of_day, Some("noon".to_string()));
    }
test_backward_compatible_config function · rust · L585-L597 (13 LOC)
cli/src/global_config.rs
    fn test_backward_compatible_config() {
        // Old config files only had [defaults] section
        let toml_str = r#"
[defaults]
author = "TestAuthor"
language = "java"
"#;
        let config: GlobalConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.defaults.author, Some("TestAuthor".to_string()));
        // Should still get defaults for new sections
        assert_eq!(config.options.auto_jump, Some(false));
        assert_eq!(config.gamerules.do_weather_cycle, Some(false));
    }
test_list_returns_all_sections function · rust · L600-L608 (9 LOC)
cli/src/global_config.rs
    fn test_list_returns_all_sections() {
        let config = GlobalConfig::default();
        let entries = config.list();
        let sections: Vec<&str> = entries.iter().map(|(s, _, _)| *s).collect();
        assert!(sections.contains(&"Defaults"));
        assert!(sections.contains(&"Client Options"));
        assert!(sections.contains(&"Game Rules"));
        assert_eq!(entries.len(), 10);
    }
test_mc_version_to_pack_format function · rust · L611-L624 (14 LOC)
cli/src/global_config.rs
    fn test_mc_version_to_pack_format() {
        assert_eq!(mc_version_to_pack_format("1.21"), (48, 0));
        assert_eq!(mc_version_to_pack_format("1.21.1"), (48, 0));
        assert_eq!(mc_version_to_pack_format("1.21.2"), (57, 0));
        assert_eq!(mc_version_to_pack_format("1.21.3"), (57, 0));
        assert_eq!(mc_version_to_pack_format("1.21.4"), (61, 0));
        assert_eq!(mc_version_to_pack_format("1.21.5"), (71, 0));
        assert_eq!(mc_version_to_pack_format("1.21.6"), (80, 0));
        assert_eq!(mc_version_to_pack_format("1.21.7"), (81, 0));
        assert_eq!(mc_version_to_pack_format("1.21.8"), (81, 0));
        assert_eq!(mc_version_to_pack_format("1.21.9"), (88, 0));
        assert_eq!(mc_version_to_pack_format("1.21.10"), (88, 0));
        assert_eq!(mc_version_to_pack_format("1.21.11"), (94, 1));
    }
test_uses_new_pack_format function · rust · L627-L632 (6 LOC)
cli/src/global_config.rs
    fn test_uses_new_pack_format() {
        assert!(!uses_new_pack_format("1.21.4"));
        assert!(!uses_new_pack_format("1.21.8"));
        assert!(uses_new_pack_format("1.21.9"));
        assert!(uses_new_pack_format("1.21.11"));
    }
test_render_pack_mcmeta_old_format function · rust · L635-L640 (6 LOC)
cli/src/global_config.rs
    fn test_render_pack_mcmeta_old_format() {
        let mcmeta = render_pack_mcmeta("1.21.4");
        assert!(mcmeta.contains("\"pack_format\": 61"));
        assert!(!mcmeta.contains("min_format"));
        assert!(!mcmeta.contains("max_format"));
    }
test_render_pack_mcmeta_new_format_no_minor function · rust · L643-L648 (6 LOC)
cli/src/global_config.rs
    fn test_render_pack_mcmeta_new_format_no_minor() {
        let mcmeta = render_pack_mcmeta("1.21.9");
        assert!(mcmeta.contains("\"pack_format\": 88"));
        assert!(mcmeta.contains("\"min_format\": 88"));
        assert!(mcmeta.contains("\"max_format\": 88"));
    }
Repobility — same analyzer, your code, free for public repos · /scan/
test_render_pack_mcmeta_new_format_with_minor function · rust · L651-L656 (6 LOC)
cli/src/global_config.rs
    fn test_render_pack_mcmeta_new_format_with_minor() {
        let mcmeta = render_pack_mcmeta("1.21.11");
        assert!(mcmeta.contains("\"pack_format\": [94, 1]"));
        assert!(mcmeta.contains("\"min_format\": [94, 0]"));
        assert!(mcmeta.contains("\"max_format\": [94, 1]"));
    }
test_unknown_version_fallback function · rust · L659-L664 (6 LOC)
cli/src/global_config.rs
    fn test_unknown_version_fallback() {
        // Unknown future version with high minor should use latest known
        assert_eq!(mc_version_to_pack_format("1.21.15"), (94, 1));
        // Completely unknown version falls back to 1.21.4's format
        assert_eq!(mc_version_to_pack_format("1.22"), (61, 0));
    }
test_install_dir_returns_ok function · rust · L667-L676 (10 LOC)
cli/src/global_config.rs
    fn test_install_dir_returns_ok() {
        // Should succeed on any platform with HOME or LOCALAPPDATA set
        let dir = install_dir();
        assert!(dir.is_ok());
        let dir = dir.unwrap();
        #[cfg(target_os = "windows")]
        assert!(dir.to_string_lossy().contains("mcmod"));
        #[cfg(not(target_os = "windows"))]
        assert!(dir.to_string_lossy().contains(".local"));
    }
test_install_path_has_correct_filename function · rust · L679-L687 (9 LOC)
cli/src/global_config.rs
    fn test_install_path_has_correct_filename() {
        let path = install_path().unwrap();
        let filename = path.file_name().unwrap().to_string_lossy();
        if cfg!(target_os = "windows") {
            assert_eq!(filename, "mcmod.exe");
        } else {
            assert_eq!(filename, "mcmod");
        }
    }
test_is_on_path_with_known_dir function · rust · L690-L698 (9 LOC)
cli/src/global_config.rs
    fn test_is_on_path_with_known_dir() {
        // The system PATH should contain at least one directory
        if let Ok(path_var) = std::env::var("PATH") {
            let sep = if cfg!(target_os = "windows") { ';' } else { ':' };
            if let Some(first) = path_var.split(sep).next() {
                assert!(is_on_path(Path::new(first)));
            }
        }
    }
add_include_to_settings function · rust · L6-L46 (41 LOC)
cli/src/gradle.rs
pub fn add_include_to_settings(dir: &Path, module: &str) -> Result<()> {
    let path = dir.join("settings.gradle");
    let content = std::fs::read_to_string(&path)?;
    let include_line = format!("include(\"{}\")", module);

    // Don't add if already present
    if content.contains(&include_line) {
        return Ok(());
    }

    let mut lines: Vec<String> = content.lines().map(|l| l.to_string()).collect();

    // Find the last include(...) line
    let mut last_include_idx = None;
    for (i, line) in lines.iter().enumerate() {
        if line.trim().starts_with("include(") {
            last_include_idx = Some(i);
        }
    }

    if let Some(idx) = last_include_idx {
        lines.insert(idx + 1, include_line);
    } else {
        // No include lines found; insert before rootProject.name
        let rp_idx = lines
            .iter()
            .position(|l| l.trim().starts_with("rootProject.name"))
            .unwrap_or(lines.len());
        lines.insert(rp_idx, incl
add_platform_to_gradle_properties function · rust · L49-L76 (28 LOC)
cli/src/gradle.rs
pub fn add_platform_to_gradle_properties(dir: &Path, platform: &str) -> Result<()> {
    let path = dir.join("gradle.properties");
    let content = std::fs::read_to_string(&path)?;

    let mut lines: Vec<String> = content.lines().map(|l| l.to_string()).collect();

    for line in &mut lines {
        if line.starts_with("enabled_platforms=") {
            let current = line.trim_start_matches("enabled_platforms=");
            let platforms: Vec<&str> = current.split(',').map(|s| s.trim()).collect();
            if !platforms.contains(&platform) {
                let mut new_platforms: Vec<&str> = platforms;
                new_platforms.push(platform);
                *line = format!("enabled_platforms={}", new_platforms.join(","));
            }
            break;
        }
    }

    let result = lines.join("\n");
    let result = if content.ends_with('\n') && !result.ends_with('\n') {
        result + "\n"
    } else {
        result
    };
    std::fs::write(&path, result)?;
   
set_gradle_property function · rust · L79-L110 (32 LOC)
cli/src/gradle.rs
pub fn set_gradle_property(dir: &Path, key: &str, value: &str) -> Result<()> {
    let path = dir.join("gradle.properties");
    let content = std::fs::read_to_string(&path)?;

    let mut lines: Vec<String> = content.lines().map(|l| l.to_string()).collect();
    let prefix = format!("{key}=");
    let commented_prefix = format!("# {key}=");
    let new_line = format!("{key}={value}");

    let mut found = false;
    for line in &mut lines {
        if line.starts_with(&prefix) || line.starts_with(&commented_prefix) {
            *line = new_line.clone();
            found = true;
            break;
        }
    }

    if !found {
        // Add at the end, before any trailing blank lines
        lines.push(new_line);
    }

    let result = lines.join("\n");
    let result = if content.ends_with('\n') && !result.ends_with('\n') {
        result + "\n"
    } else {
        result
    };
    std::fs::write(&path, result)?;
    Ok(())
}
Generated by Repobility's multi-pass static-analysis pipeline (https://repobility.com)
main function · rust · L112-L161 (50 LOC)
cli/src/main.rs
fn main() {
    let cli = Cli::parse();

    let result = match cli.command {
        Commands::Init {
            dir,
            mod_id,
            mod_name,
            package,
            author,
            description,
            language,
            loaders,
            ci,
            server,
            publishing,
            modrinth_id,
            curseforge_id,
            offline,
        } => commands::init::run(commands::init::InitOptions {
            dir,
            mod_id,
            mod_name,
            package,
            author,
            description,
            language,
            loaders,
            ci,
            server,
            publishing,
            modrinth_id,
            curseforge_id,
            offline,
        }),
        Commands::Add { feature, dir } => commands::add::run(&feature, &dir),
        Commands::Update => commands::update::run(),
        Commands::Config { action } => match action {
            ConfigCommands::Set { 
render function · rust · L42-L49 (8 LOC)
cli/src/template.rs
pub fn render(template: &str, vars: &HashMap<String, String>) -> String {
    let mut result = template.to_string();
    for (key, value) in vars {
        let placeholder = format!("{{{{{}}}}}", key);
        result = result.replace(&placeholder, value);
    }
    result
}
build_vars function · rust · L70-L115 (46 LOC)
cli/src/template.rs
pub fn build_vars(tv: &TemplateVars) -> HashMap<String, String> {
    let mut vars = HashMap::new();
    vars.insert("mod_id".to_string(), tv.mod_id.to_string());
    vars.insert("mod_name".to_string(), tv.mod_name.to_string());
    vars.insert("package".to_string(), tv.package.to_string());
    vars.insert(
        "package_path".to_string(),
        crate::util::package_to_path(tv.package),
    );
    vars.insert("class_name".to_string(), tv.class_name.to_string());
    vars.insert("author".to_string(), tv.author.to_string());
    vars.insert("description".to_string(), tv.description.to_string());
    vars.insert("language".to_string(), tv.language.to_string());
    vars.insert(
        "minecraft_version".to_string(),
        tv.minecraft_version.to_string(),
    );
    vars.insert(
        "fabric_loader_version".to_string(),
        tv.fabric_loader_version.to_string(),
    );
    vars.insert(
        "fabric_api_version".to_string(),
        tv.fabric_api_version.to_string(),
   
chrono_year function · rust · L163-L174 (12 LOC)
cli/src/template.rs
fn chrono_year() -> String {
    // Use a simple approach: read from system time
    use std::time::{SystemTime, UNIX_EPOCH};
    let secs = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    // Approximate year calculation (good enough for copyright)
    let year = 1970 + secs / 31_557_600; // average seconds per year
    year.to_string()
}
test_render_simple function · rust · L181-L189 (9 LOC)
cli/src/template.rs
    fn test_render_simple() {
        let mut vars = HashMap::new();
        vars.insert("name".to_string(), "World".to_string());
        vars.insert("greeting".to_string(), "Hello".to_string());
        assert_eq!(
            render("{{greeting}}, {{name}}!", &vars),
            "Hello, World!"
        );
    }
test_strip_conditional_blocks_enabled function · rust · L205-L211 (7 LOC)
cli/src/template.rs
    fn test_strip_conditional_blocks_enabled() {
        let input = "before\n{{#fabric}}\nfabric content\n{{/fabric}}\nafter\n";
        let result = strip_conditional_blocks(input, &[("fabric", true)]);
        assert!(result.contains("fabric content"));
        assert!(!result.contains("{{#fabric}}"));
        assert!(!result.contains("{{/fabric}}"));
    }
test_strip_conditional_blocks_disabled function · rust · L214-L220 (7 LOC)
cli/src/template.rs
    fn test_strip_conditional_blocks_disabled() {
        let input = "before\n{{#curseforge}}\ncurseforge content\n{{/curseforge}}\nafter\n";
        let result = strip_conditional_blocks(input, &[("curseforge", false)]);
        assert!(!result.contains("curseforge content"));
        assert!(result.contains("before"));
        assert!(result.contains("after"));
    }
test_strip_conditional_blocks_nested function · rust · L223-L229 (7 LOC)
cli/src/template.rs
    fn test_strip_conditional_blocks_nested() {
        let input = "{{#fabric}}\nouter\n{{#curseforge}}\ninner\n{{/curseforge}}\nrest\n{{/fabric}}\n";
        let result = strip_conditional_blocks(input, &[("fabric", true), ("curseforge", false)]);
        assert!(result.contains("outer"));
        assert!(!result.contains("inner"));
        assert!(result.contains("rest"));
    }
If a scraper extracted this row, it came from Repobility (https://repobility.com)
validate_mod_id function · rust · L6-L15 (10 LOC)
cli/src/util.rs
pub fn validate_mod_id(id: &str) -> Result<()> {
    let re = |c: char| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_';
    if id.is_empty()
        || !id.starts_with(|c: char| c.is_ascii_lowercase())
        || !id.chars().all(re)
    {
        return Err(McmodError::InvalidModId(id.to_string()));
    }
    Ok(())
}
validate_package function · rust · L18-L29 (12 LOC)
cli/src/util.rs
pub fn validate_package(pkg: &str) -> Result<()> {
    let valid_segment = |s: &str| -> bool {
        !s.is_empty()
            && s.starts_with(|c: char| c.is_ascii_lowercase())
            && s.chars()
                .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
    };
    if pkg.is_empty() || !pkg.split('.').all(valid_segment) {
        return Err(McmodError::InvalidPackage(pkg.to_string()));
    }
    Ok(())
}
to_pascal_case function · rust · L33-L48 (16 LOC)
cli/src/util.rs
pub fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                Some(c) => {
                    let mut result = c.to_uppercase().to_string();
                    result.extend(chars);
                    result
                }
                None => String::new(),
            }
        })
        .collect()
}
neoforge_major function · rust · L64-L71 (8 LOC)
cli/src/util.rs
pub fn neoforge_major(version: &str) -> String {
    let parts: Vec<&str> = version.splitn(3, '.').collect();
    if parts.len() >= 2 {
        format!("{}.{}", parts[0], parts[1])
    } else {
        version.to_string()
    }
}
ensure_dir function · rust · L74-L79 (6 LOC)
cli/src/util.rs
pub fn ensure_dir(path: &Path) -> Result<()> {
    if !path.exists() {
        std::fs::create_dir_all(path)?;
    }
    Ok(())
}
write_file function · rust · L82-L88 (7 LOC)
cli/src/util.rs
pub fn write_file(path: &Path, content: &str) -> Result<()> {
    if let Some(parent) = path.parent() {
        ensure_dir(parent)?;
    }
    std::fs::write(path, content)?;
    Ok(())
}
write_binary function · rust · L91-L97 (7 LOC)
cli/src/util.rs
pub fn write_binary(path: &Path, content: &[u8]) -> Result<()> {
    if let Some(parent) = path.parent() {
        ensure_dir(parent)?;
    }
    std::fs::write(path, content)?;
    Ok(())
}
http_get function · rust · L100-L109 (10 LOC)
cli/src/util.rs
pub fn http_get(url: &str) -> Result<String> {
    let body = ureq::get(url)
        .header("User-Agent", "mcmod-cli")
        .call()
        .map_err(|e| McmodError::Http(format!("{e}")))?
        .into_body()
        .read_to_string()
        .map_err(|e| McmodError::Http(format!("{e}")))?;
    Ok(body)
}
All rows scored by the Repobility analyzer (https://repobility.com)
http_get_bytes function · rust · L112-L125 (14 LOC)
cli/src/util.rs
pub fn http_get_bytes(url: &str) -> Result<Vec<u8>> {
    let response = ureq::get(url)
        .header("User-Agent", "mcmod-cli")
        .call()
        .map_err(|e| McmodError::Http(format!("{e}")))?;

    let mut bytes = Vec::new();
    response
        .into_body()
        .as_reader()
        .read_to_end(&mut bytes)
        .map_err(|e| McmodError::Http(format!("{e}")))?;
    Ok(bytes)
}
test_validate_mod_id function · rust · L132-L143 (12 LOC)
cli/src/util.rs
    fn test_validate_mod_id() {
        assert!(validate_mod_id("mymod").is_ok());
        assert!(validate_mod_id("my_mod").is_ok());
        assert!(validate_mod_id("mod123").is_ok());
        assert!(validate_mod_id("a").is_ok());

        assert!(validate_mod_id("").is_err());
        assert!(validate_mod_id("MyMod").is_err());
        assert!(validate_mod_id("1mod").is_err());
        assert!(validate_mod_id("my-mod").is_err());
        assert!(validate_mod_id("_mod").is_err());
    }
test_validate_package function · rust · L146-L157 (12 LOC)
cli/src/util.rs
    fn test_validate_package() {
        assert!(validate_package("com.example.mymod").is_ok());
        assert!(validate_package("com.example").is_ok());
        assert!(validate_package("mymod").is_ok());

        assert!(validate_package("").is_err());
        assert!(validate_package("Com.example").is_err());
        assert!(validate_package("com..example").is_err());
        assert!(validate_package(".com").is_err());
        assert!(validate_package("com.").is_err());
        assert!(validate_package("com.1example").is_err());
    }
‹ prevpage 2 / 3next ›