code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
name: flop on: pull_request: paths: - "flop/**" - ".github/workflows/flop.yaml" branches: - main jobs: semantic-pull-request: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/semantic_pull_request.yml@v1 build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/flutter_package.yml@v1.12.0 with: flutter_channel: stable working_directory: flop min_coverage: 0
io_flip/.github/workflows/flop.yaml/0
{'file_path': 'io_flip/.github/workflows/flop.yaml', 'repo_id': 'io_flip', 'token_count': 196}
import 'package:json_annotation/json_annotation.dart'; part 'template_metadata.g.dart'; /// {@template metadata} /// Metadata for templates. /// {@endtemplate} @JsonSerializable() class TemplateMetadata { /// {@macro metadata} const TemplateMetadata({ required this.title, required this.description, required this.shareUrl, required this.favIconUrl, required this.ga, required this.gameUrl, required this.image, }); /// The title of the page. final String title; /// The description of the page. final String description; /// The share url. final String shareUrl; /// The favicon url. final String favIconUrl; /// The Google Analytics code. final String ga; /// The game url. final String gameUrl; /// The image url. final String image; /// Returns this instance as a json. Map<String, dynamic> toJson() { return _$TemplateMetadataToJson(this); } }
io_flip/api/lib/templates/template_metadata.dart/0
{'file_path': 'io_flip/api/lib/templates/template_metadata.dart', 'repo_id': 'io_flip', 'token_count': 298}
import 'dart:typed_data'; import 'package:card_renderer/card_renderer.dart'; import 'package:game_domain/game_domain.dart'; import 'package:http/http.dart'; import 'package:image/image.dart'; // Component Sizes const _cardSize = _Size(width: 327, height: 435); const _characterSize = _Size(width: 279, height: 279); const _descriptionSize = _Size(width: 263, height: 72); const _powerSpriteSize = _Size(width: 113, height: 64); // Component Positions const _titlePosition = 300; const _characterPosition = [24, 20]; const _powerSpritePosition = [218, 44]; const _descriptionPosition = [32, 345]; const _elementIconPositions = { Suit.air: [213, 12], Suit.earth: [210, 4], Suit.fire: [225, 2], Suit.water: [226, 3], Suit.metal: [220, 24], }; // Assets const _powerSpriteAsset = 'http://127.0.0.1:8080/assets/power-sprites.png'; const _titleFontAsset = 'http://127.0.0.1:8080/assets/Saira-Bold-28.ttf.zip'; const _descriptionFontAsset = 'http://127.0.0.1:8080/assets/GoogleSans-14.ttf.zip'; const _elementIconAssets = { Suit.air: 'http://127.0.0.1:8080/assets/icon-air.png', Suit.earth: 'http://127.0.0.1:8080/assets/icon-earth.png', Suit.fire: 'http://127.0.0.1:8080/assets/icon-fire.png', Suit.water: 'http://127.0.0.1:8080/assets/icon-water.png', Suit.metal: 'http://127.0.0.1:8080/assets/icon-metal.png', }; const _elementFrameAssets = { Suit.air: 'http://127.0.0.1:8080/assets/card-air.png', Suit.earth: 'http://127.0.0.1:8080/assets/card-earth.png', Suit.fire: 'http://127.0.0.1:8080/assets/card-fire.png', Suit.water: 'http://127.0.0.1:8080/assets/card-water.png', Suit.metal: 'http://127.0.0.1:8080/assets/card-metal.png', }; const _holoFrameAssets = { Suit.air: 'http://127.0.0.1:8080/assets/holos/card-air.png', Suit.earth: 'http://127.0.0.1:8080/assets/holos/card-earth.png', Suit.fire: 'http://127.0.0.1:8080/assets/holos/card-fire.png', Suit.water: 'http://127.0.0.1:8080/assets/holos/card-water.png', Suit.metal: 'http://127.0.0.1:8080/assets/holos/card-metal.png', }; /// {@template card_renderer_failure} /// Exception thrown when a card rendering fails. /// {@endtemplate} class CardRendererFailure implements Exception { /// {@macro card_renderer_failure} CardRendererFailure(this.message, this.stackTrace); /// Message describing the failure. final String message; /// Stack trace of the failure. final StackTrace stackTrace; @override String toString() => '[CardRendererFailure]: $message'; } /// Function definition to get an image from a [Uri] used by /// [CardRenderer]. typedef GetCall = Future<Response> Function(Uri uri); /// Function definition to create a [Command] used by [CardRenderer]. typedef CreateCommand = Command Function(); /// Function definition to parse a [BitmapFont] from a [Uint8List] used by /// [CardRenderer]. typedef ParseFont = BitmapFont Function(Uint8List); /// {@template card_renderer} /// Renders a card based on its metadata and character /// {@endtemplate} class CardRenderer { /// {@macro card_renderer} CardRenderer({ // Card Frames CreateCommand createCommand = Command.new, ParseFont parseFont = BitmapFont.fromZip, GetCall getCall = get, }) : _createCommand = createCommand, _parseFont = parseFont, _get = getCall; final GetCall _get; final CreateCommand _createCommand; final ParseFont _parseFont; Future<Uint8List> _getFile(Uri uri) async { final response = await _get(uri); if (response.statusCode != 200) { throw Exception('Failed to get image from $uri'); } return response.bodyBytes; } List<_Line> _splitText(String string, BitmapFont font, int width) { final words = string.split(RegExp(r'\s+')); final lines = <_Line>[]; var lineWidth = 0; var line = ''; for (var w in words) { final ws = StringBuffer() ..write(w) ..write(' '); w = ws.toString(); final chars = w.codeUnits; var wordWidth = 0; for (final c in chars) { if (!font.characters.containsKey(c)) { wordWidth += font.base ~/ 2; } else { wordWidth += font.characters[c]!.xAdvance; } } if ((lineWidth + wordWidth) < width) { line += w; lineWidth += wordWidth; } else { lines.add(_Line(line, lineWidth)); line = w; lineWidth = wordWidth; } } if (line.isNotEmpty) lines.add(_Line(line, lineWidth)); return lines; } /// Renders a [Card] to a [Uint8List] containing the PNG image. Future<Uint8List> renderCard(Card card) async { final power = _PowerSprite(power: card.power); final elementIcon = _ElementIcon(card.suit); try { final assets = await Future.wait([ _getFile(Uri.parse(card.image)), _getFile( Uri.parse( card.rarity ? _holoFrameAssets[card.suit]! : _elementFrameAssets[card.suit]!, ), ), _getFile(Uri.parse(_elementIconAssets[card.suit]!)), _getFile(Uri.parse(_powerSpriteAsset)), _getFile(Uri.parse(_descriptionFontAsset)), _getFile(Uri.parse(_titleFontAsset)), ]); final characterCmd = _createCommand() ..decodePng(assets.first) ..copyResize( width: _characterSize.width, height: _characterSize.height, interpolation: Interpolation.cubic, ); final frameCmd = _createCommand()..decodePng(assets[1]); final elementIconCmd = _createCommand()..decodePng(assets[2]); final powerSpriteCmd = _createCommand()..decodePng(assets[3]); final descriptionFont = _parseFont(assets[4]); final titleFont = _parseFont(assets[5]); final compositionCommand = _createCommand() ..createImage( width: _cardSize.width, height: _cardSize.height, numChannels: 4, ) ..convert(numChannels: 4, alpha: 0) ..compositeImage( characterCmd, dstX: _characterPosition.first, dstY: _characterPosition.last, ) ..compositeImage( frameCmd, dstX: 0, dstY: 0, ); if (card.rarity) { compositionCommand ..filter(rainbowFilter) ..chromaticAberration(shift: 2); } final titleLines = _splitText(card.name, titleFont, _cardSize.width); final titleLineHeight = titleFont.lineHeight; var titlePosition = _titlePosition; if (titleLines.length > 1) titlePosition -= titleLineHeight ~/ 2; for (var i = 0; i < titleLines.length; i++) { final line = titleLines[i]; compositionCommand.drawString( line.text.trimRight(), font: titleFont, x: ((_cardSize.width - line.width) / 2).round(), y: titlePosition + ((titleLineHeight - 15) * i), ); } final lineHeight = descriptionFont.lineHeight; final descriptionLines = _splitText(card.description, descriptionFont, _descriptionSize.width); for (var i = 0; i < descriptionLines.length; i++) { final line = descriptionLines[i]; compositionCommand.drawString( line.text.trimRight(), font: descriptionFont, x: _descriptionPosition.first + ((_descriptionSize.width - line.width) / 2).round(), y: _descriptionPosition.last + (lineHeight * i), ); } compositionCommand ..compositeImage( elementIconCmd, dstX: elementIcon.dstX, dstY: elementIcon.dstY, ) ..compositeImage( powerSpriteCmd, dstX: power.dstX, dstY: power.dstY, srcX: power.srcX, srcY: power.srcY, srcW: power.width, srcH: power.height, dstW: power.width, dstH: power.height, ) ..encodePng(); await compositionCommand.execute(); final output = compositionCommand.outputBytes; if (output == null) { throw CardRendererFailure('Failed to render card', StackTrace.current); } return output; } on CardRendererFailure { rethrow; } catch (e, s) { throw CardRendererFailure(e.toString(), s); } } /// Renders a list of [Card] to a [Uint8List] containing the PNG image. Future<Uint8List> renderDeck(List<Card> cards) async { try { final cardBytes = await Future.wait( cards.map(renderCard), ); final cardCommands = cardBytes .map( (e) => _createCommand()..decodePng(e), ) .toList(); final compositionCommand = _createCommand() ..createImage( width: _cardSize.width * cards.length + (20 * (cards.length - 1)), height: _cardSize.height, numChannels: 4, ); for (var i = 0; i < cards.length; i++) { compositionCommand.compositeImage( cardCommands[i], dstX: (_cardSize.width + 20) * i, ); } compositionCommand.encodePng(); await compositionCommand.execute(); final output = compositionCommand.outputBytes; if (output == null) { throw CardRendererFailure('Failed to render deck', StackTrace.current); } return output; } on CardRendererFailure { rethrow; } catch (e, s) { throw CardRendererFailure(e.toString(), s); } } } class _Size { const _Size({required this.height, required this.width}); final int height; final int width; } class _PowerSprite { const _PowerSprite({ required this.power, }); final int power; static const size = _powerSpriteSize; int get width => size.width; int get height => size.height; int get srcX => (power % 10) * size.width; int get srcY => (power ~/ 10) * size.height; int get dstX => (power == 100) ? _powerSpritePosition.first - 6 : _powerSpritePosition.first; int get dstY => _powerSpritePosition.last; } class _ElementIcon { const _ElementIcon(this.suit); final Suit suit; int get dstX => _elementIconPositions[suit]!.first; int get dstY => _elementIconPositions[suit]!.last; } class _Line { const _Line(this.text, this.width); final String text; final int width; }
io_flip/api/packages/card_renderer/lib/src/card_renderer.dart/0
{'file_path': 'io_flip/api/packages/card_renderer/lib/src/card_renderer.dart', 'repo_id': 'io_flip', 'token_count': 4345}
/// Key String representing empty attribute const emptyKey = 'EMPTY'; /// Key String representing a reserved room for a CPU match const reservedKey = 'RESERVED_EMPTY';
io_flip/api/packages/game_domain/lib/src/keys.dart/0
{'file_path': 'io_flip/api/packages/game_domain/lib/src/keys.dart', 'repo_id': 'io_flip', 'token_count': 43}
import 'package:equatable/equatable.dart'; import 'package:json_annotation/json_annotation.dart'; part 'prompt_term.g.dart'; /// The type of the prompt term. enum PromptTermType { /// Character. character, /// Character Class. characterClass, /// Primary power type. power, /// A location. location; } /// {@template prompt_term} /// A term used as a prompt for card generation. /// {@endtemplate} @JsonSerializable(ignoreUnannotated: true) class PromptTerm extends Equatable { /// {@macro prompt_term} const PromptTerm({ required this.term, required this.type, this.shortenedTerm, this.id, }); /// Creates a [PromptTerm] from a JSON object. factory PromptTerm.fromJson(Map<String, dynamic> json) => _$PromptTermFromJson(json); /// The id of the prompt term. @JsonKey() final String? id; /// The term of the prompt term. @JsonKey() final String term; /// The shortened term of the prompt term. @JsonKey() final String? shortenedTerm; /// The type of the prompt term. @JsonKey() final PromptTermType type; /// Converts a [PromptTerm] to a JSON object. Map<String, dynamic> toJson() => _$PromptTermToJson(this); @override List<Object?> get props => [id, term, shortenedTerm, type]; }
io_flip/api/packages/game_domain/lib/src/models/prompt_term.dart/0
{'file_path': 'io_flip/api/packages/game_domain/lib/src/models/prompt_term.dart', 'repo_id': 'io_flip', 'token_count': 429}
// ignore_for_file: prefer_const_constructors import 'package:game_domain/game_domain.dart'; import 'package:test/test.dart'; void main() { group('Prompt', () { test('can be instantiated', () { expect( Prompt(), isNotNull, ); }); test('Prompt correctly copies', () { const data1 = Prompt(); final data2 = data1 .copyWithNewAttribute('characterClass') .copyWithNewAttribute('power') .copyWithNewAttribute('secondaryPower'); expect( data2, equals( const Prompt( characterClass: 'characterClass', power: 'power', ), ), ); }); test('toJson returns the instance as json', () { expect( Prompt( characterClass: 'characterClass', power: 'power', ).toJson(), equals({ 'characterClass': 'characterClass', 'power': 'power', }), ); }); test('fromJson returns the correct instance', () { expect( Prompt.fromJson(const { 'characterClass': 'characterClass', 'power': 'power', }), equals( Prompt( characterClass: 'characterClass', power: 'power', ), ), ); }); test('supports equality', () { expect( Prompt( characterClass: 'characterClass', power: '', ), equals( Prompt( characterClass: 'characterClass', power: '', ), ), ); expect( Prompt( characterClass: '', power: 'power', ), equals( Prompt( characterClass: '', power: 'power', ), ), ); }); test('sets intro seen', () { final prompt = Prompt(); expect( prompt.setIntroSeen(), equals(Prompt(isIntroSeen: true)), ); }); }); }
io_flip/api/packages/game_domain/test/src/models/prompt_test.dart/0
{'file_path': 'io_flip/api/packages/game_domain/test/src/models/prompt_test.dart', 'repo_id': 'io_flip', 'token_count': 1020}
import 'dart:typed_data'; import 'package:clock/clock.dart'; import 'package:jwt_middleware/src/jwt.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import 'package:x509/x509.dart'; class _MockVerifier extends Mock implements Verifier<PublicKey> {} void main() { const validToken = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjFlOTczZWUwZTE2ZjdlZWY0ZjkyM' 'WQ1MGRjNjFkNzBiMmVmZWZjMTkiLCJ0eXAiOiJKV1QifQ.eyJwcm92aWRlcl9pZCI6ImFub2' '55bW91cyIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS90b3AtZGFzaC' '1kZXYiLCJhdWQiOiJ0b3AtZGFzaC1kZXYiLCJhdXRoX3RpbWUiOjE2NzkwNjUwNTEsInVzZX' 'JfaWQiOiJVUHlnNURKWHFuTmw0OWQ0YUJKV1Z6dmFKeDEyIiwic3ViIjoiVVB5ZzVESlhxbk' '5sNDlkNGFCSldWenZhSngxMiIsImlhdCI6MTY3OTA2NTA1MiwiZXhwIjoxNjc5MDY4NjUyLC' 'JmaXJlYmFzZSI6eyJpZGVudGl0aWVzIjp7fSwic2lnbl9pbl9wcm92aWRlciI6ImFub255bW' '91cyJ9fQ.v0DpGE7mKOwg4S6TbG_xxy5Spnfvb_Bdh7c_A_iW8RBPwt_XtN-3XK7h6Rv8-Z6' '5nkYIuLugJZTuC5rSnnwxb6Kn_p2lhYJZY5c1OdK9EvCfA47E3CIL621ujxcKGHOOUjJUZTr' '9dd8g0-FDagc0GbYFrGVRvwe5gcEDxRrAOMsbZoJ3D3IJAIiDTYFrQSAyF8LY_Cy6hMrBvdv' 'cpt29UML0rjcWdU5gB6u80rjOg_cgo5y3eWZOsOrYnKQd8iarrKDXFGRzPLgfDWEKJcRduXv' 'H_wIKqaprx2eK3FXiCDfhZDbwANzrfiVuI2HUcrqtdx78ylXTMMWPv4GNqJDodw'; const noSignatureToken = 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjFlOTczZWUwZTE2ZjdlZWY0ZjkyM' 'WQ1MGRjNjFkNzBiMmVmZWZjMTkiLCJ0eXAiOiJKV1QifQ.eyJwcm92aWRlcl9pZCI6ImFub2' '55bW91cyIsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS90b3AtZGFzaC' '1kZXYiLCJhdWQiOiJ0b3AtZGFzaC1kZXYiLCJhdXRoX3RpbWUiOjE2NzkwNjUwNTEsInVzZX' 'JfaWQiOiJVUHlnNURKWHFuTmw0OWQ0YUJKV1Z6dmFKeDEyIiwic3ViIjoiVVB5ZzVESlhxbk' '5sNDlkNGFCSldWenZhSngxMiIsImlhdCI6MTY3OTA2NTA1MiwiZXhwIjoxNjc5MDY4NjUyLC' 'JmaXJlYmFzZSI6eyJpZGVudGl0aWVzIjp7fSwic2lnbl9pbl9wcm92aWRlciI6ImFub255bW' '91cyJ9fQ.'; group('JWT', () { final body = Uint8List(4); final signature = Signature(Uint8List(8)); const nowSeconds = 1679079237; const projectId = 'PROJECT_ID'; final now = DateTime.fromMillisecondsSinceEpoch(nowSeconds * 1000); final clock = Clock.fixed(now); JWT buildSubject({ String? alg = 'RS256', int? exp = nowSeconds + 10800, int? iat = nowSeconds - 60, String? aud = projectId, String? iss = 'https://securetoken.google.com/$projectId', String? sub = 'userId', int? authTime = nowSeconds - 60, String? userId = 'userId', String? kid = '1e973ee0e16f7eef4f921d50dc61d70b2efefc19', }) => JWT( body: body, signature: signature, payload: { 'exp': exp, 'iat': iat, 'aud': aud, 'iss': iss, 'sub': sub, 'auth_time': authTime, 'user_id': userId, }, header: { 'alg': alg, 'kid': kid, }, ); group('from', () { test('parses a valid token', () { final jwt = JWT.from(validToken); expect(jwt.keyId, equals('1e973ee0e16f7eef4f921d50dc61d70b2efefc19')); expect(jwt.userId, equals('UPyg5DJXqnNl49d4aBJWVzvaJx12')); }); test('parses a token without a signature', () { final jwt = JWT.from(noSignatureToken); expect(jwt.keyId, equals('1e973ee0e16f7eef4f921d50dc61d70b2efefc19')); expect(jwt.userId, equals('UPyg5DJXqnNl49d4aBJWVzvaJx12')); }); }); group('userId', () { test('returns the user id', () { final jwt = buildSubject(); expect(jwt.userId, equals('userId')); }); test('returns null when the user id is not in the payload', () { final jwt = buildSubject(userId: null); expect(jwt.userId, isNull); }); }); group('keyId', () { test('returns the key id', () { final jwt = buildSubject(); expect(jwt.keyId, equals('1e973ee0e16f7eef4f921d50dc61d70b2efefc19')); }); test('returns null when the key id is not in the header', () { final jwt = buildSubject(kid: null); expect(jwt.keyId, isNull); }); }); group('verifyWith', () { test('uses the verifier to verify the signature', () { final jwt = buildSubject(); final verifier = _MockVerifier(); when(() => verifier.verify(body, signature)).thenReturn(true); final result = jwt.verifyWith(verifier); expect(result, isTrue); verify(() => verifier.verify(body, signature)).called(1); }); test('returns false when there is no signature', () { final jwt = JWT.from(noSignatureToken); final verifier = _MockVerifier(); final result = jwt.verifyWith(verifier); expect(result, isFalse); }); }); group('validate', () { test( 'returns true when valid', () => withClock(clock, () { final jwt = buildSubject(); expect(jwt.validate(projectId), isTrue); }), ); group('returns false', () { test('when alg is not RS256', () { final jwt = buildSubject(alg: 'invalid'); expect(jwt.validate(projectId), isFalse); }); test('when exp is null', () { final jwt = buildSubject(exp: null); expect(jwt.validate(projectId), isFalse); }); test('when iat is null', () { final jwt = buildSubject(iat: null); expect(jwt.validate(projectId), isFalse); }); test('when aud is null', () { final jwt = buildSubject(aud: null); expect(jwt.validate(projectId), isFalse); }); test('when iss is null', () { final jwt = buildSubject(iss: null); expect(jwt.validate(projectId), isFalse); }); test('when sub is null', () { final jwt = buildSubject(sub: null); expect(jwt.validate(projectId), isFalse); }); test('when auth_time is null', () { final jwt = buildSubject(authTime: null); expect(jwt.validate(projectId), isFalse); }); test('when user_id is null', () { final jwt = buildSubject(userId: null); expect(jwt.validate(projectId), isFalse); }); test( 'when exp is in the past', () => withClock(clock, () { final jwt = buildSubject(exp: nowSeconds - 1); expect(jwt.validate(projectId), isFalse); }), ); test( 'when exp is current', () => withClock(clock, () { final jwt = buildSubject(exp: nowSeconds); expect(jwt.validate(projectId), isFalse); }), ); test( 'when iat is in the future', () => withClock(clock, () { final jwt = buildSubject(iat: nowSeconds + 1); expect(jwt.validate(projectId), isFalse); }), ); test( 'when iat is current', () => withClock(clock, () { final jwt = buildSubject(iat: nowSeconds); expect(jwt.validate(projectId), isTrue); }), ); test( 'when auth_time is in the future', () => withClock(clock, () { final jwt = buildSubject(authTime: nowSeconds + 1); expect(jwt.validate(projectId), isFalse); }), ); test( 'when auth_time is current', () => withClock(clock, () { final jwt = buildSubject(authTime: nowSeconds); expect(jwt.validate(projectId), isTrue); }), ); test( 'when aud is not the project id', () => withClock(clock, () { final jwt = buildSubject(aud: 'invalid'); expect(jwt.validate(projectId), isFalse); }), ); test( 'when iss is not the expected url', () => withClock(clock, () { final jwt = buildSubject(iss: 'invalid'); expect(jwt.validate(projectId), isFalse); }), ); test( 'when sub is not the user id', () => withClock(clock, () { final jwt = buildSubject(sub: 'invalid'); expect(jwt.validate(projectId), isFalse); }), ); test( 'when user_id is not the user id', () => withClock(clock, () { final jwt = buildSubject(userId: 'invalid'); expect(jwt.validate(projectId), isFalse); }), ); }); }); }); }
io_flip/api/packages/jwt_middleware/test/src/jwt_test.dart/0
{'file_path': 'io_flip/api/packages/jwt_middleware/test/src/jwt_test.dart', 'repo_id': 'io_flip', 'token_count': 4644}
import 'dart:async'; import 'dart:io'; import 'package:cards_repository/cards_repository.dart'; import 'package:dart_frog/dart_frog.dart'; import 'package:jwt_middleware/jwt_middleware.dart'; import 'package:logging/logging.dart'; FutureOr<Response> onRequest(RequestContext context) { if (context.request.method == HttpMethod.post) { return _createDeck(context); } return Response(statusCode: HttpStatus.methodNotAllowed); } FutureOr<Response> _createDeck(RequestContext context) async { final json = await context.request.json() as Map<String, dynamic>; final cards = json['cards']; if (!_isListOfString(cards)) { context.read<Logger>().warning( 'Received invalid payload: $json', ); return Response(statusCode: HttpStatus.badRequest); } final ids = (cards as List).cast<String>(); final cardsRepository = context.read<CardsRepository>(); final user = context.read<AuthenticatedUser>(); final deckId = await cardsRepository.createDeck( cardIds: ids, userId: user.id, ); return Response.json(body: {'id': deckId}); } bool _isListOfString(dynamic value) { if (value is! List) { return false; } return value.whereType<String>().length == value.length; }
io_flip/api/routes/game/decks/index.dart/0
{'file_path': 'io_flip/api/routes/game/decks/index.dart', 'repo_id': 'io_flip', 'token_count': 437}
import 'dart:io'; import 'package:cards_repository/cards_repository.dart'; import 'package:dart_frog/dart_frog.dart'; import 'package:game_domain/game_domain.dart'; import 'package:mocktail/mocktail.dart'; import 'package:prompt_repository/prompt_repository.dart'; import 'package:test/test.dart'; import '../../../../routes/game/cards/index.dart' as route; class _MockRequestContext extends Mock implements RequestContext {} class _MockCardsRepository extends Mock implements CardsRepository {} class _MockPromptRepository extends Mock implements PromptRepository {} class _MockRequest extends Mock implements Request {} void main() { group('POST /game/cards', () { late CardsRepository cardsRepository; late PromptRepository promptRepository; late Request request; late RequestContext context; final cards = List.generate( 12, (_) => const Card( id: '', name: '', description: '', rarity: true, image: '', power: 1, suit: Suit.air, ), ); const prompt = Prompt( power: 'baggles', characterClass: 'mage', ); setUp(() { promptRepository = _MockPromptRepository(); cardsRepository = _MockCardsRepository(); when( () => cardsRepository.generateCards( characterClass: any(named: 'characterClass'), characterPower: any( named: 'characterPower', ), ), ).thenAnswer( (_) async => cards, ); request = _MockRequest(); when(() => request.method).thenReturn(HttpMethod.post); context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.request).thenReturn(request); when(request.json).thenAnswer((_) async => prompt.toJson()); when(() => context.read<CardsRepository>()).thenReturn(cardsRepository); when(() => context.read<PromptRepository>()).thenReturn(promptRepository); registerFallbackValue(prompt); when(() => promptRepository.isValidPrompt(any())) .thenAnswer((invocation) => Future.value(true)); }); test('responds with a 200', () async { final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.ok)); }); test('uses the character class and power from the prompt', () async { await route.onRequest(context); verify( () => cardsRepository.generateCards( characterClass: 'mage', characterPower: 'baggles', ), ).called(1); }); test('responds bad request when class is null', () async { when(request.json).thenAnswer( (_) async => const Prompt(power: '').toJson(), ); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.badRequest)); }); test('responds bad request when power is null', () async { when(request.json).thenAnswer( (_) async => const Prompt( characterClass: '', ).toJson(), ); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.badRequest)); }); test('responds with the generated card', () async { final response = await route.onRequest(context); final json = await response.json(); expect( json, equals({ 'cards': List.generate( 12, (index) => { 'id': '', 'name': '', 'description': '', 'rarity': true, 'image': '', 'power': 1, 'suit': 'air', 'shareImage': null, }, ), }), ); }); test('allows only post methods', () async { when(() => request.method).thenReturn(HttpMethod.get); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); test('invalid prompt returns Bad Request', () async { when(() => promptRepository.isValidPrompt(any())) .thenAnswer((invocation) => Future.value(false)); final response = await route.onRequest(context); expect(response.statusCode, equals(HttpStatus.badRequest)); }); }); }
io_flip/api/test/routes/game/cards/index_test.dart/0
{'file_path': 'io_flip/api/test/routes/game/cards/index_test.dart', 'repo_id': 'io_flip', 'token_count': 1760}
import 'dart:io'; import 'dart:typed_data'; import 'package:api/game_url.dart'; import 'package:card_renderer/card_renderer.dart'; import 'package:cards_repository/cards_repository.dart'; import 'package:dart_frog/dart_frog.dart'; import 'package:firebase_cloud_storage/firebase_cloud_storage.dart'; import 'package:game_domain/game_domain.dart'; import 'package:logging/logging.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import '../../../../routes/public/decks/[deckId].dart' as route; class _MockRequestContext extends Mock implements RequestContext {} class _MockRequest extends Mock implements Request {} class _MockCardRepository extends Mock implements CardsRepository {} class _MockCardRenderer extends Mock implements CardRenderer {} class _MockFirebaseCloudStorage extends Mock implements FirebaseCloudStorage {} class _MockLogger extends Mock implements Logger {} void main() { group('GET /public/decks/[deckId]', () { late Request request; late RequestContext context; late CardsRepository cardsRepository; late CardRenderer cardRenderer; late FirebaseCloudStorage firebaseCloudStorage; late Logger logger; const gameUrl = GameUrl('https://example.com'); final cards = List.generate( 3, (i) => Card( id: 'cardId$i', name: 'cardName$i', description: 'cardDescription', image: 'cardImageUrl', suit: Suit.fire, rarity: false, power: 10, ), ); final deck = Deck( id: 'deckId', cards: cards, userId: 'userId', ); setUpAll(() { registerFallbackValue(Uint8List(0)); registerFallbackValue(deck); }); setUp(() { request = _MockRequest(); when(() => request.method).thenReturn(HttpMethod.get); when(() => request.uri).thenReturn( Uri.parse('/public/decks/${deck.id}'), ); logger = _MockLogger(); cardsRepository = _MockCardRepository(); when(() => cardsRepository.getDeck(deck.id)).thenAnswer( (_) async => deck, ); when(() => cardsRepository.updateDeck(any())).thenAnswer( (_) async {}, ); cardRenderer = _MockCardRenderer(); when(() => cardRenderer.renderDeck(deck.cards)).thenAnswer( (_) async => Uint8List(0), ); context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.read<Logger>()).thenReturn(logger); when(() => context.read<GameUrl>()).thenReturn(gameUrl); when(() => context.read<CardsRepository>()).thenReturn(cardsRepository); when(() => context.read<CardRenderer>()).thenReturn(cardRenderer); firebaseCloudStorage = _MockFirebaseCloudStorage(); when(() => firebaseCloudStorage.uploadFile(any(), any())) .thenAnswer((_) async => 'https://example.com/share.png'); when(() => context.read<FirebaseCloudStorage>()) .thenReturn(firebaseCloudStorage); }); test('responds with a 200', () async { final response = await route.onRequest(context, deck.id); expect(response.statusCode, equals(HttpStatus.ok)); }); test('updates the deck with the share image', () async { await route.onRequest(context, deck.id); verify( () => cardsRepository.updateDeck( deck.copyWithShareImage('https://example.com/share.png'), ), ).called(1); }); test('redirects with the cached image if present', () async { when(() => cardsRepository.getDeck(deck.id)).thenAnswer( (_) async => deck.copyWithShareImage('https://example.com/share.png'), ); final response = await route.onRequest(context, deck.id); expect( response.statusCode, equals(HttpStatus.movedPermanently), ); expect( response.headers['location'], equals('https://example.com/share.png'), ); }); test('responds with a 404 if the card is not found', () async { when(() => cardsRepository.getDeck(deck.id)).thenAnswer( (_) async => null, ); final response = await route.onRequest(context, deck.id); expect(response.statusCode, equals(HttpStatus.notFound)); }); test('only allows get methods', () async { when(() => request.method).thenReturn(HttpMethod.post); final response = await route.onRequest(context, deck.id); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); }); }
io_flip/api/test/routes/public/decks/[deckId]_test.dart/0
{'file_path': 'io_flip/api/test/routes/public/decks/[deckId]_test.dart', 'repo_id': 'io_flip', 'token_count': 1755}
import 'package:game_domain/game_domain.dart'; /// A mapping of the CSV columns to the [PromptTermType]. const promptColumnMap = { 0: PromptTermType.character, 1: PromptTermType.characterClass, 2: PromptTermType.power, 4: PromptTermType.location, }; /// Given the [lines] of a CSV file, returns a map of [PromptTermType]; Map<PromptTermType, List<String>> mapCsvToPrompts(List<String> lines) { final map = { for (final term in PromptTermType.values) term: <String>[], }; for (final line in lines.skip(1)) { final parts = line.split(','); for (var j = 0; j < promptColumnMap.length; j++) { final idx = promptColumnMap.keys.elementAt(j); final type = promptColumnMap.values.elementAt(j); final value = parts[idx].trim(); if (value.isNotEmpty) { map[type]!.add(value); } } } return map; }
io_flip/api/tools/data_loader/lib/src/prompt_mapper.dart/0
{'file_path': 'io_flip/api/tools/data_loader/lib/src/prompt_mapper.dart', 'repo_id': 'io_flip', 'token_count': 324}
// ignore_for_file: avoid_web_libraries_in_flutter, avoid_print import 'dart:html'; import 'dart:js' as js; import 'package:flop/app/app.dart'; import 'package:flop/bootstrap.dart'; import 'package:flutter/foundation.dart'; void main() { bootstrap( () => App( setAppCheckDebugToken: (appCheckDebugToken) { if (kDebugMode) { js.context['FIREBASE_APPCHECK_DEBUG_TOKEN'] = appCheckDebugToken; } }, reload: () { window.location.reload(); }, ), ); }
io_flip/flop/lib/main.dart/0
{'file_path': 'io_flip/flop/lib/main.dart', 'repo_id': 'io_flip', 'token_count': 229}
part of 'connection_bloc.dart'; abstract class ConnectionEvent extends Equatable { const ConnectionEvent(); @override List<Object> get props => []; } class ConnectionRequested extends ConnectionEvent { const ConnectionRequested(); } class ConnectionClosed extends ConnectionEvent { const ConnectionClosed(); } class WebSocketMessageReceived extends ConnectionEvent { const WebSocketMessageReceived(this.message); final WebSocketMessage message; @override List<Object> get props => [message]; }
io_flip/lib/connection/bloc/connection_event.dart/0
{'file_path': 'io_flip/lib/connection/bloc/connection_event.dart', 'repo_id': 'io_flip', 'token_count': 136}
part of 'how_to_play_bloc.dart'; class HowToPlayState extends Equatable { const HowToPlayState({ this.position = 0, this.wheelSuits = const [ Suit.fire, Suit.air, Suit.metal, Suit.earth, Suit.water, ], }); final int position; final List<Suit> wheelSuits; static const steps = <Widget>[ HowToPlayIntro(), HowToPlayHandBuilding(), HowToPlaySuitsIntro(), ]; int get totalSteps => steps.length + wheelSuits.length; List<int> get affectedIndicatorIndexes { return wheelSuits.first.suitsAffected .map((e) => wheelSuits.indexOf(e) - 1) .toList(); } @override List<Object> get props => [position, wheelSuits]; HowToPlayState copyWith({ int? position, List<Suit>? wheelSuits, }) { return HowToPlayState( position: position ?? this.position, wheelSuits: wheelSuits ?? this.wheelSuits, ); } }
io_flip/lib/how_to_play/bloc/how_to_play_state.dart/0
{'file_path': 'io_flip/lib/how_to_play/bloc/how_to_play_state.dart', 'repo_id': 'io_flip', 'token_count': 374}
import 'package:api_client/api_client.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:game_domain/game_domain.dart'; part 'leaderboard_event.dart'; part 'leaderboard_state.dart'; class LeaderboardBloc extends Bloc<LeaderboardEvent, LeaderboardState> { LeaderboardBloc({ required LeaderboardResource leaderboardResource, }) : _leaderboardResource = leaderboardResource, super(const LeaderboardState.initial()) { on<LeaderboardRequested>(_onLeaderboardRequested); } final LeaderboardResource _leaderboardResource; Future<void> _onLeaderboardRequested( LeaderboardRequested event, Emitter<LeaderboardState> emit, ) async { try { emit(state.copyWith(status: LeaderboardStateStatus.loading)); final leaderboard = await _leaderboardResource.getLeaderboardResults(); emit( state.copyWith( leaderboard: leaderboard, status: LeaderboardStateStatus.loaded, ), ); } catch (e, s) { addError(e, s); emit(state.copyWith(status: LeaderboardStateStatus.failed)); } } }
io_flip/lib/leaderboard/bloc/leaderboard_bloc.dart/0
{'file_path': 'io_flip/lib/leaderboard/bloc/leaderboard_bloc.dart', 'repo_id': 'io_flip', 'token_count': 411}
// ignore_for_file: avoid_web_libraries_in_flutter import 'dart:async'; import 'dart:js' as js; import 'package:api_client/api_client.dart'; import 'package:authentication_repository/authentication_repository.dart'; import 'package:config_repository/config_repository.dart'; import 'package:connection_repository/connection_repository.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flutter/foundation.dart'; import 'package:game_domain/game_domain.dart'; import 'package:game_script_machine/game_script_machine.dart'; import 'package:io_flip/app/app.dart'; import 'package:io_flip/bootstrap.dart'; import 'package:io_flip/firebase_options_development.dart'; import 'package:io_flip/settings/persistence/persistence.dart'; import 'package:match_maker_repository/match_maker_repository.dart'; void main() async { js.context['FIREBASE_APPCHECK_DEBUG_TOKEN'] = const String.fromEnvironment('APPCHECK_DEBUG_TOKEN'); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); unawaited( bootstrap( (firestore, firebaseAuth, appCheck) async { await appCheck.activate( webRecaptchaSiteKey: const String.fromEnvironment('RECAPTCHA_KEY'), ); await appCheck.setTokenAutoRefreshEnabled(true); try { firestore.useFirestoreEmulator('localhost', 8081); await firebaseAuth.useAuthEmulator('localhost', 9099); } catch (e) { debugPrint(e.toString()); } final authenticationRepository = AuthenticationRepository( firebaseAuth: firebaseAuth, ); final apiClient = ApiClient( baseUrl: 'http://localhost:8080', idTokenStream: authenticationRepository.idToken, refreshIdToken: authenticationRepository.refreshIdToken, appCheckTokenStream: appCheck.onTokenChange, appCheckToken: await appCheck.getToken(), ); await authenticationRepository.signInAnonymously(); await authenticationRepository.idToken.first; final currentScript = await apiClient.scriptsResource.getCurrentScript(); final gameScriptMachine = GameScriptMachine.initialize(currentScript); return App( settingsPersistence: LocalStorageSettingsPersistence(), apiClient: apiClient, matchMakerRepository: MatchMakerRepository(db: firestore), configRepository: ConfigRepository(db: firestore), connectionRepository: ConnectionRepository(apiClient: apiClient), matchSolver: MatchSolver(gameScriptMachine: gameScriptMachine), gameScriptMachine: gameScriptMachine, user: await authenticationRepository.user.first, isScriptsEnabled: true, ); }, ), ); }
io_flip/lib/main_local.dart/0
{'file_path': 'io_flip/lib/main_local.dart', 'repo_id': 'io_flip', 'token_count': 1062}
import 'package:flutter/material.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/audio/audio.dart'; import 'package:io_flip/l10n/l10n.dart'; import 'package:io_flip/prompt/prompt.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class PromptFormIntroView extends StatelessWidget { const PromptFormIntroView({super.key}); static const _gap = SizedBox(height: IoFlipSpacing.xlg); @override Widget build(BuildContext context) { final l10n = context.l10n; return Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Expanded( child: Container( alignment: Alignment.center, constraints: const BoxConstraints(maxWidth: 516), padding: const EdgeInsets.symmetric(horizontal: IoFlipSpacing.xlg), child: SingleChildScrollView( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Stack( alignment: Alignment.topCenter, children: [ const CardMaster(), Column( children: [ SizedBox( height: CardMaster.cardMasterHeight - (PromptFormIntroView._gap.height! * 2), ), Text( l10n.niceToMeetYou, style: IoFlipTextStyles.headlineH4Light, textAlign: TextAlign.center, ), const SizedBox(height: IoFlipSpacing.sm), Text( l10n.introTextPromptPage, style: IoFlipTextStyles.headlineH6Light, textAlign: TextAlign.center, ), PromptFormIntroView._gap, ], ) ], ), ], ), ), ), ), IoFlipBottomBar( leading: const AudioToggleButton(), middle: RoundedButton.text( l10n.letsGetStarted, onPressed: () => context.updateFlow<Prompt>( (data) => data.setIntroSeen(), ), ), ), ], ); } }
io_flip/lib/prompt/view/prompt_form_intro_view.dart/0
{'file_path': 'io_flip/lib/prompt/view/prompt_form_intro_view.dart', 'repo_id': 'io_flip', 'token_count': 1454}
export 'card_fan.dart'; export 'share_dialog.dart';
io_flip/lib/share/widgets/widgets.dart/0
{'file_path': 'io_flip/lib/share/widgets/widgets.dart', 'repo_id': 'io_flip', 'token_count': 21}
// ignore_for_file: avoid_print, unused_local_variable import 'package:api_client/api_client.dart'; void main() async { const url = 'ws://top-dash-dev-api-synvj3dcmq-uc.a.run.app'; const localUrl = 'ws://localhost:8080'; final client = ApiClient( baseUrl: localUrl, idTokenStream: const Stream.empty(), refreshIdToken: () async => null, appCheckTokenStream: const Stream.empty(), ); final channel = await client.connect('public/connect'); channel.messages.listen(print); }
io_flip/packages/api_client/example/connect.dart/0
{'file_path': 'io_flip/packages/api_client/example/connect.dart', 'repo_id': 'io_flip', 'token_count': 177}
import 'dart:io'; import 'dart:typed_data'; import 'package:api_client/api_client.dart'; import 'package:http/http.dart' as http; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; class _MockApiClient extends Mock implements ApiClient {} class _MockResponse extends Mock implements http.Response {} void main() { group('ShareResource', () { late ApiClient apiClient; late ShareResource resource; late http.Response response; final bytes = Uint8List(8); setUp(() { apiClient = _MockApiClient(); response = _MockResponse(); when(() => apiClient.shareHandUrl(any())).thenReturn('handUrl'); when(() => apiClient.shareCardUrl(any())).thenReturn('cardUrl'); when(() => apiClient.getPublic(any())).thenAnswer((_) async => response); when(() => response.bodyBytes).thenReturn(bytes); resource = ShareResource( apiClient: apiClient, ); }); test('can be instantiated', () { expect( resource, isNotNull, ); }); test('twitterShareHandUrl returns the correct url', () { expect( resource.twitterShareHandUrl('id'), contains('handUrl'), ); }); test('twitterShareCardUrl returns the correct url', () { expect( resource.twitterShareCardUrl('id'), contains('cardUrl'), ); }); test('facebookShareHandUrl returns the correct url', () { expect( resource.facebookShareHandUrl('id'), contains('handUrl'), ); }); test('facebookShareCardUrl returns the correct url', () { expect( resource.facebookShareCardUrl('id'), contains('cardUrl'), ); }); group('getShareCardImage', () { test('returns a Card', () async { when(() => response.statusCode).thenReturn(HttpStatus.ok); final imageResponse = await resource.getShareCardImage(''); expect(imageResponse, equals(bytes)); }); test('throws ApiClientError when request fails', () async { when(() => response.statusCode) .thenReturn(HttpStatus.internalServerError); when(() => response.body).thenReturn('Ops'); await expectLater( resource.getShareCardImage('1'), throwsA( isA<ApiClientError>().having( (e) => e.cause, 'cause', equals( 'GET public/cards/1 returned status 500 with the following response: "Ops"', ), ), ), ); }); }); group('getShareDeckImage', () { test('returns a Card', () async { when(() => response.statusCode).thenReturn(HttpStatus.ok); final imageResponse = await resource.getShareDeckImage(''); expect(imageResponse, equals(bytes)); }); test('throws ApiClientError when request fails', () async { when(() => response.statusCode) .thenReturn(HttpStatus.internalServerError); when(() => response.body).thenReturn('Ops'); await expectLater( resource.getShareDeckImage('1'), throwsA( isA<ApiClientError>().having( (e) => e.cause, 'cause', equals( 'GET public/decks/1 returned status 500 with the following response: "Ops"', ), ), ), ); }); }); }); }
io_flip/packages/api_client/test/src/resources/share_resource_test.dart/0
{'file_path': 'io_flip/packages/api_client/test/src/resources/share_resource_test.dart', 'repo_id': 'io_flip', 'token_count': 1473}
/// Repository for match making. library match_maker_repository; export 'src/config_repository.dart';
io_flip/packages/config_repository/lib/config_repository.dart/0
{'file_path': 'io_flip/packages/config_repository/lib/config_repository.dart', 'repo_id': 'io_flip', 'token_count': 33}
import 'package:io_flip_ui/gen/assets.gen.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; /// {@template fire_damage} // ignore: comment_references /// A widget that renders several [SpriteAnimation]s for the damages /// of a card on another. /// {@endtemplate} class FireDamage extends ElementalDamage { /// {@macro fire_damage} FireDamage({required super.size}) : super( chargeBackPath: Assets.images.elements.desktop.fire.chargeBack.keyName, chargeFrontPath: Assets.images.elements.desktop.fire.chargeFront.keyName, damageReceivePath: Assets.images.elements.desktop.fire.damageReceive.keyName, damageSendPath: Assets.images.elements.desktop.fire.damageSend.keyName, victoryChargeBackPath: Assets.images.elements.desktop.fire.victoryChargeBack.keyName, victoryChargeFrontPath: Assets.images.elements.desktop.fire.victoryChargeFront.keyName, badgePath: Assets.images.suits.card.fire.keyName, animationColor: IoFlipColors.seedGold, ); }
io_flip/packages/io_flip_ui/lib/src/animations/damages/fire_damage.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/lib/src/animations/damages/fire_damage.dart', 'repo_id': 'io_flip', 'token_count': 467}
import 'package:device_info_plus/device_info_plus.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/foundation.dart'; /// Definition of a platform aware asset function. typedef PlatformAwareAsset<T> = T Function({ required T desktop, required T mobile, bool isWeb, TargetPlatform? overrideDefaultTargetPlatform, }); /// Returns an asset based on the current platform. T platformAwareAsset<T>({ required T desktop, required T mobile, bool isWeb = kIsWeb, TargetPlatform? overrideDefaultTargetPlatform, }) { final platform = overrideDefaultTargetPlatform ?? defaultTargetPlatform; final isWebMobile = isWeb && (platform == TargetPlatform.iOS || platform == TargetPlatform.android); return isWebMobile ? mobile : desktop; } /// {@template device_info} /// Model with device information. /// {@endtemplate} class DeviceInfo extends Equatable { /// {@macro device_info} const DeviceInfo({ required this.osVersion, required this.platform, }); /// The OS version of the device. final int osVersion; /// The platform of the device. final TargetPlatform platform; @override List<Object?> get props => [osVersion, platform]; } /// A predicate that checks if the device is an older Android. bool isOlderAndroid(DeviceInfo deviceInfo) { return deviceInfo.platform == TargetPlatform.android && deviceInfo.osVersion <= 11; } /// A predicate that checks if the device is an android device. bool isAndroid(DeviceInfo deviceInfo) { return deviceInfo.platform == TargetPlatform.android; } /// Platform aware predicate. typedef DeviceInfoPredicate = bool Function(DeviceInfo deviceInfo); /// Device aware predicate. typedef DeviceInfoAwareAsset<T> = Future<T> Function({ required DeviceInfoPredicate predicate, required T Function() asset, required T Function() orElse, }); /// Returns an asset based on the device information. Future<T> deviceInfoAwareAsset<T>({ required DeviceInfoPredicate predicate, required T Function() asset, required T Function() orElse, TargetPlatform? overrideDefaultTargetPlatform, DeviceInfoPlugin? overrideDeviceInfoPlugin, }) async { final deviceInfo = overrideDeviceInfoPlugin ?? DeviceInfoPlugin(); final platform = overrideDefaultTargetPlatform ?? defaultTargetPlatform; late DeviceInfo info; if (platform == TargetPlatform.iOS || platform == TargetPlatform.android) { final webInfo = await deviceInfo.webBrowserInfo; final userAgent = webInfo.userAgent; try { late int version; if (platform == TargetPlatform.android) { version = int.parse( userAgent?.split('Android ')[1].split(';')[0].split('.')[0] ?? '', ); } else { version = int.parse( userAgent?.split('Version/')[1].split(' Mobile')[0].split('.')[0] ?? '', ); } info = DeviceInfo( osVersion: version, platform: platform, ); } catch (_) { return orElse(); } } else { return orElse(); } if (predicate(info)) { return asset(); } else { return orElse(); } }
io_flip/packages/io_flip_ui/lib/src/utils/platform_aware_asset.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/lib/src/utils/platform_aware_asset.dart', 'repo_id': 'io_flip', 'token_count': 984}
import 'package:flutter/material.dart'; import 'package:flutter_shaders/flutter_shaders.dart'; /// {@template foil_shader} /// A widget that applies a "foil" shader to its child. The foil shader /// is a shader that applies an effect similar to a shiny metallic card. /// {@endtemplate} class FoilShader extends StatelessWidget { /// {@macro foil_shader} const FoilShader({ required this.child, super.key, this.dx = 0, this.dy = 0, this.package = 'io_flip_ui', }); /// The optional x offset of the foil shader. /// /// This can be used for parallax. final double dx; /// The optional y offset of the foil shader. /// /// This can be used for parallax. final double dy; /// The name of the package from which the shader is included. /// /// This is used to resolve the shader asset key. final String? package; /// The child widget to apply the foil shader to. final Widget child; static const String _assetPath = 'shaders/foil.frag'; String get _assetKey => package == null ? _assetPath : 'packages/$package/$_assetPath'; @override Widget build(BuildContext context) { late final devicePixelRatio = MediaQuery.of(context).devicePixelRatio; return ShaderBuilder( assetKey: _assetKey, (context, shader, child) { return AnimatedSampler( (image, size, canvas) { shader ..setFloat(0, image.width.toDouble() / devicePixelRatio) ..setFloat(1, image.height.toDouble() / devicePixelRatio) ..setFloat(2, dx) ..setFloat(3, dy) ..setImageSampler(0, image); canvas.drawRect( Offset.zero & size, Paint()..shader = shader, ); }, child: child!, ); }, child: child, ); } }
io_flip/packages/io_flip_ui/lib/src/widgets/foil_shader.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/lib/src/widgets/foil_shader.dart', 'repo_id': 'io_flip', 'token_count': 739}
import 'dart:async'; import 'package:flame/cache.dart'; import 'package:flame/widgets.dart'; import 'package:flutter/material.dart' hide Element; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/gen/assets.gen.dart'; import 'package:io_flip_ui/src/animations/animations.dart'; import 'package:io_flip_ui/src/widgets/damages/damages.dart'; import 'package:io_flip_ui/src/widgets/damages/dual_animation.dart'; import 'package:io_flip_ui/src/widgets/game_card.dart'; import 'package:provider/provider.dart'; void main() { group('ElementalDamageAnimation', () { final findEmpty = find.byKey(const Key('elementalDamage_empty')); late Images images; setUp(() async { images = Images(prefix: ''); await images.loadAll([ ...Assets.images.elements.desktop.air.values.map((e) => e.keyName), ...Assets.images.elements.desktop.earth.values.map((e) => e.keyName), ...Assets.images.elements.desktop.fire.values.map((e) => e.keyName), ...Assets.images.elements.desktop.metal.values.map((e) => e.keyName), ...Assets.images.elements.desktop.water.values.map((e) => e.keyName), ...Assets.images.elements.mobile.air.values.map((e) => e.keyName), ...Assets.images.elements.mobile.earth.values.map((e) => e.keyName), ...Assets.images.elements.mobile.fire.values.map((e) => e.keyName), ...Assets.images.elements.mobile.metal.values.map((e) => e.keyName), ...Assets.images.elements.mobile.water.values.map((e) => e.keyName), ]); }); group('With large assets', () { group('MetalDamage', () { testWidgets('renders entire animations flow', (tester) async { final stepNotifier = ElementalDamageStepNotifier(); final completer = Completer<void>(); await tester.runAsync(() async { await tester.pumpWidget( Provider.value( value: images, child: Directionality( textDirection: TextDirection.ltr, child: ElementalDamageAnimation( Element.metal, direction: DamageDirection.topToBottom, initialState: DamageAnimationState.charging, size: const GameCardSize.md(), stepNotifier: stepNotifier, pointDeductionCompleter: completer, ), ), ), ); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsNWidgets(2)); expect(find.byType(ChargeBack), findsOneWidget); expect(find.byType(ChargeFront), findsOneWidget); var chargedComplete = false; unawaited( stepNotifier.charged.then( (_) { chargedComplete = true; }, ), ); while (!chargedComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(find.byType(DamageSend), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsOneWidget); var sendComplete = false; unawaited( stepNotifier.sent.then( (_) { sendComplete = true; }, ), ); while (!sendComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(find.byType(DamageReceive), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsOneWidget); var receiveComplete = false; unawaited( stepNotifier.received.then( (_) { receiveComplete = true; }, ), ); while (!receiveComplete) { await tester.pump(const Duration(milliseconds: 17)); } completer.complete(); await tester.pump(); expect(findEmpty, findsOneWidget); await tester.pump(); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsNWidgets(2)); expect(find.byType(VictoryChargeBack), findsOneWidget); expect(find.byType(VictoryChargeFront), findsOneWidget); var victoryComplete = false; unawaited( stepNotifier.victory.then( (_) { victoryComplete = true; }, ), ); while (!victoryComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(findEmpty, findsOneWidget); }); }); }); group('AirDamage', () { testWidgets('renders entire animations flow', (tester) async { final stepNotifier = ElementalDamageStepNotifier(); final completer = Completer<void>(); await tester.runAsync(() async { await tester.pumpWidget( Provider.value( value: images, child: Directionality( textDirection: TextDirection.ltr, child: ElementalDamageAnimation( Element.air, direction: DamageDirection.topToBottom, size: const GameCardSize.md(), initialState: DamageAnimationState.charging, stepNotifier: stepNotifier, pointDeductionCompleter: completer, ), ), ), ); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsNWidgets(2)); expect(find.byType(ChargeBack), findsOneWidget); expect(find.byType(ChargeFront), findsOneWidget); var chargedComplete = false; unawaited( stepNotifier.charged.then( (_) { chargedComplete = true; }, ), ); while (!chargedComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(find.byType(DamageSend), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsOneWidget); var sendComplete = false; unawaited( stepNotifier.sent.then( (_) { sendComplete = true; }, ), ); while (!sendComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(find.byType(DamageReceive), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsOneWidget); var receiveComplete = false; unawaited( stepNotifier.received.then( (_) { receiveComplete = true; }, ), ); while (!receiveComplete) { await tester.pump(const Duration(milliseconds: 17)); } completer.complete(); await tester.pump(); expect(findEmpty, findsOneWidget); await tester.pump(); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsNWidgets(2)); expect(find.byType(VictoryChargeBack), findsOneWidget); expect(find.byType(VictoryChargeFront), findsOneWidget); var victoryComplete = false; unawaited( stepNotifier.victory.then( (_) { victoryComplete = true; }, ), ); while (!victoryComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(findEmpty, findsOneWidget); }); }); }); group('FireDamage', () { testWidgets('renders entire animations flow', (tester) async { final stepNotifier = ElementalDamageStepNotifier(); final completer = Completer<void>(); await tester.runAsync(() async { await tester.pumpWidget( Provider.value( value: images, child: Directionality( textDirection: TextDirection.ltr, child: ElementalDamageAnimation( Element.fire, direction: DamageDirection.bottomToTop, initialState: DamageAnimationState.charging, size: const GameCardSize.md(), stepNotifier: stepNotifier, pointDeductionCompleter: completer, ), ), ), ); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsNWidgets(2)); expect(find.byType(ChargeBack), findsOneWidget); expect(find.byType(ChargeFront), findsOneWidget); var chargedComplete = false; unawaited( stepNotifier.charged.then( (_) { chargedComplete = true; }, ), ); while (!chargedComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(find.byType(DamageSend), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsOneWidget); var sendComplete = false; unawaited( stepNotifier.sent.then( (_) { sendComplete = true; }, ), ); while (!sendComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(find.byType(DamageReceive), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsOneWidget); var receiveComplete = false; unawaited( stepNotifier.received.then( (_) { receiveComplete = true; }, ), ); while (!receiveComplete) { await tester.pump(const Duration(milliseconds: 17)); } completer.complete(); await tester.pump(); expect(findEmpty, findsOneWidget); await tester.pump(); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsNWidgets(2)); expect(find.byType(VictoryChargeBack), findsOneWidget); expect(find.byType(VictoryChargeFront), findsOneWidget); var victoryComplete = false; unawaited( stepNotifier.victory.then( (_) { victoryComplete = true; }, ), ); while (!victoryComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(findEmpty, findsOneWidget); }); }); }); group('EarthDamage', () { testWidgets('renders entire animations flow', (tester) async { final stepNotifier = ElementalDamageStepNotifier(); final completer = Completer<void>(); await tester.runAsync(() async { await tester.pumpWidget( Provider.value( value: images, child: Directionality( textDirection: TextDirection.ltr, child: ElementalDamageAnimation( Element.earth, direction: DamageDirection.topToBottom, initialState: DamageAnimationState.charging, size: const GameCardSize.md(), stepNotifier: stepNotifier, pointDeductionCompleter: completer, ), ), ), ); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsNWidgets(2)); expect(find.byType(ChargeBack), findsOneWidget); expect(find.byType(ChargeFront), findsOneWidget); var chargedComplete = false; unawaited( stepNotifier.charged.then( (_) { chargedComplete = true; }, ), ); while (!chargedComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(find.byType(DamageSend), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsOneWidget); var sendComplete = false; unawaited( stepNotifier.sent.then( (_) { sendComplete = true; }, ), ); while (!sendComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(find.byType(DamageReceive), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsOneWidget); var receiveComplete = false; unawaited( stepNotifier.received.then( (_) { receiveComplete = true; }, ), ); while (!receiveComplete) { await tester.pump(const Duration(milliseconds: 17)); } completer.complete(); await tester.pump(); expect(findEmpty, findsOneWidget); await tester.pump(); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsNWidgets(2)); expect(find.byType(VictoryChargeBack), findsOneWidget); expect(find.byType(VictoryChargeFront), findsOneWidget); var victoryComplete = false; unawaited( stepNotifier.victory.then( (_) { victoryComplete = true; }, ), ); while (!victoryComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(findEmpty, findsOneWidget); }); }); }); group('WaterDamage', () { testWidgets('renders entire animations flow', (tester) async { final stepNotifier = ElementalDamageStepNotifier(); final completer = Completer<void>(); await tester.runAsync(() async { await tester.pumpWidget( Provider.value( value: images, child: Directionality( textDirection: TextDirection.ltr, child: ElementalDamageAnimation( Element.water, direction: DamageDirection.topToBottom, initialState: DamageAnimationState.charging, size: const GameCardSize.md(), stepNotifier: stepNotifier, pointDeductionCompleter: completer, ), ), ), ); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsNWidgets(2)); expect(find.byType(ChargeBack), findsOneWidget); expect(find.byType(ChargeFront), findsOneWidget); var chargedComplete = false; unawaited( stepNotifier.charged.then( (_) { chargedComplete = true; }, ), ); while (!chargedComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(find.byType(DamageSend), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsOneWidget); var sendComplete = false; unawaited( stepNotifier.sent.then( (_) { sendComplete = true; }, ), ); while (!sendComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(find.byType(DamageReceive), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsOneWidget); var receiveComplete = false; unawaited( stepNotifier.received.then( (_) { receiveComplete = true; }, ), ); while (!receiveComplete) { await tester.pump(const Duration(milliseconds: 17)); } completer.complete(); await tester.pump(); expect(findEmpty, findsOneWidget); await tester.pump(); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(SpriteAnimationWidget), findsNWidgets(2)); expect(find.byType(VictoryChargeBack), findsOneWidget); expect(find.byType(VictoryChargeFront), findsOneWidget); var victoryComplete = false; unawaited( stepNotifier.victory.then( (_) { victoryComplete = true; }, ), ); while (!victoryComplete) { await tester.pump(const Duration(milliseconds: 17)); } expect(findEmpty, findsOneWidget); }); }); }); }); group('With small assets', () { group('MetalDamage', () { testWidgets('renders entire animations flow', (tester) async { final stepNotifier = ElementalDamageStepNotifier(); final completer = Completer<void>(); await tester.pumpWidget( Provider.value( value: images, child: Directionality( textDirection: TextDirection.ltr, child: ElementalDamageAnimation( Element.metal, direction: DamageDirection.bottomToTop, size: const GameCardSize.md(), initialState: DamageAnimationState.charging, assetSize: AssetSize.small, stepNotifier: stepNotifier, pointDeductionCompleter: completer, ), ), ), ); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(ChargeBack), findsOneWidget); expect(find.byType(ChargeFront), findsOneWidget); var chargedComplete = false; unawaited( stepNotifier.charged.then( (_) { chargedComplete = true; }, ), ); while (!chargedComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } expect(find.byType(DamageSend), findsOneWidget); var sendComplete = false; unawaited( stepNotifier.sent.then( (_) { sendComplete = true; }, ), ); while (!sendComplete) { await tester.pump(const Duration(milliseconds: 15)); } expect(find.byType(DamageReceive), findsOneWidget); var receiveComplete = false; unawaited( stepNotifier.received.then( (_) { receiveComplete = true; }, ), ); while (!receiveComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } completer.complete(); await tester.pump(); expect(findEmpty, findsOneWidget); await tester.pump(); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(VictoryChargeBack), findsOneWidget); expect(find.byType(VictoryChargeFront), findsOneWidget); var victoryComplete = false; unawaited( stepNotifier.victory.then( (_) { victoryComplete = true; }, ), ); while (!victoryComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } expect(findEmpty, findsOneWidget); }); }); group('AirDamage', () { testWidgets('renders entire animations flow', (tester) async { final stepNotifier = ElementalDamageStepNotifier(); final completer = Completer<void>(); await tester.pumpWidget( Provider.value( value: images, child: Directionality( textDirection: TextDirection.ltr, child: ElementalDamageAnimation( Element.air, direction: DamageDirection.topToBottom, size: const GameCardSize.md(), initialState: DamageAnimationState.charging, assetSize: AssetSize.small, stepNotifier: stepNotifier, pointDeductionCompleter: completer, ), ), ), ); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(ChargeBack), findsOneWidget); expect(find.byType(ChargeFront), findsOneWidget); var chargedComplete = false; unawaited( stepNotifier.charged.then( (_) { chargedComplete = true; }, ), ); while (!chargedComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } expect(find.byType(DamageSend), findsOneWidget); var sendComplete = false; unawaited( stepNotifier.sent.then( (_) { sendComplete = true; }, ), ); while (!sendComplete) { await tester.pump(const Duration(milliseconds: 15)); } expect(find.byType(DamageReceive), findsOneWidget); var receiveComplete = false; unawaited( stepNotifier.received.then( (_) { receiveComplete = true; }, ), ); while (!receiveComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } completer.complete(); await tester.pump(); expect(findEmpty, findsOneWidget); await tester.pump(); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(VictoryChargeBack), findsOneWidget); expect(find.byType(VictoryChargeFront), findsOneWidget); var victoryComplete = false; unawaited( stepNotifier.victory.then( (_) { victoryComplete = true; }, ), ); while (!victoryComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } expect(findEmpty, findsOneWidget); }); }); group('FireDamage', () { testWidgets('renders entire animations flow', (tester) async { final stepNotifier = ElementalDamageStepNotifier(); final completer = Completer<void>(); await tester.pumpWidget( Provider.value( value: images, child: Directionality( textDirection: TextDirection.ltr, child: ElementalDamageAnimation( Element.fire, direction: DamageDirection.topToBottom, size: const GameCardSize.md(), initialState: DamageAnimationState.charging, assetSize: AssetSize.small, stepNotifier: stepNotifier, pointDeductionCompleter: completer, ), ), ), ); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(ChargeBack), findsOneWidget); expect(find.byType(ChargeFront), findsOneWidget); var chargedComplete = false; unawaited( stepNotifier.charged.then( (_) { chargedComplete = true; }, ), ); while (!chargedComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } expect(find.byType(DamageSend), findsOneWidget); var sendComplete = false; unawaited( stepNotifier.sent.then( (_) { sendComplete = true; }, ), ); while (!sendComplete) { await tester.pump(const Duration(milliseconds: 15)); } expect(find.byType(DamageReceive), findsOneWidget); var receiveComplete = false; unawaited( stepNotifier.received.then( (_) { receiveComplete = true; }, ), ); while (!receiveComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } completer.complete(); await tester.pump(); expect(findEmpty, findsOneWidget); await tester.pump(); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(VictoryChargeBack), findsOneWidget); expect(find.byType(VictoryChargeFront), findsOneWidget); var victoryComplete = false; unawaited( stepNotifier.victory.then( (_) { victoryComplete = true; }, ), ); while (!victoryComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } expect(findEmpty, findsOneWidget); }); }); group('EarthDamage', () { testWidgets('renders entire animations flow', (tester) async { final stepNotifier = ElementalDamageStepNotifier(); final completer = Completer<void>(); await tester.pumpWidget( Provider.value( value: images, child: Directionality( textDirection: TextDirection.ltr, child: ElementalDamageAnimation( Element.earth, direction: DamageDirection.topToBottom, size: const GameCardSize.md(), initialState: DamageAnimationState.charging, assetSize: AssetSize.small, stepNotifier: stepNotifier, pointDeductionCompleter: completer, ), ), ), ); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(ChargeBack), findsOneWidget); expect(find.byType(ChargeFront), findsOneWidget); var chargedComplete = false; unawaited( stepNotifier.charged.then( (_) { chargedComplete = true; }, ), ); while (!chargedComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } expect(find.byType(DamageSend), findsOneWidget); var sendComplete = false; unawaited( stepNotifier.sent.then( (_) { sendComplete = true; }, ), ); while (!sendComplete) { await tester.pump(const Duration(milliseconds: 15)); } expect(find.byType(DamageReceive), findsOneWidget); var receiveComplete = false; unawaited( stepNotifier.received.then( (_) { receiveComplete = true; }, ), ); while (!receiveComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } completer.complete(); await tester.pump(); expect(findEmpty, findsOneWidget); await tester.pump(); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(VictoryChargeBack), findsOneWidget); expect(find.byType(VictoryChargeFront), findsOneWidget); var victoryComplete = false; unawaited( stepNotifier.victory.then( (_) { victoryComplete = true; }, ), ); while (!victoryComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } expect(findEmpty, findsOneWidget); }); }); group('WaterDamage', () { testWidgets('renders entire animations flow', (tester) async { final stepNotifier = ElementalDamageStepNotifier(); final completer = Completer<void>(); await tester.pumpWidget( Provider.value( value: images, child: Directionality( textDirection: TextDirection.ltr, child: ElementalDamageAnimation( Element.water, direction: DamageDirection.topToBottom, size: const GameCardSize.md(), initialState: DamageAnimationState.charging, assetSize: AssetSize.small, stepNotifier: stepNotifier, pointDeductionCompleter: completer, ), ), ), ); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(ChargeBack), findsOneWidget); expect(find.byType(ChargeFront), findsOneWidget); var chargedComplete = false; unawaited( stepNotifier.charged.then( (_) { chargedComplete = true; }, ), ); while (!chargedComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } expect(find.byType(DamageSend), findsOneWidget); var sendComplete = false; unawaited( stepNotifier.sent.then( (_) { sendComplete = true; }, ), ); while (!sendComplete) { await tester.pump(const Duration(milliseconds: 15)); } expect(find.byType(DamageReceive), findsOneWidget); var receiveComplete = false; unawaited( stepNotifier.received.then( (_) { receiveComplete = true; }, ), ); while (!receiveComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } completer.complete(); await tester.pump(); expect(findEmpty, findsOneWidget); await tester.pump(); expect(find.byType(DualAnimation), findsOneWidget); expect(find.byType(VictoryChargeBack), findsOneWidget); expect(find.byType(VictoryChargeFront), findsOneWidget); var victoryComplete = false; unawaited( stepNotifier.victory.then( (_) { victoryComplete = true; }, ), ); while (!victoryComplete) { await tester.pumpAndSettle(const Duration(milliseconds: 150)); } expect(findEmpty, findsOneWidget); }); }); }); }); }
io_flip/packages/io_flip_ui/test/src/animations/damages/elemental_damage_animation_test.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/test/src/animations/damages/elemental_damage_animation_test.dart', 'repo_id': 'io_flip', 'token_count': 16742}
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; void main() { group('FadingDotLoader', () { testWidgets('renders the animation', (tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: Center( child: FadingDotLoader(), ), ), ), ); await tester.pump(const Duration(milliseconds: 2000)); expect(find.byType(Container), findsNWidgets(3)); }); }); }
io_flip/packages/io_flip_ui/test/src/widgets/fading_dot_loader_test.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/test/src/widgets/fading_dot_loader_test.dart', 'repo_id': 'io_flip', 'token_count': 265}
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/src/widgets/io_flip_dialog.dart'; void main() { group('IoFlipDialog', () { const child = Text('test'); testWidgets('renders child widget', (tester) async { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: IoFlipDialog(child: child), ), ), ); expect(find.text('test'), findsOneWidget); }); testWidgets('calls onClose method', (tester) async { var onCloseCalled = false; await tester.pumpWidget( MaterialApp( home: Scaffold( body: IoFlipDialog( onClose: () => onCloseCalled = true, child: child, ), ), ), ); await tester.tap(find.byType(CloseButton)); await tester.pumpAndSettle(); expect(onCloseCalled, isTrue); }); group('show', () { testWidgets('renders the dialog with correct child', (tester) async { await tester.pumpWidget( MaterialApp( home: Builder( builder: (BuildContext context) => Scaffold( body: Center( child: ElevatedButton( onPressed: () => IoFlipDialog.show( context, child: child, ), child: const Text('show'), ), ), ), ), ), ); await tester.tap(find.byType(ElevatedButton)); await tester.pumpAndSettle(); expect(find.byWidget(child), findsOneWidget); }); }); }); }
io_flip/packages/io_flip_ui/test/src/widgets/top_dash_dialog_test.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/test/src/widgets/top_dash_dialog_test.dart', 'repo_id': 'io_flip', 'token_count': 904}
import 'package:flutter_test/flutter_test.dart'; import 'package:go_router/go_router.dart'; import 'package:io_flip/draft/draft.dart'; import '../../helpers/helpers.dart'; void main() { late final GoRouter router; setUp(() { router = GoRouter( routes: [ GoRoute( path: '/', builder: DraftPage.routeBuilder, ), ], ); }); group('DraftPage', () { testWidgets('navigates to draft page', (tester) async { await tester.pumpSubjectWithRouter(router); expect(find.byType(DraftPage), findsOneWidget); }); }); } extension DraftPageTest on WidgetTester { Future<void> pumpSubjectWithRouter(GoRouter goRouter) { return pumpAppWithRouter(goRouter); } }
io_flip/test/draft/views/draft_page_test.dart/0
{'file_path': 'io_flip/test/draft/views/draft_page_test.dart', 'repo_id': 'io_flip', 'token_count': 310}
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; bool tapTextSpan(RichText richText, String text) { final isTapped = !richText.text.visitChildren( (visitor) => _findTextAndTap(visitor, text), ); return isTapped; } bool _findTextAndTap(InlineSpan visitor, String text) { if (visitor is TextSpan && visitor.text == text) { (visitor.recognizer as TapGestureRecognizer?)?.onTap?.call(); return false; } return true; }
io_flip/test/helpers/tap_text_span.dart/0
{'file_path': 'io_flip/test/helpers/tap_text_span.dart', 'repo_id': 'io_flip', 'token_count': 174}
import 'package:api_client/api_client.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip/l10n/l10n.dart'; import 'package:io_flip/leaderboard/initials_form/initials_form.dart'; import 'package:io_flip/leaderboard/leaderboard.dart'; import 'package:mocktail/mocktail.dart'; import '../../helpers/helpers.dart'; class _MockLeaderboardResource extends Mock implements LeaderboardResource {} void main() { late LeaderboardResource leaderboardResource; setUp(() { leaderboardResource = _MockLeaderboardResource(); when(() => leaderboardResource.getInitialsBlacklist()) .thenAnswer((_) async => []); }); group('LeaderboardEntryView', () { testWidgets('renders correct title', (tester) async { await tester.pumpSubject(leaderboardResource); final l10n = tester.element(find.byType(LeaderboardEntryView)).l10n; expect(find.text(l10n.enterYourInitials), findsOneWidget); }); testWidgets('renders initials form', (tester) async { await tester.pumpSubject(leaderboardResource); expect(find.byType(InitialsForm), findsOneWidget); }); }); } extension LeaderboardEntryViewTest on WidgetTester { Future<void> pumpSubject( LeaderboardResource leaderboardResource, ) async { return pumpApp( const LeaderboardEntryView( scoreCardId: 'scoreCardId', ), leaderboardResource: leaderboardResource, ); } }
io_flip/test/leaderboard/views/leaderboard_entry_view_test.dart/0
{'file_path': 'io_flip/test/leaderboard/views/leaderboard_entry_view_test.dart', 'repo_id': 'io_flip', 'token_count': 510}
import 'package:flame/widgets.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip/prompt/prompt.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import '../../helpers/helpers.dart'; void main() { group('CardMaster', () { testWidgets('renders correctly', (tester) async { await tester.pumpSubject(); await tester.pumpAndSettle(); expect(find.byType(CardMaster), findsOneWidget); }); testWidgets( 'render sprite animation when is newer androids', (tester) async { await tester.pumpSubject(); await tester.pumpAndSettle(); expect(find.byType(SpriteAnimationWidget), findsOneWidget); }, ); testWidgets( "Don't render the animation when is older androids", (tester) async { await tester.pumpSubject(isAndroid: true); await tester.pumpAndSettle(); expect(find.byType(SpriteAnimationWidget), findsNothing); }, ); }); } extension CardMasterTest on WidgetTester { Future<void> pumpSubject({ bool isAndroid = false, bool isDesktop = false, }) async { Future<String> deviceInfoAwareAsset({ required bool Function(DeviceInfo deviceInfo) predicate, required String Function() asset, required String Function() orElse, }) async { if (isAndroid) { return asset(); } else { return orElse(); } } await pumpApp( CardMaster(deviceInfoAwareAsset: deviceInfoAwareAsset), ); } }
io_flip/test/prompt/widgets/card_master_test.dart/0
{'file_path': 'io_flip/test/prompt/widgets/card_master_test.dart', 'repo_id': 'io_flip', 'token_count': 608}
import 'package:bloc_test/bloc_test.dart'; import 'package:flutter/material.dart' hide Card; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/share/bloc/download_bloc.dart'; import 'package:io_flip/share/widgets/widgets.dart'; import 'package:io_flip/utils/external_links.dart'; import 'package:mocktail/mocktail.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; import '../../helpers/helpers.dart'; class _MockDownloadBloc extends MockBloc<DownloadEvent, DownloadState> implements DownloadBloc {} String? launchedUrl; const shareUrl = 'https://example.com'; const card = Card( id: '', name: 'name', description: 'description', image: '', rarity: false, power: 1, suit: Suit.air, ); const deck = Deck(id: 'id', userId: 'userId', cards: [card]); void main() { group('ShareDialog', () { late DownloadBloc downloadBloc; setUp(() { downloadBloc = _MockDownloadBloc(); when(() => downloadBloc.state).thenReturn( const DownloadState(), ); }); setUpAll(() { launchedUrl = null; }); testWidgets('renders the content', (tester) async { await tester.pumpSubject( downloadBloc: downloadBloc, content: const Text('test'), ); expect(find.text('test'), findsOneWidget); }); testWidgets('renders a Twitter button', (tester) async { await tester.pumpSubject( downloadBloc: downloadBloc, ); expect(find.text(tester.l10n.twitterButtonLabel), findsOneWidget); }); testWidgets( 'tapping the Twitter button launches the correct url', (tester) async { await tester.pumpSubject( downloadBloc: downloadBloc, ); await tester.tap(find.text(tester.l10n.twitterButtonLabel)); expect( launchedUrl, shareUrl, ); }, ); testWidgets('renders a Facebook button', (tester) async { await tester.pumpSubject( downloadBloc: downloadBloc, ); expect(find.text(tester.l10n.facebookButtonLabel), findsOneWidget); }); testWidgets( 'tapping the Facebook button launches the correct url', (tester) async { await tester.pumpSubject( downloadBloc: downloadBloc, ); await tester.tap(find.text(tester.l10n.facebookButtonLabel)); expect( launchedUrl, equals( shareUrl, ), ); }, ); testWidgets( 'tapping the Google Developer button launches the correct url', (tester) async { await tester.pumpSubject( downloadBloc: downloadBloc, ); await tester.tap(find.text(tester.l10n.devButtonLabel)); expect( launchedUrl, equals( ExternalLinks.devAward, ), ); }, ); testWidgets('renders a save button', (tester) async { await tester.pumpSubject( downloadBloc: downloadBloc, ); expect(find.text(tester.l10n.saveButtonLabel), findsOneWidget); }); testWidgets('calls save card on save button tap', (tester) async { await tester.pumpSubject( downloadBloc: downloadBloc, ); await tester.tap(find.text(tester.l10n.saveButtonLabel)); verify( () => downloadBloc.add(const DownloadCardsRequested(cards: [card])), ).called(1); }); testWidgets('calls save deck on save button tap', (tester) async { await tester.pumpSubject( downloadBloc: downloadBloc, downloadDeck: deck, ); await tester.tap(find.text(tester.l10n.saveButtonLabel)); verifyNever( () => downloadBloc.add(const DownloadCardsRequested(cards: [card])), ); verify( () => downloadBloc.add(const DownloadDeckRequested(deck: deck)), ).called(1); }); testWidgets('renders a downloading button while the downloading', (tester) async { when(() => downloadBloc.state) .thenReturn(const DownloadState(status: DownloadStatus.loading)); await tester.pumpSubject( downloadBloc: downloadBloc, ); expect(find.text(tester.l10n.downloadingButtonLabel), findsOneWidget); }); testWidgets('renders a downloaded button on download complete', (tester) async { when(() => downloadBloc.state) .thenReturn(const DownloadState(status: DownloadStatus.completed)); await tester.pumpSubject( downloadBloc: downloadBloc, ); expect( find.text(tester.l10n.downloadCompleteButtonLabel), findsOneWidget, ); await tester.tap(find.text(tester.l10n.downloadCompleteButtonLabel)); verifyNever( () => downloadBloc.add(const DownloadCardsRequested(cards: [card])), ); verifyNever( () => downloadBloc.add(const DownloadDeckRequested(deck: deck)), ); }); testWidgets('renders a success message while on download complete', (tester) async { when(() => downloadBloc.state) .thenReturn(const DownloadState(status: DownloadStatus.completed)); await tester.pumpSubject( downloadBloc: downloadBloc, ); expect(find.text(tester.l10n.downloadCompleteLabel), findsOneWidget); }); testWidgets('renders a fail message while on download failure', (tester) async { when(() => downloadBloc.state) .thenReturn(const DownloadState(status: DownloadStatus.failure)); await tester.pumpSubject( downloadBloc: downloadBloc, ); expect(find.text(tester.l10n.downloadFailedLabel), findsOneWidget); }); }); } extension ShareCardDialogTest on WidgetTester { Future<void> pumpSubject({ required DownloadBloc downloadBloc, Deck? downloadDeck, Widget? content, }) async { await mockNetworkImages(() { return pumpApp( BlocProvider<DownloadBloc>.value( value: downloadBloc, child: ShareDialogView( content: content ?? Container(), twitterShareUrl: shareUrl, facebookShareUrl: shareUrl, urlLauncher: (url) async { launchedUrl = url; }, downloadCards: const [card], downloadDeck: downloadDeck, ), ), ); }); } }
io_flip/test/share/widgets/share_dialog_test.dart/0
{'file_path': 'io_flip/test/share/widgets/share_dialog_test.dart', 'repo_id': 'io_flip', 'token_count': 2748}
builders: angular: import: "package:angular/builder.dart" builder_factories: - templatePlaceholder - templateCompiler - stylesheetCompiler auto_apply: none applies_builders: - "angular|placeholder_cleanup" - "angular|component_source_cleanup" # See https://github.com/dart-lang/angular/issues/988. is_optional: true required_inputs: - ".css" build_extensions: .css: - ".css.dart" - ".css.shim.dart" .dart: - ".template.dart"
json_serializable/_test_yaml/test/src/angular_config.yaml/0
{'file_path': 'json_serializable/_test_yaml/test/src/angular_config.yaml', 'repo_id': 'json_serializable', 'token_count': 241}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'tuple_example.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** Tuple<T, S> _$TupleFromJson<T, S>( Map<String, dynamic> json, T Function(Object? json) fromJsonT, S Function(Object? json) fromJsonS, ) => Tuple<T, S>( fromJsonT(json['value1']), fromJsonS(json['value2']), ); Map<String, dynamic> _$TupleToJson<T, S>( Tuple<T, S> instance, Object? Function(T value) toJsonT, Object? Function(S value) toJsonS, ) => <String, dynamic>{ 'value1': toJsonT(instance.value1), 'value2': toJsonS(instance.value2), }; ConcreteClass _$ConcreteClassFromJson(Map<String, dynamic> json) => ConcreteClass( Tuple<int, DateTime>.fromJson(json['tuple1'] as Map<String, dynamic>, (value) => value as int, (value) => DateTime.parse(value as String)), Tuple<Duration, BigInt>.fromJson( json['tuple2'] as Map<String, dynamic>, (value) => Duration(microseconds: value as int), (value) => BigInt.parse(value as String)), ); Map<String, dynamic> _$ConcreteClassToJson(ConcreteClass instance) => <String, dynamic>{ 'tuple1': instance.tuple1.toJson( (value) => value, (value) => value.toIso8601String(), ), 'tuple2': instance.tuple2.toJson( (value) => value.inMicroseconds, (value) => value.toString(), ), };
json_serializable/example/lib/tuple_example.g.dart/0
{'file_path': 'json_serializable/example/lib/tuple_example.g.dart', 'repo_id': 'json_serializable', 'token_count': 627}
// Copyright (c) 2018, 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 'allowed_keys_helpers.dart'; /// Helper function used in generated code when /// `JsonSerializableGenerator.checked` is `true`. /// /// Should not be used directly. T $checkedCreate<T>( String className, Map map, T Function( S Function<S>( String, S Function(Object?), { Object? Function(Map, String)? readValue, }), ) constructor, { Map<String, String> fieldKeyMap = const {}, }) { Q checkedConvert<Q>( String key, Q Function(Object?) convertFunction, { Object? Function(Map, String)? readValue, }) => $checkedConvert<Q>(map, key, convertFunction, readValue: readValue); return $checkedNew( className, map, () => constructor(checkedConvert), fieldKeyMap: fieldKeyMap, ); } /// Helper function used in generated code when /// `JsonSerializableGenerator.checked` is `true`. /// /// Should not be used directly. T $checkedNew<T>( String className, Map map, T Function() constructor, { Map<String, String>? fieldKeyMap, }) { fieldKeyMap ??= const {}; try { return constructor(); } on CheckedFromJsonException catch (e) { if (identical(e.map, map) && e._className == null) { e._className = className; } rethrow; } catch (error, stack) { String? key; if (error is ArgumentError) { key = fieldKeyMap[error.name] ?? error.name; } else if (error is MissingRequiredKeysException) { key = error.missingKeys.first; } else if (error is DisallowedNullValueException) { key = error.keysWithNullValues.first; } throw CheckedFromJsonException._( error, stack, map, key, className: className, ); } } /// Helper function used in generated code when /// `JsonSerializableGenerator.checked` is `true`. /// /// Should not be used directly. T $checkedConvert<T>( Map map, String key, T Function(dynamic) castFunc, { Object? Function(Map, String)? readValue, }) { try { return castFunc(readValue == null ? map[key] : readValue(map, key)); } on CheckedFromJsonException { rethrow; } catch (error, stack) { throw CheckedFromJsonException._(error, stack, map, key); } } /// Exception thrown if there is a runtime exception in `fromJson` /// code generated when `JsonSerializableGenerator.checked` is `true` class CheckedFromJsonException implements Exception { /// The [Error] or [Exception] that triggered this exception. /// /// If this instance was created by user code, this field will be `null`. final Object? innerError; /// The [StackTrace] for the [Error] or [Exception] that triggered this /// exception. /// /// If this instance was created by user code, this field will be `null`. final StackTrace? innerStack; /// The key from [map] that corresponds to the thrown [innerError]. /// /// May be `null`. final String? key; /// The source [Map] that was used for decoding when the [innerError] was /// thrown. final Map map; /// A human-readable message corresponding to [innerError]. /// /// May be `null`. final String? message; /// The name of the class being created when [innerError] was thrown. String? get className => _className; String? _className; /// If this was thrown due to an invalid or unsupported key, as opposed to an /// invalid value. final bool badKey; /// Creates a new instance of [CheckedFromJsonException]. CheckedFromJsonException( this.map, this.key, String className, this.message, { this.badKey = false, }) : _className = className, innerError = null, innerStack = null; CheckedFromJsonException._( Object this.innerError, this.innerStack, this.map, this.key, { String? className, }) : _className = className, badKey = innerError is BadKeyException, message = _getMessage(innerError); static String _getMessage(Object error) { if (error is ArgumentError) { final message = error.message; if (message != null) { return message.toString(); } } if (error is BadKeyException) { return error.message; } if (error is FormatException) { var message = error.message; if (error.offset != null) { message = '$message at offset ${error.offset}.'; } return message; } return error.toString(); } @override String toString() => <String>[ 'CheckedFromJsonException', if (_className != null) 'Could not create `$_className`.', if (key != null) 'There is a problem with "$key".', if (message != null) message! else if (innerError != null) innerError.toString(), ].join('\n'); }
json_serializable/json_annotation/lib/src/checked_helpers.dart/0
{'file_path': 'json_serializable/json_annotation/lib/src/checked_helpers.dart', 'repo_id': 'json_serializable', 'token_count': 1737}
// 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 'package:json_annotation/json_annotation.dart'; part 'example.g.dart'; @JsonSerializable() class Person { /// The generated code assumes these values exist in JSON. final String firstName, lastName; /// The generated code below handles if the corresponding JSON value doesn't /// exist or is empty. final DateTime? dateOfBirth; Person({required this.firstName, required this.lastName, this.dateOfBirth}); /// Connect the generated [_$PersonFromJson] function to the `fromJson` /// factory. factory Person.fromJson(Map<String, dynamic> json) => _$PersonFromJson(json); /// Connect the generated [_$PersonToJson] function to the `toJson` method. Map<String, dynamic> toJson() => _$PersonToJson(this); }
json_serializable/json_serializable/example/example.dart/0
{'file_path': 'json_serializable/json_serializable/example/example.dart', 'repo_id': 'json_serializable', 'token_count': 276}
// 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 'package:build/build.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:source_gen/source_gen.dart'; import 'check_dependencies.dart'; import 'json_enum_generator.dart'; import 'json_literal_generator.dart'; import 'json_serializable_generator.dart'; import 'settings.dart'; /// Returns a [Builder] for use within a `package:build_runner` /// `BuildAction`. /// /// [formatOutput] is called to format the generated code. If not provided, /// the default Dart code formatter is used. Builder jsonPartBuilder({ String Function(String code)? formatOutput, JsonSerializable? config, }) { final settings = Settings(config: config); return SharedPartBuilder( [ _UnifiedGenerator([ JsonSerializableGenerator.fromSettings(settings), const JsonEnumGenerator(), ]), const JsonLiteralGenerator(), ], 'json_serializable', formatOutput: formatOutput, ); } /// Allows exposing separate [GeneratorForAnnotation] instances as one /// generator. /// /// We want duplicate items to be merged if folks use both `@JsonEnum` and /// `@JsonSerializable` so we don't get duplicate enum helper functions. /// /// This can only be done if the output is merged into one generator. /// /// This class allows us to keep the implementations separate. class _UnifiedGenerator extends Generator { final List<GeneratorForAnnotation> _generators; _UnifiedGenerator(this._generators); @override Future<String?> generate(LibraryReader library, BuildStep buildStep) async { final values = <String>{}; for (var generator in _generators) { for (var annotatedElement in library.annotatedWith(generator.typeChecker)) { await pubspecHasRightVersion(buildStep); final generatedValue = generator.generateForAnnotatedElement( annotatedElement.element, annotatedElement.annotation, buildStep); for (var value in _normalizeGeneratorOutput(generatedValue)) { assert(value.length == value.trim().length); values.add(value); } } } return values.join('\n\n'); } @override String toString() => 'JsonSerializableGenerator'; } // Borrowed from `package:source_gen` Iterable<String> _normalizeGeneratorOutput(Object? value) { if (value == null) { return const []; } else if (value is String) { value = [value]; } if (value is Iterable) { return value.where((e) => e != null).map((e) { if (e is String) { return e.trim(); } throw _argError(e as Object); }).where((e) => e.isNotEmpty); } throw _argError(value); } // Borrowed from `package:source_gen` ArgumentError _argError(Object value) => ArgumentError( 'Must be a String or be an Iterable containing String values. ' 'Found `${Error.safeToString(value)}` (${value.runtimeType}).');
json_serializable/json_serializable/lib/src/json_part_builder.dart/0
{'file_path': 'json_serializable/json_serializable/lib/src/json_part_builder.dart', 'repo_id': 'json_serializable', 'token_count': 1038}
// Copyright (c) 2018, 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:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:collection/collection.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:source_gen/source_gen.dart'; import 'package:source_helper/source_helper.dart'; import '../default_container.dart'; import '../lambda_result.dart'; import '../type_helper.dart'; import '../utils.dart'; import 'config_types.dart'; import 'generic_factory_helper.dart'; const _helperLambdaParam = 'value'; /// Supports types that have `fromJson` constructors and/or `toJson` functions. class JsonHelper extends TypeHelper<TypeHelperContextWithConfig> { const JsonHelper(); /// Simply returns the [expression] provided. /// /// By default, JSON encoding in from `dart:convert` calls `toJson()` on /// provided objects. @override String? serialize( DartType targetType, String expression, TypeHelperContextWithConfig context, ) { if (!_canSerialize(context.config, targetType)) { return null; } final interfaceType = targetType as InterfaceType; final toJsonArgs = <String>[]; var toJson = _toJsonMethod(interfaceType); if (toJson != null) { // Using the `declaration` here so we get the original definition – // and not one with the generics already populated. toJson = toJson.declaration; toJsonArgs.addAll( _helperParams( context.serialize, _encodeHelper, interfaceType, toJson.parameters.where((element) => element.isRequiredPositional), toJson, ), ); } if (context.config.explicitToJson || toJsonArgs.isNotEmpty) { return '$expression${interfaceType.isNullableType ? '?' : ''}' '.toJson(${toJsonArgs.map((a) => '$a, ').join()} )'; } return expression; } @override Object? deserialize( DartType targetType, String expression, TypeHelperContextWithConfig context, bool defaultProvided, ) { if (targetType is! InterfaceType) { return null; } final classElement = targetType.element; final fromJsonCtor = classElement.constructors .singleWhereOrNull((ce) => ce.name == 'fromJson'); var output = expression; if (fromJsonCtor != null) { final positionalParams = fromJsonCtor.parameters .where((element) => element.isPositional) .toList(); if (positionalParams.isEmpty) { throw InvalidGenerationSourceError( 'Expecting a `fromJson` constructor with exactly one positional ' 'parameter. Found a constructor with 0 parameters.', element: fromJsonCtor, ); } var asCastType = positionalParams.first.type; if (asCastType is InterfaceType) { final instantiated = _instantiate(asCastType, targetType); if (instantiated != null) { asCastType = instantiated; } } output = context.deserialize(asCastType, output).toString(); final args = [ output, ..._helperParams( context.deserialize, _decodeHelper, targetType, positionalParams.skip(1), fromJsonCtor, ), ]; output = args.join(', '); } else if (_annotation(context.config, targetType)?.createFactory == true) { if (context.config.anyMap) { output += ' as Map'; } else { output += ' as Map<String, dynamic>'; } } else { return null; } // TODO: the type could be imported from a library with a prefix! // https://github.com/google/json_serializable.dart/issues/19 final lambda = LambdaResult( output, '${typeToCode(targetType.promoteNonNullable())}.fromJson', ); return DefaultContainer(expression, lambda); } } List<String> _helperParams( Object? Function(DartType, String) execute, TypeParameterType Function(ParameterElement, Element) paramMapper, InterfaceType type, Iterable<ParameterElement> positionalParams, Element targetElement, ) { final rest = <TypeParameterType>[]; for (var param in positionalParams) { rest.add(paramMapper(param, targetElement)); } final args = <String>[]; for (var helperArg in rest) { final typeParamIndex = type.element.typeParameters.indexOf(helperArg.element); // TODO: throw here if `typeParamIndex` is -1 ? final typeArg = type.typeArguments[typeParamIndex]; final body = execute(typeArg, _helperLambdaParam); args.add('($_helperLambdaParam) => $body'); } return args; } TypeParameterType _decodeHelper( ParameterElement param, Element targetElement, ) { final type = param.type; if (type is FunctionType && type.returnType is TypeParameterType && type.normalParameterTypes.length == 1) { final funcReturnType = type.returnType; if (param.name == fromJsonForName(funcReturnType.element!.name!)) { final funcParamType = type.normalParameterTypes.single; if ((funcParamType.isDartCoreObject && funcParamType.isNullableType) || funcParamType is DynamicType) { return funcReturnType as TypeParameterType; } } } throw InvalidGenerationSourceError( 'Expecting a `fromJson` constructor with exactly one positional ' 'parameter. ' 'The only extra parameters allowed are functions of the form ' '`T Function(Object?) ${fromJsonForName('T')}` where `T` is a type ' 'parameter of the target type.', element: targetElement, ); } TypeParameterType _encodeHelper( ParameterElement param, Element targetElement, ) { final type = param.type; if (type is FunctionType && (type.returnType.isDartCoreObject || type.returnType is DynamicType) && type.normalParameterTypes.length == 1) { final funcParamType = type.normalParameterTypes.single; if (param.name == toJsonForName(funcParamType.element!.name!)) { if (funcParamType is TypeParameterType) { return funcParamType; } } } throw InvalidGenerationSourceError( 'Expecting a `toJson` function with no required parameters. ' 'The only extra parameters allowed are functions of the form ' '`Object Function(T) toJsonT` where `T` is a type parameter of the target ' ' type.', element: targetElement, ); } bool _canSerialize(ClassConfig config, DartType type) { if (type is InterfaceType) { final toJsonMethod = _toJsonMethod(type); if (toJsonMethod != null) { return true; } if (_annotation(config, type)?.createToJson == true) { // TODO: consider logging that we're assuming a user will wire up the // generated mixin at some point... return true; } } return false; } /// Returns an instantiation of [ctorParamType] by providing argument types /// derived by matching corresponding type parameters from [classType]. InterfaceType? _instantiate( InterfaceType ctorParamType, InterfaceType classType, ) { final argTypes = ctorParamType.typeArguments.map((arg) { final typeParamIndex = classType.element.typeParameters.indexWhere( // TODO: not 100% sure `nullabilitySuffix` is right (e) => e.instantiate(nullabilitySuffix: arg.nullabilitySuffix) == arg); if (typeParamIndex >= 0) { return classType.typeArguments[typeParamIndex]; } else { // TODO: perhaps throw UnsupportedTypeError? return null; } }).toList(); if (argTypes.any((e) => e == null)) { // TODO: perhaps throw UnsupportedTypeError? return null; } return ctorParamType.element.instantiate( typeArguments: argTypes.cast<DartType>(), nullabilitySuffix: ctorParamType.nullabilitySuffix, ); } ClassConfig? _annotation(ClassConfig config, InterfaceType source) { if (source.isEnum) { return null; } final annotations = const TypeChecker.fromRuntime(JsonSerializable) .annotationsOfExact(source.element, throwOnUnresolved: false) .toList(); if (annotations.isEmpty) { return null; } return mergeConfig( config, ConstantReader(annotations.single), classElement: source.element as ClassElement, ); } MethodElement? _toJsonMethod(DartType type) => type.typeImplementations .map((dt) => dt is InterfaceType ? dt.getMethod('toJson') : null) .firstWhereOrNull((me) => me != null);
json_serializable/json_serializable/lib/src/type_helpers/json_helper.dart/0
{'file_path': 'json_serializable/json_serializable/lib/src/type_helpers/json_helper.dart', 'repo_id': 'json_serializable', 'token_count': 3146}
// 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. @TestOn('vm') library test; import 'package:json_serializable/json_serializable.dart'; import 'package:path/path.dart' as p; import 'package:source_gen_test/source_gen_test.dart'; import 'package:test/test.dart'; Future<void> main() async { initializeBuildLogTracking(); final jsonSerializableTestReader = await initializeLibraryReaderForDirectory( p.join('test', 'src'), '_json_serializable_test_input.dart', ); testAnnotatedElements( jsonSerializableTestReader, JsonSerializableGenerator(), expectedAnnotatedTests: _expectedAnnotatedTests, ); final jsonEnumTestReader = await initializeLibraryReaderForDirectory( p.join('test', 'src'), '_json_enum_test_input.dart', ); testAnnotatedElements( jsonEnumTestReader, const JsonEnumGenerator(), expectedAnnotatedTests: { 'EnumValueIssue1147', 'EnumValueNotAField', 'EnumValueNotSupportType', 'EnumValueWeirdField', 'UnsupportedClass', }, ); } const _expectedAnnotatedTests = { 'BadEnumDefaultValue', 'BadFromFuncReturnType', 'BadNoArgs', 'BadOneNamed', 'BadToFuncReturnType', 'BadTwoRequiredPositional', 'CtorDefaultValueAndJsonKeyDefaultValue', 'DefaultDoubleConstants', 'DefaultWithConstObject', 'DefaultWithDisallowNullRequiredClass', 'DefaultWithFunction', 'DefaultWithFunctionInList', 'DefaultWithNestedEnum', 'DefaultWithSymbol', 'DefaultWithToJsonClass', 'DefaultWithType', 'DupeKeys', 'DynamicConvertMethods', 'FieldNamerKebab', 'FieldNamerNone', 'FieldNamerPascal', 'FieldNamerScreamingSnake', 'FieldNamerSnake', 'FieldWithFromJsonCtorAndTypeParams', 'FinalFields', 'FinalFieldsNotSetInCtor', 'FromDynamicCollection', 'FromNullableDynamicCollection', 'GeneralTestClass1', 'GeneralTestClass2', 'GenericArgumentFactoriesFlagWithoutGenericType', 'GenericClass', 'IgnoreAndIncludeFromJsonFieldCtorClass', 'IgnoreAndIncludeToJsonFieldCtorClass', 'IgnoreUnannotated', 'IgnoredFieldClass', 'IgnoredFieldCtorClass', 'IncludeIfNullDisallowNullClass', 'IncludeIfNullOverride', 'InvalidChildClassFromJson', 'InvalidChildClassFromJson2', 'InvalidChildClassFromJson3', 'InvalidFromFunc2Args', 'InvalidToFunc2Args', 'Issue1038RegressionTest', 'Issue713', 'JsonConvertOnField', 'JsonConverterCtorParams', 'JsonConverterDuplicateAnnotations', 'JsonConverterNamedCtor', 'JsonConverterNullableToNonNullable', 'JsonConverterOnGetter', 'JsonConverterWithBadTypeArg', 'JsonValueValid', 'JsonValueWithBool', 'JustSetter', 'JustSetterNoFromJson', 'JustSetterNoToJson', 'KeyDupesField', 'MapKeyNoNullableInt', 'MapKeyNoNullableObject', 'MapKeyNoNullableString', 'MapKeyVariety', 'NoCtorClass', 'NoDeserializeBadKey', 'NoDeserializeFieldType', 'NoSerializeBadKey', 'NoSerializeFieldType', 'ObjectConvertMethods', 'OkayOneNormalOptionalNamed', 'OkayOneNormalOptionalPositional', 'OkayOnlyOptionalPositional', 'OnlyStaticMembers', 'OverrideGetterExampleI613', 'PrivateFieldCtorClass', 'PropInMixinI448Regression', 'Reproduce869NullableGenericType', 'Reproduce869NullableGenericTypeWithDefault', 'SameCtorAndJsonKeyDefaultValue', 'SetSupport', 'SubType', 'SubTypeWithAnnotatedFieldOverrideExtends', 'SubTypeWithAnnotatedFieldOverrideExtendsWithOverrides', 'SubTypeWithAnnotatedFieldOverrideImplements', 'SubclassedJsonKey', 'TearOffFromJsonClass', 'ToJsonNullableFalseIncludeIfNullFalse', 'TypedConvertMethods', 'UnknownEnumValue', 'UnknownEnumValueListWrongEnumType', 'UnknownEnumValueListWrongType', 'UnknownEnumValueNotEnumField', 'UnknownEnumValueWrongEnumType', 'UnsupportedDateTimeField', 'UnsupportedDurationField', 'UnsupportedEnum', 'UnsupportedListField', 'UnsupportedMapField', 'UnsupportedSetField', 'UnsupportedUriField', 'ValidToFromFuncClassStatic', 'WithANonCtorGetter', 'WithANonCtorGetterChecked', 'WrongConstructorNameClass', '_BetterPrivateNames', 'annotatedMethod', 'theAnswer', };
json_serializable/json_serializable/test/json_serializable_test.dart/0
{'file_path': 'json_serializable/json_serializable/test/json_serializable_test.dart', 'repo_id': 'json_serializable', 'token_count': 1506}
import 'package:json_annotation/json_annotation.dart'; import 'package:test/test.dart'; import 'package:yaml/yaml.dart'; import '../test_utils.dart'; import 'kitchen_sink.factories.dart'; import 'kitchen_sink_interface.dart'; import 'kitchen_sink_test_shared.dart'; void main() { for (var factory in factories.where((element) => element.anyMap)) { group(factory.description, () { _anyMapTests(factory); }); } } void _anyMapTests(KitchenSinkFactory factory) { test('valid values round-trip - yaml', () { final jsonEncoded = loudEncode(validValues); final yaml = loadYaml(jsonEncoded); expect(jsonEncoded, loudEncode(factory.fromJson(yaml as YamlMap))); }); group('a bad value for', () { for (final e in invalidValueTypes.entries) { _testBadValue(e.key, e.value, factory, false); } for (final e in disallowNullKeys) { _testBadValue(e, null, factory, false); } for (final e in _invalidCheckedValues.entries) { _testBadValue(e.key, e.value, factory, true); } }); } void _testBadValue(String key, Object? badValue, KitchenSinkFactory factory, bool checkedAssignment) { final matcher = _getMatcher(factory.checked, key, checkedAssignment); for (final isJson in [true, false]) { test('`$key` fails with value `$badValue`- ${isJson ? 'json' : 'yaml'}', () { var copy = Map<dynamic, dynamic>.of(validValues); copy[key] = badValue; if (!isJson) { copy = loadYaml(loudEncode(copy)) as YamlMap; } expect(() => factory.fromJson(copy), matcher); }); } } Matcher _getMatcher(bool checked, String? expectedKey, bool checkedAssignment) { Matcher innerMatcher; if (checked) { if (checkedAssignment && const ['intIterable', 'datetime-iterable'].contains(expectedKey)) { expectedKey = null; } innerMatcher = checkedMatcher(expectedKey); } else { innerMatcher = anyOf( isTypeError, _isAUnrecognizedKeysException( 'Unrecognized keys: [invalid_key]; supported keys: ' '[value, custom_field]', ), ); if (checkedAssignment) { innerMatcher = switch (expectedKey) { 'validatedPropertyNo42' => isStateError, 'no-42' => isArgumentError, 'strictKeysObject' => _isAUnrecognizedKeysException('bob'), 'intIterable' => isTypeError, 'datetime-iterable' => isTypeError, _ => throw StateError('Not expected! - $expectedKey') }; } } return throwsA(innerMatcher); } Matcher _isAUnrecognizedKeysException(String expectedMessage) => isA<UnrecognizedKeysException>() .having((e) => e.message, 'message', expectedMessage); /// Invalid values that are found after the property set or ctor call const _invalidCheckedValues = { 'no-42': 42, 'validatedPropertyNo42': 42, 'intIterable': [true], 'datetime-iterable': [true], };
json_serializable/json_serializable/test/kitchen_sink/kitchen_sink_yaml_test.dart/0
{'file_path': 'json_serializable/json_serializable/test/kitchen_sink/kitchen_sink_yaml_test.dart', 'repo_id': 'json_serializable', 'token_count': 1141}
// Copyright (c) 2018, 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. part of '_json_serializable_test_input.dart'; @ShouldThrow( 'Error with `@JsonKey` on the `field` field. ' '`defaultValue` is `Symbol`, it must be a literal.', element: 'field', ) @JsonSerializable() class DefaultWithSymbol { @JsonKey(defaultValue: #symbol) late Object field; DefaultWithSymbol(); } int _function() => 42; @ShouldGenerate( r''' DefaultWithFunction _$DefaultWithFunctionFromJson(Map<String, dynamic> json) => DefaultWithFunction()..field = json['field'] ?? _function(); Map<String, dynamic> _$DefaultWithFunctionToJson( DefaultWithFunction instance) => <String, dynamic>{ 'field': instance.field, }; ''', ) @JsonSerializable() class DefaultWithFunction { @JsonKey(defaultValue: _function) Object? field; DefaultWithFunction(); } @ShouldThrow( 'Error with `@JsonKey` on the `field` field. ' '`defaultValue` is `List > Function`, it must be a literal.', element: 'field', ) @JsonSerializable() class DefaultWithFunctionInList { @JsonKey(defaultValue: [_function]) Object? field; DefaultWithFunctionInList(); } @ShouldThrow( 'Error with `@JsonKey` on the `field` field. ' '`defaultValue` is `Type`, it must be a literal.', element: 'field', ) @JsonSerializable() class DefaultWithType { @JsonKey(defaultValue: Object) late Object field; DefaultWithType(); } @ShouldThrow( 'Error with `@JsonKey` on the `field` field. ' '`defaultValue` is `Duration`, it must be a literal.', element: 'field', ) @JsonSerializable() class DefaultWithConstObject { @JsonKey(defaultValue: Duration()) late Object field; DefaultWithConstObject(); } enum Enum { value } @ShouldThrow( 'Error with `@JsonKey` on the `field` field. ' '`defaultValue` is `List > Enum`, it must be a literal.', element: 'field', ) @JsonSerializable() class DefaultWithNestedEnum { @JsonKey(defaultValue: [Enum.value]) late Object field; DefaultWithNestedEnum(); } @ShouldThrow( '`JsonKey.nullForUndefinedEnumValue` cannot be used with ' '`JsonKey.defaultValue`.', element: 'enumValue', ) @JsonSerializable() class BadEnumDefaultValue { @JsonKey(defaultValue: JsonKey.nullForUndefinedEnumValue) Enum? enumValue; BadEnumDefaultValue(); } @ShouldGenerate( r''' DefaultWithToJsonClass _$DefaultWithToJsonClassFromJson( Map<String, dynamic> json) => DefaultWithToJsonClass() ..fieldDefaultValueToJson = json['fieldDefaultValueToJson'] == null ? 7 : DefaultWithToJsonClass._fromJson( json['fieldDefaultValueToJson'] as String); ''', ) @JsonSerializable(createToJson: false) class DefaultWithToJsonClass { @JsonKey(defaultValue: 7, fromJson: _fromJson) late int fieldDefaultValueToJson; DefaultWithToJsonClass(); static int _fromJson(String input) => 41; } @ShouldGenerate( r''' DefaultWithDisallowNullRequiredClass _$DefaultWithDisallowNullRequiredClassFromJson(Map<String, dynamic> json) { $checkKeys( json, requiredKeys: const ['theField'], disallowNullValues: const ['theField'], ); return DefaultWithDisallowNullRequiredClass() ..theField = json['theField'] as int? ?? 7; } ''', expectedLogItems: [ 'The `defaultValue` on field `theField` will have no effect because both ' '`disallowNullValue` and `required` are set to `true`.', ], ) @JsonSerializable(createToJson: false) class DefaultWithDisallowNullRequiredClass { @JsonKey(defaultValue: 7, disallowNullValue: true, required: true) int? theField; DefaultWithDisallowNullRequiredClass(); } @ShouldGenerate( r''' CtorDefaultValueAndJsonKeyDefaultValue _$CtorDefaultValueAndJsonKeyDefaultValueFromJson( Map<String, dynamic> json) => CtorDefaultValueAndJsonKeyDefaultValue( json['theField'] as int? ?? 7, ); ''', expectedLogItems: [ 'The constructor parameter for `theField` has a default value `6`, but the ' '`JsonKey.defaultValue` value `7` will be used for missing or `null` ' 'values in JSON decoding.', ], ) @JsonSerializable(createToJson: false) class CtorDefaultValueAndJsonKeyDefaultValue { @JsonKey(defaultValue: 7) final int theField; CtorDefaultValueAndJsonKeyDefaultValue([this.theField = 6]); } @ShouldGenerate( r''' SameCtorAndJsonKeyDefaultValue _$SameCtorAndJsonKeyDefaultValueFromJson( Map<String, dynamic> json) => SameCtorAndJsonKeyDefaultValue( json['theField'] as int? ?? 3, ); ''', expectedLogItems: [ 'The default value `3` for `theField` is defined twice ' 'in the constructor and in the `JsonKey.defaultValue`.', ], ) @JsonSerializable(createToJson: false) class SameCtorAndJsonKeyDefaultValue { @JsonKey(defaultValue: 3) final int theField; SameCtorAndJsonKeyDefaultValue([this.theField = 3]); } @ShouldGenerate(r''' DefaultDoubleConstants _$DefaultDoubleConstantsFromJson( Map<String, dynamic> json) => DefaultDoubleConstants() ..defaultNan = (json['defaultNan'] as num?)?.toDouble() ?? double.nan ..defaultNegativeInfinity = (json['defaultNegativeInfinity'] as num?)?.toDouble() ?? double.negativeInfinity ..defaultInfinity = (json['defaultInfinity'] as num?)?.toDouble() ?? double.infinity ..defaultMinPositive = (json['defaultMinPositive'] as num?)?.toDouble() ?? 5e-324 ..defaultMaxFinite = (json['defaultMaxFinite'] as num?)?.toDouble() ?? 1.7976931348623157e+308; ''') @JsonSerializable(createToJson: false) class DefaultDoubleConstants { @JsonKey(defaultValue: double.nan) late double defaultNan; @JsonKey(defaultValue: double.negativeInfinity) late double defaultNegativeInfinity; @JsonKey(defaultValue: double.infinity) late double defaultInfinity; // Since these values can be represented as number literals, there is no // special handling. Including them here for completeness, though. @JsonKey(defaultValue: double.minPositive) late double defaultMinPositive; @JsonKey(defaultValue: double.maxFinite) late double defaultMaxFinite; DefaultDoubleConstants(); }
json_serializable/json_serializable/test/src/default_value_input.dart/0
{'file_path': 'json_serializable/json_serializable/test/src/default_value_input.dart', 'repo_id': 'json_serializable', 'token_count': 2260}
// Copyright (c) 2019, 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:async'; import 'package:build/build.dart'; import 'package:path/path.dart' as p; import 'package:source_helper/source_helper.dart'; import 'shared.dart'; Builder builder([_]) => _FieldMatrixBuilder(); class _FieldMatrixBuilder extends Builder { @override FutureOr<void> build(BuildStep buildStep) async { final inputBaseName = p.basenameWithoutExtension(buildStep.inputId.path); final output = buildStep.allowedOutputs.single; final content = StringBuffer(''' import 'package:json_annotation/json_annotation.dart'; part '$inputBaseName.field_matrix.g.dart'; '''); final classes = <String>{}; for (var isPublic in [true, false]) { for (var includeToJson in [null, true, false]) { for (var includeFromJson in [null, true, false]) { final className = 'ToJson${includeToJson.toString().pascal}' 'FromJson${includeFromJson.toString().pascal}' '${isPublic ? 'Public' : 'Private'}'; classes.add(className); final fieldName = isPublic ? 'field' : '_field'; final bits = [ if (includeFromJson != null) 'includeFromJson: $includeFromJson,', if (includeToJson != null) 'includeToJson: $includeToJson,', if (!isPublic) "name: 'field'", ]; final fieldAnnotation = bits.isEmpty ? '' : '@JsonKey(${bits.join()})'; content.writeln(''' @JsonSerializable() class $className { $className(); int? aField; $fieldAnnotation int? $fieldName; int? zField; factory $className.fromJson(Map<String, dynamic> json) => _\$${className}FromJson(json); Map<String, dynamic> toJson() => _\$${className}ToJson(this); @override String toString() => '$className: $fieldName: \$$fieldName'; } '''); } } } content.writeln(''' const fromJsonFactories = <Object Function(Map<String, dynamic>)>{ ${classes.map((e) => '$e.fromJson,').join()} }; '''); await buildStep.writeAsString(output, formatter.format(content.toString())); } @override Map<String, List<String>> get buildExtensions => const { '.dart': ['.field_matrix.dart'], }; }
json_serializable/json_serializable/tool/field_matrix_builder.dart/0
{'file_path': 'json_serializable/json_serializable/tool/field_matrix_builder.dart', 'repo_id': 'json_serializable', 'token_count': 961}
name: cicd on: push: branches: - main pull_request: types: [opened, reopened, synchronize] jobs: format: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: subosito/flutter-action@v2 - uses: flame-engine/flame-format-action@v1.1.0 analyze: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: subosito/flutter-action@v2 with: cache: true - name: "Analyze" run: flutter analyze
lightrunners/.github/workflows/cicd.yml/0
{'file_path': 'lightrunners/.github/workflows/cicd.yml', 'repo_id': 'lightrunners', 'token_count': 242}
import 'dart:ui'; import 'package:flame/components.dart'; import 'package:lightrunners/game/components/score_box.dart'; import 'package:lightrunners/game/lightrunners_game.dart'; import 'package:lightrunners/ui/palette.dart'; import 'package:lightrunners/utils/constants.dart'; class ScorePanel extends RectangleComponent with HasGameReference<LightRunnersGame> { @override void onLoad() { position = Vector2(game.camera.viewport.size.x - scoreBoxWidth, 0); size = Vector2(scoreBoxWidth, game.camera.viewport.size.y); paint = Paint()..color = GamePalette.black; addAll( game.ships.values.map( (ship) => ScoreBox( shipRef: ship, position: _computeTarget(ship.player.slotNumber), ), ), ); } Vector2 _computeTarget(int idx) { return Vector2(0, idx * (size.y / maxShips) + scoreBoxMargin * idx); } }
lightrunners/lib/game/components/score_panel.dart/0
{'file_path': 'lightrunners/lib/game/components/score_panel.dart', 'repo_id': 'lightrunners', 'token_count': 344}
import 'package:flutter/material.dart'; import 'package:phased/phased.dart'; class LogoController extends PhasedState<int> { LogoController() : super(values: [0, 1, 2], autostart: true); } class TitleLogo extends Phased<int> { const TitleLogo({ required super.state, super.key, }); static const _width = 500.0; static const _height = 500.0; @override Widget build(BuildContext context) { return SizedBox( width: _width, height: _height, child: Stack( alignment: Alignment.center, children: [ AnimatedPositioned( duration: const Duration(milliseconds: 250), curve: Curves.easeOutSine, onEnd: state.next, width: state.phaseValue( values: { 0: 0, 1: _width, 2: _width, }, defaultValue: 0, ), child: Image.asset('assets/images/logo_background.png'), ), AnimatedPositioned( duration: const Duration(milliseconds: 250), curve: Curves.easeOutSine, width: state.phaseValue( values: { 0: 0, 1: 0, 2: _width, }, defaultValue: 0, ), child: Image.asset('assets/images/logo_writing.png'), ), ], ), ); } }
lightrunners/lib/title/view/title_logo.dart/0
{'file_path': 'lightrunners/lib/title/view/title_logo.dart', 'repo_id': 'lightrunners', 'token_count': 746}
export 'opacity_blinker.dart'; export 'screen_scaffold.dart';
lightrunners/lib/widgets/widgets.dart/0
{'file_path': 'lightrunners/lib/widgets/widgets.dart', 'repo_id': 'lightrunners', 'token_count': 24}
// Copyright (c) 2021, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/type.dart'; import '../analyzer.dart'; const _desc = r'Avoid method calls or property accesses on a "dynamic" target.'; const _details = r''' **DO** avoid method calls or accessing properties on an object that is either explicitly or implicitly statically typed "dynamic". Dynamic calls are treated slightly different in every runtime environment and compiler, but most production modes (and even some development modes) have both compile size and runtime performance penalties associated with dynamic calls. Additionally, targets typed "dynamic" disables most static analysis, meaning it is easier to lead to a runtime "NoSuchMethodError" or "NullError" than properly statically typed Dart code. There is an exception to methods and properties that exist on "Object?": - a.hashCode - a.runtimeType - a.noSuchMethod(someInvocation) - a.toString() ... these members are dynamically dispatched in the web-based runtimes, but not in the VM-based ones. Additionally, they are so common that it would be very punishing to disallow `any.toString()` or `any == true`, for example. Note that despite "Function" being a type, the semantics are close to identical to "dynamic", and calls to an object that is typed "Function" will also trigger this lint. **BAD:** ```dart void explicitDynamicType(dynamic object) { print(object.foo()); } void implicitDynamicType(object) { print(object.foo()); } abstract class SomeWrapper { T doSomething<T>(); } void inferredDynamicType(SomeWrapper wrapper) { var object = wrapper.doSomething(); print(object.foo()); } void callDynamic(dynamic function) { function(); } void functionType(Function function) { function(); } ``` **GOOD:** ```dart void explicitType(Fooable object) { object.foo(); } void castedType(dynamic object) { (object as Fooable).foo(); } abstract class SomeWrapper { T doSomething<T>(); } void inferredType(SomeWrapper wrapper) { var object = wrapper.doSomething<Fooable>(); object.foo(); } void functionTypeWithParameters(Function() function) { function(); } ``` '''; class AvoidDynamicCalls extends LintRule implements NodeLintRule { AvoidDynamicCalls() : super( name: 'avoid_dynamic_calls', description: _desc, details: _details, group: Group.errors, maturity: Maturity.experimental, ); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context, ) { var visitor = _Visitor(this); registry ..addAssignmentExpression(this, visitor) ..addBinaryExpression(this, visitor) ..addFunctionExpressionInvocation(this, visitor) ..addIndexExpression(this, visitor) ..addMethodInvocation(this, visitor) ..addPostfixExpression(this, visitor) ..addPrefixExpression(this, visitor) ..addPrefixedIdentifier(this, visitor) ..addPropertyAccess(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); bool _lintIfDynamic(Expression? node) { if (node?.staticType?.isDynamic == true) { rule.reportLint(node); return true; } else { return false; } } void _lintIfDynamicOrFunction(Expression node, {DartType? staticType}) { staticType ??= node.staticType; if (staticType == null) { return; } if (staticType.isDynamic) { rule.reportLint(node); } if (staticType.isDartCoreFunction) { rule.reportLint(node); } } @override void visitAssignmentExpression(AssignmentExpression node) { if (node.readType?.isDynamic != true) { // An assignment expression can only be a dynamic call if it is a // "compound assignment" (i.e. such as `x += 1`); so if `readType` is not // dynamic, we don't need to check further. return; } if (node.operator.type == TokenType.QUESTION_QUESTION_EQ) { // x ??= foo is not a dynamic call. return; } rule.reportLint(node); } @override void visitBinaryExpression(BinaryExpression node) { if (!node.operator.isUserDefinableOperator) { // Operators that can never be provided by the user can't be dynamic. return; } switch (node.operator.type) { case TokenType.EQ_EQ: case TokenType.BANG_EQ: // These operators exist on every type, even "Object?". While they are // virtually dispatched, they are not considered dynamic calls by the // CFE. They would also make landing this lint exponentially harder. return; } _lintIfDynamic(node.leftOperand); // We don't check node.rightOperand, because that is an implicit cast, not a // dynamic call (the call itself is based on leftOperand). While it would be // useful to do so, it is better solved by other more specific lints to // disallow implicit casts from dynamic. } @override void visitFunctionExpressionInvocation(FunctionExpressionInvocation node) { _lintIfDynamicOrFunction(node.function); } @override void visitIndexExpression(IndexExpression node) { _lintIfDynamic(node.realTarget); } @override void visitMethodInvocation(MethodInvocation node) { var methodName = node.methodName.name; if (node.target != null) { if (methodName == 'noSuchMethod' && node.argumentList.arguments.length == 1 && node.argumentList.arguments.first is! NamedExpression) { // Special-cased; these exist on every object, even those typed "Object?". return; } if (methodName == 'toString' && node.argumentList.arguments.isEmpty) { // Special-cased; these exist on every object, even those typed "Object?". return; } } var receiverWasDynamic = _lintIfDynamic(node.realTarget); if (!receiverWasDynamic) { var target = node.target; // The ".call" method is special, where "a.call()" is treated ~as "a()". // // If the method is "call", and the receiver is a function, we assume then // we are really checking the static type of the receiver, not the static // type of the "call" method itself. DartType? staticType; if (methodName == 'call' && target != null && target.staticType is FunctionType) { staticType = target.staticType; } _lintIfDynamicOrFunction(node.function, staticType: staticType); } } void _lintPrefixOrPostfixExpression(Expression root, Expression operand) { if (_lintIfDynamic(operand)) { return; } if (root is CompoundAssignmentExpression) { // Not promoted by "is" since the type would lose capabilities. var rootAsAssignment = root as CompoundAssignmentExpression; if (rootAsAssignment.readType?.isDynamic == true) { // An assignment expression can only be a dynamic call if it is a // "compound assignment" (i.e. such as `x += 1`); so if `readType` is // dynamic we should lint. rule.reportLint(root); } } } @override void visitPrefixExpression(PrefixExpression node) { _lintPrefixOrPostfixExpression(node, node.operand); } @override void visitPrefixedIdentifier(PrefixedIdentifier node) { var property = node.identifier.name; if (const { 'hashCode', 'noSuchMethod', 'runtimeType', 'toString', }.contains(property)) { // Special-cased; these exist on every object, even those typed "Object?". return; } _lintIfDynamic(node.prefix); } @override void visitPostfixExpression(PostfixExpression node) { if (node.operator.type == TokenType.BANG) { // x! is not a dynamic call, even if "x" is dynamic. return; } _lintPrefixOrPostfixExpression(node, node.operand); } @override void visitPropertyAccess(PropertyAccess node) { _lintIfDynamic(node.realTarget); } }
linter/lib/src/rules/avoid_dynamic_calls.dart/0
{'file_path': 'linter/lib/src/rules/avoid_dynamic_calls.dart', 'repo_id': 'linter', 'token_count': 2925}
// Copyright (c) 2018, 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:math' as math; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import '../analyzer.dart'; import '../ast.dart'; const _desc = r"Don't rename parameters of overridden methods."; const _details = r'''**DON'T** rename parameters of overridden methods. Methods that override another method, but do not have their own documentation comment, will inherit the overridden method's comment when dartdoc produces documentation. If the inherited method contains the name of the parameter (in square brackets), then dartdoc cannot link it correctly. **BAD:** ```dart abstract class A { m(a); } abstract class B extends A { m(b); } ``` **GOOD:** ```dart abstract class A { m(a); } abstract class B extends A { m(a); } ``` '''; class AvoidRenamingMethodParameters extends LintRule implements NodeLintRule { AvoidRenamingMethodParameters() : super( name: 'avoid_renaming_method_parameters', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { if (!isInLibDir(context.currentUnit.unit, context.package)) { return; } var visitor = _Visitor(this, context); registry.addMethodDeclaration(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; final LinterContext context; _Visitor(this.rule, this.context); @override void visitMethodDeclaration(MethodDeclaration node) { if (node.isStatic) return; if (node.documentationComment != null) return; var parentNode = node.parent; if (parentNode is! Declaration) { return; } var parentElement = parentNode.declaredElement; // Note: there are no override semantics with extension methods. if (parentElement is! ClassElement) { return; } var classElement = parentElement; if (classElement.isPrivate) return; var parentMethod = classElement.lookUpInheritedMethod( node.name.name, classElement.library); if (parentMethod == null) return; var nodeParams = node.parameters; if (nodeParams == null) { return; } var parameters = nodeParams.parameters.where((p) => !p.isNamed).toList(); var parentParameters = parentMethod.parameters.where((p) => !p.isNamed).toList(); var count = math.min(parameters.length, parentParameters.length); for (var i = 0; i < count; i++) { if (parentParameters.length <= i) break; var paramIdentifier = parameters[i].identifier; if (paramIdentifier != null && paramIdentifier.name != parentParameters[i].name) { rule.reportLint(parameters[i].identifier); } } } }
linter/lib/src/rules/avoid_renaming_method_parameters.dart/0
{'file_path': 'linter/lib/src/rules/avoid_renaming_method_parameters.dart', 'repo_id': 'linter', 'token_count': 1071}
// Copyright (c) 2019, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/file_system/file_system.dart'; import 'package:yaml/yaml.dart'; import '../analyzer.dart'; import '../ast.dart'; const _desc = r'Avoid using web-only libraries outside Flutter web plugin packages.'; const _details = r'''Avoid using web libraries, `dart:html`, `dart:js` and `dart:js_util` in Flutter packages that are not web plugins. These libraries are not supported outside a web context; functionality that depends on them will fail at runtime in Flutter mobile, and their use is generally discouraged in Flutter web. Web library access *is* allowed in: * plugin packages that declare `web` as a supported context otherwise, imports of `dart:html`, `dart:js` and `dart:js_util` are disallowed. '''; /// todo (pq): consider making a utility and sharing w/ `prefer_relative_imports` YamlMap _parseYaml(String content) { try { var doc = loadYamlNode(content); if (doc is YamlMap) { return doc; } // ignore: avoid_catches_without_on_clauses } catch (_) { // Fall-through. } return YamlMap(); } class AvoidWebLibrariesInFlutter extends LintRule implements NodeLintRule { AvoidWebLibrariesInFlutter() : super( name: 'avoid_web_libraries_in_flutter', description: _desc, details: _details, maturity: Maturity.experimental, group: Group.errors); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addCompilationUnit(this, visitor); registry.addImportDirective(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { File? pubspecFile; final LintRule rule; bool? _shouldValidateUri; _Visitor(this.rule); bool get shouldValidateUri => _shouldValidateUri ??= checkForValidation(); bool checkForValidation() { var file = pubspecFile; if (file == null) { return false; } YamlMap parsedPubspec; try { var content = file.readAsStringSync(); parsedPubspec = _parseYaml(content); // ignore: avoid_catches_without_on_clauses } catch (_) { return false; } // Check for Flutter. if ((parsedPubspec['dependencies'] ?? const {})['flutter'] == null) { return false; } // Check for a web plugin context declaration. return (((parsedPubspec['flutter'] ?? const {})['plugin'] ?? const {})['platforms'] ?? const {})['web'] == null; } bool isWebUri(String uri) { var uriLength = uri.length; return (uriLength == 9 && uri == 'dart:html') || (uriLength == 7 && uri == 'dart:js') || (uriLength == 12 && uri == 'dart:js_util'); } @override void visitCompilationUnit(CompilationUnit node) { pubspecFile = locatePubspecFile(node); } @override void visitImportDirective(ImportDirective node) { if (shouldValidateUri) { var uriString = node.uri.stringValue; if (uriString != null && isWebUri(uriString)) { rule.reportLint(node); } } } }
linter/lib/src/rules/avoid_web_libraries_in_flutter.dart/0
{'file_path': 'linter/lib/src/rules/avoid_web_libraries_in_flutter.dart', 'repo_id': 'linter', 'token_count': 1267}
// Copyright (c) 2016, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; import '../utils.dart'; const _desc = r'Avoid empty catch blocks.'; const _details = r''' **AVOID** empty catch blocks. In general, empty catch blocks should be avoided. In cases where they are intended, a comment should be provided to explain why exceptions are being caught and suppressed. Alternatively, the exception identifier can be named with underscores (e.g., `_`) to indicate that we intend to skip it. **BAD:** ```dart try { ... } catch(exception) { } ``` **GOOD:** ```dart try { ... } catch(e) { // ignored, really. } // Alternatively: try { ... } catch(_) { } // Better still: try { ... } catch(e) { doSomething(e); } ``` '''; class EmptyCatches extends LintRule implements NodeLintRule { EmptyCatches() : super( name: 'empty_catches', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addCatchClause(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitCatchClause(CatchClause node) { // Skip exceptions named with underscores. var exceptionParameter = node.exceptionParameter; if (exceptionParameter != null && isJustUnderscores(exceptionParameter.name)) { return; } var body = node.body; if (node.body.statements.isEmpty && body.rightBracket.precedingComments == null) { rule.reportLint(body); } } }
linter/lib/src/rules/empty_catches.dart/0
{'file_path': 'linter/lib/src/rules/empty_catches.dart', 'repo_id': 'linter', 'token_count': 702}
// Copyright (c) 2016, 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 '../analyzer.dart'; import '../util/dart_type_utilities.dart'; import '../util/unrelated_types_visitor.dart'; const _desc = r'Invocation of `remove` with references of unrelated types.'; const _details = r''' **DON'T** invoke `remove` on `List` with an instance of different type than the parameter type. Doing this will invoke `==` on its elements and most likely will return `false`. **BAD:** ```dart void someFunction() { var list = <int>[]; if (list.remove('1')) print('someFunction'); // LINT } ``` **BAD:** ```dart void someFunction3() { List<int> list = <int>[]; if (list.remove('1')) print('someFunction3'); // LINT } ``` **BAD:** ```dart void someFunction8() { List<DerivedClass2> list = <DerivedClass2>[]; DerivedClass3 instance; if (list.remove(instance)) print('someFunction8'); // LINT } ``` **BAD:** ```dart abstract class SomeList<E> implements List<E> {} abstract class MyClass implements SomeList<int> { bool badMethod(String thing) => this.remove(thing); // LINT } ``` **GOOD:** ```dart void someFunction10() { var list = []; if (list.remove(1)) print('someFunction10'); // OK } ``` **GOOD:** ```dart void someFunction1() { var list = <int>[]; if (list.remove(1)) print('someFunction1'); // OK } ``` **GOOD:** ```dart void someFunction4() { List<int> list = <int>[]; if (list.remove(1)) print('someFunction4'); // OK } ``` **GOOD:** ```dart void someFunction5() { List<ClassBase> list = <ClassBase>[]; DerivedClass1 instance; if (list.remove(instance)) print('someFunction5'); // OK } abstract class ClassBase {} class DerivedClass1 extends ClassBase {} ``` **GOOD:** ```dart void someFunction6() { List<Mixin> list = <Mixin>[]; DerivedClass2 instance; if (list.remove(instance)) print('someFunction6'); // OK } abstract class ClassBase {} abstract class Mixin {} class DerivedClass2 extends ClassBase with Mixin {} ``` **GOOD:** ```dart void someFunction7() { List<Mixin> list = <Mixin>[]; DerivedClass3 instance; if (list.remove(instance)) print('someFunction7'); // OK } abstract class ClassBase {} abstract class Mixin {} class DerivedClass3 extends ClassBase implements Mixin {} ``` '''; class ListRemoveUnrelatedType extends LintRule implements NodeLintRule { ListRemoveUnrelatedType() : super( name: 'list_remove_unrelated_type', description: _desc, details: _details, group: Group.errors); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this, context.typeSystem); registry.addMethodInvocation(this, visitor); } } class _Visitor extends UnrelatedTypesProcessors { static final _definition = InterfaceTypeDefinition('List', 'dart.core'); _Visitor(LintRule rule, TypeSystem typeSystem) : super(rule, typeSystem); @override InterfaceTypeDefinition get definition => _definition; @override String get methodName => 'remove'; }
linter/lib/src/rules/list_remove_unrelated_type.dart/0
{'file_path': 'linter/lib/src/rules/list_remove_unrelated_type.dart', 'repo_id': 'linter', 'token_count': 1117}
// 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; const _desc = r'Prefix library names with the package name and a dot-separated path.'; const _details = r''' **DO** prefix library names with the package name and a dot-separated path. This guideline helps avoid the warnings you get when two libraries have the same name. Here are the rules we recommend: * Prefix all library names with the package name. * Make the entry library have the same name as the package. * For all other libraries in a package, after the package name add the dot-separated path to the library's Dart file. * For libraries under `lib`, omit the top directory name. For example, say the package name is `my_package`. Here are the library names for various files in the package: **GOOD:** ```dart // In lib/my_package.dart library my_package; // In lib/other.dart library my_package.other; // In lib/foo/bar.dart library my_package.foo.bar; // In example/foo/bar.dart library my_package.example.foo.bar; // In lib/src/private.dart library my_package.src.private; ``` '''; /// Checks if the [name] is equivalent to the specified [prefix] or at least /// is prefixed by it with a delimiting `.`. bool matchesOrIsPrefixedBy(String name, String prefix) => name == prefix || name.startsWith('$prefix.'); class PackagePrefixedLibraryNames extends LintRule implements ProjectVisitor, NodeLintRule { DartProject? project; PackagePrefixedLibraryNames() : super( name: 'package_prefixed_library_names', description: _desc, details: _details, group: Group.style); @override ProjectVisitor getProjectVisitor() => this; @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addLibraryDirective(this, visitor); } @override void visit(DartProject project) { this.project = project; } } class _Visitor extends SimpleAstVisitor<void> { final PackagePrefixedLibraryNames rule; _Visitor(this.rule); @override void visitLibraryDirective(LibraryDirective node) { // If no project info is set, bail early. // https://github.com/dart-lang/linter/issues/154 var project = rule.project; var element = node.element; if (project == null || element == null) { return; } var source = element.source; if (source == null) { return; } var prefix = Analyzer.facade.createLibraryNamePrefix( libraryPath: source.fullName, projectRoot: project.root.absolute.path, packageName: project.name); var name = element.name; if (name == null || !matchesOrIsPrefixedBy(name, prefix)) { rule.reportLint(node.name); } } }
linter/lib/src/rules/package_prefixed_library_names.dart/0
{'file_path': 'linter/lib/src/rules/package_prefixed_library_names.dart', 'repo_id': 'linter', 'token_count': 1021}
// 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 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; const _desc = r'Use => for short members whose body is a single return statement.'; const _details = r''' **CONSIDER** using => for short members whose body is a single return statement. **BAD:** ```dart get width { return right - left; } ``` **BAD:** ```dart bool ready(num time) { return minTime == null || minTime <= time; } ``` **BAD:** ```dart containsValue(String value) { return getValues().contains(value); } ``` **GOOD:** ```dart get width => right - left; ``` **GOOD:** ```dart bool ready(num time) => minTime == null || minTime <= time; ``` **GOOD:** ```dart containsValue(String value) => getValues().contains(value); ``` '''; class PreferExpressionFunctionBodies extends LintRule implements NodeLintRule { PreferExpressionFunctionBodies() : super( name: 'prefer_expression_function_bodies', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addBlockFunctionBody(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitBlockFunctionBody(BlockFunctionBody node) { var statements = node.block.statements; if (statements.length != 1) { return; } var uniqueStatement = node.block.statements.single; if (uniqueStatement is! ReturnStatement) { return; } rule.reportLint(node); } }
linter/lib/src/rules/prefer_expression_function_bodies.dart/0
{'file_path': 'linter/lib/src/rules/prefer_expression_function_bodies.dart', 'repo_id': 'linter', 'token_count': 688}
// Copyright (c) 2019, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; const _desc = r'Prefer is! operator.'; const _details = r''' When checking if an object is not of a specified type, it is preferable to use the 'is!' operator. **BAD:** ```dart if (!(foo is Foo)) { ... } ``` **GOOD:** ```dart if (foo is! Foo) { ... } ``` '''; class PreferIsNotOperator extends LintRule implements NodeLintRule { PreferIsNotOperator() : super( name: 'prefer_is_not_operator', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addIsExpression(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitIsExpression(IsExpression node) { // Return if it is `is!` expression if (node.notOperator != null) { return; } var parent = node.parent; // Check whether is expression is inside parenthesis if (parent is ParenthesizedExpression) { var prefixExpression = parent.parent; // Check for NOT (!) operator if (prefixExpression is PrefixExpression && prefixExpression.operator.type == TokenType.BANG) { rule.reportLint(prefixExpression); } } } }
linter/lib/src/rules/prefer_is_not_operator.dart/0
{'file_path': 'linter/lib/src/rules/prefer_is_not_operator.dart', 'repo_id': 'linter', 'token_count': 647}
// Copyright (c) 2020, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; import '../util/flutter_utils.dart'; const _desc = r'SizedBox for whitespace.'; const _details = r'''Use SizedBox to add whitespace to a layout. A `Container` is a heavier Widget than a `SizedBox`, and as bonus, `SizedBox` has a `const` constructor. **BAD:** ```dart Widget buildRow() { return Row( children: <Widget>[ const MyLogo(), Container(width: 4), const Expanded( child: Text('...'), ), ], ); } ``` **GOOD:** ```dart Widget buildRow() { return Row( children: const <Widget>[ MyLogo(), SizedBox(width: 4), Expanded( child: Text('...'), ), ], ); } ``` '''; class SizedBoxForWhitespace extends LintRule implements NodeLintRule { SizedBoxForWhitespace() : super( name: 'sized_box_for_whitespace', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addInstanceCreationExpression(this, visitor); } } class _Visitor extends SimpleAstVisitor { final LintRule rule; _Visitor(this.rule); @override void visitInstanceCreationExpression(InstanceCreationExpression node) { if (!isExactWidgetTypeContainer(node.staticType)) { return; } var visitor = _WidthOrHeightArgumentVisitor(); node.visitChildren(visitor); if (visitor.seenIncompatibleParams) { return; } if (visitor.seenChild && (visitor.seenWidth || visitor.seenHeight) || visitor.seenWidth && visitor.seenHeight) { rule.reportLint(node.constructorName); } } } class _WidthOrHeightArgumentVisitor extends SimpleAstVisitor<void> { var seenWidth = false; var seenHeight = false; var seenChild = false; var seenIncompatibleParams = false; @override void visitArgumentList(ArgumentList node) { for (var name in node.arguments .cast<NamedExpression>() .map((arg) => arg.name.label.name)) { if (name == 'width') { seenWidth = true; } else if (name == 'height') { seenHeight = true; } else if (name == 'child') { seenChild = true; } else if (name == 'key') { // key doesn't matter (both SiezdBox and Container have it) } else { seenIncompatibleParams = true; } } } }
linter/lib/src/rules/sized_box_for_whitespace.dart/0
{'file_path': 'linter/lib/src/rules/sized_box_for_whitespace.dart', 'repo_id': 'linter', 'token_count': 1083}
// 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; import '../ast.dart'; const _desc = r'Prefer using a public final field instead of a private field with a public' r'getter.'; const _details = r''' From the [style guide](https://dart.dev/guides/language/effective-dart/style/): **PREFER** using a public final field instead of a private field with a public getter. If you have a field that outside code should be able to see but not assign to (and you don't need to set it outside of the constructor), a simple solution that works in many cases is to just mark it `final`. **GOOD:** ```dart class Box { final contents = []; } ``` **BAD:** ```dart class Box { var _contents; get contents => _contents; } ``` '''; class UnnecessaryGetters extends LintRule implements NodeLintRule { UnnecessaryGetters() : super( name: 'unnecessary_getters', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addClassDeclaration(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitClassDeclaration(ClassDeclaration node) { var getters = <String, MethodDeclaration>{}; var setters = <String, MethodDeclaration>{}; // Filter on public methods var members = node.members.where(isPublicMethod); // Build getter/setter maps for (var member in members) { var method = member as MethodDeclaration; if (method.isGetter) { getters[method.name.toString()] = method; } else if (method.isSetter) { setters[method.name.toString()] = method; } } // Only select getters without setters var candidates = getters.keys.where((id) => !setters.keys.contains(id)); candidates.map((n) => getters[n]).forEach(_visitGetter); } void _visitGetter(MethodDeclaration? getter) { if (getter != null && isSimpleGetter(getter)) { rule.reportLint(getter.name); } } }
linter/lib/src/rules/unnecessary_getters.dart/0
{'file_path': 'linter/lib/src/rules/unnecessary_getters.dart', 'repo_id': 'linter', 'token_count': 870}
// Copyright (c) 2019, 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:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import '../analyzer.dart'; import '../util/dart_type_utilities.dart'; const _descPrefix = r'Avoid unsafe HTML APIs'; const _desc = '$_descPrefix.'; const _details = r''' **AVOID** * assigning directly to the `href` field of an AnchorElement * assigning directly to the `src` field of an EmbedElement, IFrameElement, ImageElement, or ScriptElement * assigning directly to the `srcdoc` field of an IFrameElement * calling the `createFragment` method of Element * calling the `open` method of Window * calling the `setInnerHtml` method of Element * calling the `Element.html` constructor * calling the `DocumentFragment.html` constructor **BAD:** ```dart var script = ScriptElement()..src = 'foo.js'; ``` '''; extension on DartType? { /// Returns whether this type extends [className] from the dart:html library. bool extendsDartHtmlClass(String className) => DartTypeUtilities.extendsClass(this, className, 'dart.dom.html'); } class UnsafeHtml extends LintRule implements NodeLintRule { UnsafeHtml() : super( name: 'unsafe_html', description: _desc, details: _details, group: Group.errors); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addAssignmentExpression(this, visitor); registry.addInstanceCreationExpression(this, visitor); registry.addFunctionExpressionInvocation(this, visitor); registry.addMethodInvocation(this, visitor); } @override List<LintCode> get lintCodes => [ _Visitor.unsafeAttributeCode, _Visitor.unsafeMethodCode, _Visitor.unsafeConstructorCode ]; } class _Visitor extends SimpleAstVisitor<void> { // TODO(srawlins): Reference attributes ('href', 'src', and 'srcdoc') with // single-quotes to match the convention in the analyzer and linter packages. // This requires some coordination within Google, as various allow-lists are // keyed on the exact text of the LintCode message. // ignore: deprecated_member_use static const unsafeAttributeCode = SecurityLintCodeWithUniqueName( 'unsafe_html', 'LintCode.unsafe_html_attribute', '$_descPrefix (assigning "{0}" attribute).'); // ignore: deprecated_member_use static const unsafeMethodCode = SecurityLintCodeWithUniqueName( 'unsafe_html', 'LintCode.unsafe_html_method', "$_descPrefix (calling the '{0}' method of {1})."); // ignore: deprecated_member_use static const unsafeConstructorCode = SecurityLintCodeWithUniqueName( 'unsafe_html', 'LintCode.unsafe_html_constructor', "$_descPrefix (calling the '{0}' constructor of {1})."); final LintRule rule; _Visitor(this.rule); @override void visitAssignmentExpression(AssignmentExpression node) { var leftPart = node.leftHandSide.unParenthesized; if (leftPart is SimpleIdentifier) { var leftPartElement = node.writeElement; if (leftPartElement == null) return; var enclosingElement = leftPartElement.enclosingElement; if (enclosingElement is ClassElement) { _checkAssignment(enclosingElement.thisType, leftPart, node); } } else if (leftPart is PropertyAccess) { _checkAssignment( leftPart.realTarget.staticType, leftPart.propertyName, node); } else if (leftPart is PrefixedIdentifier) { _checkAssignment(leftPart.prefix.staticType, leftPart.identifier, node); } } void _checkAssignment(DartType? type, SimpleIdentifier property, AssignmentExpression assignment) { if (type == null) return; // It is more efficient to check the setter's name before checking whether // the target is an interesting type. if (property.name == 'href') { if (type.isDynamic || type.extendsDartHtmlClass('AnchorElement')) { rule.reportLint(assignment, arguments: ['href'], errorCode: unsafeAttributeCode); } } else if (property.name == 'src') { if (type.isDynamic || type.extendsDartHtmlClass('EmbedElement') || type.extendsDartHtmlClass('IFrameElement') || type.extendsDartHtmlClass('ImageElement') || type.extendsDartHtmlClass('ScriptElement')) { rule.reportLint(assignment, arguments: ['src'], errorCode: unsafeAttributeCode); } } else if (property.name == 'srcdoc') { if (type.isDynamic || type.extendsDartHtmlClass('IFrameElement')) { rule.reportLint(assignment, arguments: ['srcdoc'], errorCode: unsafeAttributeCode); } } } @override void visitInstanceCreationExpression(InstanceCreationExpression node) { var type = node.staticType; if (type == null) return; var constructorName = node.constructorName; if (constructorName.name?.name == 'html') { if (type.extendsDartHtmlClass('DocumentFragment')) { rule.reportLint(node, arguments: ['html', 'DocumentFragment'], errorCode: unsafeConstructorCode); } else if (type.extendsDartHtmlClass('Element')) { rule.reportLint(node, arguments: ['html', 'Element'], errorCode: unsafeConstructorCode); } } } @override void visitMethodInvocation(MethodInvocation node) { var methodName = node.methodName.name; // The static type of the target. DartType? type; if (node.realTarget == null) { // Implicit `this` target. var methodElement = node.methodName.staticElement; if (methodElement == null) return; var enclosingElement = methodElement.enclosingElement; if (enclosingElement is ClassElement) { type = enclosingElement.thisType; } else { return; } } else { type = node.realTarget?.staticType; if (type == null) return; } if (methodName == 'createFragment' && (type.isDynamic || type.extendsDartHtmlClass('Element'))) { rule.reportLint(node, arguments: ['createFragment', 'Element'], errorCode: unsafeMethodCode); } else if (methodName == 'setInnerHtml' && (type.isDynamic || type.extendsDartHtmlClass('Element'))) { rule.reportLint(node, arguments: ['setInnerHtml', 'Element'], errorCode: unsafeMethodCode); } else if (methodName == 'open' && (type.isDynamic || type.extendsDartHtmlClass('Window'))) { rule.reportLint(node, arguments: ['open', 'Window'], errorCode: unsafeMethodCode); } } }
linter/lib/src/rules/unsafe_html.dart/0
{'file_path': 'linter/lib/src/rules/unsafe_html.dart', 'repo_id': 'linter', 'token_count': 2547}
// Copyright (c) 2019, 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:analyzer/error/error.dart'; import 'package:analyzer/source/line_info.dart'; Annotation? extractAnnotation(int lineNumber, String line) { var regexp = RegExp(r'(//|#) ?LINT( \[([\-+]\d+)?(,?(\d+):(\d+))?\])?( (.*))?$'); var match = regexp.firstMatch(line); if (match == null) return null; // ignore lints on commented out lines var index = match.start; var comment = match[1]!; if (line.indexOf(comment) != index) return null; var relativeLine = match[3].toInt() ?? 0; var column = match[5].toInt(); var length = match[6].toInt(); var message = match[8].toNullIfBlank(); return Annotation.forLint(message, column, length) ..lineNumber = lineNumber + relativeLine; } /// Information about a 'LINT' annotation/comment. class Annotation implements Comparable<Annotation> { final int? column; final int? length; final String? message; final ErrorType type; int? lineNumber; Annotation(this.message, this.type, this.lineNumber, {this.column, this.length}); Annotation.forError(AnalysisError error, LineInfo lineInfo) : this(error.message, error.errorCode.type, lineInfo.getLocation(error.offset).lineNumber, column: lineInfo.getLocation(error.offset).columnNumber, length: error.length); Annotation.forLint([String? message, int? column, int? length]) : this(message, ErrorType.LINT, null, column: column, length: length); @override int compareTo(Annotation other) { if (lineNumber != other.lineNumber) { return lineNumber! - other.lineNumber!; } else if (column != other.column) { return column! - other.column!; } return message!.compareTo(other.message!); } @override String toString() => '[$type]: "$message" (line: $lineNumber) - [$column:$length]'; } extension on String? { int? toInt() => this == null ? null : int.parse(this!); String? toNullIfBlank() => this == null || this!.trim().isEmpty == true ? null : this; }
linter/lib/src/test_utilities/annotation.dart/0
{'file_path': 'linter/lib/src/test_utilities/annotation.dart', 'repo_id': 'linter', 'token_count': 780}
import 'package:sample_project/dummy.dart'; // OK
linter/test/_data/always_use_package_imports/bin/bin.dart/0
{'file_path': 'linter/test/_data/always_use_package_imports/bin/bin.dart', 'repo_id': 'linter', 'token_count': 17}
import 'dart:html'; //LINT import 'dart:js'; //LINT import 'dart:js_util'; //LINT
linter/test/_data/avoid_web_libraries_in_flutter/non_web_app/lib/main.dart/0
{'file_path': 'linter/test/_data/avoid_web_libraries_in_flutter/non_web_app/lib/main.dart', 'repo_id': 'linter', 'token_count': 35}
part of dummy_lib;
linter/test/_data/directives_ordering/export_directives_after_import_directives/dummy4.dart/0
{'file_path': 'linter/test/_data/directives_ordering/export_directives_after_import_directives/dummy4.dart', 'repo_id': 'linter', 'token_count': 7}
import 'package:sample_project/dummy.dart'; //LINT import 'package:p6/p6_lib.dart'; //OK import 'package:internal_path_package/internal_lib.dart'; //OK import 'dummy.dart'; //OK
linter/test/_data/prefer_relative_imports/lib/main.dart/0
{'file_path': 'linter/test/_data/prefer_relative_imports/lib/main.dart', 'repo_id': 'linter', 'token_count': 70}
// 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:analyzer/dart/ast/ast.dart' show AstNode, AstVisitor; import 'package:analyzer/dart/ast/visitor.dart'; import 'package:analyzer/error/error.dart'; import 'package:analyzer/src/error/codes.dart'; import 'package:analyzer/src/lint/io.dart'; import 'package:analyzer/src/lint/linter.dart' hide CamelCaseString; import 'package:analyzer/src/lint/pub.dart'; import 'package:analyzer/src/string_source.dart' show StringSource; import 'package:cli_util/cli_util.dart' show getSdkPath; import 'package:linter/src/cli.dart' as cli; import 'package:linter/src/utils.dart'; import 'package:test/test.dart'; import 'mocks.dart'; import 'rule_test.dart' show ruleDir; void main() { defineLinterEngineTests(); } /// Linter engine tests void defineLinterEngineTests() { group('engine', () { group('reporter', () { void _test( String label, String expected, Function(PrintingReporter r) report) { test(label, () { String? msg; var reporter = PrintingReporter((m) => msg = m); report(reporter); expect(msg, expected); }); } _test('exception', 'EXCEPTION: LinterException: foo', (r) => r.exception(LinterException('foo'))); _test('warn', 'WARN: foo', (r) => r.warn('foo')); }); group('exceptions', () { test('message', () { expect(const LinterException('foo').message, 'foo'); }); test('toString', () { expect(const LinterException().toString(), 'LinterException'); expect(const LinterException('foo').toString(), 'LinterException: foo'); }); }); group('camel case', () { test('humanize', () { expect(CamelCaseString('FooBar').humanized, 'Foo Bar'); expect(CamelCaseString('Foo').humanized, 'Foo'); }); test('validation', () { expect(() => CamelCaseString('foo'), throwsA(TypeMatcher<ArgumentError>())); }); test('toString', () { expect(CamelCaseString('FooBar').toString(), 'FooBar'); }); }); group('groups', () { test('factory', () { expect(Group('style').custom, isFalse); expect(Group('pub').custom, isFalse); expect(Group('errors').custom, isFalse); expect(Group('Kustom').custom, isTrue); }); test('builtins', () { expect(Group.builtin.contains(Group.style), isTrue); expect(Group.builtin.contains(Group.errors), isTrue); expect(Group.builtin.contains(Group.pub), isTrue); }); }); group('lint driver', () { test('pubspec', () { bool? visited; var options = LinterOptions([MockLinter((n) => visited = true)]); SourceLinter(options).lintPubspecSource(contents: 'name: foo_bar'); expect(visited, isTrue); }); test('error collecting', () { var error = AnalysisError(StringSource('foo', ''), 0, 0, LintCode('MockLint', 'This is a test...')); var linter = SourceLinter(LinterOptions([]))..onError(error); expect(linter.errors.contains(error), isTrue); }); }); group('main', () { setUp(() { exitCode = 0; errorSink = MockIOSink(); }); tearDown(() { exitCode = 0; errorSink = stderr; }); test('smoke', () async { var firstRuleTest = Directory(ruleDir).listSync().firstWhere(isDartFile); await cli.run([firstRuleTest.path]); expect(cli.isLinterErrorCode(exitCode), isFalse); }); test('no args', () async { await cli.run([]); expect(exitCode, cli.unableToProcessExitCode); }); test('help', () async { await cli.run(['-h']); // Help shouldn't generate an error code expect(cli.isLinterErrorCode(exitCode), isFalse); }); test('unknown arg', () async { await cli.run(['-XXXXX']); expect(exitCode, cli.unableToProcessExitCode); }); test('custom sdk path', () async { // Smoke test to ensure a custom sdk path doesn't sink the ship var firstRuleTest = Directory(ruleDir).listSync().firstWhere(isDartFile); var sdk = getSdkPath(); await cli.run(['--dart-sdk', sdk, firstRuleTest.path]); expect(cli.isLinterErrorCode(exitCode), isFalse); }); }); group('dtos', () { group('hyperlink', () { test('html', () { var link = Hyperlink('dart', 'http://dart.dev'); expect(link.html, '<a href="http://dart.dev">dart</a>'); }); test('html - strong', () { var link = Hyperlink('dart', 'http://dart.dev', bold: true); expect( link.html, '<a href="http://dart.dev"><strong>dart</strong></a>'); }); }); group('rule', () { test('comparing', () { LintRule r1 = MockLintRule('Bar', Group('acme')); LintRule r2 = MockLintRule('Foo', Group('acme')); expect(r1.compareTo(r2), -1); LintRule r3 = MockLintRule('Bar', Group('acme')); LintRule r4 = MockLintRule('Bar', Group('woody')); expect(r3.compareTo(r4), -1); }); }); group('maturity', () { test('comparing', () { // Custom var m1 = Maturity('foo', ordinal: 0); var m2 = Maturity('bar', ordinal: 1); expect(m1.compareTo(m2), -1); // Builtin expect(Maturity.stable.compareTo(Maturity.experimental), -1); }); }); }); }); } typedef NodeVisitor = void Function(Object node); class MockLinter extends LintRule { final NodeVisitor? nodeVisitor; MockLinter([this.nodeVisitor]) : super( name: 'MockLint', group: Group.style, description: 'Desc', details: 'And so on...'); @override PubspecVisitor getPubspecVisitor() => MockVisitor(nodeVisitor); @override AstVisitor getVisitor() => MockVisitor(nodeVisitor); } class MockLintRule extends LintRule { MockLintRule(String name, Group group) : super(name: name, group: group, description: '', details: ''); @override AstVisitor getVisitor() => MockVisitor(null); } class MockVisitor extends GeneralizingAstVisitor with PubspecVisitor { final Function(Object node)? nodeVisitor; MockVisitor(this.nodeVisitor); @override void visitNode(AstNode node) { if (nodeVisitor != null) { nodeVisitor!(node); } } @override void visitPackageName(PSEntry node) { if (nodeVisitor != null) { nodeVisitor!(node); } } }
linter/test/engine_test.dart/0
{'file_path': 'linter/test/engine_test.dart', 'repo_id': 'linter', 'token_count': 2961}
// Copyright (c) 2020, 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:analyzer/src/lint/io.dart'; import 'package:linter/src/cli.dart' as cli; import 'package:test/test.dart'; import '../mocks.dart'; void main() { group('overridden_fields', () { var currentOut = outSink; var collectingOut = CollectingSink(); setUp(() { exitCode = 0; outSink = collectingOut; }); tearDown(() { collectingOut.buffer.clear(); outSink = currentOut; exitCode = 0; }); // https://github.com/dart-lang/linter/issues/246 test('overrides across libraries', () async { await cli.run( ['test/_data/overridden_fields', '--rules', 'overridden_fields']); expect( collectingOut.trim(), stringContainsInOrder( ['int public;', '2 files analyzed, 1 issue found, in'])); expect(exitCode, 1); }); }); }
linter/test/integration/overridden_fields.dart/0
{'file_path': 'linter/test/integration/overridden_fields.dart', 'repo_id': 'linter', 'token_count': 430}
// 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. // test w/ `dart test -N always_put_required_named_parameters_first` import 'package:meta/meta.dart'; m1( a, // OK { b, // OK @required c, // LINT @required d, // LINT e, // OK @required f, // LINT }) {} m2({ @required a, // OK @required b, // OK c, // OK @required d, // LINT e, // OK @required f, // LINT }) {} n1( a, // OK { b, // OK required c, // LINT required d, // LINT e, // OK required f, // LINT }) {} n2({ required a, // OK required b, // OK c, // OK required d, // LINT e, // OK required f, // LINT }) {} class A { A.c1( a, // OK { b, // OK @required c, // LINT @required d, // LINT e, // OK @required f, // LINT }); A.c2({ @required a, // OK @required b, // OK c, // OK @required d, // LINT e, // OK @required f, // LINT }); A.d1( a, // OK { b, // OK required c, // LINT required d, // LINT e, // OK required f, // LINT }); A.d2({ required a, // OK required b, // OK c, // OK required d, // LINT e, // OK required f, // LINT }); }
linter/test/rules/always_put_required_named_parameters_first.dart/0
{'file_path': 'linter/test/rules/always_put_required_named_parameters_first.dart', 'repo_id': 'linter', 'token_count': 585}
// Copyright (c) 2018, 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. // test w/ `dart test -N avoid_implementing_value_types` class Size { // OK final int inBytes; const Size(this.inBytes); @override bool operator ==(Object o) => o is Size && o.inBytes == inBytes; @override int get hashCode => inBytes.hashCode; } class SizeWithKilobytes extends Size { // OK SizeWithKilobytes(int inBytes) : super(inBytes); double get inKilobytes => inBytes / 1000; } class EmptyFileSize1 implements Size { // LINT @override int get inBytes => 0; } class EmptyFileSize2 implements SizeWithKilobytes { // LINT @override int get inBytes => 0; @override double get inKilobytes => 0.0; } abstract class SizeClassMixin { // OK int get inBytes => 0; @override bool operator ==(Object o) => o is Size && o.inBytes == o.inBytes; @override int get hashCode => inBytes.hashCode; } class UsesSizeClassMixin extends Object with SizeClassMixin {} // OK
linter/test/rules/avoid_implementing_value_types.dart/0
{'file_path': 'linter/test/rules/avoid_implementing_value_types.dart', 'repo_id': 'linter', 'token_count': 367}
// Copyright (c) 2018, 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. // test w/ `dart test -N avoid_shadowing_type_parameters` void fn1<T>() { void fn2<T>() {} // LINT void fn3<U>() {} // OK void fn4() {} // OK } // TODO(srawlins): Lint on this stuff as well when the analyzer/language(?) // support it. Right now analyzer spits out a compile time error: "Analysis of // generic function typed parameters is not yet supported." // void fn2<T>(void Function<T>()) {} // NOT OK class A<T> { static void fn1<T>() {} // OK } extension Ext<T> on A<T> { void fn2<T>() {} // LINT void fn3<U>() {} // OK void fn4<V>() {} // OK } mixin M<T> { void fn1<T>() {} // LINT void fn2<U>() {} // OK void fn3<V>() {} // OK } class B<T> { void fn1<T>() {} // LINT void fn2<U>() {} // OK void fn3<V>() {} // OK } class C<T> { void fn1<U>() { void fn2<T>() {} // LINT void fn3<U>() {} // LINT void fn4<V>() {} // OK void fn5() {} // OK } } class D<T> { void fn1<U>() { void fn2<V>() { void fn3<T>() {} // LINT void fn4<U>() {} // LINT void fn5<V>() {} // LINT void fn6<W>() {} // OK void fn7() {} // OK } } } // Make sure we don't hit any null pointers when none of a function or method's // ancestors have type parameters. class E { void fn1() { void fn2() { void fn3<T>() {} // OK } } void fn4<T>() {} // OK } typedef Fn1<T> = void Function<T>(T); // LINT typedef Fn2<T> = void Function<U>(T); // OK typedef Fn3<T> = void Function<U>(U); // OK typedef Fn4<T> = void Function(T); // OK typedef Fn5 = void Function<T>(T); // OK typedef Predicate = bool <E>(E element); // OK
linter/test/rules/avoid_shadowing_type_parameters.dart/0
{'file_path': 'linter/test/rules/avoid_shadowing_type_parameters.dart', 'repo_id': 'linter', 'token_count': 758}
// Copyright (c) 2018, 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. // test w/ `dart test -N curly_braces_in_flow_control_structures` testIfElse() { if (false) return; // OK if (false) {} // OK if (false) return; // LINT if (false) { // OK } if (false) return; // LINT else return; // LINT if (false) { } else if (false) { // OK } else { } if (false) return; // LINT else if (false) return; // LINT else return; // LINT if (false) { // OK } else if (false) { // OK } else { // OK } if (false) { } // OK else return; // LINT if (false) return; // LINT else return; // LINT if (false){ }// OK else {} // OK if (false) print( // LINT 'First argument' 'Second argument'); if (false) { print('should be on next line'); // OK } } testWhile() { while (true) return; // LINT while (true) {} // OK while (true) return; // LINT } testForEach(List l) { for (var i in l) return; // LINT for (var i in l) {} // OK for (var i in l) return; // LINT } testFor() { for (;;) return; // LINT for (;;) {} // OK for (;;) return; // LINT } testDo() { do print(''); while (true); // LINT do print(''); // LINT while (true); do print(''); // LINT while (true); do {print('');} // OK while (true); }
linter/test/rules/curly_braces_in_flow_control_structures.dart/0
{'file_path': 'linter/test/rules/curly_braces_in_flow_control_structures.dart', 'repo_id': 'linter', 'token_count': 585}
// Copyright (c) 2020, 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. // test w/ `dart test -N prefer_constructors_over_static_methods` class A { static final array = <A>[]; A.internal(); static A bad1() => // LINT new A.internal(); static A get newA => // LINT new A.internal(); static A bad2() { // LINT final a = new A.internal(); return a; } static A good1(int i) { // OK return array[i]; } factory A.good2() { // OK return new A.internal(); } factory A.good3() { // OK return new A.internal(); } static A generic<T>() => // OK A.internal(); static Object ok() => Object(); // OK static A? ok() => 1==1 ? null : A(); // OK } class B<T> { B.internal(); static B<T> good1<T>(T one) => // OK B.internal(); static B good2() => // OK B.internal(); static B<int> good3() => // OK B<int>.internal(); } extension E on A { static A foo() => A.internal(); // OK }
linter/test/rules/experiments/nnbd/rules/prefer_constructors_over_static_methods.dart/0
{'file_path': 'linter/test/rules/experiments/nnbd/rules/prefer_constructors_over_static_methods.dart', 'repo_id': 'linter', 'token_count': 414}
// Copyright (c) 2016, 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. // test w/ `dart test -N iterable_contains_unrelated_type` void someFunction() { var list = <int>[]; if (list.contains('1')) print('someFunction'); // LINT } void someFunction1() { var list = <int>[]; if (list.contains(1)) print('someFunction1'); // OK } void someFunction3() { List<int> list = <int>[]; if (list.contains('1')) print('someFunction3'); // LINT } void someFunction4() { List<int> list = <int>[]; if (list.contains(1)) print('someFunction4'); // OK } void someFunction4_1() { List list; if (list.contains(null)) print('someFucntion4_1'); } void someFunction5_1() { List<ClassBase> list = <ClassBase>[]; Object instance; if (list.contains(instance)) print('someFunction5_1'); // OK } void someFunction5() { List<ClassBase> list = <ClassBase>[]; DerivedClass1 instance; if (list.contains(instance)) print('someFunction5'); // OK } void someFunction6() { List<Mixin> list = <Mixin>[]; DerivedClass2 instance; if (list.contains(instance)) print('someFunction6'); // OK } void someFunction6_1() { List<DerivedClass2> list = <DerivedClass2>[]; Mixin instance; if (list.contains(instance)) print('someFunction6_1'); // OK } void someFunction7() { List<Mixin> list = <Mixin>[]; DerivedClass3 instance; if (list.contains(instance)) print('someFunction7'); // OK } void someFunction7_1() { List<DerivedClass3> list = <DerivedClass3>[]; Mixin instance; if (list.contains(instance)) print('someFunction7_1'); // OK } void someFunction8() { List<DerivedClass2> list = <DerivedClass2>[]; DerivedClass3 instance; if (list.contains(instance)) print('someFunction8'); // OK } void someFunction9() { List<Implementation> list = <Implementation>[]; Abstract instance = new Abstract(); if (list.contains(instance)) print('someFunction9'); // OK } void someFunction10() { var list = []; if (list.contains(1)) print('someFunction10'); // OK } void someFunction11(unknown) { var what = unknown - 1; List<int> list = <int>[]; list.forEach((int i) { if (what == i) print('someFunction11'); // OK }); } void someFunction12() { List<DerivedClass4> list = <DerivedClass4>[]; DerivedClass5 instance; if (list.contains(instance)) print('someFunction12'); // LINT } void bug_267(list) { if (list.contains('1')) // https://github.com/dart-lang/linter/issues/267 print('someFunction'); } abstract class ClassBase {} class DerivedClass1 extends ClassBase {} abstract class Mixin {} class DerivedClass2 extends ClassBase with Mixin {} class DerivedClass3 extends ClassBase implements Mixin {} abstract class Abstract { factory Abstract() { return new Implementation(); } Abstract._internal(); } class Implementation extends Abstract { Implementation() : super._internal(); } class DerivedClass4 extends DerivedClass2 {} class DerivedClass5 extends DerivedClass3 {} bool takesIterable(Iterable<int> iterable) => iterable.contains('a'); // LINT bool takesIterable2(Iterable<String> iterable) => iterable.contains('a'); // OK bool takesIterable3(Iterable iterable) => iterable.contains('a'); // OK abstract class A implements Iterable<int> {} abstract class B extends A {} bool takesB(B b) => b.contains('a'); // LINT abstract class A1 implements Iterable<String> {} abstract class B1 extends A1 {} bool takesB1(B1 b) => b.contains('a'); // OK abstract class A3 implements Iterable {} abstract class B3 extends A3 {} bool takesB3(B3 b) => b.contains('a'); // OK abstract class AddlInterface {} abstract class SomeIterable<E> implements Iterable<E>, AddlInterface {} abstract class MyClass implements SomeIterable<int> { bool badMethod(String thing) => this.contains(thing); // LINT bool badMethod1(String thing) => contains(thing); // LINT } abstract class MyDerivedClass extends MyClass { bool myConcreteBadMethod(String thing) => this.contains(thing); // LINT bool myConcreteBadMethod1(String thing) => contains(thing); // LINT } abstract class MyMixedClass extends Object with MyClass { bool myConcreteBadMethod(String thing) => this.contains(thing); // LINT bool myConcreteBadMethod1(String thing) => contains(thing); // LINT } abstract class MyIterableMixedClass extends Object with MyClass implements Iterable<int> { bool myConcreteBadMethod(String thing) => this.contains(thing); // LINT bool myConcreteBadMethod1(String thing) => contains(thing); // LINT }
linter/test/rules/iterable_contains_unrelated_type.dart/0
{'file_path': 'linter/test/rules/iterable_contains_unrelated_type.dart', 'repo_id': 'linter', 'token_count': 1530}
// Copyright (c) 2018, 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. // test w/ `dart test -N prefer_const_literals_to_create_immutables` import 'package:meta/meta.dart'; @immutable class A { const A(a); const A.named({a}); } // basic tests var l1 = new A([]); // LINT var l2 = new A(const[]); // OK // tests for nested lists var l3 = new A([ // LINT []]); // LINT var l4 = new A([ // LINT const[]]); // OK var l5 = new A(const[ //OK const[]]); // OK // tests with maps and parenthesis var l6 = new A({1: // LINT []});// LINT var l7 = new A(const {1: const []});// OK var l8 = new A((([])));// LINT var l9 = new A(((const[])));// OK // test with const inside var l10 = new A([const A(null)]); // LINT // test named parameter var l11 = new A.named(a: []); // LINT // test with literals var l12 = new A([1]); // LINT var l13 = new A([1.0]); // LINT var l14 = new A(['']); // LINT var l15 = new A([null]); // LINT // basic tests var m1 = new A({}); // LINT var m2 = new A(const{}); // OK // tests for nested maps var m3 = new A({ // LINT 1: {}}); // LINT var m4 = new A({ // LINT 1: const{}}); // OK var m5 = new A(const{1: //OK const{}}); // OK // tests with lists and parenthesis var m6 = new A([ // LINT {}]);// LINT var m7 = new A(const [const {}]);// OK var m8 = new A((({})));// LINT var m9 = new A(((const{})));// OK // test with const inside var m10 = new A({1: const A(null)}); // LINT // test named parameter var m11 = new A.named(a: {}); // LINT // test with literals var m12 = new A({1: 1}); // LINT var m13 = new A({1: 1.0}); // LINT var m14 = new A({1: ''}); // LINT var m15 = new A({1: null}); // LINT // ignore: undefined_class var e1 = new B([]); // OK // optional new class C {} var m16 = A([C()]); // OK @immutable class K { final List<K> children; const K({this.children}); } final k = K( children: <K>[for (var i = 0; i < 5; ++i) K()], // OK );
linter/test/rules/prefer_const_literals_to_create_immutables.dart/0
{'file_path': 'linter/test/rules/prefer_const_literals_to_create_immutables.dart', 'repo_id': 'linter', 'token_count': 798}
// Copyright (c) 2019, 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. // test w/ `dart test -N prefer_inlined_adds` var l = ['a']..add('b'); // LINT var l2 = ['a']..add('b')..add('c'); // LINT var l3 = ['a']..addAll(['b', 'c']); // LINT var things; var l4 = ['a']..addAll(things ?? const []); // OK
linter/test/rules/prefer_inlined_adds.dart/0
{'file_path': 'linter/test/rules/prefer_inlined_adds.dart', 'repo_id': 'linter', 'token_count': 158}
// Copyright (c) 2016, 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. // test w/ `dart test -N recursive_getters` class C { final int _field = 0; int get field => field; // LINT int get otherField { return otherField; // LINT } int get correct => _field; int get correctBody { return _field; } int someMethod() => someMethod(); int get value => plusOne(value); // LINT } int _field = 0; int get field => field; // LINT int get otherField { return otherField; // LINT } int get correct => _field; int get correctBody { return _field; } int get value => _field == null ? 0 : value; // LINT int plusOne(int arg) => 0; // https://github.com/dart-lang/linter/issues/586 class Nested { final Nested _parent; Nested(this._parent); Nested get ancestor => _parent.ancestor; //OK Nested get thisRecursive => this.thisRecursive; // LINT Nested get recursive => recursive; // LINT }
linter/test/rules/recursive_getters.dart/0
{'file_path': 'linter/test/rules/recursive_getters.dart', 'repo_id': 'linter', 'token_count': 351}
// Copyright (c) 2019, 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. // test w/ `dart test -N unnecessary_final` void badMethod(final int x) { // LINT final label = 'Final or var?'; // LINT print(label); for (final char in ['v', 'a', 'r']) { // LINT print(((final String char) => char.length)(char)); // LINT } } void goodMethod(int x) { var label = 'Final or var?'; // OK print(label); for (var char in ['v', 'a', 'r']) { // OK print(((String char) => char.length)(char)); // OK } } class GoodClass { final int x = 3; // OK }
linter/test/rules/unnecessary_final.dart/0
{'file_path': 'linter/test/rules/unnecessary_final.dart', 'repo_id': 'linter', 'token_count': 242}
// Copyright (c) 2019, 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. // test w/ `dart test -N unsafe_html` import 'dart:html'; void main() { AnchorElement()..href = 'foo'; // LINT var embed = EmbedElement(); embed.src = 'foo'; // LINT IFrameElement()..src = 'foo'; // LINT ImageElement()..src = 'foo'; // LINT var script = ScriptElement(); script.src = 'foo.js'; // LINT var src = 'foo.js'; // OK var src2 = script.src; // OK script ..type = 'application/javascript' ..src = 'foo.js'; // LINT script ..src = 'foo.js' // LINT ..type = 'application/javascript'; script?.src = 'foo.js'; // LINT IFrameElement()..srcdoc = 'foo'; // LINT var heading = HeadingElement.h1(); heading.createFragment('<script>'); // LINT heading..createFragment('<script>'); // LINT heading.setInnerHtml('<script>'); // LINT heading..setInnerHtml('<script>'); // LINT Window().open('url', 'name'); // LINT Window()..open('url', 'name'); // LINT DocumentFragment.html('<script>'); // LINT Element.html('<script>'); // LINT C().src = 'foo.js'; // OK var c = C(); c..src = 'foo.js'; // OK c?.src = 'foo.js'; // OK c.srcdoc = 'foo.js'; // OK c.createFragment('<script>'); // OK c.open('url', 'name'); // OK c.setInnerHtml('<script>'); // OK C.html('<script>'); // OK dynamic d; d.src = 'foo.js'; // LINT d.srcdoc = 'foo.js'; // LINT d.href = 'foo.js'; // LINT d.createFragment('<script>'); // LINT d.open('url', 'name'); // LINT d.setInnerHtml('<script>'); // LINT (script as dynamic).src = 'foo.js'; // LINT (C() as dynamic).src = 'foo.js'; // LINT } class C { String src; String srcdoc; String href; C(); C.html(String content); void createFragment(String html) {} void open(String url, String name) {} void setInnerHtml(String html) {} } extension on ScriptElement { void sneakySetSrc1(String url) => src = url; // LINT void sneakySetSrc2(String url) => this.src = url; // LINT void sneakyCreateFragment1(String html) => createFragment(html); // LINT void sneakyCreateFragment2(String html) => this.createFragment(html); // LINT void sneakySetInnerHtml1(String html) => setInnerHtml(html); // LINT void sneakySetInnerHtml2(String html) => this.setInnerHtml(html); // LINT } extension on Window { void sneakyOpen1(String url, String name) => open(url, name); // LINT void sneakyOpen2(String url, String name) => this.open(url, name); // LINT } extension on C { void sneakySetSrc1(String url) => src = url; // OK void sneakySetSrc2(String url) => this.src = url; // OK void sneakyCreateFragment1(String html) => createFragment(html); // OK void sneakyCreateFragment2(String html) => this.createFragment(html); // OK void sneakySetInnerHtml1(String html) => setInnerHtml(html); // OK void sneakySetInnerHtml2(String html) => this.setInnerHtml(html); // OK void sneakyOpen1(String url, String name) => open(url, name); // OK void sneakyOpen2(String url, String name) => this.open(url, name); // OK }
linter/test/rules/unsafe_html.dart/0
{'file_path': 'linter/test/rules/unsafe_html.dart', 'repo_id': 'linter', 'token_count': 1139}
// Copyright (c) 2019, 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:analyzer/error/error.dart'; import 'package:linter/src/test_utilities/annotation.dart'; import 'package:test/test.dart'; AnnotationMatcher matchesAnnotation( String? message, ErrorType type, int lineNumber) => AnnotationMatcher(Annotation(message, type, lineNumber)); class AnnotationMatcher extends Matcher { final Annotation _expected; AnnotationMatcher(this._expected); @override Description describe(Description description) => description.addDescriptionOf(_expected); @override bool matches(item, Map matchState) => item is Annotation && _matches(item); bool _matches(Annotation other) { // Only test messages if they're specified in the expectation if (_expected.message != null) { if (_expected.message != other.message) { return false; } } // Similarly for highlighting if (_expected.column != null) { if (_expected.column != other.column || _expected.length != other.length) { return false; } } return _expected.type == other.type && _expected.lineNumber == other.lineNumber; } }
linter/test/util/annotation_matcher.dart/0
{'file_path': 'linter/test/util/annotation_matcher.dart', 'repo_id': 'linter', 'token_count': 437}
linter: rules: - avoid_empty_else - avoid_relative_lib_imports - avoid_shadowing_type_parameters - avoid_types_as_parameter_names - await_only_futures - camel_case_extensions - camel_case_types - curly_braces_in_flow_control_structures - empty_catches - file_names - hash_and_equals - iterable_contains_unrelated_type - list_remove_unrelated_type - no_duplicate_case_values - non_constant_identifier_names - package_prefixed_library_names - prefer_generic_function_type_aliases - prefer_is_empty - prefer_is_not_empty - prefer_iterable_whereType - prefer_typing_uninitialized_variables - provide_deprecation_message - unawaited_futures - unnecessary_overrides - unrelated_type_equality_checks - valid_regexps - void_checks
linter/tool/canonical/core.yaml/0
{'file_path': 'linter/tool/canonical/core.yaml', 'repo_id': 'linter', 'token_count': 335}
always_declare_return_types: 0.1.4 always_put_control_body_on_new_line: 0.1.31 always_put_required_named_parameters_first: 0.1.33 always_require_non_null_named_parameters: 0.1.31 always_specify_types: 0.1.4 annotate_overrides: 0.1.11 avoid_annotating_with_dynamic: 0.1.31 avoid_bool_literals_in_conditional_expressions: 0.1.46 avoid_type_to_string : 0.1.119 avoid_types_on_closure_parameters: 0.1.31 avoid_as: 0.1.5 avoid_catching_errors: 0.1.31 avoid_catches_without_on_clauses: 0.1.31 avoid_classes_with_only_static_members: 0.1.31 avoid_double_and_int_checks: 0.1.47 avoid_empty_else: 0.1.8 avoid_equals_and_hash_code_on_mutable_classes : 0.1.97 avoid_escaping_inner_quotes: 0.1.111 avoid_field_initializers_in_const_classes: 0.1.48 avoid_function_literals_in_foreach_calls: 0.1.30 avoid_implementing_value_types: 0.1.62 avoid_init_to_null: 0.1.11 avoid_js_rounded_ints: 0.1.48 avoid_null_checks_in_equality_operators: 0.1.31 avoid_positional_boolean_parameters: 0.1.31 avoid_print: 0.1.93 avoid_private_typedef_functions: 0.1.46 avoid_redundant_argument_values : 0.1.107 avoid_relative_lib_imports: 0.1.44 avoid_renaming_method_parameters: 0.1.45 avoid_returning_null: 0.1.31 avoid_returning_null_for_future: 0.1.72 avoid_returning_null_for_void: 0.1.69 avoid_return_types_on_setters: 0.1.11 avoid_returning_this: 0.1.31 avoid_setters_without_getters: 0.1.31 avoid_shadowing_type_parameters: 0.1.72 avoid_single_cascade_in_expression_statements: 0.1.46 avoid_slow_async_io: 0.1.30 avoid_types_as_parameter_names: 0.1.45 avoid_unnecessary_containers : 0.1.102 avoid_unused_constructor_parameters: 0.1.36 always_use_package_imports : 0.1.118 avoid_void_async: 0.1.60 avoid_web_libraries_in_flutter : 0.1.101 await_only_futures: 0.1.16 camel_case_types: 0.1.1 camel_case_extensions: 0.1.97+1 cancel_subscriptions: 0.1.20 cascade_invocations: 0.1.29 cast_nullable_to_non_nullable : 0.1.120 close_sinks: 0.1.19 comment_references: 0.1.17 control_flow_in_finally: 0.1.16 constant_identifier_names: 0.1.1 curly_braces_in_flow_control_structures: 0.1.57 diagnostic_describe_all_properties: 0.1.85 directives_ordering: 0.1.30 do_not_use_environment : 0.1.117 empty_catches: 0.1.22 empty_constructor_bodies: 0.1.1 empty_statements: 0.1.21 exhaustive_cases : 0.1.116 file_names: 0.1.54 flutter_style_todos: 0.1.61 hash_and_equals: 0.1.11 implementation_imports: 0.1.4 invariant_booleans: 0.1.25 iterable_contains_unrelated_type: 0.1.17 join_return_with_assignment: 0.1.31 leading_newlines_in_multiline_strings : 0.1.113 library_names: 0.1.1 library_prefixes: 0.1.1 lines_longer_than_80_chars: 0.1.56 list_remove_unrelated_type: 0.1.22 literal_only_boolean_expressions: 0.1.25 missing_whitespace_between_adjacent_strings : 0.1.110 no_adjacent_strings_in_list: 0.1.30 no_default_cases : 0.1.116 no_duplicate_case_values: 0.1.30 no_logic_in_create_state : 0.1.106 non_constant_identifier_names: 0.1.1 no_runtimeType_toString : 0.1.110 null_check_on_nullable_type_parameter : 0.1.120 null_closures: 0.1.56 one_member_abstracts: 0.1.1 omit_local_variable_types: 0.1.30 only_throw_errors: 0.1.21 overridden_fields: 0.1.18 package_api_docs: 0.1.1 package_prefixed_library_names: 0.1.1 parameter_assignments: 0.1.27 prefer_adjacent_string_concatenation: 0.1.30 prefer_asserts_with_message: 0.1.84 prefer_bool_in_asserts: 0.1.36 prefer_collection_literals: 0.1.30 prefer_conditional_assignment: 0.1.31 prefer_const_constructors: 0.1.30 prefer_const_constructors_in_immutables: 0.1.33 prefer_const_declarations: 0.1.43 prefer_const_literals_to_create_immutables: 0.1.43 prefer_asserts_in_initializer_lists: 0.1.33 prefer_constructors_over_static_methods: 0.1.31 prefer_contains: 0.1.30 prefer_double_quotes: 0.1.88 prefer_equal_for_default_values: 0.1.46 prefer_expression_function_bodies: 0.1.30 prefer_final_fields: 0.1.27 prefer_final_in_for_each: 0.1.78 prefer_final_locals: 0.1.27 prefer_foreach: 0.1.31 prefer_for_elements_to_map_fromIterable: 0.1.85 prefer_function_declarations_over_variables: 0.1.30 prefer_generic_function_type_aliases: 0.1.47 prefer_if_elements_to_conditional_expressions: 0.1.85 prefer_if_null_operators: 0.1.89 prefer_initializing_formals: 0.1.30 prefer_inlined_adds: 0.1.86 prefer_int_literals: 0.1.71 prefer_interpolation_to_compose_strings: 0.1.30 prefer_iterable_whereType: 0.1.47 prefer_is_empty: 0.1.30 prefer_is_not_empty: 0.1.5 prefer_is_not_operator : 0.1.102 prefer_mixin: 0.1.62 prefer_null_aware_operators: 0.1.80 prefer_relative_imports : 0.1.99 prefer_single_quotes: 0.1.33 prefer_spread_collections: 0.1.85 prefer_typing_uninitialized_variables: 0.1.36 prefer_void_to_null: 0.1.59 provide_deprecation_message: 0.1.82 public_member_api_docs: 0.1.11 package_names: 0.1.31 recursive_getters: 0.1.30 sized_box_for_whitespace : 0.1.115 slash_for_doc_comments: 0.1.1 sort_child_properties_last: 0.1.88 sort_constructors_first: 0.1.11 sort_pub_dependencies: 0.1.63 sort_unnamed_constructors_first: 0.1.11 super_goes_last: 0.1.1 test_types_in_equals: 0.1.16 throw_in_finally: 0.1.16 tighten_type_of_initializing_formals : 0.1.120 type_annotate_public_apis: 0.1.5 type_init_formals: 0.1.1 unawaited_futures: 0.1.19 unnecessary_await_in_return: 0.1.73 unnecessary_brace_in_string_interps: 0.1.30 unnecessary_const: 0.1.54 unnecessary_final : 0.1.104 unnecessary_getters_setters: 0.1.1 unnecessary_lambdas: 0.1.30 unnecessary_new: 0.1.54 unnecessary_null_aware_assignments: 0.1.30 unnecessary_null_checks : 0.1.119 unnecessary_nullable_for_final_variable_declarations : 0.1.118 unnecessary_null_in_if_null_operators: 0.1.30 unnecessary_overrides: 0.1.31 unnecessary_parenthesis: 0.1.44 unnecessary_raw_strings : 0.1.111 unnecessary_statements: 0.1.36 unnecessary_string_escapes : 0.1.111 unnecessary_string_interpolations : 0.1.110 unnecessary_this: 0.1.30 unrelated_type_equality_checks: 0.1.16 unsafe_html : 0.1.90 use_full_hex_values_for_flutter_colors: 0.1.80 use_function_type_syntax_for_parameters: 0.1.72 use_is_even_rather_than_modulo : 0.1.116 use_key_in_widget_constructors : 0.1.108 use_late_for_private_fields_and_variables : 0.1.118 use_raw_strings : 0.1.111 use_rethrow_when_possible: 0.1.31 use_setters_to_change_properties: 0.1.31 use_string_buffers: 0.1.31 use_to_and_as_if_applicable: 0.1.31 valid_regexps: 0.1.22 void_checks: 0.1.49
linter/tool/since/linter.yaml/0
{'file_path': 'linter/tool/since/linter.yaml', 'repo_id': 'linter', 'token_count': 2740}
name: CI on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v1 - uses: actions/setup-java@v1 with: java-version: '12.x' - uses: subosito/flutter-action@v1 with: channel: 'stable' # or: 'dev' or 'beta' - run: flutter pub get - name : Building APK working-directory: ./example run: flutter build apk --debug
liquid_swipe_flutter/.github/workflows/main.yml/0
{'file_path': 'liquid_swipe_flutter/.github/workflows/main.yml', 'repo_id': 'liquid_swipe_flutter', 'token_count': 214}
import 'package:colorize_lumberdash/colorize_lumberdash.dart'; import 'package:lumberdash/lumberdash.dart'; void main() { putLumberdashToWork(withClients: [ColorizeLumberdash()]); logWarning('Hello Warning'); logFatal('Hello Fatal!'); logMessage('Hello Message!'); logError(Exception('Hello Error')); }
lumberdash/plugins/colorize_lumberdash/example/lib/example.dart/0
{'file_path': 'lumberdash/plugins/colorize_lumberdash/example/lib/example.dart', 'repo_id': 'lumberdash', 'token_count': 105}
import 'package:lumberdash/lumberdash.dart'; import 'package:firebase_analytics/firebase_analytics.dart'; import 'package:firebase_lumberdash/firebase_lumberdash.dart'; void main() { putLumberdashToWork(withClients: [ FirebaseLumberdash( firebaseAnalyticsClient: FirebaseAnalytics(), environment: 'development', releaseVersion: '1.0.0', ), ]); logWarning('Hello Warning'); logFatal('Hello Fatal!'); logMessage('Hello Message!'); logError(Exception('Hello Error')); }
lumberdash/plugins/firebase_lumberdash/example/lib/main.dart/0
{'file_path': 'lumberdash/plugins/firebase_lumberdash/example/lib/main.dart', 'repo_id': 'lumberdash', 'token_count': 181}
name: plugin description: An example plugin template version: 0.1.0+1 vars: android: type: boolean description: Whether to generate an Android project. default: false prompt: Do you want to generate an Android project? ios: type: boolean description: Whether to generate an iOS project. default: false prompt: Do you want to generate an iOS project?
mason/bricks/plugin/brick.yaml/0
{'file_path': 'mason/bricks/plugin/brick.yaml', 'repo_id': 'mason', 'token_count': 118}
import 'dart:convert'; import 'package:json_annotation/json_annotation.dart'; import 'package:meta/meta.dart'; part 'brick_yaml.g.dart'; /// {@template mason_yaml} /// Brick yaml file which contains metadata required to create /// a `MasonGenerator` from a brick template. /// {@endtemplate} @immutable @JsonSerializable() class BrickYaml { /// {@macro mason_yaml} const BrickYaml({ required this.name, required this.description, required this.version, this.publishTo, this.environment = const BrickEnvironment(), this.vars = const <String, BrickVariableProperties>{}, this.repository, this.path, }); /// Converts [Map] to [BrickYaml] factory BrickYaml.fromJson(Map<dynamic, dynamic> json) => _$BrickYamlFromJson(json); /// Converts [BrickYaml] to [Map] Map<dynamic, dynamic> toJson() => _$BrickYamlToJson(this); /// static constant for brick configuration file name. /// `brick.yaml` static const file = 'brick.yaml'; /// static constant for brick template directory name. /// `__brick__` static const dir = '__brick__'; /// static constant for brick hooks directory name. /// `hooks` static const hooks = 'hooks'; /// Name of the brick. final String name; /// Description of the brick. final String description; /// Version of the brick (semver). final String version; /// Environment of the brick. final BrickEnvironment environment; /// Optional url pointing to the brick's source code repository. final String? repository; /// Optional url used to specify a custom brick registry /// as the publish target. /// /// Can either be "none" or a custom brick registry url. /// Defaults to https://registry.brickhub.dev when not specified. @JsonKey(name: 'publish_to') final String? publishTo; /// Map of variable properties used when templating a brick. @VarsConverter() final Map<String, BrickVariableProperties> vars; /// Path to the [BrickYaml] file. final String? path; /// Returns a copy of the current [BrickYaml] with /// an overridden [path]. BrickYaml copyWith({String? path}) { return BrickYaml( name: name, description: description, version: version, vars: vars, environment: environment, repository: repository, path: path ?? this.path, publishTo: publishTo, ); } @override bool operator ==(Object other) { if (identical(this, other)) return true; return other is BrickYaml && other.name == name; } @override int get hashCode => name.hashCode; } /// The type of brick variable. enum BrickVariableType { /// An array (e.g. ["one", "two", "three"]). /// Values must be present in the list of /// available options. array, /// A number (e.g. 42) number, /// A string (e.g. "Dash") string, /// A boolean (e.g. true/false) boolean, /// An enumeration (e.g. ["red", "green", "blue"]) @JsonValue('enum') enumeration, /// A dynamic list of values. Unlike [BrickVariableType.array], /// [BrickVariableType.list] supports a dynamic list /// of values. list, } /// {@template brick_variable_properties} /// An object representing a brick variable. /// {@endtemplate} @immutable @JsonSerializable() class BrickVariableProperties { /// {@macro brick_variable_properties} @internal const BrickVariableProperties({ required this.type, this.description, this.defaultValue, this.defaultValues, this.prompt, this.values, this.separator, }); /// {@macro brick_variable_properties} /// /// Creates an instance of a [BrickVariableProperties] /// of type [BrickVariableType.string]. const BrickVariableProperties.string({ String? description, String? defaultValue, String? prompt, }) : this( type: BrickVariableType.string, description: description, defaultValue: defaultValue, prompt: prompt, ); /// {@macro brick_variable_properties} /// /// Creates an instance of a [BrickVariableProperties] /// of type [BrickVariableType.boolean]. const BrickVariableProperties.boolean({ String? description, bool? defaultValue, String? prompt, }) : this( type: BrickVariableType.boolean, description: description, defaultValue: defaultValue, prompt: prompt, ); /// {@macro brick_variable_properties} /// /// Creates an instance of a [BrickVariableProperties] /// of type [BrickVariableType.number]. const BrickVariableProperties.number({ String? description, num? defaultValue, String? prompt, }) : this( type: BrickVariableType.number, description: description, defaultValue: defaultValue, prompt: prompt, ); /// {@macro brick_variable_properties} /// /// Creates an instance of a [BrickVariableProperties] /// of type [BrickVariableType.enumeration]. const BrickVariableProperties.enumeration({ required List<String> values, String? description, String? defaultValue, String? prompt, }) : this( type: BrickVariableType.enumeration, description: description, defaultValue: defaultValue, prompt: prompt, values: values, ); /// {@macro brick_variable_properties} /// /// Creates an instance of a [BrickVariableProperties] /// of type [BrickVariableType.array]. const BrickVariableProperties.array({ required List<String> values, String? description, List<String>? defaultValues, String? prompt, }) : this( type: BrickVariableType.array, description: description, defaultValues: defaultValues, prompt: prompt, values: values, ); /// {@macro brick_variable_properties} /// /// Creates an instance of a [BrickVariableProperties] /// of type [BrickVariableType.list]. const BrickVariableProperties.list({ String? description, String? prompt, String? separator, }) : this( type: BrickVariableType.list, description: description, prompt: prompt, separator: separator, ); /// Converts [Map] to [BrickYaml] factory BrickVariableProperties.fromJson(Map<dynamic, dynamic> json) => _$BrickVariablePropertiesFromJson(json); /// Converts [BrickVariableProperties] to [Map] Map<dynamic, dynamic> toJson() => _$BrickVariablePropertiesToJson(this); /// The type of the variable. final BrickVariableType type; /// An optional description of the variable. final String? description; /// An optional default value for the variable. @JsonKey(name: 'default') final Object? defaultValue; /// Optional default values for the variable used /// when [type] is [BrickVariableType.array]. @JsonKey(name: 'defaults') final Object? defaultValues; /// An optional prompt used when requesting the variable. final String? prompt; /// An optional list of values used when [type] is: /// * [BrickVariableType.array] /// * [BrickVariableType.enumeration] final List<String>? values; /// An optional separator used when [type] is: /// * [BrickVariableType.list] final String? separator; } /// {@template vars_converter} /// Json Converter for [Map<String, BrickVariableProperties>]. /// {@endtemplate} class VarsConverter implements JsonConverter<Map<String, BrickVariableProperties>, dynamic> { /// {@macro vars_converter} const VarsConverter(); @override dynamic toJson(Map<String, BrickVariableProperties> value) { return value.map((key, value) => MapEntry(key, value.toJson())); } @override Map<String, BrickVariableProperties> fromJson(dynamic value) { final dynamic _value = value is String ? json.decode(value) : value; if (_value is List) { return <String, BrickVariableProperties>{ for (final v in _value) v as String: const BrickVariableProperties.string(), }; } if (_value is Map) { return _value.map( (dynamic key, dynamic value) => MapEntry( key as String, BrickVariableProperties.fromJson(_value[key] as Map), ), ); } throw const FormatException(); } } /// {@template brick_environment} /// An object representing the environment for a given brick. /// {@endtemplate} @immutable @JsonSerializable() class BrickEnvironment { /// {@macro brick_environment} const BrickEnvironment({this.mason = 'any'}); /// Converts [Map] to [BrickYaml] factory BrickEnvironment.fromJson(Map<dynamic, dynamic> json) => _$BrickEnvironmentFromJson(json); /// Converts [BrickEnvironment] to [Map] Map<dynamic, dynamic> toJson() => _$BrickEnvironmentToJson(this); /// Mason version constraint (semver). /// Defaults to 'any'. final String mason; }
mason/packages/mason/lib/src/brick_yaml.dart/0
{'file_path': 'mason/packages/mason/lib/src/brick_yaml.dart', 'repo_id': 'mason', 'token_count': 3072}
import 'dart:convert'; import 'package:mason/mason.dart'; import 'package:mustache_template/mustache_template.dart'; final _newlineInRegExp = RegExp(r'(\\\r\n|\\\r|\\\n)'); final _newlineOutRegExp = RegExp(r'(\r\n|\r|\n)'); final _unicodeInRegExp = RegExp(r'\\[^\x00-\x7F]'); final _unicodeOutRegExp = RegExp(r'[^\x00-\x7F]'); String _sanitizeInput(String input) { return input.replaceAllMapped( RegExp('${_newlineOutRegExp.pattern}|${_unicodeOutRegExp.pattern}'), (match) => match.group(0) != null ? '\\${match.group(0)}' : match.input, ); } String _sanitizeOutput(String output) { return output.replaceAllMapped( RegExp('${_newlineInRegExp.pattern}|${_unicodeInRegExp.pattern}'), (match) => match.group(0)?.substring(1) ?? match.input, ); } /// [Map] of all the built-in lambda functions. final _builtInLambdas = <String, LambdaFunction>{ /// camelCase 'camelCase': (ctx) => ctx.renderString().camelCase, /// CONSTANT_CASE 'constantCase': (ctx) => ctx.renderString().constantCase, /// dot.case 'dotCase': (ctx) => ctx.renderString().dotCase, /// Header-Case 'headerCase': (ctx) => ctx.renderString().headerCase, /// lower case 'lowerCase': (ctx) => ctx.renderString().lowerCase, /// {{ mustache case }} 'mustacheCase': (ctx) => ctx.renderString().mustacheCase, /// PascalCase 'pascalCase': (ctx) => ctx.renderString().pascalCase, /// Pascal.Dot.Case 'pascalDotCase': (ctx) => ctx.renderString().pascalDotCase, /// param-case 'paramCase': (ctx) => ctx.renderString().paramCase, /// path/case 'pathCase': (ctx) => ctx.renderString().pathCase, /// Sentence case 'sentenceCase': (ctx) => ctx.renderString().sentenceCase, /// snake_case 'snakeCase': (ctx) => ctx.renderString().snakeCase, /// Title Case 'titleCase': (ctx) => ctx.renderString().titleCase, /// UPPER CASE 'upperCase': (ctx) => ctx.renderString().upperCase, }; /// [Map] of all the built-in variables. const _builtInVars = <String, dynamic>{ '__LEFT_CURLY_BRACKET__': '{', '__RIGHT_CURLY_BRACKET__': '}', }; /// {@template render_template} /// Given a `String` with mustache templates, and a [Map] of String key / /// value pairs, substitute all instances of `{{key}}` for `value`. /// /// ``` /// Hello {{name}}! /// ``` /// /// and /// /// ``` /// {'name': 'Bob'} /// ``` /// /// becomes: /// /// ``` /// Hello Bob! /// ``` /// {@endtemplate} extension RenderTemplate on String { /// {@macro render_template} String render( Map<String, dynamic> vars, [ Map<String, List<int>>? partials = const {}, ]) { final template = Template( _sanitizeInput(transpiled()), lenient: true, partialResolver: (name) => partials?.resolve(name), ); return _sanitizeOutput( template.renderString(<String, dynamic>{ ...vars, ..._builtInLambdas, ..._builtInVars, }), ); } } extension on String { String transpiled() { final builtInLambdaNamesEscaped = _builtInLambdas.keys.map(RegExp.escape).join('|'); final lambdaPattern = RegExp('{?{{ *([^{}]*)\\.($builtInLambdaNamesEscaped)\\(\\) *}}}?'); var currentIteration = this; // Continue substituting until no match is found to account for chained // lambdas while (lambdaPattern.hasMatch(currentIteration)) { currentIteration = currentIteration.replaceAllMapped(lambdaPattern, (match) { final expression = match.group(0)!; final variable = match.group(1)!; final lambda = match.group(2)!; final startsWithTriple = expression.startsWith('{{{'); final endsWithTriple = expression.endsWith('}}}'); final isTriple = startsWithTriple && endsWithTriple; final output = isTriple ? '{{{$variable}}}' : '{{$variable}}'; if (startsWithTriple && !isTriple) { return '{{__LEFT_CURLY_BRACKET__}}{{#$lambda}}$output{{/$lambda}}'; } if (endsWithTriple && !isTriple) { return '{{#$lambda}}$output{{/$lambda}}{{__RIGHT_CURLY_BRACKET__}}'; } return '{{#$lambda}}$output{{/$lambda}}'; }); } return currentIteration; } } /// {@template resolve_partial} /// A resolver function which given a partial name. /// attempts to return a new [Template]. /// {@endtemplate} extension ResolvePartial on Map<String, List<int>> { /// {@macro resolve_partial} Template? resolve(String name) { final content = this['{{~ $name }}']; if (content == null) return null; final decoded = utf8.decode(content); final sanitized = _sanitizeInput(decoded.transpiled()); return Template(sanitized, name: name, lenient: true); } }
mason/packages/mason/lib/src/render.dart/0
{'file_path': 'mason/packages/mason/lib/src/render.dart', 'repo_id': 'mason', 'token_count': 1827}
import 'package:mason/mason.dart';void run(HookContext context){throw Exception();}
mason/packages/mason/test/fixtures/execution_exception/hooks/pre_gen.dart/0
{'file_path': 'mason/packages/mason/test/fixtures/execution_exception/hooks/pre_gen.dart', 'repo_id': 'mason', 'token_count': 25}
include: ../../analysis_options.yaml analyzer: errors: todo: ignore exclude: - "example/main.dart"
mason/packages/mason_api/analysis_options.yaml/0
{'file_path': 'mason/packages/mason_api/analysis_options.yaml', 'repo_id': 'mason', 'token_count': 45}
import 'dart:io'; import 'package:mason/mason.dart' hide packageVersion; import 'package:mason_cli/src/command.dart'; import 'package:mason_cli/src/command_runner.dart'; import 'package:mason_cli/src/version.dart'; import 'package:pub_updater/pub_updater.dart'; /// {@template update_command} /// `mason update` command which updates mason. /// {@endtemplate} class UpdateCommand extends MasonCommand { /// {@macro update_command} UpdateCommand({ required PubUpdater pubUpdater, super.logger, }) : _pubUpdater = pubUpdater; final PubUpdater _pubUpdater; @override final String description = 'Update mason.'; @override final String name = 'update'; @override Future<int> run() async { final updateCheckProgress = logger.progress('Checking for updates'); late final String latestVersion; try { latestVersion = await _pubUpdater.getLatestVersion(packageName); } catch (error) { updateCheckProgress.fail(); logger.err('$error'); return ExitCode.software.code; } updateCheckProgress.complete('Checked for updates'); final isUpToDate = packageVersion == latestVersion; if (isUpToDate) { logger.info('mason is already at the latest version.'); return ExitCode.success.code; } final progress = logger.progress('Updating to $latestVersion'); late final ProcessResult result; try { result = await _pubUpdater.update( packageName: packageName, versionConstraint: latestVersion, ); } catch (error) { progress.fail(); logger.err('$error'); return ExitCode.software.code; } if (result.exitCode != ExitCode.success.code) { progress.fail('Unable to update to $latestVersion'); logger.err('${result.stderr}'); return ExitCode.software.code; } progress.complete('Updated to $latestVersion'); return ExitCode.success.code; } }
mason/packages/mason_cli/lib/src/commands/update.dart/0
{'file_path': 'mason/packages/mason_cli/lib/src/commands/update.dart', 'repo_id': 'mason', 'token_count': 690}
import 'dart:io'; import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:mason/mason.dart' hide packageVersion; import 'package:mason_api/mason_api.dart'; import 'package:mason_cli/src/commands/commands.dart'; import 'package:mocktail/mocktail.dart'; import 'package:path/path.dart' as p; import 'package:test/test.dart'; import '../helpers/helpers.dart'; class _MockLogger extends Mock implements Logger {} class _MockMasonApi extends Mock implements MasonApi {} class _MockUser extends Mock implements User {} class _MockArgResults extends Mock implements ArgResults {} class _MockProgress extends Mock implements Progress {} class FakeUri extends Fake implements Uri {} void main() { final cwd = Directory.current; setUpAll(() { registerFallbackValue(FakeUri()); }); group('PublishCommand', () { final brickPath = p.join('..', '..', '..', '..', '..', 'bricks', 'greeting'); late Logger logger; late MasonApi masonApi; late ArgResults argResults; late PublishCommand publishCommand; setUp(() async { logger = _MockLogger(); masonApi = _MockMasonApi(); argResults = _MockArgResults(); publishCommand = PublishCommand( logger: logger, masonApiBuilder: ({Uri? hostedUri}) => masonApi, )..testArgResults = argResults; when(() => logger.progress(any())).thenReturn(_MockProgress()); setUpTestingEnvironment(cwd, suffix: '.publish'); }); tearDown(() { Directory.current = cwd; }); test('can be instantiated without any parameters', () { expect(PublishCommand.new, returnsNormally); }); test( 'throws usageException when ' 'called with both --force and --dry-run', () async { final runner = CommandRunner<int>('mason', '') ..addCommand(publishCommand..testArgResults = null); await expectLater( () => runner.run(['publish', '--dry-run', '--force']), throwsA( isA<UsageException>().having( (e) => e.message, 'message', 'Cannot use both --force and --dry-run.', ), ), ); }); test('exits with code 70 when brick could not be found', () async { final tempDir = Directory.systemTemp.createTempSync(); Directory.current = tempDir.path; final brickYamlPath = p.join(tempDir.path, BrickYaml.file); when(() => argResults['directory'] as String).thenReturn(tempDir.path); final result = await publishCommand.run(); expect(result, equals(ExitCode.software.code)); verify( () => logger.err('Could not find ${BrickYaml.file} at $brickYamlPath.'), ).called(1); verifyNever(() => masonApi.close()); }); test('exits with code 70 when it is a private brick', () async { final brickPath = p.join('..', '..', 'bricks', 'no_registry'); when(() => argResults['directory'] as String).thenReturn(brickPath); final result = await publishCommand.run(); expect(result, equals(ExitCode.software.code)); verify( () => logger.err('A private brick cannot be published.'), ).called(1); verify( () => logger.err(''' Please change or remove the "publish_to" field in the brick.yaml before publishing.'''), ).called(1); verifyNever(() => masonApi.close()); }); test('exits with code 70 when publish_to has an invalid value', () async { final brickPath = p.join('..', '..', 'bricks', 'invalid_registry'); when(() => argResults['directory'] as String).thenReturn(brickPath); final result = await publishCommand.run(); verify( () => logger.err( 'Invalid "publish_to" in brick.yaml: "invalid registry"', ), ).called(1); verify( () => logger.err( '"publish_to" must be a valid registry url such as ' '"https://registry.brickhub.dev" or "none" for private bricks.', ), ).called(1); verifyNever(() => masonApi.close()); expect(result, equals(ExitCode.software.code)); }); test('exits with code 70 when not logged in', () async { when(() => argResults['directory'] as String).thenReturn(brickPath); final result = await publishCommand.run(); expect(result, equals(ExitCode.software.code)); verify(() => logger.err('You must be logged in to publish.')).called(1); verify( () => logger.err("Run 'mason login' to log in and try again."), ).called(1); verify(() => masonApi.close()).called(1); }); test('exits with code 70 when email is not verified', () async { final user = _MockUser(); when(() => user.emailVerified).thenReturn(false); when(() => masonApi.currentUser).thenReturn(user); when(() => argResults['directory'] as String).thenReturn(brickPath); final result = await publishCommand.run(); expect(result, equals(ExitCode.software.code)); verify( () => logger.err('You must verify your email in order to publish.'), ).called(1); verify(() => masonApi.close()).called(1); }); test('exits with code 70 when bundle is too large', () async { final user = _MockUser(); when(() => user.emailVerified).thenReturn(true); when(() => masonApi.currentUser).thenReturn(user); when(() => argResults['directory'] as String).thenReturn(brickPath); final publishCommand = PublishCommand( masonApiBuilder: ({Uri? hostedUri}) => masonApi, logger: logger, maxBundleSize: 100, )..testArgResults = argResults; final result = await publishCommand.run(); expect(result, equals(ExitCode.software.code)); verify(() => logger.progress('Bundling greeting')).called(1); verify( () => logger.err( any( that: contains('Hosted bricks must be smaller than 0.000095 MB.'), ), ), ).called(1); verify(() => masonApi.close()).called(1); }); test('exits with code 0 without publishing when using --dry-run', () async { final user = _MockUser(); final progressLogs = <String>[]; when(() => user.emailVerified).thenReturn(true); when(() => masonApi.currentUser).thenReturn(user); when( () => masonApi.publish(bundle: any(named: 'bundle')), ).thenAnswer((_) async {}); final progress = _MockProgress(); when(() => progress.complete(any())).thenAnswer((invocation) { final update = invocation.positionalArguments[0] as String?; if (update != null) progressLogs.add(update); }); when(() => logger.progress(any())).thenReturn(progress); when(() => logger.confirm(any())).thenReturn(true); when(() => argResults['directory'] as String).thenReturn(brickPath); when(() => argResults['dry-run'] as bool).thenReturn(true); final result = await publishCommand.run(); expect(result, equals(ExitCode.success.code)); expect(progressLogs, equals(['Bundled greeting'])); verify(() => logger.info('No issues detected.')).called(1); verify( () => logger.info('The server may enforce additional checks.'), ).called(1); verifyNever(() => logger.progress('Publishing greeting 0.1.0+1')); verifyNever(() { logger.success( '''\nPublished greeting 0.1.0+1 to ${BricksJson.hostedUri}.''', ); }); verifyNever(() => masonApi.publish(bundle: any(named: 'bundle'))); verify(() => masonApi.close()).called(1); }); test('exits with code 70 when publish is aborted', () async { final policyLink = styleUnderlined.wrap( link(uri: Uri.parse('https://brickhub.dev/policy')), ); final user = _MockUser(); when(() => user.emailVerified).thenReturn(true); when(() => masonApi.currentUser).thenReturn(user); when(() => logger.confirm(any())).thenReturn(false); when(() => argResults['directory'] as String).thenReturn(brickPath); final result = await publishCommand.run(); expect(result, equals(ExitCode.software.code)); verify(() => logger.progress('Bundling greeting')).called(1); verify(() { logger.info( lightCyan.wrap( styleBold.wrap( '\nPublishing is forever; bricks cannot be unpublished.', ), ), ); }).called(1); verify(() { logger.info('See policy details at $policyLink\n'); }).called(1); verify( () => logger.confirm('Do you want to publish greeting 0.1.0+1?'), ).called(1); verify(() => logger.err('Brick was not published.')).called(1); verifyNever(() => logger.progress('Publishing greeting 0.1.0+1')); verifyNever(() => masonApi.publish(bundle: any(named: 'bundle'))); verify(() => masonApi.close()).called(1); }); test('exits with code 70 when publish fails', () async { final user = _MockUser(); const message = 'oops'; const exception = MasonApiPublishFailure(message: message); when(() => user.emailVerified).thenReturn(true); when(() => masonApi.currentUser).thenReturn(user); when( () => masonApi.publish(bundle: any(named: 'bundle')), ).thenThrow(exception); when(() => logger.confirm(any())).thenReturn(true); when(() => argResults['directory'] as String).thenReturn(brickPath); final result = await publishCommand.run(); expect(result, equals(ExitCode.software.code)); verify(() => logger.progress('Publishing greeting 0.1.0+1')).called(1); verify(() => masonApi.publish(bundle: any(named: 'bundle'))).called(1); verify(() => masonApi.close()).called(1); verify(() => logger.err('$exception')).called(1); }); test('exits with code 70 when publish fails (generic)', () async { final exception = Exception('oops'); final user = _MockUser(); when(() => user.emailVerified).thenReturn(true); when(() => masonApi.currentUser).thenReturn(user); when( () => masonApi.publish(bundle: any(named: 'bundle')), ).thenThrow(exception); when(() => logger.confirm(any())).thenReturn(true); when(() => argResults['directory'] as String).thenReturn(brickPath); await expectLater(publishCommand.run, throwsA(exception)); verify(() => logger.progress('Publishing greeting 0.1.0+1')).called(1); verify(() => masonApi.publish(bundle: any(named: 'bundle'))).called(1); verify(() => masonApi.close()).called(1); }); test('exits with code 0 when publish succeeds', () async { final user = _MockUser(); final progressLogs = <String>[]; when(() => user.emailVerified).thenReturn(true); when(() => masonApi.currentUser).thenReturn(user); when( () => masonApi.publish(bundle: any(named: 'bundle')), ).thenAnswer((_) async {}); final progress = _MockProgress(); when(() => progress.complete(any())).thenAnswer((invocation) { final update = invocation.positionalArguments[0] as String?; if (update != null) progressLogs.add(update); }); when(() => logger.progress(any())).thenReturn(progress); when(() => logger.confirm(any())).thenReturn(true); when(() => argResults['directory'] as String).thenReturn(brickPath); final result = await publishCommand.run(); expect(result, equals(ExitCode.success.code)); expect( progressLogs, equals(['Bundled greeting', 'Published greeting 0.1.0+1']), ); verify(() => logger.progress('Publishing greeting 0.1.0+1')).called(1); verify(() { logger.success( '''\nPublished greeting 0.1.0+1 to ${BricksJson.hostedUri}.''', ); }).called(1); verify(() => masonApi.publish(bundle: any(named: 'bundle'))).called(1); verify(() => masonApi.close()).called(1); }); test('exits with code 0 when publish succeeds with --force', () async { final user = _MockUser(); final progressLogs = <String>[]; when(() => user.emailVerified).thenReturn(true); when(() => masonApi.currentUser).thenReturn(user); when( () => masonApi.publish(bundle: any(named: 'bundle')), ).thenAnswer((_) async {}); final progress = _MockProgress(); when(() => progress.complete(any())).thenAnswer((invocation) { final update = invocation.positionalArguments[0] as String?; if (update != null) progressLogs.add(update); }); when(() => logger.progress(any())).thenReturn(progress); when(() => argResults['directory'] as String).thenReturn(brickPath); when(() => argResults['force'] as bool).thenReturn(true); final result = await publishCommand.run(); expect(result, equals(ExitCode.success.code)); expect( progressLogs, equals(['Bundled greeting', 'Published greeting 0.1.0+1']), ); verify(() => logger.progress('Publishing greeting 0.1.0+1')).called(1); verify(() { logger.success( '''\nPublished greeting 0.1.0+1 to ${BricksJson.hostedUri}.''', ); }).called(1); verifyNever(() => logger.confirm(any())); verify(() => masonApi.publish(bundle: any(named: 'bundle'))).called(1); verify(() => masonApi.close()).called(1); }); test( 'exits with code 0 when publish succeeds ' 'with a custom registry (publish_to)', () async { final brickPath = p.join('..', '..', 'bricks', 'custom_registry'); final customHostedUri = Uri.parse('https://custom.brickhub.dev'); final user = _MockUser(); final progressLogs = <String>[]; when(() => user.emailVerified).thenReturn(true); Uri? publishTo; final publishCommand = PublishCommand( masonApiBuilder: ({Uri? hostedUri}) { publishTo = hostedUri; return masonApi; }, logger: logger, )..testArgResults = argResults; when(() => masonApi.currentUser).thenReturn(user); when( () => masonApi.publish(bundle: any(named: 'bundle')), ).thenAnswer((_) async {}); final progress = _MockProgress(); when(() => progress.complete(any())).thenAnswer((invocation) { final update = invocation.positionalArguments[0] as String?; if (update != null) progressLogs.add(update); }); when(() => logger.progress(any())).thenReturn(progress); when(() => logger.confirm(any())).thenReturn(true); when(() => argResults['directory'] as String).thenReturn(brickPath); final result = await publishCommand.run(); expect(result, equals(ExitCode.success.code)); expect( progressLogs, equals([ 'Bundled custom_registry', 'Published custom_registry 0.1.0+1', ]), ); expect(publishTo, equals(customHostedUri)); verify( () => logger.progress('Publishing custom_registry 0.1.0+1'), ).called(1); verify( () => logger.success( '''\nPublished custom_registry 0.1.0+1 to $customHostedUri.''', ), ).called(1); verify( () => masonApi.publish(bundle: any(named: 'bundle')), ).called(1); verify(() => masonApi.close()).called(1); }, ); }); }
mason/packages/mason_cli/test/commands/publish_test.dart/0
{'file_path': 'mason/packages/mason_cli/test/commands/publish_test.dart', 'repo_id': 'mason', 'token_count': 6321}
void main() { print('Android'); }
mason/packages/mason_cli/test/fixtures/make/plugin/ios/example/ios.dart/0
{'file_path': 'mason/packages/mason_cli/test/fixtures/make/plugin/ios/example/ios.dart', 'repo_id': 'mason', 'token_count': 13}
import 'package:mason/mason.dart'; void run(HookContext context) { // TODO: add pre-generation logic. }
mason/packages/mason_cli/test/fixtures/new/hooks/hooks/pre_gen.dart/0
{'file_path': 'mason/packages/mason_cli/test/fixtures/new/hooks/hooks/pre_gen.dart', 'repo_id': 'mason', 'token_count': 39}
// ignore_for_file: prefer_const_constructors import 'package:mason/mason.dart'; import 'package:mason_cli/src/install_brick.dart'; import 'package:test/test.dart'; void main() { group('resolveBrickLocation', () { test('returns original location when locked location is null', () { final location = BrickLocation(); expect( resolveBrickLocation(location: location, lockedLocation: null), equals(location), ); }); test('returns original location when using a local path', () { final location = BrickLocation(path: '.'); final lockedLocation = BrickLocation(); expect( resolveBrickLocation( location: location, lockedLocation: lockedLocation, ), equals(location), ); }); test('returns original location when locked location is null (git)', () { final location = BrickLocation( git: GitPath('https://github.com/felangel/mason'), ); final lockedLocation = BrickLocation(); expect( resolveBrickLocation( location: location, lockedLocation: lockedLocation, ), equals(location), ); }); test('returns original location when locked location is not similar (git)', () { final location = BrickLocation( git: GitPath( 'https://github.com/felangel/mason', path: 'bricks/hello', ), ); final lockedLocation = BrickLocation( git: GitPath( 'https://github.com/felangel/mason', path: 'bricks/widget', ), ); expect( resolveBrickLocation( location: location, lockedLocation: lockedLocation, ), equals(location), ); }); test('returns locked location when locations are similar (git)', () { final location = BrickLocation( git: GitPath( 'https://github.com/felangel/mason', path: 'bricks/hello', ), ); final lockedLocation = BrickLocation( git: GitPath( 'https://github.com/felangel/mason', path: 'bricks/hello', ref: 'test-ref', ), ); expect( resolveBrickLocation( location: location, lockedLocation: lockedLocation, ), equals(lockedLocation), ); }); test('returns original location when locked location is null (version)', () { final location = BrickLocation(version: '1.0.0'); final lockedLocation = BrickLocation(); expect( resolveBrickLocation( location: location, lockedLocation: lockedLocation, ), equals(location), ); }); test('returns original location when locked version is incompatible', () { final location = BrickLocation(version: '^1.0.0'); final lockedLocation = BrickLocation(version: '0.1.2'); expect( resolveBrickLocation( location: location, lockedLocation: lockedLocation, ), equals(location), ); }); test('returns locked location when locked version is compatible', () { final location = BrickLocation(version: '^1.0.0'); final lockedLocation = BrickLocation(version: '1.1.2'); expect( resolveBrickLocation( location: location, lockedLocation: lockedLocation, ), equals(lockedLocation), ); }); }); }
mason/packages/mason_cli/test/src/install_brick_test.dart/0
{'file_path': 'mason/packages/mason_cli/test/src/install_brick_test.dart', 'repo_id': 'mason', 'token_count': 1473}
import 'dart:async'; import 'dart:convert'; import 'dart:io' as io; import 'package:mason_logger/mason_logger.dart'; import 'package:mason_logger/src/ffi/terminal.dart'; import 'package:mason_logger/src/io.dart'; import 'package:mason_logger/src/terminal_overrides.dart'; part 'progress.dart'; /// Type definition for a function which accepts a log message /// and returns a styled version of that message. /// /// Generally, [AnsiCode] values are used to generate a [LogStyle]. /// /// ```dart /// final alertStyle = (m) => backgroundRed.wrap(styleBold.wrap(white.wrap(m))); /// ``` typedef LogStyle = String? Function(String? message); String? _detailStyle(String? m) => darkGray.wrap(m); String? _infoStyle(String? m) => m; String? _errStyle(String? m) => lightRed.wrap(m); String? _warnStyle(String? m) => yellow.wrap(styleBold.wrap(m)); String? _alertStyle(String? m) => backgroundRed.wrap(styleBold.wrap(white.wrap(m))); String? _successStyle(String? m) => lightGreen.wrap(m); /// {@template log_theme} /// A theme object which contains styles for all log message types. /// {@endtemplate} class LogTheme { /// {@macro log_theme} const LogTheme({ LogStyle? detail, LogStyle? info, LogStyle? err, LogStyle? warn, LogStyle? alert, LogStyle? success, }) : detail = detail ?? _detailStyle, info = info ?? _infoStyle, err = err ?? _errStyle, warn = warn ?? _warnStyle, alert = alert ?? _alertStyle, success = success ?? _successStyle; /// The [LogStyle] used by [detail]. final LogStyle detail; /// The [LogStyle] used by [info]. final LogStyle info; /// The [LogStyle] used by [err]. final LogStyle err; /// The [LogStyle] used by [warn]. final LogStyle warn; /// The [LogStyle] used by [alert]. final LogStyle alert; /// The [LogStyle] used by [success]. final LogStyle success; } /// {@template logger} /// A basic Logger which wraps `stdio` and applies various styles. /// {@endtemplate} class Logger { /// {@macro logger} Logger({ this.theme = const LogTheme(), this.level = Level.info, this.progressOptions = const ProgressOptions(), }); /// The current theme for this logger. final LogTheme theme; /// The current log level for this logger. Level level; /// The progress options for the logger instance. ProgressOptions progressOptions; final _queue = <String?>[]; final io.IOOverrides? _overrides = io.IOOverrides.current; io.Stdout get _stdout => _overrides?.stdout ?? io.stdout; io.Stdin get _stdin => _overrides?.stdin ?? io.stdin; io.Stdout get _stderr => _overrides?.stderr ?? io.stderr; Never _exit(int code) => (TerminalOverrides.current?.exit ?? io.exit)(code); final _terminal = TerminalOverrides.current?.createTerminal() ?? Terminal(); KeyStroke Function() get _readKey { return () { _terminal.enableRawMode(); final key = TerminalOverrides.current?.readKey() ?? readKey(); _terminal.disableRawMode(); if (key.controlChar == ControlCharacter.ctrlC) _exit(130); return key; }; } /// Flushes internal message queue. void flush([void Function(String?)? print]) { final writeln = print ?? info; for (final message in _queue) { writeln(message); } _queue.clear(); } /// Write message via `stdout.write`. void write(String? message) => _stdout.write(message); /// Writes info message to stdout. void info(String? message, {LogStyle? style}) { if (level.index > Level.info.index) return; style ??= theme.info; _stdout.writeln(style.call(message) ?? message); } /// Writes delayed message to stdout. void delayed(String? message) => _queue.add(message); /// Writes progress message to stdout. /// Optionally provide [options] to override the current /// [ProgressOptions] for the generated [Progress]. Progress progress(String message, {ProgressOptions? options}) { return Progress._( message, _stdout, level, options: options ?? progressOptions, ); } /// Writes error message to stderr. void err(String? message, {LogStyle? style}) { if (level.index > Level.error.index) return; style ??= theme.err; _stderr.writeln(style(message)); } /// Writes alert message to stdout. void alert(String? message, {LogStyle? style}) { if (level.index > Level.critical.index) return; style ??= theme.alert; _stderr.writeln(style(message)); } /// Writes detail message to stdout. void detail(String? message, {LogStyle? style}) { if (level.index > Level.debug.index) return; style ??= theme.detail; _stdout.writeln(style(message)); } /// Writes warning message to stderr. void warn(String? message, {String tag = 'WARN', LogStyle? style}) { if (level.index > Level.warning.index) return; final output = tag.isEmpty ? '$message' : '[$tag] $message'; style ??= theme.warn; _stderr.writeln(style(output)); } /// Writes success message to stdout. void success(String? message, {LogStyle? style}) { if (level.index > Level.info.index) return; style ??= theme.success; _stdout.writeln(style(message)); } /// Prompts user and returns response. /// Provide a default value via [defaultValue]. /// Set [hidden] to `true` if you want to hide user input for sensitive info. String prompt(String? message, {Object? defaultValue, bool hidden = false}) { final hasDefault = defaultValue != null && '$defaultValue'.isNotEmpty; final resolvedDefaultValue = hasDefault ? '$defaultValue' : ''; final suffix = hasDefault ? ' ${darkGray.wrap('($resolvedDefaultValue)')}' : ''; final resolvedMessage = '$message$suffix '; _stdout.write(resolvedMessage); final input = hidden ? _readLineHiddenSync() : _stdin.readLineSync()?.trim(); final response = input == null || input.isEmpty ? resolvedDefaultValue : input; final lines = resolvedMessage.split('\n').length - 1; final prefix = lines > 1 ? '\x1b[A\u001B[2K\u001B[${lines}A' : '\x1b[A\u001B[2K'; _stdout.writeln( '''$prefix$resolvedMessage${styleDim.wrap(lightCyan.wrap(hidden ? '******' : response))}''', ); return response; } /// Prompts user for a free-form list of responses. List<String> promptAny(String? message, {String separator = ','}) { _stdin ..echoMode = false ..lineMode = false; final delimeter = '$separator '; var rawString = ''; _stdout.write('$message '); while (true) { final key = _readKey(); final isEnterOrReturnKey = key.controlChar == ControlCharacter.ctrlJ || key.controlChar == ControlCharacter.ctrlM; final isDeleteOrBackspaceKey = key.controlChar == ControlCharacter.delete || key.controlChar == ControlCharacter.backspace || key.controlChar == ControlCharacter.ctrlH; if (isEnterOrReturnKey) break; if (isDeleteOrBackspaceKey) { if (rawString.isNotEmpty) { if (rawString.endsWith(delimeter)) { _stdout.write('\b\b\x1b[K'); rawString = rawString.substring(0, rawString.length - 2); } else { _stdout.write('\b\x1b[K'); rawString = rawString.substring(0, rawString.length - 1); } } continue; } if (key.char == separator) { _stdout.write(delimeter); rawString += delimeter; } else { _stdout.write(key.char); rawString += key.char; } } if (rawString.endsWith(delimeter)) { rawString = rawString.substring(0, rawString.length - 2); } final results = rawString.isEmpty ? <String>[] : rawString.split(delimeter); const clearLine = '\u001b[2K\r'; _stdout.write( '$clearLine$message ${styleDim.wrap(lightCyan.wrap('$results'))}\n', ); _stdin ..lineMode = true ..echoMode = true; return results; } /// Prompts user with a yes/no question. bool confirm(String? message, {bool defaultValue = false}) { final suffix = ' ${darkGray.wrap('(${defaultValue.toYesNo()})')}'; final resolvedMessage = '$message$suffix '; _stdout.write(resolvedMessage); String? input; try { input = _stdin.readLineSync()?.trim(); } on FormatException catch (_) { // FormatExceptions can occur due to utf8 decoding errors // so we treat them as the user pressing enter (e.g. use `defaultValue`). _stdout.writeln(); } final response = input == null || input.isEmpty ? defaultValue : input.toBoolean() ?? defaultValue; final lines = resolvedMessage.split('\n').length - 1; final prefix = lines > 1 ? '\x1b[A\u001B[2K\u001B[${lines}A' : '\x1b[A\u001B[2K'; _stdout.writeln( '''$prefix$resolvedMessage${styleDim.wrap(lightCyan.wrap(response ? 'Yes' : 'No'))}''', ); return response; } /// Prompts user with [message] to choose one value from the provided /// [choices]. /// /// An optional [defaultValue] can be specified. /// The [defaultValue] must be one of the provided [choices]. T chooseOne<T extends Object?>( String? message, { required List<T> choices, T? defaultValue, String Function(T choice)? display, }) { final resolvedDisplay = display ?? (value) => '$value'; final hasDefault = defaultValue != null && resolvedDisplay(defaultValue).isNotEmpty; var index = hasDefault ? choices.indexOf(defaultValue) : 0; void writeChoices() { _stdout // save cursor ..write('\x1b7') // hide cursor ..write('\x1b[?25l') ..writeln('$message'); for (final choice in choices) { final isCurrent = choices.indexOf(choice) == index; final checkBox = isCurrent ? lightCyan.wrap('◉') : '◯'; if (isCurrent) { _stdout ..write(green.wrap('❯')) ..write(' $checkBox ${lightCyan.wrap(resolvedDisplay(choice))}'); } else { _stdout ..write(' ') ..write(' $checkBox ${resolvedDisplay(choice)}'); } if (choices.last != choice) { _stdout.write('\n'); } } } _stdin ..echoMode = false ..lineMode = false; writeChoices(); T? result; while (result == null) { final key = _readKey(); final isArrowUpOrKKey = key.controlChar == ControlCharacter.arrowUp || key.char == 'k'; final isArrowDownOrJKey = key.controlChar == ControlCharacter.arrowDown || key.char == 'j'; final isReturnOrEnterOrSpaceKey = key.controlChar == ControlCharacter.ctrlJ || key.controlChar == ControlCharacter.ctrlM || key.char == ' '; if (isArrowUpOrKKey) { index = (index - 1) % (choices.length); } else if (isArrowDownOrJKey) { index = (index + 1) % (choices.length); } else if (isReturnOrEnterOrSpaceKey) { _stdin ..lineMode = true ..echoMode = true; _stdout // restore cursor ..write('\x1b8') // clear to end of screen ..write('\x1b[J') // show cursor ..write('\x1b[?25h') ..write('$message ') ..writeln( styleDim.wrap(lightCyan.wrap(resolvedDisplay(choices[index]))), ); result = choices[index]; break; } // restore cursor _stdout.write('\x1b8'); writeChoices(); } return result!; } /// Prompts user with [message] to choose zero or more values /// from the provided [choices]. /// /// An optional list of [defaultValues] can be specified. /// The [defaultValues] must be one of the provided [choices]. List<T> chooseAny<T extends Object?>( String? message, { required List<T> choices, List<T>? defaultValues, String Function(T choice)? display, }) { final resolvedDisplay = display ?? (value) => '$value'; final hasDefaults = defaultValues != null && defaultValues.isNotEmpty; final selections = hasDefaults ? defaultValues.map((value) => choices.indexOf(value)).toSet() : <int>{}; var index = 0; void writeChoices() { _stdout // save cursor ..write('\x1b7') // hide cursor ..write('\x1b[?25l') ..writeln('$message'); for (final choice in choices) { final choiceIndex = choices.indexOf(choice); final isCurrent = choiceIndex == index; final isSelected = selections.contains(choiceIndex); final checkBox = isSelected ? lightCyan.wrap('◉') : '◯'; if (isCurrent) { _stdout ..write(green.wrap('❯')) ..write(' $checkBox ${lightCyan.wrap(resolvedDisplay(choice))}'); } else { _stdout ..write(' ') ..write(' $checkBox ${resolvedDisplay(choice)}'); } if (choices.last != choice) { _stdout.write('\n'); } } } _stdin ..echoMode = false ..lineMode = false; writeChoices(); List<T>? results; while (results == null) { final key = _readKey(); final keyIsUpOrKKey = key.controlChar == ControlCharacter.arrowUp || key.char == 'k'; final keyIsDownOrJKey = key.controlChar == ControlCharacter.arrowDown || key.char == 'j'; final keyIsSpaceKey = key.char == ' '; final keyIsEnterOrReturnKey = key.controlChar == ControlCharacter.ctrlJ || key.controlChar == ControlCharacter.ctrlM; if (keyIsUpOrKKey) { index = (index - 1) % (choices.length); } else if (keyIsDownOrJKey) { index = (index + 1) % (choices.length); } else if (keyIsSpaceKey) { selections.contains(index) ? selections.remove(index) : selections.add(index); } else if (keyIsEnterOrReturnKey) { _stdin ..lineMode = true ..echoMode = true; results = selections.map((index) => choices[index]).toList(); _stdout // restore cursor ..write('\x1b8') // clear to end of screen ..write('\x1b[J') // show cursor ..write('\x1b[?25h') ..write('$message ') ..writeln( styleDim.wrap( lightCyan.wrap('${results.map(resolvedDisplay).toList()}'), ), ); break; } // restore cursor _stdout.write('\x1b8'); writeChoices(); } return results; } String _readLineHiddenSync() { const lineFeed = 10; const carriageReturn = 13; const delete = 127; final value = <int>[]; try { _stdin ..echoMode = false ..lineMode = false; int char; do { char = _stdin.readByteSync(); if (char != lineFeed && char != carriageReturn) { final shouldDelete = char == delete && value.isNotEmpty; shouldDelete ? value.removeLast() : value.add(char); } } while (char != lineFeed && char != carriageReturn); } finally { _stdin ..lineMode = true ..echoMode = true; } _stdout.writeln(); return utf8.decode(value); } } extension on bool { String toYesNo() { return this == true ? 'Y/n' : 'y/N'; } } extension on String { bool? toBoolean() { switch (toLowerCase()) { case 'y': case 'yea': case 'yeah': case 'yep': case 'yes': case 'yup': return true; case 'n': case 'no': case 'nope': return false; default: return null; } } }
mason/packages/mason_logger/lib/src/mason_logger.dart/0
{'file_path': 'mason/packages/mason_logger/lib/src/mason_logger.dart', 'repo_id': 'mason', 'token_count': 6466}
import 'dart:io'; import 'package:mason/mason.dart'; /** * Deletes all .gitkeep files inside of generated folder */ Future<void> run(HookContext context) async { final filesRemoved = context.logger.progress('All files removed!'); var dir = Directory('.'); removeFiles(dir).listen((event) { context.logger.info(event); }, onDone: () => filesRemoved()); } Stream<String> removeFiles(Directory dir) async* { var entities = await dir.list(recursive: true); await for (FileSystemEntity entity in entities) { if (entity.toString().contains('.gitkeep')) { await entity.delete(); yield '.gitkeep file removed'; } } }
mason_bricks/bricks/clean_starter/hooks/post_gen.dart/0
{'file_path': 'mason_bricks/bricks/clean_starter/hooks/post_gen.dart', 'repo_id': 'mason_bricks', 'token_count': 218}
import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:meetup/one-feature-one-widget/good-mock.dart'; // main class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return Configurations( child: MaterialApp(/* ... */), ); } } // somewhere class Usage extends StatelessWidget { Widget build(BuildContext context) { // automatic reload on configurations change return Text(Configurations.of(context).foo); } } void main() { testWidgets('Foo', (tester) async { await tester.pumpWidget( Configurations.mock( configurations: ConfigurationData(foo: "42"), child: MaterialApp(home: Usage()), ), ); expect(find.text('42'), findsOneWidget); }); }
meetup-18-10-18/lib/one-feature-one-widget/good-usage_test.dart/0
{'file_path': 'meetup-18-10-18/lib/one-feature-one-widget/good-usage_test.dart', 'repo_id': 'meetup-18-10-18', 'token_count': 288}
name: mfsao description: My Flutter-specific analysis options version: 3.0.0 homepage: https://www.github.com/jogboms/mfsao environment: sdk: ">=2.17.3 <3.0.0" flutter: ">=3.0.0" dependencies: flutter_lints: ^2.0.1
mfsao/pubspec.yaml/0
{'file_path': 'mfsao/pubspec.yaml', 'repo_id': 'mfsao', 'token_count': 101}
export 'mini_sprite_component.dart';
mini_sprite/packages/flame_mini_sprite/lib/src/components/components.dart/0
{'file_path': 'mini_sprite/packages/flame_mini_sprite/lib/src/components/components.dart', 'repo_id': 'mini_sprite', 'token_count': 13}
include: package:very_good_analysis/analysis_options.3.0.1.yaml
mini_sprite/packages/flutter_mini_sprite/analysis_options.yaml/0
{'file_path': 'mini_sprite/packages/flutter_mini_sprite/analysis_options.yaml', 'repo_id': 'mini_sprite', 'token_count': 23}
name: flutter_mini_sprite description: Provides Widgets to render mini sprites into Flutter homepage: https://github.com/bluefireteam/mini_sprite version: 0.0.1+1 environment: sdk: ">=2.17.0 <3.0.0" dependencies: flutter: sdk: flutter mini_sprite: ^0.1.0 dev_dependencies: flutter_test: sdk: flutter very_good_analysis: ^3.0.1
mini_sprite/packages/flutter_mini_sprite/pubspec.yaml/0
{'file_path': 'mini_sprite/packages/flutter_mini_sprite/pubspec.yaml', 'repo_id': 'mini_sprite', 'token_count': 143}
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_colorpicker/flutter_colorpicker.dart'; import 'package:mini_sprite_editor/config/config.dart'; import 'package:mini_sprite_editor/l10n/l10n.dart'; class ConfigDialog extends StatefulWidget { const ConfigDialog({super.key}); static Future<Offset?> show(BuildContext context) { return showDialog<Offset?>( context: context, builder: (_) { return BlocProvider<ConfigCubit>.value( value: context.read<ConfigCubit>(), child: const ConfigDialog(), ); }, ); } @override State<ConfigDialog> createState() => _ConfigDialogState(); } class _ConfigDialogState extends State<ConfigDialog> { late final TextEditingController _gridFieldController; @override void initState() { super.initState(); _gridFieldController = TextEditingController() ..text = context.read<ConfigCubit>().state.mapGridSize.toString(); } Future<Color?> _showColorPicker(Color color) { Color? _color = color; return showDialog<Color?>( context: context, builder: (context) => AlertDialog( title: Text(context.l10n.chooseColor), content: SingleChildScrollView( child: ColorPicker( pickerColor: color, onColorChanged: (color) => _color = color, ), ), actions: <Widget>[ ElevatedButton( child: Text(context.l10n.confirm), onPressed: () { Navigator.of(context).pop(_color); }, ), ], ), ); } @override Widget build(BuildContext context) { final l10n = context.l10n; final cubit = context.watch<ConfigCubit>(); final state = cubit.state; return Dialog( child: SizedBox( width: 650, height: 450, child: Column( children: [ const SizedBox(height: 32), Text( l10n.configurations, style: Theme.of(context).textTheme.headlineMedium, ), const SizedBox(height: 32), Expanded( child: Row( children: [ Expanded( child: Column( children: [ Text( l10n.themeSettings, style: Theme.of(context).textTheme.titleLarge, ), ListTile( title: Text(l10n.system), leading: Radio<ThemeMode>( key: const Key('radio_system'), value: ThemeMode.system, groupValue: state.themeMode, onChanged: (ThemeMode? value) { if (value != null) { cubit.setThemeMode(value); } }, ), ), ListTile( title: Text(l10n.dark), leading: Radio<ThemeMode>( key: const Key('radio_dark'), value: ThemeMode.dark, groupValue: state.themeMode, onChanged: (ThemeMode? value) { if (value != null) { cubit.setThemeMode(value); } }, ), ), ListTile( title: Text(l10n.light), leading: Radio<ThemeMode>( key: const Key('radio_light'), value: ThemeMode.light, groupValue: state.themeMode, onChanged: (ThemeMode? value) { if (value != null) { cubit.setThemeMode(value); } }, ), ), ], ), ), Expanded( child: Column( children: [ Text( l10n.colorSettings, style: Theme.of(context).textTheme.titleLarge, ), _ColorTile( buttonKey: const Key('filled_color_key'), color: state.filledColor, label: l10n.filledPixelColor, onPressed: () async { final color = await _showColorPicker(state.filledColor); if (color != null) { cubit.setFilledColor(color); } }, ), _ColorTile( buttonKey: const Key('unfilled_color_key'), color: state.unfilledColor, label: l10n.unfilledPixelColor, onPressed: () async { final color = await _showColorPicker( state.unfilledColor, ); if (color != null) { cubit.setUnfilledColor(color); } }, ), _ColorTile( buttonKey: const Key('background_color_key'), color: state.backgroundColor, label: l10n.backgroundColor, onPressed: () async { final color = await _showColorPicker( state.backgroundColor, ); if (color != null) { cubit.setBackgroundColor(color); } }, ), ], ), ), Expanded( child: Column( children: [ Text( l10n.mapSettings, style: Theme.of(context).textTheme.titleLarge, ), Padding( padding: const EdgeInsets.all(16), child: TextField( controller: _gridFieldController, keyboardType: TextInputType.number, inputFormatters: [ FilteringTextInputFormatter.digitsOnly, ], decoration: InputDecoration( labelText: l10n.mapGridSize, ), ), ), ], ), ), ], ), ), Padding( padding: const EdgeInsets.all(16), child: ElevatedButton( onPressed: () { cubit.setGridSize( int.parse(_gridFieldController.text), ); Navigator.of(context).pop(); }, child: Text(l10n.close), ), ), ], ), ), ); } } class _ColorTile extends StatelessWidget { const _ColorTile({ required this.color, required this.label, required this.onPressed, this.buttonKey, }); final Color color; final VoidCallback onPressed; final String label; final Key? buttonKey; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.only(left: 16, top: 16), child: Row( children: [ _ColorButton( key: buttonKey, color: color, onPressed: onPressed, ), const SizedBox(width: 16), Expanded(child: Text(label)), ], ), ); } } class _ColorButton extends StatelessWidget { const _ColorButton({ super.key, required this.color, required this.onPressed, }); final Color color; final VoidCallback onPressed; @override Widget build(BuildContext context) { return InkWell( onTap: onPressed, child: Card( child: Container( width: 32, height: 32, color: color, ), ), ); } }
mini_sprite/packages/mini_sprite_editor/lib/config/view/config_dialog.dart/0
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/config/view/config_dialog.dart', 'repo_id': 'mini_sprite', 'token_count': 5566}
import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/services.dart'; import 'package:mini_sprite/mini_sprite.dart'; part 'map_state.dart'; class MapCubit extends Cubit<MapState> { MapCubit({ Future<void> Function(ClipboardData)? setClipboardData, Future<ClipboardData?> Function(String)? getClipboardData, }) : _setClipboardData = setClipboardData ?? Clipboard.setData, _getClipboardData = getClipboardData ?? Clipboard.getData, super(const MapState.initial()); final Future<void> Function(ClipboardData) _setClipboardData; final Future<ClipboardData?> Function(String) _getClipboardData; void copyToClipboard() { final data = MiniMap( objects: state.objects, width: state.mapSize.width.toInt(), height: state.mapSize.height.toInt(), ).toDataString(); _setClipboardData(ClipboardData(text: data)); } Future<void> importFromClipboard() async { final data = await _getClipboardData('text/plain'); final text = data?.text; if (text != null) { final map = MiniMap.fromDataString(text); emit(state.copyWith(objects: map.objects)); } } void setObjectData(int x, int y, Map<String, dynamic> data) { final position = MapPosition(x, y); if (state.objects[position] == null) { addObject(x, y, data); } else { final objData = state.objects[MapPosition(x, y)]!; final newData = <String, dynamic>{ ...objData, ...data, }; emit( state.copyWith( objects: { ...state.objects, position: newData, }, ), ); } } void addObject(int x, int y, Map<String, dynamic> data) { emit( state.copyWith( objects: { ...state.objects, MapPosition(x, y): data, }, ), ); } void removeObject(int x, int y) { final newObjects = Map.fromEntries( state.objects.entries.where( (entry) => entry.key != MapPosition( x, y, ), ), ); emit(state.copyWith(objects: newObjects)); } void setSize(int x, int y) { emit( state.copyWith( mapSize: Size( x.toDouble(), y.toDouble(), ), ), ); } void clearMap() { emit(state.copyWith(objects: {})); } void setSelected(MapPosition position) { if (state.selectedObject == position) { emit(state.copyWith(selectedObject: const MapPosition(-1, -1))); } else { emit(state.copyWith(selectedObject: position)); } } void removeProperty(MapPosition selected, String key) { final selectedObject = state.objects[selected]; if (selectedObject != null) { final data = <String, dynamic>{ ...Map<String, dynamic>.fromEntries( selectedObject.entries.where((entry) => entry.key != key).toList(), ), }; emit( state.copyWith( objects: { ...state.objects, selected: data, }, ), ); } } }
mini_sprite/packages/mini_sprite_editor/lib/map/cubit/map_cubit.dart/0
{'file_path': 'mini_sprite/packages/mini_sprite_editor/lib/map/cubit/map_cubit.dart', 'repo_id': 'mini_sprite', 'token_count': 1391}