code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
import 'package:bloc_todos/filtered_todos/filtered_todos.dart'; import 'package:bloc_todos/todos/todos.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; class FilteredTodosList extends StatelessWidget { const FilteredTodosList({Key key}) : super(key: key); @override Widget build(BuildContext context) { return BlocBuilder<FilteredTodosBloc, FilteredTodosState>( builder: (context, state) { return ListView.builder( itemCount: state.filteredTodos.length, itemBuilder: (context, index) { final todo = state.filteredTodos[index]; return BlocProvider( create: (context) => TodoBloc( todo: todo, todosBloc: context.bloc<TodosBloc>(), ), child: TodoItem( key: Key('__todo_item_${todo.id}__'), todo: todo, onDismissed: (_) { context.bloc<TodosBloc>().add(TodoDeleted(todo)); Scaffold.of(context).showSnackBar( _DeleteTodoSnackBar( todo: todo, onUndo: () { context.bloc<TodosBloc>().add(TodoAdded(todo)); }, ), ); }, ), ); }, ); }, ); } } class _DeleteTodoSnackBar extends SnackBar { _DeleteTodoSnackBar({ Key key, @required Todo todo, @required VoidCallback onUndo, }) : super( key: key, content: Text( 'Deleted ${todo.task}', maxLines: 1, overflow: TextOverflow.ellipsis, ), duration: const Duration(seconds: 2), action: SnackBarAction( label: 'Undo', onPressed: onUndo, ), ); }
bloc_todos/lib/filtered_todos/filtered_todos_list.dart/0
{'file_path': 'bloc_todos/lib/filtered_todos/filtered_todos_list.dart', 'repo_id': 'bloc_todos', 'token_count': 1071}
part of 'stats_bloc.dart'; abstract class StatsEvent extends Equatable { const StatsEvent(); @override List<Object> get props => []; @override bool get stringify => true; } class TodosChanged extends StatsEvent { const TodosChanged(this.todos); final List<Todo> todos; @override List<Object> get props => [todos]; }
bloc_todos/lib/stats/bloc/stats_event.dart/0
{'file_path': 'bloc_todos/lib/stats/bloc/stats_event.dart', 'repo_id': 'bloc_todos', 'token_count': 117}
export 'bloc/todos_bloc.dart'; export 'models/models.dart'; export 'todo/todo.dart'; export 'todos_page.dart';
bloc_todos/lib/todos/todos.dart/0
{'file_path': 'bloc_todos/lib/todos/todos.dart', 'repo_id': 'bloc_todos', 'token_count': 50}
import 'dart:ui'; import 'dart:math'; import 'package:flame/time.dart'; import 'package:flame/position.dart'; import 'package:flame/sprite.dart'; import 'package:flame/components/component.dart'; import "game.dart"; import "coin.dart"; import "../../main.dart"; final Random random = Random(); class PickUpsHandler { final Game _gameRef; Timer _pickUpCreatorTimer; PickUpsHandler(this._gameRef) { _pickUpCreatorTimer = Timer(5, repeat: true, callback: () { if (random.nextDouble() <= 0.6) { final r = random.nextDouble(); if (r <= 0.2) { _gameRef.add(GoldNuggetComponent(_gameRef)); } else if (r <= 0.4 && _gameRef.controller.powerUp == null) { _gameRef.add(CoffeeComponent(_gameRef)); } else if (r <= 0.6 && _gameRef.controller.powerUp == null) { _gameRef.add(BubbleComponent(_gameRef)); } else if (r <= 0.8 && _gameRef.controller.powerUp == null) { _gameRef.add(MagnetComponent(_gameRef)); } else if(_gameRef.controller.powerUp == null) { final mushroomR = random.nextDouble(); if (mushroomR >= 0.5) { _gameRef.add(GrowMushroomComponent(_gameRef)); } else { _gameRef.add(ShrinkMushroomComponent(_gameRef)); } } } }); _pickUpCreatorTimer.start(); } void update(double dt) { _pickUpCreatorTimer.update(dt); } } abstract class PickupComponent extends SpriteComponent { static const double SPEED = 150; bool _collected = false; bool removed = false; final Game gameRef; PickupComponent(this.gameRef) { sprite = powerUpSprite(_powerUp()); width = 50; height = 50; y = -50; x = (gameRef.size.width - 50) * random.nextDouble(); } PowerUp _powerUp(); void _onPickup(); String _pickupSfx(); @override void update(double dt) { super.update(dt); y += SPEED * dt; if (toRect().overlaps(gameRef.player.toRect())) { _collected = true; _onPickup(); if (_pickupSfx() != null) { Main.soundManager.playSfxs(_pickupSfx()); } } } @override bool destroy() { return removed || _collected || y >= gameRef.size.height; } } enum PowerUp { NUGGET, MAGNET, COFFEE, BUBBLE, GROW_MUSHROOM, SHRINK_MUSHROOM, } Sprite powerUpSprite(PowerUp powerUp) { double textureX; switch(powerUp) { case PowerUp.NUGGET: { textureX = 0; break; } case PowerUp.MAGNET: { textureX = 16; break; } case PowerUp.COFFEE: { textureX = 32; break; } case PowerUp.BUBBLE: { textureX = 48; break; } case PowerUp.GROW_MUSHROOM: { textureX = 64; break; } case PowerUp.SHRINK_MUSHROOM: { textureX = 80; break; } } return Sprite("pick-ups.png", width: 16, height: 16, x: textureX); } class GoldNuggetComponent extends PickupComponent { static double COINS_AMMOUNT = 5; GoldNuggetComponent(Game gameRef): super(gameRef); @override PowerUp _powerUp() => PowerUp.NUGGET; @override String _pickupSfx() => "Nugget"; @override void _onPickup() { final double factor = gameRef.size.width / COINS_AMMOUNT; for (var y = 0; y < COINS_AMMOUNT; y++) { for (var x = 0; x < COINS_AMMOUNT; x++) { gameRef.add( CoinComponent( gameRef, (x * factor) + (factor * random.nextDouble()), y: (y * factor) + (factor * random.nextDouble()), ) ); } } } } class BubbleComponent extends PickupComponent { BubbleComponent(Game gameRef): super(gameRef); @override String _pickupSfx() => "Bubble_Shield"; @override PowerUp _powerUp() => PowerUp.BUBBLE; @override void _onPickup() { gameRef.player.hasBubble = true; } } abstract class HoldeablePickupComponent extends PickupComponent { HoldeablePickupComponent(Game gameRef): super(gameRef); double _time(); void Function() _expireCallback() => null; void _onPickup() { gameRef.controller.powerUpTimer = Timer(_time())..start(); gameRef.controller.powerUpSprite = sprite; gameRef.controller.powerUpSpriteRect = Rect.fromLTWH(gameRef.size.width - 60, 50, 50, 55); gameRef.controller.powerUpTimerTextPosition = Position(gameRef.size.width - 100, 75); gameRef.controller.powerUp = _powerUp(); final callback = _expireCallback(); if (callback != null) { gameRef.controller.powerUpOnFinish = callback; } } } class MagnetComponent extends HoldeablePickupComponent { MagnetComponent(Game gameRef): super(gameRef); @override String _pickupSfx() => "Magnet"; double _time() => 120; PowerUp _powerUp() => PowerUp.MAGNET; } class CoffeeComponent extends HoldeablePickupComponent { CoffeeComponent(Game gameRef): super(gameRef); @override String _pickupSfx() => "Coffee"; @override double _time() => 15.0; @override PowerUp _powerUp() => PowerUp.COFFEE; } class GrowMushroomComponent extends HoldeablePickupComponent { GrowMushroomComponent(Game gameRef): super(gameRef); @override String _pickupSfx() => "Grow"; double _time() => 30.0; @override PowerUp _powerUp() => PowerUp.GROW_MUSHROOM; @override void _onPickup() { super._onPickup(); gameRef.player.grow(); } @override void Function() _expireCallback() => () { gameRef.player.resetGrow(); }; } class ShrinkMushroomComponent extends HoldeablePickupComponent { ShrinkMushroomComponent(Game gameRef): super(gameRef); @override String _pickupSfx() => "Shrink"; @override double _time() => 30.0; @override PowerUp _powerUp() => PowerUp.SHRINK_MUSHROOM; @override void _onPickup() { super._onPickup(); gameRef.player.shrink(); } @override void Function() _expireCallback() => () { gameRef.player.resetShrink(); }; }
bob_box/game/lib/screens/game/pick_ups_handler.dart/0
{'file_path': 'bob_box/game/lib/screens/game/pick_ups_handler.dart', 'repo_id': 'bob_box', 'token_count': 2423}
/// ***************************************************************************** /// Copyright (c) 2015, Daniel Murphy, Google /// All rights reserved. /// /// Redistribution and use in source and binary forms, with or without modification, /// are permitted provided that the following conditions are met: /// * Redistributions of source code must retain the above copyright notice, /// this list of conditions and the following disclaimer. /// * Redistributions in binary form must reproduce the above copyright notice, /// this list of conditions and the following disclaimer in the documentation /// and/or other materials provided with the distribution. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND /// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED /// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. /// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, /// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT /// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR /// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, /// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) /// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE /// POSSIBILITY OF SUCH DAMAGE. /// ***************************************************************************** import 'dart:html'; import 'package:box2d_flame/box2d_browser.dart'; import 'bench2d.dart'; void main() { // Render version new Bench2dWeb() ..initializeAnimation() ..runAnimation(); } class Bench2dWeb extends Bench2d { static const int CANVAS_WIDTH = 900; static const int CANVAS_HEIGHT = 600; static const double _VIEWPORT_SCALE = 10.0; CanvasElement canvas; CanvasRenderingContext2D ctx; ViewportTransform viewport; DebugDraw debugDraw; /// Creates the canvas and readies the demo for animation. Must be called /// before calling runAnimation. void initializeAnimation() { // Setup the canvas. canvas = new CanvasElement() ..width = CANVAS_WIDTH ..height = CANVAS_HEIGHT; ctx = canvas.getContext("2d") as CanvasRenderingContext2D; document.body.append(canvas); // Create the viewport transform with the center at extents. final extents = new Vector2(CANVAS_WIDTH / 2, CANVAS_HEIGHT / 2); viewport = new CanvasViewportTransform(extents, extents) ..scale = _VIEWPORT_SCALE; // Create our canvas drawing tool to give to the world. debugDraw = new CanvasDraw(viewport, ctx); // Have the world draw itself for debugging purposes. world.debugDraw = debugDraw; initialize(); } void render(num delta) { super.step(); ctx.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT); world.drawDebugData(); window.animationFrame.then(render); } void runAnimation() { window.animationFrame.then(render); } }
box2d.dart/benchmark/bench2d_web.dart/0
{'file_path': 'box2d.dart/benchmark/bench2d_web.dart', 'repo_id': 'box2d.dart', 'token_count': 940}
/// ***************************************************************************** /// Copyright (c) 2015, Daniel Murphy, Google /// All rights reserved. /// /// Redistribution and use in source and binary forms, with or without modification, /// are permitted provided that the following conditions are met: /// * Redistributions of source code must retain the above copyright notice, /// this list of conditions and the following disclaimer. /// * Redistributions in binary form must reproduce the above copyright notice, /// this list of conditions and the following disclaimer in the documentation /// and/or other materials provided with the distribution. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND /// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED /// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. /// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, /// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT /// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR /// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, /// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) /// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE /// POSSIBILITY OF SUCH DAMAGE. /// ***************************************************************************** part of box2d; class ConstantVolumeJoint extends Joint { final List<Body> _bodies; Float64List _targetLengths; double _targetVolume = 0.0; List<Vector2> _normals; double _impulse = 0.0; World _world; List<DistanceJoint> _distanceJoints; List<Body> getBodies() { return _bodies; } List<DistanceJoint> getJoints() { return _distanceJoints; } void inflate(double factor) { _targetVolume *= factor; } ConstantVolumeJoint(World argWorld, ConstantVolumeJointDef def) : _bodies = def.bodies.toList(growable: false), super(argWorld.getPool(), def) { _world = argWorld; if (def.bodies.length <= 2) { throw "You cannot create a constant volume joint with less than three _bodies."; } _targetLengths = new Float64List(_bodies.length); for (int i = 0; i < _targetLengths.length; ++i) { final int next = (i == _targetLengths.length - 1) ? 0 : i + 1; double dist = (_bodies[i].worldCenter - _bodies[next].worldCenter).length; _targetLengths[i] = dist; } _targetVolume = getBodyArea(); if (def.joints != null && def.joints.length != def.bodies.length) { throw "Incorrect joint definition. Joints have to correspond to the _bodies"; } if (def.joints == null) { final DistanceJointDef djd = new DistanceJointDef(); _distanceJoints = new List<DistanceJoint>(_bodies.length); for (int i = 0; i < _targetLengths.length; ++i) { final int next = (i == _targetLengths.length - 1) ? 0 : i + 1; djd.frequencyHz = def.frequencyHz; // 20.0; djd.dampingRatio = def.dampingRatio; // 50.0; djd.collideConnected = def.collideConnected; djd.initialize(_bodies[i], _bodies[next], _bodies[i].worldCenter, _bodies[next].worldCenter); _distanceJoints[i] = _world.createJoint(djd) as DistanceJoint; } } else { _distanceJoints = def.joints.toList(); } _normals = new List<Vector2>(_bodies.length); for (int i = 0; i < _normals.length; ++i) { _normals[i] = new Vector2.zero(); } } void destructor() { for (int i = 0; i < _distanceJoints.length; ++i) { _world.destroyJoint(_distanceJoints[i]); } } double getBodyArea() { double area = 0.0; for (int i = 0; i < _bodies.length; ++i) { final int next = (i == _bodies.length - 1) ? 0 : i + 1; area += _bodies[i].worldCenter.x * _bodies[next].worldCenter.y - _bodies[next].worldCenter.x * _bodies[i].worldCenter.y; } area *= .5; return area; } double getSolverArea(List<Position> positions) { double area = 0.0; for (int i = 0; i < _bodies.length; ++i) { final int next = (i == _bodies.length - 1) ? 0 : i + 1; area += positions[_bodies[i]._islandIndex].c.x * positions[_bodies[next]._islandIndex].c.y - positions[_bodies[next]._islandIndex].c.x * positions[_bodies[i]._islandIndex].c.y; } area *= .5; return area; } bool _constrainEdges(List<Position> positions) { double perimeter = 0.0; for (int i = 0; i < _bodies.length; ++i) { final int next = (i == _bodies.length - 1) ? 0 : i + 1; double dx = positions[_bodies[next]._islandIndex].c.x - positions[_bodies[i]._islandIndex].c.x; double dy = positions[_bodies[next]._islandIndex].c.y - positions[_bodies[i]._islandIndex].c.y; double dist = Math.sqrt(dx * dx + dy * dy); if (dist < Settings.EPSILON) { dist = 1.0; } _normals[i].x = dy / dist; _normals[i].y = -dx / dist; perimeter += dist; } final Vector2 delta = pool.popVec2(); double deltaArea = _targetVolume - getSolverArea(positions); double toExtrude = 0.5 * deltaArea / perimeter; // *relaxationFactor // double sumdeltax = 0.0f; bool done = true; for (int i = 0; i < _bodies.length; ++i) { final int next = (i == _bodies.length - 1) ? 0 : i + 1; delta.setValues(toExtrude * (_normals[i].x + _normals[next].x), toExtrude * (_normals[i].y + _normals[next].y)); // sumdeltax += dx; double normSqrd = delta.length2; if (normSqrd > Settings.maxLinearCorrection * Settings.maxLinearCorrection) { delta.scale(Settings.maxLinearCorrection / Math.sqrt(normSqrd)); } if (normSqrd > Settings.linearSlop * Settings.linearSlop) { done = false; } positions[_bodies[next]._islandIndex].c.x += delta.x; positions[_bodies[next]._islandIndex].c.y += delta.y; // _bodies[next]._linearVelocity.x += delta.x * step.inv_dt; // _bodies[next]._linearVelocity.y += delta.y * step.inv_dt; } pool.pushVec2(1); // System.out.println(sumdeltax); return done; } void initVelocityConstraints(final SolverData step) { List<Velocity> velocities = step.velocities; List<Position> positions = step.positions; final List<Vector2> d = pool.getVec2Array(_bodies.length); for (int i = 0; i < _bodies.length; ++i) { final int prev = (i == 0) ? _bodies.length - 1 : i - 1; final int next = (i == _bodies.length - 1) ? 0 : i + 1; d[i].setFrom(positions[_bodies[next]._islandIndex].c); d[i].sub(positions[_bodies[prev]._islandIndex].c); } if (step.step.warmStarting) { _impulse *= step.step.dtRatio; // double lambda = -2.0f * crossMassSum / dotMassSum; // System.out.println(crossMassSum + " " +dotMassSum); // lambda = MathUtils.clamp(lambda, -Settings.maxLinearCorrection, // Settings.maxLinearCorrection); // _impulse = lambda; for (int i = 0; i < _bodies.length; ++i) { velocities[_bodies[i]._islandIndex].v.x += _bodies[i]._invMass * d[i].y * .5 * _impulse; velocities[_bodies[i]._islandIndex].v.y += _bodies[i]._invMass * -d[i].x * .5 * _impulse; } } else { _impulse = 0.0; } } bool solvePositionConstraints(SolverData step) { return _constrainEdges(step.positions); } void solveVelocityConstraints(final SolverData step) { double crossMassSum = 0.0; double dotMassSum = 0.0; List<Velocity> velocities = step.velocities; List<Position> positions = step.positions; final List<Vector2> d = pool.getVec2Array(_bodies.length); for (int i = 0; i < _bodies.length; ++i) { final int prev = (i == 0) ? _bodies.length - 1 : i - 1; final int next = (i == _bodies.length - 1) ? 0 : i + 1; d[i].setFrom(positions[_bodies[next]._islandIndex].c); d[i].sub(positions[_bodies[prev]._islandIndex].c); dotMassSum += (d[i].length2) / _bodies[i].mass; crossMassSum += velocities[_bodies[i]._islandIndex].v.cross(d[i]); } double lambda = -2.0 * crossMassSum / dotMassSum; // System.out.println(crossMassSum + " " +dotMassSum); // lambda = MathUtils.clamp(lambda, -Settings.maxLinearCorrection, // Settings.maxLinearCorrection); _impulse += lambda; // System.out.println(_impulse); for (int i = 0; i < _bodies.length; ++i) { velocities[_bodies[i]._islandIndex].v.x += _bodies[i]._invMass * d[i].y * .5 * lambda; velocities[_bodies[i]._islandIndex].v.y += _bodies[i]._invMass * -d[i].x * .5 * lambda; } } /// No-op void getAnchorA(Vector2 argOut) {} /// No-op void getAnchorB(Vector2 argOut) {} /// No-op void getReactionForce(double inv_dt, Vector2 argOut) {} /// No-op double getReactionTorque(double inv_dt) { return 0.0; } }
box2d.dart/lib/src/dynamics/joints/constant_volume_joints.dart/0
{'file_path': 'box2d.dart/lib/src/dynamics/joints/constant_volume_joints.dart', 'repo_id': 'box2d.dart', 'token_count': 3703}
/// ***************************************************************************** /// Copyright (c) 2015, Daniel Murphy, Google /// All rights reserved. /// /// Redistribution and use in source and binary forms, with or without modification, /// are permitted provided that the following conditions are met: /// * Redistributions of source code must retain the above copyright notice, /// this list of conditions and the following disclaimer. /// * Redistributions in binary form must reproduce the above copyright notice, /// this list of conditions and the following disclaimer in the documentation /// and/or other materials provided with the distribution. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND /// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED /// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. /// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, /// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT /// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR /// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, /// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) /// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE /// POSSIBILITY OF SUCH DAMAGE. /// ***************************************************************************** part of box2d; /// A mouse joint is used to make a point on a body track a specified world point. This a soft /// constraint with a maximum force. This allows the constraint to stretch and without applying huge /// forces. NOTE: this joint is not documented in the manual because it was developed to be used in /// the testbed. If you want to learn how to use the mouse joint, look at the testbed. class MouseJoint extends Joint { final Vector2 _localAnchorB = new Vector2.zero(); final Vector2 _targetA = new Vector2.zero(); double _frequencyHz = 0.0; double _dampingRatio = 0.0; double _beta = 0.0; // Solver shared final Vector2 _impulse = new Vector2.zero(); double _maxForce = 0.0; double _gamma = 0.0; // Solver temp int _indexB = 0; final Vector2 _rB = new Vector2.zero(); final Vector2 _localCenterB = new Vector2.zero(); double _invMassB = 0.0; double _invIB = 0.0; final Matrix2 _mass = new Matrix2.zero(); final Vector2 _C = new Vector2.zero(); MouseJoint(IWorldPool argWorld, MouseJointDef def) : super(argWorld, def) { assert(MathUtils.vector2IsValid(def.target)); assert(def.maxForce >= 0); assert(def.frequencyHz >= 0); assert(def.dampingRatio >= 0); _targetA.setFrom(def.target); Transform.mulTransToOutUnsafeVec2( _bodyB._transform, _targetA, _localAnchorB); _maxForce = def.maxForce; _impulse.setZero(); _frequencyHz = def.frequencyHz; _dampingRatio = def.dampingRatio; } void getAnchorA(Vector2 argOut) { argOut.setFrom(_targetA); } void getAnchorB(Vector2 argOut) { _bodyB.getWorldPointToOut(_localAnchorB, argOut); } void getReactionForce(double invDt, Vector2 argOut) { argOut ..setFrom(_impulse) ..scale(invDt); } double getReactionTorque(double invDt) { return invDt * 0.0; } void setTarget(Vector2 target) { if (_bodyB.isAwake() == false) { _bodyB.setAwake(true); } _targetA.setFrom(target); } Vector2 getTarget() { return _targetA; } void initVelocityConstraints(final SolverData data) { _indexB = _bodyB._islandIndex; _localCenterB.setFrom(_bodyB._sweep.localCenter); _invMassB = _bodyB._invMass; _invIB = _bodyB._invI; Vector2 cB = data.positions[_indexB].c; double aB = data.positions[_indexB].a; Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; final Rot qB = pool.popRot(); qB.setAngle(aB); double mass = _bodyB.mass; // Frequency double omega = 2.0 * Math.pi * _frequencyHz; // Damping coefficient double d = 2.0 * mass * _dampingRatio * omega; // Spring stiffness double k = mass * (omega * omega); // magic formulas // gamma has units of inverse mass. // beta has units of inverse time. double h = data.step.dt; assert(d + h * k > Settings.EPSILON); _gamma = h * (d + h * k); if (_gamma != 0.0) { _gamma = 1.0 / _gamma; } _beta = h * k * _gamma; Vector2 temp = pool.popVec2(); // Compute the effective mass matrix. Rot.mulToOutUnsafe( qB, temp ..setFrom(_localAnchorB) ..sub(_localCenterB), _rB); // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] final Matrix2 K = pool.popMat22(); double a11 = _invMassB + _invIB * _rB.y * _rB.y + _gamma; double a21 = -_invIB * _rB.x * _rB.y; double a12 = a21; double a22 = _invMassB + _invIB * _rB.x * _rB.x + _gamma; K.setValues(a11, a21, a12, a22); _mass.setFrom(K); _mass.invert(); _C ..setFrom(cB) ..add(_rB) ..sub(_targetA); _C.scale(_beta); // Cheat with some damping wB *= 0.98; if (data.step.warmStarting) { _impulse.scale(data.step.dtRatio); vB.x += _invMassB * _impulse.x; vB.y += _invMassB * _impulse.y; wB += _invIB * _rB.cross(_impulse); } else { _impulse.setZero(); } // data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; pool.pushVec2(1); pool.pushMat22(1); pool.pushRot(1); } bool solvePositionConstraints(final SolverData data) { return true; } void solveVelocityConstraints(final SolverData data) { Vector2 vB = data.velocities[_indexB].v; double wB = data.velocities[_indexB].w; // Cdot = v + cross(w, r) final Vector2 Cdot = pool.popVec2(); _rB.scaleOrthogonalInto(wB, Cdot); Cdot.add(vB); final Vector2 impulse = pool.popVec2(); final Vector2 temp = pool.popVec2(); temp ..setFrom(_impulse) ..scale(_gamma) ..add(_C) ..add(Cdot) ..negate(); _mass.transformed(temp, impulse); Vector2 oldImpulse = temp; oldImpulse.setFrom(_impulse); _impulse.add(impulse); double maxImpulse = data.step.dt * _maxForce; if (_impulse.length2 > maxImpulse * maxImpulse) { _impulse.scale(maxImpulse / _impulse.length); } impulse ..setFrom(_impulse) ..sub(oldImpulse); vB.x += _invMassB * impulse.x; vB.y += _invMassB * impulse.y; wB += _invIB * _rB.cross(impulse); // data.velocities[_indexB].v.set(vB); data.velocities[_indexB].w = wB; pool.pushVec2(3); } }
box2d.dart/lib/src/dynamics/joints/mouse_joint.dart/0
{'file_path': 'box2d.dart/lib/src/dynamics/joints/mouse_joint.dart', 'repo_id': 'box2d.dart', 'token_count': 2799}
/******************************************************************************* * Copyright (c) 2015, Daniel Murphy, Google * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ part of box2d; class IntArray { final HashMap<int, List<int>> _map = new HashMap<int, List<int>>(); List<int> get(int argLength) { assert(argLength > 0); if (!_map.containsKey(argLength)) { _map[argLength] = getInitializedArray(argLength); } assert(_map[argLength].length == argLength); // : "Array not built of correct length"; return _map[argLength]; } List<int> getInitializedArray(int argLength) { return BufferUtils.allocClearIntList(argLength); } }
box2d.dart/lib/src/pooling/arrays/int_array.dart/0
{'file_path': 'box2d.dart/lib/src/pooling/arrays/int_array.dart', 'repo_id': 'box2d.dart', 'token_count': 587}
import 'dart:math' as math; import 'package:brache/src/core/src/component/component.dart'; import 'package:brache/src/core/src/renderer/renderer.dart'; import 'package:brache/src/core/src/renderer/src/canvas_renderer.dart'; class Ellipse extends $Component<Ellipse> { Ellipse({ required super.x, required super.y, required this.radiusX, required this.radiusY, required super.color, }); final double radiusX; final double radiusY; @override void draw($Renderer renderer) { if (renderer is CanvasRenderer) { renderer.ctx.beginPath(); renderer.ctx.ellipse(x, y, radiusX, radiusY, 0, 0, 2 * math.pi, false); renderer.ctx.fillStyle = color; renderer.ctx.fill(); } } @override Ellipse copyWith({double? x, double? y, String? color}) { return Ellipse( x: x ?? this.x, y: y ?? this.y, radiusX: radiusX, radiusY: radiusY, color: color ?? this.color, ); } }
brache/packages/brache/lib/src/components/src/shapes/src/ellipse.dart/0
{'file_path': 'brache/packages/brache/lib/src/components/src/shapes/src/ellipse.dart', 'repo_id': 'brache', 'token_count': 402}
import 'dart:html'; import 'package:brache/src/core/src/component/component.dart'; import 'package:brache/src/core/src/renderer/renderer.dart'; import 'package:brache/src/core/src/scene/scene.dart'; /// Represents a renderer which uses the HTML Canvas API. class CanvasRenderer implements $Renderer { /// Creates a new [CanvasRenderer] instance. CanvasRenderer(this.canvas) { ctx = canvas.getContext('2d')! as CanvasRenderingContext2D; } /// The canvas element used for rendering. late CanvasElement canvas; /// The rendering context used for drawing. late CanvasRenderingContext2D ctx; @override void init() { clearScene(); } @override void renderShape($Component shape) { shape.draw(this); } @override void renderShapes(List<$Component> shapes) { for (final shape in shapes) { renderShape(shape); } } @override void clearScene() { ctx.clearRect(0, 0, canvas.width!, canvas.height!); } @override void updateScene(Scene scene) { clearScene(); for (final shape in scene.getAllComponents()) { renderShape(shape); } } @override void setFillColor(String color) { ctx.fillStyle = color; } @override void setStrokeColor(String color) { ctx.strokeStyle = color; } @override void beginRenderCycle() { saveState(); } @override void endRenderCycle() { restoreState(); } @override void saveState() { ctx.save(); } @override void restoreState() { ctx.restore(); } @override void translate(double dx, double dy) { ctx.translate(dx, dy); } @override void rotate(double angle) { ctx.rotate(angle); } @override void scale(double scaleX, double scaleY) { ctx.scale(scaleX, scaleY); } @override void resize(int width, int height) { canvas ..width = width ..height = height; } }
brache/packages/brache/lib/src/core/src/renderer/src/canvas_renderer.dart/0
{'file_path': 'brache/packages/brache/lib/src/core/src/renderer/src/canvas_renderer.dart', 'repo_id': 'brache', 'token_count': 709}
import 'dart:io'; import 'package:mason_logger/mason_logger.dart'; import 'package:mocktail/mocktail.dart'; import 'package:brache_cli/src/command_runner.dart'; import 'package:brache_cli/src/commands/commands.dart'; import 'package:brache_cli/src/version.dart'; import 'package:pub_updater/pub_updater.dart'; import 'package:test/test.dart'; class _MockLogger extends Mock implements Logger {} class _MockProgress extends Mock implements Progress {} class _MockPubUpdater extends Mock implements PubUpdater {} void main() { const latestVersion = '0.0.0'; group('update', () { late PubUpdater pubUpdater; late Logger logger; late BracheCliCommandRunner commandRunner; setUp(() { final progress = _MockProgress(); final progressLogs = <String>[]; pubUpdater = _MockPubUpdater(); logger = _MockLogger(); commandRunner = BracheCliCommandRunner( logger: logger, pubUpdater: pubUpdater, ); when( () => pubUpdater.getLatestVersion(any()), ).thenAnswer((_) async => packageVersion); when( () => pubUpdater.update( packageName: packageName, versionConstraint: latestVersion, ), ).thenAnswer( (_) async => ProcessResult(0, ExitCode.success.code, null, null), ); when( () => pubUpdater.isUpToDate( packageName: any(named: 'packageName'), currentVersion: any(named: 'currentVersion'), ), ).thenAnswer((_) async => true); when(() => progress.complete(any())).thenAnswer((_) { final message = _.positionalArguments.elementAt(0) as String?; if (message != null) progressLogs.add(message); }); when(() => logger.progress(any())).thenReturn(progress); }); test('can be instantiated without a pub updater', () { final command = UpdateCommand(logger: logger); expect(command, isNotNull); }); test( 'handles pub latest version query errors', () async { when( () => pubUpdater.getLatestVersion(any()), ).thenThrow(Exception('oops')); final result = await commandRunner.run(['update']); expect(result, equals(ExitCode.software.code)); verify(() => logger.progress('Checking for updates')).called(1); verify(() => logger.err('Exception: oops')); verifyNever( () => pubUpdater.update( packageName: any(named: 'packageName'), versionConstraint: any(named: 'versionConstraint'), ), ); }, ); test( 'handles pub update errors', () async { when( () => pubUpdater.getLatestVersion(any()), ).thenAnswer((_) async => latestVersion); when( () => pubUpdater.update( packageName: any(named: 'packageName'), versionConstraint: any(named: 'versionConstraint'), ), ).thenThrow(Exception('oops')); final result = await commandRunner.run(['update']); expect(result, equals(ExitCode.software.code)); verify(() => logger.progress('Checking for updates')).called(1); verify(() => logger.err('Exception: oops')); verify( () => pubUpdater.update( packageName: any(named: 'packageName'), versionConstraint: any(named: 'versionConstraint'), ), ).called(1); }, ); test('handles pub update process errors', () async { const error = 'Oh no! Installing this is not possible right now!'; when( () => pubUpdater.getLatestVersion(any()), ).thenAnswer((_) async => latestVersion); when( () => pubUpdater.update( packageName: any(named: 'packageName'), versionConstraint: any(named: 'versionConstraint'), ), ).thenAnswer((_) async => ProcessResult(0, 1, null, error)); final result = await commandRunner.run(['update']); expect(result, equals(ExitCode.software.code)); verify(() => logger.progress('Checking for updates')).called(1); verify(() => logger.err('Error updating CLI: $error')); verify( () => pubUpdater.update( packageName: any(named: 'packageName'), versionConstraint: any(named: 'versionConstraint'), ), ).called(1); }); test( 'updates when newer version exists', () async { when( () => pubUpdater.getLatestVersion(any()), ).thenAnswer((_) async => latestVersion); when( () => pubUpdater.update( packageName: any(named: 'packageName'), versionConstraint: any(named: 'versionConstraint'), ), ).thenAnswer( (_) async => ProcessResult(0, ExitCode.success.code, null, null), ); when(() => logger.progress(any())).thenReturn(_MockProgress()); final result = await commandRunner.run(['update']); expect(result, equals(ExitCode.success.code)); verify(() => logger.progress('Checking for updates')).called(1); verify(() => logger.progress('Updating to $latestVersion')).called(1); verify( () => pubUpdater.update( packageName: packageName, versionConstraint: latestVersion, ), ).called(1); }, ); test( 'does not update when already on latest version', () async { when( () => pubUpdater.getLatestVersion(any()), ).thenAnswer((_) async => packageVersion); when(() => logger.progress(any())).thenReturn(_MockProgress()); final result = await commandRunner.run(['update']); expect(result, equals(ExitCode.success.code)); verify( () => logger.info('CLI is already at the latest version.'), ).called(1); verifyNever(() => logger.progress('Updating to $latestVersion')); verifyNever( () => pubUpdater.update( packageName: any(named: 'packageName'), versionConstraint: any(named: 'versionConstraint'), ), ); }, ); }); }
brache/packages/brache_cli/test/src/commands/update_command_test.dart/0
{'file_path': 'brache/packages/brache_cli/test/src/commands/update_command_test.dart', 'repo_id': 'brache', 'token_count': 2619}
blank_issues_enabled: false
broadcast_bloc/.github/ISSUE_TEMPLATE/config.yml/0
{'file_path': 'broadcast_bloc/.github/ISSUE_TEMPLATE/config.yml', 'repo_id': 'broadcast_bloc', 'token_count': 7}
targets: $default: builders: build_web_compilers:entrypoint: options: compiler: dart2js dart2js_args: - --enable-asserts generate_for: - web/main.dart - web/sub/main.dart - test/configurable_uri_test.dart - test/configurable_uri_test.dart.browser_test.dart - test/hello_world_test.dart - test/hello_world_test.dart.browser_test.dart - test/hello_world_deferred_test.dart - test/hello_world_deferred_test.dart.browser_test.dart - test/hello_world_custom_html_test.dart - test/hello_world_custom_html_test.dart.browser_test.dart - test/other_test.dart.browser_test.dart - test/sub-dir/subdir_test.dart - test/sub-dir/subdir_test.dart.browser_test.dart build_vm_compilers:entrypoint: generate_for: - test/configurable_uri_test.dart.vm_test.dart - test/help_test.dart.vm_test.dart
build/_test/build.dart2js.yaml/0
{'file_path': 'build/_test/build.dart2js.yaml', 'repo_id': 'build', 'token_count': 513}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build/build.dart'; import 'package:build_runner_core/build_runner_core.dart'; class RunnerAssetWriterSpy extends AssetWriterSpy implements RunnerAssetWriter { final RunnerAssetWriter _delegate; final _assetsDeleted = <AssetId>{}; Iterable<AssetId> get assetsDeleted => _assetsDeleted; RunnerAssetWriterSpy(this._delegate) : super(_delegate); @override Future delete(AssetId id) { _assetsDeleted.add(id); return _delegate.delete(id); } }
build/_test_common/lib/runner_asset_writer_spy.dart/0
{'file_path': 'build/_test_common/lib/runner_asset_writer_spy.dart', 'repo_id': 'build', 'token_count': 223}
// 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:async'; import 'build_step.dart'; /// The basic builder class, used to build new files from existing ones. abstract class Builder { /// Generates the outputs for a given [BuildStep]. FutureOr<void> build(BuildStep buildStep); /// Mapping from input file extension to output file extensions. /// /// All input sources matching any key in this map will be passed as build /// step to this builder. Only files with the same basename and an extension /// from the values in this map are expected as outputs. /// /// - If an empty key exists, all inputs are considered matching. /// - An instance of a builder must always return the same configuration. /// Typically, a builder will return a `const` map. Builders may also choose /// extensions based on [BuilderOptions]. /// - Most builders will use a single input extension and one or more output /// extensions. /// - For more information on build extensions, see /// https://github.com/dart-lang/build/blob/master/docs/writing_a_builder.md#configuring-outputs Map<String, List<String>> get buildExtensions; } class BuilderOptions { /// A configuration with no options set. static const empty = BuilderOptions({}); /// A configuration with [isRoot] set to `true`, and no options set. static const forRoot = BuilderOptions({}, isRoot: true); /// The configuration to apply to a given usage of a [Builder]. /// /// A `Map` parsed from json or yaml. The value types will be `String`, `num`, /// `bool` or `List` or `Map` of these types. final Map<String, dynamic> config; /// Whether or not this builder is running on the root package. final bool isRoot; const BuilderOptions(this.config, {this.isRoot = false}); /// Returns a new set of options with keys from [other] overriding options in /// this instance. /// /// Config values are overridden at a per-key granularity. There is no value /// level merging. [other] may be null, in which case this instance is /// returned directly. /// /// The `isRoot` value will also be overridden to value from [other]. BuilderOptions overrideWith(BuilderOptions? other) { if (other == null) return this; return BuilderOptions( {} ..addAll(config) ..addAll(other.config), isRoot: other.isRoot); } } /// Creates a [Builder] honoring the configuation in [options]. typedef BuilderFactory = Builder Function(BuilderOptions options);
build/build/lib/src/builder/builder.dart/0
{'file_path': 'build/build/lib/src/builder/builder.dart', 'repo_id': 'build', 'token_count': 751}
// 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. @TestOn('vm') import 'dart:async'; import 'dart:convert'; import 'package:build/build.dart'; import 'package:build/src/builder/build_step.dart'; import 'package:build/src/builder/build_step_impl.dart'; import 'package:build_resolvers/build_resolvers.dart'; import 'package:build_test/build_test.dart'; import 'package:test/test.dart'; void main() { late ResourceManager resourceManager; setUp(() { resourceManager = ResourceManager(); }); tearDown(() async { await resourceManager.disposeAll(); }); group('with reader/writer stub', () { late AssetId primary; late BuildStepImpl buildStep; late List<AssetId> outputs; setUp(() { var reader = StubAssetReader(); var writer = StubAssetWriter(); primary = makeAssetId(); outputs = List.generate(5, (index) => makeAssetId()); buildStep = BuildStepImpl(primary, outputs, reader, writer, AnalyzerResolvers(), resourceManager); }); test('doesnt allow non-expected outputs', () { var id = makeAssetId(); expect(() => buildStep.writeAsString(id, '$id'), throwsA(TypeMatcher<UnexpectedOutputException>())); expect(() => buildStep.writeAsBytes(id, [0]), throwsA(TypeMatcher<UnexpectedOutputException>())); }); test('reports allowed outputs', () { expect(buildStep.allowedOutputs, outputs); }); test('fetchResource can fetch resources', () async { var expected = 1; var intResource = Resource(() => expected); var actual = await buildStep.fetchResource(intResource); expect(actual, expected); }); test('does not allow multiple writes to the same output', () async { final id = outputs.first; await buildStep.writeAsString(id, 'foo'); final expectedException = isA<InvalidOutputException>() .having((e) => e.assetId, 'assetId', id) .having((e) => e.message, 'message', contains('already wrote to')); expect( () => buildStep.writeAsString(id, 'bar'), throwsA(expectedException)); expect(() => buildStep.writeAsBytes(id, []), throwsA(expectedException)); }); }); group('with in memory file system', () { late InMemoryAssetWriter writer; late InMemoryAssetReader reader; setUp(() { writer = InMemoryAssetWriter(); reader = InMemoryAssetReader.shareAssetCache(writer.assets); }); test('tracks outputs created by a builder', () async { var builder = TestBuilder(); var primary = makeAssetId('a|web/primary.txt'); var inputs = { primary: 'foo', }; addAssets(inputs, writer); var outputId = AssetId.parse('$primary.copy'); var buildStep = BuildStepImpl(primary, [outputId], reader, writer, AnalyzerResolvers(), resourceManager); await builder.build(buildStep); await buildStep.complete(); // One output. expect(writer.assets[outputId], decodedMatches('foo')); }); group('resolve', () { test('can resolve assets', () async { var inputs = { makeAssetId('a|web/a.dart'): ''' library a; import 'b.dart'; ''', makeAssetId('a|web/b.dart'): ''' library b; ''', }; addAssets(inputs, writer); var primary = makeAssetId('a|web/a.dart'); var buildStep = BuildStepImpl( primary, [], reader, writer, AnalyzerResolvers(), resourceManager); var resolver = buildStep.resolver; var aLib = await resolver.libraryFor(primary); expect(aLib.name, 'a'); expect(aLib.importedLibraries.length, 2); expect(aLib.importedLibraries.any((library) => library.name == 'b'), isTrue); var bLib = await resolver.findLibraryByName('b'); expect(bLib!.name, 'b'); expect(bLib.importedLibraries.length, 1); await buildStep.complete(); }); }); }); group('With slow writes', () { late BuildStepImpl buildStep; late SlowAssetWriter assetWriter; late AssetId outputId; late String outputContent; setUp(() async { var primary = makeAssetId(); assetWriter = SlowAssetWriter(); outputId = makeAssetId('a|test.txt'); outputContent = '$outputId'; buildStep = BuildStepImpl(primary, [outputId], StubAssetReader(), assetWriter, AnalyzerResolvers(), resourceManager); }); test('Completes only after writes finish', () async { unawaited(buildStep.writeAsString(outputId, outputContent)); var isComplete = false; unawaited(buildStep.complete().then((_) { isComplete = true; })); await Future(() {}); expect(isComplete, false, reason: 'File has not written, should not be complete'); assetWriter.finishWrite(); await Future(() {}); expect(isComplete, true, reason: 'File is written, should be complete'); }); test('Completes only after async writes finish', () async { var outputCompleter = Completer<String>(); unawaited(buildStep.writeAsString(outputId, outputCompleter.future)); var isComplete = false; unawaited(buildStep.complete().then((_) { isComplete = true; })); await Future(() {}); expect(isComplete, false, reason: 'File has not resolved, should not be complete'); outputCompleter.complete(outputContent); await Future(() {}); expect(isComplete, false, reason: 'File has not written, should not be complete'); assetWriter.finishWrite(); await Future(() {}); expect(isComplete, true, reason: 'File is written, should be complete'); }); }); group('With erroring writes', () { late AssetId primary; late BuildStepImpl buildStep; late AssetId output; setUp(() { var reader = StubAssetReader(); var writer = StubAssetWriter(); primary = makeAssetId(); output = makeAssetId(); buildStep = BuildStepImpl(primary, [output], reader, writer, AnalyzerResolvers(), resourceManager, stageTracker: NoOpStageTracker.instance); }); test('Captures failed asynchronous writes', () { buildStep.writeAsString(output, Future.error('error')); expect(buildStep.complete(), throwsA('error')); }); }); test('reportUnusedAssets forwards calls if provided', () { var reader = StubAssetReader(); var writer = StubAssetWriter(); var unused = <AssetId>{}; var buildStep = BuildStepImpl( makeAssetId(), [], reader, writer, AnalyzerResolvers(), resourceManager, reportUnusedAssets: unused.addAll); var reported = [ makeAssetId(), makeAssetId(), makeAssetId(), ]; buildStep.reportUnusedAssets(reported); expect(unused, equals(reported)); }); } class SlowAssetWriter implements AssetWriter { final _writeCompleter = Completer<void>(); void finishWrite() { _writeCompleter.complete(null); } @override Future<void> writeAsBytes(AssetId id, FutureOr<List<int>> bytes) => _writeCompleter.future; @override Future<void> writeAsString(AssetId id, FutureOr<String> contents, {Encoding encoding = utf8}) => _writeCompleter.future; }
build/build/test/builder/build_step_impl_test.dart/0
{'file_path': 'build/build/test/builder/build_step_impl_test.dart', 'repo_id': 'build', 'token_count': 2840}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'build_target.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** BuildTarget _$BuildTargetFromJson(Map json) => $checkedCreate( 'BuildTarget', json, ($checkedConvert) { $checkKeys( json, allowedKeys: const [ 'auto_apply_builders', 'builders', 'dependencies', 'sources' ], ); final val = BuildTarget( autoApplyBuilders: $checkedConvert('auto_apply_builders', (v) => v as bool?), sources: $checkedConvert( 'sources', (v) => v == null ? null : InputSet.fromJson(v)), dependencies: $checkedConvert('dependencies', (v) => (v as List<dynamic>?)?.map((e) => e as String)), builders: $checkedConvert( 'builders', (v) => (v as Map?)?.map( (k, e) => MapEntry( k as String, TargetBuilderConfig.fromJson(e as Map)), )), ); return val; }, fieldKeyMap: const {'autoApplyBuilders': 'auto_apply_builders'}, ); TargetBuilderConfig _$TargetBuilderConfigFromJson(Map json) => $checkedCreate( 'TargetBuilderConfig', json, ($checkedConvert) { $checkKeys( json, allowedKeys: const [ 'enabled', 'generate_for', 'options', 'dev_options', 'release_options' ], ); final val = TargetBuilderConfig( isEnabled: $checkedConvert('enabled', (v) => v as bool?), generateFor: $checkedConvert( 'generate_for', (v) => v == null ? null : InputSet.fromJson(v)), options: $checkedConvert( 'options', (v) => (v as Map?)?.map( (k, e) => MapEntry(k as String, e), )), devOptions: $checkedConvert( 'dev_options', (v) => (v as Map?)?.map( (k, e) => MapEntry(k as String, e), )), releaseOptions: $checkedConvert( 'release_options', (v) => (v as Map?)?.map( (k, e) => MapEntry(k as String, e), )), ); return val; }, fieldKeyMap: const { 'isEnabled': 'enabled', 'generateFor': 'generate_for', 'devOptions': 'dev_options', 'releaseOptions': 'release_options' }, ); GlobalBuilderConfig _$GlobalBuilderConfigFromJson(Map json) => $checkedCreate( 'GlobalBuilderConfig', json, ($checkedConvert) { $checkKeys( json, allowedKeys: const [ 'options', 'dev_options', 'release_options', 'runs_before' ], ); final val = GlobalBuilderConfig( options: $checkedConvert( 'options', (v) => (v as Map?)?.map( (k, e) => MapEntry(k as String, e), )), devOptions: $checkedConvert( 'dev_options', (v) => (v as Map?)?.map( (k, e) => MapEntry(k as String, e), )), releaseOptions: $checkedConvert( 'release_options', (v) => (v as Map?)?.map( (k, e) => MapEntry(k as String, e), )), runsBefore: $checkedConvert('runs_before', (v) => (v as List<dynamic>?)?.map((e) => e as String).toList()), ); return val; }, fieldKeyMap: const { 'devOptions': 'dev_options', 'releaseOptions': 'release_options', 'runsBefore': 'runs_before' }, );
build/build_config/lib/src/build_target.g.dart/0
{'file_path': 'build/build_config/lib/src/build_target.g.dart', 'repo_id': 'build', 'token_count': 2084}
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:watcher/watcher.dart' show WatchEvent; abstract class ChangeProvider { /// Returns a list of file changes. /// /// Called immediately before a manual build. If the list is empty a no-op /// build of all tracked targets will be attempted. Future<List<WatchEvent>> collectChanges(); /// A stream of file changes. /// /// A build is triggered upon each stream event. /// /// If multiple files change together then they should be sent in the same /// event. Otherwise, at least two builds will be triggered. Stream<List<WatchEvent>> get changes; }
build/build_daemon/lib/change_provider.dart/0
{'file_path': 'build/build_daemon/lib/change_provider.dart', 'repo_id': 'build', 'token_count': 220}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'package:analyzer/dart/analysis/utilities.dart'; import 'package:analyzer/dart/ast/ast.dart'; import 'package:build/build.dart'; import 'platform.dart'; /// A Dart library within a module. /// /// Modules can be computed based on library dependencies (imports and exports) /// and parts. class ModuleLibrary { /// The AssetId of the original Dart source file. final AssetId id; /// Whether this library can be imported. /// /// This will be false if the source file is a "part of", or imports code that /// can't be used outside the SDK. final bool isImportable; /// Whether this library is an entrypoint. /// /// True if the library is in `lib/` but not `lib/src`, or if it is outside of /// `lib/` and contains a `main` method. Always false if this is not an /// importable library. final bool isEntryPoint; /// Deps that are imported with a conditional import. /// /// Keys are the stringified ast node for the conditional, and the default /// import is under the magic `$default` key. final List<Map<String, AssetId>> conditionalDeps; /// The IDs of libraries that are imported or exported by this library. final Set<AssetId> _deps; /// The "part" files for this library. final Set<AssetId> parts; /// The `dart:` libraries that this library directly depends on. final Set<String> sdkDeps; /// Whether this library has a `main` function. final bool hasMain; ModuleLibrary._(this.id, {required this.isEntryPoint, required Set<AssetId> deps, required this.parts, required this.conditionalDeps, required this.sdkDeps, required this.hasMain}) : _deps = deps, isImportable = true; ModuleLibrary._nonImportable(this.id) : isImportable = false, isEntryPoint = false, _deps = const {}, parts = const {}, conditionalDeps = const [], sdkDeps = const {}, hasMain = false; factory ModuleLibrary._fromCompilationUnit( AssetId id, bool isEntryPoint, CompilationUnit parsed) { var deps = <AssetId>{}; var parts = <AssetId>{}; var sdkDeps = <String>{}; var conditionalDeps = <Map<String, AssetId>>[]; for (var directive in parsed.directives) { if (directive is! UriBasedDirective) continue; var path = directive.uri.stringValue; if (path == null) continue; List<Configuration>? conditionalDirectiveConfigurations; if (directive is ImportDirective && directive.configurations.isNotEmpty) { conditionalDirectiveConfigurations = directive.configurations; } else if (directive is ExportDirective && directive.configurations.isNotEmpty) { conditionalDirectiveConfigurations = directive.configurations; } var uri = Uri.parse(path); if (uri.isScheme('dart-ext')) { // TODO: What should we do for native extensions? continue; } if (uri.scheme == 'dart') { if (conditionalDirectiveConfigurations != null) { _checkValidConditionalImport(uri, id, directive); } sdkDeps.add(uri.path); continue; } var linkedId = AssetId.resolve(uri, from: id); if (directive is PartDirective) { parts.add(linkedId); continue; } if (conditionalDirectiveConfigurations != null) { var conditions = <String, AssetId>{r'$default': linkedId}; for (var condition in conditionalDirectiveConfigurations) { var uriString = condition.uri.stringValue; var parsedUri = uriString == null ? null : Uri.parse(uriString); _checkValidConditionalImport(parsedUri, id, directive); parsedUri = parsedUri!; conditions[condition.name.toSource()] = AssetId.resolve(parsedUri, from: id); } conditionalDeps.add(conditions); } else { deps.add(linkedId); } } return ModuleLibrary._(id, isEntryPoint: isEntryPoint, deps: deps, parts: parts, sdkDeps: sdkDeps, conditionalDeps: conditionalDeps, hasMain: _hasMainMethod(parsed)); } static void _checkValidConditionalImport( Uri? parsedUri, AssetId id, UriBasedDirective node) { if (parsedUri == null) { throw ArgumentError( 'Unsupported conditional import with non-constant uri found in $id:' '\n\n${node.toSource()}'); } else if (parsedUri.scheme == 'dart') { throw ArgumentError( 'Unsupported conditional import of `$parsedUri` found in $id:\n\n' '${node.toSource()}\n\nThis environment does not support direct ' 'conditional imports of `dart:` libraries. Instead you must create ' 'a separate library which unconditionally imports (or exports) the ' '`dart:` library that you want to use, and conditionally import (or ' 'export) that library.'); } } /// Parse the directives from [source] and compute the library information. static ModuleLibrary fromSource(AssetId id, String source) { final isLibDir = id.path.startsWith('lib/'); final parsed = parseString(content: source, throwIfDiagnostics: false).unit; // Packages within the SDK but published might have libraries that can't be // used outside the SDK. if (parsed.directives.any((d) => d is UriBasedDirective && d.uri.stringValue?.startsWith('dart:_') == true && id.package != 'dart_internal')) { return ModuleLibrary._nonImportable(id); } if (_isPart(parsed)) { return ModuleLibrary._nonImportable(id); } final isEntryPoint = (isLibDir && !id.path.startsWith('lib/src/')) || _hasMainMethod(parsed); return ModuleLibrary._fromCompilationUnit(id, isEntryPoint, parsed); } /// Parses the output of [serialize] back into a [ModuleLibrary]. /// /// Importable libraries can be round tripped to a String. Non-importable /// libraries should not be printed or parsed. factory ModuleLibrary.deserialize(AssetId id, String encoded) { var json = jsonDecode(encoded); return ModuleLibrary._(id, isEntryPoint: json['isEntrypoint'] as bool, deps: _deserializeAssetIds(json['deps'] as Iterable), parts: _deserializeAssetIds(json['parts'] as Iterable), sdkDeps: Set.of((json['sdkDeps'] as Iterable).cast<String>()), conditionalDeps: (json['conditionalDeps'] as Iterable).map((conditions) { return Map.of((conditions as Map<String, dynamic>) .map((k, v) => MapEntry(k, AssetId.parse(v as String)))); }).toList(), hasMain: json['hasMain'] as bool); } String serialize() => jsonEncode({ 'isEntrypoint': isEntryPoint, 'deps': _deps.map((id) => id.toString()).toList(), 'parts': parts.map((id) => id.toString()).toList(), 'conditionalDeps': conditionalDeps .map((conditions) => conditions.map((k, v) => MapEntry(k, v.toString()))) .toList(), 'sdkDeps': sdkDeps.toList(), 'hasMain': hasMain, }); List<AssetId> depsForPlatform(DartPlatform platform) { AssetId depForConditions(Map<String, AssetId> conditions) { var selectedImport = conditions[r'$default']!; for (var condition in conditions.keys) { if (condition == r'$default') continue; if (!condition.startsWith('dart.library.')) { throw UnsupportedError( '$condition not supported for config specific imports. Only the ' 'dart.library.<name> constants are supported.'); } var library = condition.substring('dart.library.'.length); if (platform.supportsLibrary(library)) { selectedImport = conditions[condition]!; break; } } return selectedImport; } return [ ..._deps, for (var conditions in conditionalDeps) depForConditions(conditions) ]; } } Set<AssetId> _deserializeAssetIds(Iterable serlialized) => Set.from(serlialized.map((decoded) => AssetId.parse(decoded as String))); bool _isPart(CompilationUnit dart) => dart.directives.any((directive) => directive is PartOfDirective); /// Allows two or fewer arguments to `main` so that entrypoints intended for /// use with `spawnUri` get counted. // // TODO: This misses the case where a Dart file doesn't contain main(), // but has a part that does, or it exports a `main` from another library. bool _hasMainMethod(CompilationUnit dart) => dart.declarations.any((node) => node is FunctionDeclaration && node.name2.lexeme == 'main' && node.functionExpression.parameters != null && node.functionExpression.parameters!.parameters.length <= 2);
build/build_modules/lib/src/module_library.dart/0
{'file_path': 'build/build_modules/lib/src/module_library.dart', 'repo_id': 'build', 'token_count': 3394}
library dart.pkg.not_in_sdk;
build/build_modules/test/fixtures/a/lib/a_non_sdk.dart/0
{'file_path': 'build/build_modules/test/fixtures/a/lib/a_non_sdk.dart', 'repo_id': 'build', 'token_count': 13}
// 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:build/build.dart'; import 'package:build_modules/build_modules.dart'; import 'package:build_test/build_test.dart'; import 'package:test/test.dart'; void main() { final platform = DartPlatform.register('test', ['html']); group('computeTransitiveDeps', () { final rootId = AssetId('a', 'lib/a.dart'); final directDepId = AssetId('a', 'lib/src/dep.dart'); final transitiveDepId = AssetId('b', 'lib/b.dart'); final deepTransitiveDepId = AssetId('b', 'lib/src/dep.dart'); final rootModule = Module(rootId, [rootId], [directDepId], platform, true); final directDepModule = Module(directDepId, [directDepId], [transitiveDepId], platform, true); final transitiveDepModule = Module(transitiveDepId, [transitiveDepId], [deepTransitiveDepId], platform, true); final deepTransitiveDepModule = Module(deepTransitiveDepId, [deepTransitiveDepId], [], platform, true); test('finds transitive deps', () async { await testBuilder( TestBuilder( buildExtensions: { 'lib/a${moduleExtension(platform)}': ['.transitive'] }, build: expectAsync2((buildStep, _) async { var transitiveDeps = (await rootModule.computeTransitiveDependencies(buildStep)) .map((m) => m.primarySource) .toList(); expect( transitiveDeps, unorderedEquals([ directDepModule.primarySource, transitiveDepModule.primarySource, deepTransitiveDepModule.primarySource, ])); expect( transitiveDeps.indexOf(transitiveDepModule.primarySource), lessThan( transitiveDeps.indexOf(directDepModule.primarySource))); expect( transitiveDeps .indexOf(deepTransitiveDepModule.primarySource), lessThan(transitiveDeps .indexOf(transitiveDepModule.primarySource))); })), { 'a|lib/a${moduleExtension(platform)}': jsonEncode(rootModule.toJson()), 'a|lib/src/dep${moduleExtension(platform)}': jsonEncode(directDepModule.toJson()), 'b|lib/b${moduleExtension(platform)}': jsonEncode(transitiveDepModule.toJson()), 'b|lib/src/dep${moduleExtension(platform)}': jsonEncode(deepTransitiveDepModule.toJson()), }); }); test('missing modules report nice errors', () async { await testBuilder( TestBuilder( buildExtensions: { 'lib/a${moduleExtension(platform)}': ['.transitive'] }, build: expectAsync2((buildStep, _) async { await expectLater( () => rootModule.computeTransitiveDependencies(buildStep), throwsA(isA<MissingModulesException>() .having((e) => e.message, 'message', contains(''' Unable to find modules for some sources, this is usually the result of either a bad import, a missing dependency in a package (or possibly a dev_dependency needs to move to a real dependency), or a build failure (if importing a generated file). Please check the following imports: `import 'src/dep.dart';` from b|lib/b.dart at 1:1 ''')))); })), { 'a|lib/a${moduleExtension(platform)}': jsonEncode(rootModule.toJson()), 'a|lib/src/dep${moduleExtension(platform)}': jsonEncode(directDepModule.toJson()), 'b|lib/b${moduleExtension(platform)}': jsonEncode(transitiveDepModule.toJson()), // No module for b|lib/src/dep.dart 'b|lib/b.dart': 'import \'src/dep.dart\';', }); }); group('unsupported modules', () { test('are not allowed as the root', () async { final unsupportedRootModule = Module(rootId, [rootId], [directDepId], platform, false); await testBuilder( TestBuilder( buildExtensions: { 'lib/a${moduleExtension(platform)}': ['.transitive'] }, build: expectAsync2((buildStep, _) async { await expectLater( () => rootModule.computeTransitiveDependencies(buildStep, throwIfUnsupported: true), throwsA(isA<UnsupportedModules>().having( (e) => e.unsupportedModules.map((m) => m.primarySource), 'unsupportedModules', equals([unsupportedRootModule.primarySource])))); })), { 'a|lib/a${moduleExtension(platform)}': jsonEncode(unsupportedRootModule.toJson()), 'a|lib/src/dep${moduleExtension(platform)}': jsonEncode(directDepModule.toJson()), 'b|lib/b${moduleExtension(platform)}': jsonEncode(transitiveDepModule.toJson()), 'b|lib/src/dep${moduleExtension(platform)}': jsonEncode(deepTransitiveDepModule.toJson()), }); }); test('are not allowed in immediate deps', () async { final unsupportedDirectDepModule = Module( directDepId, [directDepId], [transitiveDepId], platform, false); await testBuilder( TestBuilder( buildExtensions: { 'lib/a${moduleExtension(platform)}': ['.transitive'] }, build: expectAsync2((buildStep, _) async { await expectLater( () => rootModule.computeTransitiveDependencies(buildStep, throwIfUnsupported: true), throwsA(isA<UnsupportedModules>().having( (e) => e.unsupportedModules.map((m) => m.primarySource), 'unsupportedModules', equals([unsupportedDirectDepModule.primarySource])))); })), { 'a|lib/a${moduleExtension(platform)}': jsonEncode(rootModule.toJson()), 'a|lib/src/dep${moduleExtension(platform)}': jsonEncode(unsupportedDirectDepModule.toJson()), 'b|lib/b${moduleExtension(platform)}': jsonEncode(transitiveDepModule.toJson()), 'b|lib/src/dep${moduleExtension(platform)}': jsonEncode(deepTransitiveDepModule.toJson()), }); }); test('are not allowed in transitive deps', () async { final unsupportedTransitiveDepDepModule = Module(transitiveDepId, [transitiveDepId], [deepTransitiveDepId], platform, false); await testBuilder( TestBuilder( buildExtensions: { 'lib/a${moduleExtension(platform)}': ['.transitive'] }, build: expectAsync2((buildStep, _) async { await expectLater( () => rootModule.computeTransitiveDependencies(buildStep, throwIfUnsupported: true), throwsA(isA<UnsupportedModules>().having( (e) => e.unsupportedModules.map((m) => m.primarySource), 'unsupportedModules', equals([ unsupportedTransitiveDepDepModule.primarySource ])))); })), { 'a|lib/a${moduleExtension(platform)}': jsonEncode(rootModule.toJson()), 'a|lib/src/dep${moduleExtension(platform)}': jsonEncode(directDepModule.toJson()), 'b|lib/b${moduleExtension(platform)}': jsonEncode(unsupportedTransitiveDepDepModule.toJson()), 'b|lib/src/dep${moduleExtension(platform)}': jsonEncode(deepTransitiveDepModule.toJson()), }); }); }); }); }
build/build_modules/test/modules_test.dart/0
{'file_path': 'build/build_modules/test/modules_test.dart', 'repo_id': 'build', 'token_count': 4369}
// 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:build_daemon/constants.dart'; import 'package:path/path.dart' as p; String assetServerPortFilePath(String workingDirectory) => p.join(daemonWorkspace(workingDirectory), '.asset_server_port'); /// Returns the port of the daemon asset server. int assetServerPort(String workingDirectory) { var portFile = File(assetServerPortFilePath(workingDirectory)); if (!portFile.existsSync()) { throw Exception('Unable to read daemon asset port file.'); } return int.parse(portFile.readAsStringSync()); }
build/build_runner/lib/src/daemon/constants.dart/0
{'file_path': 'build/build_runner/lib/src/daemon/constants.dart', 'repo_id': 'build', 'token_count': 224}
// 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:async'; import 'dart:io'; /// Fires [shouldTerminate] once a `SIGINT` is intercepted. /// /// The `SIGINT` stream can optionally be replaced with another Stream in the /// constructor. [cancel] should be called after work is finished. If multiple /// events are receieved on the terminate event stream before work is finished /// the process will be terminated with [exit]. class Terminator { /// A Future that fires when a signal has been received indicating that builds /// should stop. final Future shouldTerminate; final StreamSubscription _subscription; factory Terminator([Stream<ProcessSignal>? terminateEventStream]) { var shouldTerminate = Completer<void>(); terminateEventStream ??= ProcessSignal.sigint.watch(); var numEventsSeen = 0; var terminateListener = terminateEventStream.listen((_) { numEventsSeen++; if (numEventsSeen == 1) { shouldTerminate.complete(); } else { exit(2); } }); return Terminator._(shouldTerminate.future, terminateListener); } Terminator._(this.shouldTerminate, this._subscription); Future cancel() => _subscription.cancel(); }
build/build_runner/lib/src/generate/terminator.dart/0
{'file_path': 'build/build_runner/lib/src/generate/terminator.dart', 'repo_id': 'build', 'token_count': 407}
// 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:async'; import 'dart:io'; import 'package:async/async.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:logging/logging.dart'; import 'asset_change.dart'; import 'node_watcher.dart'; PackageNodeWatcher _default(PackageNode node) => PackageNodeWatcher(node); /// Allows watching an entire graph of packages to schedule rebuilds. class PackageGraphWatcher { // TODO: Consider pulling logging out and providing hooks instead. final Logger _logger; final PackageNodeWatcher Function(PackageNode) _strategy; final PackageGraph _graph; final _readyCompleter = Completer<void>(); Future<void> get ready => _readyCompleter.future; bool _isWatching = false; /// Creates a new watcher for a [PackageGraph]. /// /// May optionally specify a [watch] strategy, otherwise will attempt a /// reasonable default based on the current platform. PackageGraphWatcher( this._graph, { Logger? logger, PackageNodeWatcher Function(PackageNode node)? watch, }) : _logger = logger ?? Logger('build_runner'), _strategy = watch ?? _default; /// Returns a stream of records for assets that changed in the package graph. Stream<AssetChange> watch() { assert(!_isWatching); _isWatching = true; return LazyStream( () => logTimedSync(_logger, 'Setting up file watchers', _watch)); } Stream<AssetChange> _watch() { final allWatchers = _graph.allPackages.values .where((node) => node.dependencyType == DependencyType.path) .map(_strategy) .toList(); final filteredEvents = allWatchers .map((w) => w .watch() .where(_nestedPathFilter(w.node)) .handleError((Object e, StackTrace s) { _logger.severe( 'Error from directory watcher for package:${w.node.name}\n\n' 'If you see this consistently then it is recommended that ' 'you enable the polling file watcher with ' '--use-polling-watcher.\n\n', e, s); })) .toList(); // Asynchronously complete the `_readyCompleter` once all the watchers // are done. () async { await Future.wait( allWatchers.map((nodeWatcher) => nodeWatcher.watcher.ready)); _readyCompleter.complete(); }(); return StreamGroup.merge(filteredEvents); } bool Function(AssetChange) _nestedPathFilter(PackageNode rootNode) { final ignorePaths = _nestedPaths(rootNode); return (change) => !ignorePaths.any(change.id.path.startsWith); } // Returns a set of all package paths that are "nested" within a node. // // This allows the watcher to optimize and avoid duplicate events. List<String> _nestedPaths(PackageNode rootNode) { return _graph.allPackages.values .where((node) { return node.path.length > rootNode.path.length && node.path.startsWith(rootNode.path); }) .map((node) => node.path.substring(rootNode.path.length + 1) + Platform.pathSeparator) .toList(); } }
build/build_runner/lib/src/watcher/graph_watcher.dart/0
{'file_path': 'build/build_runner/lib/src/watcher/graph_watcher.dart', 'repo_id': 'build', 'token_count': 1295}
// 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:async'; import 'dart:convert'; import 'dart:io'; import 'package:_test_common/build_configs.dart'; import 'package:_test_common/common.dart'; import 'package:async/async.dart'; import 'package:build/build.dart'; import 'package:build_config/build_config.dart'; import 'package:build_runner/src/generate/watch_impl.dart' as watch_impl; import 'package:build_runner_core/build_runner_core.dart'; import 'package:build_runner_core/src/asset_graph/graph.dart'; import 'package:build_runner_core/src/asset_graph/node.dart'; import 'package:build_test/build_test.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as path; import 'package:test/test.dart'; import 'package:watcher/watcher.dart'; void main() { /// Basic phases/phase groups which get used in many tests final copyABuildApplication = applyToRoot( TestBuilder(buildExtensions: appendExtension('.copy', from: '.txt'))); final defaultBuilderOptions = const BuilderOptions({}); final packageConfigId = makeAssetId('a|.dart_tool/package_config.json'); late InMemoryRunnerAssetWriter writer; setUp(() async { writer = InMemoryRunnerAssetWriter(); await writer.writeAsString(packageConfigId, jsonEncode(_packageConfig)); }); group('watch', () { setUp(() { _terminateWatchController = StreamController(); }); tearDown(() { FakeWatcher.watchers.clear(); return terminateWatch(); }); group('simple', () { test('rebuilds once on file updates', () async { var buildState = await startWatch( [copyABuildApplication], {'a|web/a.txt': 'a'}, writer); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|web/a.txt.copy': 'a'}, writer: writer); await writer.writeAsString(makeAssetId('a|web/a.txt'), 'b'); result = await results.next; checkBuild(result, outputs: {'a|web/a.txt.copy': 'b'}, writer: writer); // Wait for the `_debounceDelay` before terminating. await Future<void>.delayed(_debounceDelay); await terminateWatch(); expect(await results.hasNext, isFalse); }); test('emits an error message when no builders are specified', () async { var logs = <LogRecord>[]; var buildState = await startWatch( [], {'a|web/a.txt.copy': 'a'}, writer, onLog: logs.add, logLevel: Level.SEVERE, ); var result = await buildState.buildResults.first; expect(result.status, BuildStatus.success); expect( logs, contains(predicate((LogRecord record) => record.message.contains( 'Nothing can be built, yet a build was requested.')))); }); test('rebuilds on file updates outside hardcoded sources', () async { var buildState = await startWatch( [copyABuildApplication], {'a|test_files/a.txt': 'a'}, writer, overrideBuildConfig: parseBuildConfigs({ 'a': { 'targets': { 'a': { 'sources': ['test_files/**'] } } } })); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|test_files/a.txt.copy': 'a'}, writer: writer); await writer.writeAsString(makeAssetId('a|test_files/a.txt'), 'b'); result = await results.next; checkBuild(result, outputs: {'a|test_files/a.txt.copy': 'b'}, writer: writer); }); test('rebuilds on new files', () async { var buildState = await startWatch( [copyABuildApplication], {'a|web/a.txt': 'a'}, writer); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|web/a.txt.copy': 'a'}, writer: writer); await writer.writeAsString(makeAssetId('a|web/b.txt'), 'b'); result = await results.next; checkBuild(result, outputs: {'a|web/b.txt.copy': 'b'}, writer: writer); // Previous outputs should still exist. expect(writer.assets[makeAssetId('a|web/a.txt.copy')], decodedMatches('a')); }); test('rebuilds on new files outside hardcoded sources', () async { var buildState = await startWatch( [copyABuildApplication], {'a|test_files/a.txt': 'a'}, writer, overrideBuildConfig: parseBuildConfigs({ 'a': { 'targets': { 'a': { 'sources': ['test_files/**'] } } } })); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|test_files/a.txt.copy': 'a'}, writer: writer); await writer.writeAsString(makeAssetId('a|test_files/b.txt'), 'b'); result = await results.next; checkBuild(result, outputs: {'a|test_files/b.txt.copy': 'b'}, writer: writer); // Previous outputs should still exist. expect(writer.assets[makeAssetId('a|test_files/a.txt.copy')], decodedMatches('a')); }); test('rebuilds on deleted files', () async { var buildState = await startWatch([ copyABuildApplication ], { 'a|web/a.txt': 'a', 'a|web/b.txt': 'b', }, writer); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|web/a.txt.copy': 'a', 'a|web/b.txt.copy': 'b'}, writer: writer); // Don't call writer.delete, that has side effects. writer.assets.remove(makeAssetId('a|web/a.txt')); FakeWatcher.notifyWatchers( WatchEvent(ChangeType.REMOVE, path.absolute('a', 'web', 'a.txt'))); result = await results.next; // Shouldn't rebuild anything, no outputs. checkBuild(result, outputs: {}, writer: writer); // The old output file should no longer exist either. expect(writer.assets[makeAssetId('a|web/a.txt.copy')], isNull); // Previous outputs should still exist. expect(writer.assets[makeAssetId('a|web/b.txt.copy')], decodedMatches('b')); }); test('rebuilds on deleted files outside hardcoded sources', () async { var buildState = await startWatch([ copyABuildApplication ], { 'a|test_files/a.txt': 'a', 'a|test_files/b.txt': 'b', }, writer, overrideBuildConfig: parseBuildConfigs({ 'a': { 'targets': { 'a': { 'sources': ['test_files/**'] } } } })); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: { 'a|test_files/a.txt.copy': 'a', 'a|test_files/b.txt.copy': 'b' }, writer: writer); // Don't call writer.delete, that has side effects. writer.assets.remove(makeAssetId('a|test_files/a.txt')); FakeWatcher.notifyWatchers(WatchEvent( ChangeType.REMOVE, path.absolute('a', 'test_files', 'a.txt'))); result = await results.next; // Shouldn't rebuild anything, no outputs. checkBuild(result, outputs: {}, writer: writer); // The old output file should no longer exist either. expect(writer.assets[makeAssetId('a|test_files/a.txt.copy')], isNull); // Previous outputs should still exist. expect(writer.assets[makeAssetId('a|test_files/b.txt.copy')], decodedMatches('b')); }); test('rebuilds properly update asset_graph.json', () async { var buildState = await startWatch([copyABuildApplication], {'a|web/a.txt': 'a', 'a|web/b.txt': 'b'}, writer); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|web/a.txt.copy': 'a', 'a|web/b.txt.copy': 'b'}, writer: writer); await writer.writeAsString(makeAssetId('a|web/c.txt'), 'c'); await writer.writeAsString(makeAssetId('a|web/b.txt'), 'b2'); // Don't call writer.delete, that has side effects. writer.assets.remove(makeAssetId('a|web/a.txt')); FakeWatcher.notifyWatchers( WatchEvent(ChangeType.REMOVE, path.absolute('a', 'web', 'a.txt'))); result = await results.next; checkBuild(result, outputs: {'a|web/b.txt.copy': 'b2', 'a|web/c.txt.copy': 'c'}, writer: writer); var cachedGraph = AssetGraph.deserialize( writer.assets[makeAssetId('a|$assetGraphPath')]!); var expectedGraph = await AssetGraph.build( [], <AssetId>{}, {packageConfigId}, buildPackageGraph({rootPackage('a'): []}), InMemoryAssetReader(sourceAssets: writer.assets)); var builderOptionsId = makeAssetId('a|Phase0.builderOptions'); var builderOptionsNode = BuilderOptionsAssetNode(builderOptionsId, computeBuilderOptionsDigest(defaultBuilderOptions)); expectedGraph.add(builderOptionsNode); var bCopyId = makeAssetId('a|web/b.txt.copy'); var bTxtId = makeAssetId('a|web/b.txt'); var bCopyNode = GeneratedAssetNode(bCopyId, phaseNumber: 0, primaryInput: makeAssetId('a|web/b.txt'), state: NodeState.upToDate, wasOutput: true, isFailure: false, builderOptionsId: builderOptionsId, lastKnownDigest: computeDigest(bCopyId, 'b2'), inputs: [makeAssetId('a|web/b.txt')], isHidden: false); builderOptionsNode.outputs.add(bCopyNode.id); expectedGraph ..add(bCopyNode) ..add(makeAssetNode( 'a|web/b.txt', [bCopyNode.id], computeDigest(bTxtId, 'b2'))); var cCopyId = makeAssetId('a|web/c.txt.copy'); var cTxtId = makeAssetId('a|web/c.txt'); var cCopyNode = GeneratedAssetNode(cCopyId, phaseNumber: 0, primaryInput: cTxtId, state: NodeState.upToDate, wasOutput: true, isFailure: false, builderOptionsId: builderOptionsId, lastKnownDigest: computeDigest(cCopyId, 'c'), inputs: [makeAssetId('a|web/c.txt')], isHidden: false); builderOptionsNode.outputs.add(cCopyNode.id); expectedGraph ..add(cCopyNode) ..add(makeAssetNode( 'a|web/c.txt', [cCopyNode.id], computeDigest(cTxtId, 'c'))); // TODO: We dont have a shared way of computing the combined input // hashes today, but eventually we should test those here too. expect(cachedGraph, equalsAssetGraph(expectedGraph, checkPreviousInputsDigest: false)); }); test('ignores events from nested packages', () async { final packageGraph = buildPackageGraph({ rootPackage('a', path: path.absolute('a')): ['b'], package('b', path: path.absolute('a', 'b')): [] }); var buildState = await startWatch([ copyABuildApplication, ], { 'a|web/a.txt': 'a', 'b|web/b.txt': 'b' }, writer, packageGraph: packageGraph); var results = StreamQueue(buildState.buildResults); var result = await results.next; // Should ignore the files under the `b` package, even though they // match the input set. checkBuild(result, outputs: {'a|web/a.txt.copy': 'a'}, writer: writer); await writer.writeAsString(makeAssetId('a|web/a.txt'), 'b'); await writer.writeAsString(makeAssetId('b|web/b.txt'), 'c'); // Have to manually notify here since the path isn't standard. FakeWatcher.notifyWatchers(WatchEvent( ChangeType.MODIFY, path.absolute('a', 'b', 'web', 'a.txt'))); result = await results.next; // Ignores the modification under the `b` package, even though it // matches the input set. checkBuild(result, outputs: {'a|web/a.txt.copy': 'b'}, writer: writer); }); test('rebuilds on file updates during first build', () async { var blocker = Completer<void>(); var buildAction = applyToRoot(TestBuilder(extraWork: (_, __) => blocker.future)); var buildState = await startWatch([buildAction], {'a|web/a.txt': 'a'}, writer); var results = StreamQueue(buildState.buildResults); FakeWatcher.notifyWatchers( WatchEvent(ChangeType.MODIFY, path.absolute('a', 'web', 'a.txt'))); blocker.complete(); var result = await results.next; // TODO: Move this up above the call to notifyWatchers once // https://github.com/dart-lang/build/issues/526 is fixed. await writer.writeAsString(makeAssetId('a|web/a.txt'), 'b'); checkBuild(result, outputs: {'a|web/a.txt.copy': 'a'}, writer: writer); result = await results.next; checkBuild(result, outputs: {'a|web/a.txt.copy': 'b'}, writer: writer); }); test( 'edits to .dart_tool/package_config.json prevent future builds ' 'and ask you to restart', () async { var logs = <LogRecord>[]; var buildState = await startWatch( [copyABuildApplication], {'a|web/a.txt': 'a'}, writer, logLevel: Level.SEVERE, onLog: logs.add); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|web/a.txt.copy': 'a'}, writer: writer); var newConfig = Map.of(_packageConfig); newConfig['extra'] = 'stuff'; await writer.writeAsString(packageConfigId, jsonEncode(newConfig)); expect(await results.hasNext, isFalse); expect(logs, hasLength(1)); expect( logs.first.message, contains('Terminating builds due to package graph update, ' 'please restart the build.')); }); test('Gives the package config a chance to be re-written before failing', () async { var logs = <LogRecord>[]; var buildState = await startWatch( [copyABuildApplication], {'a|web/a.txt': 'a'}, writer, logLevel: Level.SEVERE, onLog: logs.add); buildState.buildResults.handleError((e, s) => print('$e\n$s')); buildState.buildResults.listen(print); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|web/a.txt.copy': 'a'}, writer: writer); await writer.delete(packageConfigId); // Wait for it to try reading the file twice to ensure it will retry. await _readerForState[buildState]! .onCanRead .where((id) => id == packageConfigId) .take(2) .drain(); var newConfig = Map.of(_packageConfig); newConfig['extra'] = 'stuff'; await writer.writeAsString(packageConfigId, jsonEncode(newConfig)); expect(await results.hasNext, isFalse); expect(logs, hasLength(1)); expect( logs.first.message, contains('Terminating builds due to package graph update, ' 'please restart the build.')); }); group('build.yaml', () { final packageGraph = buildPackageGraph({ rootPackage('a', path: path.absolute('a')): ['b'], package('b', path: path.absolute('b'), type: DependencyType.path): [] }); late List<LogRecord> logs; late StreamQueue<BuildResult> results; group('is added', () { setUp(() async { logs = <LogRecord>[]; var buildState = await startWatch( [copyABuildApplication], {}, writer, logLevel: Level.SEVERE, onLog: logs.add, packageGraph: packageGraph); results = StreamQueue(buildState.buildResults); await results.next; }); test('to the root package', () async { await writer.writeAsString( AssetId('a', 'build.yaml'), '# New build.yaml file'); expect(await results.hasNext, isTrue); var next = await results.next; expect(next.status, BuildStatus.failure); expect(next.failureType, FailureType.buildConfigChanged); expect(logs, hasLength(1)); expect(logs.first.message, contains('Terminating builds due to a:build.yaml update')); }); test('to a dependency', () async { await writer.writeAsString( AssetId('b', 'build.yaml'), '# New build.yaml file'); expect(await results.hasNext, isTrue); var next = await results.next; expect(next.status, BuildStatus.failure); expect(next.failureType, FailureType.buildConfigChanged); expect(logs, hasLength(1)); expect(logs.first.message, contains('Terminating builds due to b:build.yaml update')); }); test('<package>.build.yaml', () async { await writer.writeAsString( AssetId('a', 'b.build.yaml'), '# New b.build.yaml file'); expect(await results.hasNext, isTrue); var next = await results.next; expect(next.status, BuildStatus.failure); expect(next.failureType, FailureType.buildConfigChanged); expect(logs, hasLength(1)); expect(logs.first.message, contains('Terminating builds due to a:b.build.yaml update')); }); }); group('is edited', () { setUp(() async { logs = <LogRecord>[]; var buildState = await startWatch([copyABuildApplication], {'a|build.yaml': '', 'b|build.yaml': ''}, writer, logLevel: Level.SEVERE, onLog: logs.add, packageGraph: packageGraph); results = StreamQueue(buildState.buildResults); await results.next; }); test('in the root package', () async { await writer.writeAsString( AssetId('a', 'build.yaml'), '# Edited build.yaml file'); expect(await results.hasNext, isTrue); var next = await results.next; expect(next.status, BuildStatus.failure); expect(next.failureType, FailureType.buildConfigChanged); expect(logs, hasLength(1)); expect(logs.first.message, contains('Terminating builds due to a:build.yaml update')); }); test('in a dependency', () async { await writer.writeAsString( AssetId('b', 'build.yaml'), '# Edited build.yaml file'); expect(await results.hasNext, isTrue); var next = await results.next; expect(next.status, BuildStatus.failure); expect(next.failureType, FailureType.buildConfigChanged); expect(logs, hasLength(1)); expect(logs.first.message, contains('Terminating builds due to b:build.yaml update')); }); }); group('with --config', () { setUp(() async { logs = <LogRecord>[]; var buildState = await startWatch([copyABuildApplication], {'a|build.yaml': '', 'a|build.cool.yaml': ''}, writer, configKey: 'cool', logLevel: Level.SEVERE, onLog: logs.add, overrideBuildConfig: { 'a': BuildConfig.useDefault('a', ['b']) }, packageGraph: packageGraph); results = StreamQueue(buildState.buildResults); await results.next; }); test('original is edited', () async { await writer.writeAsString( AssetId('a', 'build.yaml'), '# Edited build.yaml file'); expect(await results.hasNext, isTrue); var next = await results.next; expect(next.status, BuildStatus.failure); expect(next.failureType, FailureType.buildConfigChanged); expect(logs, hasLength(1)); expect(logs.first.message, contains('Terminating builds due to a:build.yaml update')); }); test('build.<config>.yaml in dependencies are ignored', () async { await writer.writeAsString( AssetId('b', 'build.cool.yaml'), '# New build.yaml file'); await Future<void>.delayed(_debounceDelay); expect(logs, isEmpty); await terminateWatch(); }); test('build.<config>.yaml is edited', () async { await writer.writeAsString(AssetId('a', 'build.cool.yaml'), '# Edited build.cool.yaml file'); expect(await results.hasNext, isTrue); var next = await results.next; expect(next.status, BuildStatus.failure); expect(next.failureType, FailureType.buildConfigChanged); expect(logs, hasLength(1)); expect(logs.first.message, contains('Terminating builds due to a:build.cool.yaml update')); }); }); }); }); group('file updates to same contents', () { test('does not rebuild', () async { var runCount = 0; var buildState = await startWatch([ applyToRoot(TestBuilder( buildExtensions: appendExtension('.copy', from: '.txt'), build: (buildStep, _) { runCount++; buildStep.writeAsString(buildStep.inputId.addExtension('.copy'), buildStep.readAsString(buildStep.inputId)); throw StateError('Fail'); })) ], { 'a|web/a.txt': 'a' }, writer); var results = StreamQueue(buildState.buildResults); var result = await results.next; expect(runCount, 1); checkBuild(result, status: BuildStatus.failure, writer: writer); await writer.writeAsString(makeAssetId('a|web/a.txt'), 'a'); // Wait for the `_debounceDelay * 4` before terminating to // give it a chance to pick up the change. await Future<void>.delayed(_debounceDelay * 4); await terminateWatch(); expect(await results.hasNext, isFalse); }); }); group('multiple phases', () { test('edits propagate through all phases', () async { var buildActions = [ copyABuildApplication, applyToRoot(TestBuilder( buildExtensions: appendExtension('.copy', from: '.copy'))) ]; var buildState = await startWatch(buildActions, {'a|web/a.txt': 'a'}, writer); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|web/a.txt.copy': 'a', 'a|web/a.txt.copy.copy': 'a'}, writer: writer); await writer.writeAsString(makeAssetId('a|web/a.txt'), 'b'); result = await results.next; checkBuild(result, outputs: {'a|web/a.txt.copy': 'b', 'a|web/a.txt.copy.copy': 'b'}, writer: writer); }); test('adds propagate through all phases', () async { var buildActions = [ copyABuildApplication, applyToRoot(TestBuilder( buildExtensions: appendExtension('.copy', from: '.copy'))) ]; var buildState = await startWatch(buildActions, {'a|web/a.txt': 'a'}, writer); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|web/a.txt.copy': 'a', 'a|web/a.txt.copy.copy': 'a'}, writer: writer); await writer.writeAsString(makeAssetId('a|web/b.txt'), 'b'); result = await results.next; checkBuild(result, outputs: {'a|web/b.txt.copy': 'b', 'a|web/b.txt.copy.copy': 'b'}, writer: writer); // Previous outputs should still exist. expect(writer.assets[makeAssetId('a|web/a.txt.copy')], decodedMatches('a')); expect(writer.assets[makeAssetId('a|web/a.txt.copy.copy')], decodedMatches('a')); }); test('deletes propagate through all phases', () async { var buildActions = [ copyABuildApplication, applyToRoot(TestBuilder( buildExtensions: appendExtension('.copy', from: '.copy'))) ]; var buildState = await startWatch( buildActions, {'a|web/a.txt': 'a', 'a|web/b.txt': 'b'}, writer); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: { 'a|web/a.txt.copy': 'a', 'a|web/a.txt.copy.copy': 'a', 'a|web/b.txt.copy': 'b', 'a|web/b.txt.copy.copy': 'b' }, writer: writer); // Don't call writer.delete, that has side effects. writer.assets.remove(makeAssetId('a|web/a.txt')); FakeWatcher.notifyWatchers( WatchEvent(ChangeType.REMOVE, path.absolute('a', 'web', 'a.txt'))); result = await results.next; // Shouldn't rebuild anything, no outputs. checkBuild(result, outputs: {}, writer: writer); // Derived outputs should no longer exist. expect(writer.assets[makeAssetId('a|web/a.txt.copy')], isNull); expect(writer.assets[makeAssetId('a|web/a.txt.copy.copy')], isNull); // Other outputs should still exist. expect(writer.assets[makeAssetId('a|web/b.txt.copy')], decodedMatches('b')); expect(writer.assets[makeAssetId('a|web/b.txt.copy.copy')], decodedMatches('b')); }); test('deleted generated outputs are regenerated', () async { var buildActions = [ copyABuildApplication, applyToRoot(TestBuilder( buildExtensions: appendExtension('.copy', from: '.copy'))) ]; var buildState = await startWatch(buildActions, {'a|web/a.txt': 'a'}, writer); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: { 'a|web/a.txt.copy': 'a', 'a|web/a.txt.copy.copy': 'a', }, writer: writer); // Don't call writer.delete, that has side effects. writer.assets.remove(makeAssetId('a|web/a.txt.copy')); FakeWatcher.notifyWatchers(WatchEvent( ChangeType.REMOVE, path.absolute('a', 'web', 'a.txt.copy'))); result = await results.next; // Should rebuild the generated asset, but not its outputs because its // content didn't change. checkBuild(result, outputs: { 'a|web/a.txt.copy': 'a', }, writer: writer); }); }); /// Tests for updates group('secondary dependency', () { test('of an output file is edited', () async { var buildActions = [ applyToRoot(TestBuilder( buildExtensions: appendExtension('.copy', from: '.a'), build: copyFrom(makeAssetId('a|web/file.b')))) ]; var buildState = await startWatch( buildActions, {'a|web/file.a': 'a', 'a|web/file.b': 'b'}, writer); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|web/file.a.copy': 'b'}, writer: writer); await writer.writeAsString(makeAssetId('a|web/file.b'), 'c'); result = await results.next; checkBuild(result, outputs: {'a|web/file.a.copy': 'c'}, writer: writer); }); test( 'of an output which is derived from another generated file is edited', () async { var buildActions = [ applyToRoot(TestBuilder( buildExtensions: appendExtension('.copy', from: '.a'))), applyToRoot(TestBuilder( buildExtensions: appendExtension('.copy', from: '.a.copy'), build: copyFrom(makeAssetId('a|web/file.b')))) ]; var buildState = await startWatch( buildActions, {'a|web/file.a': 'a', 'a|web/file.b': 'b'}, writer); var results = StreamQueue(buildState.buildResults); var result = await results.next; checkBuild(result, outputs: {'a|web/file.a.copy': 'a', 'a|web/file.a.copy.copy': 'b'}, writer: writer); await writer.writeAsString(makeAssetId('a|web/file.b'), 'c'); result = await results.next; checkBuild(result, outputs: {'a|web/file.a.copy.copy': 'c'}, writer: writer); }); }); }); } final _debounceDelay = Duration(milliseconds: 10); StreamController<ProcessSignal>? _terminateWatchController; /// Start watching files and running builds. Future<BuildState> startWatch(List<BuilderApplication> builders, Map<String, String> inputs, InMemoryRunnerAssetWriter writer, {PackageGraph? packageGraph, Map<String, BuildConfig> overrideBuildConfig = const {}, void Function(LogRecord)? onLog, Level logLevel = Level.OFF, String? configKey}) async { onLog ??= (_) {}; inputs.forEach((serializedId, contents) { writer.writeAsString(makeAssetId(serializedId), contents); }); packageGraph ??= buildPackageGraph({rootPackage('a', path: path.absolute('a')): []}); final reader = InMemoryRunnerAssetReader.shareAssetCache(writer.assets, rootPackage: packageGraph.root.name); FakeWatcher watcherFactory(String path) => FakeWatcher(path); var state = await watch_impl.watch(builders, configKey: configKey, deleteFilesByDefault: true, debounceDelay: _debounceDelay, directoryWatcherFactory: watcherFactory, overrideBuildConfig: overrideBuildConfig, reader: reader, writer: writer, packageGraph: packageGraph, terminateEventStream: _terminateWatchController!.stream, logLevel: logLevel, onLog: onLog, skipBuildScriptCheck: true); // Some tests need access to `reader` so we expose it through an expando. _readerForState[state] = reader; return state; } /// Tells the program to stop watching files and terminate. Future terminateWatch() async { var terminateWatchController = _terminateWatchController; if (terminateWatchController == null) return; /// Can add any type of event. terminateWatchController.add(ProcessSignal.sigabrt); await terminateWatchController.close(); _terminateWatchController = null; } const _packageConfig = { 'configVersion': 2, 'packages': [ {'name': 'a', 'rootUri': 'file://fake/pkg/path', 'packageUri': 'lib/'}, ], }; /// Store the private in memory asset reader for a given [BuildState] object /// here so we can get access to it. final _readerForState = Expando<InMemoryRunnerAssetReader>();
build/build_runner/test/generate/watch_test.dart/0
{'file_path': 'build/build_runner/test/generate/watch_test.dart', 'repo_id': 'build', 'token_count': 14236}
// 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:async'; import 'dart:mirrors'; import 'package:build/build.dart'; import 'package:collection/collection.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import '../asset/reader.dart'; import '../asset_graph/graph.dart'; import '../package_graph/package_graph.dart'; /// Functionality for detecting if the build script itself or any of its /// transitive imports have changed. abstract class BuildScriptUpdates { /// Checks if the current running program has been updated, based on /// [updatedIds]. bool hasBeenUpdated(Set<AssetId> updatedIds); /// Creates a [BuildScriptUpdates] object, using [reader] to ensure that /// the [assetGraph] is tracking digests for all transitive sources. /// /// If [disabled] is `true` then all checks are skipped and /// [hasBeenUpdated] will always return `false`. static Future<BuildScriptUpdates> create(RunnerAssetReader reader, PackageGraph packageGraph, AssetGraph assetGraph, {bool disabled = false}) async { if (disabled) return _NoopBuildScriptUpdates(); return _MirrorBuildScriptUpdates.create(reader, packageGraph, assetGraph); } } /// Uses mirrors to find all transitive imports of the current script. class _MirrorBuildScriptUpdates implements BuildScriptUpdates { final Set<AssetId> _allSources; final bool _supportsIncrementalRebuilds; _MirrorBuildScriptUpdates._( this._supportsIncrementalRebuilds, this._allSources); static Future<BuildScriptUpdates> create(RunnerAssetReader reader, PackageGraph packageGraph, AssetGraph graph) async { var supportsIncrementalRebuilds = true; var rootPackage = packageGraph.root.name; Set<AssetId> allSources; var logger = Logger('BuildScriptUpdates'); try { allSources = _urisForThisScript .map((id) => _idForUri(id, rootPackage)) .whereNotNull() .toSet(); var missing = allSources.firstWhereOrNull((id) => !graph.contains(id)); if (missing != null) { supportsIncrementalRebuilds = false; logger.warning('$missing was not found in the asset graph, ' 'incremental builds will not work.\n This probably means you ' 'don\'t have your dependencies specified fully in your ' 'pubspec.yaml.'); } else { // Make sure we are tracking changes for all ids in [allSources]. for (var id in allSources) { graph.get(id)!.lastKnownDigest ??= await reader.digest(id); } } } on ArgumentError catch (_) { supportsIncrementalRebuilds = false; allSources = <AssetId>{}; } return _MirrorBuildScriptUpdates._(supportsIncrementalRebuilds, allSources); } static Iterable<Uri> get _urisForThisScript => currentMirrorSystem().libraries.keys; /// Checks if the current running program has been updated, based on /// [updatedIds]. @override bool hasBeenUpdated(Set<AssetId> updatedIds) { if (!_supportsIncrementalRebuilds) return true; return updatedIds.intersection(_allSources).isNotEmpty; } /// Attempts to return an [AssetId] for [uri]. /// /// Returns `null` if the uri should be ignored, or throws an [ArgumentError] /// if the [uri] is not recognized. static AssetId? _idForUri(Uri uri, String rootPackage) { switch (uri.scheme) { case 'dart': // TODO: check for sdk updates! break; case 'package': var parts = uri.pathSegments; return AssetId(parts[0], p.url.joinAll(['lib', ...parts.getRange(1, parts.length)])); case 'file': var relativePath = p.relative(uri.toFilePath(), from: p.current); return AssetId(rootPackage, relativePath); case 'data': // Test runner uses a `data` scheme, don't invalidate for those. if (uri.path.contains('package:test')) break; continue unsupported; case 'http': continue unsupported; unsupported: default: throw ArgumentError('Unsupported uri scheme `${uri.scheme}` found for ' 'library in build script.\n' 'This probably means you are running in an unsupported ' 'context, such as in an isolate or via `dart run`.\n' 'Full uri was: $uri.'); } return null; } } /// Always returns false for [hasBeenUpdated], used when we want to skip /// the build script checks. class _NoopBuildScriptUpdates implements BuildScriptUpdates { @override bool hasBeenUpdated(void _) => false; }
build/build_runner_core/lib/src/changes/build_script_updates.dart/0
{'file_path': 'build/build_runner_core/lib/src/changes/build_script_updates.dart', 'repo_id': 'build', 'token_count': 1681}
// GENERATED CODE - DO NOT MODIFY BY HAND part of build_runner.src.generate.performance_tracker; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** BuildPerformance _$BuildPerformanceFromJson(Map<String, dynamic> json) => BuildPerformance( (json['phases'] as List<dynamic>).map( (e) => BuildPhasePerformance.fromJson(e as Map<String, dynamic>)), (json['actions'] as List<dynamic>).map( (e) => BuilderActionPerformance.fromJson(e as Map<String, dynamic>)), DateTime.parse(json['startTime'] as String), DateTime.parse(json['stopTime'] as String), ); Map<String, dynamic> _$BuildPerformanceToJson(BuildPerformance instance) => <String, dynamic>{ 'startTime': instance.startTime.toIso8601String(), 'stopTime': instance.stopTime.toIso8601String(), 'phases': instance.phases.toList(), 'actions': instance.actions.toList(), }; BuildPhasePerformance _$BuildPhasePerformanceFromJson( Map<String, dynamic> json) => BuildPhasePerformance( (json['builderKeys'] as List<dynamic>).map((e) => e as String).toList(), DateTime.parse(json['startTime'] as String), DateTime.parse(json['stopTime'] as String), ); Map<String, dynamic> _$BuildPhasePerformanceToJson( BuildPhasePerformance instance) => <String, dynamic>{ 'startTime': instance.startTime.toIso8601String(), 'stopTime': instance.stopTime.toIso8601String(), 'builderKeys': instance.builderKeys, }; BuilderActionPerformance _$BuilderActionPerformanceFromJson( Map<String, dynamic> json) => BuilderActionPerformance( json['builderKey'] as String, _assetIdFromJson(json['primaryInput'] as String), (json['stages'] as List<dynamic>).map((e) => BuilderActionStagePerformance.fromJson(e as Map<String, dynamic>)), DateTime.parse(json['startTime'] as String), DateTime.parse(json['stopTime'] as String), ); Map<String, dynamic> _$BuilderActionPerformanceToJson( BuilderActionPerformance instance) => <String, dynamic>{ 'startTime': instance.startTime.toIso8601String(), 'stopTime': instance.stopTime.toIso8601String(), 'builderKey': instance.builderKey, 'primaryInput': _assetIdToJson(instance.primaryInput), 'stages': instance.stages.toList(), }; BuilderActionStagePerformance _$BuilderActionStagePerformanceFromJson( Map<String, dynamic> json) => BuilderActionStagePerformance( json['label'] as String, (json['slices'] as List<dynamic>) .map((e) => TimeSlice.fromJson(e as Map<String, dynamic>)) .toList(), ); Map<String, dynamic> _$BuilderActionStagePerformanceToJson( BuilderActionStagePerformance instance) => <String, dynamic>{ 'slices': instance.slices, 'label': instance.label, };
build/build_runner_core/lib/src/generate/performance_tracker.g.dart/0
{'file_path': 'build/build_runner_core/lib/src/generate/performance_tracker.g.dart', 'repo_id': 'build', 'token_count': 1080}
sdk: - pubspec - dev stages: - analyze_and_format: - group: - format - analyze: --fatal-infos . sdk: dev - unit_test: - test: --test-randomize-ordering-seed=random os: - linux - windows
build/build_runner_core/mono_pkg.yaml/0
{'file_path': 'build/build_runner_core/mono_pkg.yaml', 'repo_id': 'build', 'token_count': 97}
name: with_dev_deps version: 1.0.0 dependencies: a: 2.0.0 dev_dependencies: b: 3.0.0
build/build_runner_core/test/fixtures/with_dev_deps/pubspec.yaml/0
{'file_path': 'build/build_runner_core/test/fixtures/with_dev_deps/pubspec.yaml', 'repo_id': 'build', 'token_count': 45}
// 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:convert'; import 'package:build/build.dart'; import 'package:crypto/crypto.dart'; import 'package:glob/glob.dart'; /// A no-op implementation of [AssetReader]. class StubAssetReader extends AssetReader implements MultiPackageAssetReader { StubAssetReader(); @override Future<bool> canRead(AssetId id) => Future.value(false); @override Future<List<int>> readAsBytes(AssetId id) => Future.value([]); @override Future<String> readAsString(AssetId id, {Encoding encoding = utf8}) => Future.value(''); @override Stream<AssetId> findAssets(Glob glob, {String? package}) => const Stream<Never>.empty(); @override Future<Digest> digest(AssetId id) => Future.value(Digest([1, 2, 3])); }
build/build_test/lib/src/stub_reader.dart/0
{'file_path': 'build/build_test/lib/src/stub_reader.dart', 'repo_id': 'build', 'token_count': 306}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:build/build.dart'; import 'package:build_test/build_test.dart'; import 'package:glob/glob.dart'; import 'package:test/test.dart'; void main() { group('$PackageAssetReader', () { late PackageAssetReader reader; final buildAsset = AssetId('build', 'lib/build.dart'); final buildTest = AssetId('build_test', 'lib/build_test.dart'); final buildMissing = AssetId('build_test', 'lib/build_missing.dart'); final thisFile = AssetId('build_test', 'test/package_reader_test.dart'); setUp(() async { reader = await PackageAssetReader.currentIsolate( rootPackage: 'build_test', ); }); test('should be able to read `build_test.dart`', () async { expect(await reader.canRead(buildTest), isTrue); expect(await reader.readAsString(buildTest), isNotEmpty); }); test('should be able to read this file (in test/)', () async { expect(await reader.canRead(thisFile), isTrue); }); test('should not be able to read a missing file', () async { expect(await reader.canRead(buildMissing), isFalse); }); test('should be able to use `findAssets` for files in lib', () { expect(reader.findAssets(Glob('lib/*.dart')), emitsThrough(buildTest)); }); test('should be able to use `findAssets` for files in test', () { expect(reader.findAssets(Glob('test/*.dart')), emitsThrough(thisFile)); }); test('should be able to use `findAssets` for files in non-root packages', () { expect(reader.findAssets(Glob('lib/*.dart'), package: 'build'), emitsThrough(buildAsset)); }); }); group('PackageAssetReader.forPackage', () { AssetReader reader; final exampleLibA = 'test/_libs/example_a/'; final exampleLibB = 'test/_libs/example_b/'; final exampleLibAFile = AssetId('example_a', 'lib/example_a.dart'); final exampleLibBFile = AssetId('example_b', 'lib/example_b.dart'); test('should resolve one library', () async { reader = PackageAssetReader.forPackageRoot('test/_libs'); expect(await reader.canRead(exampleLibAFile), isTrue); expect(await reader.canRead(exampleLibBFile), isTrue); }); test('should resolve multiple libraries', () async { reader = PackageAssetReader.forPackages({ 'example_a': exampleLibA, 'example_b': exampleLibB, }); expect(await reader.canRead(exampleLibAFile), isTrue); expect(await reader.canRead(exampleLibBFile), isTrue); }); }); }
build/build_test/test/package_reader_test.dart/0
{'file_path': 'build/build_test/test/package_reader_test.dart', 'repo_id': 'build', 'token_count': 984}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'package:_test_common/common.dart'; import 'package:test/test.dart'; import 'package:test_descriptor/test_descriptor.dart' as d; void main() { group('without null safety', () => _runTests(false)); group('with null safety', () => _runTests(true)); } void _runTests(bool nullSafe) { group('can compile vm apps to kernel', () { setUpAll(() async { final versionComment = nullSafe ? '' : '// @dart=2.9\n'; await d.dir('a', [ await pubspec( 'a', currentIsolateDependencies: [ 'analyzer', 'build', 'build_config', 'build_daemon', 'build_modules', 'build_resolvers', 'build_runner', 'build_runner_core', 'build_vm_compilers', 'code_builder', 'scratch_space', ], versionDependencies: { 'glob': 'any', 'path': 'any', }, sdkEnvironment: nullSafe ? '>=2.12.0 <3.0.0' : '>=2.9.0 <3.0.0', ), d.dir('bin', [ d.file('hello.dart', ''' $versionComment import 'package:path/path.dart' as p; void main() { print(p.url.join('hello', 'world')); } '''), d.file('goodbye.dart', ''' $versionComment import 'package:path/path.dart' as p; import 'hello.dart'; void main() { print(p.url.join('goodbye', 'world')); } '''), d.file('sync_async.dart', ''' $versionComment void main() async { print('before'); printAsync(); print('after'); } void printAsync() async { print('running'); } '''), ]), ]).create(); await pubGet('a'); // Run a build and expect it to succeed. var buildResult = await runPub('a', 'run', args: ['build_runner', 'build', '-o', 'out']); expect(buildResult.exitCode, 0, reason: buildResult.stderr as String?); }); test(' and run them', () async { var runResult = await runDart('a', 'out/bin/hello.vm.app.dill'); expect(runResult.exitCode, 0, reason: runResult.stderr as String?); expect(runResult.stdout, 'hello/world$_newLine'); }); test(' and run root libraries main', () async { var runResult = await runDart('a', 'out/bin/goodbye.vm.app.dill'); expect(runResult.exitCode, 0, reason: runResult.stderr as String?); expect(runResult.stdout, 'goodbye/world$_newLine'); }); test(' and enables sync-async', () async { var runResult = await runDart('a', 'out/bin/sync_async.vm.app.dill'); expect(runResult.exitCode, 0, reason: runResult.stderr as String?); expect(runResult.stdout, 'before${_newLine}running${_newLine}after$_newLine'); }); }); } final _newLine = Platform.isWindows ? '\r\n' : '\n';
build/build_vm_compilers/test/vm_kernel_integration_test.dart/0
{'file_path': 'build/build_vm_compilers/test/vm_kernel_integration_test.dart', 'repo_id': 'build', 'token_count': 1321}
publish_to: none name: build_development_tools description: Collection of scripts used during development of build packages. environment: sdk: '>=2.15.0 <3.0.0' dependencies: path: ^1.8.0 yaml_edit: ^2.0.1 yaml: ^3.1.0 dev_dependencies: lints: '>=1.0.0 <3.0.0' test_descriptor: ^2.0.0 test: ^1.20.1
build/tool/pubspec.yaml/0
{'file_path': 'build/tool/pubspec.yaml', 'repo_id': 'build', 'token_count': 142}
targets: $default: builders: lint_visitor_generator: enabled: true generate_for: include: - "**/node_lint_visitor.dart" source_gen|combining_builder: options: ignore_for_file: - "type=lint"
build_runner_bug/packages/custom_lint_core/build.yaml/0
{'file_path': 'build_runner_bug/packages/custom_lint_core/build.yaml', 'repo_id': 'build_runner_bug', 'token_count': 153}
@Timeout.factor(4) import 'package:build_verify/build_verify.dart' show defaultCommand; import 'package:build_verify/src/impl.dart'; import 'package:build_verify/src/utils.dart'; import 'package:git/git.dart'; import 'package:test/test.dart'; import 'package:test_descriptor/test_descriptor.dart' as d; import 'package:test_process/test_process.dart'; void main() { setUp(() async { await d.file('pubspec.yaml', ''' name: example version: 1.2.3 environment: sdk: '>=2.0.0 <3.0.0' dev_dependencies: build_runner: ^1.0.0 build_version: ^2.0.0 ''').create(); await d.dir('lib', [ d.dir('src', [ d.file('version.dart', r''' // Generated code. Do not modify. const packageVersion = '1.2.3'; ''') ]) ]).create(); final gitDir = await GitDir.init(d.sandbox, allowContent: true); await gitDir.runCommand(['add', '.']); await gitDir.runCommand(['commit', '-am', 'test']); final process = await TestProcess.start( pubPath, ['get', '--offline', '--no-precompile'], workingDirectory: d.sandbox); await process.shouldExit(0); }); test('succes unit test', () async { expectBuildCleanImpl(d.sandbox, defaultCommand); }); }
build_verify/test/integration_test.dart/0
{'file_path': 'build_verify/test/integration_test.dart', 'repo_id': 'build_verify', 'token_count': 485}
name: bunq description: A starting point for Dart libraries or applications. # version: 1.0.0 # homepage: https://www.example.com # author: Jogboms <jeremiahogbomo@gmail.com> environment: sdk: '>=2.3.0 <3.0.0' dependencies: pointycastle: ^1.0.0 asn1lib: ^0.5.3 uuid: ^2.0.1 http: ^0.12.0 built_value: ^6.4.0 built_collection: ^4.2.0 meta: ^1.1.7 dev_dependencies: pedantic: ^1.0.0 test: ^1.0.0 test_coverage: ^0.2.0 build_runner: ^1.3.1 built_value_generator: ^6.4.0
bunq.dart/pubspec.yaml/0
{'file_path': 'bunq.dart/pubspec.yaml', 'repo_id': 'bunq.dart', 'token_count': 234}
name: cached_value description: A simple way to cache values that result from rather expensive operations. version: 0.2.0 repository: https://github.com/bluefireteam/cached_value environment: sdk: ">=2.12.0 <3.0.0" dependencies: meta: ^1.3.0 collection: ^1.15.0 dev_dependencies: test: ^1.17.2 effective_dart: ^1.3.1
cached_value/pubspec.yaml/0
{'file_path': 'cached_value/pubspec.yaml', 'repo_id': 'cached_value', 'token_count': 128}
import 'dart:ui'; import 'canvas_command.dart'; /// canvas.drawLine() class LineCommand extends CanvasCommand { LineCommand(this.p1, this.p2, this.paint); final Offset p1; final Offset p2; final Paint? paint; @override bool equals(LineCommand other) { return eq(p1, other.p1) && eq(p2, other.p2) && eq(paint, other.paint); } @override String toString() { return 'drawLine(${repr(p1)}, ${repr(p2)}, ${repr(paint)})'; } }
canvas_test/lib/src/canvas_commands/line_command.dart/0
{'file_path': 'canvas_test/lib/src/canvas_commands/line_command.dart', 'repo_id': 'canvas_test', 'token_count': 185}
import 'package:carea/carea.dart'; import 'package:flutter/material.dart'; Future<void> main() async { WidgetsFlutterBinding.ensureInitialized(); runApp(const Carea()); }
carea/lib/main.dart/0
{'file_path': 'carea/lib/main.dart', 'repo_id': 'carea', 'token_count': 61}
name: ci concurrency: group: $-$ cancel-in-progress: true on: pull_request: branches: - master jobs: semantic_pull_request: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/semantic_pull_request.yml@v1 pana: runs-on: ubuntu-latest steps: - name: noop run: echo 'noop'
chance-dart/.github/workflows/master.yml/0
{'file_path': 'chance-dart/.github/workflows/master.yml', 'repo_id': 'chance-dart', 'token_count': 144}
import 'dart:math'; import 'package:chance_dart/chance_dart.dart'; /// It takes in a credit card type and a length, and returns a valid credit /// card number /// /// Args: /// ccType (CCType): The type of credit card you want to generate. /// visaLength (int): The length of the card number. /// /// Returns: /// A string of numbers. String cc({ CCType? ccType, int? visaLength, }) { // ccType = CCType.mastercard; final visaTypeCheck = visaLength != null && ccType != CCType.visa; final visaLengthCheck = visaLength != null && (visaLength != 13 || visaLength != 16); /// Checking if the ccType is visa and visaLength is not null. assert(visaTypeCheck, ''); /// Checking if the visaLength is not null and if it is not 13 or 16. assert(visaLengthCheck); // if (visaTypeCheck) { // throw ChanceException( // message: 'visalength can only be assigned to visa cards', // ); // } // if (!visaLengthCheck) { // throw ChanceException( // message: 'Card length not valid', // ); // } int pos = 0; List<int> str = List<int>.filled(16, 0); num finalDigit; num sum = 0; int tracker = 0; num lengthOffset = 0; int length = 0; if (ccType == CCType.visa) { str[0] = 4; pos = 1; length = visaLength!; } else if (ccType == CCType.mastercard) { str[0] = 5; tracker = (Random().nextDouble() * 5).floor() % 5; str[1] = 1 + tracker; pos = 2; length = 16; } else if (ccType == CCType.americanExpress) { str[0] = 3; tracker = (Random().nextDouble() * 4).floor() % 4; str[1] = 4 + tracker; pos = 2; length = 15; } else if (ccType == CCType.discover) { str[0] = 6; str[1] = 0; str[2] = 1; str[3] = 1; pos = 4; length = 16; } else {} while (pos < length - 1) { str[pos++] = (Random().nextDouble() * 10).floor() % 10; } lengthOffset = (length + 1) % 2; for (pos = 0; pos < length - 1; pos++) { if ((pos + lengthOffset) % 2 != 0) { tracker = str[pos] * 2; if (tracker > 9) { tracker -= 9; } sum += tracker; } else { sum += str[pos]; } } finalDigit = (10 - (sum % 10)) % 10; str[length - 1] = finalDigit.toInt(); // Output the CC value. tracker = int.parse(str.join('').substring(0, length)); return tracker.toString(); }
chance-dart/packages/chance_dart/lib/core/finance/src/cc.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/finance/src/cc.dart', 'repo_id': 'chance-dart', 'token_count': 933}
import 'dart:convert'; import 'package:equatable/equatable.dart'; class Coordinate extends Equatable { const Coordinate({ required this.latitude, required this.longitude, }); final double? latitude; final double? longitude; /// "If the caller passes in a value for latitude, use that value, otherwise /// use the value of /// this.latitude." /// /// The same logic applies to the longitude parameter /// /// Args: /// latitude (double): The latitude of the coordinate. /// longitude (double): The longitude of the coordinate. /// /// Returns: /// A new Coordinate object with the same values as the original Coordinate /// object, except for the /// values that are passed in as parameters. Coordinate copyWith({ double? latitude, double? longitude, }) { return Coordinate( latitude: latitude ?? this.latitude, longitude: longitude ?? this.longitude, ); } /// It converts the latitude and longitude into a map. /// /// Returns: /// A map of the latitude and longitude. Map<String, dynamic> toMap() { return <String, dynamic>{ 'latitude': latitude, 'longitude': longitude, }; } /// `Coordinate.fromMap` is a factory constructor that takes a /// `Map<String, dynamic>` and returns a /// `Coordinate` object /// /// Args: /// map (Map<String, dynamic>): The map that contains the data to be /// converted to a Coordinate object. /// /// Returns: /// A Coordinate object. factory Coordinate.fromMap(Map<String, dynamic> map) { return Coordinate( latitude: map['latitude'] as double?, longitude: map['longitude'] as double?, ); } /// It converts the object to a map. String toJson() => json.encode(toMap()); /// It converts a JSON string into a Coordinate object. /// /// Args: /// source (String): The JSON string to be converted to a Coordinate object. factory Coordinate.fromJson(String source) => Coordinate.fromMap(json.decode(source) as Map<String, dynamic>); @override bool get stringify => true; @override List<Object?> get props => [latitude, longitude]; }
chance-dart/packages/chance_dart/lib/core/location/models/coordinate.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/location/models/coordinate.dart', 'repo_id': 'chance-dart', 'token_count': 697}
import 'dart:math'; /// Generate a random 9 digit number, convert it to a string, and return it. /// /// Returns: /// A string String ssn() { final ssnNumber = (100000000 + Random().nextDouble() * 900000000).floor(); return ssnNumber.toString(); }
chance-dart/packages/chance_dart/lib/core/person/src/ssn.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/person/src/ssn.dart', 'repo_id': 'chance-dart', 'token_count': 81}
import 'package:chance_dart/chance_dart.dart'; /// Returns a random integer between 0 and 999. /// /// Returns: /// A random integer between 0 and 999. int hour() { return integer(max: 999); }
chance-dart/packages/chance_dart/lib/core/time/src/hour.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/time/src/hour.dart', 'repo_id': 'chance-dart', 'token_count': 64}
export 'src/chance_exception.dart';
chance-dart/packages/chance_dart/lib/src/exceptions/exceptions.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/src/exceptions/exceptions.dart', 'repo_id': 'chance-dart', 'token_count': 13}
import 'package:chance_dart/core/time/src/second.dart'; import 'package:test/test.dart'; void main() { test('second ... should return a valid second', () { final result = second(); final seconds = List.generate(60, (index) => index); expect(result, isIn(seconds)); }); }
chance-dart/packages/chance_dart/test/core/time/src/second_test.dart/0
{'file_path': 'chance-dart/packages/chance_dart/test/core/time/src/second_test.dart', 'repo_id': 'chance-dart', 'token_count': 100}
import 'package:analyzer/dart/constant/value.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:source_gen/source_gen.dart'; import 'package:source_helper/source_helper.dart'; const bool kConstConstructors = true; String constantToString( DartObject? object, [ List<String> typeInformation = const [], ]) { if (object == null || object.isNull) return 'null'; final reader = ConstantReader(object); return reader.isLiteral ? literalToString(object, typeInformation) : revivableToString(object, typeInformation); } String revivableToString(DartObject? object, List<String> typeInformation) { final reader = ConstantReader(object); final revivable = reader.revive(); if (revivable.source.fragment.isEmpty) { // Enums return revivable.accessor; } else { // Classes final nextTypeInformation = [...typeInformation, '$object']; final prefix = kConstConstructors ? 'const ' : ''; final ctor = revivable.accessor.isEmpty ? '' : '.${revivable.accessor}'; final arguments = <String>[ for (var arg in revivable.positionalArguments) constantToString(arg, nextTypeInformation), for (var kv in revivable.namedArguments.entries) '${kv.key}: ${constantToString(kv.value, nextTypeInformation)}' ]; return '$prefix${revivable.source.fragment}$ctor(${arguments.join(', ')})'; } } String literalToString(DartObject object, List<String> typeInformation) { final reader = ConstantReader(object); String? badType; if (reader.isSymbol) { badType = 'Symbol'; } else if (reader.isType) { badType = 'Type'; } else if (object.type is FunctionType) { badType = 'Function'; } else if (!reader.isLiteral) { badType = object.type!.element!.name; } if (badType != null) { badType = typeInformation.followedBy([badType]).join(' > '); throwUnsupported('`defaultValue` is `$badType`, it must be a literal.'); } if (reader.isDouble || reader.isInt || reader.isString || reader.isBool) { final value = reader.literalValue; if (value is String) return escapeDartString(value); if (value is double) { if (value.isNaN) { return 'double.nan'; } if (value.isInfinite) { if (value.isNegative) { return 'double.negativeInfinity'; } return 'double.infinity'; } } if (value is bool || value is num) return value.toString(); } if (reader.isList) { final listTypeInformation = [...typeInformation, 'List']; final listItems = reader.listValue .map((it) => constantToString(it, listTypeInformation)) .join(', '); return '[$listItems]'; } if (reader.isSet) { final setTypeInformation = [...typeInformation, 'Set']; final setItems = reader.setValue .map((it) => constantToString(it, setTypeInformation)) .join(', '); return '{$setItems}'; } if (reader.isMap) { final mapTypeInformation = [...typeInformation, 'Map']; final buffer = StringBuffer('{'); var first = true; reader.mapValue.forEach((key, value) { if (first) { first = false; } else { buffer.writeln(','); } buffer ..write(constantToString(key, mapTypeInformation)) ..write(': ') ..write(constantToString(value, mapTypeInformation)); }); buffer.write('}'); return buffer.toString(); } badType = typeInformation.followedBy(['$object']).join(' > '); throwUnsupported( 'The provided value is not supported: $badType. ' 'This may be an error in package:echancegenerator. ' 'Please rerun your build with `--verbose` and file an issue.', ); } Never throwUnsupported(String message) => throw InvalidGenerationSourceError('Error with `@ChanceField`. $message');
chance-dart/packages/chance_generator/lib/src/builder/utils/type_utils/type_helper.dart/0
{'file_path': 'chance-dart/packages/chance_generator/lib/src/builder/utils/type_utils/type_helper.dart', 'repo_id': 'chance-dart', 'token_count': 1409}
name: ci concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true on: push: branches: - main pull_request: branches: - main jobs: semantic_pull_request: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/semantic_pull_request.yml@v1 spell-check: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/spell_check.yml@v1 with: includes: "**/*.md" modified_files_only: false build: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/dart_package.yml@v1 pana_score: uses: VeryGoodOpenSource/very_good_workflows/.github/workflows/pana.yml@v1 integration_tests: runs-on: ubuntu-latest defaults: run: working-directory: "example/" steps: - name: 📚 Git Checkout uses: actions/checkout@v4 - name: 🎯 Setup Dart uses: dart-lang/setup-dart@v1 - name: 📦 Install Dependencies run: dart pub get - name: 🧪 Run Tests run: dart test --run-skipped -t integration -x known-issues
cli_completion/.github/workflows/main.yaml/0
{'file_path': 'cli_completion/.github/workflows/main.yaml', 'repo_id': 'cli_completion', 'token_count': 458}
/// Contains the completion command runner based elements to add completion to /// dart command line applications. library cli_completion; export 'src/command_runner/commands/commands.dart'; export 'src/command_runner/completion_command_runner.dart';
cli_completion/lib/cli_completion.dart/0
{'file_path': 'cli_completion/lib/cli_completion.dart', 'repo_id': 'cli_completion', 'token_count': 66}
import 'package:args/args.dart'; import 'package:cli_completion/parser.dart'; import 'package:meta/meta.dart'; /// {@template completion_result} /// Describes the result of a completion handling process. /// {@endtemplate} /// /// Generated after parsing a completion request from the shell, it is /// responsible to contain the information to be sent back to the shell /// (via stdout) including suggestions and its metadata (description). /// /// See also: /// - [AllOptionsAndCommandsCompletionResult] /// - [AllAbbrOptionsCompletionResult] /// - [MatchingCommandsCompletionResult] /// - [MatchingOptionsCompletionResult] /// - [OptionValuesCompletionResult] @immutable abstract class CompletionResult { /// {@macro completion_result} const CompletionResult(); /// A collection of [MapEntry] with completion suggestions to their /// descriptions. Map<String, String?> get completions; } /// {@template all_options_and_commands_completion_result} /// A [CompletionResult] that suggests all options and commands in a /// [completionLevel]. /// {@endtemplate} class AllOptionsAndCommandsCompletionResult extends CompletionResult { /// {@macro all_options_and_commands_completion_result} const AllOptionsAndCommandsCompletionResult({ required this.completionLevel, }); /// The [CompletionLevel] in which the suggested options and subcommands are /// supposed to be located at. final CompletionLevel completionLevel; @override Map<String, String?> get completions { final mapCompletions = <String, String?>{}; for (final subcommand in completionLevel.visibleSubcommands) { mapCompletions[subcommand.name] = subcommand.description; } for (final option in completionLevel.visibleOptions) { mapCompletions['--${option.name}'] = option.help; if (option.negatable ?? false) { mapCompletions['--no-${option.name}'] = option.help; } } return mapCompletions; } } /// {@template all_options_and_commands_completion_result} /// A [CompletionResult] that suggests all abbreviated options in a /// [completionLevel]. /// {@endtemplate} /// /// See also: /// - [AllOptionsAndCommandsCompletionResult] class AllAbbrOptionsCompletionResult extends CompletionResult { /// {@macro all_options_and_commands_completion_result} const AllAbbrOptionsCompletionResult({ required this.completionLevel, }); /// The [CompletionLevel] in which the suggested options and subcommands are /// supposed to be located at. final CompletionLevel completionLevel; @override Map<String, String?> get completions { final mapCompletions = <String, String?>{}; for (final option in completionLevel.visibleOptions) { final abbr = option.abbr; if (abbr != null) { mapCompletions['-$abbr'] = option.help; } } return mapCompletions; } } /// {@template matching_commands_completion_result} /// A [CompletionResult] that suggests the sub commands in a [completionLevel] /// that matches [pattern] (A.K.A: startsWith). /// {@endtemplate} /// /// If a command doesnt match the pattern, its aliases are also checked. class MatchingCommandsCompletionResult extends CompletionResult { /// {@macro matching_commands_completion_result} const MatchingCommandsCompletionResult({ required this.completionLevel, required this.pattern, }); /// The [CompletionLevel] in which the suggested commands are supposed to be /// located at. final CompletionLevel completionLevel; /// The pattern in which the matching commands will be suggested. final String pattern; @override Map<String, String?> get completions { final mapCompletions = <String, String>{}; for (final command in completionLevel.visibleSubcommands) { final description = command.description; if (command.name.startsWith(pattern)) { mapCompletions[command.name] = description; } else { for (final alias in command.aliases) { if (alias.startsWith(pattern)) { mapCompletions[alias] = description; } } } } return mapCompletions; } } /// {@template matching_options_completion_result} /// A [CompletionResult] that suggests the options in a [completionLevel] that /// starts with [pattern]. /// {@endtemplate} /// /// If an option does not match the pattern, its aliases will be checked. class MatchingOptionsCompletionResult extends CompletionResult { /// {@macro matching_options_completion_result} const MatchingOptionsCompletionResult({ required this.completionLevel, required this.pattern, }); /// The [CompletionLevel] in which the suggested options are supposed to be /// located at. final CompletionLevel completionLevel; /// The pattern in which the matching options will be suggested. final String pattern; @override Map<String, String?> get completions { final mapCompletions = <String, String?>{}; for (final option in completionLevel.visibleOptions) { final isNegatable = option.negatable ?? false; if (isNegatable) { if (option.negatedName.startsWith(pattern)) { mapCompletions['--${option.negatedName}'] = option.help; } else { for (final negatedAlias in option.negatedAliases) { if (negatedAlias.startsWith(pattern)) { mapCompletions['--$negatedAlias'] = option.help; } } } } if (option.name.startsWith(pattern)) { mapCompletions['--${option.name}'] = option.help; } else { for (final alias in option.aliases) { if (alias.startsWith(pattern)) { mapCompletions['--$alias'] = option.help; } } } } return mapCompletions; } } /// {@template option_values_completion_result} /// A [CompletionResult] that suggests the values of an option given its /// [optionName] and its [completionLevel]. /// {@endtemplate} /// /// For options with [Option.allowed] values, the suggestions will be those /// values with [Option.allowedHelp] as description. /// /// If [pattern] is not null, only the values that start with the pattern will /// be suggested. /// /// Use [OptionValuesCompletionResult.isAbbr] to suggest the values of an option /// in an abbreviated form. class OptionValuesCompletionResult extends CompletionResult { /// {@macro option_values_completion_result} const OptionValuesCompletionResult({ required this.completionLevel, required this.optionName, this.pattern, }) : isAbbr = false, includeAbbrName = false; /// {@macro option_values_completion_result} const OptionValuesCompletionResult.abbr({ required this.completionLevel, required String abbrName, this.pattern, this.includeAbbrName = false, }) : isAbbr = true, optionName = abbrName; /// The [CompletionLevel] in which the suggested option is supposed to be /// located at. final CompletionLevel completionLevel; /// The pattern in which the matching options values be suggested. final String? pattern; /// The name of the option whose values will be suggested. final String optionName; /// Whether the option name is abbreviated. final bool isAbbr; /// Whether the option name should be included in the suggestions. /// This is only used when [isAbbr] is true. /// /// If true, suggestions will look like `-psomething` where `p` is the /// abbreviated option name and `something` is the suggested value. final bool includeAbbrName; @override Map<String, String?> get completions { final Option? option; if (isAbbr) { option = completionLevel.grammar.findByAbbreviation(optionName); } else { option = completionLevel.grammar.findByNameOrAlias(optionName); } final allowed = option?.allowed ?? []; Iterable<String> filteredAllowed; if (pattern == null) { filteredAllowed = allowed; } else { filteredAllowed = allowed.where((e) => e.startsWith(pattern!)); } return { for (final allowed in filteredAllowed) if (includeAbbrName) '-$optionName$allowed': option?.allowedHelp?[allowed] else allowed: option?.allowedHelp?[allowed], }; } } extension on Option { String get negatedName => 'no-$name'; Iterable<String> get negatedAliases => aliases.map((e) => 'no-$e'); }
cli_completion/lib/src/parser/completion_result.dart/0
{'file_path': 'cli_completion/lib/src/parser/completion_result.dart', 'repo_id': 'cli_completion', 'token_count': 2749}
import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:cli_completion/parser.dart'; import 'package:test/test.dart'; class _TestCommand extends Command<void> { _TestCommand({ required this.name, required this.description, required this.aliases, }); @override final String description; @override final String name; @override final List<String> aliases; } void main() { group('AllOptionsAndCommandsCompletionResult', () { test( 'renders suggestions for all sub commands and options in' ' a completion level', () { final testArgParser = ArgParser() ..addOption('option1') ..addFlag('option2', help: 'yay option 2') ..addFlag( 'trueflag', negatable: false, ); final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const <String>[], visibleSubcommands: [ _TestCommand( name: 'command1', description: 'yay command 1', aliases: [], ), _TestCommand( name: 'command2', description: 'yay command 2', aliases: ['alias'], ), ], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = AllOptionsAndCommandsCompletionResult( completionLevel: completionLevel, ); expect( completionResult.completions, { 'command1': 'yay command 1', 'command2': 'yay command 2', '--option1': null, '--option2': 'yay option 2', '--no-option2': 'yay option 2', '--trueflag': null, }, ); }, ); }); group('AllAbbrOptionsCompletionResult', () { test( 'render suggestions for all abbreviated options ins a completion level', () { final testArgParser = ArgParser() ..addOption('option1') ..addOption('option2', abbr: 'a') ..addFlag('flag1') ..addFlag('flag2', abbr: 'b', help: 'yay flag1 2'); final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const [], visibleSubcommands: const [], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = AllAbbrOptionsCompletionResult( completionLevel: completionLevel, ); expect( completionResult.completions, {'-a': null, '-b': 'yay flag1 2'}, ); }, ); }); group('MatchingCommandsCompletionResult', () { test( 'renders suggestions only for sub commands that starts with pattern', () { final testArgParser = ArgParser()..addOption('option'); final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const <String>[], visibleSubcommands: [ _TestCommand( name: 'command1', description: 'yay command 1', aliases: [], ), _TestCommand( name: 'command2', description: 'yay command 2', aliases: ['command2alias'], ), _TestCommand( name: 'weird_command', description: 'yay weird command', aliases: ['command_not_weird'], ), ], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = MatchingCommandsCompletionResult( completionLevel: completionLevel, pattern: 'co', ); expect( completionResult.completions, { 'command1': 'yay command 1', 'command2': 'yay command 2', 'command_not_weird': 'yay weird command', }, ); }, ); }); group('MatchingOptionsCompletionResult', () { test( 'renders suggestions only for options that starts with pattern', () { final testArgParser = ArgParser() ..addOption('option1') ..addOption( 'noption2', aliases: ['option2alias'], help: 'yay noption2', ) ..addFlag('oflag1'); final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const <String>[], visibleSubcommands: const [], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = MatchingOptionsCompletionResult( completionLevel: completionLevel, pattern: 'o', ); expect( completionResult.completions, { '--option1': null, '--option2alias': 'yay noption2', '--oflag1': null, }, ); }, ); test( 'renders suggestions only for negated flags', () { final testArgParser = ArgParser() ..addOption('option1') ..addOption( 'noption2', aliases: ['option2alias'], help: 'yay noption2', ) ..addFlag('flag', aliases: ['aliasforflag']) ..addFlag('trueflag', negatable: false); final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const <String>[], visibleSubcommands: const [], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = MatchingOptionsCompletionResult( completionLevel: completionLevel, pattern: 'no', ); expect( completionResult.completions, { '--noption2': 'yay noption2', '--no-flag': null, }, ); final completionResultAlias = MatchingOptionsCompletionResult( completionLevel: completionLevel, pattern: 'no-a', ); expect( completionResultAlias.completions, { '--no-aliasforflag': null, }, ); }, ); }); group('OptionValuesCompletionResult', () { final testArgParser = ArgParser() ..addOption('continuous', abbr: 'c') ..addOption( 'allowed', abbr: 'a', allowed: [ 'value', 'valuesomething', 'anothervalue', ], allowedHelp: { 'valueyay': 'yay valueyay', 'valuesomething': 'yay valuesomething', }, ); group('OptionValuesCompletionResult.new', () { test('render suggestions for all option values', () { final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const <String>[], visibleSubcommands: const [], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = OptionValuesCompletionResult( completionLevel: completionLevel, optionName: 'allowed', ); expect(completionResult.completions, { 'value': null, 'valuesomething': 'yay valuesomething', 'anothervalue': null, }); }); test( 'renders suggestions for option values that starts with pattern', () { final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const <String>[], visibleSubcommands: const [], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = OptionValuesCompletionResult( completionLevel: completionLevel, optionName: 'allowed', pattern: 'va', ); expect(completionResult.completions, { 'value': null, 'valuesomething': 'yay valuesomething', }); }, ); test('renders no suggestions when there is no allowed values', () { final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const <String>[], visibleSubcommands: const [], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = OptionValuesCompletionResult( completionLevel: completionLevel, optionName: 'continuous', ); expect(completionResult.completions, isEmpty); }); }); group('OptionValuesCompletionResult.abbr', () { test('render suggestions for all option values', () { final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const <String>[], visibleSubcommands: const [], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = OptionValuesCompletionResult.abbr( completionLevel: completionLevel, abbrName: 'a', ); expect(completionResult.completions, { 'value': null, 'valuesomething': 'yay valuesomething', 'anothervalue': null, }); }); test( 'renders suggestions for option values that starts with pattern', () { final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const <String>[], visibleSubcommands: const [], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = OptionValuesCompletionResult.abbr( completionLevel: completionLevel, abbrName: 'a', pattern: 'va', ); expect(completionResult.completions, { 'value': null, 'valuesomething': 'yay valuesomething', }); }, ); test('renders no suggestions when there is no allowed values', () { final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const <String>[], visibleSubcommands: const [], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = OptionValuesCompletionResult.abbr( completionLevel: completionLevel, abbrName: 'o', ); expect(completionResult.completions, isEmpty); }); test('render suggestions for all option values with name', () { final completionLevel = CompletionLevel( grammar: testArgParser, rawArgs: const <String>[], visibleSubcommands: const [], visibleOptions: testArgParser.options.values.toList(), ); final completionResult = OptionValuesCompletionResult.abbr( completionLevel: completionLevel, abbrName: 'a', includeAbbrName: true, ); expect(completionResult.completions, { '-avalue': null, '-avaluesomething': 'yay valuesomething', '-aanothervalue': null, }); }); }); }); }
cli_completion/test/src/parser/completion_result_test.dart/0
{'file_path': 'cli_completion/test/src/parser/completion_result_test.dart', 'repo_id': 'cli_completion', 'token_count': 5132}
import 'dart:ui'; import 'package:canvas_clock/main.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; enum ClockColor { /// This is also used for tick marks or lines on the /// analog clock and thermometer. text, /// Used to outline some components. border, ballPrimary, ballSecondary, thermometerBackgroundPrimary, thermometerBackgroundSecondary, brad, /// Highlight colors here are used to resemble a shining material, /// i.e. some parts of the object should appear closer to the light source /// and e.g. metal will be lighter in those areas. bradHighlight, thermometerTube, thermometerMount, temperature, temperatureMax, temperatureMin, bracket, bracketHighlight, weatherArrow, weatherBackground, weatherBackgroundHighlight, cloud, fog, raindrop, snowflake, sun, lightning, windPrimary, windSecondary, background, goo, analogTimeBackground, analogTimeBackgroundHighlight, hourHand, minuteHand, secondHand, shadow, /// The digital time is on a different part of the background, /// i.e. on the goo and therefore might need a different text /// color. digitalTimeText, /// The two dots that are drawn onto the ball /// in order to always show rotation turned /// into more than that and also have a signaling /// function. They show what state the ball is /// currently in. dotsIdleColor, dotsPrimedColor, dotsDisengagedColor, /// These form a linear gradient. slidePrimary, slideSecondary, /// Colors used for [ExtendedCanvas.drawPetals]. petals, petalsHighlight, } /// A controller for the palette for all colors used in the clock face. /// /// The actual palette values are stored as `Map<ClockColor, Color>` /// ([Map], [ClockColor], & [Color]) and this [StatefulWidget] controls /// which palette is currently shown. /// /// Predefined palettes are [vibrantLight] and [subtleLight] or [vibrantDark] and [subtleDark], /// which override values in [light]/[dark] respectively, which override values in [base]. class Palette extends StatefulWidget { static _PaletteState of(BuildContext context) => context.findAncestorStateOfType<_PaletteState>(); static const Map<ClockColor, Color> base = { // Temperature colors are supposed to match // the colors that a temperature makes us think of. ClockColor.temperature: Color(0xde6ab7ff), ClockColor.temperatureMax: Color(0x9cff3a4b), ClockColor.temperatureMin: Color(0xae2a42ff), // Weather icons resemble real life colors. ClockColor.cloud: Color(0xcbc1beba), ClockColor.fog: Color(0xc5cdc8be), ClockColor.raindrop: Color(0xdda1c6cc), ClockColor.snowflake: Color(0xbbfffafa), ClockColor.sun: Color(0xfffcd440), ClockColor.lightning: Color(0xfffdd023), ClockColor.windPrimary: Color(0xff96c4e8), ClockColor.windSecondary: Color(0xff008abf), ClockColor.shadow: Color(0xff000000), // Based on some metal, works everywhere. ClockColor.brad: Color(0xff898984), ClockColor.bradHighlight: Color(0xff43464b), ClockColor.bracket: Color(0xff87898c), ClockColor.bracketHighlight: Color(0xffe0e1e2), // Dots on the ball ClockColor.dotsIdleColor: Color(0x90e5e4e2), ClockColor.dotsPrimedColor: Color(0xc3e00201), ClockColor.dotsDisengagedColor: Color(0x804682b4), }, light = { ClockColor.text: Color(0xcd000000), ClockColor.border: Color(0xff000000), ClockColor.petalsHighlight: Color(0xffffffff), ClockColor.analogTimeBackgroundHighlight: Color(0xffffffff), // These look too sad in light mode otherwise ClockColor.cloud: Color(0xebc1beba), ClockColor.fog: Color(0xe5dfdad0), }, vibrantLight = { // Background ClockColor.background: Color(0xffae8c5f), ClockColor.goo: Color(0xff35271c), // Component backgrounds ClockColor.analogTimeBackground: Color(0xffe2ca5c), ClockColor.weatherBackground: Color(0xffaa8630), ClockColor.weatherBackgroundHighlight: Color(0xfffbf6ce), ClockColor.thermometerBackgroundPrimary: Color(0xffaa8630), ClockColor.thermometerBackgroundSecondary: Color(0xfff8f1a3), ClockColor.slidePrimary: Color(0xff94704e), ClockColor.slideSecondary: Color(0xff392818), // Smaller elements ClockColor.petals: Color(0xffbab33c), ClockColor.ballPrimary: Color(0xffc9855e), ClockColor.ballSecondary: Color(0xff2b2100), ClockColor.digitalTimeText: Color(0xfff3f0c7), // Thermometer ClockColor.thermometerTube: Color(0xffffe3d1), ClockColor.thermometerMount: Color(0xff836d2e), // Analog clock ClockColor.hourHand: Color(0xff3a1009), ClockColor.minuteHand: Color(0xff000000), ClockColor.secondHand: Color(0xff09103a), // Weather dial ClockColor.weatherArrow: Color(0xff3D0C02), ClockColor.raindrop: Color(0xbf8cdfe8), ClockColor.windPrimary: Color(0xef99edf3), ClockColor.windSecondary: Color(0xff1c70b7), }, subtleLight = { // Background ClockColor.background: Color(0xffb2beb5), ClockColor.goo: Color(0xff828e84), // Component backgrounds ClockColor.analogTimeBackground: Color(0xffdcddd8), ClockColor.weatherBackground: Color(0xffdcddd8), ClockColor.weatherBackgroundHighlight: Color(0xfffafafa), ClockColor.thermometerBackgroundPrimary: Color(0xffffffff), ClockColor.thermometerBackgroundSecondary: Color(0xffc6c8c5), ClockColor.slideSecondary: Color(0xffcdcbce), ClockColor.slidePrimary: Color(0xff9d9e98), // Smaller elements ClockColor.ballPrimary: Color(0xff828e84), ClockColor.ballSecondary: Color(0xff2a3731), ClockColor.petals: Color(0xdd000000), ClockColor.digitalTimeText: Color(0xcd000000), // Thermometer ClockColor.thermometerMount: Color(0xff919c9f), ClockColor.thermometerTube: Color(0xffededed), // Analog clock ClockColor.hourHand: Color(0xff232323), ClockColor.minuteHand: Color(0xff1a1a1a), ClockColor.secondHand: Color(0xff000000), // Weather dial ClockColor.weatherArrow: Color(0xff121314), ClockColor.sun: Color(0xffe4bd29), }, dark = { // Text ClockColor.text: Color(0xb3ffffff), ClockColor.digitalTimeText: Color(0xb3ffffff), // Misc ClockColor.border: Color(0xffffffff), ClockColor.thermometerTube: Color(0xc1d9d9d9), }, vibrantDark = { // Background ClockColor.background: Color(0xff121212), ClockColor.goo: Color(0xff000010), // Component backgrounds ClockColor.thermometerBackgroundPrimary: Color(0xff2f2f4f), ClockColor.thermometerBackgroundSecondary: Color(0xff03031f), ClockColor.analogTimeBackground: Color(0xff980036), ClockColor.analogTimeBackgroundHighlight: Color(0xffca1f7b), ClockColor.weatherBackground: Color(0xff4b0082), ClockColor.weatherBackgroundHighlight: Color(0xff7f00ff), // other elements ClockColor.petals: Color(0xff483d8b), ClockColor.petalsHighlight: Color(0xff9f79ee), ClockColor.ballPrimary: Color(0xff42426f), ClockColor.ballSecondary: Color(0xff162252), ClockColor.slidePrimary: Color(0xff200460), ClockColor.slideSecondary: Color(0xff4d4870), // Thermometer ClockColor.thermometerMount: Color(0xff525252), ClockColor.temperature: Color(0xce3a97df), ClockColor.temperatureMax: Color(0x8cdf1a2b), ClockColor.temperatureMin: Color(0xae071fdd), // Analog clock ClockColor.hourHand: Color(0xffcfbdff), ClockColor.minuteHand: Color(0xfff0e0ff), ClockColor.secondHand: Color(0xffc0aefd), // Weather dial ClockColor.weatherArrow: Color(0xffcdcded), }, subtleDark = { // Background ClockColor.background: Color(0xff050505), ClockColor.goo: Color(0xff000000), // Component backgrounds ClockColor.analogTimeBackground: Color(0xff333333), ClockColor.analogTimeBackgroundHighlight: Color(0xff646464), ClockColor.weatherBackground: Color(0xff343434), ClockColor.weatherBackgroundHighlight: Color(0xff454545), ClockColor.thermometerBackgroundPrimary: Color(0xff343434), ClockColor.thermometerBackgroundSecondary: Color(0xff0e0e0e), ClockColor.slideSecondary: Color(0xff333333), ClockColor.slidePrimary: Color(0xff101010), // Smaller elements ClockColor.ballPrimary: Color(0xff6c6c6c), ClockColor.ballSecondary: Color(0xff080808), ClockColor.petals: Color(0xffffffff), ClockColor.petalsHighlight: Color(0x7f212121), // Thermometer ClockColor.thermometerMount: Color(0xff525252), ClockColor.temperature: Color(0xce3a97df), ClockColor.temperatureMax: Color(0x8cdf1a2b), ClockColor.temperatureMin: Color(0xae071fdd), // Analog clock ClockColor.hourHand: Color(0xffc1c1c1), ClockColor.minuteHand: Color(0xffefefef), ClockColor.secondHand: Color(0xffafafaf), // Weather dial ClockColor.weatherArrow: Color(0xff979797), }; final Widget Function(BuildContext context, Map<ClockColor, Color> palette) builder; const Palette({ @required this.builder, }) : assert(builder != null); @override _PaletteState createState() => _PaletteState(); } /// The modes determine which palette in the given theme (dark or light) is shown. /// /// This is controlled by the [paletteMode] constant. enum PaletteMode { vibrant, subtle, adaptive, } Map<ClockColor, Color> resolvePalette(Brightness brightness, bool vibrant) { final palette = Map.of(Palette.base); if (brightness == Brightness.light) { palette.addAll(Palette.light); switch (paletteMode) { case PaletteMode.vibrant: palette.addAll(Palette.vibrantLight); break; case PaletteMode.subtle: palette.addAll(Palette.subtleLight); break; case PaletteMode.adaptive: if (vibrant) { palette.addAll(Palette.vibrantLight); } else { palette.addAll(Palette.subtleLight); } break; } } else { palette.addAll(Palette.dark); switch (paletteMode) { case PaletteMode.vibrant: palette.addAll(Palette.vibrantDark); break; case PaletteMode.subtle: palette.addAll(Palette.subtleDark); break; case PaletteMode.adaptive: if (vibrant) { palette.addAll(Palette.vibrantDark); } else { palette.addAll(Palette.subtleDark); } break; } } return palette; } class _PaletteState extends State<Palette> { bool _vibrant; @override void initState() { super.initState(); _vibrant = true; } set vibrant(bool value) { if (_vibrant == value) return; setState(() { _vibrant = value; }); } bool get vibrant => _vibrant; Map<ClockColor, Color> resolve(BuildContext context) => resolvePalette(Theme.of(context).brightness, _vibrant); @override Widget build(BuildContext context) { return widget.builder(context, resolve(context)); } }
clock/canvas_clock/lib/components/style/palette.dart/0
{'file_path': 'clock/canvas_clock/lib/components/style/palette.dart', 'repo_id': 'clock', 'token_count': 4110}
/// An abstract class representing the connection logic for a cloud storage /// service. // ignore_for_file: one_member_abstracts abstract class Cloud9Connector { /// Connects to the cloud storage service. Future<dynamic> connect(); }
cloud9/lib/src/connectors/src/cloud9_connector.dart/0
{'file_path': 'cloud9/lib/src/connectors/src/cloud9_connector.dart', 'repo_id': 'cloud9', 'token_count': 63}
targets: $default: builders: source_gen|combining_builder: options: ignore_for_file: - always_specify_types - implicit_dynamic_parameter
cocoon/app_dart/build.yaml/0
{'file_path': 'cocoon/app_dart/build.yaml', 'repo_id': 'cocoon', 'token_count': 96}
// Copyright 2019 The Flutter Authors. 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:appengine/appengine.dart'; import 'package:http/http.dart' as http; /// Signature for a function that returns an App Engine [ClientContext]. /// /// This is used in [AuthenticationProvider] to provide the client context /// as part of the [AuthenticatedContext]. typedef ClientContextProvider = ClientContext Function(); /// Signature for a function that returns an [HttpClient]. /// /// This is used by [AuthenticationProvider] to provide the HTTP client that /// will be used (if necessary) to verify OAuth ID tokens (JWT tokens). typedef HttpClientProvider = http.Client Function();
cocoon/app_dart/lib/src/foundation/typedefs.dart/0
{'file_path': 'cocoon/app_dart/lib/src/foundation/typedefs.dart', 'repo_id': 'cocoon', 'token_count': 195}
// Copyright 2019 The Flutter Authors. 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:fixnum/fixnum.dart'; import 'package:gcloud/db.dart'; import '../proto/protos.dart' as pb; import 'key_helper.dart'; class KeyWrapper { const KeyWrapper(this.key); factory KeyWrapper.fromProto(pb.RootKey root) { Key<dynamic> result = Key<dynamic>.emptyKey(Partition(root.namespace)); for (pb.Key key = root.child; key.hasChild(); key = key.child) { final Type type = _typeFromString(key.type); switch (key.whichId()) { case pb.Key_Id.uid: result = result.append<int>(type, id: key.uid.toInt()); break; case pb.Key_Id.name: result = result.append<String>(type, id: key.name); break; case pb.Key_Id.notSet: result = result.append<dynamic>(type); break; } } return KeyWrapper(result); } final Key<dynamic> key; pb.RootKey toProto() { pb.Key? previous; for (Key<dynamic>? slice = key; slice != null; slice = key.parent) { final pb.Key current = pb.Key(); if (slice.type != null) { current.type = slice.type.toString(); } final Object? id = slice.id; if (id is String) { current.name = id; } else if (id is int) { current.uid = Int64(id); } if (previous != null) { current.child = previous; } previous = current; if (slice.isEmpty) { return pb.RootKey() ..namespace = slice.partition.namespace! ..child = previous; } } return pb.RootKey()..child = previous!; } static Type _typeFromString(String value) { final KeyHelper keyHelper = KeyHelper(); return keyHelper.types.keys.singleWhere((Type type) => type.toString() == value); } }
cocoon/app_dart/lib/src/model/appengine/key_wrapper.dart/0
{'file_path': 'cocoon/app_dart/lib/src/model/appengine/key_wrapper.dart', 'repo_id': 'cocoon', 'token_count': 816}
// Copyright 2019 The Flutter Authors. 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'; import '../common/json_converters.dart'; part 'token_info.g.dart'; @JsonSerializable() class TokenInfo { /// Creates a new [TokenInfo]. const TokenInfo({ this.issuer, this.authorizedParty, this.audience, this.subject, this.hostedDomain, this.email, this.emailIsVerified, this.accessTokenHash, this.fullName, this.profilePictureUrl, this.givenName, this.familyName, this.locale, this.issued, this.expiration, this.jwtId, this.algorithm, this.keyId, this.encoding, }); /// Create a new [TokenInfo] object from its JSON representation. factory TokenInfo.fromJson(Map<String, dynamic> json) => _$TokenInfoFromJson(json); /// The issuer of the token (e.g. "accounts.google.com"). @JsonKey(name: 'iss') final String? issuer; /// The party to which the ID Token was issued. @JsonKey(name: 'azp') final String? authorizedParty; /// The token's intended audience. /// /// This should be compared against the expected OAuth client ID. @JsonKey(name: 'aud') final String? audience; /// The principal (subject) of the token. @JsonKey(name: 'sub') final String? subject; /// The user's domain. /// /// https://developers.google.com/identity/protocols/OpenIDConnect#hd-param @JsonKey(name: 'hd') final String? hostedDomain; /// The user's email address. @JsonKey(name: 'email') final String? email; /// Boolean indicating whether the user has verified their email address. @JsonKey(name: 'email_verified') @BoolConverter() final bool? emailIsVerified; /// Access token hash value. @JsonKey(name: 'at_hash') final String? accessTokenHash; /// The user's full name. @JsonKey(name: 'name') final String? fullName; /// URL of the user's profile picture. @JsonKey(name: 'picture') final String? profilePictureUrl; /// The user's given name. @JsonKey(name: 'given_name') final String? givenName; /// The user's family name / surname. @JsonKey(name: 'family_name') final String? familyName; /// The user's local code (e.g. "en") @JsonKey(name: 'locale') final String? locale; /// Token issuance date. @JsonKey(name: 'iat') @SecondsSinceEpochConverter() final DateTime? issued; /// Token expiration. @JsonKey(name: 'exp') @SecondsSinceEpochConverter() final DateTime? expiration; /// Unique identifier for the token itself. @JsonKey(name: 'jti') final String? jwtId; /// Encryption algorithm used to encrypt the token (e.g. "RS256"). @JsonKey(name: 'alg') final String? algorithm; /// Key identifier. @JsonKey(name: 'kid') final String? keyId; /// The encoding that was used to encode the unverified token (e.g. "JWT") @JsonKey(name: 'typ') final String? encoding; /// Serializes this object to a JSON primitive. Map<String, dynamic> toJson() => _$TokenInfoToJson(this); }
cocoon/app_dart/lib/src/model/google/token_info.dart/0
{'file_path': 'cocoon/app_dart/lib/src/model/google/token_info.dart', 'repo_id': 'cocoon', 'token_count': 1069}
// Copyright 2019 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'package:meta/meta.dart'; import '../request_handling/api_request_handler.dart'; import '../request_handling/body.dart'; import '../request_handling/exceptions.dart'; import '../service/cache_service.dart'; import '../service/config.dart'; /// Trigger a cache flush on a config key and return empty response if successful. /// /// If [cacheKeyParam] is not passed, throws [BadRequestException]. /// If the cache does not have the given key, throws [NotFoundException]. @immutable class FlushCache extends ApiRequestHandler<Body> { const FlushCache({ required super.config, required super.authenticationProvider, required this.cache, }); final CacheService cache; /// Name of the query parameter passed to the endpoint. /// /// The value is expected to be an existing value from [CocoonConfig]. static const String cacheKeyParam = 'key'; @override Future<Body> get() async { checkRequiredQueryParameters(<String>[cacheKeyParam]); final String cacheKey = request!.uri.queryParameters[cacheKeyParam]!; // To validate cache flushes, validate that the key exists. await cache.getOrCreate( Config.configCacheName, cacheKey, createFn: () => throw NotFoundException('Failed to find cache key: $cacheKey'), ); await cache.purge(Config.configCacheName, cacheKey); return Body.empty; } }
cocoon/app_dart/lib/src/request_handlers/flush_cache.dart/0
{'file_path': 'cocoon/app_dart/lib/src/request_handlers/flush_cache.dart', 'repo_id': 'cocoon', 'token_count': 471}
// Copyright 2019 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:http/http.dart' as http; import 'package:meta/meta.dart'; import '../service/config.dart'; import '../service/logging.dart'; import 'body.dart'; import 'exceptions.dart'; /// A class that services HTTP requests and returns HTTP responses. /// /// `T` is the type of object that is returned as the body of the HTTP response /// (before serialization). Subclasses whose HTTP responses don't include a /// body should extend `RequestHandler<Body>` and return null in their service /// handlers ([get] and [post]). abstract class RequestHandler<T extends Body> { /// Creates a new [RequestHandler]. const RequestHandler({ required this.config, }); /// The global configuration of this AppEngine server. final Config config; /// Services an HTTP request. /// /// Subclasses should generally not override this method. Instead, they /// should override one of [get] or [post], depending on which methods /// they support. Future<void> service( HttpRequest request, { Future<void> Function(HttpStatusException)? onError, }) { return runZoned<Future<void>>( () async { final HttpResponse response = request.response; try { try { T body; switch (request.method) { case 'GET': body = await get(); break; case 'POST': body = await post(); break; default: throw MethodNotAllowed(request.method); } await _respond(body: body); httpClient?.close(); return; } on HttpStatusException { rethrow; } catch (error, stackTrace) { log.severe('$error\n$stackTrace'); throw InternalServerError('$error\n$stackTrace'); } } on HttpStatusException catch (error) { if (onError != null) { await onError(error); } response ..statusCode = error.statusCode ..write(error.message); await response.flush(); await response.close(); return; } }, zoneValues: <RequestKey<dynamic>, Object>{ RequestKey.request: request, RequestKey.response: request.response, RequestKey.httpClient: httpClient ?? http.Client(), }, ); } /// Responds (using [response]) with the specified [status] and optional /// [body]. /// /// Returns a future that completes when [response] has been closed. Future<void> _respond({int status = HttpStatus.ok, Body body = Body.empty}) async { response!.statusCode = status; await response!.addStream(body.serialize().cast<List<int>>()); await response!.flush(); await response!.close(); } /// Gets the value associated with the specified [key] in the request /// context. /// /// Concrete subclasses should not call this directly. Instead, they should /// access the getters that are tied to specific keys, such as [request] /// and [response]. /// /// If this is called outside the context of an HTTP request, this will /// throw a [StateError]. @protected U? getValue<U>(RequestKey<U> key, {bool allowNull = false}) { final U? value = Zone.current[key] as U?; if (!allowNull && value == null) { throw StateError('Attempt to access ${key.name} while not in a request context'); } return value; } /// Gets the current [HttpRequest]. /// /// If this is called outside the context of an HTTP request, this will /// throw a [StateError]. @protected HttpRequest? get request => getValue<HttpRequest>(RequestKey.request); /// Gets the current [HttpResponse]. /// /// If this is called outside the context of an HTTP request, this will /// throw a [StateError]. @protected HttpResponse? get response => getValue<HttpResponse>(RequestKey.response); /// Services an HTTP GET. /// /// Subclasses should override this method if they support GET requests. /// The default implementation will respond with HTTP 405 method not allowed. @protected Future<T> get() async { throw const MethodNotAllowed('GET'); } /// Services an HTTP POST. /// /// Subclasses should override this method if they support POST requests. /// The default implementation will respond with HTTP 405 method not allowed. @protected Future<T> post() async { throw const MethodNotAllowed('POST'); } /// The package:http Client to use for googleapis requests. @protected http.Client? get httpClient => getValue<http.Client>( RequestKey.httpClient, allowNull: true, ); } /// A key that can be used to index a value within the request context. /// /// Subclasses will only need to deal directly with this class if they add /// their own request context values. @protected class RequestKey<T> { const RequestKey(this.name); final String name; static const RequestKey<HttpRequest> request = RequestKey<HttpRequest>('request'); static const RequestKey<HttpResponse> response = RequestKey<HttpResponse>('response'); static const RequestKey<http.Client> httpClient = RequestKey<http.Client>('httpClient'); @override String toString() => '$runtimeType($name)'; }
cocoon/app_dart/lib/src/request_handling/request_handler.dart/0
{'file_path': 'cocoon/app_dart/lib/src/request_handling/request_handler.dart', 'repo_id': 'cocoon', 'token_count': 1873}
// Copyright 2019 The Flutter Authors. 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:cocoon_service/src/request_handling/authentication.dart' show AuthenticatedContext; import 'package:cocoon_service/src/request_handling/exceptions.dart'; import 'package:cocoon_service/src/request_handling/pubsub_authentication.dart'; import 'package:cocoon_service/src/service/config.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:test/test.dart'; import '../src/datastore/fake_config.dart'; import '../src/request_handling/fake_authentication.dart'; import '../src/request_handling/fake_http.dart'; void main() { group('PubsubAuthenticationProvider', () { late FakeConfig config; late FakeClientContext clientContext; late FakeHttpRequest request; late PubsubAuthenticationProvider auth; late MockClient httpClient; setUp(() { config = FakeConfig(); clientContext = FakeClientContext(); request = FakeHttpRequest(); auth = PubsubAuthenticationProvider( config: config, clientContextProvider: () => clientContext, httpClientProvider: () => httpClient, ); }); for (String allowedAccount in Config.allowedPubsubServiceAccounts) { test('auth succeeds for $allowedAccount', () async { httpClient = MockClient( (_) async => http.Response( _generateTokenResponse(allowedAccount), HttpStatus.ok, headers: <String, String>{ HttpHeaders.contentTypeHeader: 'application/json', }, ), ); auth = PubsubAuthenticationProvider( config: config, clientContextProvider: () => clientContext, httpClientProvider: () => httpClient, ); request.headers.add(HttpHeaders.authorizationHeader, 'Bearer token'); final AuthenticatedContext result = await auth.authenticate(request); expect(result.clientContext, same(clientContext)); }); } test('auth fails with unauthorized service account', () async { httpClient = MockClient( (_) async => http.Response( _generateTokenResponse('unauthorized@gmail.com'), HttpStatus.ok, headers: <String, String>{ HttpHeaders.contentTypeHeader: 'application/json', }, ), ); auth = PubsubAuthenticationProvider( config: config, clientContextProvider: () => clientContext, httpClientProvider: () => httpClient, ); request.headers.add(HttpHeaders.authorizationHeader, 'Bearer token'); expect(auth.authenticate(request), throwsA(isA<Unauthenticated>())); }); test('auth fails with invalid token', () async { httpClient = MockClient( (_) async => http.Response( 'Invalid token', HttpStatus.unauthorized, headers: <String, String>{ HttpHeaders.contentTypeHeader: 'application/json', }, ), ); auth = PubsubAuthenticationProvider( config: config, clientContextProvider: () => clientContext, httpClientProvider: () => httpClient, ); request.headers.add(HttpHeaders.authorizationHeader, 'Bearer token'); expect(auth.authenticate(request), throwsA(isA<FormatException>())); }); test('auth fails with expired token', () async { httpClient = MockClient( (_) async => http.Response( _generateTokenResponse( Config.allowedPubsubServiceAccounts.first, expiresIn: -1, ), HttpStatus.ok, headers: <String, String>{ HttpHeaders.contentTypeHeader: 'application/json', }, ), ); auth = PubsubAuthenticationProvider( config: config, clientContextProvider: () => clientContext, httpClientProvider: () => httpClient, ); request.headers.add(HttpHeaders.authorizationHeader, 'Bearer token'); expect(auth.authenticate(request), throwsA(isA<Unauthenticated>())); }); }); } /// Return Google's OAuth response. String _generateTokenResponse( String email, { int expiresIn = 123, }) { return '''{ "issued_to": "456", "audience": "https://flutter-dashboard.appspot.com/api/luci-status-handler", "user_id": "789", "expires_in": $expiresIn, "email": "$email", "verified_email": true, "issuer": "https://accounts.google.com", "issued_at": 412321 }'''; }
cocoon/app_dart/test/request_handling/pubsub_authentication_test.dart/0
{'file_path': 'cocoon/app_dart/test/request_handling/pubsub_authentication_test.dart', 'repo_id': 'cocoon', 'token_count': 1896}
// Copyright 2020 The Flutter Authors. 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'; import 'package:cocoon_service/src/service/github_service.dart'; import 'package:github/github.dart'; import 'package:http/http.dart' as http; import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; import '../src/utilities/mocks.dart'; void main() { late GithubService githubService; MockGitHub mockGitHub; late RepositorySlug slug; const String branch = 'master'; const int lastCommitTimestampMills = 100; const String authorName = 'Jane Doe'; const String authorEmail = 'janedoe@example.com'; const String authorDate = '2000-01-01T10:10:10Z'; const String authorLogin = 'Username'; const String authorAvatarUrl = 'http://example.com/avatar'; const String commitMessage = 'commit message'; List<String> shas; setUp(() { shas = <String>[]; mockGitHub = MockGitHub(); githubService = GithubService(mockGitHub); slug = RepositorySlug('flutter', 'flutter'); final PostExpectation<Future<http.Response>> whenGithubRequest = when( mockGitHub.request( 'GET', '/repos/${slug.owner}/${slug.name}/commits', headers: anyNamed('headers'), params: anyNamed('params'), body: anyNamed('body'), statusCode: anyNamed('statusCode'), ), ); whenGithubRequest.thenAnswer((_) async { final List<dynamic> data = <dynamic>[]; for (String sha in shas) { // https://developer.github.com/v3/repos/commits/#list-commits data.add(<String, dynamic>{ 'sha': sha, 'commit': <String, dynamic>{ 'message': commitMessage, 'author': <String, dynamic>{ 'name': authorName, 'email': authorEmail, 'date': authorDate, }, }, 'author': <String, dynamic>{ 'login': authorLogin, 'avatar_url': authorAvatarUrl, }, }); } return http.Response(json.encode(data), HttpStatus.ok); }); }); test('listCommits decodes all relevant fields of each commit', () async { shas = <String>['1']; final List<RepositoryCommit> commits = await githubService.listBranchedCommits( slug, branch, lastCommitTimestampMills, ); expect(commits, hasLength(1)); final RepositoryCommit commit = commits.single; expect(commit.sha, shas.single); expect(commit.author, isNotNull); expect(commit.author!.login, authorLogin); expect(commit.author!.avatarUrl, authorAvatarUrl); expect(commit.commit, isNotNull); expect(commit.commit!.message, commitMessage); expect(commit.commit!.committer, isNotNull); expect(commit.commit!.committer!.name, authorName); expect(commit.commit!.committer!.email, authorEmail); }); test('searchIssuesAndPRs encodes query properly', () async { mockGitHub = MockGitHub(); final mockSearchService = MockSearchService(); when(mockGitHub.search).thenReturn(mockSearchService); when(mockSearchService.issues(any)).thenAnswer((invocation) { expect( invocation.positionalArguments[0], '6afa96d84e2ecf6537f8ea76341d8ba397942e80%20repo%3Aflutter%2Fflutter', ); return const Stream.empty(); }); githubService = GithubService(mockGitHub); await githubService.searchIssuesAndPRs( slug, '6afa96d84e2ecf6537f8ea76341d8ba397942e80', ); }); }
cocoon/app_dart/test/service/github_service_test.dart/0
{'file_path': 'cocoon/app_dart/test/service/github_service_test.dart', 'repo_id': 'cocoon', 'token_count': 1443}
// Copyright 2023 The Flutter Authors. 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:auto_submit/configuration/repository_configuration.dart'; import 'package:auto_submit/service/config.dart'; import 'package:auto_submit/service/process_method.dart'; import 'package:auto_submit/validations/approval.dart'; import 'package:auto_submit/validations/ci_successful.dart'; import 'package:auto_submit/validations/empty_checks.dart'; import 'package:auto_submit/validations/mergeable.dart'; import 'package:auto_submit/validations/required_check_runs.dart'; import 'package:auto_submit/validations/validation.dart'; /// The [ValidationFilter] allows us to pick and choose and the validations to /// run on a particular type of pull request. abstract class ValidationFilter { factory ValidationFilter({ required Config config, required ProcessMethod processMethod, required RepositoryConfiguration repositoryConfiguration, }) { switch (processMethod) { case ProcessMethod.processAutosubmit: return PullRequestValidationFilter(config, repositoryConfiguration); case ProcessMethod.processRevert: return RevertRequestValidationFilter(config, repositoryConfiguration); default: throw 'No such processMethod enum value'; } } Set<Validation> getValidations(); } /// [PullRequestValidationFilter] returns a Set of validations that we run on /// all non revert pull requests that will be merged into the mainline branch. class PullRequestValidationFilter implements ValidationFilter { PullRequestValidationFilter(this.config, this.repositoryConfiguration); final Config config; final RepositoryConfiguration repositoryConfiguration; @override Set<Validation> getValidations() { final Set<Validation> validationsToRun = {}; validationsToRun.add(Approval(config: config)); // If we are running ci then we need to check the checkRuns and make sure // there are check runs created. if (repositoryConfiguration.runCi) { validationsToRun.add(CiSuccessful(config: config)); validationsToRun.add(EmptyChecks(config: config)); } validationsToRun.add(Mergeable(config: config)); return validationsToRun; } } /// [RevertRequestValidationFilter] returns a Set of validations that we run on /// all revert pull requests. class RevertRequestValidationFilter implements ValidationFilter { RevertRequestValidationFilter(this.config, this.repositoryConfiguration); final Config config; final RepositoryConfiguration repositoryConfiguration; @override Set<Validation> getValidations() { final Set<Validation> validationsToRun = {}; validationsToRun.add(Approval(config: config)); validationsToRun.add(RequiredCheckRuns(config: config)); validationsToRun.add(Mergeable(config: config)); return validationsToRun; } }
cocoon/auto_submit/lib/validations/validation_filter.dart/0
{'file_path': 'cocoon/auto_submit/lib/validations/validation_filter.dart', 'repo_id': 'cocoon', 'token_count': 871}
include: ../../analysis_options.yaml
cocoon/cipd_packages/codesign/analysis_options.yaml/0
{'file_path': 'cocoon/cipd_packages/codesign/analysis_options.yaml', 'repo_id': 'cocoon', 'token_count': 12}
// Copyright 2019 The Flutter Authors. 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:flutter/material.dart'; import 'logic/links.dart'; /// Sidebar for navigating the different pages of Cocoon. class DashboardNavigationDrawer extends StatelessWidget { const DashboardNavigationDrawer({super.key}); @override Widget build(BuildContext context) { final List<CocoonLink> cocoonLinks = createCocoonLinks(context); final String? currentRoute = ModalRoute.of(context)!.settings.name; return Drawer( child: ListView( children: <Widget>[ const DrawerHeader( decoration: FlutterLogoDecoration( margin: EdgeInsets.only(bottom: 24.0), ), child: Align( alignment: Alignment.bottomCenter, child: Text('Flutter Build Dashboard — Cocoon'), ), ), ...cocoonLinks.map( (CocoonLink link) => ListTile( leading: link.icon, title: Text(link.name!), onTap: link.action, selected: currentRoute == link.route, ), ), const AboutListTile( icon: FlutterLogo(), ), ], ), ); } }
cocoon/dashboard/lib/dashboard_navigation_drawer.dart/0
{'file_path': 'cocoon/dashboard/lib/dashboard_navigation_drawer.dart', 'repo_id': 'cocoon', 'token_count': 592}
// Copyright 2023 The Flutter Authors. 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:wiki_visualizer/dot.dart'; import 'package:wiki_visualizer/wiki_page.dart'; void main(final List<String> arguments) { if (arguments.isEmpty) { print('Usage: dart run wiki_visualizer file1.md file2.md file3.md ...'); print('Paths should be relative to the root of the wiki.'); exit(1); } final Wiki wiki = Wiki('https://github.com/flutter/flutter/wiki/'); arguments.forEach(wiki.pageForFilename); for (final WikiPage page in wiki.pages) { page.parse(wiki); } final WikiPage sidebar = wiki.pageForTitle('_Sidebar'); final Set<WikiPage> accessibleContent = sidebar.findAllAccessible(); print('strict digraph {'); final StringBuffer attributes = StringBuffer(); for (final WikiPage page in wiki.pages) { if (page.sources.isEmpty) { attributes.write(' [style=filled] [fillcolor="#FFCCCC"] [fontcolor=black]'); } else if (!accessibleContent.contains(page)) { attributes.write(' [color="#FF0000"]'); } else if (page.sources.contains(sidebar)) { attributes.write(' [style=filled] [fillcolor="#CCFFCC"] [fontcolor=black]'); } if (!page.parsed) { attributes.write(' [fontcolor=silver]'); } print(' ${dotIdentifier(page.title)}$attributes'); for (final WikiPage target in page.targets) { print(' ${dotIdentifier(page.title)} -> ${dotIdentifier(target.title)}'); } attributes.clear(); } print('}'); }
cocoon/dev/wiki-visualizer/bin/wiki_visualizer.dart/0
{'file_path': 'cocoon/dev/wiki-visualizer/bin/wiki_visualizer.dart', 'repo_id': 'cocoon', 'token_count': 558}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. library buildbucket; export 'src/generated/go.chromium.org/luci/buildbucket/proto/build.pb.dart' show Build, BuildInfra, BuildInfra_BBAgent, BuildInfra_BBAgent_Input, BuildInfra_BBAgent_Input_CIPDPackage, BuildInfra_Backend, BuildInfra_Buildbucket, BuildInfra_Buildbucket_Agent, BuildInfra_Buildbucket_Agent_Input, BuildInfra_Buildbucket_Agent_Output, BuildInfra_Buildbucket_Agent_Purpose, BuildInfra_Buildbucket_Agent_Source, BuildInfra_Buildbucket_Agent_Source_CIPD, BuildInfra_Buildbucket_ExperimentReason, BuildInfra_LogDog, BuildInfra_Recipe, BuildInfra_ResultDB, BuildInfra_Swarming, BuildInfra_Swarming_CacheEntry, Build_BuilderInfo, Build_Input, Build_Output, BuildInfra_Buildbucket_Agent_Source_DataType; export 'src/generated/go.chromium.org/luci/buildbucket/proto/builds_service.pb.dart' show GetBuildRequest, SearchBuildsRequest, SearchBuildsResponse, BatchRequest, BatchRequest_Request, BatchResponse, BatchResponse_Response, BatchRequest_Request_Request, BatchResponse_Response_Response, UpdateBuildRequest, ScheduleBuildRequest, ScheduleBuildRequest_ShadowInput, ScheduleBuildRequest_Swarming, StartBuildRequest, StartBuildResponse, StartBuildTaskRequest, StartBuildTaskResponse, CancelBuildRequest, CreateBuildRequest, SynthesizeBuildRequest, BuildMask, BuildPredicate, BuildRange, GetBuildStatusRequest; export 'src/generated/go.chromium.org/luci/buildbucket/proto/builder_service.pb.dart' show GetBuilderRequest, ListBuildersRequest, ListBuildersResponse; export 'src/generated/go.chromium.org/luci/buildbucket/proto/task.pb.dart' show Task, TaskID; export 'src/generated/go.chromium.org/luci/buildbucket/proto/builder_common.pb.dart' show BuilderID; export 'src/generated/go.chromium.org/luci/buildbucket/proto/common.pb.dart' show Status, StatusDetails, StatusDetails_ResourceExhaustion, StatusDetails_Timeout, StringPair, RequestedDimension, Trinary, TimeRange, Compression, HealthStatus, CacheEntry, GitilesCommit, GerritChange, Executable; export 'src/generated/go.chromium.org/luci/buildbucket/proto/common.pbenum.dart'; export 'src/generated/go.chromium.org/luci/buildbucket/proto/notification.pb.dart' show NotificationConfig, BuildsV2PubSub, PubSubCallBack;
cocoon/packages/buildbucket-dart/lib/buildbucket_pb.dart/0
{'file_path': 'cocoon/packages/buildbucket-dart/lib/buildbucket_pb.dart', 'repo_id': 'cocoon', 'token_count': 1239}
// // Generated code. Do not modify. // source: google/rpc/status.proto // // @dart = 2.12 // ignore_for_file: annotate_overrides, camel_case_types // ignore_for_file: constant_identifier_names, library_prefixes // ignore_for_file: non_constant_identifier_names, prefer_final_fields // ignore_for_file: unnecessary_import, unnecessary_this, unused_import
cocoon/packages/buildbucket-dart/lib/src/generated/google/rpc/status.pbenum.dart/0
{'file_path': 'cocoon/packages/buildbucket-dart/lib/src/generated/google/rpc/status.pbenum.dart', 'repo_id': 'cocoon', 'token_count': 120}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'class.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** // ignore_for_file: always_put_control_body_on_new_line // ignore_for_file: annotate_overrides // ignore_for_file: avoid_annotating_with_dynamic // ignore_for_file: avoid_catches_without_on_clauses // ignore_for_file: avoid_returning_this // ignore_for_file: lines_longer_than_80_chars // ignore_for_file: omit_local_variable_types // ignore_for_file: prefer_expression_function_bodies // ignore_for_file: sort_constructors_first class _$Class extends Class { @override final bool abstract; @override final BuiltList<Expression> annotations; @override final BuiltList<String> docs; @override final Reference extend; @override final BuiltList<Reference> implements; @override final BuiltList<Reference> mixins; @override final BuiltList<Reference> types; @override final BuiltList<Constructor> constructors; @override final BuiltList<Method> methods; @override final BuiltList<Field> fields; @override final String name; factory _$Class([void updates(ClassBuilder b)]) => (new ClassBuilder()..update(updates)).build() as _$Class; _$Class._( {this.abstract, this.annotations, this.docs, this.extend, this.implements, this.mixins, this.types, this.constructors, this.methods, this.fields, this.name}) : super._() { if (abstract == null) throw new BuiltValueNullFieldError('Class', 'abstract'); if (annotations == null) throw new BuiltValueNullFieldError('Class', 'annotations'); if (docs == null) throw new BuiltValueNullFieldError('Class', 'docs'); if (implements == null) throw new BuiltValueNullFieldError('Class', 'implements'); if (mixins == null) throw new BuiltValueNullFieldError('Class', 'mixins'); if (types == null) throw new BuiltValueNullFieldError('Class', 'types'); if (constructors == null) throw new BuiltValueNullFieldError('Class', 'constructors'); if (methods == null) throw new BuiltValueNullFieldError('Class', 'methods'); if (fields == null) throw new BuiltValueNullFieldError('Class', 'fields'); if (name == null) throw new BuiltValueNullFieldError('Class', 'name'); } @override Class rebuild(void updates(ClassBuilder b)) => (toBuilder()..update(updates)).build(); @override _$ClassBuilder toBuilder() => new _$ClassBuilder()..replace(this); @override bool operator ==(dynamic other) { if (identical(other, this)) return true; if (other is! Class) return false; return abstract == other.abstract && annotations == other.annotations && docs == other.docs && extend == other.extend && implements == other.implements && mixins == other.mixins && types == other.types && constructors == other.constructors && methods == other.methods && fields == other.fields && name == other.name; } @override int get hashCode { return $jf($jc( $jc( $jc( $jc( $jc( $jc( $jc( $jc( $jc( $jc($jc(0, abstract.hashCode), annotations.hashCode), docs.hashCode), extend.hashCode), implements.hashCode), mixins.hashCode), types.hashCode), constructors.hashCode), methods.hashCode), fields.hashCode), name.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('Class') ..add('abstract', abstract) ..add('annotations', annotations) ..add('docs', docs) ..add('extend', extend) ..add('implements', implements) ..add('mixins', mixins) ..add('types', types) ..add('constructors', constructors) ..add('methods', methods) ..add('fields', fields) ..add('name', name)) .toString(); } } class _$ClassBuilder extends ClassBuilder { _$Class _$v; @override bool get abstract { _$this; return super.abstract; } @override set abstract(bool abstract) { _$this; super.abstract = abstract; } @override ListBuilder<Expression> get annotations { _$this; return super.annotations ??= new ListBuilder<Expression>(); } @override set annotations(ListBuilder<Expression> annotations) { _$this; super.annotations = annotations; } @override ListBuilder<String> get docs { _$this; return super.docs ??= new ListBuilder<String>(); } @override set docs(ListBuilder<String> docs) { _$this; super.docs = docs; } @override Reference get extend { _$this; return super.extend; } @override set extend(Reference extend) { _$this; super.extend = extend; } @override ListBuilder<Reference> get implements { _$this; return super.implements ??= new ListBuilder<Reference>(); } @override set implements(ListBuilder<Reference> implements) { _$this; super.implements = implements; } @override ListBuilder<Reference> get mixins { _$this; return super.mixins ??= new ListBuilder<Reference>(); } @override set mixins(ListBuilder<Reference> mixins) { _$this; super.mixins = mixins; } @override ListBuilder<Reference> get types { _$this; return super.types ??= new ListBuilder<Reference>(); } @override set types(ListBuilder<Reference> types) { _$this; super.types = types; } @override ListBuilder<Constructor> get constructors { _$this; return super.constructors ??= new ListBuilder<Constructor>(); } @override set constructors(ListBuilder<Constructor> constructors) { _$this; super.constructors = constructors; } @override ListBuilder<Method> get methods { _$this; return super.methods ??= new ListBuilder<Method>(); } @override set methods(ListBuilder<Method> methods) { _$this; super.methods = methods; } @override ListBuilder<Field> get fields { _$this; return super.fields ??= new ListBuilder<Field>(); } @override set fields(ListBuilder<Field> fields) { _$this; super.fields = fields; } @override String get name { _$this; return super.name; } @override set name(String name) { _$this; super.name = name; } _$ClassBuilder() : super._(); ClassBuilder get _$this { if (_$v != null) { super.abstract = _$v.abstract; super.annotations = _$v.annotations?.toBuilder(); super.docs = _$v.docs?.toBuilder(); super.extend = _$v.extend; super.implements = _$v.implements?.toBuilder(); super.mixins = _$v.mixins?.toBuilder(); super.types = _$v.types?.toBuilder(); super.constructors = _$v.constructors?.toBuilder(); super.methods = _$v.methods?.toBuilder(); super.fields = _$v.fields?.toBuilder(); super.name = _$v.name; _$v = null; } return this; } @override void replace(Class other) { if (other == null) throw new ArgumentError.notNull('other'); _$v = other as _$Class; } @override void update(void updates(ClassBuilder b)) { if (updates != null) updates(this); } @override _$Class build() { _$Class _$result; try { _$result = _$v ?? new _$Class._( abstract: abstract, annotations: annotations.build(), docs: docs.build(), extend: extend, implements: implements.build(), mixins: mixins.build(), types: types.build(), constructors: constructors.build(), methods: methods.build(), fields: fields.build(), name: name); } catch (_) { String _$failedField; try { _$failedField = 'annotations'; annotations.build(); _$failedField = 'docs'; docs.build(); _$failedField = 'implements'; implements.build(); _$failedField = 'mixins'; mixins.build(); _$failedField = 'types'; types.build(); _$failedField = 'constructors'; constructors.build(); _$failedField = 'methods'; methods.build(); _$failedField = 'fields'; fields.build(); } catch (e) { throw new BuiltValueNestedFieldError( 'Class', _$failedField, e.toString()); } rethrow; } replace(_$result); return _$result; } }
code_builder/lib/src/specs/class.g.dart/0
{'file_path': 'code_builder/lib/src/specs/class.g.dart', 'repo_id': 'code_builder', 'token_count': 3823}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'library.dart'; // ************************************************************************** // BuiltValueGenerator // ************************************************************************** // ignore_for_file: always_put_control_body_on_new_line // ignore_for_file: annotate_overrides // ignore_for_file: avoid_annotating_with_dynamic // ignore_for_file: avoid_catches_without_on_clauses // ignore_for_file: avoid_returning_this // ignore_for_file: lines_longer_than_80_chars // ignore_for_file: omit_local_variable_types // ignore_for_file: prefer_expression_function_bodies // ignore_for_file: sort_constructors_first class _$Library extends Library { @override final BuiltList<Directive> directives; @override final BuiltList<Spec> body; factory _$Library([void updates(LibraryBuilder b)]) => (new LibraryBuilder()..update(updates)).build() as _$Library; _$Library._({this.directives, this.body}) : super._() { if (directives == null) throw new BuiltValueNullFieldError('Library', 'directives'); if (body == null) throw new BuiltValueNullFieldError('Library', 'body'); } @override Library rebuild(void updates(LibraryBuilder b)) => (toBuilder()..update(updates)).build(); @override _$LibraryBuilder toBuilder() => new _$LibraryBuilder()..replace(this); @override bool operator ==(dynamic other) { if (identical(other, this)) return true; if (other is! Library) return false; return directives == other.directives && body == other.body; } @override int get hashCode { return $jf($jc($jc(0, directives.hashCode), body.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('Library') ..add('directives', directives) ..add('body', body)) .toString(); } } class _$LibraryBuilder extends LibraryBuilder { _$Library _$v; @override ListBuilder<Directive> get directives { _$this; return super.directives ??= new ListBuilder<Directive>(); } @override set directives(ListBuilder<Directive> directives) { _$this; super.directives = directives; } @override ListBuilder<Spec> get body { _$this; return super.body ??= new ListBuilder<Spec>(); } @override set body(ListBuilder<Spec> body) { _$this; super.body = body; } _$LibraryBuilder() : super._(); LibraryBuilder get _$this { if (_$v != null) { super.directives = _$v.directives?.toBuilder(); super.body = _$v.body?.toBuilder(); _$v = null; } return this; } @override void replace(Library other) { if (other == null) throw new ArgumentError.notNull('other'); _$v = other as _$Library; } @override void update(void updates(LibraryBuilder b)) { if (updates != null) updates(this); } @override _$Library build() { _$Library _$result; try { _$result = _$v ?? new _$Library._(directives: directives.build(), body: body.build()); } catch (_) { String _$failedField; try { _$failedField = 'directives'; directives.build(); _$failedField = 'body'; body.build(); } catch (e) { throw new BuiltValueNestedFieldError( 'Library', _$failedField, e.toString()); } rethrow; } replace(_$result); return _$result; } }
code_builder/lib/src/specs/library.g.dart/0
{'file_path': 'code_builder/lib/src/specs/library.g.dart', 'repo_id': 'code_builder', 'token_count': 1235}
// 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:code_builder/code_builder.dart'; import 'package:test/test.dart'; import '../common.dart'; void main() { useDartfmt(); test('should create a field', () { expect( Field((b) => b..name = 'foo'), equalsDart(r''' var foo; '''), ); }); test('should create a typed field', () { expect( Field((b) => b ..name = 'foo' ..type = refer('String')), equalsDart(r''' String foo; '''), ); }); test('should create a final field', () { expect( Field((b) => b ..name = 'foo' ..modifier = FieldModifier.final$), equalsDart(r''' final foo; '''), ); }); test('should create a constant field', () { expect( Field((b) => b ..name = 'foo' ..modifier = FieldModifier.constant), equalsDart(r''' const foo; '''), ); }); test('should create a field with an assignment', () { expect( Field((b) => b ..name = 'foo' ..assignment = const Code('1')), equalsDart(r''' var foo = 1; '''), ); }); }
code_builder/test/specs/field_test.dart/0
{'file_path': 'code_builder/test/specs/field_test.dart', 'repo_id': 'code_builder', 'token_count': 602}
version: 2 enable-beta-ecosystems: true updates: # Github actions ecosystem. - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" labels: - "autosubmit" # Pip ecosystem. - package-ecosystem: "pip" directory: "/tfagents-flutter/" schedule: interval: "daily" labels: - "autosubmit" # Pub ecosystem. - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/adaptive_app/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/animated-responsive-layout/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/boring_to_beautiful/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/cupertino_store/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/dart-patterns-and-records/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/dartpad_codelabs/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/deeplink_cookbook/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/ffigen_codelab/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/firebase-auth-flutterfire-ui/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/flame-building-doodle-dash/finished_game/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/flame-building-doodle-dash/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/github-client/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/google-maps-in-flutter/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/haiku_generator/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/homescreen_codelab/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/in_app_purchases/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/namer/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/next-gen-ui/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/star_counter/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/testing_codelab/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/tfagents-flutter/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/tfrs-flutter/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/tfserving-flutter/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/tooling/" schedule: interval: "daily" labels: - "autosubmit" - package-ecosystem: "pub" versioning-strategy: "increase-if-necessary" directory: "/webview_flutter/" schedule: interval: "daily" labels: - "autosubmit"
codelabs/.github/dependabot.yaml/0
{'file_path': 'codelabs/.github/dependabot.yaml', 'repo_id': 'codelabs', 'token_count': 2157}
include: ../../analysis_options.yaml
codelabs/brick_breaker/step_05/analysis_options.yaml/0
{'file_path': 'codelabs/brick_breaker/step_05/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 12}
import 'package:flutter/material.dart'; class ScoreCard extends StatelessWidget { const ScoreCard({ super.key, required this.score, }); final ValueNotifier<int> score; @override Widget build(BuildContext context) { return ValueListenableBuilder<int>( valueListenable: score, builder: (context, score, child) { return Padding( padding: const EdgeInsets.fromLTRB(12, 6, 12, 18), child: Text( 'Score: $score'.toUpperCase(), style: Theme.of(context).textTheme.titleLarge!, ), ); }, ); } }
codelabs/brick_breaker/step_10/lib/src/widgets/score_card.dart/0
{'file_path': 'codelabs/brick_breaker/step_10/lib/src/widgets/score_card.dart', 'repo_id': 'codelabs', 'token_count': 258}
// ignore_for_file: prefer_const_constructors, use_key_in_widget_constructors import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: Scaffold( body: ListView.builder( itemCount: 500, padding: EdgeInsets.all(10), // Replace custom ListItem with a Material Design ListTile. Then, wrap // it in a Material Design Card! itemBuilder: (context, index) => ListItem(index: index), ), ), ), ); } class ListItem extends StatelessWidget { const ListItem({ super.key, required this.index, }); final int index; @override Widget build(BuildContext context) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( 'Item $index', style: TextStyle(fontWeight: FontWeight.bold), ), Text('Subtitle', style: TextStyle(color: Colors.grey)) ], ); } }
codelabs/dartpad_codelabs/src/introduction_to_lists/material_widgets/snippet.dart/0
{'file_path': 'codelabs/dartpad_codelabs/src/introduction_to_lists/material_widgets/snippet.dart', 'repo_id': 'codelabs', 'token_count': 405}
// TODO: Remove the following line // ignore_for_file: argument_type_not_assignable import 'dart:math'; class StringProvider { String? value = 'A String!'; } class RandomStringProvider extends StringProvider { @override set value(String? v) {} @override String? get value => Random().nextBool() ? 'A String!' : null; } void printString(String str) => print(str); void main() { StringProvider provider = RandomStringProvider(); if (provider.value == null) { print('The value is null.'); return; } printString(provider.value); }
codelabs/dartpad_codelabs/src/null_safety_workshop/step_10/snippet.dart/0
{'file_path': 'codelabs/dartpad_codelabs/src/null_safety_workshop/step_10/snippet.dart', 'repo_id': 'codelabs', 'token_count': 182}
import 'package:firebase_auth/firebase_auth.dart' hide EmailAuthProvider; import 'package:firebase_ui_auth/firebase_ui_auth.dart'; import 'package:firebase_ui_oauth_google/firebase_ui_oauth_google.dart'; import 'package:flutter/material.dart'; import 'home.dart'; import 'main.dart'; class AuthGate extends StatelessWidget { const AuthGate({super.key}); @override Widget build(BuildContext context) { return StreamBuilder<User?>( stream: FirebaseAuth.instance.authStateChanges(), builder: (context, snapshot) { if (!snapshot.hasData) { return SignInScreen( providers: [ EmailAuthProvider(), GoogleProvider(clientId: clientId), ], headerBuilder: (context, constraints, shrinkOffset) { return Padding( padding: const EdgeInsets.all(20), child: AspectRatio( aspectRatio: 1, child: Image.asset('assets/flutterfire_300x.png'), ), ); }, subtitleBuilder: (context, action) { return Padding( padding: const EdgeInsets.symmetric(vertical: 8.0), child: action == AuthAction.signIn ? const Text('Welcome to FlutterFire, please sign in!') : const Text('Welcome to Flutterfire, please sign up!'), ); }, footerBuilder: (context, action) { return const Padding( padding: EdgeInsets.only(top: 16), child: Text( 'By signing in, you agree to our terms and conditions.', style: TextStyle(color: Colors.grey), ), ); }, ); } return const HomeScreen(); }, ); } }
codelabs/firebase-auth-flutterfire-ui/complete/lib/auth_gate.dart/0
{'file_path': 'codelabs/firebase-auth-flutterfire-ui/complete/lib/auth_gate.dart', 'repo_id': 'codelabs', 'token_count': 921}
// File generated by FlutterFire CLI. // ignore_for_file: lines_longer_than_80_chars import 'package:firebase_core/firebase_core.dart' show FirebaseOptions; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; /// Default [FirebaseOptions] for use with your Firebase apps. /// /// Example: /// ```dart /// import 'firebase_options.dart'; /// // ... /// await Firebase.initializeApp( /// options: DefaultFirebaseOptions.currentPlatform, /// ); /// ``` class DefaultFirebaseOptions { static FirebaseOptions get currentPlatform { if (kIsWeb) { return web; } switch (defaultTargetPlatform) { case TargetPlatform.android: return android; case TargetPlatform.iOS: return ios; case TargetPlatform.macOS: return macos; default: throw UnsupportedError( 'DefaultFirebaseOptions are not supported for this platform.'); } } // TODO (codelab user): Replace with your Firebase credentials // Generate this file with credentials with the FlutterFire CLI static const FirebaseOptions web = FirebaseOptions( apiKey: 'YOUR API KEY', appId: 'YOUR APP ID', messagingSenderId: '', projectId: 'flutterfire-ui-codelab', authDomain: 'flutterfire-ui-codelab.firebaseapp.com', storageBucket: 'flutterfire-ui-codelab.appspot.com', measurementId: 'MEASUREMENT ID', ); static const FirebaseOptions android = FirebaseOptions( apiKey: 'YOUR API KEY', appId: 'YOUR APP ID', messagingSenderId: '', projectId: 'flutterfire-ui-codelab', storageBucket: 'flutterfire-ui-codelab.appspot.com', ); static const FirebaseOptions ios = FirebaseOptions( apiKey: 'YOUR API KEY', appId: 'YOUR APP ID', messagingSenderId: '', projectId: 'flutterfire-ui-codelab', storageBucket: 'flutterfire-ui-codelab.appspot.com', iosClientId: 'IOS CLIENT ID', iosBundleId: 'com.example.BUNDLE', ); static const FirebaseOptions macos = FirebaseOptions( apiKey: 'YOUR API KEY', appId: 'YOUR APP ID', messagingSenderId: '', projectId: 'flutterfire-ui-codelab', storageBucket: 'flutterfire-ui-codelab.appspot.com', iosClientId: 'IOS CLIENT ID', iosBundleId: 'com.example.BUNDLE', ); }
codelabs/firebase-auth-flutterfire-ui/start/lib/firebase_options.dart/0
{'file_path': 'codelabs/firebase-auth-flutterfire-ui/start/lib/firebase_options.dart', 'repo_id': 'codelabs', 'token_count': 860}
include: ../../analysis_options.yaml
codelabs/firebase-get-to-know-flutter/step_06/analysis_options.yaml/0
{'file_path': 'codelabs/firebase-get-to-know-flutter/step_06/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 12}
enum ProductStatus { purchasable, purchased, pending, } class PurchasableProduct { final String title; final String description; final String price; ProductStatus status; PurchasableProduct(this.title, this.description, this.price) : status = ProductStatus.purchasable; }
codelabs/in_app_purchases/step_00/app/lib/model/purchasable_product.dart/0
{'file_path': 'codelabs/in_app_purchases/step_00/app/lib/model/purchasable_product.dart', 'repo_id': 'codelabs', 'token_count': 91}
include: ../../analysis_options.yaml
codelabs/testing_codelab/step_03/analysis_options.yaml/0
{'file_path': 'codelabs/testing_codelab/step_03/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 12}
// Copyright 2020 The Flutter Authors. 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:flutter_driver/flutter_driver.dart' as driver; import 'package:integration_test/integration_test_driver.dart'; Future<void> main() { return integrationDriver( responseDataCallback: (data) async { if (data != null) { final timeline = driver.Timeline.fromJson( data['scrolling_summary'] as Map<String, dynamic>); final summary = driver.TimelineSummary.summarize(timeline); await summary.writeTimelineToFile( 'scrolling_summary', pretty: true, includeSummary: true, ); } }, ); }
codelabs/testing_codelab/step_08/test_driver/perf_driver.dart/0
{'file_path': 'codelabs/testing_codelab/step_08/test_driver/perf_driver.dart', 'repo_id': 'codelabs', 'token_count': 283}
include: ../../analysis_options.yaml
codelabs/webview_flutter/step_04/analysis_options.yaml/0
{'file_path': 'codelabs/webview_flutter/step_04/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 12}
include: ../../analysis_options.yaml
codelabs/webview_flutter/step_05/analysis_options.yaml/0
{'file_path': 'codelabs/webview_flutter/step_05/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 12}
// Copyright 2022 The Flutter Authors. 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:flutter/material.dart'; import 'package:path_provider/path_provider.dart'; import 'package:webview_flutter/webview_flutter.dart'; const String kExamplePage = ''' <!DOCTYPE html> <html lang="en"> <head> <title>Load file or HTML string example</title> </head> <body> <h1>Local demo page</h1> <p> This is an example page used to demonstrate how to load a local file or HTML string using the <a href="https://pub.dev/packages/webview_flutter">Flutter webview</a> plugin. </p> </body> </html> '''; enum _MenuOptions { navigationDelegate, userAgent, javascriptChannel, listCookies, clearCookies, addCookie, setCookie, removeCookie, loadFlutterAsset, loadLocalFile, loadHtmlString, } class Menu extends StatefulWidget { const Menu({required this.controller, super.key}); final WebViewController controller; @override State<Menu> createState() => _MenuState(); } class _MenuState extends State<Menu> { final cookieManager = WebViewCookieManager(); @override Widget build(BuildContext context) { return PopupMenuButton<_MenuOptions>( onSelected: (value) async { switch (value) { case _MenuOptions.navigationDelegate: await widget.controller .loadRequest(Uri.parse('https://youtube.com')); case _MenuOptions.userAgent: final userAgent = await widget.controller .runJavaScriptReturningResult('navigator.userAgent'); if (!context.mounted) return; ScaffoldMessenger.of(context).showSnackBar(SnackBar( content: Text('$userAgent'), )); case _MenuOptions.javascriptChannel: await widget.controller.runJavaScript(''' var req = new XMLHttpRequest(); req.open('GET', "https://api.ipify.org/?format=json"); req.onload = function() { if (req.status == 200) { let response = JSON.parse(req.responseText); SnackBar.postMessage("IP Address: " + response.ip); } else { SnackBar.postMessage("Error: " + req.status); } } req.send();'''); case _MenuOptions.clearCookies: await _onClearCookies(); case _MenuOptions.listCookies: await _onListCookies(widget.controller); case _MenuOptions.addCookie: await _onAddCookie(widget.controller); case _MenuOptions.setCookie: await _onSetCookie(widget.controller); case _MenuOptions.removeCookie: await _onRemoveCookie(widget.controller); case _MenuOptions.loadFlutterAsset: if (!mounted) return; await _onLoadFlutterAssetExample(widget.controller, context); case _MenuOptions.loadLocalFile: if (!mounted) return; await _onLoadLocalFileExample(widget.controller, context); case _MenuOptions.loadHtmlString: if (!mounted) return; await _onLoadHtmlStringExample(widget.controller, context); } }, itemBuilder: (context) => [ const PopupMenuItem<_MenuOptions>( value: _MenuOptions.navigationDelegate, child: Text('Navigate to YouTube'), ), const PopupMenuItem<_MenuOptions>( value: _MenuOptions.userAgent, child: Text('Show user-agent'), ), const PopupMenuItem<_MenuOptions>( value: _MenuOptions.javascriptChannel, child: Text('Lookup IP Address'), ), const PopupMenuItem<_MenuOptions>( value: _MenuOptions.clearCookies, child: Text('Clear cookies'), ), const PopupMenuItem<_MenuOptions>( value: _MenuOptions.listCookies, child: Text('List cookies'), ), const PopupMenuItem<_MenuOptions>( value: _MenuOptions.addCookie, child: Text('Add cookie'), ), const PopupMenuItem<_MenuOptions>( value: _MenuOptions.setCookie, child: Text('Set cookie'), ), const PopupMenuItem<_MenuOptions>( value: _MenuOptions.removeCookie, child: Text('Remove cookie'), ), const PopupMenuItem<_MenuOptions>( value: _MenuOptions.loadFlutterAsset, child: Text('Load Flutter Asset'), ), const PopupMenuItem<_MenuOptions>( value: _MenuOptions.loadHtmlString, child: Text('Load HTML string'), ), const PopupMenuItem<_MenuOptions>( value: _MenuOptions.loadLocalFile, child: Text('Load local file'), ), ], ); } Future<void> _onListCookies(WebViewController controller) async { final String cookies = await controller .runJavaScriptReturningResult('document.cookie') as String; if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(cookies.isNotEmpty ? cookies : 'There are no cookies.'), ), ); } Future<void> _onClearCookies() async { final hadCookies = await cookieManager.clearCookies(); String message = 'There were cookies. Now, they are gone!'; if (!hadCookies) { message = 'There were no cookies to clear.'; } if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(message), ), ); } Future<void> _onAddCookie(WebViewController controller) async { await controller.runJavaScript('''var date = new Date(); date.setTime(date.getTime()+(30*24*60*60*1000)); document.cookie = "FirstName=John; expires=" + date.toGMTString();'''); if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Custom cookie added.'), ), ); } Future<void> _onSetCookie(WebViewController controller) async { await cookieManager.setCookie( const WebViewCookie(name: 'foo', value: 'bar', domain: 'flutter.dev'), ); if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Custom cookie is set.'), ), ); } Future<void> _onRemoveCookie(WebViewController controller) async { await controller.runJavaScript( 'document.cookie="FirstName=John; expires=Thu, 01 Jan 1970 00:00:00 UTC" '); if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Custom cookie removed.'), ), ); } Future<void> _onLoadFlutterAssetExample( WebViewController controller, BuildContext context) async { await controller.loadFlutterAsset('assets/www/index.html'); } Future<void> _onLoadLocalFileExample( WebViewController controller, BuildContext context) async { final String pathToIndex = await _prepareLocalFile(); await controller.loadFile(pathToIndex); } static Future<String> _prepareLocalFile() async { final String tmpDir = (await getTemporaryDirectory()).path; final File indexFile = File('$tmpDir/www/index.html'); await Directory('$tmpDir/www').create(recursive: true); await indexFile.writeAsString(kExamplePage); return indexFile.path; } Future<void> _onLoadHtmlStringExample( WebViewController controller, BuildContext context) async { await controller.loadHtmlString(kExamplePage); } }
codelabs/webview_flutter/step_12/lib/src/menu.dart/0
{'file_path': 'codelabs/webview_flutter/step_12/lib/src/menu.dart', 'repo_id': 'codelabs', 'token_count': 2985}
export 'package:flutter_hooks/src/hook_widget.dart';
coverage_issue_reproduction/lib/flutter_hooks.dart/0
{'file_path': 'coverage_issue_reproduction/lib/flutter_hooks.dart', 'repo_id': 'coverage_issue_reproduction', 'token_count': 20}
github: [felangel]
cubit/.github/FUNDING.yml/0
{'file_path': 'cubit/.github/FUNDING.yml', 'repo_id': 'cubit', 'token_count': 8}
name: angular_counter description: A web app that uses angular_cubit environment: sdk: ">=2.7.0 <3.0.0" dependencies: angular: ^6.0.0-alpha+1 angular_cubit: path: ../../packages/angular_cubit dev_dependencies: build_runner: ^1.6.0 build_web_compilers: ^2.3.0
cubit/examples/angular_counter/pubspec.yaml/0
{'file_path': 'cubit/examples/angular_counter/pubspec.yaml', 'repo_id': 'cubit', 'token_count': 120}
name: flutter_weather description: A new Flutter project. version: 1.0.0+1 environment: sdk: ">=2.7.0 <3.0.0" dependencies: flutter: sdk: flutter cubit: ^0.0.8 flutter_cubit: ^0.0.10 google_fonts: ^1.1.0 http: ^0.12.1 json_annotation: ^3.0.1 dev_dependencies: flutter_test: sdk: flutter build_runner: ^1.8.1 cubit_test: ^0.0.5 json_serializable: ^3.3.0 matcher: ^0.12.6 mockito: ^4.0.0 flutter: uses-material-design: true
cubit/examples/flutter_weather/pubspec.yaml/0
{'file_path': 'cubit/examples/flutter_weather/pubspec.yaml', 'repo_id': 'cubit', 'token_count': 229}
import 'dart:async'; import 'package:angular/core.dart' show ChangeDetectorRef, OnDestroy, Pipe, PipeTransform; import 'package:cubit/cubit.dart'; /// {@template cubitpipe} /// A `pipe` which helps bind [Cubit] state changes to the presentation layer. /// [CubitPipe] handles rendering the html element in response to new states. /// [CubitPipe] is very similar to `AsyncPipe` but has simplified API /// to reduce the amount of boilerplate code needed. /// {@endtemplate} @Pipe('cubit', pure: false) class CubitPipe implements OnDestroy, PipeTransform { /// {@macro cubitpipe} CubitPipe(this._ref); final ChangeDetectorRef _ref; CubitStream _cubit; Object _latestValue; StreamSubscription _subscription; @override void ngOnDestroy() { if (_subscription != null) { _dispose(); } } /// Angular invokes the [transform] method with the value of a binding as the /// first argument, and any parameters as the second argument in list form. dynamic transform(CubitStream cubit) { if (_cubit == null) { if (cubit != null) { _subscribe(cubit); } } else if (!_maybeStreamIdentical(cubit, _cubit)) { _dispose(); return transform(cubit); } if (cubit == null) { return null; } return _latestValue ?? cubit.state; } void _subscribe(CubitStream cubit) { _cubit = cubit; _subscription = cubit.listen( (dynamic value) => _updateLatestValue(cubit, value), onError: (dynamic e) => throw e, ); } void _updateLatestValue(dynamic async, Object value) { if (identical(async, _cubit)) { _latestValue = value; _ref.markForCheck(); } } void _dispose() { _subscription.cancel(); _latestValue = null; _subscription = null; _cubit = null; } // StreamController.stream getter always returns new Stream instance, // operator== check is also needed. See // https://github.com/dart-lang/angular2/issues/260 static bool _maybeStreamIdentical(dynamic a, dynamic b) { if (!identical(a, b)) { return a is Stream && b is Stream && a == b; } return true; } }
cubit/packages/angular_cubit/lib/src/cubit_pipe.dart/0
{'file_path': 'cubit/packages/angular_cubit/lib/src/cubit_pipe.dart', 'repo_id': 'cubit', 'token_count': 790}
import 'package:cubit/cubit.dart'; import 'package:mockito/mockito.dart'; import 'package:test/test.dart'; class MockCubit extends Mock implements Cubit<int> {} // ignore: must_be_immutable class MockTransition extends Mock implements Transition<int> {} void main() { group('CubitObserver', () { group('onTransition', () { test('does nothing by default', () { CubitObserver().onTransition(MockCubit(), MockTransition()); }); }); }); }
cubit/packages/cubit/test/cubit_observer_test.dart/0
{'file_path': 'cubit/packages/cubit/test/cubit_observer_test.dart', 'repo_id': 'cubit', 'token_count': 170}
// ignore_for_file: invalid_use_of_visible_for_testing_member import 'dart:async'; import 'package:mockito/mockito.dart'; /// Extend or mixin this class to mark the implementation as a [MockCubit]. /// /// A mocked cubit implements all fields and methods with a default /// implementation that does not throw a [NoSuchMethodError], /// and may be further customized at runtime to define how it may behave using /// [when] and `whenListen`. /// /// _**Note**: it is critical to explicitly provide the cubit event and state /// types when extending [MockCubit]_. /// /// **GOOD** /// ```dart /// class MockCounterCubit extends MockCubit<CounterEvent, int> /// implements CounterCubit {} /// ``` /// /// **BAD** /// ```dart /// class MockCounterCubit extends MockCubit implements CounterCubit {} /// ``` class MockCubit<S> extends Mock { @override dynamic noSuchMethod(Invocation invocation) { final memberName = invocation.memberName.toString().split('"')[1]; final dynamic result = super.noSuchMethod(invocation); return (memberName == 'skip' && result == null) ? Stream<S>.empty() : result; } }
cubit/packages/cubit_test/lib/src/mock_cubit.dart/0
{'file_path': 'cubit/packages/cubit_test/lib/src/mock_cubit.dart', 'repo_id': 'cubit', 'token_count': 351}
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:mockito/mockito.dart'; import 'package:hydrated_cubit/hydrated_cubit.dart'; import 'package:cubit/cubit.dart'; import 'package:uuid/uuid.dart'; class MockStorage extends Mock implements Storage {} class MyUuidHydratedCubit extends HydratedCubit<String> { MyUuidHydratedCubit() : super(Uuid().v4()); @override Map<String, String> toJson(String state) => {'value': state}; @override String fromJson(dynamic json) => json['value'] as String; } class MyCallbackHydratedCubit extends HydratedCubit<int> { MyCallbackHydratedCubit({this.onFromJsonCalled}) : super(0); final ValueSetter<dynamic> onFromJsonCalled; void increment() => emit(state + 1); @override Map<String, int> toJson(int state) => {'value': state}; @override int fromJson(dynamic json) { onFromJsonCalled?.call(json); return json['value'] as int; } } class MyHydratedCubit extends HydratedCubit<int> { MyHydratedCubit([this._id]) : super(0); final String _id; @override String get id => _id; @override Map<String, int> toJson(int state) => {'value': state}; @override int fromJson(dynamic json) => json['value'] as int; } class MyMultiHydratedCubit extends HydratedCubit<int> { MyMultiHydratedCubit(String id) : _id = id, super(0); final String _id; @override String get id => _id; @override Map<String, int> toJson(int state) => {'value': state}; @override int fromJson(dynamic json) => json['value'] as int; } void main() { TestWidgetsFlutterBinding.ensureInitialized(); group('HydratedCubit', () { Storage storage; setUp(() { storage = MockStorage(); HydratedCubit.storage = storage; }); test('reads from storage once upon initialization', () { MyCallbackHydratedCubit(); verify<dynamic>(storage.read('MyCallbackHydratedCubit')).called(1); }); test( 'does not read from storage on subsequent state changes ' 'when cache value exists', () { when<dynamic>(storage.read('MyCallbackHydratedCubit')).thenReturn( {'value': 42}, ); final cubit = MyCallbackHydratedCubit(); expect(cubit.state, 42); cubit.increment(); expect(cubit.state, 43); verify<dynamic>(storage.read('MyCallbackHydratedCubit')).called(1); }); test( 'does not deserialize state on subsequent state changes ' 'when cache value exists', () { final fromJsonCalls = <dynamic>[]; when<dynamic>(storage.read('MyCallbackHydratedCubit')).thenReturn( {'value': 42}, ); final cubit = MyCallbackHydratedCubit( onFromJsonCalled: fromJsonCalls.add, ); expect(cubit.state, 42); cubit.increment(); expect(cubit.state, 43); expect(fromJsonCalls, [ {'value': 42} ]); }); test( 'does not read from storage on subsequent state changes ' 'when cache is empty', () { when<dynamic>(storage.read('MyCallbackHydratedCubit')).thenReturn(null); final cubit = MyCallbackHydratedCubit(); expect(cubit.state, 0); cubit.increment(); expect(cubit.state, 1); verify<dynamic>(storage.read('MyCallbackHydratedCubit')).called(1); }); test('does not deserialize state when cache is empty', () { final fromJsonCalls = <dynamic>[]; when<dynamic>(storage.read('MyCallbackHydratedCubit')).thenReturn(null); final cubit = MyCallbackHydratedCubit( onFromJsonCalled: fromJsonCalls.add, ); expect(cubit.state, 0); cubit.increment(); expect(cubit.state, 1); expect(fromJsonCalls, isEmpty); }); test( 'does not read from storage on subsequent state changes ' 'when cache is malformed', () { when<dynamic>(storage.read('MyCallbackHydratedCubit')).thenReturn('{'); final cubit = MyCallbackHydratedCubit(); expect(cubit.state, 0); cubit.increment(); expect(cubit.state, 1); verify<dynamic>(storage.read('MyCallbackHydratedCubit')).called(1); }); test('does not deserialize state when cache is malformed', () { final fromJsonCalls = <dynamic>[]; when<dynamic>(storage.read('MyCallbackHydratedCubit')).thenReturn('{'); final cubit = MyCallbackHydratedCubit( onFromJsonCalled: fromJsonCalls.add, ); expect(cubit.state, 0); cubit.increment(); expect(cubit.state, 1); expect(fromJsonCalls, isEmpty); }); group('SingleHydratedCubit', () { test('should throw HydratedStorageNotFound when storage is null', () { HydratedCubit.storage = null; expect( () => MyHydratedCubit(), throwsA(isA<HydratedStorageNotFound>()), ); }); test('HydratedStorageNotFound overrides toString', () { expect( // ignore: prefer_const_constructors HydratedStorageNotFound().toString(), 'HydratedStorage was accessed before it was initialized.\n' 'Please ensure that storage has been initialized.\n\n' 'For example:\n\n' 'HydratedCubit.storage = await HydratedStorage.build();', ); }); test('should call storage.write when onTransition is called', () { final transition = const Transition(currentState: 0, nextState: 0); final expected = <String, int>{'value': 0}; MyHydratedCubit().onTransition(transition); verify(storage.write('MyHydratedCubit', expected)).called(2); }); test( 'should call storage.write when onTransition is called with cubit id', () { final cubit = MyHydratedCubit('A'); final transition = const Transition(currentState: 0, nextState: 0); final expected = <String, int>{'value': 0}; cubit.onTransition(transition); verify(storage.write('MyHydratedCubitA', expected)).called(2); }); test('should do nothing when storage.write throws', () { runZoned(() { final expectedError = Exception('oops'); final transition = const Transition(currentState: 0, nextState: 0); when(storage.write(any, any)).thenThrow(expectedError); MyHydratedCubit().onTransition(transition); }, onError: (dynamic _) => fail('should not throw')); }); test('stores initial state when instantiated', () { MyHydratedCubit(); verify<dynamic>( storage.write('MyHydratedCubit', {'value': 0}), ).called(1); }); test('initial state should return 0 when fromJson returns null', () { when<dynamic>(storage.read('MyHydratedCubit')).thenReturn(null); expect(MyHydratedCubit().state, 0); verify<dynamic>(storage.read('MyHydratedCubit')).called(1); }); test('initial state should return 0 when deserialization fails', () { when<dynamic>(storage.read('MyHydratedCubit')) .thenThrow(Exception('oops')); expect(MyHydratedCubit().state, 0); }); test('initial state should return 101 when fromJson returns 101', () { when<dynamic>(storage.read('MyHydratedCubit')) .thenReturn({'value': 101}); expect(MyHydratedCubit().state, 101); verify<dynamic>(storage.read('MyHydratedCubit')).called(1); }); group('clear', () { test('calls delete on storage', () async { await MyHydratedCubit().clear(); verify(storage.delete('MyHydratedCubit')).called(1); }); }); }); group('MultiHydratedCubit', () { test('initial state should return 0 when fromJson returns null', () { when<dynamic>(storage.read('MyMultiHydratedCubitA')).thenReturn(null); expect(MyMultiHydratedCubit('A').state, 0); verify<dynamic>(storage.read('MyMultiHydratedCubitA')).called(1); when<dynamic>(storage.read('MyMultiHydratedCubitB')).thenReturn(null); expect(MyMultiHydratedCubit('B').state, 0); verify<dynamic>(storage.read('MyMultiHydratedCubitB')).called(1); }); test('initial state should return 101/102 when fromJson returns 101/102', () { when<dynamic>(storage.read('MyMultiHydratedCubitA')) .thenReturn({'value': 101}); expect(MyMultiHydratedCubit('A').state, 101); verify<dynamic>(storage.read('MyMultiHydratedCubitA')).called(1); when<dynamic>(storage.read('MyMultiHydratedCubitB')) .thenReturn({'value': 102}); expect(MyMultiHydratedCubit('B').state, 102); verify<dynamic>(storage.read('MyMultiHydratedCubitB')).called(1); }); group('clear', () { test('calls delete on storage', () async { await MyMultiHydratedCubit('A').clear(); verify(storage.delete('MyMultiHydratedCubitA')).called(1); verifyNever(storage.delete('MyMultiHydratedCubitB')); await MyMultiHydratedCubit('B').clear(); verify(storage.delete('MyMultiHydratedCubitB')).called(1); }); }); }); group('MyUuidHydratedCubit', () { test('stores initialState when instantiated', () { MyUuidHydratedCubit(); verify<dynamic>(storage.write('MyUuidHydratedCubit', any)).called(1); }); test('correctly caches computed initialState', () { dynamic cachedState; when<dynamic>(storage.write('MyUuidHydratedCubit', any)) .thenReturn(null); when<dynamic>(storage.read('MyUuidHydratedCubit')) .thenReturn(cachedState); MyUuidHydratedCubit(); cachedState = verify(storage.write('MyUuidHydratedCubit', captureAny)) .captured .last; when<dynamic>(storage.read('MyUuidHydratedCubit')) .thenReturn(cachedState); MyUuidHydratedCubit(); final dynamic initialStateB = verify(storage.write('MyUuidHydratedCubit', captureAny)) .captured .last; expect(initialStateB, cachedState); }); }); }); }
cubit/packages/hydrated_cubit/test/hydrated_cubit_test.dart/0
{'file_path': 'cubit/packages/hydrated_cubit/test/hydrated_cubit_test.dart', 'repo_id': 'cubit', 'token_count': 4178}
void main(List<String> args) {}
dart-for-beginners-course/003_numbers/main.dart/0
{'file_path': 'dart-for-beginners-course/003_numbers/main.dart', 'repo_id': 'dart-for-beginners-course', 'token_count': 11}
name: dummylib version: 2.0.0 environment: sdk: ">=3.0.0 <4.0.0"
dart-hotreloader/example/dummylib_v2/pubspec.yaml/0
{'file_path': 'dart-hotreloader/example/dummylib_v2/pubspec.yaml', 'repo_id': 'dart-hotreloader', 'token_count': 36}
include: package:lints/recommended.yaml analyzer: errors: deprecated_member_use_from_same_package: ignore
dart-neats/chunked_stream/analysis_options.yaml/0
{'file_path': 'dart-neats/chunked_stream/analysis_options.yaml', 'repo_id': 'dart-neats', 'token_count': 39}
include: package:lints/recommended.yaml
dart-neats/http_methods/analysis_options.yaml/0
{'file_path': 'dart-neats/http_methods/analysis_options.yaml', 'repo_id': 'dart-neats', 'token_count': 13}
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:async'; import 'dart:io' show IOException, Socket, SocketOption; import 'dart:typed_data'; import 'resp.dart'; import 'package:logging/logging.dart'; import '../../cache_provider.dart'; final _log = Logger('neat_cache'); class _RedisContext { final RespClient client; _RedisContext({ required this.client, }); } class RedisCacheProvider extends CacheProvider<List<int>> { final Uri _connectionString; final Duration _connectTimeLimit; final Duration _commandTimeLimit; final Duration _reconnectDelay; Future<_RedisContext>? _context; bool _isClosed = false; RedisCacheProvider( Uri connectionString, { Duration connectTimeLimit = const Duration(seconds: 30), Duration commandTimeLimit = const Duration(milliseconds: 200), Duration reconnectDelay = const Duration(seconds: 30), }) : _connectionString = connectionString, _connectTimeLimit = connectTimeLimit, _commandTimeLimit = commandTimeLimit, _reconnectDelay = reconnectDelay { if (!connectionString.isScheme('redis')) { throw ArgumentError.value( connectionString, 'connectionString', 'must have scheme redis://'); } if (!connectionString.hasEmptyPath) { throw ArgumentError.value( connectionString, 'connectionString', 'cannot have a path'); } if (connectTimeLimit.isNegative) { throw ArgumentError.value( connectTimeLimit, 'connectTimeLimit', 'must be positive'); } if (commandTimeLimit.isNegative) { throw ArgumentError.value( commandTimeLimit, 'commandTimeLimit', 'must be positive'); } if (reconnectDelay.isNegative) { throw ArgumentError.value( reconnectDelay, 'reconnectDelay', 'must be positive'); } } Future<_RedisContext> _createContext() async { try { _log.info('Connecting to redis'); final socket = await Socket.connect( _connectionString.host, _connectionString.port, ).timeout(_connectTimeLimit); socket.setOption(SocketOption.tcpNoDelay, true); // Create context return _RedisContext( client: RespClient(socket, socket), ); } on RedisConnectionException { throw IntermittentCacheException('connection failed'); } on TimeoutException { throw IntermittentCacheException('connect failed with timeout'); } on IOException catch (e) { throw IntermittentCacheException('connect failed with IOException: $e'); } on Exception { throw IntermittentCacheException('connect failed with exception'); } } Future<_RedisContext> _getContext() { if (_context != null) { return _context!; } _context = _createContext(); scheduleMicrotask(() async { _RedisContext ctx; try { ctx = await _context!; } on IntermittentCacheException { // If connecting fails, then we sleep and try again await Future.delayed(_reconnectDelay); _context = null; // reset _context, so next operation creates a new return; } catch (e) { _log.shout('unknown error/exception connecting to redis', e); _context = null; // reset _context, so next operation creates a new rethrow; // propagate the error to crash to application. } // If connecting was successful, then we await the connection being // closed or error, and we reset _context. try { await ctx.client.closed; } catch (e) { // ignore error } _context = null; }); return _context!; } Future<T> _withResp<T>(Future<T> Function(RespClient) fn) async { if (_isClosed) { throw StateError('CacheProvider.closed() has been called'); } final ctx = await _getContext(); try { return await fn(ctx.client).timeout(_commandTimeLimit); } on RedisCommandException catch (e) { throw AssertionError('error from redis command: $e'); } on TimeoutException { // If we had a timeout, doing the command we forcibly disconnect // from the server, such that next retry will use a new connection. await ctx.client.close(force: true); throw IntermittentCacheException('redis command timeout'); } on RedisConnectionException catch (e) { throw IntermittentCacheException('redis error: $e'); } on IOException catch (e) { throw IntermittentCacheException('socket broken: $e'); } } @override Future<void> close() async { _isClosed = true; if (_context != null) { try { final ctx = await _context!; await ctx.client.close(); } catch (e) { // ignore } } } @override Future<List<int>?> get(String key) => _withResp((client) async { final r = await client.command(['GET', key]); if (r == null) { return null; } if (r is Uint8List) { return r; } assert(false, 'unexpected response from redis server'); // Force close the client scheduleMicrotask(() => client.close(force: true)); }); @override Future<void> set(String key, List<int> value, [Duration? ttl]) => _withResp((client) async { final r = await client.command([ 'SET', key, value, if (ttl != null) ...<Object>['EX', ttl.inSeconds], ]); if (r != 'OK') { assert(false, 'unexpected response from redis server'); // Force close the client scheduleMicrotask(() => client.close(force: true)); } }); @override Future<void> purge(String key) => _withResp((client) async { final r = await client.command(['DEL', key]); if (r is! int) { assert(false, 'unexpected response from redis server'); // Force close the client scheduleMicrotask(() => client.close(force: true)); } }); }
dart-neats/neat_cache/lib/src/providers/redis.dart/0
{'file_path': 'dart-neats/neat_cache/lib/src/providers/redis.dart', 'repo_id': 'dart-neats', 'token_count': 2416}
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'dart:convert' show utf8, json; import 'package:json_annotation/json_annotation.dart'; part 'neat_status.g.dart'; /// Status of a NeatPeriodicTask. @JsonSerializable() class NeatTaskStatus { /// Value of the 'format' property. /// /// This value is used to ensure that we're not reading a JSON object that /// isn't a status. static const formatIdentifier = 'neat-periodic-task-status'; /// Latest version of the NeatTaskStatus file. static const currentVersion = 1; /// Magic value that identifies the format, this must always match /// [formatIdentifier] or the status object is ignored. final String format; /// Version of the status object. /// /// If this value is less than [currentVersion] then the object is ignored. /// If this value is greater than [currentVersion] a warning is printed and /// no further action is taken. final int version; /// Current state, one of 'finished', 'running'. final String state; /// Time the task started running. final DateTime started; /// Owner if this status object, only relevant if [state] is 'running'. /// /// The [owner] is a random slugid that identifies the process that owns the /// exclusive right to run the periodic task. final String owner; NeatTaskStatus({ required this.format, required this.version, required this.state, required this.started, required this.owner, }); NeatTaskStatus.create({ required this.state, required this.started, required this.owner, }) : format = formatIdentifier, version = currentVersion; /// Create a new [NeatTaskStatus] updating the given values. NeatTaskStatus update({ String? state, DateTime? started, String? owner, }) { return NeatTaskStatus( format: formatIdentifier, version: currentVersion, state: state ?? this.state, started: started ?? this.started, owner: owner ?? this.owner, ); } static NeatTaskStatus _initial() => NeatTaskStatus( format: formatIdentifier, version: currentVersion, state: 'idle', started: DateTime.fromMillisecondsSinceEpoch(0, isUtc: true), owner: '-', ); factory NeatTaskStatus.deserialize(List<int>? bytes) { if (bytes == null) { return _initial(); } NeatTaskStatus val; try { final raw = json.fuse(utf8).decode(bytes); if (raw == null) { return _initial(); } val = _$NeatTaskStatusFromJson( raw as Map<String, dynamic>, ); if (val.format != formatIdentifier || val.version < currentVersion) { return _initial(); } return val; } catch (_) { return _initial(); } } List<int> serialize() => json.fuse(utf8).encode(_$NeatTaskStatusToJson(this)); }
dart-neats/neat_periodic_task/lib/src/neat_status.dart/0
{'file_path': 'dart-neats/neat_periodic_task/lib/src/neat_status.dart', 'repo_id': 'dart-neats', 'token_count': 1126}
// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import 'package:test/test.dart'; import 'package:pem/pem.dart'; import 'testcases.dart'; final _labelToString = <PemLabel, String>{ PemLabel.certificate: 'certificate', PemLabel.certificateRevocationList: 'certificateRevocationList', PemLabel.certificateRequest: 'certificateRequest', PemLabel.pkcs7: 'pkcs7', PemLabel.cms: 'cms', PemLabel.privateKey: 'privateKey', PemLabel.encryptedPrivateKey: 'encryptedPrivateKey', PemLabel.attributeCertificate: 'attributeCertificate', PemLabel.publicKey: 'publicKey', }; void main() { group('decodePemBlocks (non-strict)', () { for (final label in PemLabel.values) { test(_labelToString[label], () { final blocks = decodePemBlocks(label, strictTestCases); expect(blocks, hasLength(greaterThanOrEqualTo(1))); }); } test('multiple certificate', () { // The testCases has 2 certificates. final blocks = decodePemBlocks(PemLabel.certificate, strictTestCases); expect(blocks, hasLength(equals(2))); }); test('unsafeIgoreLabels', () { final blocks = decodePemBlocks( PemLabel.certificate, strictTestCases, unsafeIgnoreLabel: true, ); expect(blocks, hasLength(equals(10))); }); }); group('decodePemBlocks (strict)', () { for (final label in PemLabel.values) { test(_labelToString[label], () { final blocks = decodePemBlocks(label, strictTestCases, strict: true); expect(blocks, hasLength(greaterThanOrEqualTo(1))); }); } test('multiple certificate', () { // The testCases has 2 certificates. final blocks = decodePemBlocks( PemLabel.certificate, strictTestCases, strict: true, ); expect(blocks, hasLength(equals(2))); }); test('unsafeIgoreLabels', () { final blocks = decodePemBlocks( PemLabel.certificate, strictTestCases, strict: true, unsafeIgnoreLabel: true, ); expect(blocks, hasLength(equals(10))); }); }); group('decodePemBlocks (non-strict) with extra whitespace', () { for (final label in PemLabel.values) { test(_labelToString[label], () { final blocks = decodePemBlocks(label, laxTestCases); expect(blocks, hasLength(greaterThanOrEqualTo(1))); }); } test('multiple certificate', () { // The laxTestCases has 2 certificates. final blocks = decodePemBlocks(PemLabel.certificate, laxTestCases); expect(blocks, hasLength(equals(2))); }); test('unsafeIgoreLabels', () { final blocks = decodePemBlocks( PemLabel.certificate, laxTestCases, unsafeIgnoreLabel: true, ); expect(blocks, hasLength(equals(10))); }); test('laxTestCases matches strictTestCases', () { final laxblocks = decodePemBlocks( PemLabel.certificate, laxTestCases, unsafeIgnoreLabel: true, ); final strictblocks = decodePemBlocks( PemLabel.certificate, strictTestCases, strict: true, unsafeIgnoreLabel: true, ); expect(laxblocks, equals(strictblocks)); }); }); group('PemCodec.decode + PemCodec.encode / PemCodec.decode (strict)', () { for (final label in PemLabel.values) { test(_labelToString[label], () { final codec = PemCodec(label); final data = codec.decode(strictTestCases); expect(data, isNotNull); final pem = codec.encode(data); final strictCodec = PemCodec(label, strict: true); final data2 = strictCodec.decode(pem); expect(data2, equals(data)); }); } }); }
dart-neats/pem/test/pem_test.dart/0
{'file_path': 'dart-neats/pem/test/pem_test.dart', 'repo_id': 'dart-neats', 'token_count': 1683}
include: package:lints/recommended.yaml
dart-neats/safe_url_check/analysis_options.yaml/0
{'file_path': 'dart-neats/safe_url_check/analysis_options.yaml', 'repo_id': 'dart-neats', 'token_count': 13}