Skip to content

Commit

Permalink
Fix public doctests that are marked ignore (#2976)
Browse files Browse the repository at this point in the history
Doctests on public items should be maintained accurate as the API
changes, so having them be type-checked makes the most sense.

I removed the doctest for the `CacheUpdate` trait as it was really 
out of date and not really possible to fix up.
  • Loading branch information
mkrasnitski committed Sep 20, 2024
1 parent 6f646f1 commit 27cfaff
Show file tree
Hide file tree
Showing 10 changed files with 62 additions and 144 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ docs.

A basic ping-pong bot looks like:

```rust,ignore
```rust
use std::env;

use serenity::async_trait;
Expand Down
90 changes: 1 addition & 89 deletions src/cache/cache_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,98 +5,10 @@ use super::Cache;
/// This may be implemented on a type and used to update the cache via [`Cache::update`].
///
/// **Info**: You may not access the fields of the cache, as they are public for the crate only.
///
/// # Examples
///
/// Creating a custom struct implementation to update the cache with:
///
/// ```rust,ignore
/// use std::collections::hash_map::Entry;
///
/// use serde_json::json;
/// use serenity::cache::{Cache, CacheUpdate};
/// use serenity::model::id::UserId;
/// use serenity::model::user::User;
///
/// // For example, an update to the user's record in the database was
/// // published to a pubsub channel.
/// struct DatabaseUserUpdate {
/// user_avatar: Option<String>,
/// user_discriminator: u16,
/// user_id: UserId,
/// user_is_bot: bool,
/// user_name: String,
/// }
///
/// #[serenity::async_trait]
/// impl CacheUpdate for DatabaseUserUpdate {
/// // A copy of the old user's data, if it existed in the cache.
/// type Output = User;
///
/// async fn update(&mut self, cache: &Cache) -> Option<Self::Output> {
/// // If an entry for the user already exists, update its fields.
/// match cache.users.entry(self.user_id) {
/// Entry::Occupied(entry) => {
/// let user = entry.get();
/// let old_user = user.clone();
///
/// user.bot = self.user_is_bot;
/// user.discriminator = self.user_discriminator;
/// user.id = self.user_id;
///
/// if user.avatar != self.user_avatar {
/// user.avatar = self.user_avatar.clone();
/// }
///
/// if user.name != self.user_name {
/// user.name = self.user_name.clone();
/// }
///
/// // Return the old copy for the user's sake.
/// Some(old_user)
/// },
/// Entry::Vacant(entry) => {
/// // We can convert a [`Value`] to a User for test
/// // purposes.
/// let user = from_value::<User>(json!({
/// "id": self.user_id,
/// "avatar": self.user_avatar.clone(),
/// "bot": self.user_is_bot,
/// "discriminator": self.user_discriminator,
/// "username": self.user_name.clone(),
/// })).expect("Error making user");
///
/// entry.insert(user);
///
/// // There was no old copy, so return None.
/// None
/// },
/// }
/// }
/// }
///
/// # async fn run() {
/// // Create an instance of the cache.
/// let mut cache = Cache::new();
///
/// // This is a sample pubsub message that you might receive from your
/// // database.
/// let mut update_message = DatabaseUserUpdate {
/// user_avatar: None,
/// user_discriminator: 6082,
/// user_id: UserId::new(379740138303127564),
/// user_is_bot: true,
/// user_name: "TofuBot".to_owned(),
/// };
///
/// // Update the cache with the message.
/// cache.update(&mut update_message).await;
/// # }
/// ```
pub trait CacheUpdate {
/// The return type of an update.
///
/// If there is nothing to return, specify this type as an unit (`()`).
/// If there is nothing to return, specify this type to be the unit `()`.
type Output;

/// Updates the cache with the implementation.
Expand Down
4 changes: 2 additions & 2 deletions src/gateway/sharding/shard_messenger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,9 +136,9 @@ impl ShardMessenger {
///
/// Set the current user as playing `"Heroes of the Storm"` and being online:
///
/// ```rust,ignore
/// ```rust,no_run
/// # use serenity::gateway::Shard;
/// # async fn run(shard: Shard) -> Result<(), Box<dyn std::error::Error>> {
/// # async fn run(mut shard: Shard) -> Result<(), Box<dyn std::error::Error>> {
/// use serenity::gateway::ActivityData;
/// use serenity::model::user::OnlineStatus;
///
Expand Down
15 changes: 12 additions & 3 deletions src/model/channel/guild_channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -224,9 +224,18 @@ impl GuildChannel {
///
/// Create an invite that can only be used 5 times:
///
/// ```rust,ignore
/// let builder = CreateBuilder::default().max_uses(5);
/// let invite = channel.create_invite(&context, builder).await;
/// ```rust,no_run
/// # use serenity::builder::CreateInvite;
/// # use serenity::http::Http;
/// # use serenity::model::channel::GuildChannel;
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let channel: GuildChannel = unimplemented!();
/// # let http: Http = unimplemented!();
///
/// let builder = CreateInvite::new().max_uses(5);
/// let invite = channel.create_invite(&http, builder).await;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
Expand Down
36 changes: 11 additions & 25 deletions src/model/guild/member.rs
Original file line number Diff line number Diff line change
Expand Up @@ -259,17 +259,18 @@ impl Member {
///
/// # Examples
///
/// Kick a member from its guild:
///
/// ```rust,ignore
/// Kick a member from the guild:
///
/// ```rust,no_run
/// # use serenity::http::Http;
/// # use serenity::model::guild::Member;
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let http: Http = unimplemented!();
/// # let member: Member = unimplemented!();
/// // assuming a `member` has already been bound
/// match member.kick(None).await {
/// Ok(()) => println!("Successfully kicked member"),
/// Err(Error::Model(ModelError::GuildNotFound)) => {
/// println!("Couldn't determine guild of member");
/// },
/// _ => {},
/// }
/// member.kick(&http, None).await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
Expand Down Expand Up @@ -314,14 +315,6 @@ impl Member {

/// Returns the guild-level permissions for the member.
///
/// # Examples
///
/// ```rust,ignore
/// // assuming there's a `member` variable gotten from anything.
/// println!("The permission bits for the member are: {}",
/// member.permissions(&cache).expect("permissions").bits());
/// ```
///
/// # Errors
///
/// Returns a [`ModelError::GuildNotFound`] if the guild the member's in could not be
Expand Down Expand Up @@ -430,13 +423,6 @@ impl Member {
impl fmt::Display for Member {
/// Mentions the user so that they receive a notification.
///
/// # Examples
///
/// ```rust,ignore
/// // assumes a `member` has already been bound
/// println!("{} is a member!", member);
/// ```
///
/// This is in the format of `<@USER_ID>`.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.user.mention(), f)
Expand Down
27 changes: 20 additions & 7 deletions src/model/guild/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -401,9 +401,18 @@ impl Guild {
///
/// Ban a member and remove all messages they've sent in the last 4 days:
///
/// ```rust,ignore
/// // assumes a `user` and `guild` have already been bound
/// let _ = guild.ban(user, 4, None);
/// ```rust,no_run
/// # use serenity::http::Http;
/// # use serenity::model::guild::Guild;
/// # use serenity::model::id::UserId;
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let http: Http = unimplemented!();
/// # let guild: Guild = unimplemented!();
/// # let user_id: UserId = unimplemented!();
/// // assumes a `user_id` and `guild` have already been bound
/// guild.ban(&http, user_id, 4, None).await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
Expand Down Expand Up @@ -524,10 +533,14 @@ impl Guild {
///
/// Create a guild called `"test"` in the [US West region] with no icon:
///
/// ```rust,ignore
/// use serenity::model::Guild;
///
/// let _guild = Guild::create_guild(&http, "test", None).await;
/// ```rust,no_run
/// # use serenity::http::Http;
/// use serenity::model::guild::Guild;
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let http: Http = unimplemented!();
/// let guild = Guild::create(&http, "test", None).await;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
Expand Down
15 changes: 12 additions & 3 deletions src/model/guild/partial_guild.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,9 +270,18 @@ impl PartialGuild {
///
/// Ban a member and remove all messages they've sent in the last 4 days:
///
/// ```rust,ignore
/// // assumes a `user` and `guild` have already been bound
/// let _ = guild.ban(user, 4);
/// ```rust,no_run
/// # use serenity::http::Http;
/// # use serenity::model::guild::PartialGuild;
/// # use serenity::model::id::UserId;
/// # async fn run() -> Result<(), Box<dyn std::error::Error>> {
/// # let http: Http = unimplemented!();
/// # let guild: PartialGuild = unimplemented!();
/// # let user_id: UserId = unimplemented!();
/// // assumes a `user_id` and `guild` have already been bound
/// guild.ban(&http, user_id, 4, None).await?;
/// # Ok(())
/// # }
/// ```
///
/// # Errors
Expand Down
11 changes: 2 additions & 9 deletions src/model/user.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@ use crate::model::utils::avatar_url;
/// ```rust,ignore
/// use std::num::NonZeroU16;
///
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Deserialize, Serialize)]
/// struct A {
/// #[serde(with = "discriminator")]
Expand Down Expand Up @@ -458,15 +460,6 @@ impl User {
/// Check if a user has a [`Role`]. This will retrieve the [`Guild`] from the [`Cache`] if it
/// is available, and then check if that guild has the given [`Role`].
///
/// # Examples
///
/// Check if a guild has a [`Role`] by Id:
///
/// ```rust,ignore
/// // Assumes a 'guild_id' and `role_id` have already been bound
/// let _ = message.author.has_role(guild_id, role_id);
/// ```
///
/// [`Cache`]: crate::cache::Cache
///
/// # Errors
Expand Down
4 changes: 0 additions & 4 deletions src/model/webhook.rs
Original file line number Diff line number Diff line change
Expand Up @@ -470,10 +470,6 @@ impl Webhook {

/// Returns the url of the webhook.
///
/// ```rust,ignore
/// assert_eq!(hook.url(), "https://discord.com/api/webhooks/245037420704169985/ig5AO-wdVWpCBtUUMxmgsWryqgsW3DChbKYOINftJ4DCrUbnkedoYZD0VOH1QLr-S3sV")
/// ```
///
/// # Errors
///
/// Returns an [`Error::Model`] if the [`Self::token`] is [`None`].
Expand Down
2 changes: 1 addition & 1 deletion src/utils/message_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ impl MessageBuilder {
///
/// Pushing a Rust codeblock:
///
/// ```rust,ignore
/// ```rust,no_run
/// use serenity::utils::MessageBuilder;
///
/// let code = r#"
Expand Down

0 comments on commit 27cfaff

Please sign in to comment.