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
mod authors;
mod config;
mod emoji;
mod git;
mod ignoreme;
mod include_exclude;
mod interactive;
mod progressbar;
mod projectname;
mod template;

use crate::git::GitConfig;
use crate::projectname::ProjectName;
use anyhow::Result;
use config::{Config, CONFIG_FILE_NAME};
use console::style;
use std::env;
use std::path::{Path, PathBuf};
use structopt::StructOpt;

/// Generate a new Cargo project from a given template
///
/// Right now, only git repositories can be used as templates. Just execute
///
/// $ cargo generate --git https://github.com/user/template.git --name foo
///
/// or
///
/// $ cargo gen --git https://github.com/user/template.git --name foo
///
/// and a new Cargo project called foo will be generated.
///
/// TEMPLATES:
///
/// In templates, the following placeholders can be used:
///
/// - `project-name`: Name of the project, in dash-case
///
/// - `crate_name`: Name of the project, but in a case valid for a Rust
///   identifier, i.e., snake_case
///
/// - `authors`: Author names, taken from usual environment variables (i.e.
///   those which are also used by Cargo and git)
#[derive(StructOpt)]
#[structopt(bin_name = "cargo")]
pub enum Cli {
    #[structopt(name = "generate", visible_alias = "gen")]
    Generate(Args),
}

#[derive(Debug, StructOpt)]
pub struct Args {
    /// Git repository to clone template from. Can be a URL (like
    /// `https://github.com/rust-cli/cli-template`), a path (relative or absolute), or an
    /// `owner/repo` abbreviated GitHub URL (like `rust-cli/cli-template`).
    /// Note that cargo generate will first attempt to interpret the `owner/repo` form as a
    /// relative path and only try a GitHub URL if the local path doesn't exist.
    #[structopt(short, long)]
    pub git: String,
    /// Branch to use when installing from git
    #[structopt(short, long)]
    pub branch: Option<String>,
    /// Directory to create / project name; if the name isn't in kebab-case, it will be converted
    /// to kebab-case unless `--force` is given.
    #[structopt(long, short)]
    pub name: Option<String>,
    /// Don't convert the project name to kebab-case before creating the directory.
    /// Note that cargo generate won't overwrite an existing directory, even if `--force` is given.
    #[structopt(long, short)]
    pub force: bool,
    /// Enables more verbose output.
    #[structopt(long, short)]
    pub verbose: bool,
}

pub fn generate(args: Args) -> Result<()> {
    let name = match args.name {
        Some(ref n) => ProjectName::new(n),
        None => ProjectName::new(interactive::name()?),
    };

    create_git(args, &name)?;

    Ok(())
}

fn create_git(args: Args, name: &ProjectName) -> Result<()> {
    let force = args.force;
    let config = GitConfig::new_abbr(&args.git, args.branch.to_owned())?;
    let verbose = args.verbose;
    if let Some(dir) = &create_project_dir(&name, force) {
        match git::create(dir, config) {
            Ok(branch) => {
                git::remove_history(dir)?;
                progress(name, dir, force, &branch, verbose)?;
            }
            Err(e) => anyhow::bail!(
                "{} {} {}",
                emoji::ERROR,
                style("Git Error:").bold().red(),
                style(e).bold().red(),
            ),
        };
    } else {
        anyhow::bail!(
            "{} {}",
            emoji::ERROR,
            style("Target directory already exists, aborting!")
                .bold()
                .red(),
        );
    }
    Ok(())
}

fn create_project_dir(name: &ProjectName, force: bool) -> Option<PathBuf> {
    let dir_name = if force {
        name.raw()
    } else {
        rename_warning(&name);
        name.kebab_case()
    };
    let project_dir = env::current_dir()
        .unwrap_or_else(|_e| ".".into())
        .join(&dir_name);

    println!(
        "{} {} `{}`{}",
        emoji::WRENCH,
        style("Creating project called").bold(),
        style(&dir_name).bold().yellow(),
        style("...").bold()
    );

    if project_dir.exists() {
        None
    } else {
        Some(project_dir)
    }
}

fn progress(
    name: &ProjectName,
    dir: &Path,
    force: bool,
    branch: &str,
    verbose: bool,
) -> Result<()> {
    let template = template::substitute(name, force)?;

    let config_path = dir.join(CONFIG_FILE_NAME);

    let template_config = Config::new(config_path)?.map(|c| c.template);

    let pbar = progressbar::new();
    pbar.tick();

    ignoreme::remove_unneeded_files(dir, verbose);

    template::walk_dir(dir, template, template_config, pbar)?;

    git::init(dir, branch)?;

    gen_success(dir);

    Ok(())
}

fn gen_success(dir: &Path) {
    let dir_string = dir.to_str().unwrap_or("");
    println!(
        "{} {} {} {}",
        emoji::SPARKLE,
        style("Done!").bold().green(),
        style("New project created").bold(),
        style(dir_string).underlined()
    );
}

fn rename_warning(name: &ProjectName) {
    if !name.is_crate_name() {
        println!(
            "{} {} `{}` {} `{}`{}",
            emoji::WARN,
            style("Renaming project called").bold(),
            style(&name.user_input).bold().yellow(),
            style("to").bold(),
            style(&name.kebab_case()).bold().green(),
            style("...").bold()
        );
    }
}