diff --git a/clippy.toml b/clippy.toml index dc063ae9..938f67e3 100644 --- a/clippy.toml +++ b/clippy.toml @@ -1,2 +1,2 @@ avoid-breaking-exported-api = false -doc-valid-idents = ["PostgreSQL", "MySQL", "SQLite", "OpenAPI", ".."] +doc-valid-idents = ["PostgreSQL", "MySQL", "SQLite", "OpenAPI", "RESTful", ".."] diff --git a/cot-cli/Cargo.toml b/cot-cli/Cargo.toml index 849af9a0..0c2fa70a 100644 --- a/cot-cli/Cargo.toml +++ b/cot-cli/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "cot-cli" version = "0.5.0" -description = "The Rust web framework for lazy developers - CLI tool." +description = "Command-line interface for the Cot web framework" categories = ["command-line-utilities", "web-programming"] edition.workspace = true rust-version.workspace = true diff --git a/cot-cli/src/args.rs b/cot-cli/src/args.rs index 9b09f4f6..45cac3bc 100644 --- a/cot-cli/src/args.rs +++ b/cot-cli/src/args.rs @@ -35,7 +35,7 @@ pub enum Commands { pub struct ProjectNewArgs { /// Path to the directory to create the new project in pub path: PathBuf, - /// Set the resulting crate name (defaults to the directory name) + /// Set the resulting crate name [default: the directory name] #[arg(long)] pub name: Option, #[command(flatten)] @@ -52,7 +52,7 @@ pub enum MigrationCommands { #[derive(Debug, Args)] pub struct MigrationListArgs { - /// Path to the crate directory to list migrations for [default: current + /// Path to the crate directory to list migrations for [default: current /// directory] pub path: Option, } @@ -62,11 +62,11 @@ pub struct MigrationMakeArgs { /// Path to the crate directory to generate migrations for [default: current /// directory] pub path: Option, - /// Name of the app to use in the migration (default: crate name) + /// Name of the app to use in the migration [default: crate name] #[arg(long)] pub app_name: Option, - /// Directory to write the migrations to (default: migrations/ directory - /// in the crate's src/ directory) + /// Directory to write the migrations to [default: the migrations/ directory + /// in the crate's src/ directory] #[arg(long)] pub output_dir: Option, } diff --git a/cot-cli/src/migration_generator.rs b/cot-cli/src/migration_generator.rs index 7dc40dcf..da3b538d 100644 --- a/cot-cli/src/migration_generator.rs +++ b/cot-cli/src/migration_generator.rs @@ -143,8 +143,8 @@ impl MigrationGenerator { Ok(migrations) } - /// Generate migrations and return internal structures that can be used to - /// generate source code. + /// Generates migrations and returns an intermediate structure that can be + /// converted into Rust source code. pub fn generate_migrations_as_generated_from_files( &self, source_files: Vec, @@ -829,14 +829,12 @@ impl MigrationProcessor { Ok(Self { migrations }) } - /// Returns the latest (in the order of applying migrations) versions of the - /// models that are marked as migration models, that means the latest - /// version of each migration model. + /// Returns the most recent versions of all models found across all + /// migrations. /// /// This is useful for generating migrations - we can compare the latest - /// version of the model in the source code with the latest version of the - /// model in the migrations (returned by this method) and generate the - /// necessary operations. + /// version of the model in the source code with the most recent version in + /// the migrations and generate the necessary operations. #[must_use] fn latest_models(&self) -> Vec { let mut migration_models: HashMap = HashMap::new(); @@ -859,10 +857,18 @@ impl MigrationProcessor { .name .split('_') .nth(1) - .with_context(|| format!("migration number not found: {}", last_migration.name))? + .with_context(|| { + format!( + "the migration number was not found: {}", + last_migration.name + ) + })? .parse::() .with_context(|| { - format!("unable to parse migration number: {}", last_migration.name) + format!( + "unable to parse the migration number: {}", + last_migration.name + ) })?; let migration_number = last_migration_number + 1; diff --git a/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_elvish.snap b/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_elvish.snap index 3b91306a..cd7d23fe 100644 --- a/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_elvish.snap +++ b/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_elvish.snap @@ -44,7 +44,7 @@ set edit:completion:arg-completer[cot] = {|@words| cand help 'Print this message or the help of the given subcommand(s)' } &'cot;new'= { - cand --name 'Set the resulting crate name (defaults to the directory name)' + cand --name 'Set the resulting crate name [default: the directory name]' cand --cot-path 'Use `cot` from the specified path instead of a published crate' cand --use-git 'Use the latest `cot` version from git instead of a published crate' cand -v 'Increase logging verbosity' @@ -74,8 +74,8 @@ set edit:completion:arg-completer[cot] = {|@words| cand --help 'Print help' } &'cot;migration;make'= { - cand --app-name 'Name of the app to use in the migration (default: crate name)' - cand --output-dir 'Directory to write the migrations to (default: migrations/ directory in the crate''s src/ directory)' + cand --app-name 'Name of the app to use in the migration [default: crate name]' + cand --output-dir 'Directory to write the migrations to [default: the migrations/ directory in the crate''s src/ directory]' cand -v 'Increase logging verbosity' cand --verbose 'Increase logging verbosity' cand -q 'Decrease logging verbosity' diff --git a/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_fish.snap b/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_fish.snap index 2287fd23..ac01602f 100644 --- a/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_fish.snap +++ b/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_fish.snap @@ -44,7 +44,7 @@ complete -c cot -n "__fish_cot_needs_command" -f -a "new" -d 'Create a new Cot p complete -c cot -n "__fish_cot_needs_command" -f -a "migration" -d 'Manage migrations for a Cot project' complete -c cot -n "__fish_cot_needs_command" -f -a "cli" -d 'Manage Cot CLI' complete -c cot -n "__fish_cot_needs_command" -f -a "help" -d 'Print this message or the help of the given subcommand(s)' -complete -c cot -n "__fish_cot_using_subcommand new" -l name -d 'Set the resulting crate name (defaults to the directory name)' -r +complete -c cot -n "__fish_cot_using_subcommand new" -l name -d 'Set the resulting crate name [default: the directory name]' -r complete -c cot -n "__fish_cot_using_subcommand new" -l cot-path -d 'Use `cot` from the specified path instead of a published crate' -r -F complete -c cot -n "__fish_cot_using_subcommand new" -l use-git -d 'Use the latest `cot` version from git instead of a published crate' complete -c cot -n "__fish_cot_using_subcommand new" -s v -l verbose -d 'Increase logging verbosity' @@ -59,8 +59,8 @@ complete -c cot -n "__fish_cot_using_subcommand migration; and not __fish_seen_s complete -c cot -n "__fish_cot_using_subcommand migration; and __fish_seen_subcommand_from list" -s v -l verbose -d 'Increase logging verbosity' complete -c cot -n "__fish_cot_using_subcommand migration; and __fish_seen_subcommand_from list" -s q -l quiet -d 'Decrease logging verbosity' complete -c cot -n "__fish_cot_using_subcommand migration; and __fish_seen_subcommand_from list" -s h -l help -d 'Print help' -complete -c cot -n "__fish_cot_using_subcommand migration; and __fish_seen_subcommand_from make" -l app-name -d 'Name of the app to use in the migration (default: crate name)' -r -complete -c cot -n "__fish_cot_using_subcommand migration; and __fish_seen_subcommand_from make" -l output-dir -d 'Directory to write the migrations to (default: migrations/ directory in the crate\'s src/ directory)' -r -F +complete -c cot -n "__fish_cot_using_subcommand migration; and __fish_seen_subcommand_from make" -l app-name -d 'Name of the app to use in the migration [default: crate name]' -r +complete -c cot -n "__fish_cot_using_subcommand migration; and __fish_seen_subcommand_from make" -l output-dir -d 'Directory to write the migrations to [default: the migrations/ directory in the crate\'s src/ directory]' -r -F complete -c cot -n "__fish_cot_using_subcommand migration; and __fish_seen_subcommand_from make" -s v -l verbose -d 'Increase logging verbosity' complete -c cot -n "__fish_cot_using_subcommand migration; and __fish_seen_subcommand_from make" -s q -l quiet -d 'Decrease logging verbosity' complete -c cot -n "__fish_cot_using_subcommand migration; and __fish_seen_subcommand_from make" -s h -l help -d 'Print help' diff --git a/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_powershell.snap b/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_powershell.snap index 78390381..a7e9a07f 100644 --- a/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_powershell.snap +++ b/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_powershell.snap @@ -48,7 +48,7 @@ Register-ArgumentCompleter -Native -CommandName 'cot' -ScriptBlock { break } 'cot;new' { - [CompletionResult]::new('--name', '--name', [CompletionResultType]::ParameterName, 'Set the resulting crate name (defaults to the directory name)') + [CompletionResult]::new('--name', '--name', [CompletionResultType]::ParameterName, 'Set the resulting crate name [default: the directory name]') [CompletionResult]::new('--cot-path', '--cot-path', [CompletionResultType]::ParameterName, 'Use `cot` from the specified path instead of a published crate') [CompletionResult]::new('--use-git', '--use-git', [CompletionResultType]::ParameterName, 'Use the latest `cot` version from git instead of a published crate') [CompletionResult]::new('-v', '-v', [CompletionResultType]::ParameterName, 'Increase logging verbosity') @@ -81,8 +81,8 @@ Register-ArgumentCompleter -Native -CommandName 'cot' -ScriptBlock { break } 'cot;migration;make' { - [CompletionResult]::new('--app-name', '--app-name', [CompletionResultType]::ParameterName, 'Name of the app to use in the migration (default: crate name)') - [CompletionResult]::new('--output-dir', '--output-dir', [CompletionResultType]::ParameterName, 'Directory to write the migrations to (default: migrations/ directory in the crate''s src/ directory)') + [CompletionResult]::new('--app-name', '--app-name', [CompletionResultType]::ParameterName, 'Name of the app to use in the migration [default: crate name]') + [CompletionResult]::new('--output-dir', '--output-dir', [CompletionResultType]::ParameterName, 'Directory to write the migrations to [default: the migrations/ directory in the crate''s src/ directory]') [CompletionResult]::new('-v', '-v', [CompletionResultType]::ParameterName, 'Increase logging verbosity') [CompletionResult]::new('--verbose', '--verbose', [CompletionResultType]::ParameterName, 'Increase logging verbosity') [CompletionResult]::new('-q', '-q', [CompletionResultType]::ParameterName, 'Decrease logging verbosity') diff --git a/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_zsh.snap b/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_zsh.snap index 9eae91bd..91430383 100644 --- a/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_zsh.snap +++ b/cot-cli/tests/snapshot_testing/cli/snapshots/cli__snapshot_testing__cli__completions_zsh.snap @@ -46,7 +46,7 @@ _cot() { case $line[1] in (new) _arguments "${_arguments_options[@]}" : \ -'--name=[Set the resulting crate name (defaults to the directory name)]:NAME:_default' \ +'--name=[Set the resulting crate name \[default\: the directory name\]]:NAME:_default' \ '--cot-path=[Use \`cot\` from the specified path instead of a published crate]:COT_PATH:_files' \ '--use-git[Use the latest \`cot\` version from git instead of a published crate]' \ '*-v[Increase logging verbosity]' \ @@ -84,13 +84,13 @@ _arguments "${_arguments_options[@]}" : \ '(-v --verbose)*--quiet[Decrease logging verbosity]' \ '-h[Print help]' \ '--help[Print help]' \ -'::path -- Path to the crate directory to list migrations for \[default\: current directory\]:_files' \ +'::path -- Path to the crate directory to list migrations for \[default\: current directory\]:_files' \ && ret=0 ;; (make) _arguments "${_arguments_options[@]}" : \ -'--app-name=[Name of the app to use in the migration (default\: crate name)]:APP_NAME:_default' \ -'--output-dir=[Directory to write the migrations to (default\: migrations/ directory in the crate'\''s src/ directory)]:OUTPUT_DIR:_files' \ +'--app-name=[Name of the app to use in the migration \[default\: crate name\]]:APP_NAME:_default' \ +'--output-dir=[Directory to write the migrations to \[default\: the migrations/ directory in the crate'\''s src/ directory\]]:OUTPUT_DIR:_files' \ '*-v[Increase logging verbosity]' \ '*--verbose[Increase logging verbosity]' \ '(-v --verbose)*-q[Decrease logging verbosity]' \ diff --git a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help.snap b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help.snap index 13a0cde4..710c81f2 100644 --- a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help.snap +++ b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help.snap @@ -8,7 +8,7 @@ info: success: true exit_code: 0 ----- stdout ----- -The Rust web framework for lazy developers - CLI tool. +Command-line interface for the Cot web framework Usage: cot [OPTIONS] diff --git a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_migration_list.snap b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_migration_list.snap index 76088626..f87813e2 100644 --- a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_migration_list.snap +++ b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_migration_list.snap @@ -15,7 +15,7 @@ List all migrations for a Cot project Usage: cot migration list [OPTIONS] [PATH] Arguments: - [PATH] Path to the crate directory to list migrations for [default: current directory] + [PATH] Path to the crate directory to list migrations for [default: current directory] Options: -v, --verbose... Increase logging verbosity diff --git a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_migration_make.snap b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_migration_make.snap index ef42c218..90eb57e0 100644 --- a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_migration_make.snap +++ b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_migration_make.snap @@ -18,10 +18,10 @@ Arguments: [PATH] Path to the crate directory to generate migrations for [default: current directory] Options: - --app-name Name of the app to use in the migration (default: crate name) + --app-name Name of the app to use in the migration [default: crate name] -v, --verbose... Increase logging verbosity - --output-dir Directory to write the migrations to (default: migrations/ - directory in the crate's src/ directory) + --output-dir Directory to write the migrations to [default: the migrations/ + directory in the crate's src/ directory] -q, --quiet... Decrease logging verbosity -h, --help Print help diff --git a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_new.snap b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_new.snap index 2795730c..4e4d857e 100644 --- a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_new.snap +++ b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__help_new.snap @@ -17,7 +17,7 @@ Arguments: Path to the directory to create the new project in Options: - --name Set the resulting crate name (defaults to the directory name) + --name Set the resulting crate name [default: the directory name] -v, --verbose... Increase logging verbosity -q, --quiet... Decrease logging verbosity --use-git Use the latest `cot` version from git instead of a published crate diff --git a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__long_help.snap b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__long_help.snap index 114b4736..0f46b54d 100644 --- a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__long_help.snap +++ b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__long_help.snap @@ -8,7 +8,7 @@ info: success: true exit_code: 0 ----- stdout ----- -The Rust web framework for lazy developers - CLI tool. +Command-line interface for the Cot web framework Usage: cot [OPTIONS] diff --git a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__no_args.snap b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__no_args.snap index 6c3cd089..6cd3549f 100644 --- a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__no_args.snap +++ b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__no_args.snap @@ -9,7 +9,7 @@ exit_code: 2 ----- stdout ----- ----- stderr ----- -The Rust web framework for lazy developers - CLI tool. +Command-line interface for the Cot web framework Usage: cot [OPTIONS] diff --git a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__short_help.snap b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__short_help.snap index 73dea59b..d2cc816d 100644 --- a/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__short_help.snap +++ b/cot-cli/tests/snapshot_testing/help/snapshots/cli__snapshot_testing__help__short_help.snap @@ -8,7 +8,7 @@ info: success: true exit_code: 0 ----- stdout ----- -The Rust web framework for lazy developers - CLI tool. +Command-line interface for the Cot web framework Usage: cot [OPTIONS] diff --git a/cot-codegen/src/symbol_resolver.rs b/cot-codegen/src/symbol_resolver.rs index 49ee479d..24d57efa 100644 --- a/cot-codegen/src/symbol_resolver.rs +++ b/cot-codegen/src/symbol_resolver.rs @@ -163,7 +163,7 @@ impl SymbolResolver { /// a `use` statement for a given type, but also, for instance, the type is /// defined in the current module. /// -/// For instance, for `use std::collections::HashMap;` the `VisibleSymbol ` +/// For instance, for `use std::collections::HashMap;` the `VisibleSymbol` /// would be: /// ``` /// use cot_codegen::symbol_resolver::{VisibleSymbol, VisibleSymbolKind}; diff --git a/cot-core/src/body.rs b/cot-core/src/body.rs index 59ee68e3..8d4a2fd7 100644 --- a/cot-core/src/body.rs +++ b/cot-core/src/body.rs @@ -143,9 +143,8 @@ impl Body { /// /// # Errors /// - /// This method returns an error if reading the body fails. - /// - /// If the body is larger than the limit, an error is returned. + /// This method returns an error if reading the body fails, or if the body + /// is larger than the specified limit. /// /// # Examples /// diff --git a/cot-core/src/handler.rs b/cot-core/src/handler.rs index b4593326..2232aed2 100644 --- a/cot-core/src/handler.rs +++ b/cot-core/src/handler.rs @@ -49,8 +49,7 @@ pub trait RequestHandler { /// /// # Errors /// - /// This method can return an error if the request handler fails to handle - /// the request. + /// This method can return an error if it fails to handle the request. fn handle(&self, request: Request) -> impl Future> + Send; } diff --git a/cot-core/src/html.rs b/cot-core/src/html.rs index 00066911..bdbd8ce9 100644 --- a/cot-core/src/html.rs +++ b/cot-core/src/html.rs @@ -193,7 +193,7 @@ impl HtmlTag { /// /// # Safety /// - /// This function will escape the attribute value. Note that it does not + /// This function escapes the attribute value. Note that it does not /// escape the attribute name. /// /// # Panics @@ -226,7 +226,7 @@ impl HtmlTag { /// /// # Safety /// - /// This function will not escape the attribute name. + /// This function does not escape the attribute name. /// /// # Panics /// diff --git a/cot-core/src/json.rs b/cot-core/src/json.rs index eb6c4f0d..e866817b 100644 --- a/cot-core/src/json.rs +++ b/cot-core/src/json.rs @@ -7,7 +7,7 @@ /// /// Note that this is just a newtype wrapper around data and does not provide /// any content validation. It is primarily useful as a request extractor and -/// response type for REST-ful endpoints. +/// response type for RESTful endpoints. /// /// # Examples /// diff --git a/cot-core/src/response.rs b/cot-core/src/response.rs index d19ef210..f9643578 100644 --- a/cot-core/src/response.rs +++ b/cot-core/src/response.rs @@ -1,12 +1,12 @@ use crate::{Body, StatusCode}; - mod into_response; /// Derive macro for the [`IntoResponse`] trait. /// /// This macro can be applied to enums to automatically implement the /// [`IntoResponse`] trait. The enum must consist of tuple variants with -/// exactly one field each, where each field type implements [`IntoResponse`]. +/// exactly one field each, with each variant containing a single field that +/// implements [`IntoResponse`]. /// /// # Requirements /// @@ -68,7 +68,7 @@ mod private { } /// Extension trait for [`http::Response`] that provides helper methods for -/// working with HTTP response. +/// working with HTTP responses. /// /// # Sealed /// @@ -95,7 +95,7 @@ pub trait ResponseExt: Sized + private::Sealed { /// /// This creates a new [`Response`] object with a status code of /// [`StatusCode::SEE_OTHER`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status/303) - /// and a location header set to the provided location. + /// and a `Location` header set to the provided location. /// /// # Examples /// diff --git a/cot-macros/src/lib.rs b/cot-macros/src/lib.rs index 558b4b2b..70d3e943 100644 --- a/cot-macros/src/lib.rs +++ b/cot-macros/src/lib.rs @@ -72,15 +72,19 @@ pub fn derive_admin_model(input: TokenStream) -> TokenStream { /// use this type; the migration engine will generate the migration model /// types for you. /// -/// Migration models have two major uses. The first is so that the migration -/// engine uses knows what was the state of model at the time the last +/// Migration models have two major uses. First, they ensure that the +/// migration engine knows what state the model was in at the time the last /// migration was generated. This allows the engine to automatically detect -/// the changes and generate the necessary migration code. The second use is -/// to allow custom code in the migrations: you might want the migration to -/// fill in some data, for instance. You can't use the actual model for this -/// because the model might have changed since the migration was generated. -/// You can, however, use the migration model, which will always represent -/// the state of the model at the time the migration runs. +/// the changes and generate the necessary migration code. Second, they allow +/// custom code in migrations: you might want the migration to fill in some +/// data, for example. After the migration has been created, though, the model +/// might have changed. If you tried to use the application model in the +/// migration code (which always represents the latest state of the model), it +/// might not match the actual database schema at the time the migration is +/// applied. You can use the migration model to ensure that your custom code +/// operates exactly on the schema that is present at the time the migration +/// is applied. +/// /// ``` /// // In a migration file /// use cot::db::model; @@ -168,7 +172,7 @@ pub fn cachetest(_args: TokenStream, input: TokenStream) -> TokenStream { /// An attribute macro that defines an `async` test function for a Cot-powered /// app. /// -/// This is pretty much an equivalent to `#[tokio::test]` provided so that you +/// This is equivalent to `#[tokio::test]`, but is provided so that you /// don't have to declare `tokio` as a dependency in your tests. /// /// # Examples diff --git a/cot/src/admin.rs b/cot/src/admin.rs index a503c592..1b5a15ee 100644 --- a/cot/src/admin.rs +++ b/cot/src/admin.rs @@ -456,8 +456,8 @@ pub trait AdminModelManager: Send + Sync { /// /// Returns an error if the object with the given ID does not exist. /// - /// Returns an error if the object could not be removed, for instance - /// due to a database error. + /// Returns an error if the object could not be removed, for example, + /// a database error. async fn remove_by_id(&self, request: &mut Request, object_id: &str) -> cot::Result<()>; } @@ -597,8 +597,8 @@ pub trait AdminModel: Any + Send + 'static { /// /// # Errors /// - /// Returns an error if the object could not be saved, for instance - /// due to a database error. + /// Returns an error if the object could not be saved, for example, + /// a database error. async fn save_from_request( request: &mut Request, object_id: Option<&str>, @@ -612,8 +612,8 @@ pub trait AdminModel: Any + Send + 'static { /// /// Returns an error if the object with the given ID does not exist. /// - /// Returns an error if the object could not be removed, for instance - /// due to a database error. + /// Returns an error if the object could not be removed, for example, + /// a database error. async fn remove_by_id(request: &mut Request, object_id: &str) -> cot::Result<()> where Self: Sized; @@ -625,12 +625,12 @@ pub trait AdminModel: Any + Send + 'static { /// /// ``` /// use cot::admin::AdminApp; -/// use cot::project::WithConfig; -/// use cot::{AppBuilder, Project, ProjectContext}; +/// use cot::project::RegisterAppsContext; +/// use cot::{AppBuilder, Project}; /// /// struct MyProject; /// impl Project for MyProject { -/// fn register_apps(&self, apps: &mut AppBuilder, _context: &ProjectContext) { +/// fn register_apps(&self, apps: &mut AppBuilder, _context: &RegisterAppsContext) { /// apps.register_with_views(AdminApp::new(), "/admin"); /// } /// } diff --git a/cot/src/auth.rs b/cot/src/auth.rs index f9841cfa..e6bc9acc 100644 --- a/cot/src/auth.rs +++ b/cot/src/auth.rs @@ -37,7 +37,7 @@ const ERROR_PREFIX: &str = "failed to authenticate user:"; #[derive(Debug, Error)] #[non_exhaustive] pub enum AuthError { - /// The password hash that is passed to [`PasswordHash::new`] is invalid. + /// The password hash that was provided to [`PasswordHash::new`] is invalid. #[error("{ERROR_PREFIX} password hash is invalid")] PasswordHashInvalid, /// An error occurred while accessing the session object. @@ -154,7 +154,7 @@ pub trait User { /// Returns the user's session authentication hash. /// - /// This used to verify that the session hash stored in the session + /// This is used to verify that the session hash stored in the session /// object is valid. If the session hash is not valid, the user is /// logged out. For instance, /// [`DatabaseUser`](db::DatabaseUser) implements this method @@ -164,9 +164,9 @@ pub trait User { /// /// The session auth hash should always be the same for the same secret key, /// unless something has changed in the user's data that should invalidate - /// the session (e.g. password change). Moreover, if a user implementation - /// returns [`Some`] session hash for some secret key A, it should also - /// return [`Some`] session hash for any other secret key B. + /// the session (for example, a password change). Moreover, if a user + /// implementation returns [`Some`] session hash for some secret key A, it + /// should also return [`Some`] session hash for any other secret key B. /// /// If this method returns `None`, the session hash is not checked. /// @@ -247,7 +247,7 @@ pub enum UserId { /// ``` /// use cot::auth::UserId; /// - /// let user_id = UserId::String("forty_two@exmaple.com".to_string()); + /// let user_id = UserId::String("forty_two@example.com".to_string()); /// ``` String(String), } @@ -314,7 +314,8 @@ impl Debug for UserWrapper { /// An anonymous, unauthenticated user. /// /// This is used to represent a user that is not authenticated. It is returned -/// by the [`Auth::user()`] method when there is no active user session. +/// by the [`Auth::user()`] method when there is no active user session or when +/// the user has been logged out. #[derive(Debug, Copy, Clone, Default)] pub struct AnonymousUser; @@ -482,8 +483,9 @@ pub struct PasswordHash(String); impl PasswordHash { /// Creates a new password hash object from a string. /// - /// Note that this method takes the hash directly. If you need to hash a - /// password, use [`PasswordHash::from_password`] instead. + /// Note that this method takes the hash directly and does not perform any + /// hashing. If you need to hash a password, use the + /// [`from_password`](Self::from_password) method instead. /// /// # Examples /// @@ -534,13 +536,13 @@ impl PasswordHash { /// Verifies a password against the hash. /// - /// * If the password is valid, returns [`PasswordVerificationResult::Ok`]. - /// * If the password is valid but the hash is obsolete, returns - /// [`PasswordVerificationResult::OkObsolete`] with the new hash - /// calculated with the currently preferred algorithm. The new hash should - /// be saved to the database. - /// * If the password is invalid, returns - /// [`PasswordVerificationResult::Invalid`]. + /// This method returns one of the following values: + /// + /// * [`PasswordVerificationResult::Ok`]: The password is valid. + /// * [`PasswordVerificationResult::OkObsolete`]: The password is valid, but + /// the hash is obsolete. The new hash, calculated with the currently + /// preferred algorithm, is provided and should be saved to the database. + /// * [`PasswordVerificationResult::Invalid`]: The password is invalid. /// /// # Examples /// @@ -638,9 +640,9 @@ impl TryFrom for PasswordHash { pub enum PasswordVerificationResult { /// The password is valid. Ok, - /// The password is valid, but the hash is obsolete. The new hash calculated - /// with the currently preferred algorithm is provided, and it should be - /// saved to the database. + /// The password is valid, but the hash is obsolete. The new hash, which was + /// calculated with the currently preferred algorithm, is provided and + /// should be saved to the database. OkObsolete(PasswordHash), /// The password is invalid. Invalid, diff --git a/cot/src/auth/db.rs b/cot/src/auth/db.rs index 938e41b0..b7cf90b2 100644 --- a/cot/src/auth/db.rs +++ b/cot/src/auth/db.rs @@ -1,7 +1,7 @@ //! Database-backed user authentication backend. //! //! This module provides a user type and an authentication backend that stores -//! the user data in a database using the Cot ORM. +//! user data in a database using the Cot ORM. use std::any::Any; use std::borrow::Cow; @@ -66,11 +66,11 @@ impl DatabaseUser { } } - /// Create a new user and save it to the database. + /// Creates a new user and saves it to the database. /// /// # Errors /// - /// Returns an error if the user could not be saved to the database. + /// Returns an error if the user could not be saved. /// /// # Example /// @@ -115,8 +115,8 @@ impl DatabaseUser { Ok(user) } - /// Get a user by their integer ID. Returns [`None`] if the user does not - /// exist. + /// Retrieves a user by their integer ID. It returns [`None`] if the user + /// does not exist. /// /// # Errors /// @@ -164,8 +164,8 @@ impl DatabaseUser { Ok(db_user) } - /// Get a user by their username. Returns [`None`] if the user does not - /// exist. + /// Retrieves a user by their username. It returns [`None`] if the user does + /// not exist. /// /// # Errors /// @@ -215,7 +215,7 @@ impl DatabaseUser { Ok(db_user) } - /// Authenticate a user. + /// Authenticates a user using the provided credentials. /// /// # Errors /// @@ -261,7 +261,7 @@ impl DatabaseUser { } } - /// Get the ID of the user. + /// Returns the ID of the user. /// /// # Example /// @@ -304,7 +304,7 @@ impl DatabaseUser { } } - /// Get the username of the user. + /// Returns the username of the user. /// /// # Example /// @@ -410,7 +410,7 @@ impl DatabaseUserCredentials { Self { username, password } } - /// Get the username of the user. + /// Returns the username of the user. /// /// # Example /// @@ -427,7 +427,7 @@ impl DatabaseUserCredentials { &self.username } - /// Get the password of the user. + /// Returns the password of the user. /// /// # Example /// diff --git a/cot/src/cache.rs b/cot/src/cache.rs index ed3106c6..a51f84fc 100644 --- a/cot/src/cache.rs +++ b/cot/src/cache.rs @@ -292,8 +292,7 @@ impl Cache { Ok(result) } - /// Stores a value in the cache with the default expiration time of 5 - /// minutes. + /// Stores a value in the cache with the default expiration time. /// /// The value will be serialized to JSON before storage. If the key already /// exists, the value will be overwritten. @@ -469,7 +468,7 @@ impl Cache { /// /// // Check that cache is empty /// let size = cache.approx_size().await?; - /// assert_eq!(size, 0); // 0 + /// assert_eq!(size, 0); /// /// # Ok(()) /// # } @@ -613,7 +612,6 @@ impl Cache { /// value, stores the result in the cache with the default expiration /// time, and returns the computed value. /// - /// /// # Errors /// /// Returns an error if the computation fails, the value cannot be diff --git a/cot/src/cache/store.rs b/cot/src/cache/store.rs index 78a84dac..10f4c406 100644 --- a/cot/src/cache/store.rs +++ b/cot/src/cache/store.rs @@ -2,8 +2,8 @@ //! //! This module defines a generic `CacheStore` trait and common types used by //! in-memory, file and Redis-backed cache implementations. The main goal is to -//! provide a simple asynchronous interface for putting, getting, and managing -//! cached values, optionally with expiration policies. +//! provide a simple asynchronous interface for storing, retrieving, and +//! managing cached values, optionally with expiration policies. pub mod memory; #[cfg(feature = "redis")] @@ -50,14 +50,14 @@ pub trait CacheStore: Send + Sync + 'static { /// /// # Errors /// - /// This method can return error if there is an issue retrieving the key. + /// This method can return an error if there is an issue retrieving the key. fn get(&self, key: &str) -> impl Future>> + Send; /// Insert a value under the given key. /// /// # Errors /// - /// This method can return error if there is an issue inserting the + /// This method can return an error if there is an issue inserting the /// key-value pair. fn insert( &self, @@ -70,14 +70,14 @@ pub trait CacheStore: Send + Sync + 'static { /// /// # Errors /// - /// This method can return error if there is an issue removing the key. + /// This method can return an error if there is an issue removing the key. fn remove(&self, key: &str) -> impl Future> + Send; /// Clear all entries in the cache. /// /// # Errors /// - /// This method can return error if there is an issue clearing the cache. + /// This method can return an error if there is an issue clearing the cache. fn clear(&self) -> impl Future> + Send; /// Get an approximate count of entries in the cache. @@ -87,15 +87,16 @@ pub trait CacheStore: Send + Sync + 'static { /// /// # Errors /// - /// This method can return error if there is an issue retrieving the length. + /// This method can return an error if there is an issue retrieving the + /// length. fn approx_size(&self) -> impl Future> + Send; /// Returns `true` if the cache contains the specified key. /// /// # Errors /// - /// This method can return error if there is an issue checking the presence - /// of the key. + /// This method can return an error if there is an issue checking the + /// presence of the key. fn contains_key(&self, key: &str) -> impl Future> + Send; } diff --git a/cot/src/cache/store/memory.rs b/cot/src/cache/store/memory.rs index b290fa20..2ce3ea63 100644 --- a/cot/src/cache/store/memory.rs +++ b/cot/src/cache/store/memory.rs @@ -58,8 +58,9 @@ type InMemoryMap = HashMap)>; /// An in-memory cache store implementation. /// -/// This store keeps all cache entries in memory using a thread-safe hashmap. -/// It's primarily useful for development and testing environments. +/// This is an in-memory implementation of the [`CacheStore`] trait that uses a +/// thread-safe hashmap to store entries. It's primarily useful for development +/// and testing environments. /// /// # Examples /// ``` @@ -72,7 +73,7 @@ pub struct Memory { } impl Memory { - /// Create a new, empty `Memory` cache store. + /// Creates a new, empty `Memory` cache store. /// /// # Examples /// ``` diff --git a/cot/src/cache/store/redis.rs b/cot/src/cache/store/redis.rs index 4d2a6a88..305f8b6d 100644 --- a/cot/src/cache/store/redis.rs +++ b/cot/src/cache/store/redis.rs @@ -1,7 +1,9 @@ //! Redis cache store implementation. //! -//! This store uses Redis as the backend for caching. +//! This is a Redis-backed implementation of the [`CacheStore`] trait. +//! //! # Examples +//! //! ```no_run //! # use cot::cache::store::redis::Redis; //! # use cot::cache::store::CacheStore; @@ -74,7 +76,7 @@ impl From for CacheStoreError { /// A Redis-backed cache store implementation. /// -/// This store uses Redis as the backend for caching. +/// This is a Redis-backed implementation of the [`CacheStore`] trait. /// /// # Examples /// ``` @@ -89,7 +91,7 @@ pub struct Redis { } impl Redis { - /// Creates and configures a new Redis cache store. + /// Creates and configures a new Redis cache store instance. /// /// This initializes a connection pool to the Redis server specified by the /// provided URL. @@ -98,8 +100,8 @@ impl Redis { /// /// Returns [`RedisCacheStoreError::InvalidConnectionString`] if the /// provided URL is not a valid Redis URL - /// and [`RedisCacheStoreError::PoolCreation`] if the connection pool could - /// not be created. + /// and [`RedisCacheStoreError::PoolCreation`] if an error occurs during + /// connection pool creation. /// /// # Examples /// diff --git a/cot/src/cli.rs b/cot/src/cli.rs index c57442a4..97652a2e 100644 --- a/cot/src/cli.rs +++ b/cot/src/cli.rs @@ -121,7 +121,7 @@ impl Cli { /// /// # Panics /// - /// Panics if a CLI task with given name has been registered already. + /// Panics if a task with the same name has already been registered. /// /// # Examples /// diff --git a/cot/src/common_types.rs b/cot/src/common_types.rs index 1df260f2..a120afe0 100644 --- a/cot/src/common_types.rs +++ b/cot/src/common_types.rs @@ -210,7 +210,7 @@ impl Url { self.0.as_str() } - /// Converts the `Url` into a owned `String` representation. + /// Converts the `Url` into an owned `String` representation. /// /// # Examples /// ``` @@ -240,8 +240,11 @@ impl Url { /// Returns the host part of the URL, if present. /// - /// This typically includes the domain name or IP address. + /// This typically includes the domain name or IP address. It returns + /// [`None`] if the URL has no host. + /// /// # Example + /// /// ``` /// use cot::common_types::Url; /// @@ -418,8 +421,8 @@ impl DatabaseField for Url { pub struct Email(EmailAddress); impl Email { - /// Creates a new `Email` from a string, validating that it's a proper email - /// address. + /// Creates a new `Email` from a string, validating that it is a proper + /// email address. /// /// # Errors /// diff --git a/cot/src/config.rs b/cot/src/config.rs index 2cd25369..218245e9 100644 --- a/cot/src/config.rs +++ b/cot/src/config.rs @@ -87,7 +87,7 @@ pub struct ProjectConfig { /// ``` pub register_panic_hook: bool, /// The secret key used for signing cookies and other sensitive data. This - /// is a cryptographic key, should be kept secret, and should a set to a + /// is a cryptographic key, should be kept secret, and should be set to a /// random and unique value for each project. /// /// When you want to rotate the secret key, you can move the current key to @@ -302,8 +302,7 @@ impl ProjectConfig { /// /// This is useful for development purposes, where you want to have a /// configuration that you can just run as quickly as possible. This is - /// mainly useful for tests and other things that are run in the local - /// environment. + /// mainly useful for tests and other local development activities. /// /// Note that what this function returns exactly is not guaranteed to be /// the same across different versions of Cot. It's meant to be used as a @@ -505,8 +504,7 @@ impl Timeout { /// /// # Panics /// - /// This function will panic if the timeout variant is `After` and the - /// `insertion_time` is `None`. + /// Panics if the timeout variant is `After` and `insertion_time` is `None`. /// /// # Examples /// @@ -620,7 +618,7 @@ pub struct CacheConfig { /// Timeout for cache operations. /// /// This controls how long to wait for cache operations to complete before - /// timing out. The default is 300 seconds(5 minutes). + /// timing out. The default is 300 seconds (5 minutes). /// /// # Examples /// @@ -1314,7 +1312,7 @@ pub enum SessionStoreTypeConfig { /// Database-backed session storage. /// /// This stores session data in the configured database. This requires the - /// "db" and "json" features enabled. + /// "db" and "json" features to be enabled. #[cfg(all(feature = "db", feature = "json"))] Database, @@ -1855,8 +1853,8 @@ pub enum EmailTransportTypeConfig { /// The URL format is: /// `scheme://user:password@host:port/?ehlo_domain=domain&tls=TLS`. /// - /// `user` (username) and `password` are optional in the case the - /// server does not require authentication. + /// `user` (username) and `password` are optional if the server does not + /// require authentication. /// When `port` is not specified, it is automatically determined based /// on the `scheme` used. /// `tls` is used to specify whether STARTTLS should be used for the diff --git a/cot/src/db.rs b/cot/src/db.rs index ba6f1ed2..445dd972 100644 --- a/cot/src/db.rs +++ b/cot/src/db.rs @@ -72,7 +72,7 @@ pub enum DatabaseError { /// Error when applying migrations. #[error("{ERROR_PREFIX} error when applying migrations: {0}")] MigrationError(#[from] migrations::MigrationEngineError), - /// An object could not be found in the database. + /// A record could not be found in the database. #[error("{ERROR_PREFIX} record with primary key `{primary_key}` not found in the database")] RecordNotFound { /// The primary key of the record that was not found. @@ -174,7 +174,7 @@ pub trait Model: Sized + Send + 'static { /// The primary key type of the model. type PrimaryKey: PrimaryKey; - /// The name of the app this model is defined in. + /// The name of the app in which this model is defined. const APP_NAME: &'static str; /// The name of the table in the database. @@ -868,7 +868,7 @@ impl Database { /// # Errors /// /// This method can return an error if the connection to the database could - /// not be closed gracefully, for instance because the connection has + /// not be closed gracefully, for example, because the connection has /// already been dropped. /// /// # Examples diff --git a/cot/src/db/migrations.rs b/cot/src/db/migrations.rs index 67659494..0c6414f6 100644 --- a/cot/src/db/migrations.rs +++ b/cot/src/db/migrations.rs @@ -22,7 +22,8 @@ pub enum MigrationEngineError { MigrationSortError(#[from] MigrationSorterError), } -/// A migration engine that can run migrations. +/// A migration engine responsible for managing and applying database +/// migrations. /// /// # Examples /// @@ -133,7 +134,7 @@ impl MigrationEngine { /// /// # Errors /// - /// Throws an error if any of the migrations fail to apply, or if there is + /// Returns an error if any of the migrations fail to apply, or if there is /// an error while interacting with the database, or if there is an /// error while marking a migration as applied. /// @@ -428,7 +429,7 @@ impl Operation { /// /// # Errors /// - /// Throws an error if the operation fails to apply. + /// Returns an error if the operation fails to apply. /// /// # Examples /// @@ -510,7 +511,7 @@ impl Operation { /// /// # Errors /// - /// Throws an error if the operation fails to apply. + /// Returns an error if the operation fails to apply. /// /// # Examples /// diff --git a/cot/src/form.rs b/cot/src/form.rs index dfc01f4d..fcfb62fa 100644 --- a/cot/src/form.rs +++ b/cot/src/form.rs @@ -75,15 +75,15 @@ pub enum FormError { #[error("{ERROR_PREFIX} request error: {error}")] #[non_exhaustive] RequestError { - /// The error that occurred while processing the request. + /// The underlying error that occurred during request processing. #[from] error: Box, }, - /// An error occurred while processing a multipart form. + /// The underlying error that occurred during multipart form processing. #[error("{ERROR_PREFIX} multipart error: {error}")] #[non_exhaustive] MultipartError { - /// The error that occurred while processing the multipart form. + /// The underlying error that occurred during multipart form processing. #[from] error: FormFieldValueError, }, @@ -108,7 +108,7 @@ pub enum FormResult { impl FormResult { /// Unwraps the form result, panicking if the form validation failed. /// - /// This should only be used in tests or in cases where the form validation + /// This should only be used in tests or when the form validation /// is guaranteed to pass. /// /// # Panics @@ -159,13 +159,13 @@ pub enum FormFieldValidationError { max_value: String, }, /// The field value is an ambiguous datetime. - #[error("This is an ambiguous datetime: {datetime}.")] + #[error("The datetime value `{datetime}` is ambiguous.")] AmbiguousDateTime { /// The ambiguous datetime value. datetime: NaiveDateTime, }, /// The field value is a non-existent local datetime. - #[error("Local datetime {datetime} does not exist for the given timezone {timezone}.")] + #[error("Local datetime {datetime} does not exist for the specified timezone {timezone}.")] NonExistentLocalDateTime { /// The non-existent local datetime value. datetime: NaiveDateTime, @@ -584,7 +584,7 @@ pub trait DynFormField: Display { fn dyn_id(&self) -> &str; /// Returns the string value of the form field if any has been set (and - /// makes sense for the field type). + /// is applicable to the field type). fn dyn_value(&self) -> Option<&str>; /// Sets the value of the form field. @@ -623,7 +623,8 @@ pub trait AsFormField { /// The form field type associated with the field. type Type: FormField; - /// Creates a new form field with the given options and custom options. + /// Creates a new form field with the provided generic and type-specific + /// options. /// /// This method is used to create a new instance of the form field with the /// given options and custom options. The options are used to set the diff --git a/cot/src/middleware.rs b/cot/src/middleware.rs index ca946e2b..8fa68f06 100644 --- a/cot/src/middleware.rs +++ b/cot/src/middleware.rs @@ -110,7 +110,7 @@ pub struct SessionMiddleware { } impl SessionMiddleware { - /// Crates a new instance of [`SessionMiddleware`]. + /// Creates a new instance of [`SessionMiddleware`]. #[must_use] pub fn new(store: S) -> Self { let layer = SessionManagerLayer::new(SessionStoreWrapper::new(Arc::new(store))); diff --git a/cot/src/openapi.rs b/cot/src/openapi.rs index af26bfa7..42d5b7e3 100644 --- a/cot/src/openapi.rs +++ b/cot/src/openapi.rs @@ -1,9 +1,8 @@ //! OpenAPI integration for Cot. //! //! This module provides traits and utilities for generating OpenAPI -//! documentation for Cot applications. The idea is to be able to use Cot's -//! existing request handlers and extractors to generate OpenAPI documentation -//! automatically. +//! documentation for Cot applications. It allows using Cot's existing request +//! handlers and extractors to generate OpenAPI documentation automatically. //! //! # Usage //! @@ -119,7 +118,8 @@ use cot_core::handler::{BoxRequestHandler, RequestHandler, handle_all_parameters /// This macro can be applied to enums to automatically implement the /// [`ApiOperationResponse`] trait for OpenAPI documentation generation. /// The enum must consist of tuple variants with exactly one field each, -/// where each field type implements [`ApiOperationResponse`]. +/// with each variant containing a single field that implements +/// [`ApiOperationResponse`]. /// /// **Note**: This macro only implements [`ApiOperationResponse`]. If you also /// need [`IntoResponse`], you must derive it separately or implement it @@ -255,8 +255,10 @@ impl Default for RouteContext<'_> { } } -/// Returns the OpenAPI path item for the route - a collection of different -/// HTTP operations (GET, POST, etc.) at a given URL. +/// Trait for types that can be converted into an OpenAPI path item. +/// +/// An OpenAPI path item is a collection of different HTTP operations (GET, +/// POST, etc.) at a given URL. /// /// You usually shouldn't need to implement this directly. Instead, it's easiest /// to use [`ApiMethodRouter`](crate::router::method::openapi::ApiMethodRouter). @@ -371,6 +373,9 @@ pub trait AsApiRoute { pub trait AsApiOperation { /// Returns the OpenAPI operation for the route. /// + /// Returns [`None`] if the operation should be hidden from the OpenAPI + /// specification. + /// /// # Examples /// /// ``` diff --git a/cot/src/project.rs b/cot/src/project.rs index 8420855d..786c7eaf 100644 --- a/cot/src/project.rs +++ b/cot/src/project.rs @@ -79,9 +79,9 @@ use crate::{Body, Error, cli, error_page}; /// * session management /// * etc. /// -/// Each app can have its own set of URLs that it can handle which can be -/// mounted on the project's router, its own set of middleware, database -/// migrations (which can depend on other apps), etc. +/// Each app can have its own set of URLs that can be mounted on the project's +/// router, its own set of middlewares, database migrations (which can depend on +/// other apps), etc. #[async_trait] pub trait App: Send + Sync { /// The name of the app. @@ -405,7 +405,7 @@ pub trait Project { /// /// # Panics /// - /// Note that this handler is exempt of the typical panic handling + /// Note that this handler is exempt from the typical panic handling /// machinery in Cot. This means that if this handler panics, no /// response will be sent to a user. Because of that, you should /// avoid panicking here and return [`Err`] instead. @@ -435,7 +435,8 @@ pub trait Project { } /// An alias for `ProjectContext` in appropriate phase for use with the -/// [`Project::register_apps`] method. +/// [`Project::register_apps`] method. This represents the `ProjectContext` +/// during the [`WithConfig`] phase. pub type RegisterAppsContext = ProjectContext; /// An alias for `ProjectContext` in appropriate phase for use with the @@ -1050,7 +1051,7 @@ struct LoadConfig { impl_into_cot_error!(LoadConfig); impl Bootstrapper { - /// Builds the Cot project instance. + /// Builds the initialized Cot project instance. /// /// This is the final step in the bootstrapping process. It initializes the /// project with the given configuration and returns a [`Bootstrapper`] @@ -1135,7 +1136,7 @@ impl Bootstrapper { } impl Bootstrapper { - /// Builds the Cot project instance. + /// Builds the initialized Cot project instance. /// /// This is the final step in the bootstrapping process. It initializes the /// project with the given configuration and returns a [`Bootstrapper`] @@ -1344,12 +1345,13 @@ impl Bootstrapper { } impl Bootstrapper { - /// Builds the Cot project instance. + /// Builds the initialized Cot project instance. /// /// This is the final step in the bootstrapping process. It initializes the /// project with the given configuration and returns a [`Bootstrapper`] /// instance that contains the project's context and handler. - /// /// You shouldn't have to use this method directly most of the time. + /// + /// You shouldn't have to use this method directly most of the time. /// It's mainly useful for controlling the bootstrapping process in /// custom [`CliTask`](cli::CliTask)s. /// diff --git a/cot/src/request.rs b/cot/src/request.rs index d6499934..42e7ca4a 100644 --- a/cot/src/request.rs +++ b/cot/src/request.rs @@ -2,7 +2,7 @@ //! //! Cot uses the [`Request`](http::Request) type from the [`http`] crate //! to represent incoming HTTP requests. However, it also provides a -//! [`RequestExt`] trait that contain various helper methods for working with +//! [`RequestExt`] trait that contains various helper methods for working with //! HTTP requests. These methods are used to access the application context, //! project configuration, path parameters, and more. You probably want to have //! a `use` statement for [`RequestExt`] in your code most of the time to be @@ -107,8 +107,8 @@ pub trait RequestExt: private::Sealed { #[must_use] fn router(&self) -> &Arc; - /// Get the app name the current route belongs to, or [`None`] if the - /// request is not routed. + /// Returns the name of the app that the current route belongs to, or + /// [`None`] if the request is not routed. /// /// This is mainly useful for providing context to reverse redirects, where /// you want to redirect to a route in the same app. @@ -127,8 +127,11 @@ pub trait RequestExt: private::Sealed { /// ``` fn app_name(&self) -> Option<&str>; - /// Get the route name, or [`None`] if the request is not routed or doesn't - /// have a route name. + /// Returns the name of the current route. + /// + /// This returns [`None`] if: + /// - the request is not routed, or + /// - the route has no name. /// /// This is mainly useful for use in templates, where you want to know which /// route is being rendered, for instance to mark the active tab. @@ -225,7 +228,7 @@ pub trait RequestExt: private::Sealed { /// /// # Errors /// - /// Throws an error if the content type is not the expected value. + /// Returns an error if the content type is not the expected value. /// /// # Examples /// diff --git a/cot/src/router.rs b/cot/src/router.rs index 9553fd24..b59139c5 100644 --- a/cot/src/router.rs +++ b/cot/src/router.rs @@ -44,9 +44,9 @@ pub mod path; /// A router that can be used to route requests to their respective views. /// -/// This struct is used to route requests to their respective views. It can be -/// created directly by calling the [`Router::with_urls`] method, and that's -/// what is typically done in [`cot::App::router`] implementations. +/// This struct is responsible for routing requests to their respective views. +/// It can be created directly by calling the [`Router::with_urls`] method, and +/// that's what is typically done in [`cot::App::router`] implementations. /// /// # Examples /// @@ -214,14 +214,15 @@ impl Router { self.route(request, &path).await } - /// Get a URL for a view by name. + /// Generates a URL for a view using its name. /// /// Instead of using this method directly, consider using the /// [`reverse!`](crate::reverse) macro which provides much more ergonomic /// way to call this. /// - /// `app_name` is the name of the app that the view should be found in. If - /// `app_name` is `None`, the view will be searched for in any app. + /// The `app_name` parameter specifies the name of the app that the view + /// should be found in. If it is `None`, the view is searched for across all + /// registered apps. /// /// # Errors /// @@ -243,12 +244,13 @@ impl Router { })?) } - /// Get a URL for a view by name. + /// Generates a URL for a view using its name. /// - /// `app_name` is the name of the app that the view should be found in. If - /// `app_name` is `None`, the view will be searched for in any app. + /// The `app_name` parameter specifies the name of the app that the view + /// should be found in. If it is `None`, the view is searched for across all + /// registered apps. /// - /// Returns `None` if the view name is not found. + /// It returns [`None`] if the view name is not found. /// /// # Errors /// @@ -576,10 +578,10 @@ impl Route { } /// Create a new route with the given handler for inclusion in the OpenAPI - /// specs. + /// specifications. /// /// See [`crate::openapi`] module documentation for more details on how to - /// generate OpenAPI specs automatically. + /// generate OpenAPI specifications automatically. /// /// # Examples /// diff --git a/cot/src/session.rs b/cot/src/session.rs index d506527c..bace4fd4 100644 --- a/cot/src/session.rs +++ b/cot/src/session.rs @@ -1,7 +1,7 @@ //! Session management //! -//! This module provides a session management system that allows you to store -//! and retrieve session data. +//! This module provides a session management system that allows for storing +//! and retrieving session data. //! //! # Examples //! diff --git a/cot/src/static_files.rs b/cot/src/static_files.rs index 85bab5c5..f1504106 100644 --- a/cot/src/static_files.rs +++ b/cot/src/static_files.rs @@ -1,7 +1,7 @@ //! Static files middleware. //! -//! This middleware serves static files from the `static` directory of the -//! project. +//! This module provides middleware for serving static files from the `static` +//! directory of the project. use std::collections::HashMap; use std::future::Future; @@ -25,9 +25,9 @@ use crate::config::{StaticFilesConfig, StaticFilesPathRewriteMode}; use crate::project::MiddlewareContext; use crate::response::{Response, ResponseExt}; -/// Macro to define static files by specifying their paths. +/// Macro to define static files by specifying paths. /// -/// The files are included at compile time using the `include_bytes!` macro. +/// The files are embedded at compile time using the `include_bytes!` macro. /// The paths are relative to the `static` directory of the project (under the /// project root, where the `Cargo.toml` file is). /// @@ -268,7 +268,7 @@ impl StaticFile { /// the [`CotApp::static_files`](crate::App::static_files) trait /// method. The middleware serves files from the `/static/` path. /// -/// If a request is made to a path starting with `/static/`, the middleware +/// When a request is made to a path starting with `/static/`, the middleware /// checks if the file exists in the static files collection. If it does, the /// file is served. Otherwise, the request is passed to the inner service. #[derive(Debug, Clone)] diff --git a/cot/src/test.rs b/cot/src/test.rs index f1c60133..e9448be3 100644 --- a/cot/src/test.rs +++ b/cot/src/test.rs @@ -53,7 +53,7 @@ use crate::{Body, Bootstrapper, Project, ProjectContext, Result}; /// A test client for making requests to a Cot project. /// -/// Useful for End-to-End testing Cot projects. +/// This client is useful for end-to-end testing of Cot projects. #[derive(Debug)] pub struct Client { context: Arc, @@ -66,7 +66,7 @@ impl Client { /// /// # Panics /// - /// Panics if the test config could not be loaded. + /// Panics if the test configuration could not be loaded. /// Panics if the project could not be initialized. /// /// # Examples @@ -112,7 +112,7 @@ impl Client { } } - /// Send a GET request to the given path. + /// Sends a GET request to the specified path. /// /// # Errors /// @@ -150,7 +150,7 @@ impl Client { .await } - /// Send a request to the given path. + /// Sends a request to the specified path. /// /// # Errors /// @@ -490,7 +490,8 @@ impl TestRequestBuilder { self } - /// Add a session support to the request builder. + /// Add session support to the request builder. This uses an in-memory + /// session store. /// /// # Examples /// @@ -608,7 +609,7 @@ impl TestRequestBuilder { /// /// # Panics /// - /// Panics if the auth object fails to be created. + /// Panics if the authentication object fails to be created. /// /// # Examples /// @@ -1411,8 +1412,9 @@ impl TestServerBuilder { /// A running test server. /// -/// This is returned by [`TestServerBuilder::start`] and can be used to access -/// the server's URL and close the server. +/// This represents a running Cot server in a background task. It is returned +/// by [`TestServerBuilder::start`] and can be used to access the server's URL +/// and close the server. /// /// # Examples ///