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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
use std::fs::{self, File};
use std::io::SeekFrom;
use std::io::prelude::*;
use std::path::{self, Path};
use std::sync::Arc;
use flate2::read::GzDecoder;
use flate2::{GzBuilder, Compression};
use git2;
use tar::{Archive, Builder, Header, EntryType};
use core::{Package, Workspace, Source, SourceId};
use sources::PathSource;
use util::{self, internal, Config, FileLock};
use util::errors::{CargoResult, CargoResultExt};
use ops::{self, DefaultExecutor};
pub struct PackageOpts<'cfg> {
pub config: &'cfg Config,
pub list: bool,
pub check_metadata: bool,
pub allow_dirty: bool,
pub verify: bool,
pub jobs: Option<u32>,
}
pub fn package(ws: &Workspace,
opts: &PackageOpts) -> CargoResult<Option<FileLock>> {
let pkg = ws.current()?;
let config = ws.config();
if pkg.manifest().features().activated().len() > 0 {
bail!("cannot package or publish crates which activate nightly-only \
cargo features")
}
let mut src = PathSource::new(pkg.root(),
pkg.package_id().source_id(),
config);
src.update()?;
if opts.check_metadata {
check_metadata(pkg, config)?;
}
verify_dependencies(&pkg)?;
if opts.list {
let root = pkg.root();
let mut list: Vec<_> = src.list_files(&pkg)?.iter().map(|file| {
util::without_prefix(&file, &root).unwrap().to_path_buf()
}).collect();
list.sort();
for file in list.iter() {
println!("{}", file.display());
}
return Ok(None)
}
if !opts.allow_dirty {
check_not_dirty(&pkg, &src)?;
}
let filename = format!("{}-{}.crate", pkg.name(), pkg.version());
let dir = ws.target_dir().join("package");
let mut dst = {
let tmp = format!(".{}", filename);
dir.open_rw(&tmp, config, "package scratch space")?
};
config.shell().status("Packaging", pkg.package_id().to_string())?;
dst.file().set_len(0)?;
tar(ws, &src, dst.file(), &filename).chain_err(|| {
"failed to prepare local package for uploading"
})?;
if opts.verify {
dst.seek(SeekFrom::Start(0))?;
run_verify(ws, dst.file(), opts).chain_err(|| {
"failed to verify package tarball"
})?
}
dst.seek(SeekFrom::Start(0))?;
{
let src_path = dst.path();
let dst_path = dst.parent().join(&filename);
fs::rename(&src_path, &dst_path).chain_err(|| {
"failed to move temporary tarball into final location"
})?;
}
Ok(Some(dst))
}
fn check_metadata(pkg: &Package, config: &Config) -> CargoResult<()> {
let md = pkg.manifest().metadata();
let mut missing = vec![];
macro_rules! lacking {
($( $($field: ident)||* ),*) => {{
$(
if $(md.$field.as_ref().map_or(true, |s| s.is_empty()))&&* {
$(missing.push(stringify!($field).replace("_", "-"));)*
}
)*
}}
}
lacking!(description, license || license_file, documentation || homepage || repository);
if !missing.is_empty() {
let mut things = missing[..missing.len() - 1].join(", ");
if !things.is_empty() {
things.push_str(" or ");
}
things.push_str(&missing.last().unwrap());
config.shell().warn(
&format!("manifest has no {things}.\n\
See http://doc.crates.io/manifest.html#package-metadata for more info.",
things = things))?
}
Ok(())
}
fn verify_dependencies(pkg: &Package) -> CargoResult<()> {
for dep in pkg.dependencies() {
if dep.source_id().is_path() {
if !dep.specified_req() {
bail!("all path dependencies must have a version specified \
when packaging.\ndependency `{}` does not specify \
a version.", dep.name())
}
}
}
Ok(())
}
fn check_not_dirty(p: &Package, src: &PathSource) -> CargoResult<()> {
if let Ok(repo) = git2::Repository::discover(p.root()) {
if let Some(workdir) = repo.workdir() {
debug!("found a git repo at {:?}, checking if index present",
workdir);
let path = p.manifest_path();
let path = path.strip_prefix(workdir).unwrap_or(path);
if let Ok(status) = repo.status_file(path) {
if (status & git2::STATUS_IGNORED).is_empty() {
debug!("Cargo.toml found in repo, checking if dirty");
return git(p, src, &repo)
}
}
}
}
return Ok(());
fn git(p: &Package,
src: &PathSource,
repo: &git2::Repository) -> CargoResult<()> {
let workdir = repo.workdir().unwrap();
let dirty = src.list_files(p)?.iter().filter(|file| {
let relative = file.strip_prefix(workdir).unwrap();
if let Ok(status) = repo.status_file(relative) {
status != git2::STATUS_CURRENT
} else {
false
}
}).map(|path| {
path.strip_prefix(p.root()).unwrap_or(path).display().to_string()
}).collect::<Vec<_>>();
if dirty.is_empty() {
Ok(())
} else {
bail!("{} files in the working directory contain changes that were \
not yet committed into git:\n\n{}\n\n\
to proceed despite this, pass the `--allow-dirty` flag",
dirty.len(), dirty.join("\n"))
}
}
}
fn tar(ws: &Workspace,
src: &PathSource,
dst: &File,
filename: &str) -> CargoResult<()> {
let filename = Path::new(filename);
let encoder = GzBuilder::new().filename(util::path2bytes(filename)?)
.write(dst, Compression::Best);
let mut ar = Builder::new(encoder);
let pkg = ws.current()?;
let config = ws.config();
let root = pkg.root();
for file in src.list_files(pkg)?.iter() {
let relative = util::without_prefix(&file, &root).unwrap();
check_filename(relative)?;
let relative = relative.to_str().ok_or_else(|| {
format!("non-utf8 path in source directory: {}",
relative.display())
})?;
config.shell().verbose(|shell| {
shell.status("Archiving", &relative)
})?;
let path = format!("{}-{}{}{}", pkg.name(), pkg.version(),
path::MAIN_SEPARATOR, relative);
let mut header = Header::new_ustar();
header.set_path(&path).chain_err(|| {
format!("failed to add to archive: `{}`", relative)
})?;
let mut file = File::open(file).chain_err(|| {
format!("failed to open for archiving: `{}`", file.display())
})?;
let metadata = file.metadata().chain_err(|| {
format!("could not learn metadata for: `{}`", relative)
})?;
header.set_metadata(&metadata);
if relative == "Cargo.toml" {
let orig = Path::new(&path).with_file_name("Cargo.toml.orig");
header.set_path(&orig)?;
header.set_cksum();
ar.append(&header, &mut file).chain_err(|| {
internal(format!("could not archive source file `{}`", relative))
})?;
let mut header = Header::new_ustar();
let toml = pkg.to_registry_toml();
header.set_path(&path)?;
header.set_entry_type(EntryType::file());
header.set_mode(0o644);
header.set_size(toml.len() as u64);
header.set_cksum();
ar.append(&header, toml.as_bytes()).chain_err(|| {
internal(format!("could not archive source file `{}`", relative))
})?;
} else {
header.set_cksum();
ar.append(&header, &mut file).chain_err(|| {
internal(format!("could not archive source file `{}`", relative))
})?;
}
}
let encoder = ar.into_inner()?;
encoder.finish()?;
Ok(())
}
fn run_verify(ws: &Workspace, tar: &File, opts: &PackageOpts) -> CargoResult<()> {
let config = ws.config();
let pkg = ws.current()?;
config.shell().status("Verifying", pkg)?;
let f = GzDecoder::new(tar)?;
let dst = pkg.root().join(&format!("target/package/{}-{}",
pkg.name(), pkg.version()));
if fs::metadata(&dst).is_ok() {
fs::remove_dir_all(&dst)?;
}
let mut archive = Archive::new(f);
archive.unpack(dst.parent().unwrap())?;
let id = SourceId::for_path(&dst)?;
let mut src = PathSource::new(&dst, &id, ws.config());
let new_pkg = src.root_package()?;
let ws = Workspace::ephemeral(new_pkg, config, None, true)?;
ops::compile_ws(&ws, None, &ops::CompileOptions {
config: config,
jobs: opts.jobs,
target: None,
features: &[],
no_default_features: false,
all_features: false,
spec: ops::Packages::Packages(&[]),
filter: ops::CompileFilter::Default { required_features_filterable: true },
release: false,
message_format: ops::MessageFormat::Human,
mode: ops::CompileMode::Build,
target_rustdoc_args: None,
target_rustc_args: None,
}, Arc::new(DefaultExecutor))?;
Ok(())
}
fn check_filename(file: &Path) -> CargoResult<()> {
let name = match file.file_name() {
Some(name) => name,
None => return Ok(()),
};
let name = match name.to_str() {
Some(name) => name,
None => {
bail!("path does not have a unicode filename which may not unpack \
on all platforms: {}", file.display())
}
};
let bad_chars = ['/', '\\', '<', '>', ':', '"', '|', '?', '*'];
for c in bad_chars.iter().filter(|c| name.contains(**c)) {
bail!("cannot package a filename with a special character `{}`: {}",
c, file.display())
}
Ok(())
}