1
0
mirror of https://github.com/google/comprehensive-rust.git synced 2025-06-20 07:55:37 +02:00

Format all Markdown files with dprint (#1157)

This is the result of running `dprint fmt` after removing `src/` from
the list of excluded directories.

This also reformats the Rust code: we might want to tweak this a bit in
the future since some of the changes removes the hand-formatting. Of
course, this formatting can be seen as a mis-feature, so maybe this is
good overall.

Thanks to mdbook-i18n-helpers 0.2, the POT file is nearly unchanged
after this, meaning that all existing translations remain valid! A few
messages were changed because of stray whitespace characters:

     msgid ""
     "Slices always borrow from another object. In this example, `a` has to remain "
    -"'alive' (in scope) for at least as long as our slice. "
    +"'alive' (in scope) for at least as long as our slice."
     msgstr ""

The formatting is enforced in CI and we will have to see how annoying
this is in practice for the many contributors. If it becomes annoying,
we should look into fixing dprint/check#11 so that `dprint` can annotate
the lines that need fixing directly, then I think we can consider more
strict formatting checks.

I added more customization to `rustfmt.toml`. This is to better emulate
the dense style used in the course:

- `max_width = 85` allows lines to take up the full width available in
our code blocks (when taking margins and the line numbers into account).
- `wrap_comments = true` ensures that we don't show very long comments
in the code examples. I edited some comments to shorten them and avoid
unnecessary line breaks — please trim other unnecessarily long comments
when you see them! Remember we're writing code for slides 😄
- `use_small_heuristics = "Max"` allows for things like struct literals
and if-statements to take up the full line width configured above.

The formatting settings apply to all our Rust code right now — I think
we could improve this with https://github.com/dprint/dprint/issues/711
which lets us add per-directory `dprint` configuration files. However,
the `inherit: true` setting is not yet implemented (as far as I can
tell), so a nested configuration file will have to copy most or all of
the top-level file.
This commit is contained in:
Martin Geisler
2023-12-31 00:15:07 +01:00
committed by GitHub
parent f43e72e0ad
commit c9f66fd425
302 changed files with 3067 additions and 2622 deletions

View File

@ -22,16 +22,18 @@
//! Slide -- a single topic (may be represented by multiple mdBook chapters)
//! ```
//!
//! This structure is parsed from the format of the book using a combination of the order in which
//! chapters are listed in `SUMMARY.md` and annotations in the frontmatter of each chapter.
//! This structure is parsed from the format of the book using a combination of
//! the order in which chapters are listed in `SUMMARY.md` and annotations in
//! the frontmatter of each chapter.
//!
//! A book contains a sequence of BookItems, each of which can contain sub-items. A top-level item
//! can potentially introduce a new course, session, segment, and slide all in the same item. If
//! the item has a `course` property in its frontmatter, then it introduces a new course. If it has
//! a `session` property, then it introduces a new session. A top-level item always corresponds
//! 1-to-1 with a segment (as long as it is a chapter), and that item becomes the first slide in
//! that segment. Any other sub-items of the top-level item are treated as further slides in the
//! same segment.
//! A book contains a sequence of BookItems, each of which can contain
//! sub-items. A top-level item can potentially introduce a new course, session,
//! segment, and slide all in the same item. If the item has a `course` property
//! in its frontmatter, then it introduces a new course. If it has a `session`
//! property, then it introduces a new session. A top-level item always
//! corresponds 1-to-1 with a segment (as long as it is a chapter), and that
//! item becomes the first slide in that segment. Any other sub-items of the
//! top-level item are treated as further slides in the same segment.
use crate::frontmatter::{split_frontmatter, Frontmatter};
use crate::markdown::{duration, relative_link};
@ -53,19 +55,19 @@ pub struct Courses {
/// A Course is the level of content at which students enroll.
///
/// Courses are identified by the `course` property in a session's frontmatter. All
/// sessions with the same value for `course` are grouped into a Course.
/// Courses are identified by the `course` property in a session's frontmatter.
/// All sessions with the same value for `course` are grouped into a Course.
#[derive(Default, Debug)]
pub struct Course {
pub name: String,
pub sessions: Vec<Session>,
}
/// A Session is a block of instructional time, containing segments. Typically a full day of
/// instruction contains two sessions: morning and afternoon.
/// A Session is a block of instructional time, containing segments. Typically a
/// full day of instruction contains two sessions: morning and afternoon.
///
/// A session is identified by the `session` property in the session's frontmatter. There can be
/// only one session with a given name in a course.
/// A session is identified by the `session` property in the session's
/// frontmatter. There can be only one session with a given name in a course.
#[derive(Default, Debug)]
pub struct Session {
pub name: String,
@ -95,8 +97,8 @@ pub struct Slide {
}
impl Courses {
/// Extract the course structure from the book. As a side-effect, the frontmatter is stripped
/// from each slide.
/// Extract the course structure from the book. As a side-effect, the
/// frontmatter is stripped from each slide.
pub fn extract_structure(mut book: Book) -> anyhow::Result<(Self, Book)> {
let mut courses = Courses::default();
let mut current_course_name = None;
@ -111,7 +113,8 @@ impl Courses {
let (frontmatter, content) = split_frontmatter(chapter)?;
chapter.content = content;
// If 'course' is given, use that course (if not 'none') and reset the session.
// If 'course' is given, use that course (if not 'none') and reset the
// session.
if let Some(course_name) = &frontmatter.course {
current_session_name = None;
if course_name == "none" {
@ -133,7 +136,8 @@ impl Courses {
);
}
// If we have a course and session, then add this chapter to it as a segment.
// If we have a course and session, then add this chapter to it as a
// segment.
if let (Some(course_name), Some(session_name)) =
(&current_course_name, &current_session_name)
{
@ -145,7 +149,8 @@ impl Courses {
Ok((courses, book))
}
/// Get a reference to a course, adding a new one if none by this name exists.
/// Get a reference to a course, adding a new one if none by this name
/// exists.
fn course_mut(&mut self, name: impl AsRef<str>) -> &mut Course {
let name = name.as_ref();
if let Some(found_idx) =
@ -164,8 +169,8 @@ impl Courses {
self.courses.iter().find(|c| c.name == name)
}
/// Find the slide generated from the given Chapter within these courses, returning the "path"
/// to that slide.
/// Find the slide generated from the given Chapter within these courses,
/// returning the "path" to that slide.
pub fn find_slide(
&self,
chapter: &Chapter,
@ -201,19 +206,15 @@ impl<'a> IntoIterator for &'a Courses {
impl Course {
fn new(name: impl Into<String>) -> Self {
Course {
name: name.into(),
..Default::default()
}
Course { name: name.into(), ..Default::default() }
}
/// Get a reference to a session, adding a new one if none by this name exists.
/// Get a reference to a session, adding a new one if none by this name
/// exists.
fn session_mut(&mut self, name: impl AsRef<str>) -> &mut Session {
let name = name.as_ref();
if let Some(found_idx) = self
.sessions
.iter()
.position(|session| &session.name == name)
if let Some(found_idx) =
self.sessions.iter().position(|session| &session.name == name)
{
return &mut self.sessions[found_idx];
}
@ -222,15 +223,17 @@ impl Course {
self.sessions.last_mut().unwrap()
}
/// Return the total duration of this course, as the sum of all segment durations.
/// Return the total duration of this course, as the sum of all segment
/// durations.
///
/// This includes breaks between segments, but does not count time between between
/// sessions.
/// This includes breaks between segments, but does not count time between
/// between sessions.
pub fn minutes(&self) -> u64 {
self.into_iter().map(|s| s.minutes()).sum()
}
/// Generate a Markdown schedule for this course, for placement at the given path.
/// Generate a Markdown schedule for this course, for placement at the given
/// path.
pub fn schedule(&self, at_source_path: impl AsRef<Path>) -> String {
let mut outline = String::from("Course schedule:\n");
for session in self {
@ -249,7 +252,10 @@ impl Course {
&mut outline,
" * [{}]({}) ({})",
segment.name,
relative_link(&at_source_path, &segment.slides[0].source_paths[0]),
relative_link(
&at_source_path,
&segment.slides[0].source_paths[0]
),
duration(segment.minutes())
)
.unwrap();
@ -270,10 +276,7 @@ impl<'a> IntoIterator for &'a Course {
impl Session {
fn new(name: impl Into<String>) -> Self {
Session {
name: name.into(),
..Default::default()
}
Session { name: name.into(), ..Default::default() }
}
/// Add a new segment to the session, representing sub-items as slides.
@ -297,7 +300,8 @@ impl Session {
Ok(())
}
/// Generate a Markdown outline for this session, for placement at the given path.
/// Generate a Markdown outline for this session, for placement at the given
/// path.
pub fn outline(&self, at_source_path: impl AsRef<Path>) -> String {
let mut outline = String::from("In this session:\n");
for segment in self {
@ -324,7 +328,8 @@ impl Session {
if instructional_time == 0 {
return instructional_time;
}
let breaks = (self.into_iter().filter(|s| s.minutes() > 0).count() - 1) as u64
let breaks = (self.into_iter().filter(|s| s.minutes() > 0).count() - 1)
as u64
* BREAK_DURATION;
instructional_time + breaks
}
@ -341,14 +346,11 @@ impl<'a> IntoIterator for &'a Session {
impl Segment {
fn new(name: impl Into<String>) -> Self {
Segment {
name: name.into(),
..Default::default()
}
Segment { name: name.into(), ..Default::default() }
}
/// Create a slide from a chapter. If `recurse` is true, sub-items of this chapter are
/// included in this slide as well.
/// Create a slide from a chapter. If `recurse` is true, sub-items of this
/// chapter are included in this slide as well.
fn add_slide(
&mut self,
frontmatter: Frontmatter,
@ -364,8 +366,8 @@ impl Segment {
Ok(())
}
/// Return the total duration of this segment (the sum of the durations of the enclosed
/// slides).
/// Return the total duration of this segment (the sum of the durations of
/// the enclosed slides).
pub fn minutes(&self) -> u64 {
self.into_iter().map(|s| s.minutes()).sum()
}
@ -406,10 +408,7 @@ impl<'a> IntoIterator for &'a Segment {
impl Slide {
fn new(frontmatter: Frontmatter, chapter: &Chapter) -> Self {
let mut slide = Self {
name: chapter.name.clone(),
..Default::default()
};
let mut slide = Self { name: chapter.name.clone(), ..Default::default() };
slide.add_frontmatter(&frontmatter);
slide.push_source_path(&chapter.source_path);
slide

View File

@ -25,10 +25,12 @@ pub struct Frontmatter {
}
/// Split a chapter's contents into frontmatter and the remaining contents.
pub fn split_frontmatter(chapter: &Chapter) -> anyhow::Result<(Frontmatter, String)> {
pub fn split_frontmatter(
chapter: &Chapter,
) -> anyhow::Result<(Frontmatter, String)> {
if let Some((frontmatter, content)) = matter(&chapter.content) {
let frontmatter: Frontmatter =
serde_yaml::from_str(&frontmatter).with_context(|| {
let frontmatter: Frontmatter = serde_yaml::from_str(&frontmatter)
.with_context(|| {
format!("error parsing frontmatter in {:?}", chapter.source_path)
})?;

View File

@ -30,7 +30,9 @@ fn main() {
pretty_env_logger::init();
let app = Command::new("mdbook-course")
.about("mdbook preprocessor for Comprehensive Rust")
.subcommand(Command::new("supports").arg(Arg::new("renderer").required(true)));
.subcommand(
Command::new("supports").arg(Arg::new("renderer").required(true)),
);
let matches = app.get_matches();
if let Some(_) = matches.subcommand_matches("supports") {
@ -65,18 +67,11 @@ fn timediff(actual: u64, target: u64) -> String {
}
fn print_summary(fundamentals: &Course) {
eprintln!(
"Fundamentals: {}",
timediff(fundamentals.minutes(), 8 * 3 * 60)
);
eprintln!("Fundamentals: {}", timediff(fundamentals.minutes(), 8 * 3 * 60));
eprintln!("Sessions:");
for session in fundamentals {
eprintln!(
" {}: {}",
session.name,
timediff(session.minutes(), 3 * 60)
);
eprintln!(" {}: {}", session.name, timediff(session.minutes(), 3 * 60));
for segment in session {
eprintln!(" {}: {}", segment.name, duration(segment.minutes()));
}
@ -95,7 +90,9 @@ fn preprocess() -> anyhow::Result<()> {
book.for_each_mut(|chapter| {
if let BookItem::Chapter(chapter) = chapter {
if let Some((course, session, segment, slide)) = courses.find_slide(chapter) {
if let Some((course, session, segment, slide)) =
courses.find_slide(chapter)
{
timing_info::insert_timing_info(slide, chapter);
replacements::replace(
&courses,

View File

@ -14,8 +14,8 @@
use std::path::Path;
/// Given a source_path for the markdown file being rendered and a source_path for the target,
/// generate a relative link.
/// Given a source_path for the markdown file being rendered and a source_path
/// for the target, generate a relative link.
pub fn relative_link(
doc_path: impl AsRef<Path>,
target_path: impl AsRef<Path>,
@ -72,7 +72,10 @@ mod test {
#[test]
fn relative_link_subdir() {
assert_eq!(
relative_link(Path::new("hello-world.md"), Path::new("hello-world/foo.md")),
relative_link(
Path::new("hello-world.md"),
Path::new("hello-world/foo.md")
),
"./hello-world/foo.md".to_string()
);
}
@ -80,7 +83,10 @@ mod test {
#[test]
fn relative_link_parent_dir() {
assert_eq!(
relative_link(Path::new("references/foo.md"), Path::new("hello-world.md")),
relative_link(
Path::new("references/foo.md"),
Path::new("hello-world.md")
),
"../hello-world.md".to_string()
);
}

View File

@ -23,11 +23,7 @@ pub fn insert_timing_info(slide: &Slide, chapter: &mut Chapter) {
{
// Include the minutes in the speaker notes.
let minutes = slide.minutes;
let plural = if slide.minutes == 1 {
"minute"
} else {
"minutes"
};
let plural = if slide.minutes == 1 { "minute" } else { "minutes" };
let mut subslides = "";
if slide.source_paths.len() > 1 {
subslides = "and its sub-slides ";