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
#![warn(rust_2018_idioms, rustdoc::broken_intra_doc_links)]
#![deny(elided_lifetimes_in_paths, unsafe_code)]
use cargo::{
core::{
registry::{LockedPatchDependency, PackageRegistry},
Dependency, EitherManifest, SourceId, Verbosity
},
util::{important_paths::find_root_manifest_for_wd, toml::read_manifest},
Config as CargoConfig
};
use clap::Parser;
use std::{
borrow::Cow,
env,
fs::File,
io::{self, Read},
path::PathBuf,
process::ExitCode
};
mod depinfo;
mod input;
mod output;
mod verify;
use input::CrateCode;
#[derive(Parser)]
enum Subcommand {
Doc2readme(Args)
}
#[derive(Parser)]
struct Args {
#[clap(long)]
manifest_path: Option<PathBuf>,
#[clap(short, long, default_value = "README.md")]
out: PathBuf,
#[clap(short, long, default_value = "README.j2")]
template: PathBuf,
#[clap(long)]
expand_macros: bool,
#[clap(long)]
check: bool,
#[clap(short, long)]
verbose: bool
}
#[derive(Parser)]
struct CmdLine {
#[clap(subcommand)]
cmd: Subcommand
}
fn main() -> ExitCode {
let args = match env::args().nth(1) {
Some(subcmd) if subcmd == "doc2readme" => match CmdLine::parse().cmd {
Subcommand::Doc2readme(args) => args
},
_ => Args::parse()
};
let manifest_path = match args.manifest_path {
Some(path) if path.is_relative() => env::current_dir().unwrap().join(path),
Some(path) => path,
None => find_root_manifest_for_wd(&env::current_dir().unwrap())
.expect("Unable to find Cargo.toml")
};
let cargo_cfg = CargoConfig::default().expect("Failed to initialize cargo");
cargo_cfg.shell().set_verbosity(
args.verbose
.then(|| Verbosity::Verbose)
.unwrap_or(Verbosity::Normal)
);
let src_id = SourceId::for_path(&manifest_path).expect("Failed to obtain source id");
let manifest =
read_manifest(&manifest_path, src_id, &cargo_cfg).expect("Failed to read Cargo.toml");
let manifest = match manifest {
(EitherManifest::Real(manifest), _) => manifest,
(EitherManifest::Virtual(_), _) => {
cargo_cfg
.shell()
.error("Virtual manifests (i.e. pure workspace roots) are not supported.")
.unwrap();
return ExitCode::FAILURE;
}
};
let targets = manifest.targets();
let target = targets
.iter()
.find(|target| target.is_lib())
.or_else(|| {
targets
.iter()
.find(|target| target.is_bin() && target.name() == manifest.name().as_str())
})
.or_else(|| targets.iter().find(|target| target.is_bin()))
.expect("Failed to find a library or binary target");
let file = target
.src_path()
.path()
.expect("Target does not have a source file");
let code = if args.expand_macros {
CrateCode::read_expansion(manifest_path.as_path(), target)
.expect("Failed to read crate code")
} else {
CrateCode::read_from_disk(file).expect("Failed to read crate code")
};
let _guard = cargo_cfg
.acquire_package_cache_lock()
.expect("Failed to aquire package cache lock");
let mut registry =
PackageRegistry::new(&cargo_cfg).expect("Failed to initialize crate registry");
for (url, deps) in manifest.patch() {
let deps: Vec<(&Dependency, Option<LockedPatchDependency>)> =
deps.iter().map(|dep| (dep, None)).collect();
registry.patch(url, &deps).expect("Failed to apply patches");
}
registry.lock_patches();
let template: Cow<'static, str> = if args.template.exists() {
let mut buf = String::new();
File::open(args.template)
.expect("Failed to open template")
.read_to_string(&mut buf)
.expect("Failed to read template");
buf.into()
} else {
include_str!("README.j2").into()
};
init_git_transports(&cargo_cfg);
cargo_cfg.shell().status("Reading", file.display()).ok();
let input_file = input::read_code(&manifest, &mut registry, code).expect("Unable to read file");
cargo_cfg
.shell()
.verbose(|shell| shell.status("Processing", format_args!("{input_file:#?}")))
.ok();
if input_file.scope.has_glob_use {
cargo_cfg.shell().warn("Your code contains glob use statements (e.g. `use std::io::prelude::*;`). Those can lead to incomplete link generation.").ok();
}
let out = if args.out.is_relative() {
env::current_dir().unwrap().join(args.out)
} else {
args.out
};
let exit_code = if args.check {
cargo_cfg.shell().status("Reading", out.display()).ok();
match File::open(&out) {
Ok(mut file) => {
let check =
verify::check_up2date(cargo_cfg.shell(), input_file, &template, &mut file)
.expect("Failed to check readme");
check.print(cargo_cfg.shell());
check.into()
},
Err(e) if e.kind() == io::ErrorKind::NotFound => {
cargo_cfg
.shell()
.error(&format!("File not found: {}", out.display()))
.ok();
ExitCode::FAILURE
},
Err(e) => panic!("Unable to open file {}: {e}", out.display())
}
} else {
cargo_cfg.shell().status("Writing", out.display()).ok();
let outfilename = out.file_name().expect("Unable to get output file name");
if outfilename.to_string_lossy() == "-" {
output::emit(input_file, &template, &mut io::stdout())
.expect("Unable to write to stdout!");
} else {
let mut file = File::create(&out).expect("Unable to create output file");
output::emit(input_file, &template, &mut file).expect("Unable to write output file");
};
ExitCode::SUCCESS
};
cargo_cfg.release_package_cache_lock();
exit_code
}
fn init_git_transports(config: &CargoConfig) {
match cargo::ops::needs_custom_http_transport(config) {
Ok(true) => {},
_ => return
}
let handle = match cargo::ops::http_handle(config) {
Ok(handle) => handle,
Err(..) => return
};
#[allow(unsafe_code)]
unsafe {
git2_curl::register(handle);
}
}