Skip to content

Creating a stand-alone example #80

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Dec 14, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ dart:
- stable

env:
- PKG=example TASK=dartanalyzer
- PKG=example TASK=dartfmt
- PKG=example TASK=test
- PKG=json_annotation TASK=dartanalyzer
- PKG=json_annotation TASK=dartfmt
- PKG=json_serializable TASK=dartanalyzer
Expand All @@ -14,6 +17,10 @@ env:

matrix:
exclude:
- dart: stable
env: PKG=example TASK=dartanalyzer
- dart: stable
env: PKG=example TASK=dartfmt
- dart: stable
env: PKG=json_serializable TASK=dartanalyzer
- dart: stable
Expand Down
11 changes: 9 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# [![Build Status](https://travis-ci.org/dart-lang/json_serializable.svg?branch=master)](https://travis-ci.org/dart-lang/json_serializable)

Provides `source_gen` `Generator`s which generate code to
make it simple to serialize to and from JSON.
Provides [source_gen] `Generator`s to create code for JSON serialization and
deserialization.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we clearly state something like "To use this package, you need to install source_gen, by going here." ?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's no install, per se. You just put the right things in your pubspec.

I will make sure to mention that.


## [json_serializable]

Expand All @@ -15,5 +15,12 @@ The annotation package which has no dependencies.

Import it into your pubspec `dependencies:` section.

## [example]

A simple example showing how to setup and use [json_serializable] and

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm confused, where is the example?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See https://github.com/dart-lang/json_serializable/tree/example (although the link is broken because this isn't on master yet)

[json_annotation].

[json_serializable]: https://github.com/dart-lang/json_serializable/blob/master/json_serializable/README.md
[json_annotation]: https://github.com/dart-lang/json_serializable/blob/master/json_annotation/README.md
[example]: https://github.com/dart-lang/json_serializable/blob/master/example/README.md
[source_gen]: https://pub.dartlang.org/packages/source_gen
5 changes: 5 additions & 0 deletions example/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Files and directories created by pub
.packages
.pub/
build/
pubspec.lock
24 changes: 24 additions & 0 deletions example/.travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
language: dart
dart:
- dev
- stable

dart_task:
# Run the tests -- include the default-skipped presubmit tests
- test: --run-skipped

matrix:
include:
- dart: dev
dart_task:
dartfmt: sdk
- dart: dev
dart_task: dartanalyzer

# Only building master means that we don't run two builds for each pull request.
branches:
only: [master]

cache:
directories:
- $HOME/.pub-cache
23 changes: 23 additions & 0 deletions example/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
An simple example of a Dart package using [json_serializable].

* `lib/example.dart`: A library configured with annotations –
`JsonSerializable` and `JsonLiteral` – to enable code generation.

* Note: the annotations are defined in `package:json_annotation`.
This is the only package required in the `dependencies` section of your
`pubspec.yaml`.

* `tool/`: Contains the code run during development to create and update
generated code.

* `build_actions.dart`: A convention when using `package:build` to
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We actually should change this convention - having separate scripts means they have separate asset graphs which isn't what you want.

Instead you could add a flag to change whether it calls build/watch?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then I have to add args parsing, etc to the example.

I'd rather have dart-lang/build#718

have one location to define the actions to be run by `build.dart` and
`watch.dart`. See the comments in the source file for more information.

* `build.dart`: Runs one build using the actions defined in
`build_actions.dart`.

* `watch.dart`: Starts a watcher that (re)runs the actions defined in
`build_actions.dart` when files change.

[json_serializable]: https://pub.dartlang.org/packages/json_serializable
3 changes: 3 additions & 0 deletions example/dart_test.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
tags:
presubmit-only:
skip: "Should only be run during presubmit"
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// BSD-style license that can be found in the LICENSE file.

// ignore_for_file: annotate_overrides
library json_serializable.example;
library example;

import 'package:json_annotation/json_annotation.dart';
part 'example.g.dart';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

// GENERATED CODE - DO NOT MODIFY BY HAND

part of json_serializable.example;
part of example;

// **************************************************************************
// Generator: JsonSerializableGenerator
Expand Down
20 changes: 20 additions & 0 deletions example/pubspec.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: example
author: Dart Team <misc@dartlang.org>

environment:
sdk: '>=1.20.1 <2.0.0'

dependencies:
json_annotation: ^0.2.1

dev_dependencies:
build_runner: any
json_serializable: ^0.2.5
source_gen: ^0.7.2+1
test: ^0.12.29

dependency_overrides:
json_annotation:
path: ../json_annotation
json_serializable:
path: ../json_serializable
63 changes: 63 additions & 0 deletions example/test/ensure_build_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// TODO(kevmoo): replace with a common utility
// https://github.com/dart-lang/build/issues/716
@Tags(const ['presubmit-only'])

import 'dart:convert';
import 'dart:io';

import 'package:path/path.dart' as p;
import 'package:test/test.dart';

void main() {
String pkgRoot;

setUpAll(() {
pkgRoot = _runProc('git', ['rev-parse', '--show-toplevel']);
var currentDir = Directory.current.resolveSymbolicLinksSync();

if (!p.equals(p.join(pkgRoot, 'example'), currentDir)) {
throw new StateError('Expected the git root ($pkgRoot) '
'to match the current directory ($currentDir).');
}
});

test('ensure local build succeeds with no changes', () {
// 1 - get a list of modified `.g.dart` files - should be empty
expect(_changedGeneratedFiles(), isEmpty);

// 2 - run build - should be no output, since nothing should change
var result = _runProc('dart', ['--checked', 'tool/build.dart']);
expect(result,
contains(new RegExp(r'Build: Succeeded after \S+ with \d+ outputs')));

// 3 - get a list of modified `.g.dart` files - should still be empty
expect(_changedGeneratedFiles(), isEmpty);
});
}

final _whitespace = new RegExp(r'\s');

Set<String> _changedGeneratedFiles() {
var output = _runProc('git', ['status', '--porcelain']);

return LineSplitter
.split(output)
.map((line) => line.split(_whitespace).last)
.where((path) => path.endsWith('.dart'))
.toSet();
}

String _runProc(String proc, List<String> args) {
var result = Process.runSync(proc, args);

if (result.exitCode != 0) {
throw new ProcessException(
proc, args, result.stderr as String, result.exitCode);
}

return (result.stdout as String).trim();
}
28 changes: 28 additions & 0 deletions example/test/example_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:convert';

import 'package:example/example.dart';
import 'package:test/test.dart';

void main() {
test('JsonSerializable', () {
final person = new Person('Inigo', 'Montoya', new DateTime(1560, 5, 5));

final prettyJson = const JsonEncoder.withIndent(' ').convert(person);
print(prettyJson);

final person2 =
new Person.fromJson(JSON.decode(prettyJson) as Map<String, dynamic>);

expect(person.firstName, person2.firstName);
expect(person.lastName, person2.lastName);
expect(person.dateOfBirth, person2.dateOfBirth);
});

test('JsonLiteral', () {
expect(glossaryData, hasLength(1));
});
}
17 changes: 17 additions & 0 deletions example/tool/build.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#!/usr/bin/env dart --checked
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'dart:io';

import 'package:build_runner/build_runner.dart';

import 'build_actions.dart';

main() async {
var result = await build(buildActions, deleteFilesByDefault: true);
if (result.status == BuildStatus.failure) {
exitCode = 1;
}
}
46 changes: 46 additions & 0 deletions example/tool/build_actions.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

/// Defines the `BuildAction` class.
import 'package:build_runner/build_runner.dart';

// Defines `JsonSerializableGenerator` and `JsonLiteralGenerator`
import 'package:json_serializable/generators.dart';

// Defines `PartBuilder`
import 'package:source_gen/source_gen.dart';

// The list of `BuildAction`s used by `build.dart` and `watch.dart` to
// generate source code for this package.
List<BuildAction> get buildActions => [
new BuildAction(
// `PartBuilder` is a `Builder` defined by `package:source_gen` for
// generating Dart "part" files (.g.dart) given a set of generators.
new PartBuilder(const [
// Uses `@JsonSerializable()` annotations in source files to create
// helpers to support to/from JSON.

const JsonSerializableGenerator(),

// Uses @JsonLiteral('...') annotations in source files to create
// Dart literals for the provided JSON file.
const JsonLiteralGenerator()
], header: _copyrightContent),

// The name of the current package
'example',

// All of the files this `BuildAction` should target when run.
inputs: const [
'lib/*.dart',
],
),
];

final _copyrightContent =
'''// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

$defaultFileHeader''';
12 changes: 12 additions & 0 deletions example/tool/watch.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#!/usr/bin/env dart --checked
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:build_runner/build_runner.dart';

import 'build_actions.dart';

main() {
watch(buildActions, deleteFilesByDefault: true);
}
7 changes: 5 additions & 2 deletions json_annotation/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
Annotations for [json_serializable]. Use these to eliminate a production
dependency on `json_serializable` and the associated transitive dependencies.
Defines the annotations used by [json_serializable] to create code for JSON
serialization and deserialization.

See the [example] to understand how to configure your package.

## Features and bugs

Please file feature requests and bugs at the [issue tracker][tracker].

[example]: https://github.com/dart-lang/json_serializable/blob/master/example/README.md
[tracker]: https://github.com/dart-lang/json_serializable/issues
[json_serializable]: https://pub.dartlang.org/packages/json_serializable
3 changes: 2 additions & 1 deletion json_serializable/.travis.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
language: dart
sudo: false

dart:
- dev
- stable

dart_task:
# Run the tests -- include the default-skipped presubmit tests
- test: --run-skipped
Expand Down
13 changes: 9 additions & 4 deletions json_serializable/README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
[![Build Status](https://travis-ci.org/dart-lang/json_serializable.svg?branch=master)](https://travis-ci.org/dart-lang/json_serializable)

Provides `source_gen` `Generator`s which generate code to
make it simple to serialize to and from JSON.
Provides [source_gen] `Generator`s to create code for JSON serialization and
deserialization.

## Example
See the [example] package to understand how to configure your project.

## User defined and generated code

Given a library `example.dart` with an `Person` class annotated with
`@JsonSerializable()`:
Expand Down Expand Up @@ -38,7 +40,7 @@ class Person extends Object with _$PersonSerializerMixin {
}
```

`source_gen` creates the corresponding part `example.g.dart`:
Building creates the corresponding part `example.g.dart`:

```dart
Person _$PersonFromJson(Map<String, dynamic> json) => new Person(
Expand Down Expand Up @@ -78,3 +80,6 @@ abstract class _$PersonSerializerMixin {
}
}
```

[example]: https://github.com/dart-lang/json_serializable/blob/master/example/README.md
[source_gen]: https://pub.dartlang.org/packages/source_gen
2 changes: 2 additions & 0 deletions json_serializable/test/ensure_build_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

// TODO(kevmoo): replace with a common utility
// https://github.com/dart-lang/build/issues/716
@Tags(const ['presubmit-only'])

import 'dart:convert';
Expand Down
1 change: 0 additions & 1 deletion json_serializable/tool/build_actions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ final List<BuildAction> buildActions = [
header: _copyrightHeader),
'json_serializable',
inputs: const [
'example/*.dart',
'test/test_files/json_literal.dart',
'test/test_files/json_test_example.dart',
'test/test_files/json_test_example.non_nullable.dart',
Expand Down