Skip to main content

cargo/ops/
cargo_new.rs

1use std::collections::BTreeMap;
2use std::env;
3use std::fmt;
4use std::fs;
5use std::path::{Path, PathBuf};
6
7use git2::Config as GitConfig;
8use git2::Repository as GitRepository;
9
10use crate::core::{compiler, Workspace};
11use crate::util::errors::{CargoResult, CargoResultExt};
12use crate::util::{existing_vcs_repo, internal, FossilRepo, GitRepo, HgRepo, PijulRepo};
13use crate::util::{paths, validate_package_name, Config};
14
15use toml;
16
17#[derive(Clone, Copy, Debug, PartialEq)]
18pub enum VersionControl {
19    Git,
20    Hg,
21    Pijul,
22    Fossil,
23    NoVcs,
24}
25
26#[derive(Debug)]
27pub struct NewOptions {
28    pub version_control: Option<VersionControl>,
29    pub kind: NewProjectKind,
30    /// Absolute path to the directory for the new package
31    pub path: PathBuf,
32    pub name: Option<String>,
33    pub edition: Option<String>,
34    pub registry: Option<String>,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub enum NewProjectKind {
39    Bin,
40    Lib,
41}
42
43impl NewProjectKind {
44    fn is_bin(self) -> bool {
45        self == NewProjectKind::Bin
46    }
47}
48
49impl fmt::Display for NewProjectKind {
50    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
51        match *self {
52            NewProjectKind::Bin => "binary (application)",
53            NewProjectKind::Lib => "library",
54        }
55        .fmt(f)
56    }
57}
58
59struct SourceFileInformation {
60    relative_path: String,
61    target_name: String,
62    bin: bool,
63}
64
65struct MkOptions<'a> {
66    version_control: Option<VersionControl>,
67    path: &'a Path,
68    name: &'a str,
69    source_files: Vec<SourceFileInformation>,
70    bin: bool,
71    edition: Option<&'a str>,
72    registry: Option<&'a str>,
73}
74
75impl NewOptions {
76    pub fn new(
77        version_control: Option<VersionControl>,
78        bin: bool,
79        lib: bool,
80        path: PathBuf,
81        name: Option<String>,
82        edition: Option<String>,
83        registry: Option<String>,
84    ) -> CargoResult<NewOptions> {
85        let kind = match (bin, lib) {
86            (true, true) => failure::bail!("can't specify both lib and binary outputs"),
87            (false, true) => NewProjectKind::Lib,
88            // default to bin
89            (_, false) => NewProjectKind::Bin,
90        };
91
92        let opts = NewOptions {
93            version_control,
94            kind,
95            path,
96            name,
97            edition,
98            registry,
99        };
100        Ok(opts)
101    }
102}
103
104struct CargoNewConfig {
105    name: Option<String>,
106    email: Option<String>,
107    version_control: Option<VersionControl>,
108}
109
110fn get_name<'a>(path: &'a Path, opts: &'a NewOptions) -> CargoResult<&'a str> {
111    if let Some(ref name) = opts.name {
112        return Ok(name);
113    }
114
115    let file_name = path.file_name().ok_or_else(|| {
116        failure::format_err!(
117            "cannot auto-detect package name from path {:?} ; use --name to override",
118            path.as_os_str()
119        )
120    })?;
121
122    file_name.to_str().ok_or_else(|| {
123        failure::format_err!(
124            "cannot create package with a non-unicode name: {:?}",
125            file_name
126        )
127    })
128}
129
130fn check_name(name: &str, opts: &NewOptions) -> CargoResult<()> {
131    // If --name is already used to override, no point in suggesting it
132    // again as a fix.
133    let name_help = match opts.name {
134        Some(_) => "",
135        None => "\nuse --name to override crate name",
136    };
137
138    // Ban keywords + test list found at
139    // https://doc.rust-lang.org/grammar.html#keywords
140    let blacklist = [
141        "abstract", "alignof", "as", "become", "box", "break", "const", "continue", "crate", "do",
142        "else", "enum", "extern", "false", "final", "fn", "for", "if", "impl", "in", "let", "loop",
143        "macro", "match", "mod", "move", "mut", "offsetof", "override", "priv", "proc", "pub",
144        "pure", "ref", "return", "self", "sizeof", "static", "struct", "super", "test", "trait",
145        "true", "type", "typeof", "unsafe", "unsized", "use", "virtual", "where", "while", "yield",
146    ];
147    if blacklist.contains(&name) || (opts.kind.is_bin() && compiler::is_bad_artifact_name(name)) {
148        failure::bail!(
149            "The name `{}` cannot be used as a crate name{}",
150            name,
151            name_help
152        )
153    }
154
155    if let Some(ref c) = name.chars().nth(0) {
156        if c.is_digit(10) {
157            failure::bail!(
158                "Package names starting with a digit cannot be used as a crate name{}",
159                name_help
160            )
161        }
162    }
163
164    validate_package_name(name, "crate name", name_help)?;
165    Ok(())
166}
167
168fn detect_source_paths_and_types(
169    package_path: &Path,
170    package_name: &str,
171    detected_files: &mut Vec<SourceFileInformation>,
172) -> CargoResult<()> {
173    let path = package_path;
174    let name = package_name;
175
176    enum H {
177        Bin,
178        Lib,
179        Detect,
180    }
181
182    struct Test {
183        proposed_path: String,
184        handling: H,
185    }
186
187    let tests = vec![
188        Test {
189            proposed_path: "src/main.rs".to_string(),
190            handling: H::Bin,
191        },
192        Test {
193            proposed_path: "main.rs".to_string(),
194            handling: H::Bin,
195        },
196        Test {
197            proposed_path: format!("src/{}.rs", name),
198            handling: H::Detect,
199        },
200        Test {
201            proposed_path: format!("{}.rs", name),
202            handling: H::Detect,
203        },
204        Test {
205            proposed_path: "src/lib.rs".to_string(),
206            handling: H::Lib,
207        },
208        Test {
209            proposed_path: "lib.rs".to_string(),
210            handling: H::Lib,
211        },
212    ];
213
214    for i in tests {
215        let pp = i.proposed_path;
216
217        // path/pp does not exist or is not a file
218        if !fs::metadata(&path.join(&pp))
219            .map(|x| x.is_file())
220            .unwrap_or(false)
221        {
222            continue;
223        }
224
225        let sfi = match i.handling {
226            H::Bin => SourceFileInformation {
227                relative_path: pp,
228                target_name: package_name.to_string(),
229                bin: true,
230            },
231            H::Lib => SourceFileInformation {
232                relative_path: pp,
233                target_name: package_name.to_string(),
234                bin: false,
235            },
236            H::Detect => {
237                let content = paths::read(&path.join(pp.clone()))?;
238                let isbin = content.contains("fn main");
239                SourceFileInformation {
240                    relative_path: pp,
241                    target_name: package_name.to_string(),
242                    bin: isbin,
243                }
244            }
245        };
246        detected_files.push(sfi);
247    }
248
249    // Check for duplicate lib attempt
250
251    let mut previous_lib_relpath: Option<&str> = None;
252    let mut duplicates_checker: BTreeMap<&str, &SourceFileInformation> = BTreeMap::new();
253
254    for i in detected_files {
255        if i.bin {
256            if let Some(x) = BTreeMap::get::<str>(&duplicates_checker, i.target_name.as_ref()) {
257                failure::bail!(
258                    "\
259multiple possible binary sources found:
260  {}
261  {}
262cannot automatically generate Cargo.toml as the main target would be ambiguous",
263                    &x.relative_path,
264                    &i.relative_path
265                );
266            }
267            duplicates_checker.insert(i.target_name.as_ref(), i);
268        } else {
269            if let Some(plp) = previous_lib_relpath {
270                failure::bail!(
271                    "cannot have a package with \
272                     multiple libraries, \
273                     found both `{}` and `{}`",
274                    plp,
275                    i.relative_path
276                )
277            }
278            previous_lib_relpath = Some(&i.relative_path);
279        }
280    }
281
282    Ok(())
283}
284
285fn plan_new_source_file(bin: bool, package_name: String) -> SourceFileInformation {
286    if bin {
287        SourceFileInformation {
288            relative_path: "src/main.rs".to_string(),
289            target_name: package_name,
290            bin: true,
291        }
292    } else {
293        SourceFileInformation {
294            relative_path: "src/lib.rs".to_string(),
295            target_name: package_name,
296            bin: false,
297        }
298    }
299}
300
301pub fn new(opts: &NewOptions, config: &Config) -> CargoResult<()> {
302    let path = &opts.path;
303    if fs::metadata(path).is_ok() {
304        failure::bail!(
305            "destination `{}` already exists\n\n\
306             Use `cargo init` to initialize the directory",
307            path.display()
308        )
309    }
310
311    let name = get_name(path, opts)?;
312    check_name(name, opts)?;
313
314    let mkopts = MkOptions {
315        version_control: opts.version_control,
316        path,
317        name,
318        source_files: vec![plan_new_source_file(opts.kind.is_bin(), name.to_string())],
319        bin: opts.kind.is_bin(),
320        edition: opts.edition.as_ref().map(|s| &**s),
321        registry: opts.registry.as_ref().map(|s| &**s),
322    };
323
324    mk(config, &mkopts).chain_err(|| {
325        failure::format_err!(
326            "Failed to create package `{}` at `{}`",
327            name,
328            path.display()
329        )
330    })?;
331    Ok(())
332}
333
334pub fn init(opts: &NewOptions, config: &Config) -> CargoResult<()> {
335    let path = &opts.path;
336
337    if fs::metadata(&path.join("Cargo.toml")).is_ok() {
338        failure::bail!("`cargo init` cannot be run on existing Cargo packages")
339    }
340
341    let name = get_name(path, opts)?;
342    check_name(name, opts)?;
343
344    let mut src_paths_types = vec![];
345
346    detect_source_paths_and_types(path, name, &mut src_paths_types)?;
347
348    if src_paths_types.is_empty() {
349        src_paths_types.push(plan_new_source_file(opts.kind.is_bin(), name.to_string()));
350    } else {
351        // --bin option may be ignored if lib.rs or src/lib.rs present
352        // Maybe when doing `cargo init --bin` inside a library package stub,
353        // user may mean "initialize for library, but also add binary target"
354    }
355
356    let mut version_control = opts.version_control;
357
358    if version_control == None {
359        let mut num_detected_vsces = 0;
360
361        if fs::metadata(&path.join(".git")).is_ok() {
362            version_control = Some(VersionControl::Git);
363            num_detected_vsces += 1;
364        }
365
366        if fs::metadata(&path.join(".hg")).is_ok() {
367            version_control = Some(VersionControl::Hg);
368            num_detected_vsces += 1;
369        }
370
371        if fs::metadata(&path.join(".pijul")).is_ok() {
372            version_control = Some(VersionControl::Pijul);
373            num_detected_vsces += 1;
374        }
375
376        if fs::metadata(&path.join(".fossil")).is_ok() {
377            version_control = Some(VersionControl::Fossil);
378            num_detected_vsces += 1;
379        }
380
381        // if none exists, maybe create git, like in `cargo new`
382
383        if num_detected_vsces > 1 {
384            failure::bail!(
385                "more than one of .hg, .git, .pijul, .fossil configurations \
386                 found and the ignore file can't be filled in as \
387                 a result. specify --vcs to override detection"
388            );
389        }
390    }
391
392    let mkopts = MkOptions {
393        version_control,
394        path,
395        name,
396        bin: src_paths_types.iter().any(|x| x.bin),
397        source_files: src_paths_types,
398        edition: opts.edition.as_ref().map(|s| &**s),
399        registry: opts.registry.as_ref().map(|s| &**s),
400    };
401
402    mk(config, &mkopts).chain_err(|| {
403        failure::format_err!(
404            "Failed to create package `{}` at `{}`",
405            name,
406            path.display()
407        )
408    })?;
409    Ok(())
410}
411
412fn mk(config: &Config, opts: &MkOptions<'_>) -> CargoResult<()> {
413    let path = opts.path;
414    let name = opts.name;
415    let cfg = global_config(config)?;
416    // Please ensure that ignore and hgignore are in sync.
417    let ignore = [
418        "/target\n",
419        "**/*.rs.bk\n",
420        if !opts.bin { "Cargo.lock\n" } else { "" },
421    ]
422    .concat();
423    // Mercurial glob ignores can't be rooted, so just sticking a 'syntax: glob' at the top of the
424    // file will exclude too much. Instead, use regexp-based ignores. See 'hg help ignore' for
425    // more.
426    let hgignore = [
427        "^target/\n",
428        "glob:*.rs.bk\n",
429        if !opts.bin { "glob:Cargo.lock\n" } else { "" },
430    ]
431    .concat();
432
433    let vcs = opts.version_control.unwrap_or_else(|| {
434        let in_existing_vcs = existing_vcs_repo(path.parent().unwrap_or(path), config.cwd());
435        match (cfg.version_control, in_existing_vcs) {
436            (None, false) => VersionControl::Git,
437            (Some(opt), false) => opt,
438            (_, true) => VersionControl::NoVcs,
439        }
440    });
441
442    match vcs {
443        VersionControl::Git => {
444            if !path.join(".git").exists() {
445                GitRepo::init(path, config.cwd())?;
446            }
447            let ignore = if path.join(".gitignore").exists() {
448                format!("\n{}", ignore)
449            } else {
450                ignore
451            };
452            paths::append(&path.join(".gitignore"), ignore.as_bytes())?;
453        }
454        VersionControl::Hg => {
455            if !path.join(".hg").exists() {
456                HgRepo::init(path, config.cwd())?;
457            }
458            let hgignore = if path.join(".hgignore").exists() {
459                format!("\n{}", hgignore)
460            } else {
461                hgignore
462            };
463            paths::append(&path.join(".hgignore"), hgignore.as_bytes())?;
464        }
465        VersionControl::Pijul => {
466            if !path.join(".pijul").exists() {
467                PijulRepo::init(path, config.cwd())?;
468            }
469            let ignore = if path.join(".ignore").exists() {
470                format!("\n{}", ignore)
471            } else {
472                ignore
473            };
474            paths::append(&path.join(".ignore"), ignore.as_bytes())?;
475        }
476        VersionControl::Fossil => {
477            if path.join(".fossil").exists() {
478                FossilRepo::init(path, config.cwd())?;
479            }
480        }
481        VersionControl::NoVcs => {
482            fs::create_dir_all(path)?;
483        }
484    };
485
486    let (author_name, email) = discover_author()?;
487    // Hoo boy, sure glad we've got exhaustiveness checking behind us.
488    let author = match (cfg.name, cfg.email, author_name, email) {
489        (Some(name), Some(email), _, _)
490        | (Some(name), None, _, Some(email))
491        | (None, Some(email), name, _)
492        | (None, None, name, Some(email)) => format!("{} <{}>", name, email),
493        (Some(name), None, _, None) | (None, None, name, None) => name,
494    };
495
496    let mut cargotoml_path_specifier = String::new();
497
498    // Calculate what [lib] and [[bin]]s do we need to append to Cargo.toml
499
500    for i in &opts.source_files {
501        if i.bin {
502            if i.relative_path != "src/main.rs" {
503                cargotoml_path_specifier.push_str(&format!(
504                    r#"
505[[bin]]
506name = "{}"
507path = {}
508"#,
509                    i.target_name,
510                    toml::Value::String(i.relative_path.clone())
511                ));
512            }
513        } else if i.relative_path != "src/lib.rs" {
514            cargotoml_path_specifier.push_str(&format!(
515                r#"
516[lib]
517name = "{}"
518path = {}
519"#,
520                i.target_name,
521                toml::Value::String(i.relative_path.clone())
522            ));
523        }
524    }
525
526    // Create Cargo.toml file with necessary [lib] and [[bin]] sections, if needed
527
528    paths::write(
529        &path.join("Cargo.toml"),
530        format!(
531            r#"[package]
532name = "{}"
533version = "0.1.0"
534authors = [{}]
535edition = {}
536{}
537[dependencies]
538{}"#,
539            name,
540            toml::Value::String(author),
541            match opts.edition {
542                Some(edition) => toml::Value::String(edition.to_string()),
543                None => toml::Value::String("2018".to_string()),
544            },
545            match opts.registry {
546                Some(registry) => format!(
547                    "publish = {}\n",
548                    toml::Value::Array(vec!(toml::Value::String(registry.to_string())))
549                ),
550                None => "".to_string(),
551            },
552            cargotoml_path_specifier
553        )
554        .as_bytes(),
555    )?;
556
557    // Create all specified source files
558    // (with respective parent directories)
559    // if they are don't exist
560
561    for i in &opts.source_files {
562        let path_of_source_file = path.join(i.relative_path.clone());
563
564        if let Some(src_dir) = path_of_source_file.parent() {
565            fs::create_dir_all(src_dir)?;
566        }
567
568        let default_file_content: &[u8] = if i.bin {
569            b"\
570fn main() {
571    println!(\"Hello, world!\");
572}
573"
574        } else {
575            b"\
576#[cfg(test)]
577mod tests {
578    #[test]
579    fn it_works() {
580        assert_eq!(2 + 2, 4);
581    }
582}
583"
584        };
585
586        if !fs::metadata(&path_of_source_file)
587            .map(|x| x.is_file())
588            .unwrap_or(false)
589        {
590            paths::write(&path_of_source_file, default_file_content)?;
591        }
592    }
593
594    if let Err(e) = Workspace::new(&path.join("Cargo.toml"), config) {
595        let msg = format!(
596            "compiling this new crate may not work due to invalid \
597             workspace configuration\n\n{}",
598            e
599        );
600        config.shell().warn(msg)?;
601    }
602
603    Ok(())
604}
605
606fn get_environment_variable(variables: &[&str]) -> Option<String> {
607    variables.iter().filter_map(|var| env::var(var).ok()).next()
608}
609
610fn discover_author() -> CargoResult<(String, Option<String>)> {
611    let cwd = env::current_dir()?;
612    let git_config = if let Ok(repo) = GitRepository::discover(&cwd) {
613        repo.config()
614            .ok()
615            .or_else(|| GitConfig::open_default().ok())
616    } else {
617        GitConfig::open_default().ok()
618    };
619    let git_config = git_config.as_ref();
620    let name_variables = [
621        "CARGO_NAME",
622        "GIT_AUTHOR_NAME",
623        "GIT_COMMITTER_NAME",
624        "USER",
625        "USERNAME",
626        "NAME",
627    ];
628    let name = get_environment_variable(&name_variables[0..3])
629        .or_else(|| git_config.and_then(|g| g.get_string("user.name").ok()))
630        .or_else(|| get_environment_variable(&name_variables[3..]));
631
632    let name = match name {
633        Some(name) => name,
634        None => {
635            let username_var = if cfg!(windows) { "USERNAME" } else { "USER" };
636            failure::bail!(
637                "could not determine the current user, please set ${}",
638                username_var
639            )
640        }
641    };
642    let email_variables = [
643        "CARGO_EMAIL",
644        "GIT_AUTHOR_EMAIL",
645        "GIT_COMMITTER_EMAIL",
646        "EMAIL",
647    ];
648    let email = get_environment_variable(&email_variables[0..3])
649        .or_else(|| git_config.and_then(|g| g.get_string("user.email").ok()))
650        .or_else(|| get_environment_variable(&email_variables[3..]));
651
652    let name = name.trim().to_string();
653    let email = email.map(|s| {
654        let mut s = s.trim();
655
656        // In some cases emails will already have <> remove them since they
657        // are already added when needed.
658        if s.starts_with('<') && s.ends_with('>') {
659            s = &s[1..s.len() - 1];
660        }
661
662        s.to_string()
663    });
664
665    Ok((name, email))
666}
667
668fn global_config(config: &Config) -> CargoResult<CargoNewConfig> {
669    let name = config.get_string("cargo-new.name")?.map(|s| s.val);
670    let email = config.get_string("cargo-new.email")?.map(|s| s.val);
671    let vcs = config.get_string("cargo-new.vcs")?;
672
673    let vcs = match vcs.as_ref().map(|p| (&p.val[..], &p.definition)) {
674        Some(("git", _)) => Some(VersionControl::Git),
675        Some(("hg", _)) => Some(VersionControl::Hg),
676        Some(("pijul", _)) => Some(VersionControl::Pijul),
677        Some(("none", _)) => Some(VersionControl::NoVcs),
678        Some((s, p)) => {
679            return Err(internal(format!(
680                "invalid configuration for key \
681                 `cargo-new.vcs`, unknown vcs `{}` \
682                 (found in {})",
683                s, p
684            )));
685        }
686        None => None,
687    };
688    Ok(CargoNewConfig {
689        name,
690        email,
691        version_control: vcs,
692    })
693}