Debian Codegraph @

scripts/redirect-to-docs.rs

raw symbols SCIP
1 #!/usr/bin/env run-cargo-script
2 /*!
3 Rewrites all HTML files in rustdoc-generated documentation to point to `https://docs.rs/` instead.
4
5 Run this script with `cargo script`.
6
7 ```cargo
8 [package]
9 authors = ["Daniel Keep <[email protected]>"]
10 version = "0.2.0"
11
12 [features]
13 trace-logging = ["env_logger", "log"]
14
15 [dependencies]
16 clap = "2.13.0"
17 env_logger = { version = "0.3.5", optional = true }
18 log = { version = "0.3.6", optional = true }
19 ```
20 */
21 /*
22 Copyright ⓒ 2016 Daniel Keep.
23
24 Licensed under the MIT license (see LICENSE or <http://opensource.org
25 /licenses/MIT>) or the Apache License, Version 2.0 (see LICENSE of
26 <http://www.apache.org/licenses/LICENSE-2.0>), at your option. All
27 files in the project carrying such notice may not be copied, modified,
28 or distributed except according to those terms.
29 */
30 #[macro_use] extern crate clap;
31 #[cfg(feature="trace-logging")] #[macro_use] extern crate log;
32 #[cfg(feature="trace-logging")] extern crate env_logger;
33
34 use std::error::Error as StdError;
35 use std::fs;
36 use std::io;
37 use std::path::{Path, PathBuf};
38 use std::result::Result as StdResult;
39
40 /// Base documentation URI. Use `*` for the latest version.
41 const DOC_URI: &'static str = "https://docs.rs/$CRATE/*/$CRATESAFE/$TAIL";
42
43 /**
44 Source file URI. The reason we aren't more accurate is that docs.rs changes the *structure* of the URIs, and trying to get that exactly right would just be a PITA.
45
46 So I don't bother.
47 */
48 const SRC_URI: &'static str = "https://docs.rs/crate/$CRATE/";
49
50 #[cfg(feature="trace-logging")]
51 macro_rules! trace_ { ($($args:tt)*) => { trace!($($args)*) } }
52 #[cfg(not(feature="trace-logging"))]
53 macro_rules! trace_ { ($($args:tt)*) => {} }
54
55 type Result<T> = StdResult<T, Error>;
56 type Error = Box<StdError>;
57
58 #[derive(Debug)]
59 struct Args {
60 crate_name: String,
61 delete_others: bool,
62 doc_root: PathBuf,
63 dry_run: bool,
64 }
65
66 fn main() {
67 use std::io::Write;
68
69 {
70 #[cfg(feature="trace-logging")]
71 macro_rules! env_logger_init {
72 () => {
73 if let Err(err) = env_logger::init() {
74 let _ = writeln!(std::io::stderr(), "warning: failed to initialise logging: {}", err);
75 }
76 }
77 }
78
79 #[cfg(not(feature="trace-logging"))]
80 macro_rules! env_logger_init {
81 () => {}
82 }
83
84 env_logger_init!();
85 }
86
87 match try_main() {
88 Ok(()) => (),
89 Err(err) => {
90 let _ = writeln!(std::io::stderr(), "error: {}", err);
91 std::process::exit(1);
92 }
93 }
94 }
95
96 fn try_main() -> Result<()> {
97 let args = try!(get_args());
98 let crate_safe_name = args.crate_name.replace("-", "_");
99
100 {
101 let dir = args.doc_root.join(&crate_safe_name);
102 let base_uri = DOC_URI
103 .replace("$CRATESAFE", &crate_safe_name)
104 .replace("$CRATE", &args.crate_name)
105 ;
106 println!("Rewriting {}...", dir.display());
107 try!(rewrite_dir(&args, &dir, &base_uri));
108 }
109
110 {
111 let dir = args.doc_root.join("src").join(&crate_safe_name);
112 let base_uri = SRC_URI
113 .replace("$CRATESAFE", &crate_safe_name)
114 .replace("$CRATE", &args.crate_name)
115 ;
116 println!("Rewriting {}...", dir.display());
117 try!(rewrite_dir(&args, &dir, &base_uri));
118 }
119
120 if args.delete_others {
121 let dir = args.doc_root.join("implementors").join(&crate_safe_name);
122 if dir.is_dir() {
123 println!("Removing {}...", dir.display());
124 if !args.dry_run {
125 try!(fs::remove_dir_all(&dir));
126 }
127 }
128 }
129
130 println!("Done.");
131
132 if args.delete_others {
133 println!("You may also wish to remove files in {}.", args.doc_root.display());
134 }
135
136 if args.dry_run {
137 println!("Dry run complete; see `--help` for details.")
138 }
139
140 Ok(())
141 }
142
143 fn rewrite_dir(args: &Args, dir: &Path, base_uri: &str) -> Result<()> {
144 trace_!("rewrite_dir(_, {:?}, {:?}) {{", dir, base_uri);
145 for de in try!(fs::read_dir(dir)) {
146 let de = try!(de);
147 let fpath = de.path();
148 let ftype = try!(de.file_type());
149 let fname = try!(fpath.file_name()
150 .and_then(|s| s.to_str())
151 .ok_or_else(|| format!("couldn't get file name from {:?}", fpath))
152 );
153
154 if ftype.is_dir() {
155 let new_uri = base_uri.replace("$TAIL", &format!("{}/$TAIL", fname));
156 try!(rewrite_dir(args, &fpath, &new_uri));
157 } else if ftype.is_file() {
158 if fname.ends_with(".html") {
159 let new_uri = base_uri.replace("$TAIL", fname);
160 try!(rewrite_html(args, &fpath, &new_uri));
161 } else {
162 if args.delete_others {
163 print!("- rm {}", fpath.display());
164 try!(flush());
165 if !args.dry_run {
166 try!(fs::remove_file(&fpath));
167 }
168 println!("");
169 }
170 }
171 }
172 }
173 trace_!("rewrite_dir(_, {:?}, {:?}) }}", dir, base_uri);
174 Ok(())
175 }
176
177 fn rewrite_html(args: &Args, path: &Path, uri: &str) -> Result<()> {
178 trace_!("rewrite_html(_, {:?}, {:?})", path, uri);
179 use std::io::{Read, Write};
180
181 // Check to see if this file is *already* doing a redirection.
182 let cur_body = {
183 let f = try!(fs::File::open(path));
184 // We won't bother looking past the first 512 bytes.
185 let mut buf = String::with_capacity(512);
186 try!(f.take(buf.capacity() as u64).read_to_string(&mut buf));
187 buf
188 };
189 if {
190 cur_body.find("</head>")
191 .map(|off| cur_body[..off]
192 .contains(r#"<meta http-equiv="refresh""#))
193 .unwrap_or(false)
194 } {
195 // Already redirecting, no need to do more.
196 println!("- skip {}", path.display());
197 return Ok(())
198 }
199
200 let body = REDIR_TEMPLATE
201 .replace("$CRATE", &args.crate_name)
202 .replace("$DEST", uri)
203 ;
204
205 print!("- redir {}", path.display());
206 try!(flush());
207 if !args.dry_run {
208 let mut f = try!(fs::File::create(path));
209 try!(f.write_all(body.as_bytes()));
210 try!(f.sync_all());
211 }
212 println!(" -> {}", uri);
213 Ok(())
214 }
215
216 fn get_args() -> Result<Args> {
217 use clap::Arg;
218 let matches = clap::App::new("redirect-to-docs.rs")
219 .version(crate_version!())
220 .author(crate_authors!())
221 .about("Rewrites all HTML files in rustdoc-generated documentation \
222 to point to `https://docs.rs/` instead.")
223 .after_help("By default, performs a dry run, listing everything it \
224 intends to do. You should review this output and then re-run \
225 with the --commit flag.\n\
226 \n\
227 Also note that files which contain legacy redirections generated \
228 by `rustdoc` itself will be skipped.")
229 .arg(Arg::with_name("commit")
230 .long("commit")
231 .help("Actually take the requested actions, instead of performing a dry run.")
232 )
233 .arg(Arg::with_name("crate_name")
234 .long("crate-name")
235 .value_name("NAME")
236 .takes_value(true)
237 .required(true)
238 .help("Manually specify the name of the crate being documented.")
239 )
240 .arg(Arg::with_name("delete_others")
241 .long("delete-others")
242 .help("Delete other, non-HTML files.")
243 )
244 .arg(Arg::with_name("doc_root")
245 .long("doc-root")
246 .value_name("PATH")
247 .takes_value(true)
248 .required(true)
249 .help("Manually specify the root directory for the crate documentation.")
250 )
251 .get_matches();
252
253 let commit = matches.is_present("commit");
254 let crate_name = matches.value_of("crate_name").map(String::from).unwrap();
255 let delete_others = matches.is_present("delete_others");
256 let doc_root = matches.value_of("doc_root").map(PathBuf::from).unwrap();
257
258 Ok(Args {
259 crate_name: crate_name,
260 delete_others: delete_others,
261 doc_root: doc_root,
262 dry_run: !commit,
263 })
264 }
265
266 fn flush() -> io::Result<()> {
267 use std::io::Write;
268 std::io::stdout().flush()
269 }
270
271 const REDIR_TEMPLATE: &'static str = r##"<!DOCTYPE html>
272 <html>
273 <head>
274 <meta charset="UTF-8">
275 <title>$CRATE</title>
276 <style type="text/css">
277
278 body {
279 font-family: sans-serif;
280 position: absolute;
281 top: 40%;
282 left: 50%;
283 margin-right: -50%;
284 transform: translate(-50%, -50%);
285 margin-left: auto;
286 margin-top: auto;
287 margin-bottom: auto;
288 }
289
290 </style>
291 <meta http-equiv="refresh" content="0; url=$DEST">
292 </head>
293 <body>
294 <h1><a href="$DEST">Content Moved</a></h1>
295 <p>This documentation is now being hosted on <a href="https://docs.rs/">docs.rs</a>. <a href="$DEST">Follow the redirection</a> if it does not work automatically.</p>
296 </body>
297 </html>
298 "##;