Move error types to mdbook-core

This moves Result and Error to mdbook-core with the anticipation of
using them in user crates. For now, the internal APIs will be using
anyhow directly, but the intent is to transition more of these to
mdbook-core where it makes sense.
This commit is contained in:
Eric Huss 2025-07-21 11:37:46 -07:00
parent 461884f109
commit f51d89ba02
34 changed files with 67 additions and 65 deletions

4
Cargo.lock generated
View file

@ -1297,6 +1297,9 @@ dependencies = [
[[package]] [[package]]
name = "mdbook-core" name = "mdbook-core"
version = "0.5.0-alpha.1" version = "0.5.0-alpha.1"
dependencies = [
"anyhow",
]
[[package]] [[package]]
name = "mdbook-preprocessor" name = "mdbook-preprocessor"
@ -1309,6 +1312,7 @@ dependencies = [
name = "mdbook-remove-emphasis" name = "mdbook-remove-emphasis"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"anyhow",
"mdbook", "mdbook",
"pulldown-cmark 0.12.2", "pulldown-cmark 0.12.2",
"pulldown-cmark-to-cmark", "pulldown-cmark-to-cmark",

View file

@ -21,6 +21,7 @@ repository = "https://github.com/rust-lang/mdBook"
rust-version = "1.85.0" # Keep in sync with installation.md and .github/workflows/main.yml rust-version = "1.85.0" # Keep in sync with installation.md and .github/workflows/main.yml
[workspace.dependencies] [workspace.dependencies]
anyhow = "1.0.98"
mdbook-core = { path = "crates/mdbook-core" } mdbook-core = { path = "crates/mdbook-core" }
[package] [package]
@ -42,7 +43,7 @@ description = "Creates a book from markdown files"
rust-version.workspace = true rust-version.workspace = true
[dependencies] [dependencies]
anyhow = "1.0.71" anyhow.workspace = true
chrono = { version = "0.4.24", default-features = false, features = ["clock"] } chrono = { version = "0.4.24", default-features = false, features = ["clock"] }
clap = { version = "4.3.12", features = ["cargo", "wrap_help"] } clap = { version = "4.3.12", features = ["cargo", "wrap_help"] }
clap_complete = "4.3.2" clap_complete = "4.3.2"

View file

@ -8,6 +8,7 @@ repository.workspace = true
rust-version.workspace = true rust-version.workspace = true
[dependencies] [dependencies]
anyhow.workspace = true
[lints] [lints]
workspace = true workspace = true

View file

@ -5,3 +5,8 @@
/// This is provided as a way for custom preprocessors and renderers to do /// This is provided as a way for custom preprocessors and renderers to do
/// compatibility checks. /// compatibility checks.
pub const MDBOOK_VERSION: &str = env!("CARGO_PKG_VERSION"); pub const MDBOOK_VERSION: &str = env!("CARGO_PKG_VERSION");
/// The error types used in mdbook.
pub mod errors {
pub use anyhow::{Error, Result};
}

View file

@ -1,9 +1,9 @@
//! A basic example of a preprocessor that does nothing. //! A basic example of a preprocessor that does nothing.
use crate::nop_lib::Nop; use crate::nop_lib::Nop;
use anyhow::Error;
use clap::{Arg, ArgMatches, Command}; use clap::{Arg, ArgMatches, Command};
use mdbook::book::Book; use mdbook::book::Book;
use mdbook::errors::Error;
use mdbook::preprocess::{CmdPreprocessor, Preprocessor, PreprocessorContext}; use mdbook::preprocess::{CmdPreprocessor, Preprocessor, PreprocessorContext};
use semver::{Version, VersionReq}; use semver::{Version, VersionReq};
use std::io; use std::io;

View file

@ -4,6 +4,7 @@ version = "0.1.0"
edition.workspace = true edition.workspace = true
[dependencies] [dependencies]
anyhow.workspace = true
mdbook = { path = "../../.." } mdbook = { path = "../../.." }
pulldown-cmark = { version = "0.12.2", default-features = false } pulldown-cmark = { version = "0.12.2", default-features = false }
pulldown-cmark-to-cmark = "18.0.0" pulldown-cmark-to-cmark = "18.0.0"

View file

@ -1,9 +1,9 @@
//! This is a demonstration of an mdBook preprocessor which parses markdown //! This is a demonstration of an mdBook preprocessor which parses markdown
//! and removes any instances of emphasis. //! and removes any instances of emphasis.
use anyhow::Error;
use mdbook::BookItem; use mdbook::BookItem;
use mdbook::book::{Book, Chapter}; use mdbook::book::{Book, Chapter};
use mdbook::errors::Error;
use mdbook::preprocess::{CmdPreprocessor, Preprocessor, PreprocessorContext}; use mdbook::preprocess::{CmdPreprocessor, Preprocessor, PreprocessorContext};
use pulldown_cmark::{Event, Parser, Tag, TagEnd}; use pulldown_cmark::{Event, Parser, Tag, TagEnd};
use std::io; use std::io;

View file

@ -6,8 +6,8 @@ use std::path::{Path, PathBuf};
use super::summary::{Link, SectionNumber, Summary, SummaryItem, parse_summary}; use super::summary::{Link, SectionNumber, Summary, SummaryItem, parse_summary};
use crate::config::BuildConfig; use crate::config::BuildConfig;
use crate::errors::*;
use crate::utils::bracket_escape; use crate::utils::bracket_escape;
use anyhow::{Context, Result};
use log::debug; use log::debug;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};

View file

@ -4,9 +4,9 @@ use std::path::PathBuf;
use super::MDBook; use super::MDBook;
use crate::config::Config; use crate::config::Config;
use crate::errors::*;
use crate::theme; use crate::theme;
use crate::utils::fs::write_file; use crate::utils::fs::write_file;
use anyhow::{Context, Result};
use log::{debug, error, info, trace}; use log::{debug, error, info, trace};
/// A helper for setting up a new book and its directory structure. /// A helper for setting up a new book and its directory structure.

View file

@ -13,6 +13,7 @@ pub use self::book::{Book, BookItem, BookItems, Chapter, load_book};
pub use self::init::BookBuilder; pub use self::init::BookBuilder;
pub use self::summary::{Link, SectionNumber, Summary, SummaryItem, parse_summary}; pub use self::summary::{Link, SectionNumber, Summary, SummaryItem, parse_summary};
use anyhow::{Context, Error, Result, bail};
use log::{debug, error, info, log_enabled, trace, warn}; use log::{debug, error, info, log_enabled, trace, warn};
use std::ffi::OsString; use std::ffi::OsString;
use std::io::{IsTerminal, Write}; use std::io::{IsTerminal, Write};
@ -22,7 +23,6 @@ use tempfile::Builder as TempFileBuilder;
use toml::Value; use toml::Value;
use topological_sort::TopologicalSort; use topological_sort::TopologicalSort;
use crate::errors::*;
use crate::preprocess::{ use crate::preprocess::{
CmdPreprocessor, IndexPreprocessor, LinkPreprocessor, Preprocessor, PreprocessorContext, CmdPreprocessor, IndexPreprocessor, LinkPreprocessor, Preprocessor, PreprocessorContext,
}; };

View file

@ -1,4 +1,4 @@
use crate::errors::*; use anyhow::{Context, Error, Result, bail};
use log::{debug, trace, warn}; use log::{debug, trace, warn};
use memchr::Memchr; use memchr::Memchr;
use pulldown_cmark::{DefaultBrokenLinkCallback, Event, HeadingLevel, Tag, TagEnd}; use pulldown_cmark::{DefaultBrokenLinkCallback, Event, HeadingLevel, Tag, TagEnd};

View file

@ -1,7 +1,7 @@
use super::command_prelude::*; use super::command_prelude::*;
use crate::{get_book_dir, open}; use crate::{get_book_dir, open};
use anyhow::Result;
use mdbook::MDBook; use mdbook::MDBook;
use mdbook::errors::Result;
use std::path::PathBuf; use std::path::PathBuf;
// Create clap subcommand arguments // Create clap subcommand arguments

View file

@ -1,6 +1,7 @@
use super::command_prelude::*; use super::command_prelude::*;
use crate::get_book_dir; use crate::get_book_dir;
use anyhow::Context; use anyhow::Context;
use anyhow::Result;
use mdbook::MDBook; use mdbook::MDBook;
use std::mem::take; use std::mem::take;
use std::path::PathBuf; use std::path::PathBuf;
@ -15,7 +16,7 @@ pub fn make_subcommand() -> Command {
} }
// Clean command implementation // Clean command implementation
pub fn execute(args: &ArgMatches) -> mdbook::errors::Result<()> { pub fn execute(args: &ArgMatches) -> Result<()> {
let book_dir = get_book_dir(args); let book_dir = get_book_dir(args);
let book = MDBook::load(book_dir)?; let book = MDBook::load(book_dir)?;
@ -47,7 +48,7 @@ pub struct Clean {
} }
impl Clean { impl Clean {
fn new(dir: &PathBuf) -> mdbook::errors::Result<Clean> { fn new(dir: &PathBuf) -> Result<Clean> {
let mut files = vec![dir.clone()]; let mut files = vec![dir.clone()];
let mut children = Vec::new(); let mut children = Vec::new();
let mut num_files_removed = 0; let mut num_files_removed = 0;

View file

@ -1,8 +1,8 @@
use crate::get_book_dir; use crate::get_book_dir;
use anyhow::Result;
use clap::{ArgMatches, Command as ClapCommand, arg}; use clap::{ArgMatches, Command as ClapCommand, arg};
use mdbook::MDBook; use mdbook::MDBook;
use mdbook::config; use mdbook::config;
use mdbook::errors::Result;
use std::io; use std::io;
use std::io::Write; use std::io::Write;
use std::process::Command; use std::process::Command;

View file

@ -2,6 +2,7 @@ use super::command_prelude::*;
#[cfg(feature = "watch")] #[cfg(feature = "watch")]
use super::watch; use super::watch;
use crate::{get_book_dir, open}; use crate::{get_book_dir, open};
use anyhow::Result;
use axum::Router; use axum::Router;
use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade}; use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
use axum::routing::get; use axum::routing::get;
@ -9,7 +10,6 @@ use clap::builder::NonEmptyStringValueParser;
use futures_util::StreamExt; use futures_util::StreamExt;
use futures_util::sink::SinkExt; use futures_util::sink::SinkExt;
use mdbook::MDBook; use mdbook::MDBook;
use mdbook::errors::*;
use mdbook::utils::fs::get_404_output_file; use mdbook::utils::fs::get_404_output_file;
use std::net::{SocketAddr, ToSocketAddrs}; use std::net::{SocketAddr, ToSocketAddrs};
use std::path::PathBuf; use std::path::PathBuf;

View file

@ -1,9 +1,9 @@
use super::command_prelude::*; use super::command_prelude::*;
use crate::get_book_dir; use crate::get_book_dir;
use anyhow::Result;
use clap::ArgAction; use clap::ArgAction;
use clap::builder::NonEmptyStringValueParser; use clap::builder::NonEmptyStringValueParser;
use mdbook::MDBook; use mdbook::MDBook;
use mdbook::errors::Result;
use std::path::PathBuf; use std::path::PathBuf;
// Create clap subcommand arguments // Create clap subcommand arguments

View file

@ -1,7 +1,7 @@
use super::command_prelude::*; use super::command_prelude::*;
use crate::{get_book_dir, open}; use crate::{get_book_dir, open};
use anyhow::Result;
use mdbook::MDBook; use mdbook::MDBook;
use mdbook::errors::Result;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
mod native; mod native;

View file

@ -9,7 +9,7 @@
//! # Examples //! # Examples
//! //!
//! ```rust //! ```rust
//! # use mdbook::errors::*; //! # use anyhow::Result;
//! use std::path::PathBuf; //! use std::path::PathBuf;
//! use std::str::FromStr; //! use std::str::FromStr;
//! use mdbook::Config; //! use mdbook::Config;
@ -47,6 +47,8 @@
//! # run().unwrap() //! # run().unwrap()
//! ``` //! ```
use crate::utils::{self, toml_ext::TomlExt};
use anyhow::{Context, Error, Result, bail};
use log::{debug, trace, warn}; use log::{debug, trace, warn};
use serde::{Deserialize, Deserializer, Serialize, Serializer}; use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::collections::HashMap; use std::collections::HashMap;
@ -58,9 +60,6 @@ use std::str::FromStr;
use toml::Value; use toml::Value;
use toml::value::Table; use toml::value::Table;
use crate::errors::*;
use crate::utils::{self, toml_ext::TomlExt};
/// The overall configuration object for MDBook, essentially an in-memory /// The overall configuration object for MDBook, essentially an in-memory
/// representation of `book.toml`. /// representation of `book.toml`.
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]

View file

@ -1,18 +1,16 @@
#![allow(missing_docs)] #![allow(missing_docs)]
pub mod playground_editor; use anyhow::Result;
use log::warn;
pub mod fonts;
#[cfg(feature = "search")]
pub mod searcher;
use std::fs::File; use std::fs::File;
use std::io::Read; use std::io::Read;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use crate::errors::*; pub mod fonts;
use log::warn; pub mod playground_editor;
#[cfg(feature = "search")]
pub mod searcher;
pub static INDEX: &[u8] = include_bytes!("templates/index.hbs"); pub static INDEX: &[u8] = include_bytes!("templates/index.hbs");
pub static HEAD: &[u8] = include_bytes!("templates/head.hbs"); pub static HEAD: &[u8] = include_bytes!("templates/head.hbs");
pub static REDIRECT: &[u8] = include_bytes!("templates/redirect.hbs"); pub static REDIRECT: &[u8] = include_bytes!("templates/redirect.hbs");

View file

@ -93,9 +93,3 @@ pub use crate::book::MDBook;
pub use crate::config::Config; pub use crate::config::Config;
pub use crate::renderer::Renderer; pub use crate::renderer::Renderer;
pub use mdbook_core::MDBOOK_VERSION; pub use mdbook_core::MDBOOK_VERSION;
/// The error types used through out this crate.
pub mod errors {
pub(crate) use anyhow::{Context, bail, ensure};
pub use anyhow::{Error, Result};
}

View file

@ -1,6 +1,6 @@
use super::{Preprocessor, PreprocessorContext}; use super::{Preprocessor, PreprocessorContext};
use crate::book::Book; use crate::book::Book;
use crate::errors::*; use anyhow::{Context, Result, bail, ensure};
use log::{debug, trace, warn}; use log::{debug, trace, warn};
use shlex::Shlex; use shlex::Shlex;
use std::io::{self, Read, Write}; use std::io::{self, Read, Write};

View file

@ -3,7 +3,7 @@ use std::{path::Path, sync::LazyLock};
use super::{Preprocessor, PreprocessorContext}; use super::{Preprocessor, PreprocessorContext};
use crate::book::{Book, BookItem}; use crate::book::{Book, BookItem};
use crate::errors::*; use anyhow::Result;
use log::warn; use log::warn;
/// A preprocessor for converting file name `README.md` to `index.md` since /// A preprocessor for converting file name `README.md` to `index.md` since

View file

@ -1,8 +1,8 @@
use crate::errors::*;
use crate::utils::{ use crate::utils::{
take_anchored_lines, take_lines, take_rustdoc_include_anchored_lines, take_anchored_lines, take_lines, take_rustdoc_include_anchored_lines,
take_rustdoc_include_lines, take_rustdoc_include_lines,
}; };
use anyhow::{Context, Result};
use regex::{CaptureMatches, Captures, Regex}; use regex::{CaptureMatches, Captures, Regex};
use std::fs; use std::fs;
use std::ops::{Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeTo}; use std::ops::{Bound, Range, RangeBounds, RangeFrom, RangeFull, RangeTo};

View file

@ -10,7 +10,7 @@ mod links;
use crate::book::Book; use crate::book::Book;
use crate::config::Config; use crate::config::Config;
use crate::errors::*; use anyhow::Result;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::cell::RefCell; use std::cell::RefCell;

View file

@ -1,11 +1,11 @@
use crate::book::{Book, BookItem}; use crate::book::{Book, BookItem};
use crate::config::{BookConfig, Code, Config, HtmlConfig, Playground, RustEdition}; use crate::config::{BookConfig, Code, Config, HtmlConfig, Playground, RustEdition};
use crate::errors::*;
use crate::renderer::html_handlebars::StaticFiles; use crate::renderer::html_handlebars::StaticFiles;
use crate::renderer::html_handlebars::helpers; use crate::renderer::html_handlebars::helpers;
use crate::renderer::{RenderContext, Renderer}; use crate::renderer::{RenderContext, Renderer};
use crate::theme::{self, Theme}; use crate::theme::{self, Theme};
use crate::utils; use crate::utils;
use crate::utils::fs::get_404_output_file;
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::BTreeMap; use std::collections::BTreeMap;
@ -14,7 +14,7 @@ use std::fs::{self, File};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::LazyLock; use std::sync::LazyLock;
use crate::utils::fs::get_404_output_file; use anyhow::{Context, Result, bail};
use handlebars::Handlebars; use handlebars::Handlebars;
use log::{debug, info, trace, warn}; use log::{debug, info, trace, warn};
use regex::{Captures, Regex}; use regex::{Captures, Regex};

View file

@ -3,17 +3,17 @@ use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::LazyLock; use std::sync::LazyLock;
use anyhow::{Context, Result, bail};
use elasticlunr::{Index, IndexBuilder}; use elasticlunr::{Index, IndexBuilder};
use log::{debug, warn};
use pulldown_cmark::*; use pulldown_cmark::*;
use serde::Serialize;
use crate::book::{Book, BookItem, Chapter}; use crate::book::{Book, BookItem, Chapter};
use crate::config::{Search, SearchChapterSettings}; use crate::config::{Search, SearchChapterSettings};
use crate::errors::*;
use crate::renderer::html_handlebars::StaticFiles; use crate::renderer::html_handlebars::StaticFiles;
use crate::theme::searcher; use crate::theme::searcher;
use crate::utils; use crate::utils;
use log::{debug, warn};
use serde::Serialize;
const MAX_WORD_LENGTH_TO_INDEX: usize = 80; const MAX_WORD_LENGTH_TO_INDEX: usize = 80;

View file

@ -1,9 +1,9 @@
//! Support for writing static files. //! Support for writing static files.
use anyhow::{Context, Result};
use log::{debug, warn}; use log::{debug, warn};
use crate::config::HtmlConfig; use crate::config::HtmlConfig;
use crate::errors::*;
use crate::renderer::html_handlebars::helpers::resources::ResourceHelper; use crate::renderer::html_handlebars::helpers::resources::ResourceHelper;
use crate::theme::{self, Theme, playground_editor}; use crate::theme::{self, Theme, playground_editor};
use crate::utils; use crate::utils;

View file

@ -1,7 +1,7 @@
use crate::book::BookItem; use crate::book::BookItem;
use crate::errors::*;
use crate::renderer::{RenderContext, Renderer}; use crate::renderer::{RenderContext, Renderer};
use crate::utils; use crate::utils;
use anyhow::{Context, Result};
use log::trace; use log::trace;
use std::fs; use std::fs;

View file

@ -11,26 +11,24 @@
//! [For Developers]: https://rust-lang.github.io/mdBook/for_developers/index.html //! [For Developers]: https://rust-lang.github.io/mdBook/for_developers/index.html
//! [RenderContext]: struct.RenderContext.html //! [RenderContext]: struct.RenderContext.html
pub use self::html_handlebars::HtmlHandlebars; use crate::book::Book;
pub use self::markdown_renderer::MarkdownRenderer; use crate::config::Config;
use anyhow::{Context, Result, bail};
mod html_handlebars; use log::{error, info, trace, warn};
mod markdown_renderer; use serde::{Deserialize, Serialize};
use shlex::Shlex; use shlex::Shlex;
use std::collections::HashMap; use std::collections::HashMap;
use std::fs; use std::fs;
use std::io::{self, ErrorKind, Read}; use std::io::{self, ErrorKind, Read};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::process::{Command, Stdio}; use std::process::{Command, Stdio};
use crate::book::Book;
use crate::config::Config;
use crate::errors::*;
use log::{error, info, trace, warn};
use toml::Value; use toml::Value;
use serde::{Deserialize, Serialize}; pub use self::html_handlebars::HtmlHandlebars;
pub use self::markdown_renderer::MarkdownRenderer;
mod html_handlebars;
mod markdown_renderer;
/// An arbitrary `mdbook` backend. /// An arbitrary `mdbook` backend.
/// ///

View file

@ -1,6 +1,6 @@
//! Filesystem utilities and helpers. //! Filesystem utilities and helpers.
use crate::errors::*; use anyhow::{Context, Result};
use log::{debug, trace}; use log::{debug, trace};
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::Write; use std::io::Write;

View file

@ -1,19 +1,19 @@
//! Various helpers and utilities. //! Various helpers and utilities.
pub mod fs; use anyhow::Error;
mod string;
pub(crate) mod toml_ext;
use crate::errors::Error;
use log::error; use log::error;
use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd, html}; use pulldown_cmark::{CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd, html};
use regex::Regex; use regex::Regex;
use std::borrow::Cow; use std::borrow::Cow;
use std::collections::HashMap; use std::collections::HashMap;
use std::fmt::Write; use std::fmt::Write;
use std::path::Path; use std::path::Path;
use std::sync::LazyLock; use std::sync::LazyLock;
pub mod fs;
mod string;
pub(crate) mod toml_ext;
pub use self::string::{ pub use self::string::{
take_anchored_lines, take_lines, take_rustdoc_include_anchored_lines, take_anchored_lines, take_lines, take_rustdoc_include_anchored_lines,
take_rustdoc_include_lines, take_rustdoc_include_lines,

View file

@ -1,8 +1,8 @@
//! Tests for custom preprocessors. //! Tests for custom preprocessors.
use crate::prelude::*; use crate::prelude::*;
use anyhow::Result;
use mdbook::book::Book; use mdbook::book::Book;
use mdbook::errors::Result;
use mdbook::preprocess::{CmdPreprocessor, Preprocessor, PreprocessorContext}; use mdbook::preprocess::{CmdPreprocessor, Preprocessor, PreprocessorContext};
use std::sync::{Arc, Mutex}; use std::sync::{Arc, Mutex};

View file

@ -1,7 +1,7 @@
//! Tests for custom renderers. //! Tests for custom renderers.
use crate::prelude::*; use crate::prelude::*;
use mdbook::errors::Result; use anyhow::Result;
use mdbook::renderer::{RenderContext, Renderer}; use mdbook::renderer::{RenderContext, Renderer};
use snapbox::IntoData; use snapbox::IntoData;
use std::fs::File; use std::fs::File;

View file

@ -2,7 +2,7 @@
use crate::prelude::*; use crate::prelude::*;
use anyhow::Context; use anyhow::Context;
use mdbook::errors::*; use anyhow::Result;
use select::document::Document; use select::document::Document;
use select::predicate::{Attr, Class, Name, Predicate}; use select::predicate::{Attr, Class, Name, Predicate};
use std::fs; use std::fs;