• Stars
    star
    484
  • Rank 90,873 (Top 2 %)
  • Language
    Dart
  • License
    BSD 3-Clause "New...
  • Created almost 10 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Automatic source code generation for Dart

Dart CI Pub Package Version Join the chat on Gitter

Overview

source_gen provides utilities for automated source code generation for Dart:

  • A framework for writing Builders that consume and produce Dart code.
  • A convention for human and tool generated Dart code to coexist with clean separation, and for multiple code generators to integrate in the same project.

Its main purpose is to expose a developer-friendly API on top of lower-level packages like the analyzer or build. You don't have to use source_gen in order to generate source code; we also expose a set of library APIs that might be useful in your generators.

Quick Start Guide for writing a Generator

Add a dependency on source_gen in your pubspec.

dependencies:
  source_gen:

If you're only using source_gen in your own project to generate code and you won't publish your Generator for others to use, it can be a dev_dependency:

dev_dependencies:
  source_gen:

Once you have source_gen setup, you should reference the examples below.

Writing a generator to output Dart source code

Extend the Generator or GeneratorForAnnotation class and source_gen will call your generator for a Dart library or for each element within a library tagged with the annotation you are interested in.

Configuring and Running generators

source_gen is based on the build package and exposes options for using your Generator in a Builder. Choose a Builder based on where you want the generated code to end up:

  • If you want to write to .g.dart files which are referenced as a part in the original source file, use SharedPartBuilder. This is the convention for generated code in part files, and this file may also contain code from Generators provided by other packages.
  • If you want to write to .some_name.dart files which are referenced as a part in the original source file, use PartBuilder. You should choose an extension unique to your package. Multiple Generators may output to this file, but they will all come from your package and you will set up the entire list when constructing the builder. Using the extension .g.dart may cause conflicts with other projects that use SharedPartBuilder since outputs must be unique.
  • If you want to write standalone Dart library which can be imported use LibraryBuilder. Only a single Generator may be used as a LibraryBuilder.

In order to get the Builder used with build_runner it must be configured in a build.yaml file. See build_config for more details. Whenever you are publishing a package that includes a build.yaml file you should include a dependency on build_config in your pubspec.

When using SharedPartBuilder it should always be configured to build_to: cache (hidden files) and apply the combining_builder from this package. The combining builder reads in all the pieces written by different shared part builders and writes them to the final .g.dart output in the user's source directory. You should never use the .g.dart extension for any other Builder.

builders:
  some_cool_builder:
    import: "package:this_package/builder.dart"
    builder_factories: ["someCoolBuilder"]
    # The `partId` argument to `SharedPartBuilder` is "some_cool_builder"
    build_extensions: {".dart": [".some_cool_builder.g.part"]}
    auto_apply: dependents
    build_to: cache
    # To copy the `.g.part` content into `.g.dart` in the source tree
    applies_builders: ["source_gen:combining_builder"]

Configuring combining_builder

ignore_for_file

Sometimes generated code does not support all of the lints specified in the target package. When using a Builder based on package:source_gen which applies combining_builder, set the ignore_for_file option to a list of lints you wish to be ignored in all generated libraries.

Example build.yaml configuration:

targets:
  $default:
    builders:
      source_gen:combining_builder:
        options:
          ignore_for_file:
          - lint_alpha
          - lint_beta

preamble

When using a Builder based on package:source_gen which applies combining_builder, set the preamble option to a string you wish to be prepended to all generated libraries.

Example build.yaml configuration:

targets:
  $default:
    builders:
      source_gen:combining_builder:
        options:
          preamble: |
                // Foo
                
                // Bar

Hint: When both ignore_for_file and preamble are used the generated libraries will contain the lints of ignore_for_file on top of the preamble.

If you provide a builder that uses SharedPartBuilder and combining_builder, you should document these features for your users.

Generating files in different directories

The output location for an input file can be changed:

  • when using PartBuilder or LibraryBuilder.
  • when using SharedPartBuilder which apply the combining_builder as part of the build.

By default, a .g.dart or .some_name.dart file is generated next to the input. To change this, set the build_extensions option on the corresponding builder. In the options, build_extensions is a map from String to String, where the key is matches inputs and the value is a single build output. For more details on build extensions, see the docs in the build package.

For example, you can use these options to generate files under lib/generated with the following build configuration:

targets:
  $default:
    builders:
      # A SharedPartBuilder which uses the combining builder
      source_gen:combining_builder:
        options:
          build_extensions:
            '^lib/{{}}.dart': 'lib/generated/{{}}.g.dart'

      # A PartBuilder or LibraryBuilder
      some_cool_builder:
        options:
          build_extensions:
            '^lib/models/{{}}.dart': 'lib/models/generated/{{}}.foo.dart'

Remember to change the part statement in the input to refer to the correct output file in the other directory.

Note that builder options are part of source_gen's public api! When using them in a build configuration, always add a dependency on source_gen as well:

dev_dependencies:
  source_gen: ^1.1.0

FAQ

What is the difference between source_gen and build?

Build is a platform-agnostic framework for Dart asset or code generation that is pluggable into build systems including bazel, and standalone tools like build_runner. You could also build your own.

Meanwhile, source_gen provides an API and tooling that is easily usable on top of build to make common tasks easier and more developer friendly. For example the PartBuilder class wraps one or more Generator instances to make a Builder which creates part of files, while the LibraryBuilder class wraps a single Generator to make a Builder which creates Dart library files.

Publishing automation

For information about our publishing automation and release process, see https://github.com/dart-lang/ecosystem/wiki/Publishing-automation.

More Repositories

1

sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
Dart
10,110
star
2

language

Design of the Dart language
TeX
2,652
star
3

dart-pad

An online Dart editor with support for console, web, and Flutter apps
Dart
1,702
star
4

pub

The pub command line tool
Dart
1,040
star
5

http

A composable API for making HTTP requests in Dart.
Dart
1,021
star
6

site-www

Source for Dart website
Dart
944
star
7

shelf

Web server middleware for Dart
Dart
920
star
8

build

A build system for Dart written in Dart
Dart
785
star
9

pub-dev

The pub.dev website
Dart
785
star
10

dart_style

An opinionated formatter/linter for Dart code
Dart
645
star
11

dart-vim-plugin

Syntax highlighting for Dart in Vim
Vim Script
637
star
12

mockito

Mockito-inspired mock library for Dart
Dart
632
star
13

linter

Linter for Dart.
Dart
628
star
14

samples

A collection of Dart code samples by Dart DevRel
Dart
602
star
15

test

A library for writing unit tests in Dart.
Dart
492
star
16

dartdoc

API documentation tool for Dart.
Dart
473
star
17

markdown

A Dart markdown library
Dart
444
star
18

code_builder

A fluent API for generating valid Dart source code
Dart
428
star
19

web_socket_channel

StreamChannel wrappers for WebSockets.
Dart
418
star
20

leak_tracker

A framework for memory leak tracking for Dart and Flutter applications.
Dart
387
star
21

collection

The collection package for Dart contains a number of separate libraries with utility functions and classes that makes working with collections easier.
Dart
375
star
22

ffigen

FFI binding generator
Dart
364
star
23

logging

A Dart package for debug and error logging.
Dart
332
star
24

async

A Dart package that contains tools to work with asynchronous computations.
Dart
320
star
25

wasm

Utilities for loading and running WASM modules from Dart code
Dart
309
star
26

html

Dart port of html5lib. For parsing HTML/HTML5 with Dart. Works in the client and on the server.
Dart
276
star
27

crypto

A set of cryptographic functions implemented in pure Dart.
Dart
275
star
28

path

A string-based path manipulation library.
Dart
223
star
29

args

A command-line argument parsing library for Dart.
Dart
214
star
30

webdev

A CLI for Dart web development.
Dart
212
star
31

oauth2

An OAuth2 client library for Dart.
Dart
211
star
32

pana

Package ANAlysis for Dart
Dart
205
star
33

setup-dart

A GitHub Action to install and setup a Dart SDK.
Dart
188
star
34

yaml

A Dart YAML parser.
Dart
169
star
35

jnigen

Experimental bindings generator for Java bindings through dart:ffi and JNI.
Dart
154
star
36

homebrew-dart

Dart team's official tap for homebrew.
Ruby
153
star
37

native

Dart packages related to FFI and native assets bundling.
Dart
153
star
38

http2

A HTTP/2 implementation for dart.
Dart
153
star
39

sample-pop_pop_win

"Pop, Pop, Win!" is an implementation of Minesweeper in Dart.
Dart
149
star
40

usage

A Google Analytics wrapper for command-line, web, and Flutter apps.
Dart
143
star
41

watcher

A file system watcher library for Dart.
Dart
138
star
42

mime

Dart package for working with MIME type definitions and for processing streams of MIME multipart media types.
Dart
132
star
43

stack_trace

A package for manipulating stack traces and printing them readably.
Dart
128
star
44

web

Lightweight browser API bindings built around JS static interop.
Dart
128
star
45

gcloud

High-level interfaces to Google Cloud Platform APIs
Dart
126
star
46

platform

A generic platform abstraction for Dart
Dart
125
star
47

stream_transform

Dart utility methods to create StreamTransfomer instances to manipulate Streams
Dart
123
star
48

lints

Official Dart lint rules; the core and recommended set of lints suggested by the Dart team.
Dart
116
star
49

coverage

Dart coverage data manipulation and formatting
Dart
103
star
50

sse

Dart Server Sent Events package
Dart
96
star
51

csslib

A library for parsing CSS.
Dart
95
star
52

benchmark_harness

The official benchmark harness for Dart
Dart
94
star
53

appengine

Dart support for App Engine managed VMs
Dart
93
star
54

fake_async

Fake asynchronous events for deterministic testing.
Dart
90
star
55

convert

Conversion utilities
Dart
72
star
56

matcher

A declarative API for specifying expectations.
Dart
71
star
57

json_rpc_2

A Dart implementation of the JSON-RPC 2.0 spec.
Dart
71
star
58

characters

A package for characters represented as unicode extended grapheme clusters
Dart
69
star
59

dart-docker

Docker images for the Dart programming language (https://dart.dev)
Dart
68
star
60

pub_semver

A package for working with Pub/semver-style versions and version constraints
Dart
65
star
61

i18n

A general mono-repo for Dart i18n and l10n packages.
Dart
63
star
62

cli_util

A library to help in building Dart command-line apps
Dart
60
star
63

string_scanner

A class for parsing strings using a sequence of patterns.
Dart
60
star
64

glob

Bash-style filename globbing for Dart.
Dart
56
star
65

pubspec_parse

Simple package for parsing pubspec.yaml files with a type-safe API and rich error reporting
Dart
51
star
66

pool

A class for managing a finite pool of resources.
Dart
51
star
67

stream_channel

An abstraction for two-way communication channels.
Dart
50
star
68

io

Utilities for the Dart VM's dart:io.
Dart
49
star
69

macros

A Dart mono-repo for macro development.
Dart
48
star
70

fixnum

Fixed-width integer library for Dart.
Dart
45
star
71

clock

A fakeable wrapper for dart:core clock APIs.
Dart
41
star
72

ecosystem

This repository is home to general Dart Ecosystem tools and packages.
Dart
41
star
73

http_parser

A platform-independent Dart package for parsing and serializing HTTP formats.
Dart
39
star
74

site-shared

Content shared across Dart websites
JavaScript
38
star
75

co19

A Dart language and library conformance test suite
Dart
37
star
76

typed_data

Utility functions and classes that makes working with typed data lists easier in Dart
Dart
34
star
77

source_span

A library for identifying source spans and locations.
Dart
29
star
78

tools

This repository is home to tooling related Dart packages.
Dart
29
star
79

http_multi_server

A dart:io HttpServer wrapper that handles requests from multiple servers.
Dart
28
star
80

yaml_edit

A library for YAML manipulation with comment and whitespace preservation.
Dart
27
star
81

native_synchronization

Low-level synchronization primitives built using dart:ffi.
Dart
26
star
82

os_detect

Dart multi-platform operating system identification
Dart
24
star
83

dartbug.com

The redirect service for Dart issues and bugs.
Dart
23
star
84

bazel_worker

Dart integration for Bazel build system
Dart
23
star
85

boolean_selector

A flexible syntax for boolean expressions.
Dart
23
star
86

dart-syntax-highlight

Tools and documentation for how Dart code is formatted
Dart
22
star
87

api.dart.dev

Dart API docs
Python
19
star
88

grpc_cronet

Flutter dart:grpc implementation that uses the Cronet native library.
Dart
18
star
89

dart_ci

Tools used by Dart's continuous integration (CI) testing that aren't needed by Dart SDK contributors. Mirrored from dart.googlesource.com/dart_ci. Do not land pull requests on Github.
Dart
18
star
90

source_maps

A package to programmatically manipulate source maps.
Dart
16
star
91

term_glyph

Useful glyphs and Windows-safe equivalents
Dart
16
star
92

package_config

Support for working with Package Resolution Configuration files
Dart
16
star
93

test_process

A Dart package for testing subprocesses
Dart
16
star
94

browser_launcher

Provides a standardized way to launch web browsers.
Dart
16
star
95

timing

A Dart package for tracking time spent in child operations
Dart
14
star
96

root_certificates

The set of root certificates trusted by dart:io's default SecurityContext. Taken from Mozilla's NSS library.
C++
11
star
97

test_descriptor

Provides a convenient, easy-to-read API for defining and verifying directory structures in tests
Dart
10
star
98

dartlang_project_templates

Project templates for new repos under the dart-lang organization
Dart
8
star
99

source_map_stack_trace

Convert stack traces generated by dart2js-compiled code into readable native Dart stack traces
Dart
8
star
100

.github

GitHub default community health file for dart-lang repos
7
star