code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
name: deploy_firebase_functions_dev on: push: paths: - ".github/workflows/deploy_firebase_functions_dev.yaml" - "functions/**" branches: - main defaults: run: working-directory: functions jobs: deploy-dev: runs-on: ubuntu-latest name: Deploy Dev Firebase Functions steps: - name: Checkout Repo uses: actions/checkout@main - name: Setup node uses: actions/setup-node@v3 with: node-version: 18 - run: npm install - run: npm run lint - run: npm test - name: GitHub Action for Firebase uses: w9jds/firebase-action@v12.4.0 with: args: deploy --only functions env: GCP_SA_KEY: ${{ secrets.FIREBASE_SERVICE_ACCOUNT_DEV }} PROJECT_ID: top-dash-dev
io_flip/.github/workflows/deploy_firebase_functions_dev.yaml/0
{'file_path': 'io_flip/.github/workflows/deploy_firebase_functions_dev.yaml', 'repo_id': 'io_flip', 'token_count': 384}
// ignore_for_file: avoid_print import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; extension ApplicationJsonX on Map<String, String> { bool isContentTypeJson() { return this[HttpHeaders.contentTypeHeader] ?.startsWith(ContentType.json.value) ?? false; } } const methodsRequiringContentTypeJson = [ HttpMethod.post, HttpMethod.put, HttpMethod.patch, ]; Middleware contentTypeHeader() { return (handler) { return (context) async { final method = context.request.method; final headers = context.request.headers; if (methodsRequiringContentTypeJson.contains(method) && !headers.isContentTypeJson()) { final path = context.request.uri.path; final message = '${HttpHeaders.contentTypeHeader} not allowed ' 'for ${method.value} $path'; print(message); return Response(statusCode: HttpStatus.badRequest); } final response = await handler(context); return response; }; }; }
io_flip/api/headers/application_json_header.dart/0
{'file_path': 'io_flip/api/headers/application_json_header.dart', 'repo_id': 'io_flip', 'token_count': 396}
/// Access to Cards data source. library cards_repository; export 'src/cards_repository.dart';
io_flip/api/packages/cards_repository/lib/cards_repository.dart/0
{'file_path': 'io_flip/api/packages/cards_repository/lib/cards_repository.dart', 'repo_id': 'io_flip', 'token_count': 31}
/// Client used to access the game database library db_client; export 'src/db_client.dart';
io_flip/api/packages/db_client/lib/db_client.dart/0
{'file_path': 'io_flip/api/packages/db_client/lib/db_client.dart', 'repo_id': 'io_flip', 'token_count': 28}
/// A Very Good Project created by Very Good CLI. library firebase_cloud_storage; export 'src/firebase_cloud_storage.dart';
io_flip/api/packages/firebase_cloud_storage/lib/firebase_cloud_storage.dart/0
{'file_path': 'io_flip/api/packages/firebase_cloud_storage/lib/firebase_cloud_storage.dart', 'repo_id': 'io_flip', 'token_count': 37}
import 'package:equatable/equatable.dart'; import 'package:game_domain/game_domain.dart'; import 'package:json_annotation/json_annotation.dart'; part 'match.g.dart'; /// {@template match} /// A model that represents a match. /// {@endtemplate} @JsonSerializable(ignoreUnannotated: true, explicitToJson: true) class Match extends Equatable { /// {@macro match} const Match({ required this.id, required this.hostDeck, required this.guestDeck, this.hostConnected = false, this.guestConnected = false, }); /// {@macro match} factory Match.fromJson(Map<String, dynamic> json) => _$MatchFromJson(json); /// Match id. @JsonKey() final String id; /// Deck of the host. @JsonKey() final Deck hostDeck; /// Deck of the guest. @JsonKey() final Deck guestDeck; /// If the host is connected or disconnected from the match. @JsonKey() final bool hostConnected; /// If the guest is connected or disconnected from the match. @JsonKey() final bool guestConnected; /// Returns a json representation from this instance. Map<String, dynamic> toJson() => _$MatchToJson(this); @override List<Object> get props => [ id, hostDeck, guestDeck, hostConnected, guestConnected, ]; }
io_flip/api/packages/game_domain/lib/src/models/match.dart/0
{'file_path': 'io_flip/api/packages/game_domain/lib/src/models/match.dart', 'repo_id': 'io_flip', 'token_count': 459}
// ignore_for_file: prefer_const_constructors import 'package:game_domain/src/models/card_description.dart'; import 'package:test/test.dart'; void main() { group('CardDescription', () { test('can instantiate', () { expect( CardDescription( character: '', characterClass: '', power: '', location: '', description: '', ), isNotNull, ); }); test('can deserialize', () { expect( CardDescription.fromJson( const { 'character': 'character', 'characterClass': 'characterClass', 'power': 'power', 'location': 'location', 'description': 'description', }, ), equals( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), ), ); }); test('can serialize', () { expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ).toJson(), equals( const { 'character': 'character', 'characterClass': 'characterClass', 'power': 'power', 'location': 'location', 'description': 'description', }, ), ); }); }); test('supports equality', () { expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), equals( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), ), ); expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), isNot( equals( CardDescription( character: 'character1', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), ), ), ); expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), isNot( equals( CardDescription( character: 'character', characterClass: 'characterClass1', power: 'power', location: 'location', description: 'description', ), ), ), ); expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), isNot( equals( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power1', location: 'location', description: 'description', ), ), ), ); expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), isNot( equals( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location1', description: 'description', ), ), ), ); expect( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description', ), isNot( equals( CardDescription( character: 'character', characterClass: 'characterClass', power: 'power', location: 'location', description: 'description1', ), ), ), ); }); }
io_flip/api/packages/game_domain/test/src/models/card_description_test.dart/0
{'file_path': 'io_flip/api/packages/game_domain/test/src/models/card_description_test.dart', 'repo_id': 'io_flip', 'token_count': 2195}
/// The default script, used when none is found in the firebase. const defaultGameLogic = ''' external fun rollDoubleValue fun rollCardRarity() -> bool { var chance = rollDoubleValue(); return chance >= 0.95; } fun rollCardPower(isRare: bool) -> int { const maxValue = 99; const minValue = 10; const gap = maxValue - minValue; var base = rollDoubleValue(); var value = (base * gap + minValue).toInt(); value = if (isRare) 100 else value; return value; } fun compareCards(valueA: int, valueB: int, suitA: str, suitB: str) -> int { var evaluation = compareSuits(suitA, suitB); var aModifier = if (evaluation == -1) 10 else 0; var bModifier = if (evaluation == 1) 10 else 0; var a = valueA - aModifier; var b = valueB - bModifier; if (a > b) { return 1; } else if (a < b) { return -1; } else { return 0; } } fun compareSuits(suitA: str, suitB: str) -> int { when (suitA) { 'fire' -> { when (suitB) { 'air', 'metal' -> return 1; 'water', 'earth' -> return -1; else -> return 0; } } 'air' -> { when (suitB) { 'water', 'earth' -> return 1; 'fire', 'metal' -> return -1; else -> return 0; } } 'metal' -> { when (suitB) { 'water', 'air' -> return 1; 'fire', 'earth' -> return -1; else -> return 0; } } 'earth' -> { when (suitB) { 'fire', 'metal' -> return 1; 'water', 'air' -> return -1; else -> return 0; } } 'water' -> { when (suitB) { 'fire', 'earth' -> return 1; 'metal', 'air' -> return -1; else -> return 0; } } else -> return 0; } } ''';
io_flip/api/packages/game_script_machine/lib/src/default_script.dart/0
{'file_path': 'io_flip/api/packages/game_script_machine/lib/src/default_script.dart', 'repo_id': 'io_flip', 'token_count': 770}
/// A dart_frog middleware for checking JWT authorization. library jwt_middleware; export 'src/authenticated_user.dart'; export 'src/jwt_middleware.dart';
io_flip/api/packages/jwt_middleware/lib/jwt_middleware.dart/0
{'file_path': 'io_flip/api/packages/jwt_middleware/lib/jwt_middleware.dart', 'repo_id': 'io_flip', 'token_count': 50}
include: package:very_good_analysis/analysis_options.3.1.0.yaml
io_flip/api/packages/prompt_repository/analysis_options.yaml/0
{'file_path': 'io_flip/api/packages/prompt_repository/analysis_options.yaml', 'repo_id': 'io_flip', 'token_count': 23}
import 'dart:async'; import 'dart:io'; import 'package:collection/collection.dart'; import 'package:dart_frog/dart_frog.dart'; import 'package:game_domain/game_domain.dart'; import 'package:prompt_repository/prompt_repository.dart'; FutureOr<Response> onRequest(RequestContext context) async { if (context.request.method == HttpMethod.get) { final type = context.request.uri.queryParameters['type']; final promptType = PromptTermType.values.firstWhereOrNull( (element) => element.name == type, ); if (promptType == null) { return Response(statusCode: HttpStatus.badRequest, body: 'Invalid type'); } final promptRepository = context.read<PromptRepository>(); final list = await promptRepository.getPromptTermsByType( promptType, ); return Response.json(body: {'list': list.map((e) => e.term).toList()}); } return Response(statusCode: HttpStatus.methodNotAllowed); }
io_flip/api/routes/game/prompt/terms/index.dart/0
{'file_path': 'io_flip/api/routes/game/prompt/terms/index.dart', 'repo_id': 'io_flip', 'token_count': 326}
import 'dart:io'; import 'package:dart_frog/dart_frog.dart'; import 'package:game_domain/game_domain.dart'; import 'package:logging/logging.dart'; import 'package:match_repository/match_repository.dart'; import 'package:mocktail/mocktail.dart'; import 'package:test/test.dart'; import '../../../../../routes/game/matches/[matchId]/index.dart' as route; class _MockRequestContext extends Mock implements RequestContext {} class _MockMatchRepository extends Mock implements MatchRepository {} class _MockRequest extends Mock implements Request {} class _MockLogger extends Mock implements Logger {} void main() { group('GET /game/matches/[matchId]', () { late MatchRepository matchRepository; late Request request; late RequestContext context; late Logger logger; const hostDeck = Deck( id: 'hostDeckId', userId: 'hostUserId', cards: [ Card( id: '', name: '', description: '', image: '', power: 10, rarity: false, suit: Suit.air, ), ], ); const guestDeck = Deck( id: 'guestDeckId', userId: 'guestUserId', cards: [ Card( id: '', name: '', description: '', image: '', power: 10, rarity: false, suit: Suit.air, ), ], ); const match = Match( id: 'matchId', guestDeck: guestDeck, hostDeck: hostDeck, ); setUp(() { matchRepository = _MockMatchRepository(); when(() => matchRepository.getMatch(any())).thenAnswer( (_) async => match, ); request = _MockRequest(); when(() => request.method).thenReturn(HttpMethod.get); when(request.json).thenAnswer( (_) async => match.toJson(), ); logger = _MockLogger(); context = _MockRequestContext(); when(() => context.request).thenReturn(request); when(() => context.read<MatchRepository>()).thenReturn(matchRepository); when(() => context.read<Logger>()).thenReturn(logger); }); test('responds with a 200', () async { final response = await route.onRequest(context, match.id); expect(response.statusCode, equals(HttpStatus.ok)); }); test('responds with the match', () async { final response = await route.onRequest(context, match.id); final json = await response.json() as Map<String, dynamic>; expect( json, equals(match.toJson()), ); }); test("responds 404 when the match doesn't exists", () async { when(() => matchRepository.getMatch(any())).thenAnswer((_) async => null); final response = await route.onRequest(context, match.id); expect(response.statusCode, equals(HttpStatus.notFound)); }); test('allows only get methods', () async { when(() => request.method).thenReturn(HttpMethod.post); final response = await route.onRequest(context, match.id); expect(response.statusCode, equals(HttpStatus.methodNotAllowed)); }); }); }
io_flip/api/test/routes/game/matches/[matchId]/index_test.dart/0
{'file_path': 'io_flip/api/test/routes/game/matches/[matchId]/index_test.dart', 'repo_id': 'io_flip', 'token_count': 1268}
// ignore_for_file: avoid_print import 'dart:io'; import 'package:data_loader/src/prompt_mapper.dart'; import 'package:db_client/db_client.dart'; import 'package:game_domain/game_domain.dart'; /// {@template check_missing_descriptions} /// Dart tool that feed descriptions into the Descriptions base /// {@endtemplate} class MissingDescriptions { /// {@macro check_missing_descriptions} const MissingDescriptions({ required DbClient dbClient, required File csv, required String character, }) : _dbClient = dbClient, _csv = csv, _character = character; final File _csv; final DbClient _dbClient; final String _character; String _normalizeTerm(String term) { return term.trim().toLowerCase().replaceAll(' ', '_'); } /// Loads the descriptions from the CSV file into the database /// [onProgress] is called everytime there is progress, /// it takes in the current inserted and the total to insert. Future<void> checkMissing(void Function(int, int) onProgress) async { final lines = await _csv.readAsLines(); final map = mapCsvToPrompts(lines); final queries = <Map<String, dynamic>>[]; for (final characterClass in map[PromptTermType.characterClass]!) { for (final power in map[PromptTermType.power]!) { for (final location in map[PromptTermType.location]!) { queries.add( { 'character': _normalizeTerm(_character), 'characterClass': _normalizeTerm(characterClass), 'power': _normalizeTerm(power), 'location': _normalizeTerm(location), }, ); } } } for (final query in queries) { final result = await _dbClient.find( 'card_descriptions', query, ); if (result.isEmpty) { print(query.values.join('_')); } } print('Done'); } }
io_flip/api/tools/data_loader/lib/src/check_missing_descriptions_loader.dart/0
{'file_path': 'io_flip/api/tools/data_loader/lib/src/check_missing_descriptions_loader.dart', 'repo_id': 'io_flip', 'token_count': 733}
// ignore_for_file: avoid_web_libraries_in_flutter, avoid_print import 'dart:async'; import 'dart:math'; import 'package:api_client/api_client.dart'; import 'package:authentication_repository/authentication_repository.dart'; import 'package:bloc/bloc.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:connection_repository/connection_repository.dart'; import 'package:equatable/equatable.dart'; import 'package:firebase_app_check/firebase_app_check.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:flop/firebase_options_development.dart'; import 'package:game_domain/game_domain.dart'; import 'package:match_maker_repository/match_maker_repository.dart'; part 'flop_event.dart'; part 'flop_state.dart'; class FlopBloc extends Bloc<FlopEvent, FlopState> { FlopBloc({ required this.setAppCheckDebugToken, required this.reload, }) : super(const FlopState.initial()) { on<NextStepRequested>(_onNextStepRequested); } final void Function(String) setAppCheckDebugToken; final void Function() reload; late AuthenticationRepository authenticationRepository; late ConnectionRepository connectionRepository; late MatchMakerRepository matchMakerRepository; late ApiClient apiClient; late FirebaseAuth authInstance; late bool isHost; late List<Card> cards; late String matchId; late String deckId; late String matchStateId; Future<void> initialize(Emitter<FlopState> emit) async { emit(state.withNewMessage('πŸ€– Hello, I am Flop and I am ready!')); const recaptchaKey = String.fromEnvironment('RECAPTCHA_KEY'); const appCheckDebugToken = String.fromEnvironment('APPCHECK_DEBUG_TOKEN'); setAppCheckDebugToken(appCheckDebugToken); await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform, ); // Ensure we always have a new user. authInstance = FirebaseAuth.instance; await authInstance.setPersistence(Persistence.NONE); emit(state.withNewMessage('πŸ”₯ Firebase initialized')); final appCheck = FirebaseAppCheck.instance; await appCheck.activate( webRecaptchaSiteKey: recaptchaKey, ); await appCheck.setTokenAutoRefreshEnabled(true); emit(state.withNewMessage('βœ… AppCheck activated')); } Future<void> authenticate(Emitter<FlopState> emit) async { authenticationRepository = AuthenticationRepository( firebaseAuth: authInstance, ); final appCheck = FirebaseAppCheck.instance; apiClient = ApiClient( baseUrl: 'https://top-dash-dev-api-synvj3dcmq-uc.a.run.app', idTokenStream: authenticationRepository.idToken, refreshIdToken: authenticationRepository.refreshIdToken, appCheckTokenStream: appCheck.onTokenChange, appCheckToken: await appCheck.getToken(), ); await authenticationRepository.signInAnonymously(); await authenticationRepository.idToken.first; final user = await authenticationRepository.user.first; connectionRepository = ConnectionRepository( apiClient: apiClient, ); emit(state.withNewMessage('🎭 Authenticated anonymously: ${user.id}')); } Future<void> generateCards(Emitter<FlopState> emit) async { final generatedCards = await apiClient.gameResource.generateCards( const Prompt( characterClass: 'Wizard', power: 'Chocolate', ), ); emit( state.withNewMessage( 'πŸƒ Generated ${generatedCards.length} cards\n ' '${generatedCards.map((card) => ' - ${card.name}').join('\n ')}', ), ); cards = (generatedCards..shuffle()).take(3).toList(); emit( state.withNewMessage( 'πŸƒ Choose 3 cards\n ' '${cards.map((card) => ' - ${card.name}').join('\n ')}', ), ); } Future<void> requestMatchConnection() async { final completer = Completer<void>(); await connectionRepository.connect(); late StreamSubscription<WebSocketMessage> subscription; subscription = connectionRepository.messages.listen( (message) { if (message.messageType == MessageType.connected) { completer.complete(); subscription.cancel(); } else if (message.messageType == MessageType.error) { completer.completeError('Already connected'); } }, ); return completer.future.timeout(const Duration(seconds: 4)); } Future<void> connectToMatch({ required String matchId, required bool isHost, }) async { connectionRepository.send( WebSocketMessage.matchJoined( matchId: matchId, isHost: isHost, ), ); await connectionRepository.messages.firstWhere((message) { return message.messageType == MessageType.matchJoined; }); } Future<void> matchMaking(Emitter<FlopState> emit) async { emit(state.withNewMessage('πŸ₯Ί Requesting match connection')); await requestMatchConnection(); emit(state.withNewMessage('🀝 Connection established')); final cardIds = cards.map((card) => card.id).toList(); deckId = await apiClient.gameResource.createDeck(cardIds); emit(state.withNewMessage('πŸ‘‹ User hand is: $deckId')); matchMakerRepository = MatchMakerRepository( db: FirebaseFirestore.instance, ); final match = await matchMakerRepository.findMatch(deckId); isHost = match.guest == null; await connectToMatch( matchId: match.id, isHost: isHost, ); if (isHost) { final newState = state.copyWith( messages: [ 'πŸ‘€ No match found, created one and waiting for a guest', ...state.messages, ], steps: [...state.steps, FlopStep.matchmaking], ); emit(newState); final stream = matchMakerRepository.watchMatch(match.id); late StreamSubscription<DraftMatch> subscription; final completer = Completer<void>(); subscription = stream.listen((newMatch) { print(newMatch); if (newMatch.guest != null) { matchId = newMatch.id; emit( newState.copyWith( messages: ['πŸŽ‰ Match joined', ...newState.messages], steps: [...newState.steps, FlopStep.joinedMatch], ), ); subscription.cancel(); completer.complete(); } }); return completer.future; } else { matchId = match.id; emit( state.copyWith( messages: ['πŸŽ‰ Match joined: ${match.id}', ...state.messages], steps: [ ...state.steps, FlopStep.matchmaking, FlopStep.joinedMatch, ], ), ); } } Future<void> playCard(int i, Emitter<FlopState> emit) async { await apiClient.gameResource.playCard( matchId: matchId, cardId: cards[i].id, deckId: deckId, ); emit( state.withNewMessage( 'πŸƒ Played ${cards[i].name}', ), ); } Future<void> playGame(Emitter<FlopState> emit) async { final rng = Random(); final completer = Completer<void>(); final matchState = await apiClient.gameResource.getMatchState(matchId); matchStateId = matchState!.id; late StreamSubscription<MatchState> subscription; subscription = matchMakerRepository.watchMatchState(matchStateId).listen((matchState) { if (matchState.isOver()) { emit( state.copyWith( messages: ['πŸŽ‰ Match over', ...state.messages], steps: [...state.steps, FlopStep.playing], ), ); subscription.cancel(); completer.complete(); } else { final myPlayedCards = isHost ? matchState.hostPlayedCards : matchState.guestPlayedCards; final opponentPlayedCards = isHost ? matchState.guestPlayedCards : matchState.hostPlayedCards; if (myPlayedCards.length == opponentPlayedCards.length || myPlayedCards.length < opponentPlayedCards.length) { var retries = 3; Future<void>.delayed(Duration(milliseconds: rng.nextInt(1000) + 500), () async { await playCard(myPlayedCards.length, emit); }).onError( (error, _) { if (retries > 0) { return Future<void>.delayed( Duration(milliseconds: rng.nextInt(1000) + 500), ).then((_) { retries--; return playCard(myPlayedCards.length, emit); }); } else { emit(state.withNewMessage('😭 Error playing cards: $error')); } }, ); Future<void>.delayed(const Duration(seconds: 3)).then((_) { playCard(myPlayedCards.length, emit); }); } } }); await playCard(0, emit); await completer.future; } Future<void> _onNextStepRequested( _, Emitter<FlopState> emit, ) async { try { if (state.steps.isEmpty) { await initialize(emit); emit(state.copyWith(steps: [FlopStep.initial])); } else { final lastStep = state.steps.last; switch (lastStep) { case FlopStep.initial: await authenticate(emit); emit( state.copyWith( steps: [...state.steps, FlopStep.authentication], ), ); break; case FlopStep.authentication: await generateCards(emit); emit( state.copyWith( steps: [...state.steps, FlopStep.deckDraft], ), ); break; case FlopStep.deckDraft: await matchMaking(emit).timeout(const Duration(seconds: 120)); break; case FlopStep.matchmaking: break; case FlopStep.joinedMatch: await playGame(emit).timeout(const Duration(seconds: 30)); break; case FlopStep.playing: emit( state.copyWith( status: FlopStatus.success, ), ); await Future<void>.delayed(const Duration(seconds: 2)); reload(); break; } } } catch (e, s) { emit( state.copyWith( status: FlopStatus.error, messages: [ '🚨 Error: $e $s', ...state.messages, ], ), ); print(e); print(s); addError(e, s); await Future<void>.delayed(const Duration(seconds: 2)); reload(); } } }
io_flip/flop/lib/flop/bloc/flop_bloc.dart/0
{'file_path': 'io_flip/flop/lib/flop/bloc/flop_bloc.dart', 'repo_id': 'io_flip', 'token_count': 4558}
export 'widgets/widgets.dart';
io_flip/lib/audio/audio.dart/0
{'file_path': 'io_flip/lib/audio/audio.dart', 'repo_id': 'io_flip', 'token_count': 12}
export 'bloc/draft_bloc.dart'; export 'views/views.dart'; export 'widgets/widgets.dart';
io_flip/lib/draft/draft.dart/0
{'file_path': 'io_flip/lib/draft/draft.dart', 'repo_id': 'io_flip', 'token_count': 36}
import 'dart:async'; import 'package:flutter/material.dart' hide Card, Element; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:game_domain/game_domain.dart'; import 'package:game_script_machine/game_script_machine.dart'; import 'package:io_flip/audio/audio_controller.dart'; import 'package:io_flip/gen/assets.gen.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; enum ComparisonResult { player, opponent, none } extension on int { ComparisonResult get result { if (this == 1) { return ComparisonResult.player; } else if (this == -1) { return ComparisonResult.opponent; } else { return ComparisonResult.none; } } } extension on TickerFuture { Future<void> get done => orCancel.then<void>((_) {}, onError: (_) {}); } class ClashScene extends StatefulWidget { const ClashScene({ required this.onFinished, required this.opponentCard, required this.playerCard, super.key, }); final VoidCallback onFinished; final Card opponentCard; final Card playerCard; @override State<StatefulWidget> createState() => ClashSceneState(); } class ClashSceneState extends State<ClashScene> with TickerProviderStateMixin { Color bgColor = Colors.transparent; final AnimatedCardController opponentController = AnimatedCardController(); final AnimatedCardController playerController = AnimatedCardController(); late final AnimationController motionController = AnimationController( vsync: this, duration: const Duration(seconds: 5), ); late final motion = TweenSequence([ TweenSequenceItem(tween: Tween<double>(begin: 60, end: 15), weight: 4), TweenSequenceItem(tween: Tween<double>(begin: 15, end: 0), weight: 5), ]).animate( CurvedAnimation(parent: motionController, curve: Curves.easeOutCirc), ); late final AnimationController damageController = AnimationController( vsync: this, duration: const Duration(seconds: 2), ); final Completer<void> damageCompleter = Completer<void>(); Animation<int>? powerDecrementAnimation; late final ComparisonResult winningCard; late final ComparisonResult winningSuit; bool _flipCards = false; bool _playedWinningElementSound = false; void onFlipCards() { motionController.stop(); Future.delayed( const Duration(milliseconds: 100), () => opponentController.run(smallFlipAnimation), ); playerController.run(smallFlipAnimation); Future.delayed( const Duration(milliseconds: 500), () => setState(() => _flipCards = true), ); } void onDamageRecieved() => damageController ..forward() ..addStatusListener((status) { if (status == AnimationStatus.completed) { damageCompleter.complete(); } }); Future<void> onElementalComplete() async { if (winningCard != ComparisonResult.none) { setState(() { bgColor = Colors.black.withOpacity(0.5); }); if (winningCard == ComparisonResult.player) { await playerController.run(playerAttackForwardAnimation).done; await Future<void>.delayed(const Duration(milliseconds: 5)); await Future.wait([ playerController.run(playerAttackBackAnimation).done, opponentController.run(opponentKnockOutAnimation).done, ]); } else if (winningCard == ComparisonResult.opponent) { await opponentController.run(opponentAttackForwardAnimation).done; await Future<void>.delayed(const Duration(milliseconds: 5)); await Future.wait([ opponentController.run(opponentAttackBackAnimation).done, playerController.run(playerKnockOutAnimation).done, ]); } } widget.onFinished(); } void _getResults() { final gameScript = context.read<GameScriptMachine>(); final playerCard = widget.playerCard; final opponentCard = widget.opponentCard; winningCard = gameScript.compare(playerCard, opponentCard).result; winningSuit = gameScript.compareSuits(playerCard.suit, opponentCard.suit).result; if (winningSuit != ComparisonResult.none) { int power; if (winningSuit == ComparisonResult.player) { power = widget.opponentCard.power; } else { power = widget.playerCard.power; } powerDecrementAnimation = IntTween( begin: power, end: power - 10, ).animate( CurvedAnimation( parent: damageController, curve: Curves.easeOutCirc, ), ); } } void _playSoundByElement(Element element) { switch (element) { case Element.fire: context.read<AudioController>().playSfx(Assets.sfx.fire); break; case Element.air: context.read<AudioController>().playSfx(Assets.sfx.air); break; case Element.earth: context.read<AudioController>().playSfx(Assets.sfx.earth); break; case Element.metal: context.read<AudioController>().playSfx(Assets.sfx.metal); break; case Element.water: context.read<AudioController>().playSfx(Assets.sfx.water); break; } } @override void initState() { super.initState(); _getResults(); motionController.forward(); context.read<AudioController>().playSfx(Assets.sfx.flip); } @override void dispose() { motionController.dispose(); opponentController.dispose(); playerController.dispose(); damageController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { const cardSize = GameCardSize.md(); final clashSceneSize = Size(cardSize.width * 1.7, cardSize.height * 2.15); final playerCard = AnimatedBuilder( key: const Key('player_card'), animation: motion, builder: (_, child) { return Positioned( bottom: 0, right: motion.value, child: child!, ); }, child: AnimatedCard( controller: playerController, front: const FlippedGameCard( size: cardSize, ), back: powerDecrementAnimation != null && winningSuit == ComparisonResult.opponent ? AnimatedBuilder( animation: powerDecrementAnimation!, builder: (_, __) { return GameCard( size: cardSize, image: widget.playerCard.image, name: widget.playerCard.name, description: widget.playerCard.description, power: powerDecrementAnimation!.value, suitName: widget.playerCard.suit.name, isRare: widget.playerCard.rarity, ); }, ) : GameCard( size: cardSize, image: widget.playerCard.image, name: widget.playerCard.name, description: widget.playerCard.description, power: widget.playerCard.power, suitName: widget.playerCard.suit.name, isRare: widget.playerCard.rarity, ), ), ); final opponentCard = AnimatedBuilder( key: const Key('opponent_card'), animation: motion, builder: (_, child) { return Positioned( top: 0, left: motion.value, child: child!, ); }, child: AnimatedCard( controller: opponentController, front: const FlippedGameCard( size: cardSize, ), back: powerDecrementAnimation != null && winningSuit == ComparisonResult.player ? AnimatedBuilder( animation: powerDecrementAnimation!, builder: (_, __) { return GameCard( size: cardSize, image: widget.opponentCard.image, name: widget.opponentCard.name, description: widget.opponentCard.description, power: powerDecrementAnimation!.value, suitName: widget.opponentCard.suit.name, isRare: widget.opponentCard.rarity, ); }, ) : GameCard( size: cardSize, image: widget.opponentCard.image, name: widget.opponentCard.name, description: widget.opponentCard.description, power: widget.opponentCard.power, suitName: widget.opponentCard.suit.name, isRare: widget.opponentCard.rarity, ), ), ); if (_playedWinningElementSound) { final suit = switch (winningCard) { ComparisonResult.player => widget.playerCard.suit, ComparisonResult.opponent => widget.opponentCard.suit, ComparisonResult.none => null, }; if (suit != null) { final element = _elementsMap[suit]!; _playSoundByElement(element); } } final winningElement = _elementsMap[winningSuit == ComparisonResult.player ? widget.playerCard.suit : widget.opponentCard.suit]; if (_flipCards && !_playedWinningElementSound && winningSuit != ComparisonResult.none) { if (winningSuit != ComparisonResult.none) { _playSoundByElement(winningElement!); } _playedWinningElementSound = true; } return AnimatedContainer( duration: const Duration(milliseconds: 300), color: bgColor, child: Center( child: SizedBox.fromSize( size: clashSceneSize, child: Stack( children: [ if (winningCard == ComparisonResult.player) ...[ opponentCard, playerCard ] else ...[ playerCard, opponentCard ], Positioned.fill( child: Visibility( visible: !_flipCards, child: FlipCountdown( onComplete: onFlipCards, ), ), ), if (_flipCards) ElementalDamageAnimation( winningElement!, direction: winningSuit == ComparisonResult.player || (winningSuit == ComparisonResult.none && winningCard == ComparisonResult.player) ? DamageDirection.bottomToTop : DamageDirection.topToBottom, size: cardSize, assetSize: platformAwareAsset<AssetSize>( desktop: AssetSize.large, mobile: AssetSize.small, ), initialState: winningSuit == ComparisonResult.none ? DamageAnimationState.victory : DamageAnimationState.charging, onDamageReceived: onDamageRecieved, pointDeductionCompleter: damageCompleter, onComplete: onElementalComplete, ) ], ), ), ), ); } static const _elementsMap = { Suit.air: Element.air, Suit.earth: Element.earth, Suit.fire: Element.fire, Suit.metal: Element.metal, Suit.water: Element.water, }; }
io_flip/lib/game/widgets/clash_scene.dart/0
{'file_path': 'io_flip/lib/game/widgets/clash_scene.dart', 'repo_id': 'io_flip', 'token_count': 5033}
export 'arrow_widget.dart'; export 'circular_alignment_tween.dart'; export 'fade_animated_switcher.dart'; export 'how_to_play_styled_text.dart'; export 'suits_wheel.dart';
io_flip/lib/how_to_play/widgets/widgets.dart/0
{'file_path': 'io_flip/lib/how_to_play/widgets/widgets.dart', 'repo_id': 'io_flip', 'token_count': 67}
export 'bloc/leaderboard_bloc.dart'; export 'views/views.dart'; export 'widgets/widgets.dart';
io_flip/lib/leaderboard/leaderboard.dart/0
{'file_path': 'io_flip/lib/leaderboard/leaderboard.dart', 'repo_id': 'io_flip', 'token_count': 37}
import 'package:flutter/material.dart' hide Card; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:game_domain/game_domain.dart'; import 'package:go_router/go_router.dart'; import 'package:io_flip/audio/audio.dart'; import 'package:io_flip/game/game.dart'; import 'package:io_flip/l10n/l10n.dart'; import 'package:io_flip/match_making/match_making.dart'; import 'package:io_flip/utils/utils.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class MatchMakingView extends StatelessWidget { const MatchMakingView({ required this.deck, required this.tryAgainEvent, super.key, Future<void> Function(ClipboardData) setClipboardData = Clipboard.setData, RouterNeglectCall routerNeglectCall = Router.neglect, }) : _setClipboardData = setClipboardData, _routerNeglectCall = routerNeglectCall; final Future<void> Function(ClipboardData) _setClipboardData; final Deck deck; final RouterNeglectCall _routerNeglectCall; /// The event to add to the bloc when match making fails and we try again. final MatchMakingEvent tryAgainEvent; @override Widget build(BuildContext context) { return BlocConsumer<MatchMakingBloc, MatchMakingState>( listener: (previous, current) { if (current.status == MatchMakingStatus.completed) { Future.delayed( const Duration(seconds: 3), () => _routerNeglectCall( context, () => context.goNamed( 'game', extra: GamePageData( isHost: current.isHost, matchId: current.match?.id ?? '', deck: deck, ), ), ), ); } }, builder: (context, state) { final l10n = context.l10n; if (state.status == MatchMakingStatus.processing || state.status == MatchMakingStatus.initial) { return ResponsiveLayoutBuilder( small: (_, __) => _WaitingForMatchView( cards: deck.cards, setClipboardData: _setClipboardData, inviteCode: state.match?.inviteCode, title: IoFlipTextStyles.mobileH4Light, subtitle: IoFlipTextStyles.mobileH6Light, key: const Key('small_waiting_for_match_view'), ), large: (_, __) => _WaitingForMatchView( cards: deck.cards, setClipboardData: _setClipboardData, inviteCode: state.match?.inviteCode, title: IoFlipTextStyles.headlineH4Light, subtitle: IoFlipTextStyles.headlineH6Light, key: const Key('large_waiting_for_match_view'), ), ); } if (state.status == MatchMakingStatus.timeout) { return IoFlipScaffold( body: IoFlipErrorView( text: 'Match making timed out, sorry!', buttonText: l10n.playAgain, onPressed: () => context.read<MatchMakingBloc>().add(tryAgainEvent), ), ); } if (state.status == MatchMakingStatus.failed) { return IoFlipScaffold( body: IoFlipErrorView( text: 'Match making failed, sorry!', buttonText: l10n.playAgain, onPressed: () => context.read<MatchMakingBloc>().add(tryAgainEvent), ), ); } return IoFlipScaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( l10n.getReadyToFlip, style: IoFlipTextStyles.mobileH1, ), const SizedBox(height: IoFlipSpacing.xlg), ConstrainedBox( constraints: const BoxConstraints(maxWidth: 320), child: Text( l10n.aiGameByGoogle, style: IoFlipTextStyles.mobileH4Light, textAlign: TextAlign.center, ), ), ], ), ), ); }, ); } } class _WaitingForMatchView extends StatelessWidget { const _WaitingForMatchView({ required this.title, required this.subtitle, required this.cards, required this.setClipboardData, this.inviteCode, super.key, }); final List<Card> cards; final String? inviteCode; final Future<void> Function(ClipboardData) setClipboardData; final TextStyle title; final TextStyle subtitle; @override Widget build(BuildContext context) { return IoFlipScaffold( body: Column( children: [ Expanded( child: Center( child: ConstrainedBox( constraints: const BoxConstraints(maxHeight: 600), child: Column( children: [ const Spacer(), Text( context.l10n.findingMatch, style: title, ), if (inviteCode == null) Text( context.l10n.searchingForOpponents, style: subtitle, ) else ElevatedButton( onPressed: () { final code = inviteCode; if (code != null) { setClipboardData(ClipboardData(text: code)); } }, child: Text(context.l10n.copyInviteCode), ), const SizedBox(height: IoFlipSpacing.xxlg), const FadingDotLoader(), const Spacer(), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ for (final card in cards) Padding( padding: const EdgeInsets.all(IoFlipSpacing.xs), child: GameCard( size: const GameCardSize.xs(), image: card.image, name: card.name, description: card.description, suitName: card.suit.name, power: card.power, isRare: card.rarity, ), ), ], ), ], ), ), ), ), IoFlipBottomBar( leading: const AudioToggleButton(), middle: RoundedButton.text( context.l10n.matchmaking, backgroundColor: IoFlipColors.seedGrey50, foregroundColor: IoFlipColors.seedGrey70, ), ), ], ), ); } }
io_flip/lib/match_making/views/match_making_view.dart/0
{'file_path': 'io_flip/lib/match_making/views/match_making_view.dart', 'repo_id': 'io_flip', 'token_count': 3933}
import 'package:api_client/api_client.dart'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:game_script_machine/game_script_machine.dart'; part 'scripts_state.dart'; class ScriptsCubit extends Cubit<ScriptsState> { ScriptsCubit({ required this.scriptsResource, required this.gameScriptMachine, }) : super( ScriptsState( status: ScriptsStateStatus.loaded, current: gameScriptMachine.currentScript, ), ); final ScriptsResource scriptsResource; final GameScriptMachine gameScriptMachine; Future<void> updateScript(String content) async { try { emit( state.copyWith(status: ScriptsStateStatus.loading), ); await scriptsResource.updateScript('current', content); gameScriptMachine.currentScript = content; emit( state.copyWith( status: ScriptsStateStatus.loaded, current: content, ), ); } catch (e, s) { emit( state.copyWith( status: ScriptsStateStatus.failed, ), ); addError(e, s); } } }
io_flip/lib/scripts/cubit/scripts_cubit.dart/0
{'file_path': 'io_flip/lib/scripts/cubit/scripts_cubit.dart', 'repo_id': 'io_flip', 'token_count': 470}
import 'package:flutter/material.dart' hide Card; import 'package:game_domain/game_domain.dart'; import 'package:go_router/go_router.dart'; import 'package:io_flip/share/share.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; typedef ShowShareDialog = Future<void> Function(Card card); class CardInspectorDialog extends StatefulWidget { const CardInspectorDialog({ required this.cards, required this.playerCardIds, required this.startingIndex, super.key, }); final List<String> playerCardIds; final List<Card> cards; final int startingIndex; @override State<CardInspectorDialog> createState() => _CardInspectorDialogState(); } class _CardInspectorDialogState extends State<CardInspectorDialog> { late final start = widget.cards.length * 300 + widget.startingIndex; late final controller = PageController(initialPage: start); @override Widget build(BuildContext context) { const transitionDuration = Duration(milliseconds: 200); const phoneHeight = 600; const smallestPhoneHeight = 500; final height = MediaQuery.sizeOf(context).height; final cardSize = height > phoneHeight ? const GameCardSize.xxl() : const GameCardSize.xl(); return Dialog( insetPadding: const EdgeInsets.all(IoFlipSpacing.sm), backgroundColor: Colors.transparent, child: Column( mainAxisSize: MainAxisSize.min, children: [ _CardViewer( controller: controller, deck: widget.cards, share: (card) => IoFlipDialog.show( context, child: ShareCardDialog(card: card), ), size: cardSize, playerCardIds: widget.playerCardIds, ), if (height > smallestPhoneHeight) Padding( padding: const EdgeInsets.all(IoFlipSpacing.lg), child: Row( mainAxisSize: MainAxisSize.min, children: [ _BackButton( controller: controller, transitionDuration: transitionDuration, ), const SizedBox(width: IoFlipSpacing.lg), _ForwardButton( controller: controller, transitionDuration: transitionDuration, ), ], ), ), ], ), ); } @override void dispose() { controller.dispose(); super.dispose(); } } class _ForwardButton extends StatelessWidget { const _ForwardButton({ required this.controller, required this.transitionDuration, }); final PageController controller; final Duration transitionDuration; @override Widget build(BuildContext context) { return RoundedButton.icon( Icons.arrow_forward, onPressed: () => controller.nextPage( duration: transitionDuration, curve: Curves.linear, ), ); } } class _BackButton extends StatelessWidget { const _BackButton({ required this.controller, required this.transitionDuration, }); final PageController controller; final Duration transitionDuration; @override Widget build(BuildContext context) { return RoundedButton.icon( Icons.arrow_back, onPressed: () => controller.previousPage( duration: transitionDuration, curve: Curves.linear, ), ); } } class _CardViewer extends StatelessWidget { const _CardViewer({ required this.controller, required this.deck, required this.size, required this.share, required this.playerCardIds, }); final PageController controller; final List<Card> deck; final GameCardSize size; final ShowShareDialog share; final List<String> playerCardIds; @override Widget build(BuildContext context) { return GestureDetector( onTap: () { GoRouter.of(context).pop(); }, child: SizedBox( height: size.height, width: MediaQuery.sizeOf(context).width * .9, child: PageView.builder( clipBehavior: Clip.none, controller: controller, itemBuilder: (context, i) { final index = i % deck.length; final card = deck[index]; return Center( child: GestureDetector( // Used to ignore taps. onTap: () {}, child: Stack( clipBehavior: Clip.none, children: [ TiltBuilder( builder: (context, tilt) => GameCard( key: ValueKey('GameCard$index'), tilt: tilt / 2, size: size, image: card.image, name: card.name, description: card.description, suitName: card.suit.name, power: card.power, isRare: card.rarity, ), ), if (playerCardIds.contains(card.id)) Positioned( top: IoFlipSpacing.lg, left: IoFlipSpacing.lg, child: RoundedButton.icon( Icons.share_outlined, onPressed: () => share(card), ), ), ], ), ), ); }, ), ), ); } }
io_flip/lib/share/views/card_inspector_dialog.dart/0
{'file_path': 'io_flip/lib/share/views/card_inspector_dialog.dart', 'repo_id': 'io_flip', 'token_count': 2668}
import 'package:flutter/widgets.dart'; typedef RouterNeglectCall = void Function(BuildContext, VoidCallback);
io_flip/lib/utils/router_neglect_call.dart/0
{'file_path': 'io_flip/lib/utils/router_neglect_call.dart', 'repo_id': 'io_flip', 'token_count': 33}
name: authentication_repository description: Repository to manage authentication. version: 0.1.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" flutter: ">=3.10.0" dependencies: equatable: ^2.0.5 firebase_auth: ^4.2.9 firebase_core: ^2.5.0 firebase_core_platform_interface: ^4.5.3 flutter: sdk: flutter plugin_platform_interface: ^2.1.4 dev_dependencies: flutter_test: sdk: flutter mocktail: ^0.3.0 very_good_analysis: ^4.0.0
io_flip/packages/authentication_repository/pubspec.yaml/0
{'file_path': 'io_flip/packages/authentication_repository/pubspec.yaml', 'repo_id': 'io_flip', 'token_count': 207}
import 'dart:async'; import 'dart:convert'; import 'package:api_client/api_client.dart'; import 'package:game_domain/game_domain.dart'; import 'package:web_socket_client/web_socket_client.dart'; /// {@template connection_repository} /// Repository to manage the connection state. /// {@endtemplate} class ConnectionRepository { /// {@macro connection_repository} ConnectionRepository({ required ApiClient apiClient, }) : _apiClient = apiClient; final ApiClient _apiClient; WebSocket? _webSocket; /// Connects to the server using a WebSocket. Future<void> connect() async { _webSocket = await _apiClient.connect('/public/connect'); } /// The stream of [WebSocketMessage] received from the server. Stream<WebSocketMessage> get messages => _webSocket?.messages.transform( StreamTransformer.fromHandlers( handleData: (rawMessage, sink) { try { if (rawMessage is String) { final messageJson = jsonDecode(rawMessage); if (messageJson is Map) { final message = WebSocketMessage.fromJson( Map<String, dynamic>.from(messageJson), ); sink.add(message); } } } catch (e) { // ignore it } }, ), ) ?? const Stream.empty(); /// Sends a [WebSocketMessage] to the server. void send(WebSocketMessage message) { _webSocket?.send(jsonEncode(message)); } /// Closes the connection to the server. void close() { _webSocket?.close(); _webSocket = null; } }
io_flip/packages/connection_repository/lib/src/connection_repository.dart/0
{'file_path': 'io_flip/packages/connection_repository/lib/src/connection_repository.dart', 'repo_id': 'io_flip', 'token_count': 692}
import 'package:flutter/material.dart'; import 'package:gallery/story_scaffold.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class AppSpacingStory extends StatelessWidget { const AppSpacingStory({super.key}); @override Widget build(BuildContext context) { const spacingList = [ _SpacingItem(spacing: IoFlipSpacing.xxxs, name: 'xxxs'), _SpacingItem(spacing: IoFlipSpacing.xxs, name: 'xxs'), _SpacingItem(spacing: IoFlipSpacing.xs, name: 'xs'), _SpacingItem(spacing: IoFlipSpacing.sm, name: 'sm'), _SpacingItem(spacing: IoFlipSpacing.md, name: 'md'), _SpacingItem(spacing: IoFlipSpacing.lg, name: 'lg'), _SpacingItem(spacing: IoFlipSpacing.xlgsm, name: 'xlgsm'), _SpacingItem(spacing: IoFlipSpacing.xlg, name: 'xlg'), _SpacingItem(spacing: IoFlipSpacing.xxlg, name: 'xxlg'), _SpacingItem(spacing: IoFlipSpacing.xxxlg, name: 'xxxlg'), ]; return StoryScaffold( title: 'Spacing', body: ListView( shrinkWrap: true, children: spacingList, ), ); } } class _SpacingItem extends StatelessWidget { const _SpacingItem({required this.spacing, required this.name}); final double spacing; final String name; @override Widget build(BuildContext context) { return Padding( padding: const EdgeInsets.all(IoFlipSpacing.sm), child: Row( children: <Widget>[ Row( mainAxisAlignment: MainAxisAlignment.end, children: <Widget>[ Container( color: IoFlipColors.seedBlack, width: IoFlipSpacing.xxs, height: IoFlipSpacing.lg, ), Container( width: spacing, height: IoFlipSpacing.lg, color: IoFlipColors.seedPaletteBlue70, ), Container( color: IoFlipColors.seedBlack, width: IoFlipSpacing.xxs, height: IoFlipSpacing.lg, ), ], ), const SizedBox(width: IoFlipSpacing.sm), Text('$name ($spacing)'), ], ), ); } }
io_flip/packages/io_flip_ui/gallery/lib/spacing/app_spacing_story.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/gallery/lib/spacing/app_spacing_story.dart', 'repo_id': 'io_flip', 'token_count': 1071}
import 'package:flutter/material.dart'; import 'package:gallery/story_scaffold.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; class ResponsiveLayoutStory extends StatelessWidget { const ResponsiveLayoutStory({super.key}); @override Widget build(BuildContext context) { return StoryScaffold( title: 'Responsive Layout', body: ResponsiveLayoutBuilder( small: (_, __) => const Center( child: Text( 'Small Layout\nResize the window to see the large layout', style: TextStyle(color: IoFlipColors.seedLightBlue), textAlign: TextAlign.center, ), ), large: (_, __) => const Center( child: Text( 'Large Layout\nResize the window to see the small layout', style: TextStyle(color: IoFlipColors.seedGold), textAlign: TextAlign.center, ), ), ), ); } }
io_flip/packages/io_flip_ui/gallery/lib/widgets/responsive_layout_story.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/gallery/lib/widgets/responsive_layout_story.dart', 'repo_id': 'io_flip', 'token_count': 404}
import 'package:flutter/animation.dart'; import 'package:flutter/rendering.dart'; /// {@template card_animation} /// Used to set the animation properties of an animated card. /// {@endtemplate} class CardAnimation { /// {@macro card_animation} const CardAnimation({ required this.animatable, required this.duration, this.curve = Curves.linear, this.flipsCard = false, }); /// The animation to be used. final Animatable<Matrix4> animatable; /// The duration of the animation. final Duration duration; /// The curve of the animation. Defaults to [Curves.linear]. final Curve curve; /// Whether this animation causes the card to flip. final bool flipsCard; }
io_flip/packages/io_flip_ui/lib/src/animations/card_animation.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/lib/src/animations/card_animation.dart', 'repo_id': 'io_flip', 'token_count': 211}
import 'dart:ui'; /// Card sizes used in the I/O FLIP UI. abstract class IoFlipCardSizes { /// xxs card size static const Size xxs = Size(54, 72); /// xs card size static const Size xs = Size(103, 137); /// sm card size static const Size sm = Size(139, 185); /// md card size static const Size md = Size(175, 233); /// lg card size static const Size lg = Size(224, 298); /// xl card size static const Size xl = Size(275, 366); /// xxl card size static const Size xxl = Size(327, 435); }
io_flip/packages/io_flip_ui/lib/src/theme/io_flip_card_sizes.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/lib/src/theme/io_flip_card_sizes.dart', 'repo_id': 'io_flip', 'token_count': 179}
export 'charge_back.dart'; export 'charge_front.dart'; export 'damage_receive.dart'; export 'damage_send.dart'; export 'victory_charge_back.dart'; export 'victory_charge_front.dart';
io_flip/packages/io_flip_ui/lib/src/widgets/damages/damages.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/lib/src/widgets/damages/damages.dart', 'repo_id': 'io_flip', 'token_count': 67}
import 'package:flutter/widgets.dart'; /// Signature for callbacks that are to receive and return a value /// of the same type. typedef ValueUpdater<T> = T Function(T current); /// {@template simple_flow} /// A flow-builder like stepper widget that allows to build a flow of steps /// in a form. /// {@endtemplate} class SimpleFlow<T> extends StatefulWidget { /// {@macro simple_flow} const SimpleFlow({ required this.initialData, required this.onComplete, required this.stepBuilder, super.key, this.child, }); /// Get a [SimpleFlowState] from the [BuildContext]. static SimpleFlowState<T> of<T>(BuildContext context) { final result = context.getInheritedWidgetOfExactType<_SimpleFlowInherited<T>>(); assert(result != null, 'No ${_SimpleFlowInherited<T>} found in context'); return result!.state; } /// The initial data to be used in the flow. final ValueGetter<T> initialData; /// Called when the flow is marked as completed. final ValueChanged<T> onComplete; /// The builder for each step of the flow. final ValueWidgetBuilder<T> stepBuilder; /// Optional child widget to be passed to [stepBuilder]. final Widget? child; @override State<SimpleFlow<T>> createState() => _SimpleFlowState<T>(); } /// Public interface to manipulate the simple flow widget state. abstract class SimpleFlowState<T> { /// Update the current data. void update(ValueUpdater<T> updater); /// Mark the flow as completed. void complete(ValueUpdater<T> updater); } class _SimpleFlowState<T> extends State<SimpleFlow<T>> implements SimpleFlowState<T> { late T data; @override void initState() { super.initState(); data = widget.initialData(); } @override void complete(ValueUpdater<T> updater) { setState(() { data = updater(data); widget.onComplete(data); }); } @override void update(ValueUpdater<T> updater) { setState(() { data = updater(data); }); } @override Widget build(BuildContext context) { return _SimpleFlowInherited<T>( state: this, child: Builder( builder: (context) { return widget.stepBuilder(context, data, widget.child); }, ), ); } } class _SimpleFlowInherited<T> extends InheritedWidget { const _SimpleFlowInherited({ required super.child, required this.state, }); final SimpleFlowState<T> state; @override bool updateShouldNotify(_SimpleFlowInherited<T> old) { return false; } } /// Adds utility methods to [BuildContext] to manipulate the simple flow widget. extension SimpleFlowContext on BuildContext { /// Update the current data. void updateFlow<T>(ValueUpdater<T> updater) { SimpleFlow.of<T>(this).update(updater); } /// Mark the flow as completed. void completeFlow<T>(ValueUpdater<T> updater) { SimpleFlow.of<T>(this).complete(updater); } }
io_flip/packages/io_flip_ui/lib/src/widgets/simple_flow.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/lib/src/widgets/simple_flow.dart', 'repo_id': 'io_flip', 'token_count': 1002}
import 'package:flame/cache.dart'; import 'package:flame/widgets.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:mocktail/mocktail.dart'; import 'package:provider/provider.dart'; class _MockImages extends Mock implements Images {} void main() { group('ChargeBack', () { late Images images; setUp(() { images = _MockImages(); }); testWidgets('renders SpriteAnimationWidget', (tester) async { await tester.pumpWidget( Directionality( textDirection: TextDirection.ltr, child: Provider.value( value: images, child: const ChargeBack( '', size: GameCardSize.md(), assetSize: AssetSize.large, animationColor: Colors.white, ), ), ), ); expect(find.byType(SpriteAnimationWidget), findsOneWidget); }); }); }
io_flip/packages/io_flip_ui/test/src/widgets/damages/charge_back_test.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/test/src/widgets/damages/charge_back_test.dart', 'repo_id': 'io_flip', 'token_count': 440}
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; void main() { group('IoFlipScaffold', () { testWidgets('renders correctly', (tester) async { await tester.pumpWidget( MaterialApp( home: IoFlipScaffold( body: Center(child: Text('Test')), ), ), ); expect( find.byType(IoFlipScaffold), findsOneWidget, ); }); }); }
io_flip/packages/io_flip_ui/test/src/widgets/io_flip_scaffold_test.dart/0
{'file_path': 'io_flip/packages/io_flip_ui/test/src/widgets/io_flip_scaffold_test.dart', 'repo_id': 'io_flip', 'token_count': 259}
name: match_maker_repository description: Repository for match making. version: 0.1.0+1 publish_to: none environment: sdk: ">=3.0.0 <4.0.0" flutter: ">=3.10.0" dependencies: cloud_firestore: ^4.4.3 equatable: ^2.0.5 flutter: sdk: flutter game_domain: path: ../../api/packages/game_domain uuid: ^3.0.7 dev_dependencies: flutter_test: sdk: flutter mocktail: ^0.3.0 very_good_analysis: ^4.0.0
io_flip/packages/match_maker_repository/pubspec.yaml/0
{'file_path': 'io_flip/packages/match_maker_repository/pubspec.yaml', 'repo_id': 'io_flip', 'token_count': 198}
import 'dart:async'; import 'package:bloc_test/bloc_test.dart'; import 'package:connection_repository/connection_repository.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/connection/connection.dart'; import 'package:mocktail/mocktail.dart'; class _MockConnectionRepository extends Mock implements ConnectionRepository {} void main() { group('ConnectionBloc', () { late ConnectionRepository connectionRepository; late StreamController<WebSocketMessage> messageController; setUp(() { connectionRepository = _MockConnectionRepository(); messageController = StreamController<WebSocketMessage>(); when(() => connectionRepository.messages) .thenAnswer((_) => messageController.stream); }); group('on ConnectionRequested', () { blocTest<ConnectionBloc, ConnectionState>( 'emits ConnectionInProgress when connection is successful', setUp: () { when(() => connectionRepository.connect()).thenAnswer((_) async {}); }, build: () => ConnectionBloc(connectionRepository: connectionRepository), act: (bloc) => bloc.add(const ConnectionRequested()), expect: () => [ const ConnectionInProgress(), ], verify: (_) { verify(() => connectionRepository.connect()).called(1); verify(() => connectionRepository.messages).called(1); }, ); blocTest<ConnectionBloc, ConnectionState>( 'emits [ConnectionInProgress, ConnectionSuccessful] when connection is ' 'successful and a connected message is received', setUp: () { when(() => connectionRepository.connect()).thenAnswer((_) async {}); messageController.onListen = () { messageController.add(const WebSocketMessage.connected()); }; }, build: () => ConnectionBloc(connectionRepository: connectionRepository), act: (bloc) => bloc.add(const ConnectionRequested()), expect: () => [ const ConnectionInProgress(), const ConnectionSuccess(), ], verify: (_) { verify(() => connectionRepository.connect()).called(1); verify(() => connectionRepository.messages).called(1); }, ); blocTest<ConnectionBloc, ConnectionState>( 'emits [ConnectionInProgress, ConnectionFailure] when connection is ' 'successful and an error message is received', setUp: () { when(() => connectionRepository.connect()).thenAnswer((_) async {}); messageController.onListen = () { messageController.add( WebSocketMessage.error(WebSocketErrorCode.playerAlreadyConnected), ); }; }, build: () => ConnectionBloc(connectionRepository: connectionRepository), act: (bloc) => bloc.add(const ConnectionRequested()), expect: () => [ const ConnectionInProgress(), const ConnectionFailure(WebSocketErrorCode.playerAlreadyConnected), ], verify: (_) { verify(() => connectionRepository.connect()).called(1); verify(() => connectionRepository.messages).called(1); }, ); blocTest<ConnectionBloc, ConnectionState>( 'emits ConnectionInitial when messages stream is closed', setUp: () { when(() => connectionRepository.connect()).thenAnswer((_) async {}); messageController.onListen = () { messageController.close(); }; }, build: () => ConnectionBloc(connectionRepository: connectionRepository), act: (bloc) => bloc.add(const ConnectionRequested()), expect: () => [ const ConnectionInProgress(), const ConnectionInitial(), ], verify: (_) { verify(() => connectionRepository.connect()).called(1); verify(() => connectionRepository.messages).called(1); }, ); blocTest<ConnectionBloc, ConnectionState>( 'emits [ConnectionInProgress, ConnectionFailure] ' 'when connection is not successful', setUp: () { when(() => connectionRepository.connect()).thenThrow(Exception()); }, build: () => ConnectionBloc(connectionRepository: connectionRepository), act: (bloc) => bloc.add(const ConnectionRequested()), expect: () => [ const ConnectionInProgress(), const ConnectionFailure(WebSocketErrorCode.unknown), ], verify: (_) { verify(() => connectionRepository.connect()).called(1); }, errors: () => [ isA<Exception>(), ], ); }); }); }
io_flip/test/connection/bloc/connection_bloc_test.dart/0
{'file_path': 'io_flip/test/connection/bloc/connection_bloc_test.dart', 'repo_id': 'io_flip', 'token_count': 1869}
// ignore_for_file: prefer_const_constructors import 'dart:async'; import 'package:api_client/api_client.dart'; 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:game_script_machine/game_script_machine.dart'; import 'package:go_router/go_router.dart'; import 'package:io_flip/audio/audio_controller.dart'; import 'package:io_flip/game/game.dart'; import 'package:io_flip/gen/assets.gen.dart'; import 'package:io_flip/leaderboard/leaderboard.dart'; import 'package:io_flip/match_making/views/match_making_page.dart'; import 'package:io_flip/settings/settings_controller.dart'; import 'package:io_flip_ui/io_flip_ui.dart'; import 'package:mocktail/mocktail.dart'; import 'package:mocktail_image_network/mocktail_image_network.dart'; import '../../helpers/helpers.dart'; class _MockSettingsController extends Mock implements SettingsController {} class _MockGameBloc extends Mock implements GameBloc {} class _MockLeaderboardResource extends Mock implements LeaderboardResource {} class _MockAudioController extends Mock implements AudioController {} class _MockGameScriptMachine extends Mock implements GameScriptMachine {} class _FakeGameState extends Fake implements GameState {} void main() { group('GameView', () { late GameBloc bloc; late LeaderboardResource leaderboardResource; const playerCards = [ Card( id: 'player_card', name: 'host_card', description: '', image: '', rarity: true, power: 2, suit: Suit.air, ), Card( id: 'player_card_2', name: 'host_card_2', description: '', image: '', rarity: true, power: 2, suit: Suit.air, ), ]; const opponentCards = [ Card( id: 'opponent_card', name: 'guest_card', description: '', image: '', rarity: true, power: 1, suit: Suit.air, ), Card( id: 'opponent_card_2', name: 'guest_card', description: '', image: '', rarity: true, power: 1, suit: Suit.air, ), ]; final deck = Deck(id: '', userId: '', cards: playerCards); setUpAll(() { registerFallbackValue( Card( id: '', name: '', description: '', image: '', power: 0, rarity: false, suit: Suit.air, ), ); registerFallbackValue(_FakeGameState()); }); setUp(() { bloc = _MockGameBloc(); when(() => bloc.isHost).thenReturn(true); when(() => bloc.isWinningCard(any(), isPlayer: any(named: 'isPlayer'))) .thenReturn(null); when(() => bloc.canPlayerPlay(any())).thenReturn(true); when(() => bloc.isPlayerAllowedToPlay).thenReturn(true); when(() => bloc.matchCompleted(any())).thenReturn(false); when(() => bloc.playerDeck).thenReturn(deck); leaderboardResource = _MockLeaderboardResource(); when(() => leaderboardResource.getInitialsBlacklist()) .thenAnswer((_) async => ['WTF']); }); void mockState(GameState state) { whenListen( bloc, Stream.value(state), initialState: state, ); } testWidgets('renders a loading when on initial state', (tester) async { mockState(MatchLoadingState()); await tester.pumpSubject(bloc); expect(find.byType(CircularProgressIndicator), findsOneWidget); }); testWidgets( 'renders an error message when failed and navigates to match making', (tester) async { final goRouter = MockGoRouter(); mockState(MatchLoadFailedState(deck: deck)); await tester.pumpSubject( bloc, goRouter: goRouter, ); expect(find.text('Unable to join game!'), findsOneWidget); await tester.tap(find.byType(RoundedButton)); await tester.pumpAndSettle(); verify( () => goRouter.goNamed( 'match_making', extra: MatchMakingPageData( deck: deck, ), ), ).called(1); }, ); testWidgets( 'renders an error message when failed and navigates to home ' 'if deck not available', (tester) async { final goRouter = MockGoRouter(); mockState(MatchLoadFailedState(deck: null)); await tester.pumpSubject( bloc, goRouter: goRouter, ); expect(find.text('Unable to join game!'), findsOneWidget); await tester.tap(find.byType(RoundedButton)); await tester.pumpAndSettle(); verify(() => goRouter.go('/')).called(1); }, ); group('Gameplay', () { final baseState = MatchLoadedState( playerScoreCard: ScoreCard(id: 'scoreCardId'), match: Match( id: '', hostDeck: Deck(id: '', userId: '', cards: playerCards), guestDeck: Deck(id: '', userId: '', cards: opponentCards), ), matchState: MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], ), rounds: const [], turnTimeRemaining: 10, turnAnimationsFinished: true, isClashScene: false, showCardLanding: false, ); setUp(() { when(() => bloc.playerCards).thenReturn(playerCards); when(() => bloc.opponentCards).thenReturn(opponentCards); }); testWidgets('preloads opponent cards when game starts', (tester) async { whenListen( bloc, Stream.fromIterable([MatchLoadingState(), baseState]), initialState: MatchLoadingState(), ); await tester.pumpSubject(bloc); for (final card in opponentCards) { expect(imageCache.containsKey(NetworkImage(card.image)), isTrue); } }); testWidgets('renders the game in its initial state', (tester) async { mockState(baseState); await tester.pumpSubject(bloc); expect( find.byKey(const Key('opponent_hidden_card_opponent_card')), findsOneWidget, ); expect( find.byKey(const Key('player_card_player_card')), findsOneWidget, ); }); testWidgets( 'renders leaderboard entry view when state is LeaderboardEntryState', (tester) async { mockState(LeaderboardEntryState('scoreCardId')); await tester.pumpSubject( bloc, leaderboardResource: leaderboardResource, ); expect(find.byType(LeaderboardEntryView), findsOneWidget); }, ); testWidgets( 'renders the opponent absent message when the opponent leaves', (tester) async { mockState(OpponentAbsentState(deck: deck)); await tester.pumpSubject(bloc); expect( find.text('Opponent left the game!'), findsOneWidget, ); expect( find.widgetWithText(RoundedButton, 'PLAY AGAIN'), findsOneWidget, ); }, ); testWidgets( 'goes to match making when the replay button is tapped ' 'on opponent absent', (tester) async { final goRouter = MockGoRouter(); mockState(OpponentAbsentState(deck: deck)); await tester.pumpSubject( bloc, goRouter: goRouter, ); await tester.tap(find.byType(RoundedButton)); await tester.pumpAndSettle(); verify( () => goRouter.goNamed( 'match_making', extra: MatchMakingPageData( deck: deck, ), ), ).called(1); }, ); testWidgets( 'goes to home when the replay button is tapped on opponent absent ' 'and no deck is available', (tester) async { final goRouter = MockGoRouter(); mockState(OpponentAbsentState(deck: null)); await tester.pumpSubject( bloc, goRouter: goRouter, ); await tester.tap(find.byType(RoundedButton)); await tester.pumpAndSettle(); verify(() => goRouter.go('/')).called(1); }, ); testWidgets( 'plays a player card on tap', (tester) async { final audioController = _MockAudioController(); mockState(baseState); await tester.pumpSubject(bloc, audioController: audioController); await tester.tap(find.byKey(const Key('player_card_player_card'))); verify(() => audioController.playSfx(Assets.sfx.cardMovement)) .called(1); verify(() => bloc.add(PlayerPlayed('player_card'))).called(1); }, ); testWidgets( "can't play a card that was already played", (tester) async { mockState(baseState); when(() => bloc.canPlayerPlay('player_card')).thenReturn(false); await tester.pumpSubject(bloc); await tester.tap(find.byKey(const Key('player_card_player_card'))); verifyNever(() => bloc.add(PlayerPlayed('player_card'))); }, ); testWidgets( "can't play when it is not the player turn", (tester) async { when(() => bloc.canPlayerPlay(any())).thenReturn(false); mockState( baseState.copyWith( rounds: [ MatchRound( playerCardId: 'player_card', opponentCardId: null, ) ], ), ); await tester.pumpSubject(bloc); await tester.tap(find.byKey(const Key('player_card_player_card_2'))); verifyNever(() => bloc.add(PlayerPlayed('player_card_2'))); }, ); testWidgets( 'plays a player card when dragged', (tester) async { final audioController = _MockAudioController(); mockState(baseState); await tester.pumpSubject(bloc, audioController: audioController); final start = tester .getCenter(find.byKey(const Key('player_card_player_card'))); final end = tester.getCenter(find.byKey(const Key('clash_card_1'))); await tester.dragFrom(start, end - start); await tester.pumpAndSettle(); verify(() => audioController.playSfx(Assets.sfx.cardMovement)) .called(1); verify(() => bloc.add(PlayerPlayed('player_card'))).called(1); }, ); testWidgets( 'dragging a player card not to the correct spot does not play it', (tester) async { mockState(baseState); await tester.pumpSubject(bloc); final start = tester .getCenter(find.byKey(const Key('player_card_player_card'))); final end = tester.getCenter(find.byKey(const Key('clash_card_0'))); await tester.dragFrom(start, end - start); await tester.pumpAndSettle(); verifyNever(() => bloc.add(PlayerPlayed('player_card'))); }, ); testWidgets( 'dragging a player card moves it with the pointer', (tester) async { mockState(baseState); await tester.pumpSubject(bloc); Rect getClashRect() => tester.getRect(find.byKey(const Key('clash_card_1'))); Offset getPlayerCenter() => tester.getCenter( find.byKey(const Key('player_card_player_card')), ); final startClashRect = getClashRect(); final start = getPlayerCenter(); final end = getClashRect().center; final offset = end - start; final gesture = await tester.startGesture(start); await gesture.moveBy(Offset(kDragSlopDefault, -kDragSlopDefault)); await gesture.moveBy( Offset( offset.dx - kDragSlopDefault, offset.dy + kDragSlopDefault, ), ); await tester.pump(); await tester.pump(const Duration(milliseconds: 200)); expect(getClashRect().contains(getPlayerCenter()), isTrue); expect(getClashRect(), equals(startClashRect.inflate(8))); }, ); testWidgets( 'render the opponent card instantly when played', (tester) async { mockState( baseState.copyWith( rounds: [ MatchRound( playerCardId: 'player_card', opponentCardId: 'opponent_card', ) ], ), ); await tester.pumpSubject(bloc); expect( find.byKey(const Key('opponent_revealed_card_opponent_card')), findsOneWidget, ); expect( find.byKey(const Key('player_card_player_card')), findsOneWidget, ); }, ); testWidgets( 'shows an initially played opponent card in the clash area', (tester) async { mockState( baseState.copyWith( rounds: [ MatchRound( playerCardId: null, opponentCardId: 'opponent_card', ), ], ), ); await tester.pumpSubject(bloc); Rect getClashRect() => tester.getRect(find.byKey(const Key('clash_card_0'))); Rect getOpponentCardRect() => tester.getRect( find.byKey(const Key('opponent_card_opponent_card')), ); await tester.pumpAndSettle(); expect(getClashRect(), equals(getOpponentCardRect())); }, ); testWidgets( 'does not move opponent card until after clash scene ends', (tester) async { final gameScriptMachine = _MockGameScriptMachine(); when( () => gameScriptMachine.compare( playerCards.first, opponentCards.first, ), ).thenReturn(0); when( () => gameScriptMachine.compareSuits( playerCards.first.suit, opponentCards.first.suit, ), ).thenReturn(0); final controller = StreamController<GameState>(); whenListen(bloc, controller.stream, initialState: baseState); when(() => bloc.clashSceneOpponentCard) .thenReturn(opponentCards.first); when(() => bloc.clashScenePlayerCard).thenReturn(playerCards.first); await tester.pumpSubject( bloc, gameScriptMachine: gameScriptMachine, ); controller.add( baseState.copyWith( lastPlayedCardId: 'opponent_card', rounds: [ MatchRound( playerCardId: null, opponentCardId: 'opponent_card', ), ], ), ); await tester.pumpAndSettle(); controller.add( baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: 'opponent_card', ), ], ), ); await tester.pumpAndSettle(); controller.add( baseState.copyWith( isClashScene: true, lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: 'opponent_card', ), ], ), ); await tester.pumpAndSettle(); Rect getClashRect() => tester.getRect(find.byKey(const Key('clash_card_0'))); Rect getOpponentCardRect() => tester.getRect( find.byKey(const Key('opponent_card_opponent_card_2')), ); await tester.pumpAndSettle(); expect(getOpponentCardRect(), isNot(equals(getClashRect()))); controller.add( baseState.copyWith( lastPlayedCardId: 'opponent_card_2', isClashScene: true, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: 'opponent_card', ), MatchRound( playerCardId: null, opponentCardId: 'opponent_card_2', ), ], ), ); await tester.pump(); tester.widget<ClashScene>(find.byType(ClashScene)).onFinished(); controller.add( baseState.copyWith( lastPlayedCardId: 'opponent_card_2', isClashScene: false, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: 'opponent_card', ), MatchRound( playerCardId: null, opponentCardId: 'opponent_card_2', ), ], ), ); await tester.pump(turnEndDuration); await tester.pumpAndSettle(); expect(getOpponentCardRect(), equals(getClashRect())); }, ); testWidgets( 'render the win overlay on the player winning card', (tester) async { when( () => bloc.isWinningCard( Card( id: 'player_card', name: 'host_card', description: '', image: '', rarity: true, power: 2, suit: Suit.air, ), isPlayer: true, ), ).thenReturn(CardOverlayType.win); mockState( baseState.copyWith( rounds: [ MatchRound( playerCardId: 'player_card', opponentCardId: 'opponent_card', showCardsOverlay: true, ) ], ), ); await tester.pumpSubject(bloc); expect( find.byKey(const Key('win_card_overlay')), findsOneWidget, ); }, ); testWidgets( 'render the win overlay on the opponent winning card', (tester) async { when( () => bloc.isWinningCard( any(), isPlayer: false, ), ).thenReturn(CardOverlayType.win); mockState( baseState.copyWith( match: Match( id: '', hostDeck: baseState.match.hostDeck, guestDeck: Deck( id: '', userId: '', cards: const [ Card( id: 'opponent_card', name: 'guest_card', description: '', image: '', rarity: true, power: 10, suit: Suit.air, ), ], ), ), rounds: [ MatchRound( playerCardId: 'player_card', opponentCardId: 'opponent_card', showCardsOverlay: true, ) ], ), ); await tester.pumpSubject(bloc); expect( find.byKey(const Key('win_card_overlay')), findsOneWidget, ); }, ); }); group('Card animation', () { late GameScriptMachine gameScriptMachine; final baseState = MatchLoadedState( playerScoreCard: ScoreCard(id: 'scoreCardId'), match: Match( id: '', hostDeck: Deck(id: '', userId: '', cards: playerCards), guestDeck: Deck(id: '', userId: '', cards: opponentCards), ), matchState: MatchState( id: '', matchId: '', guestPlayedCards: const [], hostPlayedCards: const [], ), rounds: const [], turnTimeRemaining: 10, turnAnimationsFinished: true, isClashScene: false, showCardLanding: false, ); setUp(() { gameScriptMachine = _MockGameScriptMachine(); when( () => gameScriptMachine.compare( playerCards.first, opponentCards.first, ), ).thenReturn(0); when( () => gameScriptMachine.compareSuits( playerCards.first.suit, opponentCards.first.suit, ), ).thenReturn(0); when(() => bloc.playerCards).thenReturn(playerCards); when(() => bloc.opponentCards).thenReturn(opponentCards); when(() => bloc.clashScenePlayerCard).thenReturn(playerCards.first); when(() => bloc.clashSceneOpponentCard).thenReturn(opponentCards.first); }); testWidgets('starts when player plays a card', (tester) async { whenListen( bloc, Stream.fromIterable([ baseState, baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: null, ) ], ) ]), initialState: baseState, ); await tester.pumpSubject(bloc); final cardFinder = find.byKey(Key('player_card_${playerCards.first.id}')); final initialOffset = tester.getCenter(cardFinder); await tester.pumpAndSettle(); final finalOffset = tester.getCenter(cardFinder); expect( initialOffset, isNot(equals(finalOffset)), ); }); testWidgets('starts when opponent plays a card', (tester) async { whenListen( bloc, Stream.fromIterable([ baseState, baseState.copyWith( lastPlayedCardId: opponentCards.first.id, rounds: [ MatchRound( playerCardId: null, opponentCardId: opponentCards.first.id, ) ], ) ]), initialState: baseState, ); await tester.pumpSubject(bloc); final cardFinder = find.byKey(Key('opponent_card_${opponentCards.first.id}')); final initialOffset = tester.getCenter(cardFinder); await tester.pumpAndSettle(); final finalOffset = tester.getCenter(cardFinder); expect( initialOffset, isNot(equals(finalOffset)), ); }); testWidgets('completes when both players play a card', (tester) async { final controller = StreamController<GameState>(); final playedState = baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: opponentCards.first.id, ) ], ); whenListen( bloc, controller.stream, initialState: baseState, ); when(() => bloc.add(CardLandingStarted())).thenAnswer((_) { controller.add(playedState.copyWith(showCardLanding: true)); }); await tester.pumpSubject(bloc); controller ..add(baseState) ..add(playedState); await tester.pumpAndSettle(); controller.add(playedState.copyWith(showCardLanding: false)); await tester.pumpAndSettle(); verify(() => bloc.add(ClashSceneStarted())).called(1); }); testWidgets( 'completes and goes back when both players play a card and ' 'clash scene finishes, plays round lost sfx', (tester) async { final controller = StreamController<GameState>.broadcast(); final audioController = _MockAudioController(); when(() => bloc.isWinningCard(playerCards.first, isPlayer: true)) .thenReturn(CardOverlayType.lose); whenListen( bloc, controller.stream, initialState: baseState, ); await tester.pumpSubject( bloc, audioController: audioController, gameScriptMachine: gameScriptMachine, ); final playerCardFinder = find.byKey(Key('player_card_${playerCards.first.id}')); final opponentCardFinder = find.byKey(Key('opponent_card_${opponentCards.first.id}')); // Get card offset before moving final playerInitialOffset = tester.getCenter(playerCardFinder); final opponentInitialOffset = tester.getCenter(opponentCardFinder); controller.add( baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: null, ) ], ), ); // Get card offset after both players play and cards are in the clash // zone await tester.pumpAndSettle(); final playerClashOffset = tester.getCenter(playerCardFinder); expect(playerClashOffset, isNot(equals(playerInitialOffset))); controller.add( baseState.copyWith( lastPlayedCardId: opponentCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: opponentCards.first.id, ) ], ), ); await tester.pump(); await tester.pump(); await tester.pump(Duration(milliseconds: 400)); final opponentClashOffset = tester.getCenter(opponentCardFinder); expect(opponentClashOffset, isNot(equals(opponentInitialOffset))); controller.add(baseState.copyWith(isClashScene: true)); await tester.pumpAndSettle(); final clashScene = find.byType(ClashScene); expect(clashScene, findsOneWidget); tester.widget<ClashScene>(clashScene).onFinished(); controller.add(baseState.copyWith(isClashScene: false)); // Get card offset once clash is over and both cards are back in the // original position await tester.pump(turnEndDuration); await tester.pumpAndSettle(); final playerFinalOffset = tester.getCenter(playerCardFinder); final opponentFinalOffset = tester.getCenter(opponentCardFinder); expect(playerFinalOffset, equals(playerInitialOffset)); expect(opponentFinalOffset, equals(opponentInitialOffset)); verify(() => audioController.playSfx(Assets.sfx.lostMatch)).called(1); verify(() => bloc.add(ClashSceneStarted())).called(1); verify(() => bloc.add(ClashSceneCompleted())).called(1); verify(() => bloc.add(TurnAnimationsFinished())).called(1); verify(() => bloc.add(TurnTimerStarted())).called(1); }, ); testWidgets( 'completes and goes back when both players play a card and ' 'clash scene finishes, plays round win sfx', (tester) async { final controller = StreamController<GameState>.broadcast(); final audioController = _MockAudioController(); when(() => bloc.isWinningCard(playerCards.first, isPlayer: true)) .thenReturn(CardOverlayType.win); whenListen( bloc, controller.stream, initialState: baseState, ); await tester.pumpSubject( bloc, audioController: audioController, gameScriptMachine: gameScriptMachine, ); final playerCardFinder = find.byKey(Key('player_card_${playerCards.first.id}')); final opponentCardFinder = find.byKey(Key('opponent_card_${opponentCards.first.id}')); // Get card offset before moving final playerInitialOffset = tester.getCenter(playerCardFinder); final opponentInitialOffset = tester.getCenter(opponentCardFinder); controller.add( baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: null, ) ], ), ); // Get card offset after both players play and cards are in the clash // zone await tester.pumpAndSettle(); final playerClashOffset = tester.getCenter(playerCardFinder); expect(playerClashOffset, isNot(equals(playerInitialOffset))); controller.add( baseState.copyWith( lastPlayedCardId: opponentCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: opponentCards.first.id, ) ], ), ); await tester.pump(); await tester.pump(); await tester.pump(Duration(milliseconds: 400)); final opponentClashOffset = tester.getCenter(opponentCardFinder); expect(opponentClashOffset, isNot(equals(opponentInitialOffset))); controller.add(baseState.copyWith(isClashScene: true)); await tester.pumpAndSettle(); final clashScene = find.byType(ClashScene); expect(clashScene, findsOneWidget); tester.widget<ClashScene>(clashScene).onFinished(); controller.add(baseState.copyWith(isClashScene: false)); // Get card offset once clash is over and both cards are back in the // original position await tester.pump(turnEndDuration); await tester.pumpAndSettle(); final playerFinalOffset = tester.getCenter(playerCardFinder); final opponentFinalOffset = tester.getCenter(opponentCardFinder); expect(playerFinalOffset, equals(playerInitialOffset)); expect(opponentFinalOffset, equals(opponentInitialOffset)); verify(() => audioController.playSfx(Assets.sfx.winMatch)).called(1); verify(() => bloc.add(ClashSceneStarted())).called(1); verify(() => bloc.add(ClashSceneCompleted())).called(1); verify(() => bloc.add(TurnAnimationsFinished())).called(1); verify(() => bloc.add(TurnTimerStarted())).called(1); }, ); testWidgets( 'completes and shows card landing puff effect when player plays a card', (tester) async { whenListen( bloc, Stream.fromIterable([ baseState, baseState.copyWith( lastPlayedCardId: playerCards.first.id, rounds: [ MatchRound( playerCardId: playerCards.first.id, opponentCardId: null, ), ], showCardLanding: true, ), ]), initialState: baseState, ); await tester.pumpSubject(bloc); await tester.pump(bigFlipAnimation.duration); final cardLandingPuff = find.byType(CardLandingPuff); expect(cardLandingPuff, findsOneWidget); await tester.pumpAndSettle( bigFlipAnimation.duration + CardLandingPuff.duration, ); tester.widget<CardLandingPuff>(cardLandingPuff).onComplete?.call(); verify(() => bloc.add(CardLandingStarted())).called(1); verify(() => bloc.add(CardLandingCompleted())).called(1); }, ); }); }); group('CrossPainter', () { test('shouldRepaint always returns false', () { final painter = CrossPainter(); expect(painter.shouldRepaint(CrossPainter()), isFalse); }); }); } extension GameViewTest on WidgetTester { Future<void> pumpSubject( GameBloc bloc, { GoRouter? goRouter, LeaderboardResource? leaderboardResource, AudioController? audioController, GameScriptMachine? gameScriptMachine, }) { final SettingsController settingsController = _MockSettingsController(); when(() => settingsController.muted).thenReturn(ValueNotifier(true)); return mockNetworkImages(() { return pumpApp( BlocProvider<GameBloc>.value( value: bloc, child: GameView(), ), router: goRouter, settingsController: settingsController, leaderboardResource: leaderboardResource, audioController: audioController, gameScriptMachine: gameScriptMachine, ); }); } }
io_flip/test/game/views/game_view_test.dart/0
{'file_path': 'io_flip/test/game/views/game_view_test.dart', 'repo_id': 'io_flip', 'token_count': 16689}
import 'package:api_client/api_client.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart' as gd; import 'package:io_flip/leaderboard/leaderboard.dart'; import 'package:mocktail/mocktail.dart'; class _MockLeaderboardResource extends Mock implements LeaderboardResource {} void main() { const leaderboardPlayers = [ gd.LeaderboardPlayer( id: 'id', longestStreak: 1, initials: 'AAA', ), gd.LeaderboardPlayer( id: 'id2', longestStreak: 2, initials: 'BBB', ), ]; group('LeaderboardBloc', () { late LeaderboardResource leaderboardResource; setUp(() { leaderboardResource = _MockLeaderboardResource(); when(() => leaderboardResource.getLeaderboardResults()) .thenAnswer((_) async => leaderboardPlayers); }); group('LeaderboardRequested', () { blocTest<LeaderboardBloc, LeaderboardState>( 'can request a leaderboard', build: () => LeaderboardBloc( leaderboardResource: leaderboardResource, ), act: (bloc) => bloc.add(const LeaderboardRequested()), expect: () => const [ LeaderboardState( status: LeaderboardStateStatus.loading, leaderboard: [], ), LeaderboardState( status: LeaderboardStateStatus.loaded, leaderboard: leaderboardPlayers, ), ], ); blocTest<LeaderboardBloc, LeaderboardState>( 'emits failure when an error occured', setUp: () { when(() => leaderboardResource.getLeaderboardResults()) .thenThrow(Exception('oops')); }, build: () => LeaderboardBloc( leaderboardResource: leaderboardResource, ), act: (bloc) => bloc.add(const LeaderboardRequested()), expect: () => const [ LeaderboardState( status: LeaderboardStateStatus.loading, leaderboard: [], ), LeaderboardState( status: LeaderboardStateStatus.failed, leaderboard: [], ), ], ); }); }); }
io_flip/test/leaderboard/bloc/leaderboard_bloc_test.dart/0
{'file_path': 'io_flip/test/leaderboard/bloc/leaderboard_bloc_test.dart', 'repo_id': 'io_flip', 'token_count': 951}
// ignore_for_file: prefer_const_constructors import 'package:api_client/api_client.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:game_domain/game_domain.dart'; import 'package:io_flip/prompt/prompt.dart'; import 'package:mocktail/mocktail.dart'; class _MockPromptResource extends Mock implements PromptResource {} void main() { setUpAll(() { registerFallbackValue(PromptTermType.characterClass); }); group('PromptFormBloc', () { late PromptResource promptResource; const data = Prompt( characterClass: 'character', power: 'power', ); setUp(() { promptResource = _MockPromptResource(); }); blocTest<PromptFormBloc, PromptFormState>( 'emits state with prompts', setUp: () { when(() => promptResource.getPromptTerms(any())) .thenAnswer((_) async => ['test']); }, build: () => PromptFormBloc(promptResource: promptResource), seed: () => PromptFormState( status: PromptTermsStatus.loaded, prompts: Prompt(), ), act: (bloc) { bloc.add(PromptSubmitted(data: data)); }, expect: () => <PromptFormState>[ PromptFormState( status: PromptTermsStatus.loaded, prompts: data, ), ], ); blocTest<PromptFormBloc, PromptFormState>( 'emits state with error status', setUp: () { when(() => promptResource.getPromptTerms(any())) .thenThrow(Exception('Oops')); }, build: () => PromptFormBloc(promptResource: promptResource), act: (bloc) { bloc.add(PromptTermsRequested()); }, expect: () => <PromptFormState>[ PromptFormState( status: PromptTermsStatus.loading, prompts: Prompt(), ), PromptFormState( status: PromptTermsStatus.failed, prompts: Prompt(), ), ], ); }); }
io_flip/test/prompt/bloc/prompt_form_bloc_test.dart/0
{'file_path': 'io_flip/test/prompt/bloc/prompt_form_bloc_test.dart', 'repo_id': 'io_flip', 'token_count': 844}
import 'dart:typed_data'; import 'package:api_client/api_client.dart'; import 'package:bloc_test/bloc_test.dart'; import 'package:cross_file/cross_file.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:mocktail/mocktail.dart'; class _MockShareResource extends Mock implements ShareResource {} class _MockXFile extends Mock implements XFile {} void main() { final XFile file = _MockXFile(); const card = Card( id: '0', name: '', description: '', image: '', rarity: false, power: 20, suit: Suit.fire, ); const deck = Deck(id: 'id', userId: 'userId', cards: [card]); group('DownloadBloc', () { late ShareResource shareResource; setUp(() { shareResource = _MockShareResource(); when(() => shareResource.getShareCardImage(any())) .thenAnswer((_) async => Uint8List(8)); when(() => shareResource.getShareDeckImage(any())) .thenAnswer((_) async => Uint8List(8)); when(() => file.saveTo(any())).thenAnswer((_) async {}); }); group('Download Cards Requested', () { blocTest<DownloadBloc, DownloadState>( 'can request a Download', build: () => DownloadBloc( shareResource: shareResource, parseBytes: (bytes, {String? mimeType, String? name}) { return file; }, ), act: (bloc) => bloc.add( const DownloadCardsRequested(cards: [card]), ), expect: () => const [ DownloadState( status: DownloadStatus.loading, ), DownloadState( status: DownloadStatus.completed, ), ], ); blocTest<DownloadBloc, DownloadState>( 'emits failure when an error occurred', setUp: () { when(() => shareResource.getShareCardImage(any())) .thenThrow(Exception('oops')); }, build: () => DownloadBloc( shareResource: shareResource, ), act: (bloc) => bloc.add(const DownloadCardsRequested(cards: [card])), expect: () => const [ DownloadState( status: DownloadStatus.loading, ), DownloadState( status: DownloadStatus.failure, ), ], ); }); group('Download Deck Requested', () { blocTest<DownloadBloc, DownloadState>( 'can request a Download', build: () => DownloadBloc( shareResource: shareResource, parseBytes: (bytes, {String? mimeType, String? name}) { return file; }, ), act: (bloc) => bloc.add( const DownloadDeckRequested(deck: deck), ), expect: () => const [ DownloadState( status: DownloadStatus.loading, ), DownloadState( status: DownloadStatus.completed, ), ], ); blocTest<DownloadBloc, DownloadState>( 'emits failure when an error occurred', setUp: () { when(() => shareResource.getShareDeckImage(any())) .thenThrow(Exception('oops')); }, build: () => DownloadBloc( shareResource: shareResource, ), act: (bloc) => bloc.add(const DownloadDeckRequested(deck: deck)), expect: () => const [ DownloadState( status: DownloadStatus.loading, ), DownloadState( status: DownloadStatus.failure, ), ], ); }); }); }
io_flip/test/share/bloc/download_bloc_test.dart/0
{'file_path': 'io_flip/test/share/bloc/download_bloc_test.dart', 'repo_id': 'io_flip', 'token_count': 1652}
// 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:json_annotation/json_annotation.dart'; part 'generic_response_class_example.g.dart'; // An example highlighting the problem outlined in // https://github.com/google/json_serializable.dart/issues/646 // https://github.com/google/json_serializable.dart/issues/671 @JsonSerializable(createToJson: false) class BaseResponse<T> { final int? status; final String? msg; @JsonKey(fromJson: _dataFromJson) final T? data; const BaseResponse({ this.status, this.msg, this.data, }); factory BaseResponse.fromJson(Map<String, dynamic> json) => _$BaseResponseFromJson(json); /// Decodes [json] by "inspecting" its contents. static T _dataFromJson<T>(Object json) { if (json is Map<String, dynamic>) { if (json.containsKey('email')) { return User.fromJson(json) as T; } if (json.containsKey('title')) { return Article.fromJson(json) as T; } } else if (json is List) { // NOTE: this logic assumes the ONLY valid value for a `List` in this case // is a List<Author>. If that assumption changes, then it will be // necessary to "peek" into non-empty lists to determine the type! return json .map((e) => Article.fromJson(e as Map<String, dynamic>)) .toList() as T; } throw ArgumentError.value( json, 'json', 'Cannot convert the provided data.', ); } } @JsonSerializable(createToJson: false) class Article { final int id; final String title; final User? author; final List<Comment>? comments; const Article({ required this.id, required this.title, this.author, this.comments, }); factory Article.fromJson(Map<String, dynamic> json) => _$ArticleFromJson(json); } @JsonSerializable(createToJson: false) class User { final int? id; final String? email; const User({ this.id, this.email, }); factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json); } @JsonSerializable(createToJson: false) class Comment { final String? content; final int? id; const Comment({ this.id, this.content, }); factory Comment.fromJson(Map<String, dynamic> json) => _$CommentFromJson(json); }
json_serializable/example/lib/generic_response_class_example.dart/0
{'file_path': 'json_serializable/example/lib/generic_response_class_example.dart', 'repo_id': 'json_serializable', 'token_count': 907}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'package:_json_serial_shared_test/shared_test.dart'; import 'package:example/tuple_example.dart'; import 'package:test/test.dart'; void main() { test('ConcreteClass', () { final instance = ConcreteClass( Tuple(1, DateTime.fromMillisecondsSinceEpoch(24).toUtc()), Tuple(const Duration(seconds: 42), BigInt.two), ); final encoded = loudEncode(instance); const expected = r''' { "tuple1": { "value1": 1, "value2": "1970-01-01T00:00:00.024Z" }, "tuple2": { "value1": 42000000, "value2": "2" } }'''; expect(encoded, expected); final decoded = ConcreteClass.fromJson( jsonDecode(encoded) as Map<String, dynamic>, ); final encoded2 = loudEncode(decoded); expect(encoded2, encoded); }); }
json_serializable/example/test/tuple_example_test.dart/0
{'file_path': 'json_serializable/example/test/tuple_example_test.dart', 'repo_id': 'json_serializable', 'token_count': 376}
# See https://github.com/google/mono_repo.dart for details on this file stages: - analyzer_and_format: - group: - format - analyze: --fatal-infos . sdk: dev - group: - analyze sdk: pubspec
json_serializable/json_annotation/mono_pkg.yaml/0
{'file_path': 'json_serializable/json_annotation/mono_pkg.yaml', 'repo_id': 'json_serializable', 'token_count': 90}
// 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/constant/value.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:json_annotation/json_annotation.dart'; import 'package:source_gen/source_gen.dart'; import 'package:source_helper/source_helper.dart'; import 'json_literal_generator.dart'; import 'utils.dart'; String constMapName(DartType targetType) => '_\$${targetType.element!.name}EnumMap'; /// If [targetType] is not an enum, return `null`. /// /// Otherwise, returns `true` if [targetType] is nullable OR if one of the /// encoded values of the enum is `null`. bool? enumFieldWithNullInEncodeMap(DartType targetType) { final enumMap = _enumMap(targetType); if (enumMap == null) return null; if (targetType.isNullableType) { return true; } return enumMap.values.contains(null); } String? enumValueMapFromType( DartType targetType, { bool nullWithNoAnnotation = false, }) { final enumMap = _enumMap(targetType, nullWithNoAnnotation: nullWithNoAnnotation); if (enumMap == null) return null; final items = enumMap.entries .map((e) => ' ${targetType.element!.name}.${e.key.name}: ' '${jsonLiteralAsDart(e.value)},') .join(); return 'const ${constMapName(targetType)} = {\n$items\n};'; } Map<FieldElement, Object?>? _enumMap( DartType targetType, { bool nullWithNoAnnotation = false, }) { final targetTypeElement = targetType.element; if (targetTypeElement == null) return null; final annotation = _jsonEnumChecker.firstAnnotationOf(targetTypeElement); final jsonEnum = _fromAnnotation(annotation); final enumFields = iterateEnumFields(targetType); if (enumFields == null || (nullWithNoAnnotation && !jsonEnum.alwaysCreate)) { return null; } return { for (var field in enumFields) field: _generateEntry( field: field, jsonEnum: jsonEnum, targetType: targetType, ), }; } Object? _generateEntry({ required FieldElement field, required JsonEnum jsonEnum, required DartType targetType, }) { final annotation = const TypeChecker.fromRuntime(JsonValue).firstAnnotationOfExact(field); if (annotation == null) { final valueField = jsonEnum.valueField; if (valueField != null) { // TODO: fieldRename is pointless here!!! At least log a warning! final fieldElementType = field.type.element as EnumElement; final e = fieldElementType.getField(valueField); if (e == null && valueField == 'index') { return fieldElementType.fields .where((element) => element.isEnumConstant) .toList(growable: false) .indexOf(field); } if (e == null || e.isStatic) { throw InvalidGenerationSourceError( '`JsonEnum.valueField` was set to "$valueField", but ' 'that is not a valid, instance field on ' '`${typeToCode(targetType)}`.', element: targetType.element, ); } final reader = ConstantReader(field.computeConstantValue()); final valueReader = reader.read(valueField); if (valueReader.validValueType) { return valueReader.literalValue; } else { throw InvalidGenerationSourceError( '`JsonEnum.valueField` was set to "$valueField", but ' 'that field does not have a type of String, int, or null.', element: targetType.element, ); } } else { return encodedFieldName(jsonEnum.fieldRename, field.name); } } else { final reader = ConstantReader(annotation); final valueReader = reader.read('value'); if (valueReader.validValueType) { return valueReader.literalValue; } else { final targetTypeCode = typeToCode(targetType); throw InvalidGenerationSourceError( 'The `JsonValue` annotation on `$targetTypeCode.${field.name}` does ' 'not have a value of type String, int, or null.', element: field, ); } } } const _jsonEnumChecker = TypeChecker.fromRuntime(JsonEnum); JsonEnum _fromAnnotation(DartObject? dartObject) { if (dartObject == null) { return const JsonEnum(); } final reader = ConstantReader(dartObject); return JsonEnum( alwaysCreate: reader.read('alwaysCreate').literalValue as bool, fieldRename: readEnum(reader.read('fieldRename'), FieldRename.values)!, valueField: reader.read('valueField').literalValue as String?, ); } extension on ConstantReader { bool get validValueType => isString || isNull || isInt; }
json_serializable/json_serializable/lib/src/enum_utils.dart/0
{'file_path': 'json_serializable/json_serializable/lib/src/enum_utils.dart', 'repo_id': 'json_serializable', 'token_count': 1753}
// 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/type.dart'; import 'package:source_helper/source_helper.dart'; import '../lambda_result.dart'; import '../type_helper.dart'; /// Information used by [ConvertHelper] when handling `JsonKey`-annotated /// fields with `toJson` or `fromJson` values set. class ConvertData { final String name; final DartType paramType; final DartType returnType; ConvertData(this.name, this.paramType, this.returnType); } abstract class TypeHelperContextWithConvert extends TypeHelperContext { ConvertData? get serializeConvertData; ConvertData? get deserializeConvertData; } /// Handles `JsonKey`-annotated fields with `toJson` or `fromJson` values set. class ConvertHelper extends TypeHelper<TypeHelperContextWithConvert> { const ConvertHelper(); @override Object? serialize( DartType targetType, String expression, TypeHelperContextWithConvert context, ) { final toJsonData = context.serializeConvertData; if (toJsonData == null) { return null; } assert(toJsonData.paramType is TypeParameterType || targetType.isAssignableTo(toJsonData.paramType)); return LambdaResult(expression, toJsonData.name); } @override Object? deserialize( DartType targetType, String expression, TypeHelperContextWithConvert context, bool defaultProvided, ) { final fromJsonData = context.deserializeConvertData; if (fromJsonData == null) { return null; } return LambdaResult( expression, fromJsonData.name, asContent: fromJsonData.paramType, ); } }
json_serializable/json_serializable/lib/src/type_helpers/convert_helper.dart/0
{'file_path': 'json_serializable/json_serializable/lib/src/type_helpers/convert_helper.dart', 'repo_id': 'json_serializable', 'token_count': 608}
# See https://github.com/google/mono_repo.dart for details on this file sdk: - pubspec - dev stages: - analyzer_and_format: - group: - format - analyze: --fatal-infos . sdk: dev - group: - analyze sdk: pubspec - unit_test: - test: - test: -p chrome - test: --run-skipped -t presubmit-only test/annotation_version_test.dart - test: --run-skipped -t presubmit-only test/ensure_build_test.dart cache: directories: - .dart_tool/build
json_serializable/json_serializable/mono_pkg.yaml/0
{'file_path': 'json_serializable/json_serializable/mono_pkg.yaml', 'repo_id': 'json_serializable', 'token_count': 197}
import 'package:json_annotation/json_annotation.dart'; part 'field_matrix_test.field_matrix.g.dart'; @JsonSerializable() class ToJsonNullFromJsonNullPublic { ToJsonNullFromJsonNullPublic(); int? aField; int? field; int? zField; factory ToJsonNullFromJsonNullPublic.fromJson(Map<String, dynamic> json) => _$ToJsonNullFromJsonNullPublicFromJson(json); Map<String, dynamic> toJson() => _$ToJsonNullFromJsonNullPublicToJson(this); @override String toString() => 'ToJsonNullFromJsonNullPublic: field: $field'; } @JsonSerializable() class ToJsonNullFromJsonTruePublic { ToJsonNullFromJsonTruePublic(); int? aField; @JsonKey( includeFromJson: true, ) int? field; int? zField; factory ToJsonNullFromJsonTruePublic.fromJson(Map<String, dynamic> json) => _$ToJsonNullFromJsonTruePublicFromJson(json); Map<String, dynamic> toJson() => _$ToJsonNullFromJsonTruePublicToJson(this); @override String toString() => 'ToJsonNullFromJsonTruePublic: field: $field'; } @JsonSerializable() class ToJsonNullFromJsonFalsePublic { ToJsonNullFromJsonFalsePublic(); int? aField; @JsonKey( includeFromJson: false, ) int? field; int? zField; factory ToJsonNullFromJsonFalsePublic.fromJson(Map<String, dynamic> json) => _$ToJsonNullFromJsonFalsePublicFromJson(json); Map<String, dynamic> toJson() => _$ToJsonNullFromJsonFalsePublicToJson(this); @override String toString() => 'ToJsonNullFromJsonFalsePublic: field: $field'; } @JsonSerializable() class ToJsonTrueFromJsonNullPublic { ToJsonTrueFromJsonNullPublic(); int? aField; @JsonKey( includeToJson: true, ) int? field; int? zField; factory ToJsonTrueFromJsonNullPublic.fromJson(Map<String, dynamic> json) => _$ToJsonTrueFromJsonNullPublicFromJson(json); Map<String, dynamic> toJson() => _$ToJsonTrueFromJsonNullPublicToJson(this); @override String toString() => 'ToJsonTrueFromJsonNullPublic: field: $field'; } @JsonSerializable() class ToJsonTrueFromJsonTruePublic { ToJsonTrueFromJsonTruePublic(); int? aField; @JsonKey( includeFromJson: true, includeToJson: true, ) int? field; int? zField; factory ToJsonTrueFromJsonTruePublic.fromJson(Map<String, dynamic> json) => _$ToJsonTrueFromJsonTruePublicFromJson(json); Map<String, dynamic> toJson() => _$ToJsonTrueFromJsonTruePublicToJson(this); @override String toString() => 'ToJsonTrueFromJsonTruePublic: field: $field'; } @JsonSerializable() class ToJsonTrueFromJsonFalsePublic { ToJsonTrueFromJsonFalsePublic(); int? aField; @JsonKey( includeFromJson: false, includeToJson: true, ) int? field; int? zField; factory ToJsonTrueFromJsonFalsePublic.fromJson(Map<String, dynamic> json) => _$ToJsonTrueFromJsonFalsePublicFromJson(json); Map<String, dynamic> toJson() => _$ToJsonTrueFromJsonFalsePublicToJson(this); @override String toString() => 'ToJsonTrueFromJsonFalsePublic: field: $field'; } @JsonSerializable() class ToJsonFalseFromJsonNullPublic { ToJsonFalseFromJsonNullPublic(); int? aField; @JsonKey( includeToJson: false, ) int? field; int? zField; factory ToJsonFalseFromJsonNullPublic.fromJson(Map<String, dynamic> json) => _$ToJsonFalseFromJsonNullPublicFromJson(json); Map<String, dynamic> toJson() => _$ToJsonFalseFromJsonNullPublicToJson(this); @override String toString() => 'ToJsonFalseFromJsonNullPublic: field: $field'; } @JsonSerializable() class ToJsonFalseFromJsonTruePublic { ToJsonFalseFromJsonTruePublic(); int? aField; @JsonKey( includeFromJson: true, includeToJson: false, ) int? field; int? zField; factory ToJsonFalseFromJsonTruePublic.fromJson(Map<String, dynamic> json) => _$ToJsonFalseFromJsonTruePublicFromJson(json); Map<String, dynamic> toJson() => _$ToJsonFalseFromJsonTruePublicToJson(this); @override String toString() => 'ToJsonFalseFromJsonTruePublic: field: $field'; } @JsonSerializable() class ToJsonFalseFromJsonFalsePublic { ToJsonFalseFromJsonFalsePublic(); int? aField; @JsonKey( includeFromJson: false, includeToJson: false, ) int? field; int? zField; factory ToJsonFalseFromJsonFalsePublic.fromJson(Map<String, dynamic> json) => _$ToJsonFalseFromJsonFalsePublicFromJson(json); Map<String, dynamic> toJson() => _$ToJsonFalseFromJsonFalsePublicToJson(this); @override String toString() => 'ToJsonFalseFromJsonFalsePublic: field: $field'; } @JsonSerializable() class ToJsonNullFromJsonNullPrivate { ToJsonNullFromJsonNullPrivate(); int? aField; @JsonKey(name: 'field') int? _field; int? zField; factory ToJsonNullFromJsonNullPrivate.fromJson(Map<String, dynamic> json) => _$ToJsonNullFromJsonNullPrivateFromJson(json); Map<String, dynamic> toJson() => _$ToJsonNullFromJsonNullPrivateToJson(this); @override String toString() => 'ToJsonNullFromJsonNullPrivate: _field: $_field'; } @JsonSerializable() class ToJsonNullFromJsonTruePrivate { ToJsonNullFromJsonTruePrivate(); int? aField; @JsonKey(includeFromJson: true, name: 'field') int? _field; int? zField; factory ToJsonNullFromJsonTruePrivate.fromJson(Map<String, dynamic> json) => _$ToJsonNullFromJsonTruePrivateFromJson(json); Map<String, dynamic> toJson() => _$ToJsonNullFromJsonTruePrivateToJson(this); @override String toString() => 'ToJsonNullFromJsonTruePrivate: _field: $_field'; } @JsonSerializable() class ToJsonNullFromJsonFalsePrivate { ToJsonNullFromJsonFalsePrivate(); int? aField; @JsonKey(includeFromJson: false, name: 'field') int? _field; int? zField; factory ToJsonNullFromJsonFalsePrivate.fromJson(Map<String, dynamic> json) => _$ToJsonNullFromJsonFalsePrivateFromJson(json); Map<String, dynamic> toJson() => _$ToJsonNullFromJsonFalsePrivateToJson(this); @override String toString() => 'ToJsonNullFromJsonFalsePrivate: _field: $_field'; } @JsonSerializable() class ToJsonTrueFromJsonNullPrivate { ToJsonTrueFromJsonNullPrivate(); int? aField; @JsonKey(includeToJson: true, name: 'field') int? _field; int? zField; factory ToJsonTrueFromJsonNullPrivate.fromJson(Map<String, dynamic> json) => _$ToJsonTrueFromJsonNullPrivateFromJson(json); Map<String, dynamic> toJson() => _$ToJsonTrueFromJsonNullPrivateToJson(this); @override String toString() => 'ToJsonTrueFromJsonNullPrivate: _field: $_field'; } @JsonSerializable() class ToJsonTrueFromJsonTruePrivate { ToJsonTrueFromJsonTruePrivate(); int? aField; @JsonKey(includeFromJson: true, includeToJson: true, name: 'field') int? _field; int? zField; factory ToJsonTrueFromJsonTruePrivate.fromJson(Map<String, dynamic> json) => _$ToJsonTrueFromJsonTruePrivateFromJson(json); Map<String, dynamic> toJson() => _$ToJsonTrueFromJsonTruePrivateToJson(this); @override String toString() => 'ToJsonTrueFromJsonTruePrivate: _field: $_field'; } @JsonSerializable() class ToJsonTrueFromJsonFalsePrivate { ToJsonTrueFromJsonFalsePrivate(); int? aField; @JsonKey(includeFromJson: false, includeToJson: true, name: 'field') int? _field; int? zField; factory ToJsonTrueFromJsonFalsePrivate.fromJson(Map<String, dynamic> json) => _$ToJsonTrueFromJsonFalsePrivateFromJson(json); Map<String, dynamic> toJson() => _$ToJsonTrueFromJsonFalsePrivateToJson(this); @override String toString() => 'ToJsonTrueFromJsonFalsePrivate: _field: $_field'; } @JsonSerializable() class ToJsonFalseFromJsonNullPrivate { ToJsonFalseFromJsonNullPrivate(); int? aField; @JsonKey(includeToJson: false, name: 'field') int? _field; int? zField; factory ToJsonFalseFromJsonNullPrivate.fromJson(Map<String, dynamic> json) => _$ToJsonFalseFromJsonNullPrivateFromJson(json); Map<String, dynamic> toJson() => _$ToJsonFalseFromJsonNullPrivateToJson(this); @override String toString() => 'ToJsonFalseFromJsonNullPrivate: _field: $_field'; } @JsonSerializable() class ToJsonFalseFromJsonTruePrivate { ToJsonFalseFromJsonTruePrivate(); int? aField; @JsonKey(includeFromJson: true, includeToJson: false, name: 'field') int? _field; int? zField; factory ToJsonFalseFromJsonTruePrivate.fromJson(Map<String, dynamic> json) => _$ToJsonFalseFromJsonTruePrivateFromJson(json); Map<String, dynamic> toJson() => _$ToJsonFalseFromJsonTruePrivateToJson(this); @override String toString() => 'ToJsonFalseFromJsonTruePrivate: _field: $_field'; } @JsonSerializable() class ToJsonFalseFromJsonFalsePrivate { ToJsonFalseFromJsonFalsePrivate(); int? aField; @JsonKey(includeFromJson: false, includeToJson: false, name: 'field') int? _field; int? zField; factory ToJsonFalseFromJsonFalsePrivate.fromJson(Map<String, dynamic> json) => _$ToJsonFalseFromJsonFalsePrivateFromJson(json); Map<String, dynamic> toJson() => _$ToJsonFalseFromJsonFalsePrivateToJson(this); @override String toString() => 'ToJsonFalseFromJsonFalsePrivate: _field: $_field'; } const fromJsonFactories = <Object Function(Map<String, dynamic>)>{ ToJsonNullFromJsonNullPublic.fromJson, ToJsonNullFromJsonTruePublic.fromJson, ToJsonNullFromJsonFalsePublic.fromJson, ToJsonTrueFromJsonNullPublic.fromJson, ToJsonTrueFromJsonTruePublic.fromJson, ToJsonTrueFromJsonFalsePublic.fromJson, ToJsonFalseFromJsonNullPublic.fromJson, ToJsonFalseFromJsonTruePublic.fromJson, ToJsonFalseFromJsonFalsePublic.fromJson, ToJsonNullFromJsonNullPrivate.fromJson, ToJsonNullFromJsonTruePrivate.fromJson, ToJsonNullFromJsonFalsePrivate.fromJson, ToJsonTrueFromJsonNullPrivate.fromJson, ToJsonTrueFromJsonTruePrivate.fromJson, ToJsonTrueFromJsonFalsePrivate.fromJson, ToJsonFalseFromJsonNullPrivate.fromJson, ToJsonFalseFromJsonTruePrivate.fromJson, ToJsonFalseFromJsonFalsePrivate.fromJson, };
json_serializable/json_serializable/test/field_matrix_test.field_matrix.dart/0
{'file_path': 'json_serializable/json_serializable/test/field_matrix_test.field_matrix.dart', 'repo_id': 'json_serializable', 'token_count': 3676}
import 'package:json_annotation/json_annotation.dart'; part 'json_enum_example.g.dart'; @JsonEnum(alwaysCreate: true) enum StandAloneEnum { @JsonValue('a') alpha, @JsonValue('b') beta, @JsonValue('g') gamma, @JsonValue('d') delta, } Iterable<String> get standAloneEnumValues => _$StandAloneEnumEnumMap.values; @JsonEnum(alwaysCreate: true, fieldRename: FieldRename.kebab) enum DayType { noGood, rotten, veryBad, } Iterable<String> get dayTypeEnumValues => _$DayTypeEnumMap.values; @JsonEnum(alwaysCreate: true, valueField: 'value') enum MyStatusCode { success(200), @JsonValue(701) // explicit value always takes precedence weird(601); const MyStatusCode(this.value); final int value; } Iterable<int> get myStatusCodeEnumValues => _$MyStatusCodeEnumMap.values; @JsonEnum(alwaysCreate: true, valueField: 'index') enum EnumValueFieldIndex { success(200), @JsonValue(701) // explicit value always takes precedence weird(601), oneMore(777); static const tryingToBeConfusing = weird; const EnumValueFieldIndex(this.value); final int value; } Iterable<int> get enumValueFieldIndexValues => _$EnumValueFieldIndexEnumMap.values; @JsonSerializable( createToJson: false, ) class Issue559Regression { Issue559Regression({ required this.status, }); factory Issue559Regression.fromJson(Map<String, dynamic> json) => _$Issue559RegressionFromJson(json); @JsonKey( disallowNullValue: true, required: true, unknownEnumValue: JsonKey.nullForUndefinedEnumValue, ) final Issue559RegressionEnum? status; } enum Issue559RegressionEnum { alpha, beta, gamma, } enum Issue1145RegressionEnum { alpha, beta, gamma, } @JsonSerializable( createFactory: false, ) class Issue1145RegressionA { Issue1145RegressionA({ required this.status, }); Map<String, dynamic> toJson() => _$Issue1145RegressionAToJson(this); final Map<Issue1145RegressionEnum, bool> status; } @JsonSerializable( createFactory: false, ) class Issue1145RegressionB { Issue1145RegressionB({required this.status}); Map<String, dynamic> toJson() => _$Issue1145RegressionBToJson(this); final List<Issue1145RegressionEnum?> status; } @JsonSerializable(includeIfNull: false) class Issue1226Regression { Issue1226Regression({required this.durationType}); factory Issue1226Regression.fromJson(Map<String, dynamic> json) => _$Issue1226RegressionFromJson(json); final Issue1145RegressionEnum? durationType; Map<String, dynamic> toJson() => _$Issue1226RegressionToJson(this); }
json_serializable/json_serializable/test/integration/json_enum_example.dart/0
{'file_path': 'json_serializable/json_serializable/test/integration/json_enum_example.dart', 'repo_id': 'json_serializable', 'token_count': 922}
// 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. @TestOn('vm') library test; import 'dart:convert'; import 'dart:io'; import 'package:path/path.dart' as p; import 'package:test/test.dart'; import '../test_utils.dart'; import 'json_literal.dart'; void main() { test('literal round-trip', () { final dataFilePath = p.join('test', 'literal', 'json_literal.json'); final dataFile = File(dataFilePath); final dataString = loudEncode(json.decode(dataFile.readAsStringSync())); // FYI: nice to re-write the test data when it's changed to keep it pretty // ... but not a good idea to ship this // dataFile.writeAsStringSync(dataString.replaceAll('\u007F', '\\u007F')); final dartString = loudEncode(data); expect(dartString, dataString); }); test('naughty strings', () { final dataFilePath = p.join('test', 'literal', 'big-list-of-naughty-strings.json'); final dataFile = File(dataFilePath); final dataString = loudEncode(json.decode(dataFile.readAsStringSync())); final dartString = loudEncode(naughtyStrings); expect(dartString, dataString); }); }
json_serializable/json_serializable/test/literal/json_literal_test.dart/0
{'file_path': 'json_serializable/json_serializable/test/literal/json_literal_test.dart', 'repo_id': 'json_serializable', 'token_count': 446}
// 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. enum EnumType { alpha, beta, gamma, delta } class FromJsonDynamicParam { FromJsonDynamicParam({required this.value}); final int value; factory FromJsonDynamicParam.fromJson(dynamic json) => FromJsonDynamicParam(value: json as int); dynamic toJson() => null; } class FromJsonNullableObjectParam { FromJsonNullableObjectParam({required this.value}); final int value; factory FromJsonNullableObjectParam.fromJson(Object? json) => FromJsonNullableObjectParam(value: json as int); Object? toJson() => null; } class FromJsonObjectParam { FromJsonObjectParam({required this.value}); final int value; factory FromJsonObjectParam.fromJson(Object json) => FromJsonObjectParam(value: json as int); dynamic toJson() => null; }
json_serializable/json_serializable/test/supported_types/enum_type.dart/0
{'file_path': 'json_serializable/json_serializable/test/supported_types/enum_type.dart', 'repo_id': 'json_serializable', 'token_count': 306}
# See https://github.com/google/mono_repo.dart for details on this file self_validate: analyzer_and_format github: on: push: branches: - master - 4_x pull_request: schedule: - cron: "0 0 * * 0" merge_stages: - analyzer_and_format - ensure_build - unit_test
json_serializable/mono_repo.yaml/0
{'file_path': 'json_serializable/mono_repo.yaml', 'repo_id': 'json_serializable', 'token_count': 131}
import 'dart:math'; import 'dart:ui'; import 'package:collection/collection.dart'; import 'package:flame/components.dart'; import 'package:flame/extensions.dart'; import 'package:lightrunners/game/lightrunners_game.dart'; import 'package:lightrunners/ui/palette.dart'; import 'package:lightrunners/utils/delaunay.dart'; import 'package:lightrunners/utils/flame_utils.dart'; const _margin = 200.0; const _numberShades = 5; const _shadeStep = 0.1; const _colorMoveSpeed = 30; final _emptyColor = GamePalette.black.brighten(0.1); final _borderPaint = Paint() ..color = GamePalette.black ..strokeWidth = 2 ..style = PaintingStyle.stroke ..filterQuality = FilterQuality.high; final _random = Random(); typedef ShadedTriangle = ({ Path path, int shadeLevel, }); class Background extends PositionComponent with HasGameReference<LightRunnersGame>, HasPaint { late Rect clipArea; late List<ShadedTriangle> mesh; Color currentColor = _emptyColor; @override void onGameResize(Vector2 gameSize) { super.onGameResize(gameSize); position = game.playArea.topLeft.toVector2(); size = game.playArea.size.toVector2(); clipArea = Vector2.zero() & size; } @override void onLoad() { final size = game.playArea.inflate(_margin).size.toVector2(); final delta = Vector2.all(-_margin / 2); final fixedPointsGrid = game.playArea.inflate(10.0).toFlameRectangle(); final fixedPoints = fixedPointsGrid.vertices + fixedPointsGrid.edges.map(lineMidPoint).toList(); final points = fixedPoints + List.generate(30, (_) { return Vector2.random()..multiply(size); }); mesh = Delaunay.triangulate(points) .map((e) => e.translateBy(delta)) .map( (triangle) => ( path: triangle.toPath(), shadeLevel: _random.nextInt(_numberShades), ), ) .toList(); } @override void update(double dt) { super.update(dt); final targetColor = _computeTargetColor(); currentColor = _moveTowards(currentColor, targetColor, _colorMoveSpeed * dt); } @override void render(Canvas canvas) { super.render(canvas); canvas.clipRect(clipArea); for (final t in mesh) { final shadedColor = currentColor.brighten(t.shadeLevel * _shadeStep); canvas.drawPath(t.path, paint..color = shadedColor); } for (final t in mesh) { canvas.drawPath(t.path, _borderPaint); } } (int, int, int) _computeTargetColor() { final sortedShips = game.ships.values.sortedBy<num>((ship) => -ship.score); final maxScore = sortedShips.first.score; if (maxScore == 0) { return _fromColor(_emptyColor); } final colors = sortedShips .takeWhile((ship) => ship.score == maxScore) .map((ship) => ship.paint.color.darken(0.75)) .toList(); return colors.map(_fromColor).reduce((value, element) => value + element) / colors.length.toDouble(); } Color _moveTowards(Color currentColor, (int, int, int) target, double ds) { final color = _fromColor(currentColor); if (color == target) { return currentColor; } return color.moveTowards(target, ds).toColor(); } } extension on (int, int, int) { Color toColor() => Color.fromARGB(255, $1, $2, $3); (int, int, int) operator +((int, int, int) other) => (this.$1 + other.$1, this.$2 + other.$2, this.$3 + other.$3); (int, int, int) operator -((int, int, int) other) => this + (-other); (int, int, int) operator /(double other) => _fromDoubles(this.$1 / other, this.$2 / other, this.$3 / other); (int, int, int) operator *(double other) => _fromDoubles(this.$1 * other, this.$2 * other, this.$3 * other); (int, int, int) operator -() => (-this.$1, -this.$2, -this.$3); double get length => sqrt($1 * $1 + $2 * $2 + $3 * $3); (int, int, int) normalized() => this / length; (int, int, int) moveTowards((int, int, int) target, double ds) { final diff = target - this; if (diff.length < ds) { return target; } else { return this + diff.normalized() * ds; } } } (int, int, int) _fromDoubles(double r, double g, double b) => (r.round(), g.round(), b.round()); (int, int, int) _fromColor(Color color) => (color.red, color.green, color.blue);
lightrunners/lib/game/components/background.dart/0
{'file_path': 'lightrunners/lib/game/components/background.dart', 'repo_id': 'lightrunners', 'token_count': 1690}
export 'leaderboard_page.dart';
lightrunners/lib/leaderboard/view/view.dart/0
{'file_path': 'lightrunners/lib/leaderboard/view/view.dart', 'repo_id': 'lightrunners', 'token_count': 11}
import 'package:gamepads/gamepads.dart'; import 'package:lightrunners/utils/gamepad_map.dart'; class GamepadNavigator { final Function(int)? xAxisHandler; final Function(int)? yAxisHandler; final Function()? onAction; final Function()? onAny; GamepadNavigator({ this.xAxisHandler, this.yAxisHandler, this.onAction, this.onAny, }); int _getValue(GamepadEvent event) { return GamepadAnalogAxis.normalizedIntensity(event).sign.toInt(); } void handle(GamepadEvent event) { if (event.value == 1.0) { onAny?.call(); } if (leftXAxis.matches(event)) { final value = _getValue(event); if (value != 0) { xAxisHandler?.call(value); } } else if (leftYAxis.matches(event)) { final value = _getValue(event); if (value != 0) { yAxisHandler?.call(value); } } else if (aButton.matches(event)) { onAction?.call(); } } }
lightrunners/lib/utils/gamepad_navigator.dart/0
{'file_path': 'lightrunners/lib/utils/gamepad_navigator.dart', 'repo_id': 'lightrunners', 'token_count': 398}
name: lightrunners description: A simple Flame game. version: 0.1.0 publish_to: 'none' environment: sdk: ">=3.0.0 <4.0.0" dependencies: collection: ^1.17.0 firebase_admin: ^0.2.0 firedart: ^0.9.7 flame: ^1.9.0 flame_audio: ^2.1.0 flutter: sdk: flutter flutter_shaders: ^0.1.2 gamepads: ^0.1.1 google_fonts: ^4.0.4 phased: ^0.0.3 vector_math: ^2.1.4 dev_dependencies: flame_lint: ^1.1.1 flame_test: ^1.13.0 flutter_test: sdk: flutter integration_test: sdk: flutter flutter: uses-material-design: false shaders: - shaders/super_crt.glsl assets: - google_fonts/ - assets/audio/ - assets/images/ - assets/images/ships/ - assets/images/powerups/
lightrunners/pubspec.yaml/0
{'file_path': 'lightrunners/pubspec.yaml', 'repo_id': 'lightrunners', 'token_count': 343}
// 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'Avoid annotating with dynamic when not required.'; const _details = r''' **AVOID** annotating with dynamic when not required. As `dynamic` is the assumed return value of a function or method, it is usually not necessary to annotate it. **BAD:** ```dart dynamic lookUpOrDefault(String name, Map map, dynamic defaultValue) { var value = map[name]; if (value != null) return value; return defaultValue; } ``` **GOOD:** ```dart lookUpOrDefault(String name, Map map, defaultValue) { var value = map[name]; if (value != null) return value; return defaultValue; } ``` '''; class AvoidAnnotatingWithDynamic extends LintRule implements NodeLintRule { AvoidAnnotatingWithDynamic() : super( name: 'avoid_annotating_with_dynamic', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addSimpleFormalParameter(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitSimpleFormalParameter(SimpleFormalParameter node) { var type = node.type; if (type is TypeName && type.name.name == 'dynamic') { rule.reportLint(node); } } }
linter/lib/src/rules/avoid_annotating_with_dynamic.dart/0
{'file_path': 'linter/lib/src/rules/avoid_annotating_with_dynamic.dart', 'repo_id': 'linter', 'token_count': 590}
// 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/visitor.dart'; import '../analyzer.dart'; const _desc = r"Don't declare multiple variables on a single line."; const _details = r''' **DON'T** declare multiple variables on a single line. **BAD:** ```dart String? foo, bar, baz; ``` **GOOD:** ```dart String? foo; String? bar; String? baz; ``` '''; class AvoidMultipleDeclarationsPerLine extends LintRule implements NodeLintRule { AvoidMultipleDeclarationsPerLine() : super( name: 'avoid_multiple_declarations_per_line', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addVariableDeclarationList(this, visitor); } } class _Visitor extends SimpleAstVisitor { final LintRule rule; _Visitor(this.rule); @override void visitVariableDeclarationList(VariableDeclarationList node) { var variables = node.variables; if (variables.length > 1) { var secondVariable = variables[1]; rule.reportLint(secondVariable.name); } } }
linter/lib/src/rules/avoid_multiple_declarations_per_line.dart/0
{'file_path': 'linter/lib/src/rules/avoid_multiple_declarations_per_line.dart', 'repo_id': 'linter', 'token_count': 509}
// 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 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import '../analyzer.dart'; import '../util/dart_type_utilities.dart'; const _desc = r'Avoid slow async `dart:io` methods.'; const _details = r''' **AVOID** using the following asynchronous file I/O methods because they are much slower than their synchronous counterparts. * `Directory.exists` * `Directory.stat` * `File.lastModified` * `File.exists` * `File.stat` * `FileSystemEntity.isDirectory` * `FileSystemEntity.isFile` * `FileSystemEntity.isLink` * `FileSystemEntity.type` **BAD:** ```dart import 'dart:io'; Future<Null> someFunction() async { var file = File('/path/to/my/file'); var now = DateTime.now(); if ((await file.lastModified()).isBefore(now)) print('before'); // LINT } ``` **GOOD:** ```dart import 'dart:io'; Future<Null> someFunction() async { var file = File('/path/to/my/file'); var now = DateTime.now(); if (file.lastModifiedSync().isBefore(now)) print('before'); // OK } ``` '''; const List<String> _fileMethodNames = <String>[ 'lastModified', 'exists', 'stat', ]; const List<String> _dirMethodNames = <String>[ 'exists', 'stat', ]; const List<String> _fileSystemEntityMethodNames = <String>[ 'isDirectory', 'isFile', 'isLink', 'type', ]; class AvoidSlowAsyncIo extends LintRule implements NodeLintRule { AvoidSlowAsyncIo() : super( name: 'avoid_slow_async_io', description: _desc, details: _details, group: Group.errors); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addMethodInvocation(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitMethodInvocation(MethodInvocation node) { if (node.argumentList.arguments.isEmpty) { var type = node.target?.staticType; _checkFileMethods(node, type); _checkDirectoryMethods(node, type); return; } else { _checkFileSystemEntityMethods(node); return; } } void _checkFileMethods(MethodInvocation node, DartType? type) { if (DartTypeUtilities.extendsClass(type, 'File', 'dart.io')) { if (_fileMethodNames.contains(node.methodName.name)) { rule.reportLint(node); } } } void _checkDirectoryMethods(MethodInvocation node, DartType? type) { if (DartTypeUtilities.extendsClass(type, 'Directory', 'dart.io')) { if (_dirMethodNames.contains(node.methodName.name)) { rule.reportLint(node); } } } void _checkFileSystemEntityMethods(MethodInvocation node) { var target = node.target; if (target is Identifier) { var elem = target.staticElement; if (elem is ClassElement && elem.name == 'FileSystemEntity') { if (_fileSystemEntityMethodNames.contains(node.methodName.name)) { rule.reportLint(node); } } } } }
linter/lib/src/rules/avoid_slow_async_io.dart/0
{'file_path': 'linter/lib/src/rules/avoid_slow_async_io.dart', 'repo_id': 'linter', 'token_count': 1265}
// 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 '../utils.dart'; const _desc = r'Prefer using lowerCamelCase for constant names.'; const _details = r''' **PREFER** using lowerCamelCase for constant names. In new code, use `lowerCamelCase` for constant variables, including enum values. In existing code that uses `ALL_CAPS_WITH_UNDERSCORES` for constants, you may continue to use all caps to stay consistent. **GOOD:** ```dart const pi = 3.14; const defaultTimeout = 1000; final urlScheme = RegExp('^([a-z]+):'); class Dice { static final numberGenerator = Random(); } ``` **BAD:** ```dart const PI = 3.14; const kDefaultTimeout = 1000; final URL_SCHEME = RegExp('^([a-z]+):'); class Dice { static final NUMBER_GENERATOR = Random(); } ``` '''; class ConstantIdentifierNames extends LintRule implements NodeLintRule { ConstantIdentifierNames() : super( name: 'constant_identifier_names', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addEnumConstantDeclaration(this, visitor); registry.addTopLevelVariableDeclaration(this, visitor); registry.addVariableDeclarationList(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); void checkIdentifier(SimpleIdentifier id) { if (!isLowerCamelCase(id.name)) { rule.reportLint(id); } } @override void visitEnumConstantDeclaration(EnumConstantDeclaration node) { checkIdentifier(node.name); } @override void visitTopLevelVariableDeclaration(TopLevelVariableDeclaration node) { visitVariableDeclarationList(node.variables); } @override void visitVariableDeclarationList(VariableDeclarationList node) { node.variables.forEach((VariableDeclaration v) { if (v.isConst) { checkIdentifier(v.name); } }); } }
linter/lib/src/rules/constant_identifier_names.dart/0
{'file_path': 'linter/lib/src/rules/constant_identifier_names.dart', 'repo_id': 'linter', 'token_count': 815}
// 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 Iterable<E>.contains with references of unrelated' r' types.'; const _details = r''' **DON'T** invoke `contains` on `Iterable` 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.contains('1')) print('someFunction'); // LINT } ``` **BAD:** ```dart void someFunction3() { List<int> list = <int>[]; if (list.contains('1')) print('someFunction3'); // LINT } ``` **BAD:** ```dart void someFunction8() { List<DerivedClass2> list = <DerivedClass2>[]; DerivedClass3 instance; if (list.contains(instance)) print('someFunction8'); // LINT } ``` **BAD:** ```dart abstract class SomeIterable<E> implements Iterable<E> {} abstract class MyClass implements SomeIterable<int> { bool badMethod(String thing) => this.contains(thing); // LINT } ``` **GOOD:** ```dart void someFunction10() { var list = []; if (list.contains(1)) print('someFunction10'); // OK } ``` **GOOD:** ```dart void someFunction1() { var list = <int>[]; if (list.contains(1)) print('someFunction1'); // OK } ``` **GOOD:** ```dart void someFunction4() { List<int> list = <int>[]; if (list.contains(1)) print('someFunction4'); // OK } ``` **GOOD:** ```dart void someFunction5() { List<ClassBase> list = <ClassBase>[]; DerivedClass1 instance; if (list.contains(instance)) print('someFunction5'); // OK } abstract class ClassBase {} class DerivedClass1 extends ClassBase {} ``` **GOOD:** ```dart void someFunction6() { List<Mixin> list = <Mixin>[]; DerivedClass2 instance; if (list.contains(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.contains(instance)) print('someFunction7'); // OK } abstract class ClassBase {} abstract class Mixin {} class DerivedClass3 extends ClassBase implements Mixin {} ``` '''; class IterableContainsUnrelatedType extends LintRule implements NodeLintRule { IterableContainsUnrelatedType() : super( name: 'iterable_contains_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('Iterable', 'dart.core'); _Visitor(LintRule rule, TypeSystem typeSystem) : super(rule, typeSystem); @override InterfaceTypeDefinition get definition => _definition; @override String get methodName => 'contains'; }
linter/lib/src/rules/iterable_contains_unrelated_type.dart/0
{'file_path': 'linter/lib/src/rules/iterable_contains_unrelated_type.dart', 'repo_id': 'linter', 'token_count': 1150}
// 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/analysis/features.dart'; 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'; import 'unnecessary_null_checks.dart'; const _desc = r"Don't use null check on a potentially nullable type parameter."; const _details = r''' Don't use null check on a potentially nullable type parameter. Given a generic type parameter `T` which has a nullable bound (e.g. the default bound of `Object?`), it is very easy to introduce erroneous null checks when working with a variable of type `T?`. Specifically, it is not uncommon to have `T? x;` and want to assert that `x` has been set to a valid value of type `T`. A common mistake is to do so using `x!`. This is almost always incorrect, since if `T` is a nullable type, `x` may validly hold `null` as a value of type `T`. **BAD:** ```dart T run<T>(T callback()) { T? result; (() { result = callback(); })(); return result!; } ``` **GOOD:** ```dart T run<T>(T callback()) { T? result; (() { result = callback(); })(); return result as T; } ``` '''; class NullCheckOnNullableTypeParameter extends LintRule implements NodeLintRule { NullCheckOnNullableTypeParameter() : super( name: 'null_check_on_nullable_type_parameter', description: _desc, details: _details, maturity: Maturity.experimental, group: Group.style, ); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { if (!context.isEnabled(Feature.non_nullable)) { return; } var visitor = _Visitor(this, context); registry.addCompilationUnit(this, visitor); registry.addPostfixExpression(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { _Visitor(this.rule, this.context); final LintRule rule; final LinterContext context; @override void visitPostfixExpression(PostfixExpression node) { if (node.operator.type != TokenType.BANG) return; var expectedType = getExpectedType(node); var type = node.operand.staticType; if (type is TypeParameterType && context.typeSystem.isNullable(type) && expectedType != null && context.typeSystem.isPotentiallyNullable(expectedType) && context.typeSystem.promoteToNonNull(type) == context.typeSystem.promoteToNonNull(expectedType)) { rule.reportLintForToken(node.operator); } } }
linter/lib/src/rules/null_check_on_nullable_type_parameter.dart/0
{'file_path': 'linter/lib/src/rules/null_check_on_nullable_type_parameter.dart', 'repo_id': 'linter', 'token_count': 980}
// 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 'package:analyzer/dart/element/element.dart'; import 'package:collection/collection.dart' show IterableExtension; import '../analyzer.dart'; const _desc = r'Prefer declaring const constructors on `@immutable` classes.'; const _details = r''' **PREFER** declaring const constructors on `@immutable` classes. If a class is immutable, it is usually a good idea to make its constructor a const constructor. **GOOD:** ```dart @immutable class A { final a; const A(this.a); } ``` **BAD:** ```dart @immutable class A { final a; A(this.a); } ``` '''; /// The name of the top-level variable used to mark a immutable class. String _immutableVarName = 'immutable'; /// The name of `meta` library, used to define analysis annotations. String _metaLibName = 'meta'; bool _isImmutable(Element? element) => element is PropertyAccessorElement && element.name == _immutableVarName && element.library.name == _metaLibName; class PreferConstConstructorsInImmutables extends LintRule implements NodeLintRule { PreferConstConstructorsInImmutables() : super( name: 'prefer_const_constructors_in_immutables', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this, context); registry.addConstructorDeclaration(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; final LinterContext context; _Visitor(this.rule, this.context); @override void visitConstructorDeclaration(ConstructorDeclaration node) { var element = node.declaredElement; if (element == null) { return; } var isRedirected = element.isFactory && element.redirectedConstructor != null; if (node.body is EmptyFunctionBody && !element.isConst && !_hasMixin(element.enclosingElement) && _hasImmutableAnnotation(element.enclosingElement) && (isRedirected && element.redirectedConstructor?.isConst == true || (!isRedirected && _hasConstConstructorInvocation(node) && context.canBeConstConstructor(node)))) { rule.reportLintForToken(node.firstTokenAfterCommentAndMetadata); } } bool _hasConstConstructorInvocation(ConstructorDeclaration node) { var declaredElement = node.declaredElement; if (declaredElement == null) { return false; } var clazz = declaredElement.enclosingElement; // construct with super var superInvocation = node.initializers .firstWhereOrNull((e) => e is SuperConstructorInvocation) as SuperConstructorInvocation?; if (superInvocation != null) { return superInvocation.staticElement?.isConst == true; } // construct with this var redirectInvocation = node.initializers .firstWhereOrNull((e) => e is RedirectingConstructorInvocation) as RedirectingConstructorInvocation?; if (redirectInvocation != null) { return redirectInvocation.staticElement?.isConst == true; } // construct with implicit super() var supertype = clazz.supertype; return supertype != null && supertype.constructors.firstWhere((e) => e.name.isEmpty).isConst; } bool _hasImmutableAnnotation(ClassElement clazz) { var selfAndInheritedClasses = _getSelfAndInheritedClasses(clazz); var selfAndInheritedAnnotations = selfAndInheritedClasses.expand((c) => c.metadata).map((m) => m.element); return selfAndInheritedAnnotations.any(_isImmutable); } bool _hasMixin(ClassElement clazz) => clazz.mixins.isNotEmpty; static Iterable<ClassElement> _getSelfAndInheritedClasses( ClassElement self) sync* { ClassElement? current = self; var seenElements = <ClassElement>{}; while (current != null && seenElements.add(current)) { yield current; current = current.supertype?.element; } } }
linter/lib/src/rules/prefer_const_constructors_in_immutables.dart/0
{'file_path': 'linter/lib/src/rules/prefer_const_constructors_in_immutables.dart', 'repo_id': 'linter', 'token_count': 1543}
// 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 using if null operators.'; const _details = r''' Prefer using if null operators instead of null checks in conditional expressions. **BAD:** ```dart v = a == null ? b : a; ``` **GOOD:** ```dart v = a ?? b; ``` '''; class PreferIfNullOperators extends LintRule implements NodeLintRule { PreferIfNullOperators() : super( name: 'prefer_if_null_operators', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addConditionalExpression(this, visitor); } } class _Visitor extends SimpleAstVisitor { final LintRule rule; _Visitor(this.rule); @override void visitConditionalExpression(ConditionalExpression node) { var condition = node.condition; if (condition is BinaryExpression && (condition.operator.type == TokenType.EQ_EQ || condition.operator.type == TokenType.BANG_EQ)) { // ensure condition is a null check Expression expression; if (condition.leftOperand is NullLiteral) { expression = condition.rightOperand; } else if (condition.rightOperand is NullLiteral) { expression = condition.leftOperand; } else { return; } var exp = condition.operator.type == TokenType.EQ_EQ ? node.elseExpression : node.thenExpression; if (exp.toString() == expression.toString()) { rule.reportLint(node); } } } }
linter/lib/src/rules/prefer_if_null_operators.dart/0
{'file_path': 'linter/lib/src/rules/prefer_if_null_operators.dart', 'repo_id': 'linter', 'token_count': 753}
// 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/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; const _desc = r"Don't use the Null type, unless you are positive that you don't want void."; const _details = r''' **DO NOT** use the type Null where void would work. **BAD:** ```dart Null f() {} Future<Null> f() {} Stream<Null> f() {} f(Null x) {} ``` **GOOD:** ```dart void f() {} Future<void> f() {} Stream<void> f() {} f(void x) {} ``` Some exceptions include formulating special function types: ```dart Null Function(Null, Null); ``` and for making empty literals which are safe to pass into read-only locations for any type of map or list: ```dart <Null>[]; <int, Null>{}; ``` '''; class PreferVoidToNull extends LintRule implements NodeLintRule { PreferVoidToNull() : super( name: 'prefer_void_to_null', description: _desc, details: _details, group: Group.errors); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addSimpleIdentifier(this, visitor); registry.addTypeName(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitTypeName(TypeName node) { var nodeType = node.type; if (nodeType == null || !nodeType.isDartCoreNull) { return; } var parent = node.parent; // Null Function() if (parent is GenericFunctionType) { return; } // Function(Null) if (parent is SimpleFormalParameter && parent.parent is FormalParameterList && parent.parent?.parent is GenericFunctionType) { return; } // <Null>[] or <Null, Null>{} if (parent is TypeArgumentList) { var literal = parent.parent; if (literal is ListLiteral && literal.elements.isEmpty) { return; } else if (literal is SetOrMapLiteral && literal.elements.isEmpty) { return; } } rule.reportLint(node.name); } }
linter/lib/src/rules/prefer_void_to_null.dart/0
{'file_path': 'linter/lib/src/rules/prefer_void_to_null.dart', 'repo_id': 'linter', 'token_count': 879}
// 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/ast/ast.dart'; import 'package:analyzer/dart/ast/visitor.dart'; import '../analyzer.dart'; const _desc = r'Unnecessary parenthesis can be removed.'; const _details = r''' **AVOID** using parenthesis when not needed. **GOOD:** ```dart a = b; ``` **BAD:** ```dart a = (b); ``` '''; class UnnecessaryParenthesis extends LintRule implements NodeLintRule { UnnecessaryParenthesis() : super( name: 'unnecessary_parenthesis', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addParenthesizedExpression(this, visitor); } } class _Visitor extends SimpleAstVisitor<void> { final LintRule rule; _Visitor(this.rule); @override void visitParenthesizedExpression(ParenthesizedExpression node) { if (node.expression is SimpleIdentifier) { var parent = node.parent; if (parent is PropertyAccess) { if (parent.propertyName.name == 'hashCode' || parent.propertyName.name == 'runtimeType') { // Code like `(String).hashCode` is allowed. return; } } else if (parent is MethodInvocation) { if (parent.methodName.name == 'noSuchMethod' || parent.methodName.name == 'toString') { // Code like `(String).noSuchMethod()` is allowed. return; } } rule.reportLint(node); return; } var parent = node.parent; if (parent is ParenthesizedExpression) { rule.reportLint(node); return; } // `a..b=(c..d)` is OK. if (node.expression is CascadeExpression || node.thisOrAncestorMatching( (n) => n is Statement || n is CascadeExpression) is CascadeExpression) { return; } // Constructor field initializers are rather unguarded by delimiting // tokens, which can get confused with a function expression. See test // cases for issues #1395 and #1473. if (parent is ConstructorFieldInitializer && _containsFunctionExpression(node)) { return; } if (parent is Expression) { if (parent is BinaryExpression) return; if (parent is ConditionalExpression) return; if (parent is CascadeExpression) return; if (parent is FunctionExpressionInvocation) return; // A prefix expression (! or -) can have an argument wrapped in // "unnecessary" parens if that argument has potentially confusing // whitespace after its first token. if (parent is PrefixExpression && _expressionStartsWithWhitespace(node.expression)) return; // Another case of the above exception, something like // `!(const [7]).contains(5);`, where the _parent's_ parent is the // PrefixExpression. if (parent is MethodInvocation) { var target = parent.target; if (parent.parent is PrefixExpression && target == node && _expressionStartsWithWhitespace(node.expression)) return; } // Something like `({1, 2, 3}).forEach(print);`. // The parens cannot be removed because then the curly brackets are not // interpreted as a set-or-map literal. if (parent is PropertyAccess || parent is MethodInvocation) { var target = (parent as dynamic).target; if (target == node && node.expression is SetOrMapLiteral && parent.parent is ExpressionStatement) return; } if (parent.precedence < node.expression.precedence) { rule.reportLint(node); return; } } else { rule.reportLint(node); return; } } bool _containsFunctionExpression(ParenthesizedExpression node) { var containsFunctionExpressionVisitor = _ContainsFunctionExpressionVisitor(); node.accept(containsFunctionExpressionVisitor); return containsFunctionExpressionVisitor.hasFunctionExpression; } /// Returns whether [node] "starts" with whitespace. /// /// That is, is there definitely whitespace after the first token in [node]? bool _expressionStartsWithWhitespace(Expression? node) => // As in, `!(await foo)`. node is AwaitExpression || // As in, `!(new Foo())`. (node is InstanceCreationExpression && node.keyword != null) || // No TypedLiteral (ListLiteral, MapLiteral, SetLiteral) accepts `-` or // `!` as a prefix operator, but this method can be called recursively, // so this catches things like `!(const [].contains(42))`. (node is TypedLiteral && node.constKeyword != null) || // As in, `!(const List(3).contains(7))`, and chains like // `-(new List(3).skip(1).take(3).skip(1).length)`. (node is MethodInvocation && _expressionStartsWithWhitespace(node.target)) || // As in, `-(new List(3).length)`, and chains like // `-(new List(3).length.bitLength.bitLength)`. (node is PropertyAccess && _expressionStartsWithWhitespace(node.target)); } class _ContainsFunctionExpressionVisitor extends UnifyingAstVisitor<void> { bool hasFunctionExpression = false; @override void visitFunctionExpression(FunctionExpression node) { hasFunctionExpression = true; } @override void visitNode(AstNode node) { if (!hasFunctionExpression) { node.visitChildren(this); } } }
linter/lib/src/rules/unnecessary_parenthesis.dart/0
{'file_path': 'linter/lib/src/rules/unnecessary_parenthesis.dart', 'repo_id': 'linter', 'token_count': 2141}
// 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'; const _desc = r'Use raw string to avoid escapes.'; const _details = r''' A raw string can be used to avoid escaping only backslashes and dollars. **BAD:** ```dart var s = 'A string with only \\ and \$'; ``` **GOOD:** ```dart var s = r'A string with only \ and $'; ``` '''; class UseRawStrings extends LintRule implements NodeLintRule { UseRawStrings() : super( name: 'use_raw_strings', description: _desc, details: _details, group: Group.style); @override void registerNodeProcessors( NodeLintRegistry registry, LinterContext context) { var visitor = _Visitor(this); registry.addSimpleStringLiteral(this, visitor); } } class _Visitor extends SimpleAstVisitor { final LintRule rule; _Visitor(this.rule); @override void visitSimpleStringLiteral(SimpleStringLiteral node) { if (node.isRaw) return; var lexeme = node.literal.lexeme.substring( node.contentsOffset - node.literal.offset, node.contentsEnd - node.literal.offset); var hasEscape = false; for (var i = 0; i < lexeme.length - 1; i++) { var current = lexeme[i]; if (current == r'\') { hasEscape = true; i += 1; current = lexeme[i]; if (current != r'\' && current != r'$') { return; } } } if (hasEscape) { rule.reportLint(node); } } }
linter/lib/src/rules/use_raw_strings.dart/0
{'file_path': 'linter/lib/src/rules/use_raw_strings.dart', 'repo_id': 'linter', 'token_count': 703}
// 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 'dart:collection'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:analyzer/dart/ast/token.dart'; import '../util/boolean_expression_utilities.dart'; void _addNodeComparisons(Expression node, Set<Expression> comparisons) { if (_isComparison(node)) { comparisons.add(node); } else if (_isBooleanOperation(node)) { comparisons.addAll(_extractComparisons(node as BinaryExpression)); } } Set<Expression> _extractComparisons(BinaryExpression node) { Set<Expression> comparisons = HashSet<Expression>.identity(); if (_isComparison(node)) { comparisons.add(node); } if (node.operator.type != TokenType.AMPERSAND_AMPERSAND) { return comparisons; } _addNodeComparisons(node.leftOperand, comparisons); _addNodeComparisons(node.rightOperand, comparisons); return comparisons; } bool _isBooleanOperation(Expression expression) => expression is BinaryExpression && BooleanExpressionUtilities.BOOLEAN_OPERATIONS .contains(expression.operator.type); bool _isComparison(Expression expression) => expression is BinaryExpression && BooleanExpressionUtilities.COMPARISONS.contains(expression.operator.type); bool _isNegationOrComparison( TokenType cOperatorType, TokenType eOperatorType, TokenType tokenType) { var isNegationOperation = cOperatorType == BooleanExpressionUtilities.NEGATIONS[eOperatorType] || BooleanExpressionUtilities.IMPLICATIONS[cOperatorType] == BooleanExpressionUtilities.NEGATIONS[eOperatorType]; var isTrichotomyConjunction = BooleanExpressionUtilities.TRICHOTOMY_OPERATORS .contains(eOperatorType) && BooleanExpressionUtilities.TRICHOTOMY_OPERATORS.contains(cOperatorType) && tokenType == TokenType.AMPERSAND_AMPERSAND; var isNegationOrComparison = isNegationOperation || isTrichotomyConjunction; return isNegationOrComparison; } bool _sameOperands(String eLeftOperand, String bcLeftOperand, String eRightOperand, String bcRightOperand) { var sameOperandsSameOrder = eLeftOperand == bcLeftOperand && eRightOperand == bcRightOperand; var sameOperandsInverted = eRightOperand == bcLeftOperand && eLeftOperand == bcRightOperand; return sameOperandsSameOrder || sameOperandsInverted; } typedef _RecurseCallback = void Function(Expression expression); class ContradictoryComparisons { final Expression? first; final Expression second; ContradictoryComparisons(this.first, this.second); } class TestedExpressions { final Expression testingExpression; final Set<Expression> truths; final Set<Expression> negations; LinkedHashSet<ContradictoryComparisons>? _contradictions; TestedExpressions(this.testingExpression, this.truths, this.negations); LinkedHashSet<ContradictoryComparisons>? evaluateInvariant() { if (_contradictions != null) { return _contradictions; } var testingExpression = this.testingExpression; var binaryExpression = testingExpression is BinaryExpression ? testingExpression : null; Iterable<Expression> facts; if (testingExpression is BinaryExpression) { facts = [testingExpression.leftOperand, testingExpression.rightOperand]; } else { facts = [testingExpression]; } _contradictions = _findContradictoryComparisons( LinkedHashSet.from(facts), binaryExpression != null ? binaryExpression.operator.type : TokenType.AMPERSAND_AMPERSAND); if (_contradictions?.isEmpty == true) { var set = (binaryExpression != null ? _extractComparisons(testingExpression as BinaryExpression) : {testingExpression}) ..addAll(truths.whereType<Expression>()) ..addAll(negations.whereType<Expression>()); // Here and in several places we proceed only for // TokenType.AMPERSAND_AMPERSAND because we then know that all comparisons // must be true. _contradictions?.addAll( _findContradictoryComparisons(set, TokenType.AMPERSAND_AMPERSAND)); } return _contradictions; } /// TODO: A truly smart implementation would detect /// (ref.prop && other.otherProp) && (!ref.prop || !other.otherProp) /// assuming properties are pure computations. i.e. dealing with De Morgan's /// laws https://en.wikipedia.org/wiki/De_Morgan%27s_laws LinkedHashSet<ContradictoryComparisons> _findContradictoryComparisons( Set<Expression> comparisons, TokenType tokenType) { Iterable<Expression> binaryExpressions = comparisons.whereType<BinaryExpression>().toSet(); var contradictions = LinkedHashSet<ContradictoryComparisons>.identity(); var testingExpression = this.testingExpression; if (testingExpression is SimpleIdentifier) { bool sameIdentifier(n) => n is SimpleIdentifier && testingExpression.staticElement == n.staticElement; if (negations.any(sameIdentifier)) { var otherIdentifier = negations.firstWhere(sameIdentifier) as SimpleIdentifier?; contradictions .add(ContradictoryComparisons(otherIdentifier, testingExpression)); } } binaryExpressions.forEach((Expression ex) { if (contradictions.isNotEmpty) { return; } var expression = ex as BinaryExpression; var eLeftOperand = expression.leftOperand.toString(); var eRightOperand = expression.rightOperand.toString(); var eOperatorType = expression.operator.type; comparisons .where((comparison) => comparison.offset < expression.offset && comparison is BinaryExpression) .forEach((Expression c) { if (contradictions.isNotEmpty) { return; } var otherExpression = c as BinaryExpression; var bcLeftOperand = otherExpression.leftOperand.toString(); var bcRightOperand = otherExpression.rightOperand.toString(); var sameOperands = _sameOperands( eLeftOperand, bcLeftOperand, eRightOperand, bcRightOperand); var cOperatorType = negations.contains(c) ? BooleanExpressionUtilities .NEGATIONS[otherExpression.operator.type] : otherExpression.operator.type; if (cOperatorType != null) { var isNegationOrComparison = _isNegationOrComparison(cOperatorType, eOperatorType, tokenType); if (isNegationOrComparison && sameOperands) { contradictions .add(ContradictoryComparisons(otherExpression, expression)); } } }); }); if (contradictions.isEmpty) { binaryExpressions.forEach(_recurseOnChildNodes(contradictions)); } return contradictions; } _RecurseCallback _recurseOnChildNodes( LinkedHashSet<ContradictoryComparisons> expressions) => (Expression e) { var ex = e as BinaryExpression; if (ex.operator.type != TokenType.AMPERSAND_AMPERSAND) { return; } var set = _findContradictoryComparisons( HashSet.from([ex.leftOperand, ex.rightOperand]), ex.operator.type); expressions.addAll(set); }; }
linter/lib/src/util/tested_expressions.dart/0
{'file_path': 'linter/lib/src/util/tested_expressions.dart', 'repo_id': 'linter', 'token_count': 2708}
// 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. // @dart=2.9 // ignore_for_file: prefer_initializing_formals // ignore_for_file: unnecessary_new // ignore_for_file: unnecessary_this // ignore_for_file: unused_field // ignore_for_file: unused_local_variable // ignore_for_file: use_setters_to_change_properties import 'dart:async'; import 'dart:io'; class B0 { IOSink _sinkB0; // OK void init(filename) { _sinkB0 = new File(filename).openWrite(); } void dispose(filename) { this._sinkB0.close(); } } class MockIOSink implements Sink { @override void add(data) {} @override void close() {} } IOSink outSink = stdout; void inScope() { IOSink currentOut = outSink; } class A { IOSink _sinkA; // LINT void init(String filename) { _sinkA = new File(filename).openWrite(); } } class B { IOSink _sinkB; void init(String filename) { _sinkB = new File(filename).openWrite(); // OK } void dispose(filename) { _sinkB.close(); } } class B1 { Socket _socketB1; Future init(String filename) async { _socketB1 = await Socket.connect(null /*address*/, 1234); // OK } void dispose(String filename) { _socketB1.destroy(); } } class C { final IOSink _sinkC; // OK C(this._sinkC); } class C1 { final IOSink _sinkC1; // OK final Object unrelated; C1.initializer(IOSink sink, blah) : this._sinkC1 = sink, this.unrelated = blah; } class C2 { IOSink _sinkC2; // OK void initialize(IOSink sink) { this._sinkC2 = sink; } } class C3 { IOSink _sinkC3; // OK void initialize(IOSink sink) { _sinkC3 = sink; } } class D { IOSink init(String filename) { IOSink _sinkF = new File(filename).openWrite(); // OK return _sinkF; } } void someFunction() { IOSink _sinkSomeFunction; // LINT } void someFunctionOK() { IOSink _sinkFOK; // OK _sinkFOK.close(); } IOSink someFunctionReturningIOSink() { IOSink _sinkF = new File('filename').openWrite(); // OK return _sinkF; } void startChunkedConversion(Socket sink) { Sink stringSink; if (sink is IOSink) { stringSink = sink; } else { stringSink = new MockIOSink(); } } void onListen(Stream<int> stream) { StreamController controllerListen = new StreamController(); stream.listen((int event) { event.toString(); }, onError: controllerListen.addError, onDone: controllerListen.close); } void someFunctionClosing(StreamController controller) {} void controllerPassedAsArgument() { StreamController controllerArgument = new StreamController(); someFunctionClosing(controllerArgument); } void fluentInvocation() { StreamController cascadeController = new StreamController() ..add(null) ..close(); } class CascadeSink { StreamController cascadeController = new StreamController(); // OK void closeSink() { cascadeController ..add(null) ..close(); } }
linter/test/_data/close_sinks/src/a.dart/0
{'file_path': 'linter/test/_data/close_sinks/src/a.dart', 'repo_id': 'linter', 'token_count': 1131}
name: p2
linter/test/_data/p2/_pubspec.yaml/0
{'file_path': 'linter/test/_data/p2/_pubspec.yaml', 'repo_id': 'linter', 'token_count': 4}
/// Class b. class b {}
linter/test/_data/p8/src/ignored/b.dart/0
{'file_path': 'linter/test/_data/p8/src/ignored/b.dart', 'repo_id': 'linter', 'token_count': 9}
rules: - unnecessary_lambdas
linter/test/_data/unnecessary_lambdas/lintconfig.yaml/0
{'file_path': 'linter/test/_data/unnecessary_lambdas/lintconfig.yaml', 'repo_id': 'linter', 'token_count': 11}
// 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/src/lint/io.dart'; import 'package:analyzer/src/lint/linter.dart'; import 'package:linter/src/analyzer.dart'; import 'package:linter/src/cli.dart' as cli; import 'package:test/test.dart'; import '../mocks.dart'; void main() { group('unnecessary_string_escapes', () { var currentOut = outSink; var collectingOut = CollectingSink(); setUp(() => outSink = collectingOut); tearDown(() { collectingOut.buffer.clear(); outSink = currentOut; }); test('no_closing_quote', () async { await cli.runLinter([ 'test/_data/unnecessary_string_escapes/no_closing_quote.dart', '--rules=unnecessary_string_escapes', ], LinterOptions()); // No exception. }); }); }
linter/test/integration/unnecessary_string_escapes.dart/0
{'file_path': 'linter/test/integration/unnecessary_string_escapes.dart', 'repo_id': 'linter', 'token_count': 363}
// 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. /// Constants for use in metadata annotations. /// /// See also `@deprecated` and `@override` in the `dart:core` library. /// /// Annotations provide semantic information that tools can use to provide a /// better user experience. For example, an IDE might not autocomplete the name /// of a function that's been marked `@deprecated`, or it might display the /// function's name differently. /// /// For information on installing and importing this library, see the [meta /// package on pub.dev](https://pub.dev/packages/meta). For examples of using /// annotations, see /// [Metadata](https://dart.dev/guides/language/language-tour#metadata) in the /// language tour. library meta; /// Used to annotate a function `f`. Indicates that `f` always throws an /// exception. Any functions that override `f`, in class inheritence, are also /// expected to conform to this contract. /// /// Tools, such as the analyzer, can use this to understand whether a block of /// code "exits". For example: /// /// ```dart /// @alwaysThrows toss() { throw 'Thrown'; } /// /// int fn(bool b) { /// if (b) { /// return 0; /// } else { /// toss(); /// print("Hello."); /// } /// } /// ``` /// /// Without the annotation on `toss`, it would look as though `fn` doesn't /// always return a value. The annotation shows that `fn` does always exit. In /// addition, the annotation reveals that any statements following a call to /// `toss` (like the `print` call) are dead code. /// /// Tools, such as the analyzer, can also expect this contract to be enforced; /// that is, tools may emit warnings if a function with this annotation /// _doesn't_ always throw. const _AlwaysThrows alwaysThrows = _AlwaysThrows(); /// Used to annotate a parameter of an instance method that overrides another /// method. /// /// Indicates that this parameter may have a tighter type than the parameter on /// its superclass. The actual argument will be checked at runtime to ensure it /// is a subtype of the overridden parameter type. /// /// DEPRECATED: Use the `covariant` modifier instead. @deprecated const _Checked checked = _Checked(); /// Used to annotate a library, or any declaration that is part of the public /// interface of a library (such as top-level members, class members, and /// function parameters) to indicate that the annotated API is experimental and /// may be removed or changed at any-time without updating the version of the /// containing package, despite the fact that it would otherwise be a breaking /// change. /// /// If the annotation is applied to a library then it is equivalent to applying /// the annotation to all of the top-level members of the library. Applying the /// annotation to a class does *not* apply the annotation to subclasses, but /// does apply the annotation to members of the class. /// /// Tools, such as the analyzer, can provide feedback if /// /// * the annotation is associated with a declaration that is not part of the /// public interface of a library (such as a local variable or a declaration /// that is private) or a directive other than the first directive in the /// library, or /// * the declaration is referenced by a package that has not explicitly /// indicated its intention to use experimental APIs (details TBD). const _Experimental experimental = _Experimental(); /// Used to annotate an instance or static method `m`. Indicates that `m` must /// either be abstract or must return a newly allocated object or `null`. In /// addition, every method that either implements or overrides `m` is implicitly /// annotated with this same annotation. /// /// Tools, such as the analyzer, can provide feedback if /// /// * the annotation is associated with anything other than a method, or /// * a method that has this annotation can return anything other than a newly /// allocated object or `null`. const _Factory factory = _Factory(); /// Used to annotate a class `C`. Indicates that `C` and all subtypes of `C` /// must be immutable. /// /// A class is immutable if all of the instance fields of the class, whether /// defined directly or inherited, are `final`. /// /// Tools, such as the analyzer, can provide feedback if /// * the annotation is associated with anything other than a class, or /// * a class that has this annotation or extends, implements or mixes in a /// class that has this annotation is not immutable. const Immutable immutable = Immutable(); /// Used to annotate a test framework function that runs a single test. /// /// Tools, such as IDEs, can show invocations of such function in a file /// structure view to help the user navigating in large test files. /// /// The first parameter of the function must be the description of the test. const _IsTest isTest = _IsTest(); /// Used to annotate a test framework function that runs a group of tests. /// /// Tools, such as IDEs, can show invocations of such function in a file /// structure view to help the user navigating in large test files. /// /// The first parameter of the function must be the description of the group. const _IsTestGroup isTestGroup = _IsTestGroup(); /// Used to annotate a const constructor `c`. Indicates that any invocation of /// the constructor must use the keyword `const` unless one or more of the /// arguments to the constructor is not a compile-time constant. /// /// Tools, such as the analyzer, can provide feedback if /// /// * the annotation is associated with anything other than a const constructor, /// or /// * an invocation of a constructor that has this annotation is not invoked /// using the `const` keyword unless one or more of the arguments to the /// constructor is not a compile-time constant. const _Literal literal = _Literal(); /// Used to annotate an instance method `m`. Indicates that every invocation of /// a method that overrides `m` must also invoke `m`. In addition, every method /// that overrides `m` is implicitly annotated with this same annotation. /// /// Note that private methods with this annotation cannot be validly overridden /// outside of the library that defines the annotated method. /// /// Tools, such as the analyzer, can provide feedback if /// /// * the annotation is associated with anything other than an instance method, /// or /// * a method that overrides a method that has this annotation can return /// without invoking the overridden method. const _MustCallSuper mustCallSuper = _MustCallSuper(); /// Used to annotate an instance member (method, getter, setter, operator, or /// field) `m` in a class `C` or mixin `M`. Indicates that `m` should not be /// overridden in any classes that extend or mixin `C` or `M`. /// /// Tools, such as the analyzer, can provide feedback if /// /// * the annotation is associated with anything other than an instance member, /// * the annotation is associated with an abstract member (because subclasses /// are required to override the member), /// * the annotation is associated with an extension method, /// * the annotation is associated with a member `m` in class `C`, and there is /// a class `D` or mixin `M`, that extends or mixes in `C`, that declares an /// overriding member `m`. const _NonVirtual nonVirtual = _NonVirtual(); /// Used to annotate a class, mixin, or extension declaration `C`. Indicates /// that any type arguments declared on `C` are to be treated as optional. /// Tools such as the analyzer and linter can use this information to suppress /// warnings that would otherwise require type arguments on `C` to be provided. const _OptionalTypeArgs optionalTypeArgs = _OptionalTypeArgs(); /// Used to annotate an instance member (method, getter, setter, operator, or /// field) `m` in a class `C`. If the annotation is on a field it applies to the /// getter, and setter if appropriate, that are induced by the field. Indicates /// that `m` should only be invoked from instance methods of `C` or classes that /// extend, implement or mix in `C`, either directly or indirectly. Additionally /// indicates that `m` should only be invoked on `this`, whether explicitly or /// implicitly. /// /// Tools, such as the analyzer, can provide feedback if /// /// * the annotation is associated with anything other than an instance member, /// or /// * an invocation of a member that has this annotation is used outside of an /// instance member defined on a class that extends or mixes in (or a mixin /// constrained to) the class in which the protected member is defined. /// * an invocation of a member that has this annotation is used within an /// instance method, but the receiver is something other than `this`. const _Protected protected = _Protected(); /// Used to annotate a named parameter `p` in a method or function `f`. /// Indicates that every invocation of `f` must include an argument /// corresponding to `p`, despite the fact that `p` would otherwise be an /// optional parameter. /// /// Tools, such as the analyzer, can provide feedback if /// /// * the annotation is associated with anything other than a named parameter, /// * the annotation is associated with a named parameter in a method `m1` that /// overrides a method `m0` and `m0` defines a named parameter with the same /// name that does not have this annotation, or /// * an invocation of a method or function does not include an argument /// corresponding to a named parameter that has this annotation. const Required required = Required(); /// Annotation marking a class as not allowed as a super-type. /// /// Classes in the same package as the marked class may extend, implement or /// mix-in the annotated class. /// /// Tools, such as the analyzer, can provide feedback if /// /// * the annotation is associated with anything other than a class, /// * the annotation is associated with a class `C`, and there is a class or /// mixin `D`, which extends, implements, mixes in, or constrains to `C`, and /// `C` and `D` are declared in different packages. const _Sealed sealed = _Sealed(); /// Used to annotate a field that is allowed to be overridden in Strong Mode. /// /// Deprecated: Most of strong mode is now the default in 2.0, but the notion of /// virtual fields was dropped, so this annotation no longer has any meaning. /// Uses of the annotation should be removed. @deprecated const _Virtual virtual = _Virtual(); /// Used to annotate an instance member that was made public so that it could be /// overridden but that is not intended to be referenced from outside the /// defining library. /// /// Tools, such as the analyzer, can provide feedback if /// /// * the annotation is associated with a declaration other than a public /// instance member in a class or mixin, or /// * the member is referenced outside of the defining library. const _VisibleForOverriding visibleForOverriding = _VisibleForOverriding(); /// Used to annotate a declaration was made public, so that it is more visible /// than otherwise necessary, to make code testable. /// /// Tools, such as the analyzer, can provide feedback if /// /// * the annotation is associated with a declaration not in the `lib` folder /// of a package, or a private declaration, or a declaration in an unnamed /// static extension, or /// * the declaration is referenced outside of its the defining library or a /// library which is in the `test` folder of the defining package. const _VisibleForTesting visibleForTesting = _VisibleForTesting(); /// Used to annotate a class. /// /// See [immutable] for more details. class Immutable { /// A human-readable explanation of the reason why the class is immutable. final String reason; /// Initialize a newly created instance to have the given [reason]. const Immutable([this.reason = '']); } /// Used to annotate a named parameter `p` in a method or function `f`. /// /// See [required] for more details. class Required { /// A human-readable explanation of the reason why the annotated parameter is /// required. For example, the annotation might look like: /// /// ButtonWidget({ /// Function onHover, /// @Required('Buttons must do something when pressed') /// Function onPressed, /// ... /// }) ... final String reason; /// Initialize a newly created instance to have the given [reason]. const Required([this.reason = '']); } class _AlwaysThrows { const _AlwaysThrows(); } class _Checked { const _Checked(); } class _Experimental { const _Experimental(); } class _Factory { const _Factory(); } class _IsTest { const _IsTest(); } class _IsTestGroup { const _IsTestGroup(); } class _Literal { const _Literal(); } class _MustCallSuper { const _MustCallSuper(); } class _NonVirtual { const _NonVirtual(); } class _OptionalTypeArgs { const _OptionalTypeArgs(); } class _Protected { const _Protected(); } class _Sealed { const _Sealed(); } @deprecated class _Virtual { const _Virtual(); } class _VisibleForOverriding { const _VisibleForOverriding(); } class _VisibleForTesting { const _VisibleForTesting(); }
linter/test/mock_packages/meta/lib/meta.dart/0
{'file_path': 'linter/test/mock_packages/meta/lib/meta.dart', 'repo_id': 'linter', 'token_count': 3435}
// 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 avoid_classes_with_only_static_members` class Bad { // LINT static int a; static foo() {} } class Bad2 extends Good1 { // LINT static int staticInt; static foo() {} } class Bad3 {} // OK class Good1 { // OK int a = 0; } class Good2 { // OK void foo() {} } class Good3 { // OK Good3(); } class Color { // OK static const red = '#f00'; static const green = '#0f0'; static const blue = '#00f'; static const black = '#000'; static const white = '#fff'; }
linter/test/rules/avoid_classes_with_only_static_members.dart/0
{'file_path': 'linter/test/rules/avoid_classes_with_only_static_members.dart', 'repo_id': 'linter', 'token_count': 246}
// 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 await_only_futures` import 'dart:async'; bad() async { print(await 23); // LINT } good() async { print(await new Future.value(23)); } Future awaitWrapper(dynamic future) async { return await future; // OK } class CancellableFuture<T> implements Future<T> { @override Stream<T> asStream() { throw new Exception('Not supported.'); } @override Future<T> catchError(Function onError, {bool test(Object error)}) { throw new Exception('Not supported.'); } @override Future<T> timeout(Duration timeLimit, {onTimeout()}) { throw new Exception('Not supported.'); } @override Future<T> whenComplete(action()) { throw new Exception('Not supported.'); } @override Future<R> then<R>(FutureOr<R> Function(T value) onValue, {Function onError}) { throw new Exception('Not supported.'); } } Future awaitCancellableFuture(dynamic future) async { return await new CancellableFuture(); // OK } Future<String> awaitFutureOr(FutureOr<String> callback()) async { return await callback(); // OK } allow_await_null() async { await null; // OK }
linter/test/rules/await_only_futures.dart/0
{'file_path': 'linter/test/rules/await_only_futures.dart', 'repo_id': 'linter', 'token_count': 436}
analyzer: enable-experiment: - non-nullable
linter/test/rules/experiments/nnbd/analysis_options.yaml/0
{'file_path': 'linter/test/rules/experiments/nnbd/analysis_options.yaml', 'repo_id': 'linter', 'token_count': 20}
// 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 missing_whitespace_between_adjacent_strings` f(o) { f('long line' // LINT 'is long'); f('long $f line' // LINT 'is long'); f('long line' ' is long'); // OK f('long line ' 'is long'); // OK f('long $f line ' 'is long'); // OK f('longLineWithoutSpaceCouldBe' 'AnURL'); // OK f('long line\n' 'is long'); // OK f('long line\r' 'is long'); // OK f('long line\t' 'is long'); // OK f(RegExp('(\n)+' '(\n)+' '(\n)+')); // OK new Unresolved('aaa' 'bbb'); // OK matches('(\n)+' '(\n)+' '(\n)+'); // OK } void matches(String value){}
linter/test/rules/missing_whitespace_between_adjacent_strings.dart/0
{'file_path': 'linter/test/rules/missing_whitespace_between_adjacent_strings.dart', 'repo_id': 'linter', 'token_count': 297}
// 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_asserts_with_message` m() { assert(true); // LINT assert(true, ''); // OK } class A { A() : assert(true), // LINT assert(true, ''), // OK super(); }
linter/test/rules/prefer_asserts_with_message.dart/0
{'file_path': 'linter/test/rules/prefer_asserts_with_message.dart', 'repo_id': 'linter', 'token_count': 152}
// 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. // ignore_for_file: prefer_expression_function_bodies f(Iterable<int> i) { var k = 3; return Map.fromIterable(i, key: (k) => k * 2, value: (v) => k); // LINT } g(Iterable<int> i) { return Map.fromIterable(i, key: (k) => k * 2, value: (v) => 0); // LINT } h(Iterable<int> i) { var e = 2; return Map.fromIterable(i, key: (k) => k * e, value: (v) => v + e); // LINT } i(Iterable<int> i) { // Missing key return Map.fromIterable(i, value: (e) => e + 3); // OK } j(Iterable<int> i) { //Not map fromIterable return A.fromIterable(i, key: (e) => e * 2, value: (e) => e + 3); // OK } class A { A.fromIterable(i, {key, value}); }
linter/test/rules/prefer_for_elements_to_map_fromIterable.dart/0
{'file_path': 'linter/test/rules/prefer_for_elements_to_map_fromIterable.dart', 'repo_id': 'linter', 'token_count': 344}
// 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_null_aware_operators` var v; m(p) { var a, b; a == null ? null : a.b; // LINT a == null ? null : a.b(); // LINT a == null ? null : a.b.c; // LINT a == null ? null : a.b.c(); // LINT a.b == null ? null : a.b.c; // LINT a.b == null ? null : a.b.c(); // LINT p == null ? null : p.b; // LINT v == null ? null : v.b; // LINT null == a ? null : a.b; // LINT null == a ? null : a.b(); // LINT null == a ? null : a.b.c; // LINT null == a ? null : a.b.c(); // LINT null == a.b ? null : a.b.c; // LINT null == a.b ? null : a.b.c(); // LINT null == p ? null : p.b; // LINT null == v ? null : v.b; // LINT a != null ? a.b : null; // LINT a != null ? a.b() : null; // LINT a != null ? a.b.c : null; // LINT a != null ? a.b.c() : null; // LINT a.b != null ? a.b.c : null; // LINT a.b != null ? a.b.c() : null; // LINT p != null ? p.b : null; // LINT v != null ? v.b : null; // LINT null != a ? a.b : null; // LINT null != a ? a.b() : null; // LINT null != a ? a.b.c : null; // LINT null != a ? a.b.c() : null; // LINT null != a.b ? a.b.c : null; // LINT null != a.b ? a.b.c() : null; // LINT null != p ? p.b : null; // LINT null != v ? v.b : null; // LINT a == null ? b : a; // OK a == null ? b.c : null; // OK a.b != null ? a.b : null; // OK a == null ? null : a.b + 10; // OK }
linter/test/rules/prefer_null_aware_operators.dart/0
{'file_path': 'linter/test/rules/prefer_null_aware_operators.dart', 'repo_id': 'linter', 'token_count': 688}
// 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 throw_in_finally` class Ok { double compliantMethod() { var i = 5; try { i = 1 / 0; } catch (e) { print(e); } finally { i = i * i; // OK } return i; } } class BadThrow01 { double nonCompliantMethod() { try { print('hello world! ${1 / 0}'); } catch (e) { print(e); } finally { if (1 > 0) { throw 'Find the hidden error :P'; // LINT } else { print('should catch nested throws!'); } } return 1.0; } } class GoodThrow01 { double compliantMethod() { try { print('hello world! ${1 / 0}'); } catch (e) { print(e); } finally { try { print(1 / 0); } catch (e) { throw new WeirdException(); // OK } } return 1.0; } } class WeirdException {} Function registrationGuard; void outer() { try { registrationGuard(); } finally { registrationGuard = () { throw new WeirdException(); // OK }; } }
linter/test/rules/throw_in_finally.dart/0
{'file_path': 'linter/test/rules/throw_in_finally.dart', 'repo_id': 'linter', 'token_count': 525}
// 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 unnecessary_parenthesis` import 'dart:async'; var a, b, c, d; main() async { 1; // OK (1); // LINT print(1); // OK print((1)); // LINT if (a && b || c && d) true; // OK // OK because it may be hard to know all of the precedence rules. if ((a && b) || c && d) true; // OK (await new Future.value(1)).toString(); // OK ('' as String).toString(); // OK !(true as bool); // OK a = (a); // LINT (a) ? true : false; // LINT true ? (a) : false; // LINT true ? true : (a); // LINT // OK because it is unobvious that the space-involving ternary binds tighter // than the cascade. (true ? [] : [])..add(''); // OK (a ?? true) ? true : true; // OK true ? [] : [] ..add(''); // OK m(p: (1 + 3)); // LINT // OK because it is unobvious where cascades fall in precedence. a..b = (c..d); // OK a.b = (c..d); // OK a..b = (c.d); // OK ((x) => x is bool ? x : false)(a); // OK (fn)(a); // LINT // OK because unary operators mixed with space-separated tokens may have // unexpected ordering. !(const [7].contains(42)); // OK !(new List(3).contains(42)); // OK !(await Future.value(false)); // OK -(new List(3).length); // OK !(new List(3).length.isEven); // OK -(new List(3).length.abs().abs().abs()); // OK -(new List(3).length.sign.sign.sign); // OK !(const [7]).contains(42); // OK // OK because some methods are defined on Type, but removing the parentheses // would attempt to call a _static_ method on the target. (String).hashCode; (int).runtimeType; (bool).noSuchMethod(); (double).toString(); ({false: 'false', true: 'true'}).forEach((k, v) => print('$k: $v')); ({false, true}).forEach(print); ({false, true}).length; print(({1, 2, 3}).length); // LINT ([false, true]).forEach(print); // LINT } m({p}) => null; bool Function(dynamic) get fn => (x) => x is bool ? x : false; class ClassWithFunction { Function f; int number; ClassWithFunction.named(int a) : this.number = (a + 2); // LINT // https://github.com/dart-lang/linter/issues/1473 ClassWithFunction.named2(Function value) : this.f = (value ?? (_) => 42); // OK } class ClassWithClassWithFunction { ClassWithFunction c; // https://github.com/dart-lang/linter/issues/1395 ClassWithClassWithFunction() : c = (ClassWithFunction()..f = () => 42); // OK } class UnnecessaryParenthesis { ClassWithClassWithFunction c; UnnecessaryParenthesis() : c = (ClassWithClassWithFunction() ..c = ClassWithFunction().f = () => 42); // OK }
linter/test/rules/unnecessary_parenthesis.dart/0
{'file_path': 'linter/test/rules/unnecessary_parenthesis.dart', 'repo_id': 'linter', 'token_count': 997}
// 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 use_rethrow_when_possible` void bad1() { try {} catch (e) { throw e; // LINT } } void bad2() { try {} catch (e, stackTrace) { print(stackTrace); throw e; // LINT } } void good1() { try {} catch (e) { rethrow; } } void good2() { try {} catch (e) { throw new Exception(); // OK } } void good3() { try {} catch (e) { try {} catch (f) { throw e; // OK } } }
linter/test/rules/use_rethrow_when_possible.dart/0
{'file_path': 'linter/test/rules/use_rethrow_when_possible.dart', 'repo_id': 'linter', 'token_count': 259}
// 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:io'; import 'package:linter/src/version.dart'; import 'package:test/test.dart'; import 'package:yaml/yaml.dart' as yaml; void main() { group('package version', () { test('version file up to date', () { expect(readPackageVersion(), version, reason: 'lib/src/version.dart should match pubspec.yaml'); }); }); } String? readPackageVersion() { var pubspec = File('pubspec.yaml'); var yamlDoc = yaml.loadYaml(pubspec.readAsStringSync()); if (yamlDoc == null) { fail('Cannot find pubspec.yaml in ${Directory.current}'); } var version = yamlDoc['version']; return version as String?; }
linter/test/version_test.dart/0
{'file_path': 'linter/test/version_test.dart', 'repo_id': 'linter', 'token_count': 293}
// 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:convert'; import 'dart:io'; const baseLinePath = 'tool/baseline/pana.json'; void main() async { print('Reading baseline...'); var contents = File(baseLinePath).readAsStringSync(); var baseline = jsonDecode(contents)['scores']; print(baseline); print('Installing pana...'); var activate = await Process.run('pub', ['global', 'activate', 'pana']); expectOk(activate); print(activate.stdout); print('Running pana...'); var output = await Process.run('pub', [ 'global', 'run', 'pana', '-s', 'path', Directory.current.path, '-j', ]); expectOk(output); print(output.stdout); var panaJson = jsonDecode(output.stdout as String); var scores = panaJson['scores']; print(scores); var failureReport = ''; var baselinePoints = baseline['grantedPoints'] as int; var currentPoints = scores['grantedPoints'] as int; if (currentPoints < baselinePoints) { if (failureReport.isNotEmpty) { failureReport += ', '; } failureReport += 'granted points dropped from $baselinePoints to $currentPoints'; } if (failureReport.isNotEmpty) { print('Baseline check failed: $failureReport'); exit(13); } print('Baseline check passed βœ…'); if (currentPoints != baselinePoints) { print( '... you have a new baseline! πŸŽ‰ Consider updating $baseLinePath to match.'); } } void expectOk(ProcessResult result) { if (result.exitCode != 0) { print(result.stdout); print(result.stderr); exit(result.exitCode); } }
linter/tool/pana_baseline.dart/0
{'file_path': 'linter/tool/pana_baseline.dart', 'repo_id': 'linter', 'token_count': 609}
name: liquid_swipe description: A Flutter plugin to implement liquid Swipe effect to provided widgets. version: 2.1.1 homepage: https://github.com/iamSahdeep/liquid_swipe_flutter environment: sdk: '>=2.12.0 <3.0.0' dependencies: flutter: sdk: flutter provider: ^6.0.0 dev_dependencies: flutter_test: sdk: flutter # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec # The following section is specific to Flutter. flutter: # This section identifies this Flutter project as a plugin project. # The androidPackage and pluginClass identifiers should not ordinarily # be modified. They are used by the tooling to maintain consistency when # adding or updating assets for this project. # To add assets to your plugin package, add an assets section, like this: # assets: # - images/a_dot_burr.jpeg # - images/a_dot_ham.jpeg # # For details regarding assets in packages, see # https://flutter.dev/assets-and-images/#from-packages # # An image asset can refer to one or more resolution-specific "variants", see # https://flutter.dev/assets-and-images/#resolution-aware. # To add custom fonts to your plugin package, add a fonts section here, # in this "flutter" section. Each entry in this list should have a # "family" key with the font family name, and a "fonts" key with a # list giving the asset and other descriptors for the font. For # example: # fonts: # - family: Schyler # fonts: # - asset: fonts/Schyler-Regular.ttf # - asset: fonts/Schyler-Italic.ttf # style: italic # - family: Trajan Pro # fonts: # - asset: fonts/TrajanPro.ttf # - asset: fonts/TrajanPro_Bold.ttf # weight: 700 # # For details regarding fonts in packages, see # https://flutter.dev/custom-fonts/#from-packages
liquid_swipe_flutter/pubspec.yaml/0
{'file_path': 'liquid_swipe_flutter/pubspec.yaml', 'repo_id': 'liquid_swipe_flutter', 'token_count': 641}
library lumberdash; export 'src/client/client.dart'; export 'src/lumberdash.dart';
lumberdash/lib/lumberdash.dart/0
{'file_path': 'lumberdash/lib/lumberdash.dart', 'repo_id': 'lumberdash', 'token_count': 30}
blank_issues_enabled: false
mason/.github/ISSUE_TEMPLATE/config.yml/0
{'file_path': 'mason/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'mason', 'token_count': 7}
name: hello description: An example brick. repository: https://github.com/felangel/mason/tree/master/bricks/hello version: 0.1.0+1 environment: mason: ">=0.1.0-dev <0.1.0" vars: name: type: string description: Your name default: Dash prompt: What is your name?
mason/bricks/hello/brick.yaml/0
{'file_path': 'mason/bricks/hello/brick.yaml', 'repo_id': 'mason', 'token_count': 115}
include: ../../analysis_options.yaml analyzer: exclude: - "test/.test_coverage.dart" - "test/fixtures/**" - "**/*.g.dart" - "lib/src/version.dart" linter: rules: no_leading_underscores_for_local_identifiers: false
mason/packages/mason/analysis_options.yaml/0
{'file_path': 'mason/packages/mason/analysis_options.yaml', 'repo_id': 'mason', 'token_count': 105}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'mason_bundle.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** MasonBundledFile _$MasonBundledFileFromJson(Map json) => $checkedCreate( 'MasonBundledFile', json, ($checkedConvert) { $checkKeys( json, allowedKeys: const ['path', 'data', 'type'], ); final val = MasonBundledFile( $checkedConvert('path', (v) => v as String), $checkedConvert('data', (v) => v as String), $checkedConvert('type', (v) => v as String), ); return val; }, ); Map<String, dynamic> _$MasonBundledFileToJson(MasonBundledFile instance) => <String, dynamic>{ 'path': instance.path, 'data': instance.data, 'type': instance.type, }; MasonBundle _$MasonBundleFromJson(Map json) => $checkedCreate( 'MasonBundle', json, ($checkedConvert) { $checkKeys( json, allowedKeys: const [ 'files', 'hooks', 'name', 'description', 'version', 'environment', 'repository', 'publish_to', 'readme', 'changelog', 'license', 'vars' ], ); final val = MasonBundle( name: $checkedConvert('name', (v) => v as String), description: $checkedConvert('description', (v) => v as String), version: $checkedConvert('version', (v) => v as String), environment: $checkedConvert( 'environment', (v) => v == null ? const BrickEnvironment() : BrickEnvironment.fromJson(v as Map)), vars: $checkedConvert( 'vars', (v) => v == null ? const <String, BrickVariableProperties>{} : const VarsConverter().fromJson(v)), files: $checkedConvert( 'files', (v) => (v as List<dynamic>?) ?.map((e) => MasonBundledFile.fromJson( Map<String, dynamic>.from(e as Map))) .toList() ?? const []), hooks: $checkedConvert( 'hooks', (v) => (v as List<dynamic>?) ?.map((e) => MasonBundledFile.fromJson( Map<String, dynamic>.from(e as Map))) .toList() ?? const []), repository: $checkedConvert('repository', (v) => v as String?), publishTo: $checkedConvert('publish_to', (v) => v as String?), readme: $checkedConvert( 'readme', (v) => v == null ? null : MasonBundledFile.fromJson( Map<String, dynamic>.from(v as Map))), changelog: $checkedConvert( 'changelog', (v) => v == null ? null : MasonBundledFile.fromJson( Map<String, dynamic>.from(v as Map))), license: $checkedConvert( 'license', (v) => v == null ? null : MasonBundledFile.fromJson( Map<String, dynamic>.from(v as Map))), ); return val; }, fieldKeyMap: const {'publishTo': 'publish_to'}, ); Map<String, dynamic> _$MasonBundleToJson(MasonBundle instance) { final val = <String, dynamic>{ 'files': instance.files.map((e) => e.toJson()).toList(), 'hooks': instance.hooks.map((e) => e.toJson()).toList(), 'name': instance.name, 'description': instance.description, 'version': instance.version, 'environment': instance.environment.toJson(), }; void writeNotNull(String key, dynamic value) { if (value != null) { val[key] = value; } } writeNotNull('repository', instance.repository); writeNotNull('publish_to', instance.publishTo); writeNotNull('readme', instance.readme?.toJson()); writeNotNull('changelog', instance.changelog?.toJson()); writeNotNull('license', instance.license?.toJson()); writeNotNull('vars', const VarsConverter().toJson(instance.vars)); return val; }
mason/packages/mason/lib/src/mason_bundle.g.dart/0
{'file_path': 'mason/packages/mason/lib/src/mason_bundle.g.dart', 'repo_id': 'mason', 'token_count': 2261}
name: malformed_pubspec_hooks
mason/packages/mason/test/fixtures/malformed_pubspec/hooks/pubspec.yaml/0
{'file_path': 'mason/packages/mason/test/fixtures/malformed_pubspec/hooks/pubspec.yaml', 'repo_id': 'mason', 'token_count': 10}
import 'dart:convert'; import 'package:mason/src/render.dart'; import 'package:mustache_template/mustache_template.dart' show Template; import 'package:test/test.dart'; void main() { group('render', () { test('outputs unchanged string when there are no variables', () { const input = 'hello world'; expect(input.render(<String, dynamic>{}), equals(input)); }); test('outputs correct string when there is a single variable', () { const name = 'dash'; const input = 'hello {{name}}'; const expected = 'hello $name'; expect(input.render(<String, dynamic>{'name': name}), equals(expected)); }); test('outputs correct string when there is are multiple variables', () { const name = 'dash'; const age = 42; const input = 'hello {{name}}! Age is {{age}}'; const expected = 'hello $name! Age is $age'; expect( input.render(<String, dynamic>{'name': name, 'age': age}), equals(expected), ); }); test('outputs correct string when variable is missing', () { const input = 'hello {{name}}!'; const expected = 'hello !'; expect(input.render(<String, dynamic>{}), equals(expected)); }); group('partials', () { test('resolve outputs correct template', () { const name = 'header'; const content = 'Hello world!'; final source = utf8.encode(content); expect( {'{{~ $name }}': source}.resolve(name), isA<Template>() .having((template) => template.name, 'name', name) .having((template) => template.source, 'source', content), ); }); test('resolve outputs correct template w/lambda', () { const name = 'header'; const content = 'Hello {{#upperCase}}{{name}}{{/upperCase}}!'; final source = utf8.encode(content); expect( {'{{~ $name }}': source}.resolve(name), isA<Template>() .having((template) => template.name, 'name', name) .having((template) => template.source, 'source', content), ); }); test('resolve outputs correct template w/lambda shorthand', () { const name = 'header'; const content = 'Hello {{name.upperCase()}}!'; final source = utf8.encode(content); const expected = 'Hello {{#upperCase}}{{name}}{{/upperCase}}!'; expect( {'{{~ $name }}': source}.resolve(name), isA<Template>() .having((template) => template.name, 'name', name) .having((template) => template.source, 'source', expected), ); }); }); group('lambdas', () { test('camelCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{#camelCase}}{{greeting}}{{/camelCase}}!'; const expected = 'Greeting: helloWorld!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('constantCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{#constantCase}}{{greeting}}{{/constantCase}}!'; const expected = 'Greeting: HELLO_WORLD!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('dotCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{#dotCase}}{{greeting}}{{/dotCase}}!'; const expected = 'Greeting: hello.world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('headerCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{#headerCase}}{{greeting}}{{/headerCase}}!'; const expected = 'Greeting: Hello-World!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('lowerCase outputs correct string', () { const greeting = 'Hello World'; const input = 'Greeting: {{#lowerCase}}{{greeting}}{{/lowerCase}}!'; const expected = 'Greeting: hello world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('mustacheCase outputs correct string', () { const greeting = 'Hello World'; const input = 'Greeting: {{#mustacheCase}}{{greeting}}{{/mustacheCase}}!'; const expected = 'Greeting: {{ Hello World }}!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('pascalCase outputs correct string', () { const greeting = 'Hello World'; const input = 'Greeting: {{#pascalCase}}{{greeting}}{{/pascalCase}}!'; const expected = 'Greeting: HelloWorld!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('paramCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{#paramCase}}{{greeting}}{{/paramCase}}!'; const expected = 'Greeting: hello-world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('pathCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{#pathCase}}{{greeting}}{{/pathCase}}!'; const expected = 'Greeting: hello/world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('sentenceCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{#sentenceCase}}{{greeting}}{{/sentenceCase}}!'; const expected = 'Greeting: Hello world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('snakeCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{#snakeCase}}{{greeting}}{{/snakeCase}}!'; const expected = 'Greeting: hello_world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('titleCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{#titleCase}}{{greeting}}{{/titleCase}}!'; const expected = 'Greeting: Hello World!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('upperCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{#upperCase}}{{greeting}}{{/upperCase}}!'; const expected = 'Greeting: HELLO WORLD!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); }); group('lambda shortcuts', () { test('camelCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.camelCase()}}!'; const expected = 'Greeting: helloWorld!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('constantCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.constantCase()}}!'; const expected = 'Greeting: HELLO_WORLD!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('dotCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.dotCase()}}!'; const expected = 'Greeting: hello.world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('headerCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.headerCase()}}!'; const expected = 'Greeting: Hello-World!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('lowerCase outputs correct string', () { const greeting = 'Hello World'; const input = 'Greeting: {{greeting.lowerCase()}}!'; const expected = 'Greeting: hello world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('pascalCase outputs correct string', () { const greeting = 'Hello World'; const input = 'Greeting: {{greeting.pascalCase()}}!'; const expected = 'Greeting: HelloWorld!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('pascalDotCase outputs correct string', () { const greeting = 'Hello World'; const input = 'Greeting: {{greeting.pascalDotCase()}}!'; const expected = 'Greeting: Hello.World!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('paramCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.paramCase()}}!'; const expected = 'Greeting: hello-world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('pathCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.pathCase()}}!'; const expected = 'Greeting: hello/world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('sentenceCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.sentenceCase()}}!'; const expected = 'Greeting: Hello world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('snakeCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.snakeCase()}}!'; const expected = 'Greeting: hello_world!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('titleCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.titleCase()}}!'; const expected = 'Greeting: Hello World!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('upperCase outputs correct string', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.upperCase()}}!'; const expected = 'Greeting: HELLO WORLD!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('support chaining', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.dotCase().upperCase()}}!'; const expected = 'Greeting: HELLO.WORLD!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('support unescaped chaining', () { const greeting = '"hello world"'; const input = 'Greeting: {{{greeting.dotCase().upperCase()}}}!'; const expected = 'Greeting: "HELLO.WORLD"!'; expect( input.render(<String, dynamic>{'greeting': greeting}), equals(expected), ); }); test('support multiple unescaped lambdas', () { const greeting = '"hello world"'; const name = '"dash"'; const input = '''Greeting: {{{greeting.upperCase()}}} Name: {{{name.upperCase()}}}!'''; const expected = 'Greeting: "HELLO WORLD" Name: "DASH"!'; expect( input.render(<String, dynamic>{'greeting': greeting, 'name': name}), equals(expected), ); }); test('mixed with regular mustache syntax after', () { const greeting = 'hello world'; const input = 'Greeting: {{greeting.upperCase()}}{{#is_suffixed}}!{{/is_suffixed}}'; var expected = 'Greeting: HELLO WORLD!'; expect( input.render( <String, dynamic>{ 'greeting': greeting, 'is_suffixed': true, }, ), equals(expected), ); expected = 'Greeting: HELLO WORLD'; expect( input.render( <String, dynamic>{ 'greeting': greeting, 'is_suffixed': false, }, ), equals(expected), ); }); test('mixed with regular mustache syntax before', () { const greeting = 'hello world'; const input = '{{#is_prefixed}}Greeting: {{/is_prefixed}}{{greeting.upperCase()}}!'; var expected = 'Greeting: HELLO WORLD!'; expect( input.render( <String, dynamic>{ 'greeting': greeting, 'is_prefixed': true, }, ), equals(expected), ); expected = 'HELLO WORLD!'; expect( input.render( <String, dynamic>{ 'greeting': greeting, 'is_prefixed': false, }, ), equals(expected), ); }); test('mixed within loop (List<String>)', () { const values = 'RED,GREEN,BLUE,'; const input = 'Greeting: {{#colors}}{{..upperCase()}},{{/colors}}!'; const expected = 'Greeting: $values!'; expect( input.render(<String, dynamic>{ 'colors': ['red', 'green', 'blue'], }), equals(expected), ); }); test('mixed within loop (List<Map>)', () { const values = 'RED,GREEN,BLUE,'; const input = 'Greeting: {{#colors}}{{name.upperCase()}},{{/colors}}!'; const expected = 'Greeting: $values!'; expect( input.render(<String, dynamic>{ 'colors': [ {'name': 'red'}, {'name': 'green'}, {'name': 'blue'}, ], }), equals(expected), ); }); test('handles nested variables', () { const input = '{{greeting.name.upperCase()}}'; const expected = 'HELLO WORLD'; expect( input.render(<String, dynamic>{ 'greeting': { 'name': 'hello world', }, }), equals(expected), ); }); test('allows whitespace', () { const input = '{{ greeting.upperCase() }}'; const expected = 'HELLO WORLD'; expect( input.render(<String, dynamic>{ 'greeting': 'hello world', }), equals(expected), ); }); test('nested lambdas with whitespace', () { const input = '{{ greeting.dotCase().upperCase() }}'; const expected = 'HELLO.WORLD'; expect( input.render(<String, dynamic>{ 'greeting': 'hello world', }), equals(expected), ); }); test('asymmetrical curly brackets (prefix)', () { const input = '{{{greeting.dotCase()}}'; const expected = '{hello.world'; expect( input.render(<String, dynamic>{ 'greeting': 'hello world', }), equals(expected), ); }); test('asymmetrical curly brackets (suffix)', () { const input = '{{greeting.dotCase()}}}'; const expected = 'hello.world}'; expect( input.render(<String, dynamic>{ 'greeting': 'hello world', }), equals(expected), ); }); }); }); }
mason/packages/mason/test/src/render_test.dart/0
{'file_path': 'mason/packages/mason/test/src/render_test.dart', 'repo_id': 'mason', 'token_count': 7635}
import 'package:json_annotation/json_annotation.dart'; part 'credentials.g.dart'; /// {@template credentials} /// Credentials for an authenticated user. /// {@endtemplate} @JsonSerializable() class Credentials { /// {@macro credentials} const Credentials({ required this.accessToken, required this.refreshToken, required this.expiresAt, required this.tokenType, }); /// Converts a [Map] to [Credentials] from a token response. factory Credentials.fromTokenResponse(Map<String, dynamic> json) { return Credentials( accessToken: json['access_token'] as String, refreshToken: json['refresh_token'] as String, expiresAt: DateTime.now() .toUtc() .add(Duration(seconds: int.parse(json['expires_in'] as String))), tokenType: json['token_type'] as String, ); } /// Converts a [Map] to [Credentials]. factory Credentials.fromJson(Map<String, dynamic> json) => _$CredentialsFromJson(json); /// The access token. final String accessToken; /// The refresh token. final String refreshToken; /// When the token expires. final DateTime expiresAt; /// The token type (usually 'Bearer'). final String tokenType; /// Converts a [Credentials] to Map<String, dynamic>. Map<String, dynamic> toJson() => _$CredentialsToJson(this); }
mason/packages/mason_api/lib/src/models/credentials.dart/0
{'file_path': 'mason/packages/mason_api/lib/src/models/credentials.dart', 'repo_id': 'mason', 'token_count': 462}
import 'package:mason/mason.dart' hide packageVersion; import 'package:mason_api/mason_api.dart'; import 'package:mason_cli/src/command.dart'; import 'package:mason_cli/src/command_runner.dart'; /// {@template logout_command} /// `mason logout` command which allows users to log out. /// {@endtemplate} class LogoutCommand extends MasonCommand { /// {@macro logout_command} LogoutCommand({super.logger, MasonApiBuilder? masonApiBuilder}) : _masonApiBuilder = masonApiBuilder ?? MasonApi.new; final MasonApiBuilder _masonApiBuilder; @override final String description = 'Log out of brickhub.dev.'; @override final String name = 'logout'; @override Future<int> run() async { final masonApi = _masonApiBuilder(); final user = masonApi.currentUser; if (user == null) { logger.info('You are already logged out.'); masonApi.close(); return ExitCode.success.code; } final progress = logger.progress('Logging out of brickhub.dev.'); try { masonApi.logout(); progress.complete('Logged out of brickhub.dev'); return ExitCode.success.code; } catch (error) { progress.fail(); logger.err('$error'); return ExitCode.software.code; } finally { masonApi.close(); } } }
mason/packages/mason_cli/lib/src/commands/logout.dart/0
{'file_path': 'mason/packages/mason_cli/lib/src/commands/logout.dart', 'repo_id': 'mason', 'token_count': 483}
name: compilation_error description: A test brick version: 0.1.0+1
mason/packages/mason_cli/test/bricks/compilation_error/brick.yaml/0
{'file_path': 'mason/packages/mason_cli/test/bricks/compilation_error/brick.yaml', 'repo_id': 'mason', 'token_count': 22}
# Register bricks which can be consumed via the Mason CLI. # Run "mason get" to install all registered bricks. # To learn more, visit https://docs.brickhub.dev. bricks: # Bricks can be imported via version constraint from a registry. # Uncomment the following line to import the "hello" brick from BrickHub. # hello: 0.1.0+1 # Bricks can also be imported via remote git url. # Uncomment the following lines to import the "widget" brick from git. # widget: # git: # url: https://github.com/felangel/mason.git # path: bricks/widget
mason/packages/mason_cli/test/fixtures/init/mason.yaml/0
{'file_path': 'mason/packages/mason_cli/test/fixtures/init/mason.yaml', 'repo_id': 'mason', 'token_count': 173}
void main() { print('Android'); }
mason/packages/mason_cli/test/fixtures/make/plugin/android_ios/example/ios.dart/0
{'file_path': 'mason/packages/mason_cli/test/fixtures/make/plugin/android_ios/example/ios.dart', 'repo_id': 'mason', 'token_count': 13}
import 'dart:io'; import 'package:collection/collection.dart'; import 'package:path/path.dart' as path; const _equality = DeepCollectionEquality(); bool directoriesDeepEqual( Directory? a, Directory? b, { List<String> ignore = const <String>[], }) { if (identical(a, b)) return true; if (a == null && b == null) return true; if (a == null || b == null) return false; final dirAContents = a.listSync(recursive: true).whereType<File>(); final dirBContents = b.listSync(recursive: true).whereType<File>(); if (dirAContents.length != dirBContents.length) return false; for (var i = 0; i < dirAContents.length; i++) { final fileEntityA = dirAContents.elementAt(i); final fileEntityB = dirBContents.elementAt(i); final fileA = File(fileEntityA.path); final fileB = File(fileEntityB.path); if (path.basename(fileA.path) != path.basename(fileB.path)) return false; if (ignore.contains(path.basename(fileA.path))) continue; try { final normalizedA = fileA .readAsStringSync() .replaceAll('\r', '') .replaceAll('\n', '') .replaceAll(r'\', '/'); final normalizedB = fileB .readAsStringSync() .replaceAll('\r', '') .replaceAll('\n', '') .replaceAll(r'\', '/'); if (!_equality.equals(normalizedA, normalizedB)) return false; } catch (_) { if (!_equality.equals(fileA.readAsBytesSync(), fileB.readAsBytesSync())) { return false; } } } return true; }
mason/packages/mason_cli/test/helpers/directories_deep_equal.dart/0
{'file_path': 'mason/packages/mason_cli/test/helpers/directories_deep_equal.dart', 'repo_id': 'mason', 'token_count': 617}
export 'package:io/ansi.dart' show AnsiCode, AnsiCodeType, ansiOutputEnabled, backgroundBlack, backgroundBlue, backgroundColors, backgroundCyan, backgroundDarkGray, backgroundDefault, backgroundGreen, backgroundLightBlue, backgroundLightCyan, backgroundLightGray, backgroundLightGreen, backgroundLightMagenta, backgroundLightRed, backgroundLightYellow, backgroundMagenta, backgroundRed, backgroundWhite, backgroundYellow, black, blue, cyan, darkGray, defaultForeground, foregroundColors, green, lightBlue, lightCyan, lightGray, lightGreen, lightMagenta, lightRed, lightYellow, magenta, overrideAnsiOutput, red, resetAll, resetBlink, resetBold, resetDim, resetItalic, resetReverse, resetUnderlined, styleBlink, styleBold, styleDim, styleItalic, styleReverse, styleUnderlined, styles, white, yellow;
mason/packages/mason_logger/lib/src/ansi.dart/0
{'file_path': 'mason/packages/mason_logger/lib/src/ansi.dart', 'repo_id': 'mason', 'token_count': 642}
# Register bricks which can be consumed via the Mason CLI. # https://github.com/felangel/mason bricks: # Sample Brick # Run `mason make hello` to try it out. hello: 0.1.0+1 # Bricks can also be imported via git url. # Uncomment the following lines to import # a brick from a remote git url. firebase_auth_riverpod: path: bricks/firebase_auth_riverpod # widget: # git: # url: https://github.com/felangel/mason.git # path: bricks/widget
mason_bricks-1/mason.yaml/0
{'file_path': 'mason_bricks-1/mason.yaml', 'repo_id': 'mason_bricks-1', 'token_count': 168}