Automatic source code generation for Dart

Overview

Build Status 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.
  • 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

If you provide a builder that uses SharedPartBuilder and combining_builder, you should document this feature 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.

Comments
  • Exception with json_serializable on String? override (FieldElementImpl)

    Exception with json_serializable on String? override (FieldElementImpl)

    https://github.com/rrousselGit/freezed/issues/507#issue-984354925

    Describe the bug Following build_runner command is throwing an exception so generation of 'risk_factor.model.g.dart' gets failed.

    dart run build_runner build --delete-conflicting-outputs --verbose

    InconsistentAnalysisException: Requested result might be inconsistent with previously returned results

    package:analyzer/src/dart/analysis/session.dart 197:7 AnalysisSessionImpl._checkConsistency package:analyzer/src/dart/analysis/session.dart 107:5 AnalysisSessionImpl.getParsedLibraryByElement package:source_gen/src/type_checker.dart 305:16 UnresolvedAnnotationException._findSpan package:source_gen/src/type_checker.dart 344:24 new UnresolvedAnnotationException._from package:source_gen/src/type_checker.dart 114:43 TypeChecker._computeConstantValue package:source_gen/src/type_checker.dart 139:21 TypeChecker._annotationsWhere dart:core Iterable.isEmpty package:source_gen/src/type_checker.dart 73:20 TypeChecker.firstAnnotationOf package:json_serializable/src/utils.dart 17:21 _jsonKeyAnnotation package:json_serializable/src/utils.dart 27:5 hasJsonKeyAnnotation dart:collection ListMixin.firstWhere package:json_serializable/src/field_helpers.dart 30:16 new _FieldSet package:json_serializable/src/field_helpers.dart 102:19 createSortedFieldSet. dart:core Iterable.toList package:json_serializable/src/field_helpers.dart 103:8 createSortedFieldSet package:json_serializable/src/generator_helper.dart 54:26 GeneratorHelper.generate

    [SEVERE] json_serializable:json_serializable on lib/src/clpapi/risk_factor.model.dart:

    Could not resolve annotation for String? type. package:source_gen/src/type_checker.dart 114:7 TypeChecker._computeConstantValue package:source_gen/src/type_checker.dart 139:21 TypeChecker._annotationsWhere dart:core Iterable.isEmpty package:source_gen/src/type_checker.dart 73:20 TypeChecker.firstAnnotationOf package:json_serializable/src/utils.dart 17:21 _jsonKeyAnnotation package:json_serializable/src/utils.dart 27:5 hasJsonKeyAnnotation dart:collection ListMixin.firstWhere package:json_serializable/src/field_helpers.dart 30:16 new _FieldSet package:json_serializable/src/field_helpers.dart 102:19 createSortedFieldSet. dart:core Iterable.toList package:json_serializable/src/field_helpers.dart 103:8 createSortedFieldSet package:json_serializable/src/generator_helper.dart 54:26 GeneratorHelper.generate

    To Reproduce

    This is the 'risk_factor.model.dart' Strange thing is that I have String? type, in other model classes but only this particular class gets the exception on build.

    import 'package:freezed_annotation/freezed_annotation.dart';
    
    part 'risk_factor.model.freezed.dart';
    part 'risk_factor.model.g.dart';
    
    @freezed
    class RiskFactorModel with _$RiskFactorModel {
      factory RiskFactorModel({
        String? type,
        String? value,
        String? override,
      }) = _RiskFactorModel;
    
      factory RiskFactorModel.fromJson(Map<String, Object?> json) =>
          _$RiskFactorModelFromJson(json);
    }
    

    Flutter version:

    [✓] Flutter (Channel master, 2.6.0-1.0.pre.142, on macOS 11.5.2 20G95 darwin-x64, locale en-US) • Flutter version 2.6.0-1.0.pre.142 at • Upstream repository https://github.com/flutter/flutter.git • Framework revision cf806f7d5f (3 hours ago), 2021-08-31 11:11:04 -0700 • Engine revision fe89463f14 • Dart version 2.15.0 (build 2.15.0-66.0.dev)

    Package versions in the lock:

    analyzer: version: "2.1.0" build_runner: version: "2.1.1" source_gen: version: "1.1.0"

    Expected behavior Just building of this particular class is fine as the other model classes with freezed.

    opened by chunghha 16
  • auto-apply dartfmt fixes

    auto-apply dartfmt fixes

    Closes https://github.com/dart-lang/source_gen/issues/551

    I think this is pretty reasonable, especially since you can override the behavior.

    @munificent are there any cases you know about where a fix would break code or all they all super safe?

    cla: yes 
    opened by jakemac53 14
  • Add

    Add "jsonKey" annotation

    This fixes #65. This adds the ability to specify a JsonKey annotation:

    @JsonSerializable()
    class MyClass {
      @JsonKey("foo")
      final int FooBar;
      ...
    

    source_gen then uses that value for the key when serializing to JSON:

    {
        "foo": 123
    }
    

    FYI @kevmoo

    opened by johnpryan 14
  • AnalysisException: Cannot compute SOURCE_KIND for Instance of 'AssetBasedSource'

    AnalysisException: Cannot compute SOURCE_KIND for Instance of 'AssetBasedSource'

    Hi, experiencing a rather cryptic error, the cause of which I am having a tough time of diagnosing.

    Here is my project: https://github.com/thosakwe/lsp4dart It's got nothing in it except for tool/ boilerplate and two files which will eventually contain serializable classes.

    When I run tool/build.dart, I get the following error:

    [SEVERE] Build: Failed after 518ms
    AnalysisException: Cannot compute SOURCE_KIND for Instance of 'AssetBasedSource'
    Caused by Could not resolve "dart:core": SDK incorrectly configured
    #0      ParseDartTask.internalPerform (package:analyzer/src/task/dart.dart:4059:7)
    #1      AnalysisTask._safelyPerform (package:analyzer/task/model.dart:339:9)
    #2      AnalysisTask.perform (package:analyzer/task/model.dart:238:7)
    #3      AnalysisDriver.performWorkItem (package:analyzer/src/task/driver.dart:284:10)
    #4      AnalysisDriver.computeResult (package:analyzer/src/task/driver.dart:109:22)
    #5      AnalysisContextImpl.computeResult (package:analyzer/src/context/context.dart:723:14)
    #6      AnalysisContextImpl.computeKindOf (package:analyzer/src/context/context.dart:686:14)
    #7      ResolverImpl._performResolve.<anonymous closure>.<anonymous closure> (package:code_transformers/src/resolver_impl.dart:165:29)
    #8      MappedListIterable.elementAt (dart:_internal/iterable.dart:413)
    #9      ListIterable.toList (dart:_internal/iterable.dart:218)
    #10     ResolverImpl._performResolve.<anonymous closure> (package:code_transformers/src/resolver_impl.dart:168:10)
    #11     StackZoneSpecification._registerUnaryCallback.<anonymous closure>.<anonymous closure> (package:stack_trace/src/stack_zone_specification.dart:109:26)
    #12     StackZoneSpecification._run (package:stack_trace/src/stack_zone_specification.dart:187:15)
    #13     StackZoneSpecification._registerUnaryCallback.<anonymous closure> (package:stack_trace/src/stack_zone_specification.dart:109:14)
    #14     _rootRunUnary (dart:async/zone.dart:1128)
    #15     _CustomZone.runUnary (dart:async/zone.dart:1012)
    #16     _FutureListener.handleValue (dart:async/future_impl.dart:129)
    #17     _Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:636)
    #18     _Future._propagateToListeners (dart:async/future_impl.dart:665)
    #19     _Future._completeWithValue (dart:async/future_impl.dart:478)
    #20     _Future._asyncComplete.<anonymous closure> (dart:async/future_impl.dart:510)
    #21     StackZoneSpecification._run (package:stack_trace/src/stack_zone_specification.dart:187:15)
    #22     StackZoneSpecification._registerCallback.<anonymous closure> (package:stack_trace/src/stack_zone_specification.dart:99:48)
    #23     _rootRun (dart:async/zone.dart:1120)
    #24     _CustomZone.run (dart:async/zone.dart:1001)
    #25     _CustomZone.runGuarded (dart:async/zone.dart:901)
    #26     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:926)
    #27     _microtaskLoop (dart:async/schedule_microtask.dart:41)
    #28     _startMicrotaskLoop (dart:async/schedule_microtask.dart:50)
    #29     _runPendingImmediateCallback (dart:isolate-patch/isolate_patch.dart:99)
    #30     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:152)
    
    
    package:analyzer/src/context/context.dart 728:7           AnalysisContextImpl.computeResult
    package:analyzer/src/context/context.dart 686:14          AnalysisContextImpl.computeKindOf
    package:code_transformers/src/resolver_impl.dart 165:29   ResolverImpl._performResolve.<fn>.<fn>
    dart:_internal                                            ListIterable.toList
    package:code_transformers/src/resolver_impl.dart 168:10   ResolverImpl._performResolve.<fn>
    dart:async                                                _Future.then
    package:code_transformers/src/resolver_impl.dart 154:28   ResolverImpl._performResolve
    package:code_transformers/src/resolver_impl.dart 90:14    ResolverImpl.resolve.<fn>
    dart:async                                                _Future.whenComplete
    package:code_transformers/src/resolver_impl.dart 88:37    ResolverImpl.resolve
    package:code_transformers/src/resolvers.dart 63:17        Resolvers.get
    package:build_barback/src/analyzer/resolver.dart 47:44    BarbackResolvers.get
    dart:async                                                new Future.microtask
    package:build_barback/src/analyzer/resolver.dart 46:61    BarbackResolvers.get
    package:build/src/builder/build_step_impl.dart 56:61      BuildStepImpl.resolver
    package:source_gen/src/builder.dart 32:36                 GeneratorBuilder.build
    dart:async                                                new Future.microtask
    package:source_gen/src/builder.dart 31:43                 GeneratorBuilder.build
    package:build/src/generate/run_builder.dart 33:21         runBuilder.buildForInput
    dart:async                                                new Future.microtask
    package:build/src/generate/run_builder.dart 28:51         runBuilder.buildForInput
    dart:async                                                Future.wait
    package:build/src/generate/run_builder.dart 39:31         runBuilder.<fn>
    dart:async                                                runZoned
    package:build/src/builder/logging.dart 13:5               scopeLog
    package:build/src/generate/run_builder.dart 39:9          runBuilder
    dart:async                                                new Future.microtask
    package:build/src/generate/run_builder.dart 24:48         runBuilder
    package:build_runner/src/generate/build_impl.dart 552:13  BuildImpl._runBuilder
    dart:async                                                _StreamIterator.moveNext
    package:build_runner/src/generate/build_impl.dart 442:16  BuildImpl._runPhases.<fn>
    dart:async                                                new Future.microtask
    package:build_runner/src/generate/build_impl.dart 439:50  BuildImpl._runPhases.<fn>
    dart:async                                                Future.wait
    package:build_runner/src/generate/build_impl.dart 439:20  BuildImpl._runPhases
    dart:async                                                new Future.microtask
    package:build_runner/src/generate/build_impl.dart 430:42  BuildImpl._runPhases
    package:build_runner/src/logging/logging.dart 19:28       logWithTime
    dart:async                                                new Future.microtask
    package:build_runner/src/logging/logging.dart 16:70       logWithTime
    package:build_runner/src/generate/build_impl.dart 146:26  BuildImpl.runBuild.<fn>
    dart:async                                                _asyncThenWrapperHelper
    package:build_runner/src/generate/build_impl.dart 78:28   BuildImpl.runBuild.<fn>
    package:stack_trace                                       Chain.capture
    package:build_runner/src/generate/build_impl.dart 78:11   BuildImpl.runBuild
    

    I've run into this error with both of the following generators, in separate projects:

    • owl_codegen
    • angel_serialize_generator

    So I am assuming there is some underlying issue that I am missing somewhere. I get this error both with [email protected] and [email protected]. Haven't tried any versions in between.

    Thanks in advance for your help.

    opened by thosakwe 13
  • API for

    API for "reviving" `DartObject`

    One of the hardest and most brittle parts of the AngularDart compiler...

    Basically, we need to go from a computed DartObject to some sort of model class that enables code generation of an identical object. Here are some simple (trivial) examples that are solvable with ConstantReader today:

    • String
    • int / double
    • bool
    • null
    • List<...> or Map<...> of these types, recursively

    However, it's much harder with classes and enums. Consider these:

    • const Duration(seconds: 5)
    • const SomeClass._privateConstructor()
    • Enum.someValue

    We could do this with ConstantReader, if we add a few more methods:

    abstract class ConstantReader {
      bool get isEnum;
      RevivableEnum get enumValue;
    
      bool get isInstance;
      RevivableInstance get instanceValue;
    }
    
    abstract class RevivableEnum implements ConstantReader {
      Uri get uri;
      String get name;
      int get index;
    }
    
    abstract class RevivableInstance implements ConstantReader {
      Uri get uri;
      String get name;
      String get constructor;
      List<ConstantReader> get positionalArguments;
      Map<String, ConstantReader> get namedArguments;
    }
    

    We could also do error handling, i.e., a flag for checking if it is revivable (visible):

    abstract class RevivableInstance implements ConstantReader {
      ...
      bool get isVisible;
    }
    

    This isn't a perfect API, but it is probably better for some of this to live in source_gen (and have closer watch by the ecosystem team and analysis team) than buried in the AngularDart compiler.

    /cc @jakemac53 @alorenzen @kevmoo

    Type: enhancement 
    opened by matanlurey 13
  • Patch instantiateAnnotation to support extended annotation classes

    Patch instantiateAnnotation to support extended annotation classes

    I've left details about an error I'm experiencing with source_gen in #155.

    This PR will solve one of the two problems I noticed, which is that instantiateAnnotation does not work for annotations that are extended from a parent class.

    Please let me know if there is anything I should change before this PR is merged!

    cla: yes 
    opened by thosakwe 13
  • Allow the library builder to work with non-dart (json, xml, yaml, etc...) based on allow build extension

    Allow the library builder to work with non-dart (json, xml, yaml, etc...) based on allow build extension

    The current source generator only works with dart code even for LibraryBuilder, which kind not does not make sense. This change will support to generate code for non-dart extension.

    cla: yes 
    opened by pratikpparikh 12
  • Explain how to use this package

    Explain how to use this package

    I've been trying hard enough to figure out how to use this package, reading all the extense build package documentation and that... and I'm still lost. Can someone please put some trivial e2e example in the wiki, with both the code and the commands needed to generate code and execute it in your project? Thanks in advance

    opened by Rodsevich 12
  • Generate code in another folder?

    Generate code in another folder?

    I think it could be interesting to group all the generated code in different folder from the original sources. this makes simple to distinguish main source files from generated one (that one should not edit by hand).

    Is it possible to add some options to PartBuilder and LibraryBuilder in order to specify a different folder (even restricted to lib) where to put generated files ?

    opened by dam0vm3nt 12
  • Add TypeChecker class.

    Add TypeChecker class.

    This will be nice to have versus stuffed into the AngularDart compiler, and it doesn't feel "right" going into a library like build, which I think benefits from having a very small interface and low-threshold for changes.

    Advantages of this approach

    • Adds an "approved" (not `/lib/src/annotations.dart') way of performing checks.
    • Has two backing implementations not based on dart:mirrors (for long-term safety).
    • Easy re-usable setup for complex compilers like inject or angular.

    See type_checker_test.dart for some functional tests.

    Closes https://github.com/dart-lang/source_gen/issues/136.

    cla: yes 
    opened by matanlurey 12
  • Add a CombiningBuilder for .g.dart files and document how to use it

    Add a CombiningBuilder for .g.dart files and document how to use it

    We added runs_before and applies_builder to build config so it should be possible now to put everything together with one or more source_gen part builders cooperating to generate a single part file. We'll want a "CombiningBuilder" ("MergingBuilder"?) in this package to read in all the files generated by different part builders and write them to a single output.

    • [x] Fix duplicate headers - https://github.com/dart-lang/source_gen/pull/348
    • [x] Fix logging of missing part directive - https://github.com/dart-lang/source_gen/pull/348
    • [x] Document usage in readme
    • [x] Update build.yaml to properly expose CombiningBuilder
    • [x] BLOCKING Get build issue fixed related to running built-to-cache builder over transitive dependencies - https://github.com/dart-lang/build/issues/1578
    • [x] Add a cleanup builder

    After published...

    • [x] Add a working example to repo/example
    State: blocked 
    opened by natebosch 11
  • Bump actions/cache from 3.0.11 to 3.2.2

    Bump actions/cache from 3.0.11 to 3.2.2

    Bumps actions/cache from 3.0.11 to 3.2.2.

    Release notes

    Sourced from actions/cache's releases.

    v3.2.2

    What's Changed

    New Contributors

    Full Changelog: https://github.com/actions/cache/compare/v3.2.1...v3.2.2

    v3.2.1

    What's Changed

    Full Changelog: https://github.com/actions/cache/compare/v3.2.0...v3.2.1

    v3.2.0

    What's Changed

    New Contributors

    ... (truncated)

    Changelog

    Sourced from actions/cache's changelog.

    Releases

    3.0.0

    • Updated minimum runner version support from node 12 -> node 16

    3.0.1

    • Added support for caching from GHES 3.5.
    • Fixed download issue for files > 2GB during restore.

    3.0.2

    • Added support for dynamic cache size cap on GHES.

    3.0.3

    • Fixed avoiding empty cache save when no files are available for caching. (issue)

    3.0.4

    • Fixed tar creation error while trying to create tar with path as ~/ home folder on ubuntu-latest. (issue)

    3.0.5

    • Removed error handling by consuming actions/cache 3.0 toolkit, Now cache server error handling will be done by toolkit. (PR)

    3.0.6

    • Fixed #809 - zstd -d: no such file or directory error
    • Fixed #833 - cache doesn't work with github workspace directory

    3.0.7

    • Fixed #810 - download stuck issue. A new timeout is introduced in the download process to abort the download if it gets stuck and doesn't finish within an hour.

    3.0.8

    • Fix zstd not working for windows on gnu tar in issues #888 and #891.
    • Allowing users to provide a custom timeout as input for aborting download of a cache segment using an environment variable SEGMENT_DOWNLOAD_TIMEOUT_MINS. Default is 60 minutes.

    3.0.9

    • Enhanced the warning message for cache unavailablity in case of GHES.

    3.0.10

    • Fix a bug with sorting inputs.
    • Update definition for restore-keys in README.md

    3.0.11

    • Update toolkit version to 3.0.5 to include @actions/core@^1.10.0
    • Update @actions/cache to use updated saveState and setOutput functions from @actions/core@^1.10.0

    3.1.0-beta.1

    • Update @actions/cache on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. (issue)

    3.1.0-beta.2

    • Added support for fallback to gzip to restore old caches on windows.

    3.1.0-beta.3

    ... (truncated)

    Commits
    • 4723a57 Revert compression changes related to windows but keep version logging (#1049)
    • d1507cc Merge pull request #1042 from me-and/correct-readme-re-windows
    • 3337563 Merge branch 'main' into correct-readme-re-windows
    • 60c7666 save/README.md: Fix typo in example (#1040)
    • b053f2b Fix formatting error in restore/README.md (#1044)
    • 501277c README.md: remove outdated Windows cache tip link
    • c1a5de8 Upgrade codeql to v2 (#1023)
    • 9b0be58 Release compression related changes for windows (#1039)
    • c17f4bf GA for granular cache (#1035)
    • ac25611 docs: fix an invalid link in workarounds.md (#929)
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies 
    opened by dependabot[bot] 0
  • Bump actions/checkout from 3.1.0 to 3.2.0

    Bump actions/checkout from 3.1.0 to 3.2.0

    Bumps actions/checkout from 3.1.0 to 3.2.0.

    Release notes

    Sourced from actions/checkout's releases.

    v3.2.0

    What's Changed

    New Contributors

    Full Changelog: https://github.com/actions/checkout/compare/v3...v3.2.0

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies 
    opened by dependabot[bot] 0
  • `isAssignableFrom` does not work for mixins as stated by the docs

    `isAssignableFrom` does not work for mixins as stated by the docs

    Trying to check if a mixin element type represents a super type I found the following statement documented on isSuperTypeOf():

    Returns true if representing a super type of staticType.

    This only takes into account the extends hierarchy. If you wish to check mixins and interfaces, use isAssignableFromType.

    So with this information I thought that isAssignableFromType would work as it is.

    Implementation:

    bool isAssignableFromType(DartType staticType) =>
        isAssignableFrom(staticType.element2!);
    
    bool isAssignableFrom(Element element) =>
        isExactly(element) ||
        (element is ClassElement && element.allSupertypes.any(isExactlyType));
    

    However, given that a mixin type is a MixinElement and not a ClassElement, the previous condition fails since element is ClassElement is false.

    opened by rubenferreira97 0
  • Coverage ignore option

    Coverage ignore option

    Hi,

    is it possible to add an option to combining_builder which leads to the line //coverage:ignore-file beeing added on top of generated files. Or is there already an existing solution?

    Something like:

    targets:
      $default:
        builders:
          source_gen:combining_builder:
            options:
              coverage-ignore-file: true
    
    opened by jtdLab 3
  • isAssignableFromType throws null check error for Function types

    isAssignableFromType throws null check error for Function types

    The implementation null asserts DartType.element2: https://github.com/dart-lang/source_gen/blob/0d4c54d2a299643ba2a783ef2e9fcf878305a62d/source_gen/lib/src/type_checker.dart#L170-L171

    Which is always null for Function types: https://github.com/dart-lang/sdk/blob/d6ff1193c5eb1d4b98e232f545cce49c63492b5c/pkg/analyzer/lib/src/dart/element/type.dart#L95-L96

    opened by leonsenft 5
  • Is there a way to find declared source of predefined annotations?

    Is there a way to find declared source of predefined annotations?

    const predefinedAnnotation = SomeAnnotation('this is predefined');
    
    @predefinedAnnotation  // this is the first case
    @SomeAnnotation('this is defined as it's needed') // this is the second case
    class SomeClass {
    }
    

    In this case, I am currently getting a declaration by using below code.

    // `element `is `ClassElement` of SomeClass
    for (final annotations in element. metadata) {
      print(annotations.toSource());
    }
    

    In the first case (predefined annotation), it only prints predefinedAnnotation, the name of the constant variable. In the second case, it prints what I want. The full code of @SomeAnnotation('this is defined as it's needed').

    Is there a way to get the full code in case of predefinedAnnotation?

    opened by wurikiji 0
Releases(v0.9.1)
  • v0.9.1(Sep 10, 2018)

    0.9.1

    • The result of ConstantReader.revive() now returns a Revivable that assumes access to a private class, constructor, or function instead of null where possible. This allows generators that use part files to still use this functionality and allows generators that use separate libraries to emit more actionable error messages (i.e. "cannot use private class _X").

    • Revivable.isPrivate now returns true when the underyling class was public but the constructor was private, or the Revivable was pointing to a top-level or static private field or method. Previously it was only true when referencing a private class.

    Source code(tar.gz)
    Source code(zip)
  • 0.8.2(Jun 14, 2018)

    • Simplification to the output of generator names in header sections.

    • Update handling of whitespace in generator outputs.

      • If the output from a generator has wrapping whitespace, it is trimmed.
      • If the output from a generator is empty or whitespace-only, it is ignored.
      • These changes will likely have no effect on output, unless you customize the code formatter.
    Source code(tar.gz)
    Source code(zip)
  • v0.8.1(Apr 16, 2018)

    • Cleanup logging output that duplicates headers provided by package:build_runner.

    • InvalidGenerationSourceError added an optional element parameter to support more helpful error messages.

    Source code(tar.gz)
    Source code(zip)
  • v0.8.0(Mar 29, 2018)

    • BREAKING removed the deprecated requireLibraryDirective parameter in PartBuilder.

    • Revivable no longer throws a type error when attempting to revive a reference to a top-level function or static-class method. Now is returns a reference to that function or method, as expected.

    Source code(tar.gz)
    Source code(zip)
  • v0.7.6(Mar 7, 2018)

    0.7.6

    • TypeChecker now throws an UnresolvedAnnotationException with a more detailed exception body (and properties useful for further debugging) instead of Could not resolve @null.
    Source code(tar.gz)
    Source code(zip)
  • v0.7.5+1(Feb 15, 2018)

    • LibraryBuilder and PartBuilder now have a more readable toString(), which is useful when emitting a warning or error in a build system. For example you may see Generating .g.dart: MyBuilder instead of Instance of LibraryBuilder in your build logs.
    Source code(tar.gz)
    Source code(zip)
  • v0.7.4+2(Jan 31, 2018)

    • BUG FIX: ConstantReader.revive() now properly returns no URL fragment when the constant expression is resolved from a top-level or static-field. The documentation had said otherwise, and it was impossible to tell the difference between a constructor and a field. Now, fields are always in the form of accessor = {clazz}.{field} or {topLevelField}.

    • Fix file URIs on windows.

    Source code(tar.gz)
    Source code(zip)
  • v0.7.4+1(Jan 22, 2018)

    • Removed a log.finest with the output source of each generator. This allows a verbose option (-v) for tools like bazel or build_runner to be much more readable and debuggable. Files are emitted to disk for inspection in any case.
    Source code(tar.gz)
    Source code(zip)
  • v0.7.4(Jan 18, 2018)

    • Added typeNameOf, which is a safe way to get the name of a DartType, even when the type is a FunctionType, which has a null name in newer versions of the Dart analyzer.

    • Added LibraryReader.pathToUrl(Uri|String), which computes the import or export path necessary to reach the provided URL from the current library. Also added pathToAsset and pathToElement as convenience functions.

    • Expanded package:build support to allow version 0.12.0.

    Source code(tar.gz)
    Source code(zip)
  • v0.7.0(Jul 26, 2017)

    • Breaking changes: See the wiki for help upgrading.

      • Generator.generate now operates on a LibraryReader rather than being called for every Element within a library. Generators can iterate over elements using LibraryReader.allElements. GeneratorForAnnotation will continue to call generateForAnnotatedElement repeatedly for each element.
      • GeneratorForAnnotation passes in a ConstantReader for the annotation instance rather than re-creating it using mirrors.
      • GeneratorBuilder is replaced with PartBuilder and LibraryBuilder depending on whether the output is meant to be included in a part file.
      • Removed JsonSerializable and related classes. These are moved to package:json_serializable.
      • Removed lib/builder.dart. Import through source_gen.dart instead.
      • Removed OutputFormatter typedef.
    • Add LibraryReader.allElements - a utility to iterate across all Element instances contained in Dart library.

    • Add LibraryReader.element to get back to the LibraryElement instance.

    • Add ConstantReader.objectValue to get back to the DartObject instance.

    • Add ConstantReader.peek to read a value that returns null if not found:

    // Tries to read the field "token" first, then "_token".
    findTokenField(DartObject o) {
      final reader = new ConstantReader(o);
      final token = o.peek('token') ?? o.read('_token');
    }
    
    • Add throwOnUnresolved optional parameter to TypeChecker.annotationsOf, TypeChecker.annotationsOfExact, TypeChecker.firstAnnotationOf, and TypeChecker.firstAnnotationOfExact. Setting this to false will enable you to check for matching annotations with incomplete type information (at your own risk).
    • Builder logs now log the primary inputs AssetId instead of the library, which is more useful for tracking down the actual files.
    Source code(tar.gz)
    Source code(zip)
  • v0.6.1+1(Jul 18, 2017)

    • Added spanForElement; returns a SourceSpan for an analyzer Element.
    • Logs a warning to the console when a GeneratorBuilder outputs a part file for a given input, but that input does not define part 'name.g.dart';.
    Source code(tar.gz)
    Source code(zip)
  • v0.6.0(Jul 6, 2017)

    • Breaking change: TypeChecker#annotationsOf|firstAnnotationOf now returns annotations that are assignable to the TypeChecker's type. As a result we've added #annotationsOfExact|firstAnnotationOfExact which has the old behavior for precise checks.

    • TypeChecker#annotations...-methods now throw a StateError if one or more annotations on an element are not resolvable. This is usually a sign of a mispelling, missing import, or missing dependency.

    • Added TypeChecker.any, which delegates to multiple other TypeChecker implementations when making a type check.

    Source code(tar.gz)
    Source code(zip)
  • v0.5.9(Jun 23, 2017)

    0.5.9

    • Update the minimum Dart SDK to 1.22.1.

    • Deprecated builder.dart: import source_gen.dart instead.

    • Added TypeChecker, a high-level API for performing static type checks:

      import 'package:analyzer/dart/element/type.dart';
      import 'package:source_gen/source_gen.dart';
      
      void checkType(DartType dartType) {
        // Checks compared to runtime type `SomeClass`.
        print(const TypeChecker.forRuntime(SomeClass).isExactlyType(dartType));
      
        // Checks compared to a known Url/Symbol:
        const TypeChecker.forUrl('package:foo/foo.dart#SomeClass');
      
        // Checks compared to another resolved `DartType`:
        const TypeChecker.forStatic(anotherDartType);
      }
      
    • Failing to add a library directive to a library that is being used as a generator target that generates partial files (part of) is now an explicit error that gives a hint on how to name and fix your library:

      > Could not find library identifier so a "part of" cannot be built.
      >
      > Consider adding the following to your source file:
      >
      > "library foo.bar;"
      

      In Dart SDK >=1.25.0 this can be relaxed as part of can refer to a path. To opt-in, GeneratorBuilder now has a new flag, requireLibraryDirective. Set it to false, and also set your sdk constraint appropriately:

        sdk: '>=1.25.0 <2.0.0'
      
    • Added LibraryReader, a utility class for LibraryElement that exposes high-level APIs, including findType, which traverses export directives for publicly exported types. For example, to find Generator from package:source_gen/source_gen.dart:

      void example(LibraryElement pkgSourceGen) {
        var library = new LibraryReader(pkgSourceGen);
      
        // Instead of pkgSourceGen.getType('Generator'), which is null.
        library.findType('Generator');
      }
      
    • Added ConstantReader, a high-level API for reading from constant (static) values from Dart source code (usually represented by DartObject from the analyzer package):

      abstract class ConstantReader {
        factory ConstantReader(DartObject object) => ...
      
        // Other methods and properties also exist.
      
        /// Reads[ field] from the constant as another constant value.
        ConstantReader read(String field);
      
        /// Reads [field] from the constant as a boolean.
        ///
        /// If the resulting value is `null`, uses [defaultTo] if defined.
        bool readBool(String field, {bool defaultTo()});
      
        /// Reads [field] from the constant as an int.
        ///
        /// If the resulting value is `null`, uses [defaultTo] if defined.
        int readInt(String field, {int defaultTo()});
      
        /// Reads [field] from the constant as a string.
        ///
        /// If the resulting value is `null`, uses [defaultTo] if defined.
        String readString(String field, {String defaultTo()});
      }
      
    Source code(tar.gz)
    Source code(zip)
  • v0.5.8(Jun 1, 2017)

    Add formatOutput optional parameter to the GeneratorBuilder constructor. This is a lamda of the form String formatOutput(String originalCode) which allows you to do custom formatting.

    Source code(tar.gz)
    Source code(zip)
  • v0.5.4(Jan 27, 2017)

  • v0.5.1+5(Nov 1, 2016)

  • 0.5.1(Aug 5, 2016)

Owner
Dart
Dart is an open-source, scalable programming language, with robust libraries and runtimes, for building web, server, and mobile apps.
Dart
(mostly) Automatic search-enabled appBar for flutter

flutter_search_bar A simple and mostly automatic material search bar for flutter (dart). Note: use flutter_search_bar and not search_bar -- I own both

Spencer 266 Dec 31, 2022
Simple Dart package with build-in code generation. It simplifies and speedup creation of cache mechanism for dart classes.

Simple Dart package with build-in code generation. It simplifies and speedup creation of cache mechanism for dart classes.

iteo 37 Jan 2, 2023
Create dart data classes easily, fast and without writing boilerplate or running code generation.

Dart Data Class Generator Create dart data classes easily, fast and without writing boilerplate or running code generation. Features The generator can

null 186 Feb 28, 2022
This is an opinionated code-generation tool from GraphQL to Dart/Flutter.

GraphQL Codegen This is an opinionated code-generation tool from GraphQL to Dart/Flutter. It'll allow you to generate Dart serializers and client help

United Traders 1 Dec 29, 2021
A flutter plugin about qr code or bar code scan , it can scan from file、url、memory and camera qr code or bar code .Welcome to feedback your issue.

r_scan A flutter plugin about qr code or bar code scan , it can scan from file、url、memory and camera qr code or bar code .Welcome to feedback your iss

PengHui Li 112 Nov 11, 2022
💘 This is my Youtube tutorial of my Social Media App Generation Made in Flutter 💘

?? Generation Tutorial ?? ⌛ This is the project source code of my youtube video tutorial of ⌛ ?? Flutter Social Media App Tutorial 2021 ?? ?? Tutorial

Samarpan Dasgupta 17 Nov 24, 2022
Router_generator is a flutter library for router generation

Router_generator is a flutter library for router generation

Jelly Bean 20 Sep 27, 2022
POC fit-generation

fit_generation POC for fit-generation Table of content Table of content Project Description Getting started Git commit rules Navigation Deep Linking N

Andy 2 Jun 3, 2022
A fluent API for generating valid Dart source code

A fluent, builder-based library for generating valid Dart code. Usage code_builder has a narrow and user-friendly API. See the example and test folder

Dart 330 Jan 7, 2023
Enum extendable - Dart code generator. Generates enum extensions code.

Generates code for the extension on an enum. Overview Being able to add fields and methods to an enum. Let's say we have the following enum: enum Math

null 0 Jan 10, 2022
Write iOS&Android Code using Dart. This package liberates you from redundant glue code and low performance of Flutter Channel.

Dart_Native Dart_Native operates as both a code generator tool and a bridge to communicate between Dart and native APIs. Replaces the low-performing F

DartNative 893 Jan 4, 2023
Shader manages the compilation of your GLSL shaders into SPIR-V byte code and Dart code

shader Shader manages the compilation of your GLSL shaders into SPIR-V byte code and Dart code. Quickstart # Install cli dart pub global activate shad

Felix Blaschke 25 Dec 1, 2022
Repository containing source code for the tutorials made using with flutter

Flutter Tutorials Repository Containing Source code for tutorials found here: https://petercoding.com Note: Don't forgot to run pub get or just open p

Peter Haddad 19 Dec 9, 2022
The repo contains the source code for all the tutorials on the FilledStacks Youtube channel.

Flutter tutorials The repo contains the source code for all the written tutorials by Filledstacks. All Tutorials plus additional snippets and shorter

Dane Mackier 4.5k Dec 31, 2022
PalestineDevelopers is an open-source tools code-base

PalestineDevelopers مبادرة لإحياء إسم فلسطين بتقديم أدوات برمجية تحمل إسم أرض الميعاد Flutter Packages .. will be replaced .. will be replaced .. will

Mohamed Sayed 10 Jan 4, 2022
Fluttery - the source code of a quiz app about Flutter

Fluttery This repository aims to store the source code of a quiz app about Flutt

Naomi Lago 3 May 11, 2022
Source code for login demo in Coding with Flutter series

Flutter & Firebase Authentication demo Source code based on my Flutter & Firebase Authentication video series: Part 1 Part 2 Part 3 Part 4 Part 5 Part

Andrea Bizzotto 162 Dec 29, 2022
Source code of the "Sova – What? Where? When?" mobile application

WWW-flutter This repository contains source code of the "Sova – What? Where? When?" mobile application - an application for fans of the popular show "

Anna (Domashych) Leushchenko 51 Oct 1, 2022
Repository containing source code for the tutorials made using firebase with flutter

Firebase-Flutter Tutorials Repository Containing Source code for tutorials found here: https://petercoding.com Note: Don't forgot to run pub get or ju

Peter Haddad 231 Dec 21, 2022