navid/veins / bc0b02d957b7af60232a5b91bf4caefba5dfba19c68970ec43e5c39830934f19 / veinsrs/src/cli/commands/init.rs

init.rs

← veinsrs/src/cli/commands · 2595 bytes · raw · download

use std::path::Path;

use crate::core;
use crate::error::{Error, Result};
use crate::store::layout;

pub fn run(arguments: &[String]) -> Result<u8> {
    let mut path = ".".to_string();
    let mut source = None;
    let mut remote_url = String::new();
    let mut remote_name = "o".to_string();
    let mut remote_name_given = false;
    let mut end_flags = false;
    for argument in arguments {
        if !end_flags && argument == "--" {
            end_flags = true;
        } else if !end_flags && let Some(value) = argument.strip_prefix("-git-import:") {
            if value.is_empty() {
                return Err(Error::new("-git-import: requires a path"));
            }
            source = Some(value.to_string());
        } else if !end_flags && let Some(value) = argument.strip_prefix("-remote:") {
            if value.is_empty() {
                return Err(Error::new("-remote: requires a URL"));
            }
            remote_url = value.to_string();
        } else if !end_flags && let Some(value) = argument.strip_prefix("-remote-name:") {
            if value.is_empty() {
                return Err(Error::new("-remote-name: requires a name"));
            }
            remote_name = value.to_string();
            remote_name_given = true;
        } else if !end_flags && core::is_flag(argument) {
            return Err(Error::new(format!("unknown flag: {argument}")));
        } else {
            path = argument.clone();
        }
    }
    if remote_name_given && remote_url.is_empty() {
        return Err(Error::new("-remote-name: requires -remote:<url>"));
    }
    if source.is_none() && !remote_url.is_empty() {
        return Err(Error::new("-remote: requires -git-import:<path>"));
    }
    let root = layout::init(Path::new(&path)).map_err(|_| Error::new("init failed"))?;
    println!("info: initialized veins repository at {}", root.display());
    if let Some(source) = source {
        let prepared = crate::git::prepare_mirror(&root, &source);
        if prepared != 0 {
            if prepared == 2 {
                return Err(Error::new(format!(
                    "-git-import: {source} is not a git repository root (expected the directory containing .git)"
                )));
            }
            return Err(Error::new(format!(
                "cannot prepare git mirror from {source} (code {prepared})"
            )));
        }
        let imported = crate::git::import(&root);
        if imported != 0 {
            return Ok(1);
        }
        crate::git::configure_remote(&root, &remote_url, &remote_name);
    }
    Ok(0)
}