1use std::fs::{self, File};
2use std::io::prelude::*;
3use std::io::SeekFrom;
4use std::path::{self, Path, PathBuf};
5use std::sync::Arc;
6
7use flate2::read::GzDecoder;
8use flate2::{Compression, GzBuilder};
9use log::debug;
10use serde_json::{self, json};
11use tar::{Archive, Builder, EntryType, Header};
12
13use crate::core::compiler::{BuildConfig, CompileMode, DefaultExecutor, Executor};
14use crate::core::{Package, Source, SourceId, Workspace};
15use crate::ops;
16use crate::sources::PathSource;
17use crate::util::errors::{CargoResult, CargoResultExt};
18use crate::util::paths;
19use crate::util::{self, internal, Config, FileLock};
20
21pub struct PackageOpts<'cfg> {
22 pub config: &'cfg Config,
23 pub list: bool,
24 pub check_metadata: bool,
25 pub allow_dirty: bool,
26 pub verify: bool,
27 pub jobs: Option<u32>,
28 pub target: Option<String>,
29}
30
31static VCS_INFO_FILE: &'static str = ".cargo_vcs_info.json";
32
33pub fn package(ws: &Workspace<'_>, opts: &PackageOpts<'_>) -> CargoResult<Option<FileLock>> {
34 ops::resolve_ws(ws)?;
35 let pkg = ws.current()?;
36 let config = ws.config();
37
38 let mut src = PathSource::new(pkg.root(), pkg.package_id().source_id(), config);
39 src.update()?;
40
41 if opts.check_metadata {
42 check_metadata(pkg, config)?;
43 }
44
45 verify_dependencies(pkg)?;
46
47 let src_files = src.list_files(pkg)?;
49
50 check_vcs_file_collision(pkg, &src_files)?;
53
54 let vcs_info = if !opts.allow_dirty {
58 check_repo_state(pkg, &src_files, &config, opts.allow_dirty)?
59 .map(|h| json!({"git":{"sha1": h}}))
60 } else {
61 None
62 };
63
64 if opts.list {
65 let root = pkg.root();
66 let mut list: Vec<_> = src
67 .list_files(pkg)?
68 .iter()
69 .map(|file| util::without_prefix(file, root).unwrap().to_path_buf())
70 .collect();
71 if include_lockfile(pkg) {
72 list.push("Cargo.lock".into());
73 }
74 if vcs_info.is_some() {
75 list.push(Path::new(VCS_INFO_FILE).to_path_buf());
76 }
77 list.sort_unstable();
78 for file in list.iter() {
79 println!("{}", file.display());
80 }
81 return Ok(None);
82 }
83
84 let filename = format!("{}-{}.crate", pkg.name(), pkg.version());
85 let dir = ws.target_dir().join("package");
86 let mut dst = {
87 let tmp = format!(".{}", filename);
88 dir.open_rw(&tmp, config, "package scratch space")?
89 };
90
91 config
96 .shell()
97 .status("Packaging", pkg.package_id().to_string())?;
98 dst.file().set_len(0)?;
99 tar(ws, &src_files, vcs_info.as_ref(), dst.file(), &filename)
100 .chain_err(|| failure::format_err!("failed to prepare local package for uploading"))?;
101 if opts.verify {
102 dst.seek(SeekFrom::Start(0))?;
103 run_verify(ws, &dst, opts).chain_err(|| "failed to verify package tarball")?
104 }
105 dst.seek(SeekFrom::Start(0))?;
106 {
107 let src_path = dst.path();
108 let dst_path = dst.parent().join(&filename);
109 fs::rename(&src_path, &dst_path)
110 .chain_err(|| "failed to move temporary tarball into final location")?;
111 }
112 Ok(Some(dst))
113}
114
115fn include_lockfile(pkg: &Package) -> bool {
116 pkg.manifest().publish_lockfile() && pkg.targets().iter().any(|t| t.is_example() || t.is_bin())
117}
118
119fn check_metadata(pkg: &Package, config: &Config) -> CargoResult<()> {
122 let md = pkg.manifest().metadata();
123
124 let mut missing = vec![];
125
126 macro_rules! lacking {
127 ($( $($field: ident)||* ),*) => {{
128 $(
129 if $(md.$field.as_ref().map_or(true, |s| s.is_empty()))&&* {
130 $(missing.push(stringify!($field).replace("_", "-"));)*
131 }
132 )*
133 }}
134 }
135 lacking!(
136 description,
137 license || license_file,
138 documentation || homepage || repository
139 );
140
141 if !missing.is_empty() {
142 let mut things = missing[..missing.len() - 1].join(", ");
143 if !things.is_empty() {
146 things.push_str(" or ");
147 }
148 things.push_str(missing.last().unwrap());
149
150 config.shell().warn(&format!(
151 "manifest has no {things}.\n\
152 See http://doc.crates.io/manifest.html#package-metadata for more info.",
153 things = things
154 ))?
155 }
156 Ok(())
157}
158
159fn verify_dependencies(pkg: &Package) -> CargoResult<()> {
161 for dep in pkg.dependencies() {
162 if dep.source_id().is_path() && !dep.specified_req() {
163 failure::bail!(
164 "all path dependencies must have a version specified \
165 when packaging.\ndependency `{}` does not specify \
166 a version.",
167 dep.name_in_toml()
168 )
169 }
170 }
171 Ok(())
172}
173
174fn check_repo_state(
179 p: &Package,
180 src_files: &[PathBuf],
181 config: &Config,
182 allow_dirty: bool,
183) -> CargoResult<Option<String>> {
184 if let Ok(repo) = git2::Repository::discover(p.root()) {
185 if let Some(workdir) = repo.workdir() {
186 debug!("found a git repo at {:?}", workdir);
187 let path = p.manifest_path();
188 let path = path.strip_prefix(workdir).unwrap_or(path);
189 if let Ok(status) = repo.status_file(path) {
190 if (status & git2::Status::IGNORED).is_empty() {
191 debug!(
192 "found (git) Cargo.toml at {:?} in workdir {:?}",
193 path, workdir
194 );
195 return git(p, src_files, &repo, allow_dirty);
196 }
197 }
198 config.shell().verbose(|shell| {
199 shell.warn(format!(
200 "No (git) Cargo.toml found at `{}` in workdir `{}`",
201 path.display(),
202 workdir.display()
203 ))
204 })?;
205 }
206 } else {
207 config.shell().verbose(|shell| {
208 shell.warn(format!("No (git) VCS found for `{}`", p.root().display()))
209 })?;
210 }
211
212 return Ok(None);
215
216 fn git(
217 p: &Package,
218 src_files: &[PathBuf],
219 repo: &git2::Repository,
220 allow_dirty: bool,
221 ) -> CargoResult<Option<String>> {
222 let workdir = repo.workdir().unwrap();
223 let dirty = src_files
224 .iter()
225 .filter(|file| {
226 let relative = file.strip_prefix(workdir).unwrap();
227 if let Ok(status) = repo.status_file(relative) {
228 status != git2::Status::CURRENT
229 } else {
230 false
231 }
232 })
233 .map(|path| {
234 path.strip_prefix(p.root())
235 .unwrap_or(path)
236 .display()
237 .to_string()
238 })
239 .collect::<Vec<_>>();
240 if dirty.is_empty() {
241 let rev_obj = repo.revparse_single("HEAD")?;
242 Ok(Some(rev_obj.id().to_string()))
243 } else {
244 if !allow_dirty {
245 failure::bail!(
246 "{} files in the working directory contain changes that were \
247 not yet committed into git:\n\n{}\n\n\
248 to proceed despite this, pass the `--allow-dirty` flag",
249 dirty.len(),
250 dirty.join("\n")
251 )
252 }
253 Ok(None)
254 }
255 }
256}
257
258fn check_vcs_file_collision(pkg: &Package, src_files: &[PathBuf]) -> CargoResult<()> {
262 let root = pkg.root();
263 let vcs_info_path = Path::new(VCS_INFO_FILE);
264 let collision = src_files
265 .iter()
266 .find(|&p| util::without_prefix(&p, root).unwrap() == vcs_info_path);
267 if collision.is_some() {
268 failure::bail!(
269 "Invalid inclusion of reserved file name \
270 {} in package source",
271 VCS_INFO_FILE
272 );
273 }
274 Ok(())
275}
276
277fn tar(
278 ws: &Workspace<'_>,
279 src_files: &[PathBuf],
280 vcs_info: Option<&serde_json::Value>,
281 dst: &File,
282 filename: &str,
283) -> CargoResult<()> {
284 let filename = Path::new(filename);
286 let encoder = GzBuilder::new()
287 .filename(util::path2bytes(filename)?)
288 .write(dst, Compression::best());
289
290 let mut ar = Builder::new(encoder);
292 let pkg = ws.current()?;
293 let config = ws.config();
294 let root = pkg.root();
295 for file in src_files.iter() {
296 let relative = util::without_prefix(file, root).unwrap();
297 check_filename(relative)?;
298 let relative = relative.to_str().ok_or_else(|| {
299 failure::format_err!("non-utf8 path in source directory: {}", relative.display())
300 })?;
301 config
302 .shell()
303 .verbose(|shell| shell.status("Archiving", &relative))?;
304 let path = format!(
305 "{}-{}{}{}",
306 pkg.name(),
307 pkg.version(),
308 path::MAIN_SEPARATOR,
309 relative
310 );
311
312 let mut header = Header::new_ustar();
331 header
332 .set_path(&path)
333 .chain_err(|| format!("failed to add to archive: `{}`", relative))?;
334 let mut file = File::open(file)
335 .chain_err(|| format!("failed to open for archiving: `{}`", file.display()))?;
336 let metadata = file
337 .metadata()
338 .chain_err(|| format!("could not learn metadata for: `{}`", relative))?;
339 header.set_metadata(&metadata);
340
341 if relative == "Cargo.toml" {
342 let orig = Path::new(&path).with_file_name("Cargo.toml.orig");
343 header.set_path(&orig)?;
344 header.set_cksum();
345 ar.append(&header, &mut file)
346 .chain_err(|| internal(format!("could not archive source file `{}`", relative)))?;
347
348 let mut header = Header::new_ustar();
349 let toml = pkg.to_registry_toml(ws.config())?;
350 header.set_path(&path)?;
351 header.set_entry_type(EntryType::file());
352 header.set_mode(0o644);
353 header.set_size(toml.len() as u64);
354 header.set_cksum();
355 ar.append(&header, toml.as_bytes())
356 .chain_err(|| internal(format!("could not archive source file `{}`", relative)))?;
357 } else {
358 header.set_cksum();
359 ar.append(&header, &mut file)
360 .chain_err(|| internal(format!("could not archive source file `{}`", relative)))?;
361 }
362 }
363
364 if let Some(ref json) = vcs_info {
365 let filename: PathBuf = Path::new(VCS_INFO_FILE).into();
366 debug_assert!(check_filename(&filename).is_ok());
367 let fnd = filename.display();
368 config
369 .shell()
370 .verbose(|shell| shell.status("Archiving", &fnd))?;
371 let path = format!(
372 "{}-{}{}{}",
373 pkg.name(),
374 pkg.version(),
375 path::MAIN_SEPARATOR,
376 fnd
377 );
378 let mut header = Header::new_ustar();
379 header
380 .set_path(&path)
381 .chain_err(|| format!("failed to add to archive: `{}`", fnd))?;
382 let json = format!("{}\n", serde_json::to_string_pretty(json)?);
383 let mut header = Header::new_ustar();
384 header.set_path(&path)?;
385 header.set_entry_type(EntryType::file());
386 header.set_mode(0o644);
387 header.set_size(json.len() as u64);
388 header.set_cksum();
389 ar.append(&header, json.as_bytes())
390 .chain_err(|| internal(format!("could not archive source file `{}`", fnd)))?;
391 }
392
393 if include_lockfile(pkg) {
394 let toml = paths::read(&ws.root().join("Cargo.lock"))?;
395 let path = format!(
396 "{}-{}{}Cargo.lock",
397 pkg.name(),
398 pkg.version(),
399 path::MAIN_SEPARATOR
400 );
401 let mut header = Header::new_ustar();
402 header.set_path(&path)?;
403 header.set_entry_type(EntryType::file());
404 header.set_mode(0o644);
405 header.set_size(toml.len() as u64);
406 header.set_cksum();
407 ar.append(&header, toml.as_bytes())
408 .chain_err(|| internal("could not archive source file `Cargo.lock`"))?;
409 }
410
411 let encoder = ar.into_inner()?;
412 encoder.finish()?;
413 Ok(())
414}
415
416fn run_verify(ws: &Workspace<'_>, tar: &FileLock, opts: &PackageOpts<'_>) -> CargoResult<()> {
417 let config = ws.config();
418 let pkg = ws.current()?;
419
420 config.shell().status("Verifying", pkg)?;
421
422 let f = GzDecoder::new(tar.file());
423 let dst = tar
424 .parent()
425 .join(&format!("{}-{}", pkg.name(), pkg.version()));
426 if dst.exists() {
427 paths::remove_dir_all(&dst)?;
428 }
429 let mut archive = Archive::new(f);
430 archive.set_preserve_mtime(false);
433 archive.unpack(dst.parent().unwrap())?;
434
435 let id = SourceId::for_path(&dst)?;
438 let mut src = PathSource::new(&dst, id, ws.config());
439 let new_pkg = src.root_package()?;
440 let pkg_fingerprint = src.last_modified_file(&new_pkg)?;
441 let ws = Workspace::ephemeral(new_pkg, config, None, true)?;
442
443 let exec: Arc<dyn Executor> = Arc::new(DefaultExecutor);
444 ops::compile_ws(
445 &ws,
446 None,
447 &ops::CompileOptions {
448 config,
449 build_config: BuildConfig::new(config, opts.jobs, &opts.target, CompileMode::Build)?,
450 features: Vec::new(),
451 no_default_features: false,
452 all_features: false,
453 spec: ops::Packages::Packages(Vec::new()),
454 filter: ops::CompileFilter::Default {
455 required_features_filterable: true,
456 },
457 target_rustdoc_args: None,
458 target_rustc_args: None,
459 local_rustdoc_args: None,
460 export_dir: None,
461 },
462 &exec,
463 )?;
464
465 let ws_fingerprint = src.last_modified_file(ws.current()?)?;
467 if pkg_fingerprint != ws_fingerprint {
468 let (_, path) = ws_fingerprint;
469 failure::bail!(
470 "Source directory was modified by build.rs during cargo publish. \
471 Build scripts should not modify anything outside of OUT_DIR. \
472 Modified file: {}\n\n\
473 To proceed despite this, pass the `--no-verify` flag.",
474 path.display()
475 )
476 }
477
478 Ok(())
479}
480
481fn check_filename(file: &Path) -> CargoResult<()> {
488 let name = match file.file_name() {
489 Some(name) => name,
490 None => return Ok(()),
491 };
492 let name = match name.to_str() {
493 Some(name) => name,
494 None => failure::bail!(
495 "path does not have a unicode filename which may not unpack \
496 on all platforms: {}",
497 file.display()
498 ),
499 };
500 let bad_chars = ['/', '\\', '<', '>', ':', '"', '|', '?', '*'];
501 if let Some(c) = bad_chars.iter().find(|c| name.contains(**c)) {
502 failure::bail!(
503 "cannot package a filename with a special character `{}`: {}",
504 c,
505 file.display()
506 )
507 }
508 Ok(())
509}