Skip to content

Commit

Permalink
Auto merge of #32230 - GuillaumeGomez:extend_css, r=alexcrichton
Browse files Browse the repository at this point in the history
Add --extend-css option to rustdoc

Fixes #32223

r? @brson
  • Loading branch information
bors committed Apr 7, 2016
2 parents bf5da36 + 669edfa commit a9f34c8
Show file tree
Hide file tree
Showing 5 changed files with 196 additions and 123 deletions.
106 changes: 85 additions & 21 deletions src/librustc/session/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -785,12 +785,12 @@ impl RustcOptGroup {
self.stability == OptionStability::Stable
}

fn stable(g: getopts::OptGroup) -> RustcOptGroup {
pub fn stable(g: getopts::OptGroup) -> RustcOptGroup {
RustcOptGroup { opt_group: g, stability: OptionStability::Stable }
}

#[allow(dead_code)] // currently we have no "truly unstable" options
fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
pub fn unstable(g: getopts::OptGroup) -> RustcOptGroup {
RustcOptGroup { opt_group: g, stability: OptionStability::Unstable }
}

Expand Down Expand Up @@ -926,33 +926,32 @@ pub fn rustc_short_optgroups() -> Vec<RustcOptGroup> {
pub fn rustc_optgroups() -> Vec<RustcOptGroup> {
let mut opts = rustc_short_optgroups();
opts.extend_from_slice(&[
opt::multi_s("", "extern", "Specify where an external rust library is \
located",
"NAME=PATH"),
opt::multi_s("", "extern", "Specify where an external rust library is located",
"NAME=PATH"),
opt::opt_s("", "sysroot", "Override the system root", "PATH"),
opt::multi_ubnr("Z", "", "Set internal debugging options", "FLAG"),
opt::opt_ubnr("", "error-format",
"How errors and other messages are produced",
"human|json"),
opt::opt_s("", "color", "Configure coloring of output:
auto = colorize, if output goes to a tty (default);
always = always colorize output;
never = never colorize output", "auto|always|never"),
auto = colorize, if output goes to a tty (default);
always = always colorize output;
never = never colorize output", "auto|always|never"),

opt::flagopt_ubnr("", "pretty",
"Pretty-print the input instead of compiling;
valid types are: `normal` (un-annotated source),
`expanded` (crates expanded), or
`expanded,identified` (fully parenthesized, AST nodes with IDs).",
"TYPE"),
"Pretty-print the input instead of compiling;
valid types are: `normal` (un-annotated source),
`expanded` (crates expanded), or
`expanded,identified` (fully parenthesized, AST nodes with IDs).",
"TYPE"),
opt::flagopt_ubnr("", "unpretty",
"Present the input source, unstable (and less-pretty) variants;
valid types are any of the types for `--pretty`, as well as:
`flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
`everybody_loops` (all function bodies replaced with `loop {}`),
`hir` (the HIR), `hir,identified`, or
`hir,typed` (HIR with types for each node).",
"TYPE"),
"Present the input source, unstable (and less-pretty) variants;
valid types are any of the types for `--pretty`, as well as:
`flowgraph=<nodeid>` (graphviz formatted flowgraph for node),
`everybody_loops` (all function bodies replaced with `loop {}`),
`hir` (the HIR), `hir,identified`, or
`hir,typed` (HIR with types for each node).",
"TYPE"),

// new options here should **not** use the `_ubnr` functions, all new
// unstable options should use the short variants to indicate that they
Expand Down Expand Up @@ -1263,7 +1262,6 @@ pub fn get_unstable_features_setting() -> UnstableFeatures {
}

pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {

let mut crate_types: Vec<CrateType> = Vec::new();
for unparsed_crate_type in &list_list {
for part in unparsed_crate_type.split(',') {
Expand All @@ -1287,6 +1285,72 @@ pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateTy
return Ok(crate_types);
}

pub mod nightly_options {
use getopts;
use syntax::feature_gate::UnstableFeatures;
use super::{ErrorOutputType, OptionStability, RustcOptGroup, get_unstable_features_setting};
use session::{early_error, early_warn};

pub fn is_unstable_enabled(matches: &getopts::Matches) -> bool {
is_nightly_build() && matches.opt_strs("Z").iter().any(|x| *x == "unstable-options")
}

fn is_nightly_build() -> bool {
match get_unstable_features_setting() {
UnstableFeatures::Allow | UnstableFeatures::Cheat => true,
_ => false,
}
}

pub fn check_nightly_options(matches: &getopts::Matches, flags: &[RustcOptGroup]) {
let has_z_unstable_option = matches.opt_strs("Z").iter().any(|x| *x == "unstable-options");
let really_allows_unstable_options = match get_unstable_features_setting() {
UnstableFeatures::Disallow => false,
_ => true,
};

for opt in flags.iter() {
if opt.stability == OptionStability::Stable {
continue
}
let opt_name = if opt.opt_group.long_name.is_empty() {
&opt.opt_group.short_name
} else {
&opt.opt_group.long_name
};
if !matches.opt_present(opt_name) {
continue
}
if opt_name != "Z" && !has_z_unstable_option {
early_error(ErrorOutputType::default(),
&format!("the `-Z unstable-options` flag must also be passed to enable \
the flag `{}`",
opt_name));
}
if really_allows_unstable_options {
continue
}
match opt.stability {
OptionStability::Unstable => {
let msg = format!("the option `{}` is only accepted on the \
nightly compiler", opt_name);
early_error(ErrorOutputType::default(), &msg);
}
OptionStability::UnstableButNotReally => {
let msg = format!("the option `{}` is is unstable and should \
only be used on the nightly compiler, but \
it is currently accepted for backwards \
compatibility; this will soon change, \
see issue #31847 for more details",
opt_name);
early_warn(ErrorOutputType::default(), &msg);
}
OptionStability::Stable => {}
}
}
}
}

impl fmt::Display for CrateType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Expand Down
53 changes: 4 additions & 49 deletions src/librustc_driver/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ use rustc_save_analysis as save;
use rustc_trans::back::link;
use rustc::session::{config, Session, build_session, CompileResult};
use rustc::session::config::{Input, PrintRequest, OutputType, ErrorOutputType};
use rustc::session::config::{get_unstable_features_setting, OptionStability};
use rustc::session::config::{get_unstable_features_setting, nightly_options};
use rustc::middle::cstore::CrateStore;
use rustc::lint::Lint;
use rustc::lint;
Expand All @@ -88,7 +88,7 @@ use std::str;
use std::sync::{Arc, Mutex};
use std::thread;

use rustc::session::{early_error, early_warn};
use rustc::session::early_error;

use syntax::ast;
use syntax::parse::{self, PResult};
Expand Down Expand Up @@ -909,64 +909,19 @@ pub fn handle_options(args: &[String]) -> Option<getopts::Matches> {
// (unstable option being used on stable)
// * If we're a historically stable-but-should-be-unstable option then we
// emit a warning that we're going to turn this into an error soon.
let has_z_unstable_options = matches.opt_strs("Z")
.iter()
.any(|x| *x == "unstable-options");
let really_allows_unstable_options = match get_unstable_features_setting() {
UnstableFeatures::Disallow => false,
_ => true,
};
for opt in config::rustc_optgroups() {
if opt.stability == OptionStability::Stable {
continue
}
let opt_name = if opt.opt_group.long_name.is_empty() {
&opt.opt_group.short_name
} else {
&opt.opt_group.long_name
};
if !matches.opt_present(opt_name) {
continue
}
if opt_name != "Z" && !has_z_unstable_options {
let msg = format!("the `-Z unstable-options` flag must also be \
passed to enable the flag `{}`", opt_name);
early_error(ErrorOutputType::default(), &msg);
}
if really_allows_unstable_options {
continue
}
match opt.stability {
OptionStability::Unstable => {
let msg = format!("the option `{}` is only accepted on the \
nightly compiler", opt_name);
early_error(ErrorOutputType::default(), &msg);
}
OptionStability::UnstableButNotReally => {
let msg = format!("the option `{}` is is unstable and should \
only be used on the nightly compiler, but \
it is currently accepted for backwards \
compatibility; this will soon change, \
see issue #31847 for more details",
opt_name);
early_warn(ErrorOutputType::default(), &msg);
}
OptionStability::Stable => {}
}
}
nightly_options::check_nightly_options(&matches, &config::rustc_optgroups());

if matches.opt_present("h") || matches.opt_present("help") {
// Only show unstable options in --help if we *really* accept unstable
// options, which catches the case where we got `-Z unstable-options` on
// the stable channel of Rust which was accidentally allowed
// historically.
usage(matches.opt_present("verbose"),
has_z_unstable_options && really_allows_unstable_options);
nightly_options::is_unstable_enabled(&matches));
return None;
}

// Don't handle -W help here, because we might first load plugins.

let r = matches.opt_strs("Z");
if r.iter().any(|x| *x == "help") {
describe_debug_flags();
Expand Down
12 changes: 10 additions & 2 deletions src/librustdoc/html/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,12 @@ pub struct Page<'a> {
pub ty: &'a str,
pub root_path: &'a str,
pub description: &'a str,
pub keywords: &'a str
pub keywords: &'a str,
}

pub fn render<T: fmt::Display, S: fmt::Display>(
dst: &mut io::Write, layout: &Layout, page: &Page, sidebar: &S, t: &T)
dst: &mut io::Write, layout: &Layout, page: &Page, sidebar: &S, t: &T,
css_file_extension: bool)
-> io::Result<()>
{
write!(dst,
Expand All @@ -49,6 +50,7 @@ r##"<!DOCTYPE html>
<link rel="stylesheet" type="text/css" href="{root_path}rustdoc.css">
<link rel="stylesheet" type="text/css" href="{root_path}main.css">
{css_extension}
{favicon}
{in_header}
Expand Down Expand Up @@ -141,6 +143,12 @@ r##"<!DOCTYPE html>
<script defer src="{root_path}search-index.js"></script>
</body>
</html>"##,
css_extension = if css_file_extension {
format!("<link rel=\"stylesheet\" type=\"text/css\" href=\"{root_path}theme.css\">",
root_path = page.root_path)
} else {
"".to_owned()
},
content = *t,
root_path = page.root_path,
ty = page.ty,
Expand Down
26 changes: 22 additions & 4 deletions src/librustdoc/html/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,9 @@ pub struct SharedContext {
/// The base-URL of the issue tracker for when an item has been tagged with
/// an issue number.
pub issue_tracker_base_url: Option<String>,
/// The given user css file which allow to customize the generated
/// documentation theme.
pub css_file_extension: Option<PathBuf>,
}

/// Indicates where an external crate can be found.
Expand Down Expand Up @@ -411,7 +414,8 @@ pub fn derive_id(candidate: String) -> String {
pub fn run(mut krate: clean::Crate,
external_html: &ExternalHtml,
dst: PathBuf,
passes: HashSet<String>) -> Result<(), Error> {
passes: HashSet<String>,
css_file_extension: Option<PathBuf>) -> Result<(), Error> {
let src_root = match krate.src.parent() {
Some(p) => p.to_path_buf(),
None => PathBuf::new(),
Expand All @@ -429,6 +433,7 @@ pub fn run(mut krate: clean::Crate,
krate: krate.name.clone(),
playground_url: "".to_string(),
},
css_file_extension: css_file_extension.clone(),
};

// Crawl the crate attributes looking for attributes which control how we're
Expand Down Expand Up @@ -637,6 +642,7 @@ fn write_shared(cx: &Context,

// Add all the static files. These may already exist, but we just
// overwrite them anyway to make sure that they're fresh and up-to-date.

write(cx.dst.join("jquery.js"),
include_bytes!("static/jquery-2.1.4.min.js"))?;
write(cx.dst.join("main.js"),
Expand All @@ -647,6 +653,17 @@ fn write_shared(cx: &Context,
include_bytes!("static/rustdoc.css"))?;
write(cx.dst.join("main.css"),
include_bytes!("static/styles/main.css"))?;
if let Some(ref css) = cx.shared.css_file_extension {
let mut content = String::new();
let css = css.as_path();
let mut f = try_err!(File::open(css), css);

try_err!(f.read_to_string(&mut content), css);
let css = cx.dst.join("theme.css");
let css = css.as_path();
let mut f = try_err!(File::create(css), css);
try_err!(write!(f, "{}", &content), css);
}
write(cx.dst.join("normalize.css"),
include_bytes!("static/normalize.css"))?;
write(cx.dst.join("FiraSans-Regular.woff"),
Expand Down Expand Up @@ -932,7 +949,8 @@ impl<'a> SourceCollector<'a> {
keywords: BASIC_KEYWORDS,
};
layout::render(&mut w, &self.scx.layout,
&page, &(""), &Source(contents))?;
&page, &(""), &Source(contents),
self.scx.css_file_extension.is_some())?;
w.flush()?;
self.scx.local_sources.insert(p, href);
Ok(())
Expand Down Expand Up @@ -1294,8 +1312,8 @@ impl Context {
if !cx.render_redirect_pages {
layout::render(&mut writer, &cx.shared.layout, &page,
&Sidebar{ cx: cx, item: it },
&Item{ cx: cx, item: it })?;

&Item{ cx: cx, item: it },
cx.shared.css_file_extension.is_some())?;
} else {
let mut url = repeat("../").take(cx.current.len())
.collect::<String>();
Expand Down
Loading

0 comments on commit a9f34c8

Please sign in to comment.