organize-modules

6
0
Source

Apply private modules with public re-exports pattern for clean API design. Includes conditional visibility for docs and tests. Use when creating modules, organizing mod.rs files, or before creating commits.

Install

mkdir -p .claude/skills/organize-modules && curl -L -o skill.zip "https://mcp.directory/api/skills/download/2483" && unzip -o skill.zip -d .claude/skills/organize-modules && rm skill.zip

Installs to .claude/skills/organize-modules

About this skill

Module Organization Best Practices

When to Use

  • Creating new Rust modules
  • Refactoring module structure
  • Organizing mod.rs files
  • Reviewing code that exposes internal structure
  • Making private types visible to documentation
  • Before creating commits with module changes
  • When user says "organize modules", "refactor modules", "fix module structure", etc.

Instructions

Follow these patterns for clean, maintainable module organization:

Step 1: Apply the Recommended Pattern

Prefer private modules with public re-exports (also known as the barrel export pattern) as the default pattern.

This provides a clean API while maintaining flexibility to refactor internal structure.

// mod.rs - Module coordinator

// Private modules (hide internal structure)
mod constants;
mod types;
mod helpers;

// Public re-exports (expose stable API)
pub use constants::*;
pub use types::*;
pub use helpers::*;

What this achieves:

  • Clean, flat API for users
  • Internal structure is hidden and can be refactored freely
  • No namespace pollution from module names

Step 2: Control Rustfmt Behavior (When Needed)

For mod.rs files with deliberate manual alignment, prevent rustfmt from reformatting:

// mod.rs

#![rustfmt::skip]

// Private modules
mod constants;
mod types;
mod helpers;

// Public re-exports
pub use constants::*;
pub use types::*;
pub use helpers::*;

When to use rustfmt skip:

  • Large mod.rs files with many exports
  • Deliberately structured code alignment for clarity
  • Manual grouping of related items (e.g., test fixtures)
  • Files where organization conveys semantic meaning

When NOT to use:

  • Small, simple mod.rs files
  • When automatic formatting is preferred

Step 3: Apply Conditional Visibility for Docs and Tests

When you need a module to be:

  • Private in production builds (encapsulation)
  • Public for documentation (rustdoc links work)
  • Public for tests (test code can access internals)

Use conditional compilation:

// mod.rs - Conditional visibility

#[cfg(any(test, doc))]
pub mod internal_parser;
#[cfg(not(any(test, doc)))]
mod internal_parser;

// Re-export items for the flat public API
pub use internal_parser::*;

How this works:

  • In doc builds: Module is public → rustdoc can see and link to it
  • In test builds: Module is public → tests can access internals
  • In production builds: Module is private → internal implementation detail

This pattern is frequently used with the write-documentation skill when fixing documentation links to private types.

When to Omit the Fallback Branch

You can skip the #[cfg(not(any(test, doc)))] fallback when the module has no code to compile in production:

// ✅ OK to skip fallback - documentation-only module (no actual code)
#[cfg(any(test, doc))]
pub mod integration_tests_docs;

// ✅ OK to skip fallback - all submodules are #[cfg(test)] anyway
#[cfg(any(test, doc))]
pub mod integration_tests;

Keep the fallback when the module contains code that must compile in production (even if private):

// ✅ Need fallback - module has actual code used in production
#[cfg(any(test, doc))]
pub mod internal_parser;
#[cfg(not(any(test, doc)))]
mod internal_parser;

pub use internal_parser::*;  // Re-exports need the module to exist!

Platform-Specific Modules with Cross-Platform Docs

For modules that are platform-specific but should have docs generated on all platforms, use any(doc, ...) to separate documentation from runtime requirements:

// ✅ Linux-only runtime, but docs build on all platforms
#[cfg(any(doc, all(target_os = "linux", test)))]
pub mod input;
#[cfg(all(target_os = "linux", not(any(test, doc))))]
mod input;

// Re-export also needs the doc condition
#[cfg(any(target_os = "linux", doc))]
pub use input::*;

Key insight: rustdoc runs the Rust compiler internally. When you write #[cfg(all(target_os = "linux", any(test, doc)))], the target_os = "linux" check still excludes macOS/Windows even during doc builds. The doc cfg flag doesn't override other conditions—it's just another flag you can check.

The fix: Use any(doc, ...) to make doc an alternative path:

  • any(doc, all(target_os = "linux", test)) means: "docs on any platform OR tests on Linux"
  • all(target_os = "linux", any(test, doc)) means: "Linux AND (tests OR docs)" — still requires Linux!

When you see broken doc links for platform-specific modules:

// ❌ Broken: Docs won't generate on macOS
#[cfg(all(target_os = "linux", any(test, doc)))]
pub mod linux_only_module;

// ✅ Fixed: Docs generate on all platforms (if module code is platform-agnostic)
#[cfg(any(doc, all(target_os = "linux", test)))]
pub mod linux_only_module;
#[cfg(all(target_os = "linux", not(any(test, doc))))]
mod linux_only_module;

⚠️ Unix Dependency Caveat

The cfg(any(doc, ...)) pattern above assumes the module's code compiles on all platforms. When the module uses Unix-only APIs (e.g., mio::unix::SourceFd, signal_hook, std::os::fd::AsRawFd), restrict doc builds to Unix:

// Module uses Unix-only APIs — restrict doc builds to Unix platforms
#[cfg(any(all(unix, doc), all(target_os = "linux", test)))]
pub mod input;
#[cfg(all(target_os = "linux", not(any(test, doc))))]
mod input;

#[cfg(any(target_os = "linux", all(unix, doc)))]
pub use input::*;

Three-tier hierarchy:

Module dependenciesPatternDocs: LinuxDocs: macOSDocs: Windows
Platform-agnosticcfg(any(doc, ...))
Unix APIscfg(any(all(unix, doc), ...))excluded
Linux-only APIscfg(any(all(target_os = "linux", doc), ...))excludedexcluded

Rule of thumb: Match your doc cfg guard to your dependency's cfg guard in Cargo.toml.

Apply at all levels — If the module is nested, both parent and child need the visibility change. Also update any re-exports:

// Parent module
#[cfg(any(doc, all(target_os = "linux", test)))]
pub mod integration_tests;

// Child modules inside integration_tests/mod.rs
#[cfg(any(doc, all(target_os = "linux", test)))]
pub mod pty_input_test;

// Re-exports
#[cfg(any(target_os = "linux", doc))]
pub use integration_tests::*;

Step 4: Handle Transitive Visibility

Important: If a conditionally public module links to another module in its documentation, that target module must also be conditionally public.

// mod.rs

#[cfg(any(test, doc))]
pub mod paint_impl;  // Contains docs that link to diff_chunks
#[cfg(not(any(test, doc)))]
mod paint_impl;

#[cfg(any(test, doc))]
pub mod diff_chunks;  // Must also be conditionally public!
#[cfg(not(any(test, doc)))]
mod diff_chunks;

// Re-export for public API
pub use paint_impl::*;
pub use diff_chunks::*;

Why: Rustdoc needs to resolve all links in documentation. If paint_impl docs link to diff_chunks, rustdoc must be able to see diff_chunks.

Step 5: Reference in Rustdoc

When linking to conditionally public modules in documentation, use the mod@ prefix:

/// See [`internal_parser`] for implementation details.
///
/// [`internal_parser`]: mod@crate::internal_parser

See the write-documentation skill for complete details on rustdoc links.

Benefits of This Pattern

1. Clean, Flat API

Users import directly without unnecessary nesting:

✅ Good (flat, ergonomic):

use my_module::MyType;
use my_module::CONSTANT;

❌ Bad (exposes internal structure):

use my_module::types::MyType;
use my_module::constants::CONSTANT;

2. Refactoring Freedom

Internal reorganization doesn't break external code:

// You can move items between files freely
// External API stays: use my_module::Item;

// Before:
// mod.rs: pub use types::Item;
// types.rs: pub struct Item;

// After refactoring:
// mod.rs: pub use helpers::Item;  // Changed!
// helpers.rs: pub struct Item;    // Moved!

// External code unaffected:
// use my_module::Item;  // Still works!

3. Avoid Naming Conflicts

Private module names don't pollute the namespace:

// No conflicts with other `constants` modules in the crate
mod constants;  // Private - name hidden
pub use constants::*;  // Items public

// Elsewhere in the crate
mod constants;  // No conflict! This is in a different scope

4. Encapsulation

Module structure is an implementation detail, not part of the API:

// Internal structure can change without breaking compatibility
// v1.0: mod types; pub use types::*;
// v1.1: mod models; pub use models::*;  // Renamed module
// Users don't care!

Decision Trees

When to Use Private Modules + Public Re-exports

✅ Use this pattern when:

  • Module structure is an implementation detail
  • You want a flat, ergonomic API surface
  • Avoiding potential name collisions across the crate
  • Working with small to medium-sized modules with clear responsibilities
  • Building a library with a stable public API

Example scenarios:

  • Utility modules with helpers, types, constants
  • Internal parser implementation
  • Data structure implementations

When NOT to Use This Pattern

❌ Keep modules public when:

1. Module Structure IS the API

Different domains should be explicit:

pub mod frontend;  // Frontend-specific APIs
pub mod backend;   // Backend-specific APIs

// Users: use my_crate::frontend::Component;
// Users: use my_crate::backend::Database;

Why: The separation is meaningful to users. They WANT to know if they're using frontend or backend APIs.

2. Large Feature Domains

When namespacing provides clarity for 100+ items:

pub mod graphics;   // 100+ graphics-related items
pub mod audio;      // 100+ audio-related items
pub mod physics;    // 

---

*Content truncated.*

You might also like

flutter-development

aj-geddes

Build beautiful cross-platform mobile apps with Flutter and Dart. Covers widgets, state management with Provider/BLoC, navigation, API integration, and material design.

641968

drawio-diagrams-enhanced

jgtolentino

Create professional draw.io (diagrams.net) diagrams in XML format (.drawio files) with integrated PMP/PMBOK methodologies, extensive visual asset libraries, and industry-standard professional templates. Use this skill when users ask to create flowcharts, swimlane diagrams, cross-functional flowcharts, org charts, network diagrams, UML diagrams, BPMN, project management diagrams (WBS, Gantt, PERT, RACI), risk matrices, stakeholder maps, or any other visual diagram in draw.io format. This skill includes access to custom shape libraries for icons, clipart, and professional symbols.

590705

godot

bfollington

This skill should be used when working on Godot Engine projects. It provides specialized knowledge of Godot's file formats (.gd, .tscn, .tres), architecture patterns (component-based, signal-driven, resource-based), common pitfalls, validation tools, code templates, and CLI workflows. The `godot` command is available for running the game, validating scripts, importing resources, and exporting builds. Use this skill for tasks involving Godot game development, debugging scene/resource files, implementing game systems, or creating new Godot components.

339397

ui-ux-pro-max

nextlevelbuilder

"UI/UX design intelligence. 50 styles, 21 palettes, 50 font pairings, 20 charts, 8 stacks (React, Next.js, Vue, Svelte, SwiftUI, React Native, Flutter, Tailwind). Actions: plan, build, create, design, implement, review, fix, improve, optimize, enhance, refactor, check UI/UX code. Projects: website, landing page, dashboard, admin panel, e-commerce, SaaS, portfolio, blog, mobile app, .html, .tsx, .vue, .svelte. Elements: button, modal, navbar, sidebar, card, table, form, chart. Styles: glassmorphism, claymorphism, minimalism, brutalism, neumorphism, bento grid, dark mode, responsive, skeuomorphism, flat design. Topics: color palette, accessibility, animation, layout, typography, font pairing, spacing, hover, shadow, gradient."

318395

nano-banana-pro

garg-aayush

Generate and edit images using Google's Nano Banana Pro (Gemini 3 Pro Image) API. Use when the user asks to generate, create, edit, modify, change, alter, or update images. Also use when user references an existing image file and asks to modify it in any way (e.g., "modify this image", "change the background", "replace X with Y"). Supports both text-to-image generation and image-to-image editing with configurable resolution (1K default, 2K, or 4K for high resolution). DO NOT read the image file first - use this skill directly with the --input-image parameter.

450339

fastapi-templates

wshobson

Create production-ready FastAPI projects with async patterns, dependency injection, and comprehensive error handling. Use when building new FastAPI applications or setting up backend API projects.

304231

Stay ahead of the MCP ecosystem

Get weekly updates on new skills and servers.