Mason Documentation

repository·master·Indexed 22 days ago

https://github.com/felangel/mason

A toolkit for creating and consuming reusable code templates called 'bricks'. Mason includes a CLI for automating code generation, a VSCode extension for workspace management and YAML validation, and a Dart API client (mason_api). Key features include support for dynamic variables, custom Dart hooks (pre_gen and post_gen), bundle generation for standalone CLIs, and integration with brickhub.dev for publishing and searching bricks.

Tokens
23.2K
Snippets
100
Records
116
Agent score
77%

What's inside Mason

  1. Overview of Mason template generator

    master
    Mason is a template generator designed to help teams generate files quickly and consistently. The package:mason library contains the core generator engine. It is the foundation used by package:mason_cli and can be integrated into custom code generation tools to automate file creation using 'bricks' (templates).
  2. Mason Package Overview

    master

    Mason is a collection of packages designed to enable developers to create and consume reusable templates called bricks. The ecosystem is divided into several core packages:

    • mason: The core logic for template management.
    • mason_api: API definitions for Mason.
    • mason_cli: The command-line interface for interacting with bricks.
    • mason_logger: Logging utilities used across the Mason ecosystem.
  3. Features of the Mason VSCode extension

    master

    The Mason VSCode extension provides integrated support for managing Mason bricks directly within your editor. Key capabilities include:

    • Workspace Management: Initialize Mason in your current workspace and add/remove bricks both locally and globally.
    • Automation: Automatically fetches missing bricks when you save your mason.yaml file.
    • Brick Creation & Execution: Create new bricks and run mason make using either local or global bricks.
    • Environment Awareness: Detects if the Mason CLI is missing from your system.
    • Validation: Provides YAML schema validation for mason.yaml and brick.yaml files to ensure configuration correctness.
  4. Use Mustache syntax in Mason bricks

    master

    Mason bricks use Mustache templating to generate files. You can use conditional logic to include or exclude text based on variable values.

    • {{variable}}: Injects the value of the variable.
    • {{#variable}}...{{/variable}}: A truthy check. If variable is true, the content inside is included.
    • {{^variable}}...{{/variable}}: A falsy check. If variable is false, the content inside is included.
    Hello, my name is {{name}}! I am {{age}} years old and I {{#isDeveloper}}am{{/isDeveloper}}{{^isDeveloper}}am not{{/isDeveloper}} a developer.
  5. Write brick templates using Mustache

    master

    Templates are stored in the __brick__ directory. Mason uses Mustache syntax for variable interpolation.

    • Use {{variable}} for standard interpolation.
    • Use {{{variable}}} (triple braces) when you want to prevent the value from being escaped.
    • Nested Templates: You can use partials to include content from other files within a template using {{> filename }}. Partials are local and do not generate separate files themselves.
    • File Path Parsing: You can use {{% variable %}} tags to parse variables directly from the file path. For example, a file named __brick__/{{% url %}} will use the value of the url variable as the filename.
    # Hello {{name}}!
  6. Implement custom Dart hooks

    master

    Mason supports executing custom Dart scripts before or after generation via hooks. Hooks must be defined in a hooks/ directory at the brick's root.

    Supported hooks:

    • pre_gen: Runs immediately before generation.
    • post_gen: Runs immediately after generation.

    Each hook must contain a run method that accepts a HookContext. The HookContext allows you to access or modify vars and interact with the logger.

    import 'package:mason/mason.dart';
    
    void run(HookContext context) {
      // Read/Write vars
      context.vars = {...context.vars, 'custom_var': 'foo'};
    
      // Use the logger
      context.logger.info('hook says hi!');
    }
  7. Bundle bricks into packages

    master

    You can use mason bundle to package existing bricks into a distributable format. This is useful for creating standalone CLIs.

    There are two bundle types:

    1. Universal: Platform-agnostic.
    2. Dart: Specific to the Dart ecosystem.

    Use the -t dart flag to specify a Dart bundle and the --source flag to specify the source type (git or hosted).

    # Create a universal bundle from a local brick
    mason bundle ./path/to/brick -o ./path/to/destination
    
    # Create a dart bundle from a git brick
    mason bundle --source git https://github.com/:org/:repo -t dart -o ./path/to/destination
    
    # Create a dart bundle from a hosted brick
    mason bundle --source hosted <BRICK_NAME> -t dart -o ./path/to/destination
  8. Use the mason_api Dart client

    master

    The mason_api package is a Dart API client designed for use by package:mason_cli. It provides programmatic access to the Mason API, allowing you to perform operations such as logging in, logging out, and managing user sessions. To use it, instantiate MasonApi and call its asynchronous methods for authentication.

    import 'package:mason_api/mason_api.dart';
    
    const email = 'my@email.com';
    const password = 'top-secret!';
    
    Future<void> main() async {
      final masonApi = MasonApi();
    
      // Authenticate with the API
      final user = await masonApi.login(email: email, password: password);
      print('Logged in as ${user.email}!');
    
      // End the session
      masonApi.logout();
      print('Logged out!');
    
      // Close the client connection
      masonApi.close();
    }
  9. Generate files with `mason make`

    master

    Use mason make <BRICK_NAME> to generate files from a brick. You can provide variables in several ways:

    1. Command line arguments: Pass variables directly as flags.

    mason make hello --name Felix

    2. Interactive prompts: If a variable is not provided as an argument, Mason will prompt the user for input.

    name: [user input here]

    3. Configuration file: Pass a JSON file containing the variables using the -c flag.

    mason make hello -c config.json

    Example config.json:

    {
      "name": "Felix"
    }

    Customizing Output: Use the -o or --output-dir flag to specify a custom directory for the generated files.

    mason make hello --name Felix -o ./path/to/directory
    mason make hello --name Felix
  10. Initialize a Mason project

    master

    Run mason init in your current directory to initialize Mason. This command generates a mason.yaml file, which is used to register bricks that can be consumed via the CLI.

    Example mason.yaml configuration:

    # Register bricks which can be consumed via the Mason CLI.
    # Run "mason get" to install all registered bricks.
    bricks:
      # Import via version constraint
      hello: 0.1.0+1
      # Or import via remote git url
      # widget:
      #   git:
      #     url: https://github.com/felangel/mason.git
      #     path: bricks/widget

    Important Notes:

    • Run mason get to install all bricks registered in your mason.yaml.
    • Do not commit the .mason directory to version control.
    • Do commit the mason-lock.json file when using versioned bricks (git/hosted).
    mason init
  11. Quick Start with Mason

    master

    To start using Mason for code generation, follow these steps to activate the CLI, initialize a project, and run your first brick:

    1. Activate the CLI: Use dart pub global activate mason_cli to install the Mason command-line interface.
    2. Initialize Mason: Run mason init in your project directory to set up the necessary Mason configuration.
    3. Install a brick: Use mason add <brick_name> to add a reusable template (brick) to your project. For example, mason add hello.
    4. Execute a brick: Run mason make <brick_name> to generate code using the installed brick. For example, mason make hello.
    # 🎯 Activate from https://pub.dev
    dart pub global activate mason_cli
    
    # 🚀 Initialize mason
    mason init
    
    # 📦 Install your first brick
    mason add hello
    
    # 🧱 Use your first brick
    mason make hello