code
stringlengths 8
3.25M
| repository
stringlengths 15
175
| metadata
stringlengths 66
249
|
---|---|---|
library box2d.common;
import 'dart:math' as Math;
import 'math_utils.dart' as MathUtils;
import 'vector_math.dart';
part 'common/color3i.dart';
part 'common/raycast_result.dart';
part 'common/rot.dart';
part 'common/sweep.dart';
part 'common/timer.dart';
part 'common/transform.dart';
part 'common/viewport_transform.dart';
| box2d.dart/lib/src/common.dart/0 | {'file_path': 'box2d.dart/lib/src/common.dart', 'repo_id': 'box2d.dart', 'token_count': 126} |
/// *****************************************************************************
/// 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;
/// The class manages contact between two shapes. A contact exists for each overlapping AABB in the
/// broad-phase (except if filtered). Therefore a contact object may exist that has no contact
/// points.
abstract class Contact {
// Flags stored in _flags
// Used when crawling contact graph when forming islands.
static final int ISLAND_FLAG = 0x0001;
// Set when the shapes are touching.
static final int TOUCHING_FLAG = 0x0002;
// This contact can be disabled (by user)
static final int ENABLED_FLAG = 0x0004;
// This contact needs filtering because a fixture filter was changed.
static final int FILTER_FLAG = 0x0008;
// This bullet contact had a TOI event
static final int BULLET_HIT_FLAG = 0x0010;
static final int TOI_FLAG = 0x0020;
int _flags = 0;
// World pool and list pointers.
Contact _prev;
Contact _next;
// Nodes for connecting bodies.
ContactEdge _nodeA = ContactEdge();
ContactEdge _nodeB = ContactEdge();
Fixture _fixtureA;
Fixture _fixtureB;
int _indexA = 0;
int _indexB = 0;
final Manifold _manifold = Manifold();
int _toiCount = 0;
double _toi = 0.0;
double _friction = 0.0;
double _restitution = 0.0;
double _tangentSpeed = 0.0;
final IWorldPool _pool;
Contact(this._pool);
/// initialization for pooling
void init(Fixture fA, int indexA, Fixture fB, int indexB) {
_flags = ENABLED_FLAG;
_fixtureA = fA;
_fixtureB = fB;
_indexA = indexA;
_indexB = indexB;
_manifold.pointCount = 0;
_prev = null;
_next = null;
_nodeA.contact = null;
_nodeA.prev = null;
_nodeA.next = null;
_nodeA.other = null;
_nodeB.contact = null;
_nodeB.prev = null;
_nodeB.next = null;
_nodeB.other = null;
_toiCount = 0;
_friction = Contact.mixFriction(fA._friction, fB._friction);
_restitution = Contact.mixRestitution(fA._restitution, fB._restitution);
_tangentSpeed = 0.0;
}
/// Get the world manifold.
void getWorldManifold(WorldManifold worldManifold) {
final Body bodyA = _fixtureA.getBody();
final Body bodyB = _fixtureB.getBody();
final Shape shapeA = _fixtureA.getShape();
final Shape shapeB = _fixtureB.getShape();
worldManifold.initialize(_manifold, bodyA._transform, shapeA.radius,
bodyB._transform, shapeB.radius);
}
/// Is this contact touching
bool isTouching() {
return (_flags & TOUCHING_FLAG) == TOUCHING_FLAG;
}
/// Enable/disable this contact. This can be used inside the pre-solve contact listener. The
/// contact is only disabled for the current time step (or sub-step in continuous collisions).
void setEnabled(bool flag) {
if (flag) {
_flags |= ENABLED_FLAG;
} else {
_flags &= ~ENABLED_FLAG;
}
}
/// Has this contact been disabled?
bool isEnabled() {
return (_flags & ENABLED_FLAG) == ENABLED_FLAG;
}
/// Get the next contact in the world's contact list.
Contact getNext() {
return _next;
}
/// Get the first fixture in this contact.
Fixture get fixtureA => _fixtureA;
int getChildIndexA() {
return _indexA;
}
/// Get the second fixture in this contact.
Fixture get fixtureB => _fixtureB;
int getChildIndexB() {
return _indexB;
}
void resetFriction() {
_friction = Contact.mixFriction(_fixtureA._friction, _fixtureB._friction);
}
void resetRestitution() {
_restitution =
Contact.mixRestitution(_fixtureA._restitution, _fixtureB._restitution);
}
void evaluate(Manifold manifold, Transform xfA, Transform xfB);
/// Flag this contact for filtering. Filtering will occur the next time step.
void flagForFiltering() {
_flags |= FILTER_FLAG;
}
// djm pooling
final Manifold _oldManifold = Manifold();
void update(ContactListener listener) {
_oldManifold.set(_manifold);
// Re-enable this contact.
_flags |= ENABLED_FLAG;
bool touching = false;
bool wasTouching = (_flags & TOUCHING_FLAG) == TOUCHING_FLAG;
bool sensorA = _fixtureA.isSensor();
bool sensorB = _fixtureB.isSensor();
bool sensor = sensorA || sensorB;
Body bodyA = _fixtureA.getBody();
Body bodyB = _fixtureB.getBody();
Transform xfA = bodyA._transform;
Transform xfB = bodyB._transform;
// log.debug("TransformA: "+xfA);
// log.debug("TransformB: "+xfB);
if (sensor) {
Shape shapeA = _fixtureA.getShape();
Shape shapeB = _fixtureB.getShape();
touching = _pool
.getCollision()
.testOverlap(shapeA, _indexA, shapeB, _indexB, xfA, xfB);
// Sensors don't generate manifolds.
_manifold.pointCount = 0;
} else {
evaluate(_manifold, xfA, xfB);
touching = _manifold.pointCount > 0;
// Match old contact ids to new contact ids and copy the
// stored impulses to warm start the solver.
for (int i = 0; i < _manifold.pointCount; ++i) {
ManifoldPoint mp2 = _manifold.points[i];
mp2.normalImpulse = 0.0;
mp2.tangentImpulse = 0.0;
ContactID id2 = mp2.id;
for (int j = 0; j < _oldManifold.pointCount; ++j) {
ManifoldPoint mp1 = _oldManifold.points[j];
if (mp1.id.isEqual(id2)) {
mp2.normalImpulse = mp1.normalImpulse;
mp2.tangentImpulse = mp1.tangentImpulse;
break;
}
}
}
if (touching != wasTouching) {
bodyA.setAwake(true);
bodyB.setAwake(true);
}
}
if (touching) {
_flags |= TOUCHING_FLAG;
} else {
_flags &= ~TOUCHING_FLAG;
}
if (listener == null) {
return;
}
if (wasTouching == false && touching == true) {
listener.beginContact(this);
}
if (wasTouching == true && touching == false) {
listener.endContact(this);
}
if (sensor == false && touching) {
listener.preSolve(this, _oldManifold);
}
}
/// Friction mixing law. The idea is to allow either fixture to drive the restitution to zero. For
/// example, anything slides on ice.
static double mixFriction(double friction1, double friction2) {
return Math.sqrt(friction1 * friction2);
}
/// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. For
/// example, a superball bounces on anything.
static double mixRestitution(double restitution1, double restitution2) {
return restitution1 > restitution2 ? restitution1 : restitution2;
}
}
| box2d.dart/lib/src/dynamics/contacts/contact.dart/0 | {'file_path': 'box2d.dart/lib/src/dynamics/contacts/contact.dart', 'repo_id': 'box2d.dart', 'token_count': 2864} |
/// *****************************************************************************
/// 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;
//Point-to-point constraint
//Cdot = v2 - v1
// = v2 + cross(w2, r2) - v1 - cross(w1, r1)
//J = [-I -r1_skew I r2_skew ]
//Identity used:
//w k % (rx i + ry j) = w * (-ry i + rx j)
//Angle constraint
//Cdot = w2 - w1
//J = [0 0 -1 0 0 1]
//K = invI1 + invI2
/// A motor joint is used to control the relative motion between two bodies. A typical usage is to
/// control the movement of a dynamic body with respect to the ground.
class MotorJoint extends Joint {
// Solver shared
final Vector2 _linearOffset = new Vector2.zero();
double _angularOffset = 0.0;
final Vector2 _linearImpulse = new Vector2.zero();
double _angularImpulse = 0.0;
double _maxForce = 0.0;
double _maxTorque = 0.0;
double _correctionFactor = 0.0;
// Solver temp
int _indexA = 0;
int _indexB = 0;
final Vector2 _rA = new Vector2.zero();
final Vector2 _rB = new Vector2.zero();
final Vector2 _localCenterA = new Vector2.zero();
final Vector2 _localCenterB = new Vector2.zero();
final Vector2 _linearError = new Vector2.zero();
double _angularError = 0.0;
double _invMassA = 0.0;
double _invMassB = 0.0;
double _invIA = 0.0;
double _invIB = 0.0;
final Matrix2 _linearMass = new Matrix2.zero();
double _angularMass = 0.0;
MotorJoint(IWorldPool pool, MotorJointDef def) : super(pool, def) {
_linearOffset.setFrom(def.linearOffset);
_angularOffset = def.angularOffset;
_angularImpulse = 0.0;
_maxForce = def.maxForce;
_maxTorque = def.maxTorque;
_correctionFactor = def.correctionFactor;
}
void getAnchorA(Vector2 out) {
out.setFrom(_bodyA.position);
}
void getAnchorB(Vector2 out) {
out.setFrom(_bodyB.position);
}
void getReactionForce(double inv_dt, Vector2 out) {
out
..setFrom(_linearImpulse)
..scale(inv_dt);
}
double getReactionTorque(double inv_dt) {
return _angularImpulse * inv_dt;
}
/// Set the target linear offset, in frame A, in meters.
void setLinearOffset(Vector2 linearOffset) {
if (linearOffset.x != _linearOffset.x ||
linearOffset.y != _linearOffset.y) {
_bodyA.setAwake(true);
_bodyB.setAwake(true);
_linearOffset.setFrom(linearOffset);
}
}
/// Get the target linear offset, in frame A, in meters.
void getLinearOffsetOut(Vector2 out) {
out.setFrom(_linearOffset);
}
/// Get the target linear offset, in frame A, in meters. Do not modify.
Vector2 getLinearOffset() {
return _linearOffset;
}
/// Set the target angular offset, in radians.
///
/// @param angularOffset
void setAngularOffset(double angularOffset) {
if (angularOffset != _angularOffset) {
_bodyA.setAwake(true);
_bodyB.setAwake(true);
_angularOffset = angularOffset;
}
}
double getAngularOffset() {
return _angularOffset;
}
/// Set the maximum friction force in N.
///
/// @param force
void setMaxForce(double force) {
assert(force >= 0.0);
_maxForce = force;
}
/// Get the maximum friction force in N.
double getMaxForce() {
return _maxForce;
}
/// Set the maximum friction torque in N*m.
void setMaxTorque(double torque) {
assert(torque >= 0.0);
_maxTorque = torque;
}
/// Get the maximum friction torque in N*m.
double getMaxTorque() {
return _maxTorque;
}
void initVelocityConstraints(SolverData data) {
_indexA = _bodyA._islandIndex;
_indexB = _bodyB._islandIndex;
_localCenterA.setFrom(_bodyA._sweep.localCenter);
_localCenterB.setFrom(_bodyB._sweep.localCenter);
_invMassA = _bodyA._invMass;
_invMassB = _bodyB._invMass;
_invIA = _bodyA._invI;
_invIB = _bodyB._invI;
final Vector2 cA = data.positions[_indexA].c;
double aA = data.positions[_indexA].a;
final Vector2 vA = data.velocities[_indexA].v;
double wA = data.velocities[_indexA].w;
final Vector2 cB = data.positions[_indexB].c;
double aB = data.positions[_indexB].a;
final Vector2 vB = data.velocities[_indexB].v;
double wB = data.velocities[_indexB].w;
final Rot qA = pool.popRot();
final Rot qB = pool.popRot();
final Vector2 temp = pool.popVec2();
Matrix2 K = pool.popMat22();
qA.setAngle(aA);
qB.setAngle(aB);
// Compute the effective mass matrix.
// _rA = b2Mul(qA, -_localCenterA);
// _rB = b2Mul(qB, -_localCenterB);
_rA.x = qA.c * -_localCenterA.x - qA.s * -_localCenterA.y;
_rA.y = qA.s * -_localCenterA.x + qA.c * -_localCenterA.y;
_rB.x = qB.c * -_localCenterB.x - qB.s * -_localCenterB.y;
_rB.y = qB.s * -_localCenterB.x + qB.c * -_localCenterB.y;
// J = [-I -r1_skew I r2_skew]
// [ 0 -1 0 1]
// r_skew = [-ry; rx]
// Matlab
// K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB]
// [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB]
// [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB]
double mA = _invMassA, mB = _invMassB;
double iA = _invIA, iB = _invIB;
double a11 = mA + mB + iA * _rA.y * _rA.y + iB * _rB.y * _rB.y;
double a21 = -iA * _rA.x * _rA.y - iB * _rB.x * _rB.y;
double a12 = a21;
double a22 = mA + mB + iA * _rA.x * _rA.x + iB * _rB.x * _rB.x;
K.setValues(a11, a21, a12, a22);
_linearMass.setFrom(K);
_linearMass.invert();
_angularMass = iA + iB;
if (_angularMass > 0.0) {
_angularMass = 1.0 / _angularMass;
}
// _linearError = cB + _rB - cA - _rA - b2Mul(qA, _linearOffset);
Rot.mulToOutUnsafe(qA, _linearOffset, temp);
_linearError.x = cB.x + _rB.x - cA.x - _rA.x - temp.x;
_linearError.y = cB.y + _rB.y - cA.y - _rA.y - temp.y;
_angularError = aB - aA - _angularOffset;
if (data.step.warmStarting) {
// Scale impulses to support a variable time step.
_linearImpulse.x *= data.step.dtRatio;
_linearImpulse.y *= data.step.dtRatio;
_angularImpulse *= data.step.dtRatio;
final Vector2 P = _linearImpulse;
vA.x -= mA * P.x;
vA.y -= mA * P.y;
wA -= iA * (_rA.x * P.y - _rA.y * P.x + _angularImpulse);
vB.x += mB * P.x;
vB.y += mB * P.y;
wB += iB * (_rB.x * P.y - _rB.y * P.x + _angularImpulse);
} else {
_linearImpulse.setZero();
_angularImpulse = 0.0;
}
pool.pushVec2(1);
pool.pushMat22(1);
pool.pushRot(2);
// data.velocities[_indexA].v = vA;
data.velocities[_indexA].w = wA;
// data.velocities[_indexB].v = vB;
data.velocities[_indexB].w = wB;
}
void solveVelocityConstraints(SolverData data) {
final Vector2 vA = data.velocities[_indexA].v;
double wA = data.velocities[_indexA].w;
final Vector2 vB = data.velocities[_indexB].v;
double wB = data.velocities[_indexB].w;
double mA = _invMassA, mB = _invMassB;
double iA = _invIA, iB = _invIB;
double h = data.step.dt;
double inv_h = data.step.inv_dt;
final Vector2 temp = pool.popVec2();
// Solve angular friction
{
double Cdot = wB - wA + inv_h * _correctionFactor * _angularError;
double impulse = -_angularMass * Cdot;
double oldImpulse = _angularImpulse;
double maxImpulse = h * _maxTorque;
_angularImpulse = MathUtils.clampDouble(
_angularImpulse + impulse, -maxImpulse, maxImpulse);
impulse = _angularImpulse - oldImpulse;
wA -= iA * impulse;
wB += iB * impulse;
}
final Vector2 Cdot = pool.popVec2();
// Solve linear friction
{
// Cdot = vB + b2Cross(wB, _rB) - vA - b2Cross(wA, _rA) + inv_h * _correctionFactor *
// _linearError;
Cdot.x = vB.x +
-wB * _rB.y -
vA.x -
-wA * _rA.y +
inv_h * _correctionFactor * _linearError.x;
Cdot.y = vB.y +
wB * _rB.x -
vA.y -
wA * _rA.x +
inv_h * _correctionFactor * _linearError.y;
final Vector2 impulse = temp;
_linearMass.transformed(Cdot, impulse);
impulse.negate();
final Vector2 oldImpulse = pool.popVec2();
oldImpulse.setFrom(_linearImpulse);
_linearImpulse.add(impulse);
double maxImpulse = h * _maxForce;
if (_linearImpulse.length2 > maxImpulse * maxImpulse) {
_linearImpulse.normalize();
_linearImpulse.scale(maxImpulse);
}
impulse.x = _linearImpulse.x - oldImpulse.x;
impulse.y = _linearImpulse.y - oldImpulse.y;
vA.x -= mA * impulse.x;
vA.y -= mA * impulse.y;
wA -= iA * (_rA.x * impulse.y - _rA.y * impulse.x);
vB.x += mB * impulse.x;
vB.y += mB * impulse.y;
wB += iB * (_rB.x * impulse.y - _rB.y * impulse.x);
}
pool.pushVec2(3);
// data.velocities[_indexA].v.set(vA);
data.velocities[_indexA].w = wA;
// data.velocities[_indexB].v.set(vB);
data.velocities[_indexB].w = wB;
}
bool solvePositionConstraints(SolverData data) {
return true;
}
}
| box2d.dart/lib/src/dynamics/joints/motor_joint.dart/0 | {'file_path': 'box2d.dart/lib/src/dynamics/joints/motor_joint.dart', 'repo_id': 'box2d.dart', 'token_count': 4435} |
/*******************************************************************************
* 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 ProfileEntry {
static const int _LONG_AVG_NUMS = 20;
static const double _LONG_FRACTION = 1.0 / _LONG_AVG_NUMS;
static const int _SHORT_AVG_NUMS = 5;
static const double _SHORT_FRACTION = 1.0 / _SHORT_AVG_NUMS;
double longAvg = 0.0;
double shortAvg = 0.0;
double min = double.maxFinite;
double max = -double.maxFinite;
double _accum = 0.0;
void record(double value) {
longAvg = longAvg * (1 - _LONG_FRACTION) + value * _LONG_FRACTION;
shortAvg = shortAvg * (1 - _SHORT_FRACTION) + value * _SHORT_FRACTION;
min = Math.min(value, min);
max = Math.max(value, max);
}
void startAccum() {
_accum = 0.0;
}
void accum(double value) {
_accum += value;
}
void endAccum() {
record(_accum);
}
String toString() {
return "$shortAvg ($longAvg) [$min,$max]";
}
}
class Profile {
final ProfileEntry step = ProfileEntry();
final ProfileEntry stepInit = ProfileEntry();
final ProfileEntry collide = ProfileEntry();
final ProfileEntry solveParticleSystem = ProfileEntry();
final ProfileEntry solve = ProfileEntry();
final ProfileEntry solveInit = ProfileEntry();
final ProfileEntry solveVelocity = ProfileEntry();
final ProfileEntry solvePosition = ProfileEntry();
final ProfileEntry broadphase = ProfileEntry();
final ProfileEntry solveTOI = ProfileEntry();
void toDebugStrings(List<String> strings) {
strings.add("Profile:");
strings.add(" step: $step");
strings.add(" init: $stepInit");
strings.add(" collide: $collide");
strings.add(" particles: $solveParticleSystem");
strings.add(" solve: $solve");
strings.add(" solveInit: $solveInit");
strings.add(" solveVelocity: $solveVelocity");
strings.add(" solvePosition: $solvePosition");
strings.add(" broadphase: $broadphase");
strings.add(" solveTOI: $solveTOI");
}
}
| box2d.dart/lib/src/dynamics/profile.dart/0 | {'file_path': 'box2d.dart/lib/src/dynamics/profile.dart', 'repo_id': 'box2d.dart', 'token_count': 1066} |
export 'src/circle.dart';
export 'src/ellipse.dart';
export 'src/line.dart';
export 'src/polygon.dart';
export 'src/rectangle.dart';
export 'src/square.dart';
export 'src/triangle.dart';
| brache/packages/brache/lib/src/components/src/shapes/shapes.dart/0 | {'file_path': 'brache/packages/brache/lib/src/components/src/shapes/shapes.dart', 'repo_id': 'brache', 'token_count': 75} |
import 'package:brache/src/core/src/component/component.dart';
class TranslateAnimation {
TranslateAnimation({
required this.fromX,
required this.toX,
required this.fromY,
required this.toY,
required this.target,
});
final double fromX;
final double toX;
final double fromY;
final double toY;
final $Component target;
void apply(double progress) {
target.x = fromX + (toX - fromX) * progress;
target.y = fromY + (toY - fromY) * progress;
}
}
| brache/packages/brache/lib/src/core/src/component/src/translate_animation.dart/0 | {'file_path': 'brache/packages/brache/lib/src/core/src/component/src/translate_animation.dart', 'repo_id': 'brache', 'token_count': 177} |
// 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.
// ignore: implementation_imports
import 'package:build_runner_core/src/asset_graph/exceptions.dart';
// ignore: implementation_imports
import 'package:build_runner_core/src/asset_graph/graph.dart';
// ignore: implementation_imports
import 'package:build_runner_core/src/asset_graph/node.dart';
import 'package:test/test.dart';
final Matcher throwsCorruptedException =
throwsA(TypeMatcher<AssetGraphCorruptedException>());
final Matcher duplicateAssetNodeException =
TypeMatcher<DuplicateAssetNodeException>();
Matcher equalsAssetGraph(AssetGraph expected,
{bool checkPreviousInputsDigest = true}) =>
_AssetGraphMatcher(expected, checkPreviousInputsDigest);
class _AssetGraphMatcher extends Matcher {
final AssetGraph _expected;
final bool checkPreviousInputsDigest;
const _AssetGraphMatcher(this._expected, this.checkPreviousInputsDigest);
@override
bool matches(dynamic item, Map<dynamic, dynamic> matchState) {
if (item is! AssetGraph) return false;
var matches = true;
if (item.allNodes.length != _expected.allNodes.length) matches = false;
for (var node in item.allNodes) {
var expectedNode = _expected.get(node.id);
if (node.isDeleted != expectedNode?.isDeleted) {
matchState['IsDeleted of ${node.id}'] = [
node.isDeleted,
expectedNode?.isDeleted
];
matches = false;
}
if (node.runtimeType != expectedNode.runtimeType) {
matchState['RuntimeType'] = [
node.runtimeType,
expectedNode.runtimeType
];
matches = false;
}
if (expectedNode == null || expectedNode.id != node.id) {
matchState['AssetId'] = [node.id, expectedNode!.id];
matches = false;
}
if (!unorderedEquals(node.outputs).matches(expectedNode.outputs, {})) {
matchState['Outputs of ${node.id}'] = [
node.outputs,
expectedNode.outputs
];
matches = false;
}
if (!unorderedEquals(node.primaryOutputs)
.matches(expectedNode.primaryOutputs, {})) {
matchState['Primary outputs of ${node.id}'] = [
node.primaryOutputs,
expectedNode.primaryOutputs
];
matches = false;
}
if (!unorderedEquals(node.anchorOutputs)
.matches(expectedNode.anchorOutputs, {})) {
matchState['Anchor outputs of ${node.id}'] = [
node.anchorOutputs,
expectedNode.anchorOutputs
];
matches = false;
}
if (node.lastKnownDigest != expectedNode.lastKnownDigest) {
matchState['Digest of ${node.id}'] = [
node.lastKnownDigest,
expectedNode.lastKnownDigest
];
matches = false;
}
if (node is NodeWithInputs) {
if (expectedNode is NodeWithInputs) {
if (node.state != expectedNode.state) {
matchState['needsUpdate of ${node.id}'] = [
node.state,
expectedNode.state
];
matches = false;
}
if (!unorderedEquals(node.inputs).matches(expectedNode.inputs, {})) {
matchState['Inputs of ${node.id}'] = [
node.inputs,
expectedNode.inputs
];
matches = false;
}
}
if (node is GeneratedAssetNode) {
if (expectedNode is GeneratedAssetNode) {
if (node.primaryInput != expectedNode.primaryInput) {
matchState['primaryInput of ${node.id}'] = [
node.primaryInput,
expectedNode.primaryInput
];
matches = false;
}
if (node.wasOutput != expectedNode.wasOutput) {
matchState['wasOutput of ${node.id}'] = [
node.wasOutput,
expectedNode.wasOutput
];
matches = false;
}
if (node.isFailure != expectedNode.isFailure) {
matchState['isFailure of ${node.id}'] = [
node.isFailure,
expectedNode.isFailure
];
matches = false;
}
if (checkPreviousInputsDigest &&
node.previousInputsDigest !=
expectedNode.previousInputsDigest) {
matchState['previousInputDigest of ${node.id}'] = [
node.previousInputsDigest,
expectedNode.previousInputsDigest
];
matches = false;
}
}
} else if (node is GlobAssetNode) {
if (expectedNode is GlobAssetNode) {
if (!unorderedEquals(node.results!)
.matches(expectedNode.results, {})) {
matchState['results of ${node.id}'] = [
node.results,
expectedNode.results
];
matches = false;
}
if (node.glob.pattern != expectedNode.glob.pattern) {
matchState['glob of ${node.id}'] = [
node.glob.pattern,
expectedNode.glob.pattern
];
matches = false;
}
}
}
} else if (node is PostProcessAnchorNode) {
if (expectedNode is PostProcessAnchorNode) {
if (node.actionNumber != expectedNode.actionNumber) {
matchState['actionNumber of ${node.id}'] = [
node.actionNumber,
expectedNode.actionNumber
];
matches = false;
}
if (node.builderOptionsId != expectedNode.builderOptionsId) {
matchState['builderOptionsId of ${node.id}'] = [
node.builderOptionsId,
expectedNode.builderOptionsId
];
matches = false;
}
if (checkPreviousInputsDigest &&
node.previousInputsDigest != expectedNode.previousInputsDigest) {
matchState['previousInputsDigest of ${node.id}'] = [
node.previousInputsDigest,
expectedNode.previousInputsDigest
];
matches = false;
}
if (node.primaryInput != expectedNode.primaryInput) {
matchState['primaryInput of ${node.id}'] = [
node.primaryInput,
expectedNode.primaryInput
];
matches = false;
}
}
}
}
if (!equals(_expected.packageLanguageVersions).matches(
item.packageLanguageVersions,
matchState['packageLanguageVersions'] = {})) {
matches = false;
}
return matches;
}
@override
Description describe(Description description) =>
description.addDescriptionOf(_expected);
@override
Description describeMismatch(
item, Description mismatchDescription, Map matchState, bool verbose) {
matchState.forEach((k, v) =>
mismatchDescription.add('$k: got ${v[0]} but expected ${v[1]}'));
return mismatchDescription;
}
}
| build/_test_common/lib/matchers.dart/0 | {'file_path': 'build/_test_common/lib/matchers.dart', 'repo_id': 'build', 'token_count': 3348} |
// 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:convert';
import 'package:analyzer/dart/element/element.dart';
import 'package:meta/meta.dart';
import '../analyzer/resolver.dart';
import '../asset/id.dart';
import '../asset/reader.dart';
import '../asset/writer.dart';
import '../resource/resource.dart';
/// A single step in a build process.
///
/// This represents a single [inputId], logic around resolving as a library,
/// and the ability to read and write assets as allowed by the underlying build
/// system.
@sealed
abstract class BuildStep implements AssetReader, AssetWriter {
/// The primary for this build step.
AssetId get inputId;
/// Resolved library defined by [inputId].
///
/// Throws [NonLibraryAssetException] if [inputId] is not a Dart library file.
/// Throws [SyntaxErrorInAssetException] if [inputId] contains syntax errors.
/// If you want to support libraries with syntax errors, resolve the library
/// manually instead of using [inputLibrary]:
/// ```dart
/// Future<void> build(BuildStep step) async {
/// // Resolve the input library, allowing syntax errors
/// final inputLibrary =
/// await step.resolver.libraryFor(step.inputId, allowSyntaxErrors: true);
/// }
/// ```
Future<LibraryElement> get inputLibrary;
/// Gets an instance provided by [resource] which is guaranteed to be unique
/// within a single build, and may be reused across build steps within a
/// build if the implementation allows.
///
/// It is also guaranteed that [resource] will be disposed before the next
/// build starts (and the dispose callback will be invoked if provided).
Future<T> fetchResource<T>(Resource<T> resource);
/// Writes [bytes] to a binary file located at [id].
///
/// Returns a [Future] that completes after writing the asset out.
///
/// * Throws a `PackageNotFoundException` if `id.package` is not found.
/// * Throws an `InvalidOutputException` if the output was not valid (that is,
/// [id] is not in [allowedOutputs])
///
/// **NOTE**: Most `Builder` implementations should not need to `await` this
/// Future since the runner will be responsible for waiting until all outputs
/// are written.
@override
Future<void> writeAsBytes(AssetId id, FutureOr<List<int>> bytes);
/// Writes [contents] to a text file located at [id] with [encoding].
///
/// Returns a [Future] that completes after writing the asset out.
///
/// * Throws a `PackageNotFoundException` if `id.package` is not found.
/// * Throws an `InvalidOutputException` if the output was not valid (that is,
/// [id] is not in [allowedOutputs])
///
/// **NOTE**: Most `Builder` implementations should not need to `await` this
/// Future since the runner will be responsible for waiting until all outputs
/// are written.
@override
Future<void> writeAsString(AssetId id, FutureOr<String> contents,
{Encoding encoding = utf8});
/// A [Resolver] for [inputId].
Resolver get resolver;
/// Tracks performance of [action] separately.
///
/// If performance tracking is enabled, tracks [action] as separate stage
/// identified by [label]. Otherwise just runs [action].
///
/// You can specify [action] as [isExternal] (waiting for some external
/// resource like network, process or file IO). In that case [action] will
/// be tracked as single time slice from the beginning of the stage till
/// completion of Future returned by [action].
///
/// Otherwise all separate time slices of asynchronous execution will be
/// tracked, but waiting for external resources will be a gap.
///
/// Returns value returned by [action].
/// [action] can be async function returning [Future].
T trackStage<T>(String label, T Function() action, {bool isExternal = false});
/// Indicates that [ids] were read but their content has no impact on the
/// outputs of this step.
///
/// **WARNING**: Using this introduces serious risk of non-hermetic builds.
///
/// If these files change or become unreadable on the next build this build
/// step may not run.
///
/// **Note**: This is not guaranteed to have any effect and it should be
/// assumed to be a no-op by default. Implementations must explicitly
/// choose to support this feature.
void reportUnusedAssets(Iterable<AssetId> ids);
/// Returns assets that may be written in this build step.
///
/// Allowed outputs are formed by matching the [inputId] against the builder's
/// `buildExtensions`, which declares a list of output extensions for this
/// input.
///
/// The writing methods [writeAsBytes] and [writeAsString] will throw an
/// `InvalidOutputException` when attempting to write an asset not part of
/// the [allowedOutputs].
Iterable<AssetId> get allowedOutputs;
}
abstract class StageTracker {
T trackStage<T>(String label, T Function() action, {bool isExternal = false});
}
class NoOpStageTracker implements StageTracker {
static const StageTracker instance = NoOpStageTracker._();
@override
T trackStage<T>(String label, T Function() action,
{bool isExternal = false}) =>
action();
const NoOpStageTracker._();
}
| build/build/lib/src/builder/build_step.dart/0 | {'file_path': 'build/build/lib/src/builder/build_step.dart', 'repo_id': 'build', 'token_count': 1489} |
import 'package:build/build.dart';
import 'package:test/test.dart';
void main() {
test('InvalidInputException.toString() reports available assets', () {
final onlyLib = InvalidInputException(AssetId('a', 'test/foo.bar'));
final libReadmeAndTest = InvalidInputException(AssetId('a', 'test/foo.bar'),
allowedGlobs: ['lib/**', 'README*', 'test/**']);
expect(onlyLib.toString(), contains('only assets matching lib/**'));
expect(libReadmeAndTest.toString(),
contains('only assets matching lib/**, README* or test/**'));
});
}
| build/build/test/asset/exceptions_test.dart/0 | {'file_path': 'build/build/test/asset/exceptions_test.dart', 'repo_id': 'build', 'token_count': 190} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'build_config.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
BuildConfig _$BuildConfigFromJson(Map json) => $checkedCreate(
'BuildConfig',
json,
($checkedConvert) {
$checkKeys(
json,
allowedKeys: const [
'builders',
'post_process_builders',
'targets',
'global_options',
'additional_public_assets'
],
);
final val = BuildConfig(
buildTargets: $checkedConvert(
'targets', (v) => _buildTargetsFromJson(v as Map?)),
globalOptions: $checkedConvert(
'global_options',
(v) => (v as Map?)?.map(
(k, e) => MapEntry(
k as String, GlobalBuilderConfig.fromJson(e as Map)),
)),
builderDefinitions: $checkedConvert(
'builders',
(v) => (v as Map?)?.map(
(k, e) => MapEntry(
k as String, BuilderDefinition.fromJson(e as Map)),
)),
postProcessBuilderDefinitions: $checkedConvert(
'post_process_builders',
(v) =>
(v as Map?)?.map(
(k, e) => MapEntry(k as String,
PostProcessBuilderDefinition.fromJson(e as Map)),
) ??
const {}),
additionalPublicAssets: $checkedConvert(
'additional_public_assets',
(v) =>
(v as List<dynamic>?)?.map((e) => e as String).toList() ??
const []),
);
return val;
},
fieldKeyMap: const {
'buildTargets': 'targets',
'globalOptions': 'global_options',
'builderDefinitions': 'builders',
'postProcessBuilderDefinitions': 'post_process_builders',
'additionalPublicAssets': 'additional_public_assets'
},
);
| build/build_config/lib/src/build_config.g.dart/0 | {'file_path': 'build/build_config/lib/src/build_config.g.dart', 'repo_id': 'build', 'token_count': 1089} |
// Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
@OnPlatform({
'windows': Skip('Directories cant be deleted while processes are still open')
})
import 'dart:async';
import 'dart:convert';
import 'package:build_daemon/data/build_request.dart';
import 'package:build_daemon/data/build_status.dart';
import 'package:build_daemon/data/build_target.dart';
import 'package:build_daemon/data/build_target_request.dart';
import 'package:build_daemon/data/serializers.dart';
import 'package:build_daemon/data/server_log.dart';
import 'package:build_daemon/src/fakes/fake_change_provider.dart';
import 'package:build_daemon/src/fakes/fake_test_builder.dart';
import 'package:build_daemon/src/server.dart';
import 'package:stream_transform/stream_transform.dart';
import 'package:test/test.dart';
import 'package:web_socket_channel/io.dart';
void main() {
group('Server', () {
final webTarget = DefaultBuildTarget((b) => b.target = 'web');
late StreamController<Object?> controller;
late IOWebSocketChannel client;
late Server server;
late int port;
setUp(() async {
controller = StreamController<Object?>();
// Start the server.
server = _createServer();
port = await server.listen();
// Connect the client and redirect its logs.
client = _createClient(controller, port);
});
tearDown(() async {
await server.stop();
await client.sink.close();
await controller.close();
await expectLater(server.onDone, completes);
});
test('can forward logs to the client', () async {
final logs = controller.stream.whereType<ServerLog>().asBroadcastStream();
// Setup listening for a completed build.
final buildCompleted = expectLater(
logs,
emits(_matchServerLog(
equals(Level.INFO),
equals(FakeTestDaemonBuilder.buildCompletedMessage),
equals(FakeTestDaemonBuilder.loggerName),
)));
// Build a target to register interested channels on the server.
_requestBuild(client, webTarget);
await buildCompleted;
// Setup listening for forwarded logs.
final logsReceived = expectLater(
logs,
emits(_matchServerLog(
equals(Level.WARNING),
contains('bad request'),
equals(Server.loggerName),
isNotNull,
isNotNull,
)));
// Send request that with throw an exception an will be logged.
client.sink.add('bad request');
// Await for logs to arrive to the client.
await logsReceived;
});
test('forwards changed assets to interested clients', () async {
final interestedEvents = StreamController<Object?>();
final interstedClient = _createClient(interestedEvents, port);
addTearDown(interstedClient.sink.close);
addTearDown(interestedEvents.close);
// Register default client, not intersted in changes
client.sink.add(jsonEncode(serializers
.serialize(BuildTargetRequest((b) => b.target = webTarget))));
// Register second client which is interested in changes.
final targetWithChanges = DefaultBuildTarget((b) => b
..target = ''
..reportChangedAssets = true);
interstedClient.sink.add(jsonEncode(serializers
.serialize(BuildTargetRequest((b) => b.target = targetWithChanges))));
// Request a build. As there is no ordering guarantee between the two
// sockets, wait a bit first
await Future.delayed(const Duration(milliseconds: 500));
client.sink.add(jsonEncode(serializers.serialize(BuildRequest())));
expect(
interestedEvents.stream,
emitsThrough(isA<BuildResults>()
.having((e) => e.changedAssets, 'changedAssets', isNotEmpty)),
);
await expectLater(
controller.stream,
emitsThrough(isA<BuildResults>()
.having((e) => e.changedAssets, 'changedAssets', isNull)),
);
});
});
}
Server _createServer() {
return Server(
FakeTestDaemonBuilder(),
const Duration(seconds: 30),
FakeChangeProvider(),
);
}
IOWebSocketChannel _createClient(
StreamController<Object?> controller,
int port,
) {
final client = IOWebSocketChannel.connect('ws://localhost:$port');
client.stream.listen((data) {
final message = serializers.deserialize(jsonDecode(data as String));
controller.add(message);
});
return client;
}
void _requestBuild(IOWebSocketChannel client, BuildTarget target) {
client.sink.add(jsonEncode(
serializers.serialize(BuildTargetRequest((b) => b.target = target))));
client.sink.add(
jsonEncode(serializers.serialize(BuildRequest())),
);
}
Matcher _matchServerLog(Matcher level, Matcher message, Matcher loggerName,
[Matcher error = isNull, Matcher stackTrace = isNull]) =>
isA<ServerLog>()
.having((l) => l.level, 'level', level)
.having((l) => l.message, 'message', message)
.having((l) => l.loggerName, 'loggerName', loggerName)
.having((l) => l.error, 'error', error)
.having((l) => l.stackTrace, 'stackTrace', stackTrace);
| build/build_daemon/test/server_test.dart/0 | {'file_path': 'build/build_daemon/test/server_test.dart', 'repo_id': 'build', 'token_count': 1946} |
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'package:async/async.dart';
import 'package:build/build.dart';
import 'package:crypto/crypto.dart';
import 'meta_module.dart';
import 'modules.dart';
Map<String, dynamic> _deserialize(List<int> bytes) =>
jsonDecode(utf8.decode(bytes)) as Map<String, dynamic>;
List<int> _serialize(Map<String, dynamic> data) =>
utf8.encode(jsonEncode(data));
final metaModuleCache = DecodingCache.resource(
(m) => MetaModule.fromJson(_deserialize(m)), (m) => _serialize(m.toJson()));
final moduleCache = DecodingCache.resource(
(m) => Module.fromJson(_deserialize(m)), (m) => _serialize(m.toJson()));
/// A cache of objects decoded from written assets suitable for use as a
/// [Resource].
///
/// Instances that are decoded will be cached throughout the duration of a build
/// and invalidated between builds. Instances that are shared through the cache
/// should be treated as immutable to avoid leaking any information which was
/// not loaded from the underlying asset.
class DecodingCache<T> {
/// Create a [Resource] which can decoded instances of [T] serialized via json
/// to assets.
static Resource<DecodingCache<T>> resource<T>(
T Function(List<int>) fromBytes, List<int> Function(T) toBytes) =>
Resource<DecodingCache<T>>(() => DecodingCache._(fromBytes, toBytes),
dispose: (c) => c._dispose());
final _cached = <AssetId, _Entry<T>>{};
final T Function(List<int>) _fromBytes;
final List<int> Function(T) _toBytes;
DecodingCache._(this._fromBytes, this._toBytes);
void _dispose() {
_cached.removeWhere((_, entry) => entry.digest == null);
for (var entry in _cached.values) {
entry.needsCheck = true;
}
}
/// Find and deserialize a [T] stored in [id].
///
/// If the asset at [id] is unreadable the returned future will resolve to
/// `null`. If the instance is cached it will not be decoded again, but the
/// content dependencies will be tracked through [reader].
Future<T?> find(AssetId id, AssetReader reader) async {
if (!await reader.canRead(id)) return null;
_Entry<T> entry;
if (!_cached.containsKey(id)) {
entry = _cached[id] = _Entry(
Result.capture(reader.readAsBytes(id).then(_fromBytes)),
digest: Result.capture(reader.digest(id)));
} else {
entry = _cached[id]!;
if (entry.needsCheck) {
await (entry.onGoingCheck ??= () async {
var previousDigest =
entry.digest == null ? null : await Result.release(entry.digest!);
entry.digest = Result.capture(reader.digest(id));
if (await Result.release(entry.digest!) != previousDigest) {
entry.value =
Result.capture(reader.readAsBytes(id).then(_fromBytes));
}
entry
..needsCheck = false
..onGoingCheck = null;
}());
}
}
return Result.release(entry.value);
}
/// Serialized and write a [T] to [id].
///
/// The instance will be cached so that later calls to [find] may return the
/// instances without deserializing it.
Future<void> write(AssetId id, AssetWriter writer, T instance) async {
await writer.writeAsBytes(id, _toBytes(instance));
_cached[id] = _Entry(Result.capture(Future.value(instance)));
}
}
class _Entry<T> {
bool needsCheck = false;
Future<Result<T>> value;
Future<Result<Digest>>? digest;
Future<void>? onGoingCheck;
_Entry(this.value, {this.needsCheck = false, this.digest, this.onGoingCheck});
}
| build/build_modules/lib/src/module_cache.dart/0 | {'file_path': 'build/build_modules/lib/src/module_cache.dart', 'repo_id': 'build', 'token_count': 1359} |
library a_imports_b_no_cycle;
// ignore_for_file: unused_import
import 'package:b/b_imports_a_no_cycle.dart';
import 'package:b/b_second_import_to_a_no_cycle.dart';
part 'a_part_library_name.dart';
| build/build_modules/test/fixtures/a/lib/a_imports_b_no_cycle.dart/0 | {'file_path': 'build/build_modules/test/fixtures/a/lib/a_imports_b_no_cycle.dart', 'repo_id': 'build', 'token_count': 85} |
// 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:build/build.dart';
import 'package:build_modules/build_modules.dart';
import 'package:build_modules/src/meta_module.dart';
import 'package:build_modules/src/module_library.dart';
import 'package:build_test/build_test.dart';
import 'package:test/test.dart';
import 'matchers.dart';
void main() {
final platform = DartPlatform.register('test', ['dart:async']);
test('can serialize modules and only output for primary sources', () async {
var assetA = AssetId('a', 'lib/a.dart');
var assetB = AssetId('a', 'lib/b.dart');
var assetC = AssetId('a', 'lib/c.dart');
var assetD = AssetId('a', 'lib/d.dart');
var assetE = AssetId('a', 'lib/e.dart');
var moduleA = Module(assetA, [assetA], <AssetId>[], platform, true);
var moduleB = Module(assetB, [assetB, assetC], <AssetId>[], platform, true);
var moduleD =
Module(assetD, [assetD, assetE], <AssetId>[], platform, false);
var metaModule = MetaModule([moduleA, moduleB, moduleD]);
await testBuilder(ModuleBuilder(platform), {
'a|lib/a.dart': '',
'a|lib/b.dart': '',
'a|lib/c.dart': '',
'a|lib/d.dart': '',
'a|lib/e.dart': '',
'a|lib/${metaModuleCleanExtension(platform)}':
jsonEncode(metaModule.toJson()),
'a|lib/c$moduleLibraryExtension':
ModuleLibrary.fromSource(assetC, '').serialize(),
'a|lib/e$moduleLibraryExtension':
ModuleLibrary.fromSource(assetE, '').serialize(),
}, outputs: {
'a|lib/a${moduleExtension(platform)}': encodedMatchesModule(moduleA),
'a|lib/b${moduleExtension(platform)}': encodedMatchesModule(moduleB),
'a|lib/d${moduleExtension(platform)}': encodedMatchesModule(moduleD),
});
});
}
| build/build_modules/test/module_builder_test.dart/0 | {'file_path': 'build/build_modules/test/module_builder_test.dart', 'repo_id': 'build', 'token_count': 770} |
// 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 'dart:io' show Platform;
import 'dart:isolate';
import 'package:analyzer/dart/analysis/results.dart';
import 'package:analyzer/dart/ast/ast.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:build/build.dart';
import 'package:build/experiments.dart';
import 'package:build_resolvers/src/analysis_driver.dart';
import 'package:build_resolvers/src/resolver.dart';
import 'package:build_test/build_test.dart';
import 'package:logging/logging.dart';
import 'package:package_config/package_config.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:test/test.dart';
void main() {
final entryPoint = AssetId('a', 'web/main.dart');
group('Resolver', () {
test('should handle initial files', () {
return resolveSources({
'a|web/main.dart': ' main() {}',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
expect(lib, isNotNull);
}, resolvers: AnalyzerResolvers());
});
test('should follow imports', () {
return resolveSources({
'a|web/main.dart': '''
import 'a.dart';
main() {
} ''',
'a|web/a.dart': '''
library a;
''',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
expect(lib.importedLibraries.length, 2);
var libA = lib.importedLibraries.where((l) => l.name == 'a').single;
expect(libA.getClass('Foo'), isNull);
}, resolvers: AnalyzerResolvers());
});
test('should follow package imports', () {
return resolveSources({
'a|web/main.dart': '''
import 'package:b/b.dart';
main() {
} ''',
'b|lib/b.dart': '''
library b;
''',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
expect(lib.importedLibraries.length, 2);
var libB = lib.importedLibraries.where((l) => l.name == 'b').single;
expect(libB.getClass('Foo'), isNull);
}, resolvers: AnalyzerResolvers());
});
test('should still crawl transitively after a call to isLibrary', () {
return resolveSources({
'a|web/main.dart': '''
import 'package:b/b.dart';
main() {
} ''',
'b|lib/b.dart': '''
library b;
''',
}, (resolver) async {
await resolver.isLibrary(entryPoint);
var libs = await resolver.libraries.toList();
expect(libs, contains(predicate((LibraryElement l) => l.name == 'b')));
}, resolvers: AnalyzerResolvers());
});
test('should still crawl transitively after a call to compilationUnitFor',
() {
return resolveSources({
'a|web/main.dart': '''
import 'package:b/b.dart';
main() {
} ''',
'b|lib/b.dart': '''
library b;
''',
}, (resolver) async {
await resolver.compilationUnitFor(entryPoint);
var libs = await resolver.libraries.toList();
expect(libs, contains(predicate((LibraryElement l) => l.name == 'b')));
}, resolvers: AnalyzerResolvers());
});
group('language versioning', () {
test('gives a correct languageVersion based on comments', () async {
await resolveSources({
'a|web/main.dart': '// @dart=2.1\n\nmain() {}',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
expect(lib.languageVersion.effective.major, 2);
expect(lib.languageVersion.effective.minor, 1);
}, resolvers: AnalyzerResolvers());
});
test('defaults to the current isolate package config', () async {
await resolveSources({
'a|web/main.dart': 'main() {}',
}, (resolver) async {
var buildResolversId =
AssetId('build_resolvers', 'lib/build_resolvers.dart');
var lib = await resolver.libraryFor(buildResolversId);
var currentPackageConfig =
await loadPackageConfigUri((await Isolate.packageConfig)!);
var expectedVersion =
currentPackageConfig['build_resolvers']!.languageVersion!;
expect(lib.languageVersion.effective.major, expectedVersion.major);
expect(lib.languageVersion.effective.minor, expectedVersion.minor);
}, resolvers: AnalyzerResolvers());
});
test('uses the overridden package config if provided', () async {
// An arbitrary past version that could never be selected for this
// package.
var customVersion = LanguageVersion(2, 1);
var customPackageConfig = PackageConfig([
Package('a', Uri.file('/fake/a/'),
packageUriRoot: Uri.file('/fake/a/lib/'),
languageVersion: customVersion)
]);
await resolveSources({
'a|web/main.dart': 'main() {}',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
expect(lib.languageVersion.effective.major, customVersion.major);
expect(lib.languageVersion.effective.minor, customVersion.minor);
}, resolvers: AnalyzerResolvers(null, null, customPackageConfig));
});
test('gives the current language version if not provided', () async {
var customPackageConfig = PackageConfig([
Package('a', Uri.file('/fake/a/'),
packageUriRoot: Uri.file('/fake/a/lib/'), languageVersion: null),
]);
await resolveSources({
'a|web/main.dart': 'main() {}',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
expect(lib.languageVersion.effective.major, sdkLanguageVersion.major);
expect(lib.languageVersion.effective.minor, sdkLanguageVersion.minor);
}, resolvers: AnalyzerResolvers(null, null, customPackageConfig));
});
test('allows a version of analyzer compatibile with the current sdk',
() async {
var originalLevel = Logger.root.level;
Logger.root.level = Level.WARNING;
var listener = Logger.root.onRecord.listen((record) {
fail('Got an unexpected warning during analysis:\n\n$record');
});
addTearDown(() {
Logger.root.level = originalLevel;
listener.cancel();
});
await resolveSources({
'a|web/main.dart': 'main() {}',
}, (resolver) async {
await resolver.libraryFor(entryPoint);
}, resolvers: AnalyzerResolvers());
}, skip: _skipOnPreRelease);
});
group('assets that aren\'t a transitive import of input', () {
Future _runWith(Future Function(Resolver) test) {
return resolveSources({
'a|web/main.dart': '''
main() {}
''',
'a|lib/other.dart': '''
library other;
'''
}, test, resolvers: AnalyzerResolvers());
}
final otherId = AssetId.parse('a|lib/other.dart');
test('can be resolved', () {
return _runWith((resolver) async {
final main = await resolver.libraryFor(entryPoint);
expect(main, isNotNull);
final other = await resolver.libraryFor(otherId);
expect(other.name, 'other');
});
});
test('are included in library stream', () {
return _runWith((resolver) async {
await expectLater(
resolver.libraries.map((l) => l.name), neverEmits('other'));
await resolver.libraryFor(otherId);
await expectLater(
resolver.libraries.map((l) => l.name), emitsThrough('other'));
});
});
test('can be found by name', () {
return _runWith((resolver) async {
await resolver.libraryFor(otherId);
await expectLater(
resolver.findLibraryByName('other'), completion(isNotNull));
});
});
});
test('handles missing files', () {
return resolveSources({
'a|web/main.dart': '''
import 'package:b/missing.dart';
part 'missing.g.dart';
main() {
} ''',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
expect(lib.parts2.length, 1);
expect(lib.parts2.whereType<DirectiveUriWithSource>(), isEmpty);
}, resolvers: AnalyzerResolvers());
});
test('handles discovering previously missing parts', () async {
var resolvers = AnalyzerResolvers();
await resolveSources({
'a|web/main.dart': '''
part 'main.g.dart';
class A implements B {}
''',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
var clazz = lib.getClass('A');
expect(clazz, isNotNull);
expect(clazz!.interfaces, isEmpty);
}, resolvers: resolvers);
await resolveSources({
'a|web/main.dart': '''
part 'main.g.dart';
class A implements B {}
''',
'a|web/main.g.dart': '''
part of 'main.dart';
class B {}
''',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
var clazz = lib.getClass('A');
expect(clazz, isNotNull);
expect(clazz!.interfaces, hasLength(1));
expect(clazz.interfaces.first.getDisplayString(withNullability: false),
'B');
}, resolvers: resolvers);
});
test('should list all libraries', () {
return resolveSources({
'a|web/main.dart': '''
library a.main;
import 'package:a/a.dart';
import 'package:a/b.dart';
export 'package:a/d.dart';
''',
'a|lib/a.dart': 'library a.a;\n import "package:a/c.dart";',
'a|lib/b.dart': 'library a.b;\n import "c.dart";',
'a|lib/c.dart': 'library a.c;',
'a|lib/d.dart': 'library a.d;'
}, (resolver) async {
var libs = await resolver.libraries.where((l) => !l.isInSdk).toList();
expect(
libs.map((l) => l.name),
unorderedEquals([
'a.main',
'a.a',
'a.b',
'a.c',
'a.d',
]));
}, resolvers: AnalyzerResolvers());
});
test('should resolve types and library uris', () {
return resolveSources({
'a|web/main.dart': '''
// dart and dart-ext uris should be ignored
import 'dart:core';
import 'dart-ext:some-ext';
// package: and relative uris should be available
import 'package:a/a.dart';
import 'package:a/b.dart';
import 'sub_dir/d.dart';
class Foo {}
''',
'a|lib/a.dart': 'library a.a;\n import "package:a/c.dart";',
'a|lib/b.dart': 'library a.b;\n import "c.dart";',
'a|lib/c.dart': '''
library a.c;
class Bar {}
''',
'a|web/sub_dir/d.dart': '''
library a.web.sub_dir.d;
class Baz{}
''',
}, (resolver) async {
var a = await resolver.findLibraryByName('a.a');
expect(a, isNotNull);
var main = await resolver.findLibraryByName('');
expect(main, isNotNull);
}, resolvers: AnalyzerResolvers());
});
test('resolves constants transitively', () {
return resolveSources({
'a|web/main.dart': '''
library web.main;
import 'package:a/dont_resolve.dart';
export 'package:a/dont_resolve.dart';
class Foo extends Bar {}
''',
'a|lib/dont_resolve.dart': '''
library a.dont_resolve;
const int annotation = 0;
@annotation
class Bar {}''',
}, (resolver) async {
var main = (await resolver.findLibraryByName('web.main'))!;
var meta = main.getClass('Foo')!.supertype!.element2.metadata[0];
expect(meta, isNotNull);
expect(meta.computeConstantValue()?.toIntValue(), 0);
}, resolvers: AnalyzerResolvers());
});
test('handles circular imports', () {
return resolveSources({
'a|web/main.dart': '''
library main;
import 'package:a/a.dart'; ''',
'a|lib/a.dart': '''
library a;
import 'package:a/b.dart'; ''',
'a|lib/b.dart': '''
library b;
import 'package:a/a.dart'; ''',
}, (resolver) async {
var libs = await resolver.libraries.map((lib) => lib.name).toList();
expect(libs.contains('a'), isTrue);
expect(libs.contains('b'), isTrue);
}, resolvers: AnalyzerResolvers());
});
test('assetIdForElement', () {
return resolveSources({
'a|lib/a.dart': '''
import 'b.dart';
main() {
SomeClass();
} ''',
'a|lib/b.dart': '''
class SomeClass {}
''',
}, (resolver) async {
var entry = await resolver.libraryFor(AssetId('a', 'lib/a.dart'));
var classDefinition = entry.importedLibraries
.map((l) => l.getClass('SomeClass'))
.singleWhere((c) => c != null)!;
expect(await resolver.assetIdForElement(classDefinition),
AssetId('a', 'lib/b.dart'));
}, resolvers: AnalyzerResolvers());
});
test('assetIdForElement throws for ambiguous elements', () {
return resolveSources({
'a|lib/a.dart': '''
import 'b.dart';
import 'c.dart';
@SomeClass()
main() {}
''',
'a|lib/b.dart': '''
class SomeClass {}
''',
'a|lib/c.dart': '''
class SomeClass {}
''',
}, (resolver) async {
var entry = await resolver.libraryFor(AssetId('a', 'lib/a.dart'));
final element = entry.topLevelElements
.firstWhere((e) => e is FunctionElement && e.name == 'main')
.metadata
.single
.element!;
await expectLater(() => resolver.assetIdForElement(element),
throwsA(isA<UnresolvableAssetException>()));
}, resolvers: AnalyzerResolvers());
});
test('Respects withEnabledExperiments', () async {
Logger.root.level = Level.ALL;
Logger.root.onRecord.listen(print);
await withEnabledExperiments(
() => resolveSources({
'a|web/main.dart': '''
// @dart=${sdkLanguageVersion.major}.${sdkLanguageVersion.minor}
int? get x => 1;
''',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
expect(lib.languageVersion.effective.major,
sdkLanguageVersion.major);
expect(lib.languageVersion.effective.minor,
sdkLanguageVersion.minor);
var errors = await lib.session.getErrors('/a/web/main.dart')
as ErrorsResult;
expect(errors.errors, isEmpty);
}, resolvers: AnalyzerResolvers()),
['non-nullable']);
}, skip: _skipOnPreRelease);
test('can get a new analysis session after resolving additional assets',
() async {
var resolvers = AnalyzerResolvers();
await resolveSources({
'a|web/main.dart': '',
'a|web/other.dart': '',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
expect(await resolver.isLibrary(AssetId('a', 'web/other.dart')), true);
var newLib =
await resolver.libraryFor(await resolver.assetIdForElement(lib));
expect(await newLib.session.getResolvedLibraryByElement(newLib),
isA<ResolvedLibraryResult>());
}, resolvers: resolvers);
});
group('syntax errors', () {
test('are reported', () {
return resolveSources({
'a|errors.dart': '''
library a_library;
void withSyntaxErrors() {
String x = ;
}
''',
}, (resolver) async {
await expectLater(
resolver.libraryFor(AssetId.parse('a|errors.dart')),
throwsA(isA<SyntaxErrorInAssetException>()),
);
await expectLater(
resolver.compilationUnitFor(AssetId.parse('a|errors.dart')),
throwsA(isA<SyntaxErrorInAssetException>()),
);
});
});
test('are reported for part files with errors', () {
return resolveSources({
'a|lib.dart': '''
library a_library;
part 'errors.dart';
part 'does_not_exist.dart';
''',
'a|errors.dart': '''
part of 'lib.dart';
void withSyntaxErrors() {
String x = ;
}
''',
}, (resolver) async {
await expectLater(
resolver.libraryFor(AssetId.parse('a|lib.dart')),
throwsA(
isA<SyntaxErrorInAssetException>()
.having((e) => e.syntaxErrors, 'syntaxErrors', hasLength(1)),
),
);
await expectLater(
resolver.compilationUnitFor(AssetId.parse('a|errors.dart')),
throwsA(
isA<SyntaxErrorInAssetException>()
.having((e) => e.syntaxErrors, 'syntaxErrors', hasLength(1)),
),
);
});
});
test('are not reported when disabled', () {
return resolveSources({
'a|errors.dart': '''
library a_library;
void withSyntaxErrors() {
String x = ;
}
''',
}, (resolver) async {
await expectLater(
resolver.libraryFor(AssetId.parse('a|errors.dart'),
allowSyntaxErrors: true),
completion(isNotNull),
);
await expectLater(
resolver.compilationUnitFor(AssetId.parse('a|errors.dart'),
allowSyntaxErrors: true),
completion(isNotNull),
);
});
});
test('are truncated if necessary', () {
return resolveSources({
'a|errors.dart': '''
library a_library;
void withSyntaxErrors() {
String x = ;
String x = ;
String x = ;
String x = ;
String x = ;
}
''',
}, (resolver) async {
var expectation = throwsA(
isA<SyntaxErrorInAssetException>().having(
(e) => e.toString(),
'toString()',
contains(RegExp(r'And \d more')),
),
);
await expectLater(
resolver.libraryFor(AssetId.parse('a|errors.dart')),
expectation,
);
await expectLater(
resolver.compilationUnitFor(AssetId.parse('a|errors.dart')),
expectation,
);
});
});
test('do not report semantic errors', () {
return resolveSources({
'a|errors.dart': '''
library a_library;
void withSemanticErrors() {
String x = withSemanticErrors();
String x = null;
}
''',
}, (resolver) async {
await expectLater(
resolver.libraryFor(AssetId.parse('a|errors.dart')),
completion(isNotNull),
);
await expectLater(
resolver.compilationUnitFor(AssetId.parse('a|errors.dart')),
completion(isNotNull),
);
});
});
});
});
test('throws when reading a part-of file', () {
return resolveSources(
{
'a|lib/a.dart': '''
part 'b.dart';
''',
'a|lib/b.dart': '''
part of 'a.dart';
'''
},
(resolver) async {
final assetId = AssetId.parse('a|lib/b.dart');
await expectLater(
() => resolver.libraryFor(assetId),
throwsA(const TypeMatcher<NonLibraryAssetException>()
.having((e) => e.assetId, 'assetId', equals(assetId))),
);
},
);
});
group('The ${isFlutter ? 'flutter' : 'dart'} sdk', () {
test('can${isFlutter ? '' : ' not'} resolve types from dart:ui', () async {
return resolveSources({
'a|lib/a.dart': '''
import 'dart:ui';
class MyClass {
final Color color;
MyClass(this.color);
} ''',
}, (resolver) async {
var entry = await resolver.libraryFor(AssetId('a', 'lib/a.dart'));
var classDefinition = entry.getClass('MyClass')!;
var color = classDefinition.getField('color')!;
if (isFlutter) {
expect(color.type.element2!.name, equals('Color'));
expect(color.type.element2!.library!.name, equals('dart.ui'));
expect(
color.type.element2!.library!.definingCompilationUnit.source.uri
.toString(),
equals('dart:ui'));
} else {
expect(color.type.element2!.name, equals('dynamic'));
}
}, resolvers: AnalyzerResolvers());
});
});
test('generated part files are not considered libraries', () async {
var writer = InMemoryAssetWriter();
var reader = InMemoryAssetReader.shareAssetCache(writer.assets);
var input = AssetId('a', 'lib/input.dart');
writer.assets[input] = utf8.encode("part 'input.a.dart';");
var builder = TestBuilder(
buildExtensions: {
'.dart': ['.a.dart']
},
build: (buildStep, buildExtensions) async {
var isLibrary = await buildStep.resolver.isLibrary(buildStep.inputId);
if (buildStep.inputId == input) {
await buildStep.writeAsString(
buildStep.inputId
.changeExtension(buildExtensions['.dart']!.first),
"part of 'input.dart';");
expect(isLibrary, true);
} else {
expect(isLibrary, false,
reason:
'${buildStep.inputId} should not be considered a library');
}
});
var resolvers = AnalyzerResolvers();
await runBuilder(builder, [input], reader, writer, resolvers);
await runBuilder(
builder, [input.changeExtension('.a.dart')], reader, writer, resolvers);
});
test('missing files are not considered libraries', () async {
var writer = InMemoryAssetWriter();
var reader = InMemoryAssetReader.shareAssetCache(writer.assets);
var input = AssetId('a', 'lib/input.dart');
writer.assets[input] = utf8.encode('void doStuff() {}');
var builder = TestBuilder(
buildExtensions: {
'.dart': ['.a.dart']
},
build: expectAsync2((buildStep, _) async {
expect(
await buildStep.resolver.isLibrary(
buildStep.inputId.changeExtension('doesnotexist.dart')),
false);
}));
var resolvers = AnalyzerResolvers();
await runBuilder(builder, [input], reader, writer, resolvers);
});
test('assets with extensions other than `.dart` are not considered libraries',
() async {
var writer = InMemoryAssetWriter();
var reader = InMemoryAssetReader.shareAssetCache(writer.assets);
var input = AssetId('a', 'lib/input.dart');
writer.assets[input] = utf8.encode('void doStuff() {}');
var otherFile = AssetId('a', 'lib/input.notdart');
writer.assets[otherFile] = utf8.encode('Not a Dart file');
var builder = TestBuilder(
buildExtensions: {
'.dart': ['.a.dart']
},
build: expectAsync2((buildStep, _) async {
var other = buildStep.inputId.changeExtension('.notdart');
expect(await buildStep.canRead(other), true);
expect(await buildStep.resolver.isLibrary(other), false);
}));
var resolvers = AnalyzerResolvers();
await runBuilder(builder, [input], reader, writer, resolvers);
});
group('compilationUnitFor', () {
test('can parse a given input', () {
return resolveSources({
'a|web/main.dart': ' main() {}',
}, (resolver) async {
var unit = await resolver.compilationUnitFor(entryPoint);
expect(unit, isNotNull);
expect(unit.declarations.length, 1);
expect(
unit.declarations.first,
isA<FunctionDeclaration>()
.having((d) => d.name2.lexeme, 'main', 'main'));
}, resolvers: AnalyzerResolvers());
});
});
group('astNodeFor', () {
test('can return an unresolved ast', () {
return resolveSources({
'a|web/main.dart': ' main() {}',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
var unit = await resolver.astNodeFor(lib.topLevelElements.first);
expect(unit, isA<FunctionDeclaration>());
expect(unit!.toSource(), 'main() {}');
expect((unit as FunctionDeclaration).declaredElement2, isNull);
}, resolvers: AnalyzerResolvers());
});
test('can return an resolved ast', () {
return resolveSources({
'a|web/main.dart': 'main() {}',
}, (resolver) async {
var lib = await resolver.libraryFor(entryPoint);
var unit = await resolver.astNodeFor(lib.topLevelElements.first,
resolve: true);
expect(
unit,
isA<FunctionDeclaration>()
.having((fd) => fd.toSource(), 'toSource()', 'main() {}')
.having(
(fd) => fd.declaredElement2, 'declaredElement', isNotNull),
);
}, resolvers: AnalyzerResolvers());
});
});
}
final _skipOnPreRelease =
Version.parse(Platform.version.split(' ').first).isPreRelease
? 'Skipped on prerelease sdks'
: null;
| build/build_resolvers/test/resolver_test.dart/0 | {'file_path': 'build/build_resolvers/test/resolver_test.dart', 'repo_id': 'build', 'token_count': 12636} |
// 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 'dart:io';
import 'package:build_runner/src/entrypoint/options.dart';
import 'package:http_multi_server/http_multi_server.dart';
import 'package:logging/logging.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart' as shelf_io;
import '../server/server.dart';
import 'daemon_builder.dart';
final _logger = Logger('AssetServer');
class AssetServer {
final HttpServer _server;
AssetServer._(this._server);
int get port => _server.port;
Future<void> stop() => _server.close(force: true);
static Future<AssetServer> run(
DaemonOptions options,
BuildRunnerDaemonBuilder builder,
String rootPackage,
) async {
var server = await HttpMultiServer.loopback(0);
var cascade = Cascade().add((_) async {
await builder.building;
return Response.notFound('');
}).add(AssetHandler(builder.reader, rootPackage).handle);
var pipeline = Pipeline();
if (options.logRequests) {
pipeline = pipeline.addMiddleware(
logRequests(logger: (message, isError) => _logger.finest(message)));
}
shelf_io.serveRequests(server, pipeline.addHandler(cascade.handler));
return AssetServer._(server);
}
}
| build/build_runner/lib/src/daemon/asset_server.dart/0 | {'file_path': 'build/build_runner/lib/src/daemon/asset_server.dart', 'repo_id': 'build', 'token_count': 489} |
// 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:io';
import 'package:build/build.dart';
import 'package:build_runner/src/generate/terminator.dart';
import 'package:build_runner_core/build_runner_core.dart';
import 'package:logging/logging.dart';
import 'package:shelf/shelf.dart';
import 'package:watcher/watcher.dart';
import '../logging/std_io_logging.dart';
import '../package_graph/build_config_overrides.dart';
import '../server/server.dart';
import 'watch_impl.dart' as watch_impl;
/// Runs all of the BuilderApplications in [builders] once.
///
/// By default, the user will be prompted to delete any files which already
/// exist but were not generated by this specific build script. The
/// [deleteFilesByDefault] option can be set to `true` to skip this prompt.
///
/// A [packageGraph] may be supplied, otherwise one will be constructed using
/// [PackageGraph.forThisPackage]. The default functionality assumes you are
/// running in the root directory of a package, with both a `pubspec.yaml` and
/// `.dart_tool/package_config.json` file present.
///
/// A [reader] and [writer] may also be supplied, which can read/write assets
/// to arbitrary locations or file systems. By default they will write directly
/// to the root package directory, and will use the [packageGraph] to know where
/// to read files from.
///
/// Logging may be customized by passing a custom [logLevel] below which logs
/// will be ignored, as well as an [onLog] handler which defaults to [print].
///
/// The [terminateEventStream] is a stream which can send termination events.
/// By default the [ProcessSignal.sigint] stream is used. In this mode, it
/// will simply consume the first event and allow the build to continue.
/// Multiple termination events will cause a normal shutdown.
///
/// If [outputSymlinksOnly] is `true`, then the merged output directories will
/// contain only symlinks, which is much faster but not generally suitable for
/// deployment.
///
/// If [verbose] is `true` then verbose logging will be enabled. This changes
/// the default [logLevel] to [Level.ALL] and removes stack frame folding, among
/// other things.
Future<BuildResult> build(List<BuilderApplication> builders,
{bool? deleteFilesByDefault,
bool? assumeTty,
String? configKey,
PackageGraph? packageGraph,
RunnerAssetReader? reader,
RunnerAssetWriter? writer,
Resolvers? resolvers,
Level? logLevel,
void Function(LogRecord)? onLog,
Stream<ProcessSignal>? terminateEventStream,
bool? enableLowResourcesMode,
Set<BuildDirectory>? buildDirs,
bool? outputSymlinksOnly,
bool? trackPerformance,
bool? skipBuildScriptCheck,
bool? verbose,
bool? isReleaseBuild,
Map<String, Map<String, dynamic>>? builderConfigOverrides,
String? logPerformanceDir,
Set<BuildFilter>? buildFilters}) async {
builderConfigOverrides ??= const {};
buildDirs ??= <BuildDirectory>{};
buildFilters ??= <BuildFilter>{};
deleteFilesByDefault ??= false;
enableLowResourcesMode ??= false;
isReleaseBuild ??= false;
outputSymlinksOnly ??= false;
packageGraph ??= await PackageGraph.forThisPackage();
skipBuildScriptCheck ??= false;
trackPerformance ??= false;
verbose ??= false;
var environment = OverrideableEnvironment(
IOEnvironment(
packageGraph,
assumeTty: assumeTty,
outputSymlinksOnly: outputSymlinksOnly,
),
reader: reader,
writer: writer,
onLog: onLog ?? stdIOLogListener(assumeTty: assumeTty, verbose: verbose));
var logSubscription =
LogSubscription(environment, verbose: verbose, logLevel: logLevel);
var options = await BuildOptions.create(
logSubscription,
deleteFilesByDefault: deleteFilesByDefault,
packageGraph: packageGraph,
skipBuildScriptCheck: skipBuildScriptCheck,
overrideBuildConfig: await findBuildConfigOverrides(
packageGraph, environment.reader,
configKey: configKey),
enableLowResourcesMode: enableLowResourcesMode,
trackPerformance: trackPerformance,
logPerformanceDir: logPerformanceDir,
resolvers: resolvers,
);
var terminator = Terminator(terminateEventStream);
try {
var build = await BuildRunner.create(
options,
environment,
builders,
builderConfigOverrides,
isReleaseBuild: isReleaseBuild,
);
var result =
await build.run({}, buildDirs: buildDirs, buildFilters: buildFilters);
await build.beforeExit();
return result;
} finally {
await terminator.cancel();
await options.logListener.cancel();
}
}
/// Same as [build], except it watches the file system and re-runs builds
/// automatically.
///
/// Call [ServeHandler.handlerFor] to create a [Handler] for use with
/// `package:shelf`. Requests for assets will be blocked while builds are
/// running then served with the latest version of the asset. Only source and
/// generated assets can be served through this handler.
///
/// The [debounceDelay] controls how often builds will run. As long as files
/// keep changing with less than that amount of time apart, builds will be put
/// off.
///
/// The [directoryWatcherFactory] allows you to inject a way of creating custom
/// `DirectoryWatcher`s. By default a normal `DirectoryWatcher` will be used.
///
/// The [terminateEventStream] is a stream which can send termination events.
/// By default the [ProcessSignal.sigint] stream is used. In this mode, the
/// first event will allow any ongoing builds to finish, and then the program
/// will complete normally. Subsequent events are not handled (and will
/// typically cause a shutdown).
Future<ServeHandler> watch(List<BuilderApplication> builders,
{bool? deleteFilesByDefault,
bool? assumeTty,
String? configKey,
PackageGraph? packageGraph,
RunnerAssetReader? reader,
RunnerAssetWriter? writer,
Resolvers? resolvers,
Level? logLevel,
void Function(LogRecord)? onLog,
Duration? debounceDelay,
required DirectoryWatcher Function(String) directoryWatcherFactory,
Stream<ProcessSignal>? terminateEventStream,
bool? enableLowResourcesMode,
Set<BuildDirectory>? buildDirs,
bool? outputSymlinksOnly,
bool? trackPerformance,
bool? skipBuildScriptCheck,
bool? verbose,
bool? isReleaseBuild,
Map<String, Map<String, dynamic>>? builderConfigOverrides,
String? logPerformanceDir,
Set<BuildFilter>? buildFilters}) =>
watch_impl.watch(
builders,
assumeTty: assumeTty,
deleteFilesByDefault: deleteFilesByDefault,
configKey: configKey,
packageGraph: packageGraph,
reader: reader,
writer: writer,
resolvers: resolvers,
logLevel: logLevel,
onLog: onLog,
debounceDelay: debounceDelay,
directoryWatcherFactory: directoryWatcherFactory,
terminateEventStream: terminateEventStream,
enableLowResourcesMode: enableLowResourcesMode,
buildDirs: buildDirs,
outputSymlinksOnly: outputSymlinksOnly,
trackPerformance: trackPerformance,
skipBuildScriptCheck: skipBuildScriptCheck,
verbose: verbose,
builderConfigOverrides: builderConfigOverrides,
isReleaseBuild: isReleaseBuild,
logPerformanceDir: logPerformanceDir,
buildFilters: buildFilters,
);
| build/build_runner/lib/src/generate/build.dart/0 | {'file_path': 'build/build_runner/lib/src/generate/build.dart', 'repo_id': 'build', 'token_count': 2429} |
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:build/build.dart';
import 'package:build_runner/src/watcher/asset_change.dart';
import 'package:watcher/watcher.dart';
/// Merges [AssetChange] events.
///
/// For example, if an asset was added then immediately deleted, no event will
/// be recorded for the given asset.
Map<AssetId, ChangeType> collectChanges(List<List<AssetChange>> changes) {
var changeMap = <AssetId, ChangeType>{};
for (var change in changes.expand((l) => l)) {
var originalChangeType = changeMap[change.id];
if (originalChangeType != null) {
switch (originalChangeType) {
case ChangeType.ADD:
if (change.type == ChangeType.REMOVE) {
// ADD followed by REMOVE, just remove the change.
changeMap.remove(change.id);
}
break;
case ChangeType.REMOVE:
if (change.type == ChangeType.ADD) {
// REMOVE followed by ADD, convert to a MODIFY
changeMap[change.id] = ChangeType.MODIFY;
} else if (change.type == ChangeType.MODIFY) {
// REMOVE followed by MODIFY isn't sensible, just throw.
throw StateError(
'Internal error, got REMOVE event followed by MODIFY event for '
'${change.id}.');
}
break;
case ChangeType.MODIFY:
if (change.type == ChangeType.REMOVE) {
// MODIFY followed by REMOVE, convert to REMOVE
changeMap[change.id] = change.type;
} else if (change.type == ChangeType.ADD) {
// MODIFY followed by ADD isn't sensible, just throw.
throw StateError(
'Internal error, got MODIFY event followed by ADD event for '
'${change.id}.');
}
break;
}
} else {
changeMap[change.id] = change.type;
}
}
return changeMap;
}
| build/build_runner/lib/src/watcher/collect_changes.dart/0 | {'file_path': 'build/build_runner/lib/src/watcher/collect_changes.dart', 'repo_id': 'build', 'token_count': 871} |
// 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/common.dart';
import 'package:async/async.dart';
import 'package:build_runner/src/generate/watch_impl.dart' as watch_impl;
import 'package:build_runner/src/server/server.dart';
import 'package:build_runner_core/build_runner_core.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as path;
import 'package:shelf/shelf.dart';
import 'package:test/test.dart';
void main() {
group('ServeHandler', () {
late InMemoryRunnerAssetWriter writer;
setUp(() async {
_terminateServeController = StreamController();
writer = InMemoryRunnerAssetWriter();
await writer.writeAsString(
makeAssetId('a|.dart_tool/package_config.json'),
jsonEncode({
'configVersion': 2,
'packages': [
{
'name': 'a',
'rootUri': 'file://fake/pkg/path',
'packageUri': 'lib/'
},
],
}));
});
tearDown(() async {
FakeWatcher.watchers.clear();
await terminateServe();
});
test('does basic builds', () async {
var handler = await createHandler(
[applyToRoot(TestBuilder())], {'a|web/a.txt': 'a'}, writer);
var results = StreamQueue(handler.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);
});
test('blocks serving files until the build is done', () async {
var buildBlocker1 = Completer<void>();
var nextBuildBlocker = buildBlocker1.future;
var handler = await createHandler(
[applyToRoot(TestBuilder(extraWork: (_, __) => nextBuildBlocker))],
{'a|web/a.txt': 'a'},
writer);
var webHandler = handler.handlerFor('web');
var results = StreamQueue(handler.buildResults);
// Give the build enough time to get started.
await wait(100);
var request = Request('GET', Uri.parse('http://localhost:8000/a.txt'));
unawaited((webHandler(request) as Future<Response>)
.then(expectAsync1((Response response) {
expect(buildBlocker1.isCompleted, isTrue,
reason: 'Server shouldn\'t respond until builds are done.');
})));
await wait(250);
buildBlocker1.complete();
var result = await results.next;
checkBuild(result, outputs: {'a|web/a.txt.copy': 'a'}, writer: writer);
/// Next request completes right away.
var buildBlocker2 = Completer<void>();
unawaited((webHandler(request) as Future<Response>)
.then(expectAsync1((response) {
expect(buildBlocker1.isCompleted, isTrue);
expect(buildBlocker2.isCompleted, isFalse);
})));
/// Make an edit to force another build, and we should block again.
nextBuildBlocker = buildBlocker2.future;
await writer.writeAsString(makeAssetId('a|web/a.txt'), 'b');
// Give the build enough time to get started.
await wait(500);
var done = Completer<void>();
unawaited((webHandler(request) as Future<Response>)
.then(expectAsync1((response) {
expect(buildBlocker1.isCompleted, isTrue);
expect(buildBlocker2.isCompleted, isTrue);
done.complete();
})));
await wait(250);
buildBlocker2.complete();
result = await results.next;
checkBuild(result, outputs: {'a|web/a.txt.copy': 'b'}, writer: writer);
/// Make sure we actually see the final request finish.
return done.future;
});
});
}
final _debounceDelay = Duration(milliseconds: 10);
StreamController<ProcessSignal>? _terminateServeController;
/// Start serving files and running builds.
Future<ServeHandler> createHandler(List<BuilderApplication> builders,
Map<String, String> inputs, InMemoryRunnerAssetWriter writer) async {
await Future.wait(inputs.keys.map((serializedId) async {
await writer.writeAsString(
makeAssetId(serializedId), inputs[serializedId]!);
}));
final packageGraph =
buildPackageGraph({rootPackage('a', path: path.absolute('a')): []});
final reader = InMemoryRunnerAssetReader.shareAssetCache(writer.assets,
rootPackage: packageGraph.root.name);
FakeWatcher watcherFactory(String path) => FakeWatcher(path);
return watch_impl.watch(builders,
deleteFilesByDefault: true,
debounceDelay: _debounceDelay,
directoryWatcherFactory: watcherFactory,
reader: reader,
writer: writer,
packageGraph: packageGraph,
terminateEventStream: _terminateServeController!.stream,
logLevel: Level.OFF,
skipBuildScriptCheck: true);
}
/// Tells the program to terminate.
Future terminateServe() {
/// Can add any type of event.
_terminateServeController!.add(ProcessSignal.sigabrt);
return _terminateServeController!.close();
}
| build/build_runner/test/generate/serve_test.dart/0 | {'file_path': 'build/build_runner/test/generate/serve_test.dart', 'repo_id': 'build', 'token_count': 2029} |
// 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 'dart:convert';
import 'dart:html';
import 'dart:js' as js;
final _graphReference = js.context[r'$build']!;
final _details = document.getElementById('details')!;
void main() async {
var filterBox = document.getElementById('filter') as InputElement;
var searchBox = document.getElementById('searchbox') as InputElement;
var searchForm = document.getElementById('searchform')!;
searchForm.onSubmit.listen((e) {
e.preventDefault();
_focus(searchBox.value!.trim(),
filter: filterBox.value!.isNotEmpty ? filterBox.value : null);
});
_graphReference.callMethod('initializeGraph', [_focus]);
}
void _error(String message, [Object? error, StackTrace? stack]) {
var msg = [message, error, stack].where((e) => e != null).join('\n');
_details.innerHtml = '<pre>$msg</pre>';
}
Future _focus(String query, {String? filter}) async {
if (query.isEmpty) {
_error('Provide content in the query.');
return;
}
Map nodeInfo;
var queryParams = {'q': query};
if (filter != null) queryParams['f'] = filter;
var uri = Uri(queryParameters: queryParams);
try {
nodeInfo = json.decode(await HttpRequest.getString(uri.toString()))
as Map<String, dynamic>;
} catch (e, stack) {
var msg = 'Error requesting query "$query".';
if (e is ProgressEvent) {
var target = e.target;
if (target is HttpRequest) {
msg = [
msg,
'${target.status} ${target.statusText}',
target.responseText
].join('\n');
}
_error(msg);
} else {
_error(msg, e, stack);
}
return;
}
var graphData = {'edges': nodeInfo['edges'], 'nodes': nodeInfo['nodes']};
_graphReference.callMethod('setData', [js.JsObject.jsify(graphData)]);
var primaryNode = nodeInfo['primary'];
_details.innerHtml = '<strong>ID:</strong> ${primaryNode['id']} <br />'
'<strong>Type:</strong> ${primaryNode['type']}<br />'
'<strong>Hidden:</strong> ${primaryNode['hidden']} <br />'
'<strong>State:</strong> ${primaryNode['state']} <br />'
'<strong>Was Output:</strong> ${primaryNode['wasOutput']} <br />'
'<strong>Failed:</strong> ${primaryNode['isFailure']} <br />'
'<strong>Phase:</strong> ${primaryNode['phaseNumber']} <br />'
'<strong>Glob:</strong> ${primaryNode['glob']}<br />'
'<strong>Last Digest:</strong> ${primaryNode['lastKnownDigest']}<br />';
}
| build/build_runner/web/graph_viz_main.dart/0 | {'file_path': 'build/build_runner/web/graph_viz_main.dart', 'repo_id': 'build', 'token_count': 999} |
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'package:build/build.dart';
import 'package:build_runner_core/build_runner_core.dart';
import '../generate/phase.dart';
import '../util/build_dirs.dart';
import 'graph.dart';
import 'node.dart';
/// A cache of the results of checking whether outputs from optional build steps
/// were required by in the current build.
///
/// An optional output becomes required if:
/// - Any of it's transitive outputs is required (based on the criteria below).
/// - It was output by the same build step as any required output.
///
/// Any outputs from non-optional phases are considered required, unless the
/// following are all true.
/// - [_buildDirs] is non-empty.
/// - The output lives in a non-lib directory.
/// - The outputs path is not prefixed by one of [_buildDirs].
/// - If [_buildFilters] is non-empty and the output doesn't match one of the
/// filters.
///
/// Non-required optional output might still exist in the generated directory
/// and the asset graph but we should avoid serving them, outputting them in
/// the merged directories, or considering a failed output as an overall.
class OptionalOutputTracker {
final _checkedOutputs = <AssetId, bool>{};
final AssetGraph _assetGraph;
final Set<String> _buildDirs;
final Set<BuildFilter> _buildFilters;
final List<BuildPhase> _buildPhases;
OptionalOutputTracker(
this._assetGraph, this._buildDirs, this._buildFilters, this._buildPhases);
/// Returns whether [output] is required.
///
/// If necessary crawls transitive outputs that read [output] or any other
/// assets generated by the same phase until it finds one which is required.
///
/// [currentlyChecking] is used to aovid repeatedly checking the same outputs.
bool isRequired(AssetId output, [Set<AssetId>? currentlyChecking]) {
currentlyChecking ??= <AssetId>{};
if (currentlyChecking.contains(output)) return false;
currentlyChecking.add(output);
final node = _assetGraph.get(output);
if (node is! GeneratedAssetNode) return true;
final phase = _buildPhases[node.phaseNumber];
if (!phase.isOptional &&
shouldBuildForDirs(output, _buildDirs, _buildFilters, phase)) {
return true;
}
return _checkedOutputs.putIfAbsent(
output,
() =>
node.outputs.any((o) => isRequired(o, currentlyChecking)) ||
_assetGraph
.outputsForPhase(output.package, node.phaseNumber)
.where((n) => n.primaryInput == node.primaryInput)
.map((n) => n.id)
.any((o) => isRequired(o, currentlyChecking)));
}
/// Clears the cache of which assets were required.
///
/// If the tracker is used across multiple builds it must be reset in between
/// each one.
void reset() {
_checkedOutputs.clear();
}
}
| build/build_runner_core/lib/src/asset_graph/optional_output_tracker.dart/0 | {'file_path': 'build/build_runner_core/lib/src/asset_graph/optional_output_tracker.dart', 'repo_id': 'build', 'token_count': 972} |
// 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 'package:build/build.dart';
import 'package:build/experiments.dart';
import 'package:build_config/build_config.dart';
import 'package:build_resolvers/build_resolvers.dart';
import 'package:glob/glob.dart';
import 'package:logging/logging.dart';
import 'package:path/path.dart' as p;
import '../environment/build_environment.dart';
import '../package_graph/package_graph.dart';
import '../package_graph/target_graph.dart';
import 'exceptions.dart';
/// The default list of files visible for non-root packages.
///
/// This is also the default list of files for targets in non-root packages when
/// an explicit include is not provided.
const List<String> defaultNonRootVisibleAssets = [
'CHANGELOG*',
'lib/**',
'bin/**',
'LICENSE*',
'pubspec.yaml',
'README*',
];
/// The default list of files to include when an explicit include is not
/// provided.
///
/// This should be a superset of [defaultNonRootVisibleAssets].
const List<String> defaultRootPackageSources = [
'assets/**',
'benchmark/**',
'bin/**',
'CHANGELOG*',
'example/**',
'lib/**',
'test/**',
'tool/**',
'web/**',
'node/**',
'LICENSE*',
'pubspec.yaml',
'pubspec.lock',
'README*',
r'$package$',
];
final _logger = Logger('BuildOptions');
class LogSubscription {
factory LogSubscription(BuildEnvironment environment,
{bool verbose = false, Level? logLevel}) {
// Set up logging
logLevel ??= verbose ? Level.ALL : Level.INFO;
// Severe logs can fail the build and should always be shown.
if (logLevel == Level.OFF) logLevel = Level.SEVERE;
Logger.root.level = logLevel;
var logListener = Logger.root.onRecord.listen(environment.onLog);
return LogSubscription._(logListener);
}
LogSubscription._(this.logListener);
final StreamSubscription<LogRecord> logListener;
}
/// Describes a set of files that should be built.
class BuildFilter {
/// The package name glob that files must live under in order to match.
final Glob _package;
/// A glob for files under [_package] that must match.
final Glob _path;
BuildFilter(this._package, this._path);
/// Builds a [BuildFilter] from a command line argument.
///
/// Both relative paths and package: uris are supported. Relative
/// paths are treated as relative to the [rootPackage].
///
/// Globs are supported in package names and paths.
factory BuildFilter.fromArg(String arg, String rootPackage) {
var uri = Uri.parse(arg);
if (uri.scheme == 'package') {
var package = uri.pathSegments.first;
var glob = Glob(p.url.joinAll([
'lib',
...uri.pathSegments.skip(1),
]));
return BuildFilter(Glob(package), glob);
} else if (uri.scheme.isEmpty) {
return BuildFilter(Glob(rootPackage), Glob(uri.path));
} else {
throw FormatException('Unsupported scheme ${uri.scheme}', uri);
}
}
/// Returns whether or not [id] mathes this filter.
bool matches(AssetId id) =>
_package.matches(id.package) && _path.matches(id.path);
@override
int get hashCode => Object.hash(
_package.context,
_package.pattern,
_package.recursive,
_path.context,
_path.pattern,
_path.recursive,
);
@override
bool operator ==(Object other) =>
other is BuildFilter &&
other._path.context == _path.context &&
other._path.pattern == _path.pattern &&
other._path.recursive == _path.recursive &&
other._package.context == _package.context &&
other._package.pattern == _package.pattern &&
other._package.recursive == _package.recursive;
}
/// Manages setting up consistent defaults for all options and build modes.
class BuildOptions {
final bool deleteFilesByDefault;
final bool enableLowResourcesMode;
final StreamSubscription logListener;
/// If present, the path to a directory to write performance logs to.
final String? logPerformanceDir;
final PackageGraph packageGraph;
final Resolvers resolvers;
final TargetGraph targetGraph;
final bool trackPerformance;
// Watch mode options.
Duration debounceDelay;
// For testing only, skips the build script updates check.
bool skipBuildScriptCheck;
BuildOptions._({
required this.debounceDelay,
required this.deleteFilesByDefault,
required this.enableLowResourcesMode,
required this.logListener,
required this.packageGraph,
required this.skipBuildScriptCheck,
required this.trackPerformance,
required this.targetGraph,
required this.logPerformanceDir,
required this.resolvers,
});
/// Creates a [BuildOptions] with sane defaults.
///
/// NOTE: If a custom [resolvers] instance is passed it must ensure that it
/// enables [enabledExperiments] on any analysis options it creates.
static Future<BuildOptions> create(
LogSubscription logSubscription, {
Duration debounceDelay = const Duration(milliseconds: 250),
bool deleteFilesByDefault = false,
bool enableLowResourcesMode = false,
required PackageGraph packageGraph,
Map<String, BuildConfig> overrideBuildConfig = const {},
bool skipBuildScriptCheck = false,
bool trackPerformance = false,
String? logPerformanceDir,
Resolvers? resolvers,
}) async {
TargetGraph targetGraph;
try {
targetGraph = await TargetGraph.forPackageGraph(packageGraph,
overrideBuildConfig: overrideBuildConfig,
defaultRootPackageSources: defaultRootPackageSources,
requiredSourcePaths: [r'lib/$lib$'],
requiredRootSourcePaths: [r'$package$', r'lib/$lib$']);
} on BuildConfigParseException catch (e, s) {
_logger.severe('''
Failed to parse `build.yaml` for ${e.packageName}.
If you believe you have gotten this message in error, especially if using a new
feature, you may need to run `dart run build_runner clean` and then rebuild.
''', e.exception, s);
throw CannotBuildException();
}
/// Set up other defaults.
if (logPerformanceDir != null) {
// Requiring this to be under the root package allows us to use an
// `AssetWriter` to write logs.
if (!p.isWithin(p.current, logPerformanceDir)) {
_logger.severe('Performance logs may only be output under the root '
'package, but got `$logPerformanceDir` which is not.');
throw CannotBuildException();
}
trackPerformance = true;
}
resolvers ??= AnalyzerResolvers();
return BuildOptions._(
debounceDelay: debounceDelay,
deleteFilesByDefault: deleteFilesByDefault,
enableLowResourcesMode: enableLowResourcesMode,
logListener: logSubscription.logListener,
packageGraph: packageGraph,
skipBuildScriptCheck: skipBuildScriptCheck,
trackPerformance: trackPerformance,
targetGraph: targetGraph,
logPerformanceDir: logPerformanceDir,
resolvers: resolvers,
);
}
}
| build/build_runner_core/lib/src/generate/options.dart/0 | {'file_path': 'build/build_runner_core/lib/src/generate/options.dart', 'repo_id': 'build', 'token_count': 2381} |
// 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.
/// Checks whether [thisVersion] and [thatVersion] have the same semver
/// identifier without extra platform specific information.
bool isSameSdkVersion(String? thisVersion, String? thatVersion) =>
thisVersion?.split(' ').first == thatVersion?.split(' ').first;
| build/build_runner_core/lib/src/util/sdk_version_match.dart/0 | {'file_path': 'build/build_runner_core/lib/src/util/sdk_version_match.dart', 'repo_id': 'build', 'token_count': 126} |
name: c
version: 4.0.0
| build/build_runner_core/test/fixtures/with_dev_deps/pkg/c/pubspec.yaml/0 | {'file_path': 'build/build_runner_core/test/fixtures/with_dev_deps/pkg/c/pubspec.yaml', 'repo_id': 'build', 'token_count': 12} |
// 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';
// ignore: implementation_imports
import 'package:build/src/builder/logging.dart';
import 'package:logging/logging.dart';
import 'package:matcher/matcher.dart';
/// Executes [run] with a new [Logger], returning the resulting log records.
///
/// The returned [Stream] is _closed_ after the [run] function is executed. If
/// [run] returns a [Future], that future is awaited _before_ the stream is
/// closed.
///
/// ```dart
/// test('should log "uh oh!"', () async {
/// final logs = recordLogs(() => runBuilder());
/// expect(logs, emitsInOrder([
/// anyLogOf('uh oh!'),
/// ]);
/// });
/// ```
Stream<LogRecord> recordLogs(dynamic Function() run, {String name = ''}) {
final logger = Logger(name);
Timer.run(() async {
await scopeLogAsync(() => Future.value(run()), logger);
logger.clearListeners();
});
return logger.onRecord;
}
/// Matches [LogRecord] of any level whose message is [messageOrMatcher].
///
/// ```dart
/// anyLogOf('Hello World)'; // Exactly match 'Hello World'.
/// anyLogOf(contains('ERROR')); // Contains the sub-string 'ERROR'.
/// ```
Matcher anyLogOf(dynamic messageOrMatcher) =>
_LogRecordMatcher(anything, messageOrMatcher);
/// Matches [LogRecord] of [Level.INFO] where message is [messageOrMatcher].
Matcher infoLogOf(dynamic messageOrMatcher) =>
_LogRecordMatcher(Level.INFO, messageOrMatcher);
/// Matches [LogRecord] of [Level.WARNING] where message is [messageOrMatcher].
Matcher warningLogOf(dynamic messageOrMatcher) =>
_LogRecordMatcher(Level.WARNING, messageOrMatcher);
/// Matches [LogRecord] of [Level.SEVERE] where message is [messageOrMatcher].
Matcher severeLogOf(dynamic messageOrMatcher) =>
_LogRecordMatcher(Level.SEVERE, messageOrMatcher);
class _LogRecordMatcher extends Matcher {
final Matcher _level;
final Matcher _message;
_LogRecordMatcher(dynamic levelOr, dynamic messageOr)
: this._(levelOr is Matcher ? levelOr : equals(levelOr),
messageOr is Matcher ? messageOr : equals(messageOr));
_LogRecordMatcher._(this._level, this._message);
@override
Description describe(Description description) {
description.add('level: ');
_level.describe(description);
description.add(', message: ');
_message.describe(description);
return description;
}
@override
Description describeMismatch(
covariant LogRecord item, Description description, _, __) {
if (!_level.matches(item.level, {})) {
_level.describeMismatch(item.level, description, {}, false);
}
if (!_message.matches(item.message, {})) {
_message.describeMismatch(item.message, description, {}, false);
}
return description;
}
@override
bool matches(item, _) =>
item is LogRecord &&
_level.matches(item.level, {}) &&
_message.matches(item.message, {});
}
| build/build_test/lib/src/record_logs.dart/0 | {'file_path': 'build/build_test/lib/src/record_logs.dart', 'repo_id': 'build', 'token_count': 1027} |
// 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('$InMemoryAssetReader', () {
final packageName = 'some_pkg';
final libAsset = AssetId(packageName, 'lib/some_pkg.dart');
final testAsset = AssetId(packageName, 'test/some_test.dart');
late InMemoryAssetReader assetReader;
setUp(() {
var allAssets = {
libAsset: 'libAsset',
testAsset: 'testAsset',
};
assetReader = InMemoryAssetReader(
sourceAssets: allAssets,
rootPackage: packageName,
);
});
test('#findAssets should throw if rootPackage and package are not supplied',
() {
assetReader = InMemoryAssetReader();
expect(
() => assetReader.findAssets(Glob('lib/*.dart')),
throwsUnsupportedError,
);
});
test('#findAssets should list files in lib/', () async {
expect(await assetReader.findAssets(Glob('lib/*.dart')).toList(),
[libAsset]);
});
test('#findAssets should list files in test/', () async {
expect(await assetReader.findAssets(Glob('test/*.dart')).toList(),
[testAsset]);
});
test('#findAssets should be able to list files in non-root packages',
() async {
var otherLibAsset = AssetId('other', 'lib/other.dart');
assetReader.cacheStringAsset(otherLibAsset, 'otherLibAsset');
expect(
await assetReader
.findAssets(Glob('lib/*.dart'), package: 'other')
.toList(),
[otherLibAsset]);
});
});
}
| build/build_test/test/in_memory_reader_test.dart/0 | {'file_path': 'build/build_test/test/in_memory_reader_test.dart', 'repo_id': 'build', 'token_count': 734} |
sdk:
- pubspec
- dev
stages:
- analyze_and_format:
- group:
- format
- analyze: --fatal-infos .
- unit_test:
- test:
os:
- linux
- windows
| build/build_vm_compilers/mono_pkg.yaml/0 | {'file_path': 'build/build_vm_compilers/mono_pkg.yaml', 'repo_id': 'build', 'token_count': 78} |
// ignore: unused_import
import 'a_cycle.dart';
| build/build_web_compilers/test/fixtures/a/lib/a_secondary_in_cycle.dart/0 | {'file_path': 'build/build_web_compilers/test/fixtures/a/lib/a_secondary_in_cycle.dart', 'repo_id': 'build', 'token_count': 17} |
// Copyright (c) 2022, 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:path/path.dart' as p;
import 'package:yaml/yaml.dart';
import 'package:yaml_edit/yaml_edit.dart';
const _buildPackages = [
'build',
'build_config',
'build_daemon',
'build_modules',
'build_resolvers',
'build_runner',
'build_runner_core',
'build_test',
'build_vm_compilers',
'build_web_compilers',
'scratch_space',
];
/// Adds `dependency_overrides` for to a pubspec.yaml file in [packageDir]
/// build packages, assuming that the current working directory is the root of
/// the `build` repository checkout.
Future<void> patchBuildDependencies(String packageDir) async {
final pubspec = File(p.join(packageDir, 'pubspec.yaml'));
if (!await pubspec.exists()) {
throw UnsupportedError('No pubspec.yaml in $packageDir');
}
final editor = YamlEditor(await pubspec.readAsString());
const targetSection = ['dependency_overrides'];
if (editor
.parseAt(targetSection, orElse: () => YamlScalar.wrap(null))
.value ==
null) {
// There are no `dependency_overrides` in this pubspec, so create an empty
// block first.
editor.update(targetSection, {});
}
final buildCheckout = Directory.current.path;
for (final buildPackage in _buildPackages) {
final path = p.join(buildCheckout, buildPackage);
editor.update([...targetSection, buildPackage], {'path': path});
}
await pubspec.writeAsString(editor.toString());
}
| build/tool/lib/patch_build_dependencies.dart/0 | {'file_path': 'build/tool/lib/patch_build_dependencies.dart', 'repo_id': 'build', 'token_count': 563} |
name: build_verify
description: >-
Test utility to ensure generated Dart code within a package is up-to-date
when using package:build.
version: 1.1.2-dev
homepage: https://github.com/kevmoo/build_verify
author: Kevin Moore <kevmoo@google.com>
environment:
sdk: '>=2.2.0 <3.0.0'
dependencies:
path: ^1.0.0
test: ^1.0.0
dev_dependencies:
build: ^1.0.0
build_runner: ^1.0.0
build_version: ^2.0.0
git: ^1.0.0
pedantic: ^1.1.0
test_descriptor: ^1.1.1
test_process: ^1.0.4
| build_verify/pubspec.yaml/0 | {'file_path': 'build_verify/pubspec.yaml', 'repo_id': 'build_verify', 'token_count': 217} |
language: dart
dart:
- dev
branches:
only: [master]
dart_task:
- dartfmt
- test
- dartanalyzer
script:
- pub run test_coverage
after_success:
- bash <(curl -s https://codecov.io/bash)
cache:
directories:
- $HOME/.pub-cache
- .dart_tool
| bunq.dart/.travis.yml/0 | {'file_path': 'bunq.dart/.travis.yml', 'repo_id': 'bunq.dart', 'token_count': 116} |
name: Test
on: push
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: subosito/flutter-action@v1
with:
channel: 'stable'
- run: flutter pub get
- run: ./format.sh
- run: flutter test
| cached_value/.github/workflows/test.yml/0 | {'file_path': 'cached_value/.github/workflows/test.yml', 'repo_id': 'cached_value', 'token_count': 134} |
import 'dart:async';
import 'cached_value.dart';
import 'single_child_cached_value.dart';
/// A [CachedValue] that is invalidated some time after a refresh.
///
/// It keeps an internal [Timer] that is restarted very time the cache is
/// refreshed.
///
/// After that time, [isValid] will be false and any access to [value] will
/// trigger [refresh] and the timer will be restarted.
///
/// Besides dependency change, this cache can also be manually updated on
/// marked as invalid via [refresh] and [invalidate].
///
/// The duration of the timer is equal to [lifeTime].
///
/// Do not wrap a TTL cache on another, otherwise an assertion will be thrown.
///
/// It can be created via `CachedValue.withTimeToLive`
class TimeToLiveCachedValue<CacheContentType>
extends SingleChildCachedValue<CacheContentType> {
/// The amount of time that will take to the cache to be considered invalid
/// after a refresh.
final Duration lifeTime;
late Timer _timer;
TimeToLiveCachedValue._(CachedValue<CacheContentType> child, this.lifeTime)
: super(child) {
assert(_debugVerifyDuplicity());
_timer = Timer(lifeTime, () {});
}
@override
bool get isValid => super.isValid && _timer.isActive;
@override
CacheContentType get value {
if (!isValid) {
return refresh();
}
return super.value;
}
/// {@template ttl_refresh}
/// Calls refresh on its [child] and restarts the internal [Timer].
/// {@endtemplate}
///
/// {@macro main_refresh}
///
/// See also:
/// - [CachedValue.refresh] for the general behavior of refresh.
@override
CacheContentType refresh() {
final newValue = super.refresh();
_startLifeAgain();
return newValue;
}
void _startLifeAgain() {
if (_timer.isActive) {
_timer.cancel();
}
_timer = Timer(lifeTime, () {});
}
bool _debugVerifyDuplicity() {
assert(() {
bool verifyDuplicity(CachedValue child) {
if (child is TimeToLiveCachedValue) {
return false;
}
if (child is SingleChildCachedValue) {
return verifyDuplicity(child.child);
}
return true;
}
return verifyDuplicity(child);
}(), """
There is a declaration of a cached value time to live specified more than once""");
return true;
}
}
/// Adds [withTimeToLive] to [CachedValue].
extension TimeToLiveExtension<CacheContentType>
on CachedValue<CacheContentType> {
/// Wraps the declared [CachedValue] with a [TimeToLiveCachedValue].
///
/// Usage example:
/// ```dart
/// int factorial(int n) {
/// if (n < 0) throw ('Negative numbers are not allowed.');
/// return n <= 1 ? 1 : n * factorial(n - 1);
/// }
///
/// int originalValue = 1;
/// final factorialCache = CachedValue(
/// () => factorial(originalValue),
/// ).withTimeToLive(
/// lifetime: Duration(seconds: 3),
/// );
///
/// originalValue = 6;
/// print(factorialCache.value); // 1
///
/// await Future.delayed(Duration(seconds: 3));
///
/// print(factorialCache.value); // 720
/// ```
CachedValue<CacheContentType> withTimeToLive({
required Duration lifetime,
}) =>
TimeToLiveCachedValue._(this, lifetime);
}
| cached_value/lib/src/time_to_live_cached_value.dart/0 | {'file_path': 'cached_value/lib/src/time_to_live_cached_value.dart', 'repo_id': 'cached_value', 'token_count': 1105} |
import 'dart:ui';
import 'canvas_command.dart';
/// canvas.clipRect()
class ClipRectCommand extends CanvasCommand {
ClipRectCommand(this.clipRect, this.clipOp, this.doAntiAlias);
final Rect clipRect;
final ClipOp clipOp;
final bool doAntiAlias;
@override
bool equals(ClipRectCommand other) {
return eq(clipRect, other.clipRect) &&
clipOp == other.clipOp &&
doAntiAlias == other.doAntiAlias;
}
@override
String toString() {
return 'clipRect(${repr(clipRect)}, clipOp=$clipOp, doAntiAlias=$doAntiAlias)';
}
}
| canvas_test/lib/src/canvas_commands/cliprect_command.dart/0 | {'file_path': 'canvas_test/lib/src/canvas_commands/cliprect_command.dart', 'repo_id': 'canvas_test', 'token_count': 201} |
library chance_dart;
export 'core/core.dart';
export 'src/src.dart';
| chance-dart/packages/chance_dart/lib/chance_dart.dart/0 | {'file_path': 'chance-dart/packages/chance_dart/lib/chance_dart.dart', 'repo_id': 'chance-dart', 'token_count': 28} |
export 'src/cc.dart';
export 'src/cc_type.dart';
export 'src/cedi.dart';
export 'src/currency.dart';
export 'src/currency_pair.dart';
export 'src/dollar.dart';
export 'src/euro.dart';
export 'src/exp.dart';
export 'src/exp_month.dart';
export 'src/exp_year.dart';
export 'src/exp_year.dart';
export 'src/naira.dart';
| chance-dart/packages/chance_dart/lib/core/finance/finance.dart/0 | {'file_path': 'chance-dart/packages/chance_dart/lib/core/finance/finance.dart', 'repo_id': 'chance-dart', 'token_count': 133} |
export 'src/address.dart';
export 'src/altitude.dart';
export 'src/area_code.dart';
export 'src/city.dart';
export 'src/coordinates.dart';
export 'src/country.dart';
export 'src/depth.dart';
export 'src/geohash.dart';
export 'src/latitude.dart';
export 'src/locale.dart';
export 'src/longitude.dart';
export 'src/phone.dart';
export 'src/postal.dart';
export 'src/postcode.dart';
export 'src/province.dart';
export 'src/state.dart';
export 'src/street.dart';
export 'src/zip.dart';
| chance-dart/packages/chance_dart/lib/core/location/location.dart/0 | {'file_path': 'chance-dart/packages/chance_dart/lib/core/location/location.dart', 'repo_id': 'chance-dart', 'token_count': 192} |
import 'dart:convert';
import 'dart:math';
import '../constants/postals.dart';
/// It takes a base64 encoded JSON string, decodes it, converts it to a map,
/// gets the keys of the map,
/// converts the keys to a list, and returns a random key from the list
///
/// Returns:
/// A random postal code from the list of postal codes.
String postal() {
final decodedAddress = base64Decode(postals);
final postalsMap = jsonDecode(
String.fromCharCodes(decodedAddress),
) as Map<String, dynamic>;
final pstals = postalsMap.keys.toList();
return pstals[Random().nextInt(pstals.length)];
}
| chance-dart/packages/chance_dart/lib/core/location/src/postal.dart/0 | {'file_path': 'chance-dart/packages/chance_dart/lib/core/location/src/postal.dart', 'repo_id': 'chance-dart', 'token_count': 191} |
import 'package:chance_dart/core/person/model/user.dart';
import 'package:chance_dart/core/person/src/user.dart';
/// If the user's name is not null, return the user's last name, otherwise
/// return an empty string.
String lastName() => (user<User>()).name?.last ?? '';
| chance-dart/packages/chance_dart/lib/core/person/src/last_name.dart/0 | {'file_path': 'chance-dart/packages/chance_dart/lib/core/person/src/last_name.dart', 'repo_id': 'chance-dart', 'token_count': 89} |
/// Return a string containing the current day, month, and year, separated by
/// dashes.
///
/// Returns:
/// A string with the current date.
String date() {
final now = DateTime.now();
return now.toIso8601String();
}
| chance-dart/packages/chance_dart/lib/core/time/src/date.dart/0 | {'file_path': 'chance-dart/packages/chance_dart/lib/core/time/src/date.dart', 'repo_id': 'chance-dart', 'token_count': 68} |
enum ChanceAlias {
boolean,
character,
falsy,
floating,
integer,
letter,
natural,
prime,
string,
template,
ccType,
cc,
cedi,
currenyPair,
currency,
dollar,
euro,
expMonth,
expYear,
exp,
naira,
address,
altitude,
areaCode,
city,
coordinates,
country,
depth,
geohash,
latitude,
locale,
longitude,
phone,
postal,
postCode,
province,
state,
street,
zip,
age,
birthday,
firstName,
gender,
lastName,
personTitle,
ssn,
// user,
fullName,
paragraph,
sentence,
syllable,
animal,
amPm,
date,
hour,
millisecond,
minute,
month,
second,
timestamp,
timezone,
weekday,
year,
}
| chance-dart/packages/chance_dart/lib/src/enums/chance_alias.dart/0 | {'file_path': 'chance-dart/packages/chance_dart/lib/src/enums/chance_alias.dart', 'repo_id': 'chance-dart', 'token_count': 286} |
import 'package:chance_dart/core/time/src/hour.dart';
import 'package:test/test.dart';
void main() {
test(
'verify that hour returned is less than 999(which is the maximum)',
() => expect(hour(), lessThan(999)),
);
}
| chance-dart/packages/chance_dart/test/core/time/src/hour_test.dart/0 | {'file_path': 'chance-dart/packages/chance_dart/test/core/time/src/hour_test.dart', 'repo_id': 'chance-dart', 'token_count': 85} |
import 'package:analyzer/dart/constant/value.dart';
import 'package:analyzer/dart/element/element.dart';
import 'package:analyzer/dart/element/type.dart';
import 'package:chance_dart/chance_dart.dart';
class WrapperField {
// final int index;
final String name;
final ChanceAlias alias;
final Map<String, dynamic> args;
final DartType type;
final DartObject? defaultValue;
WrapperField(
this.name,
this.type,
this.defaultValue,
this.alias,
this.args,
);
}
abstract class Builder {
final InterfaceElement interfaceElement;
final List<WrapperField> getters;
final List<WrapperField> setters;
Builder(
this.interfaceElement,
this.getters, [
this.setters = const <WrapperField>[],
]);
// List buildList();
// T buildModel();
}
| chance-dart/packages/chance_generator/lib/src/builder/builder.dart/0 | {'file_path': 'chance-dart/packages/chance_generator/lib/src/builder/builder.dart', 'repo_id': 'chance-dart', 'token_count': 277} |
import 'package:flutter_test/flutter_test.dart';
void main() {
test('example', () {});
}
| ci/packages/main/test/example_test.dart/0 | {'file_path': 'ci/packages/main/test/example_test.dart', 'repo_id': 'ci', 'token_count': 35} |
import 'package:example/src/command_runner.dart';
import 'package:mason_logger/mason_logger.dart';
import 'package:mocktail/mocktail.dart';
import 'package:test/test.dart';
class MockLogger extends Mock implements Logger {}
void main() {
group('SomeCommand', () {
late Logger logger;
late ExampleCommandRunner commandRunner;
setUp(() {
logger = MockLogger();
commandRunner = ExampleCommandRunner(
logger: logger,
);
});
test('list passed options', () async {
final exitCode = await commandRunner.run(
'some_command '
'--discrete foo '
'--continuous something '
'--multi-d fii --multi-d bar '
'--multi-c oof --multi-c rab '
'--flag '
'--no-inverseflag '
'--trueflag'
.split(' '),
);
expect(exitCode, ExitCode.success.code);
verify(() => logger.info(' - discrete: foo')).called(1);
verify(() => logger.info(' - continuous: something')).called(1);
verify(() => logger.info(' - multi-d: [fii, bar]')).called(1);
verify(() => logger.info(' - multi-c: [oof, rab]')).called(1);
verify(() => logger.info(' - flag: true')).called(1);
verify(() => logger.info(' - inverseflag: false')).called(1);
verify(() => logger.info(' - trueflag: true')).called(1);
verify(() => logger.info(' - help: false')).called(1);
});
});
}
| cli_completion/example/test/src/commands/some_command_test.dart/0 | {'file_path': 'cli_completion/example/test/src/commands/some_command_test.dart', 'repo_id': 'cli_completion', 'token_count': 645} |
import 'package:args/args.dart';
final _optionRegex = RegExp(r'^--(([a-zA-Z\-_0-9]+)(=(.*))?)?$');
/// Defines if [string] complies with the GNU argument syntax.
///
/// Does not match abbreviated options.
bool isOption(String string) => _optionRegex.hasMatch(string);
final _abbrRegex = RegExp(r'^-(([a-zA-Z0-9]+)(.*))?$');
/// Defines if [string] complies with the GNU argument syntax in an
/// abbreviated form.
bool isAbbr(String string) => _abbrRegex.hasMatch(string);
/// Extends [ArgParser] with utility methods that allow parsing a completion
/// input, which in most cases only regards part of the rules.
extension ArgParserExtension on ArgParser {
/// Tries to parse the minimal subset of valid [args] as valid options.
ArgResults? findValidOptions(List<String> args) {
final loosenOptionsGramamar = _looseOptions();
var currentArgs = args;
while (currentArgs.isNotEmpty) {
try {
return loosenOptionsGramamar.parse(currentArgs);
} catch (_) {
currentArgs = currentArgs.take(currentArgs.length - 1).toList();
}
}
return null;
}
/// Parses [args] with this [ArgParser]'s command structure only, ignore
/// option strict rules (mandatory, allowed values, non negatable flags,
/// default values, etc);
///
/// Still breaks if an unknown option/alias is passed.
///
/// Returns null if there is an error when parsing, which means the given args
/// do not respect the known command structure.
ArgResults? tryParseCommandsOnly(Iterable<String> args) {
final commandsOnlyGrammar = _cloneCommandsOnly();
final filteredArgs = args.where((element) {
return !isAbbr(element) && !isOption(element) && element.isNotEmpty;
});
try {
return commandsOnlyGrammar
.parse(filteredArgs.where((element) => element.isNotEmpty));
} on ArgParserException {
return null;
}
}
/// Recursively copies this [ArgParser] without options.
ArgParser _cloneCommandsOnly() {
final clonedArgParser = ArgParser(
allowTrailingOptions: allowTrailingOptions,
);
for (final entry in commands.entries) {
final parser = entry.value._cloneCommandsOnly();
clonedArgParser.addCommand(entry.key, parser);
}
return clonedArgParser;
}
/// Copies this [ArgParser] with a less strict option mapping.
///
/// It preserves only the options names, types, abbreviations and aliases.
///
/// It disregard subcommands.
ArgParser _looseOptions() {
final clonedArgParser = ArgParser(
allowTrailingOptions: allowTrailingOptions,
);
for (final entry in options.entries) {
final option = entry.value;
if (option.isFlag) {
clonedArgParser.addFlag(
option.name,
abbr: option.abbr,
aliases: option.aliases,
negatable: option.negatable ?? true,
);
}
if (option.isSingle) {
clonedArgParser.addOption(
option.name,
abbr: option.abbr,
aliases: option.aliases,
);
}
if (option.isMultiple) {
clonedArgParser.addMultiOption(
option.name,
abbr: option.abbr,
aliases: option.aliases,
);
}
}
return clonedArgParser;
}
}
| cli_completion/lib/src/parser/arg_parser_extension.dart/0 | {'file_path': 'cli_completion/lib/src/parser/arg_parser_extension.dart', 'repo_id': 'cli_completion', 'token_count': 1211} |
import 'package:args/args.dart';
import 'package:cli_completion/src/parser/arg_parser_extension.dart';
import 'package:test/test.dart';
void main() {
group('isOption', () {
test('detects options', () {
expect(isOption('--'), isTrue);
expect(isOption('--o'), isTrue);
expect(isOption('--option'), isTrue);
expect(isOption('--opt1on'), isTrue);
expect(isOption('--opTion'), isTrue);
expect(isOption('--option="value"'), isTrue);
expect(isOption('--option=value'), isTrue);
});
test('discards not options', () {
expect(isOption('-'), isFalse);
expect(isOption('-o'), isFalse);
expect(isOption('cake'), isFalse);
expect(isOption('-- wow'), isFalse);
});
});
group('isAbbr', () {
test('detects abbreviations', () {
expect(isAbbr('-'), isTrue);
expect(isAbbr('-y'), isTrue);
expect(isAbbr('-yay'), isTrue);
});
test('discards not abbreviations', () {
expect(isAbbr('--'), isFalse);
expect(isAbbr('--option'), isFalse);
expect(isAbbr('cake'), isFalse);
expect(isAbbr('- wow'), isFalse);
});
});
group('ArgParserExtension', () {
group('tryParseCommandsOnly', () {
final rootArgParser = ArgParser()..addFlag('rootFlag');
final subArgPasrser = ArgParser();
rootArgParser.addCommand('subcommand', subArgPasrser);
test('parses commands only disregarding all option rules', () {
final args = '--rootFlag subcommand'.split(' ');
final results = rootArgParser.tryParseCommandsOnly(args);
expect(results, isNotNull);
results!;
expect(results.name, null);
expect(
results.arguments,
<String>[
'subcommand',
],
);
expect(
results.command,
isA<ArgResults>().having(
(results) => results.name,
'level 1 name',
'subcommand',
),
);
expect(results.options, <String>{});
});
test('returns null when args make no sense', () {
final args = '--rootFlag oh my god subcommand'.split(' ');
final results = rootArgParser.tryParseCommandsOnly(args);
expect(results, isNull);
});
test('parses args with leading spaces', () {
final args = ' subcommand'.split(' ');
final results = rootArgParser.tryParseCommandsOnly(args);
expect(results, isNotNull);
});
});
group('findValidOptions', () {
final argParser = ArgParser()
..addFlag(
'flag',
abbr: 'f',
aliases: ['flagalias'],
)
..addOption('mandatoryOption', mandatory: true)
..addMultiOption('multiOption', allowed: ['a', 'b', 'c'])
..addCommand('subcommand', ArgParser());
group('parses the minimal amount of valid options', () {
test('options values and abbr', () {
final args = '-f --mandatoryOption="yay" --multiOption'.split(' ');
final results = argParser.findValidOptions(args);
expect(
results,
isA<ArgResults>()
.having((res) => res.wasParsed('flag'), 'parsed flag', true)
.having(
(res) => res.wasParsed('mandatoryOption'),
'parsed mandatoryOption',
true,
)
.having(
(res) => res.wasParsed('multiOption'),
'parsed multiOption',
false,
),
);
});
test('alias', () {
final args = '--flagalias --mandatoryOption'.split(' ');
final results = argParser.findValidOptions(args);
expect(
results,
isA<ArgResults>()
.having((res) => res.wasParsed('flag'), 'parsed flag', true)
.having(
(res) => res.wasParsed('mandatoryOption'),
'parsed mandatoryOption',
false,
)
.having(
(res) => res.wasParsed('multiOption'),
'parsed multiOption',
false,
),
);
});
});
test('returns null when there is no valid options', () {
final args = '--extraneousOption --flag'.split(' ');
final results = argParser.findValidOptions(args);
expect(results, isNull);
});
test('disregard sub command', () {
final args = '--flag subcommand'.split(' ');
final results = argParser.findValidOptions(args);
expect(
results,
isA<ArgResults>()
.having((res) => res.wasParsed('flag'), 'parsed flag', true)
.having(
(res) => res.wasParsed('mandatoryOption'),
'parsed mandatoryOption',
false,
)
.having(
(res) => res.wasParsed('multiOption'),
'parsed multiOption',
false,
)
.having((res) => res.command, 'command', isNull),
);
});
});
});
}
| cli_completion/test/src/parser/arg_parser_extension_test.dart/0 | {'file_path': 'cli_completion/test/src/parser/arg_parser_extension_test.dart', 'repo_id': 'cli_completion', 'token_count': 2533} |
github: creativecreatorormaybenot
| clock/.github/funding.yml/0 | {'file_path': 'clock/.github/funding.yml', 'repo_id': 'clock', 'token_count': 9} |
import 'package:canvas_clock/clock.dart';
import 'package:canvas_clock/main.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_clock_helper/model.dart';
export 'automatic.dart';
export 'manual.dart';
typedef ClockModelBuilder = Widget Function(
BuildContext context, ClockModel model);
/// Customization flows control the behavior of the clock.
///
/// The selected mode is determined by the [customizationFlowMode]
/// constants.
enum CustomizationFlow {
manual,
automatic,
}
class Customizer extends StatelessWidget {
final ClockModelBuilder builder;
final CustomizationFlow mode;
/// Inserts a [SemanticsDebugger] when `true`.
///
/// It does not matter where the debugger is inserted.
/// It will always show semantics information for the parent
/// widgets as well. Thus, it is fine to wrap the customizers
/// in the debugger.
final bool debugSemantics;
const Customizer({
Key key,
@required this.mode,
this.debugSemantics = false,
@required this.builder,
}) : assert(mode != null),
assert(debugSemantics != null),
assert(builder != null),
super(key: key);
@override
Widget build(BuildContext context) {
Widget result;
if (mode == CustomizationFlow.automatic) {
result = AutomatedCustomizer(builder: builder);
} else {
result = ManualCustomizer(builder: builder);
}
if (debugSemantics) {
result = SemanticsDebugger(child: result);
}
return result;
}
}
| clock/canvas_clock/lib/customizer/customizer.dart/0 | {'file_path': 'clock/canvas_clock/lib/customizer/customizer.dart', 'repo_id': 'clock', 'token_count': 486} |
include: package:very_good_analysis/analysis_options.3.1.0.yaml
| cloud9/analysis_options.yaml/0 | {'file_path': 'cloud9/analysis_options.yaml', 'repo_id': 'cloud9', 'token_count': 23} |
import 'package:cloud9/cloud9.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
void initState() {
super.initState();
final cloud9 = Cloud9.instance;
final initializer = GoogleDriveInitializer()..initialize();
final connector = GoogleDriveConnector()..connect();
final connectors = DropBoxConnector(
'3c977fuu0s0f0r2', 'rwwyxpaey8876f2', 'https://cloud9.com')
..connect();
}
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: const Scaffold(),
);
}
}
| cloud9/example/lib/main.dart/0 | {'file_path': 'cloud9/example/lib/main.dart', 'repo_id': 'cloud9', 'token_count': 521} |
/// A class representing the Cloud9 package.
class Cloud9 {
// Private constructor to prevent direct instantiation of the class.
Cloud9._();
// Private instance of the class.
static final Cloud9 _instance = Cloud9._();
// Public getter to access the instance of the class.
static Cloud9 get instance {
return _instance;
}
}
| cloud9/lib/src/cloud9.dart/0 | {'file_path': 'cloud9/lib/src/cloud9.dart', 'repo_id': 'cloud9', 'token_count': 93} |
// 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 '../../request_handling/body.dart';
part 'grpc.g.dart';
/// [Status] defines a logical error model that is suitable for
/// different programming environments, including REST APIs and RPC APIs. It is
/// used by [gRPC](https://github.com/grpc). Each [Status] message contains
/// three pieces of data: error code, error message, and error details.
///
/// Resources:
/// * https://cloud.google.com/apis/design/errors
@JsonSerializable(includeIfNull: false)
class GrpcStatus extends JsonBody {
const GrpcStatus({required this.code, this.message, this.details});
/// Creates a [Status] from JSON.
static GrpcStatus fromJson(Map<String, dynamic> json) => _$GrpcStatusFromJson(json);
/// The status code, which should be an enum value of [google.rpc.Code][].
final int code;
/// A developer-facing error message, which should be in English. Any
/// user-facing error message should be localized and sent in the
/// [google.rpc.Status.details][] field, or localized by the client.
final String? message;
/// A list of messages that carry the error details. There is a common set of
/// message types for APIs to use.
final dynamic details;
@override
String toString() => 'Response #$code: $message, $details';
@override
Map<String, dynamic> toJson() => _$GrpcStatusToJson(this);
}
| cocoon/app_dart/lib/src/model/google/grpc.dart/0 | {'file_path': 'cocoon/app_dart/lib/src/model/google/grpc.dart', 'repo_id': 'cocoon', 'token_count': 448} |
// Copyright 2021 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/body.dart';
import '../request_handling/request_handler.dart';
@immutable
class ReadinessCheck extends RequestHandler<Body> {
const ReadinessCheck({required super.config});
@override
Future<Body> get() async {
return Body.empty;
}
}
| cocoon/app_dart/lib/src/request_handlers/readiness_check.dart/0 | {'file_path': 'cocoon/app_dart/lib/src/request_handlers/readiness_check.dart', 'repo_id': 'cocoon', 'token_count': 151} |
// 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.
class NoBuildFoundException implements Exception {
/// Create a custom exception for no build found Errors.
NoBuildFoundException(this.cause);
final String cause;
@override
String toString() => cause;
}
class UnfinishedBuildException implements Exception {
/// Create a custom exception for an unfinished buildbucket build
UnfinishedBuildException(this.cause);
final String cause;
@override
String toString() => cause;
}
| cocoon/app_dart/lib/src/service/exceptions.dart/0 | {'file_path': 'cocoon/app_dart/lib/src/service/exceptions.dart', 'repo_id': 'cocoon', 'token_count': 154} |
// 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:cocoon_service/src/model/google/token_info.dart';
import 'package:test/test.dart';
void main() {
group('TokenInfo', () {
test('deserialize', () {
final TokenInfo token = TokenInfo.fromJson(<String, dynamic>{
'iss': 'issuer',
'azp': 'authorizedParty',
'aud': 'audience',
'sub': 'subject',
'hd': 'hostedDomain',
'email': 'test@flutter.dev',
'email_verified': 'true',
'at_hash': 'accessTokenHash',
'name': 'Test Flutter',
'picture': 'http://example.org/123.jpg',
'given_name': 'Test',
'family_name': 'Flutter',
'locale': 'en',
'iat': '12345',
'exp': '67890',
'jti': 'jwtId',
'alg': 'RSA',
'kid': 'keyId',
'typ': 'JWT',
});
expect(token.issuer, 'issuer');
expect(token.authorizedParty, 'authorizedParty');
expect(token.audience, 'audience');
expect(token.subject, 'subject');
expect(token.hostedDomain, 'hostedDomain');
expect(token.email, 'test@flutter.dev');
expect(token.emailIsVerified, isTrue);
expect(token.accessTokenHash, 'accessTokenHash');
expect(token.fullName, 'Test Flutter');
expect(token.profilePictureUrl, 'http://example.org/123.jpg');
expect(token.givenName, 'Test');
expect(token.familyName, 'Flutter');
expect(token.locale, 'en');
expect(token.issued, DateTime.fromMillisecondsSinceEpoch(12345 * 1000));
expect(token.expiration, DateTime.fromMillisecondsSinceEpoch(67890 * 1000));
expect(token.jwtId, 'jwtId');
expect(token.algorithm, 'RSA');
expect(token.keyId, 'keyId');
expect(token.encoding, 'JWT');
});
});
}
| cocoon/app_dart/test/model/google/token_info_test.dart/0 | {'file_path': 'cocoon/app_dart/test/model/google/token_info_test.dart', 'repo_id': 'cocoon', 'token_count': 814} |
// 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:cocoon_service/src/request_handling/body.dart';
import 'package:cocoon_service/src/request_handling/request_handler.dart';
import 'package:http/testing.dart' as http;
import 'package:meta/meta.dart';
import 'fake_http.dart';
class RequestHandlerTester {
RequestHandlerTester({
FakeHttpRequest? request,
this.httpClient,
}) {
this.request = request ?? FakeHttpRequest();
}
FakeHttpRequest? request;
http.MockClient? httpClient;
/// This tester's [FakeHttpResponse], derived from [request].
FakeHttpResponse get response => request!.response;
/// Executes [RequestHandler.get] on the specified [handler].
Future<T> get<T extends Body>(RequestHandler<T> handler) {
return run<T>(() {
return handler.get(); // ignore: invalid_use_of_protected_member
});
}
/// Executes [RequestHandler.post] on the specified [handler].
Future<T> post<T extends Body>(RequestHandler<T> handler) {
return run<T>(() {
return handler.post(); // ignore: invalid_use_of_protected_member
});
}
@protected
Future<T> run<T extends Body>(Future<T> Function() callback) {
return runZoned<Future<T>>(
() {
return callback();
},
zoneValues: <RequestKey<dynamic>, Object?>{
RequestKey.request: request,
RequestKey.response: response,
RequestKey.httpClient: httpClient,
},
);
}
}
| cocoon/app_dart/test/src/request_handling/request_handler_tester.dart/0 | {'file_path': 'cocoon/app_dart/test/src/request_handling/request_handler_tester.dart', 'repo_id': 'cocoon', 'token_count': 548} |
// 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:async';
import 'package:device_doctor/src/ios_device.dart';
import 'package:process/process.dart';
class FakeIosDeviceDiscovery extends IosDeviceDiscovery {
// ignore: use_super_parameters
FakeIosDeviceDiscovery(output) : super.testing(output);
List<dynamic>? _outputs;
int _pos = 0;
set outputs(List<dynamic> outputs) {
_pos = 0;
_outputs = outputs;
}
@override
Future<String> deviceListOutput({
ProcessManager processManager = const LocalProcessManager(),
}) async {
_pos++;
if (_outputs?[_pos - 1] is String) {
return _outputs?[_pos - 1] as String;
} else {
throw _outputs?[_pos - 1];
}
}
}
| cocoon/cipd_packages/device_doctor/test/src/fake_ios_device.dart/0 | {'file_path': 'cocoon/cipd_packages/device_doctor/test/src/fake_ios_device.dart', 'repo_id': 'cocoon', 'token_count': 293} |
// 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_app_icons/flutter_app_icons_platform_interface.dart';
class FakeFlutterAppIcons extends FlutterAppIconsPlatform {
@override
Future<String?> setIcon({
required String icon,
String oldIcon = '',
String appleTouchIcon = '',
}) async {
return icon;
}
}
| cocoon/dashboard/test/utils/fake_flutter_app_icons.dart/0 | {'file_path': 'cocoon/dashboard/test/utils/fake_flutter_app_icons.dart', 'repo_id': 'cocoon', 'token_count': 146} |
//
// Generated code. Do not modify.
// source: go.chromium.org/luci/buildbucket/proto/builds_service.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/go.chromium.org/luci/buildbucket/proto/builds_service.pbenum.dart/0 | {'file_path': 'cocoon/packages/buildbucket-dart/lib/src/generated/go.chromium.org/luci/buildbucket/proto/builds_service.pbenum.dart', 'repo_id': 'cocoon', 'token_count': 135} |
//
// Generated code. Do not modify.
// source: google/protobuf/empty.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/protobuf/empty.pbenum.dart/0 | {'file_path': 'cocoon/packages/buildbucket-dart/lib/src/generated/google/protobuf/empty.pbenum.dart', 'repo_id': 'cocoon', 'token_count': 121} |
name: triage_bot
description: Flutter's triage bot.
version: 1.0.0
repository: https://github.com/flutter/cocoon/
publish_to: 'none'
environment:
sdk: ^3.0.0
dependencies:
appengine: ^0.13.5
crypto: ^3.0.3
dart_jsonwebtoken: ^2.8.1
github: ^9.14.0
googleapis: ^11.2.0
http: ^0.13.6
meta: ^1.9.1
nyxx: ^5.0.4
dev_dependencies:
test: ^1.21.0
| cocoon/triage_bot/pubspec.yaml/0 | {'file_path': 'cocoon/triage_bot/pubspec.yaml', 'repo_id': 'cocoon', 'token_count': 178} |
language: dart
dart:
- dev
cache:
directories:
- $HOME/.pub-cache
dist: trusty
addons:
chrome: stable
branches:
only: [master]
# TODO: Give up the dream of running with dartdevc until...
# https://github.com/dart-lang/sdk/issues/31280
dart_task:
- test: --platform vm
- dartanalyzer
- dartfmt
| code_builder/.travis.yml/0 | {'file_path': 'code_builder/.travis.yml', 'repo_id': 'code_builder', 'token_count': 121} |
// 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:built_collection/built_collection.dart';
import '../specs/reference.dart';
abstract class HasGenerics {
/// Generic type parameters.
BuiltList<Reference> get types;
}
abstract class HasGenericsBuilder {
/// Generic type parameters.
ListBuilder<Reference> types;
}
| code_builder/lib/src/mixins/generics.dart/0 | {'file_path': 'code_builder/lib/src/mixins/generics.dart', 'repo_id': 'code_builder', 'token_count': 141} |
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'field.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 _$Field extends Field {
@override
final BuiltList<Expression> annotations;
@override
final BuiltList<String> docs;
@override
final Code assignment;
@override
final bool static;
@override
final String name;
@override
final Reference type;
@override
final FieldModifier modifier;
factory _$Field([void updates(FieldBuilder b)]) =>
(new FieldBuilder()..update(updates)).build() as _$Field;
_$Field._(
{this.annotations,
this.docs,
this.assignment,
this.static,
this.name,
this.type,
this.modifier})
: super._() {
if (annotations == null)
throw new BuiltValueNullFieldError('Field', 'annotations');
if (docs == null) throw new BuiltValueNullFieldError('Field', 'docs');
if (static == null) throw new BuiltValueNullFieldError('Field', 'static');
if (name == null) throw new BuiltValueNullFieldError('Field', 'name');
if (modifier == null)
throw new BuiltValueNullFieldError('Field', 'modifier');
}
@override
Field rebuild(void updates(FieldBuilder b)) =>
(toBuilder()..update(updates)).build();
@override
_$FieldBuilder toBuilder() => new _$FieldBuilder()..replace(this);
@override
bool operator ==(dynamic other) {
if (identical(other, this)) return true;
if (other is! Field) return false;
return annotations == other.annotations &&
docs == other.docs &&
assignment == other.assignment &&
static == other.static &&
name == other.name &&
type == other.type &&
modifier == other.modifier;
}
@override
int get hashCode {
return $jf($jc(
$jc(
$jc(
$jc(
$jc($jc($jc(0, annotations.hashCode), docs.hashCode),
assignment.hashCode),
static.hashCode),
name.hashCode),
type.hashCode),
modifier.hashCode));
}
@override
String toString() {
return (newBuiltValueToStringHelper('Field')
..add('annotations', annotations)
..add('docs', docs)
..add('assignment', assignment)
..add('static', static)
..add('name', name)
..add('type', type)
..add('modifier', modifier))
.toString();
}
}
class _$FieldBuilder extends FieldBuilder {
_$Field _$v;
@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
Code get assignment {
_$this;
return super.assignment;
}
@override
set assignment(Code assignment) {
_$this;
super.assignment = assignment;
}
@override
bool get static {
_$this;
return super.static;
}
@override
set static(bool static) {
_$this;
super.static = static;
}
@override
String get name {
_$this;
return super.name;
}
@override
set name(String name) {
_$this;
super.name = name;
}
@override
Reference get type {
_$this;
return super.type;
}
@override
set type(Reference type) {
_$this;
super.type = type;
}
@override
FieldModifier get modifier {
_$this;
return super.modifier;
}
@override
set modifier(FieldModifier modifier) {
_$this;
super.modifier = modifier;
}
_$FieldBuilder() : super._();
FieldBuilder get _$this {
if (_$v != null) {
super.annotations = _$v.annotations?.toBuilder();
super.docs = _$v.docs?.toBuilder();
super.assignment = _$v.assignment;
super.static = _$v.static;
super.name = _$v.name;
super.type = _$v.type;
super.modifier = _$v.modifier;
_$v = null;
}
return this;
}
@override
void replace(Field other) {
if (other == null) throw new ArgumentError.notNull('other');
_$v = other as _$Field;
}
@override
void update(void updates(FieldBuilder b)) {
if (updates != null) updates(this);
}
@override
_$Field build() {
_$Field _$result;
try {
_$result = _$v ??
new _$Field._(
annotations: annotations.build(),
docs: docs.build(),
assignment: assignment,
static: static,
name: name,
type: type,
modifier: modifier);
} catch (_) {
String _$failedField;
try {
_$failedField = 'annotations';
annotations.build();
_$failedField = 'docs';
docs.build();
} catch (e) {
throw new BuiltValueNestedFieldError(
'Field', _$failedField, e.toString());
}
rethrow;
}
replace(_$result);
return _$result;
}
}
| code_builder/lib/src/specs/field.g.dart/0 | {'file_path': 'code_builder/lib/src/specs/field.g.dart', 'repo_id': 'code_builder', 'token_count': 2321} |
// 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 emit a simple expression', () {
expect(literalNull, equalsDart('null'));
});
test('should emit a String', () {
expect(literalString(r'$monkey'), equalsDart(r"'$monkey'"));
});
test('should emit a raw String', () {
expect(literalString(r'$monkey', raw: true), equalsDart(r"r'$monkey'"));
});
test('should escape single quotes in a String', () {
expect(literalString(r"don't"), equalsDart(r"'don\'t'"));
});
test('does not allow single quote in raw string', () {
expect(() => literalString(r"don't", raw: true), throwsArgumentError);
});
test('should emit a && expression', () {
expect(literalTrue.and(literalFalse), equalsDart('true && false'));
});
test('should emit a list', () {
expect(literalList([]), equalsDart('[]'));
});
test('should emit a const list', () {
expect(literalConstList([]), equalsDart('const []'));
});
test('should emit an explicitly typed list', () {
expect(literalList([], refer('int')), equalsDart('<int>[]'));
});
test('should emit a map', () {
expect(literalMap({}), equalsDart('{}'));
});
test('should emit a const map', () {
expect(literalConstMap({}), equalsDart('const {}'));
});
test('should emit an explicitly typed map', () {
expect(
literalMap({}, refer('int'), refer('bool')),
equalsDart('<int, bool>{}'),
);
});
test('should emit a map of other literals and expressions', () {
expect(
literalMap({
1: 'one',
2: refer('two'),
refer('three'): 3,
refer('Map').newInstance([]): null,
}),
equalsDart(r"{1: 'one', 2: two, three: 3, new Map(): null}"),
);
});
test('should emit a list of other literals and expressions', () {
expect(
literalList([<dynamic>[], true, null, refer('Map').newInstance([])]),
equalsDart('[[], true, null, new Map()]'),
);
});
test('should emit a type as an expression', () {
expect(refer('Map'), equalsDart('Map'));
});
test('should emit a scoped type as an expression', () {
expect(
refer('Foo', 'package:foo/foo.dart'),
equalsDart('_i1.Foo', DartEmitter(Allocator.simplePrefixing())),
);
});
test('should emit invoking new Type()', () {
expect(
refer('Map').newInstance([]),
equalsDart('new Map()'),
);
});
test('should emit invoking new named constructor', () {
expect(
refer('Foo').newInstanceNamed('bar', []),
equalsDart('new Foo.bar()'),
);
});
test('should emit invoking const Type()', () {
expect(
refer('Object').constInstance([]),
equalsDart('const Object()'),
);
});
test('should emit invoking a property accessor', () {
expect(refer('foo').property('bar'), equalsDart('foo.bar'));
});
test('should emit invoking a null safe property accessor', () {
expect(refer('foo').nullSafeProperty('bar'), equalsDart('foo?.bar'));
});
test('should emit invoking a method with a single positional argument', () {
expect(
refer('foo').call([
literal(1),
]),
equalsDart('foo(1)'),
);
});
test('should emit invoking a method with positional arguments', () {
expect(
refer('foo').call([
literal(1),
literal(2),
literal(3),
]),
equalsDart('foo(1, 2, 3)'),
);
});
test('should emit invoking a method with a single named argument', () {
expect(
refer('foo').call([], {
'bar': literal(1),
}),
equalsDart('foo(bar: 1)'),
);
});
test('should emit invoking a method with named arguments', () {
expect(
refer('foo').call([], {
'bar': literal(1),
'baz': literal(2),
}),
equalsDart('foo(bar: 1, baz: 2)'),
);
});
test('should emit invoking a method with positional and named arguments', () {
expect(
refer('foo').call([
literal(1)
], {
'bar': literal(2),
'baz': literal(3),
}),
equalsDart('foo(1, bar: 2, baz: 3)'),
);
});
test('should emit invoking a method with a single type argument', () {
expect(
refer('foo').call(
[],
{},
[
refer('String'),
],
),
equalsDart('foo<String>()'),
);
});
test('should emit invoking a method with type arguments', () {
expect(
refer('foo').call(
[],
{},
[
refer('String'),
refer('int'),
],
),
equalsDart('foo<String, int>()'),
);
});
test('should emit a function type', () {
expect(
FunctionType((b) => b.returnType = refer('void')),
equalsDart('void Function()'),
);
});
test('should emit a typedef statement', () {
expect(
FunctionType((b) => b.returnType = refer('void')).toTypeDef('Void0'),
equalsDart('typedef Void0 = void Function();'),
);
});
test('should emit a function type with type parameters', () {
expect(
FunctionType((b) => b
..returnType = refer('T')
..types.add(refer('T'))),
equalsDart('T Function<T>()'),
);
});
test('should emit a function type a single parameter', () {
expect(
FunctionType((b) => b..requiredParameters.add(refer('String'))),
equalsDart('Function(String)'),
);
});
test('should emit a function type with parameters', () {
expect(
FunctionType((b) => b
..requiredParameters.add(refer('String'))
..optionalParameters.add(refer('int'))),
equalsDart('Function(String, [int])'),
);
});
test('should emit a function type with named parameters', () {
expect(
FunctionType((b) => b
..namedParameters.addAll({
'x': refer('int'),
'y': refer('int'),
})),
equalsDart('Function({int x, int y})'),
);
});
test('should emit a closure', () {
expect(
refer('map').property('putIfAbsent').call([
literalString('foo'),
Method((b) => b..body = literalTrue.code).closure,
]),
equalsDart("map.putIfAbsent('foo', () => true)"),
);
});
test('should emit an assignment', () {
expect(
refer('foo').assign(literalTrue),
equalsDart('foo = true'),
);
});
test('should emit a null-aware assignment', () {
expect(
refer('foo').assignNullAware(literalTrue),
equalsDart('foo ??= true'),
);
});
test('should emit an index operator', () {
expect(
refer('bar').index(literalString('key')).assignVar('foo').statement,
equalsDart("var foo = bar['key'];"),
);
});
test('should emit an index operator set', () {
expect(
refer('bar')
.index(literalString('key'))
.assign(literalFalse)
.assignVar('foo')
.statement,
equalsDart("var foo = bar['key'] = false;"),
);
});
test('should emit a null-aware index operator set', () {
expect(
refer('bar')
.index(literalTrue)
.assignNullAware(literalFalse)
.assignVar('foo')
.statement,
equalsDart('var foo = bar[true] ??= false;'),
);
});
test('should emit assigning to a var', () {
expect(
literalTrue.assignVar('foo'),
equalsDart('var foo = true'),
);
});
test('should emit assigning to a type', () {
expect(
literalTrue.assignVar('foo', refer('bool')),
equalsDart('bool foo = true'),
);
});
test('should emit assigning to a final', () {
expect(
literalTrue.assignFinal('foo'),
equalsDart('final foo = true'),
);
});
test('should emit assigning to a const', () {
expect(
literalTrue.assignConst('foo'),
equalsDart('const foo = true'),
);
});
test('should emit await', () {
expect(
refer('future').awaited,
equalsDart('await future'),
);
});
test('should emit return', () {
expect(
literalNull.returned,
equalsDart('return null'),
);
});
test('should emit an explicit cast', () {
expect(
refer('foo').asA(refer('String')).property('length'),
equalsDart('( foo as String ).length'),
);
});
test('should emit an is check', () {
expect(
refer('foo').isA(refer('String')),
equalsDart('foo is String'),
);
});
test('should emit an is! check', () {
expect(
refer('foo').isNotA(refer('String')),
equalsDart('foo is! String'),
);
});
test('should emit an equality check', () {
expect(
refer('foo').equalTo(literalString('bar')),
equalsDart("foo == 'bar'"),
);
});
test('should emit an inequality check', () {
expect(
refer('foo').notEqualTo(literalString('bar')),
equalsDart("foo != 'bar'"),
);
});
test('should emit an greater than check', () {
expect(
refer('foo').greaterThan(literalString('bar')),
equalsDart("foo > 'bar'"),
);
});
test('should emit an less than check', () {
expect(
refer('foo').lessThan(literalString('bar')),
equalsDart("foo < 'bar'"),
);
});
test('should emit an greater or equals check', () {
expect(
refer('foo').greaterOrEqualTo(literalString('bar')),
equalsDart("foo >= 'bar'"),
);
});
test('should emit an less or equals check', () {
expect(
refer('foo').lessOrEqualTo(literalString('bar')),
equalsDart("foo <= 'bar'"),
);
});
test('should emit a conditional', () {
expect(
refer('foo').conditional(literal(1), literal(2)),
equalsDart('foo ? 1 : 2'),
);
});
test('should emit an operator add call', () {
expect(refer('foo').operatorAdd(refer('foo2')), equalsDart('foo + foo2'));
});
test('should emit an operator substract call', () {
expect(refer('foo').operatorSubstract(refer('foo2')),
equalsDart('foo - foo2'));
});
test('should emit an operator divide call', () {
expect(
refer('foo').operatorDivide(refer('foo2')), equalsDart('foo / foo2'));
});
test('should emit an operator multiply call', () {
expect(
refer('foo').operatorMultiply(refer('foo2')), equalsDart('foo * foo2'));
});
test('should emit an euclidean modulo operator call', () {
expect(refer('foo').operatorEuclideanModulo(refer('foo2')),
equalsDart('foo % foo2'));
});
}
| code_builder/test/specs/code/expression_test.dart/0 | {'file_path': 'code_builder/test/specs/code/expression_test.dart', 'repo_id': 'code_builder', 'token_count': 4284} |
// 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:ui';
import 'package:flutter/material.dart';
import '../animations.dart';
class ListDetailTransition extends StatefulWidget {
const ListDetailTransition({
super.key,
required this.animation,
required this.one,
required this.two,
});
final Animation<double> animation;
final Widget one;
final Widget two;
@override
State<ListDetailTransition> createState() => _ListDetailTransitionState();
}
class _ListDetailTransitionState extends State<ListDetailTransition> {
Animation<double> widthAnimation = const AlwaysStoppedAnimation(0);
late final Animation<double> sizeAnimation =
SizeAnimation(parent: widget.animation);
late final Animation<Offset> offsetAnimation = Tween<Offset>(
begin: const Offset(1, 0),
end: Offset.zero,
).animate(OffsetAnimation(parent: sizeAnimation));
double currentFlexFactor = 0;
@override
void didChangeDependencies() {
super.didChangeDependencies();
// When the app's width is < 800, widgets one and two get 1/2 of
// the available width, As the app gets wider, the allocation
// gradually changes to 1/3 and 2/3 for widgets one and two. When
// the window is wider than 1600, the allocation changes to 1/4 3/4.
final double width = MediaQuery.of(context).size.width;
double nextFlexFactor = switch (width) {
>= 800 && < 1200 => lerpDouble(1000, 2000, (width - 800) / 400)!,
>= 1200 && < 1600 => lerpDouble(2000, 3000, (width - 1200) / 400)!,
>= 1600 => 3000,
_ => 1000,
};
// Continue along the current animation curve if the
// destionation flex factor has not changed.
if (nextFlexFactor == currentFlexFactor) {
return;
}
if (currentFlexFactor == 0) {
widthAnimation =
Tween<double>(begin: 0, end: nextFlexFactor).animate(sizeAnimation);
} else {
final TweenSequence<double> sequence = TweenSequence([
if (sizeAnimation.value > 0) ...[
TweenSequenceItem(
tween: Tween(begin: 0, end: widthAnimation.value),
weight: sizeAnimation.value,
),
],
if (sizeAnimation.value < 1) ...[
TweenSequenceItem(
tween: Tween(begin: widthAnimation.value, end: nextFlexFactor),
weight: 1 - sizeAnimation.value,
),
],
]);
widthAnimation = sequence.animate(sizeAnimation);
}
currentFlexFactor = nextFlexFactor;
}
@override
Widget build(BuildContext context) {
return widthAnimation.value.toInt() == 0
? widget.one
: Row(
children: [
Flexible(
flex: 1000,
child: widget.one,
),
Flexible(
flex: widthAnimation.value.toInt(),
child: FractionalTranslation(
translation: offsetAnimation.value,
child: widget.two,
),
),
],
);
}
}
| codelabs/animated-responsive-layout/step_08/lib/transitions/list_detail_transition.dart/0 | {'file_path': 'codelabs/animated-responsive-layout/step_08/lib/transitions/list_detail_transition.dart', 'repo_id': 'codelabs', 'token_count': 1263} |
include: ../../analysis_options.yaml
| codelabs/brick_breaker/step_03/analysis_options.yaml/0 | {'file_path': 'codelabs/brick_breaker/step_03/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 12} |
import 'package:flame/components.dart';
import 'package:flutter/material.dart';
class Ball extends CircleComponent {
Ball({
required this.velocity,
required super.position,
required double radius,
}) : super(
radius: radius,
anchor: Anchor.center,
paint: Paint()
..color = const Color(0xff1e6091)
..style = PaintingStyle.fill);
final Vector2 velocity;
@override
void update(double dt) {
super.update(dt);
position += velocity * dt;
}
}
| codelabs/brick_breaker/step_05/lib/src/components/ball.dart/0 | {'file_path': 'codelabs/brick_breaker/step_05/lib/src/components/ball.dart', 'repo_id': 'codelabs', 'token_count': 219} |
import 'package:flame/game.dart';
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import '../brick_breaker.dart';
import '../config.dart';
import 'overlay_screen.dart';
import 'score_card.dart';
class GameApp extends StatefulWidget {
const GameApp({super.key});
@override
State<GameApp> createState() => _GameAppState();
}
class _GameAppState extends State<GameApp> {
late final BrickBreaker game;
@override
void initState() {
super.initState();
game = BrickBreaker();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(
useMaterial3: true,
textTheme: GoogleFonts.pressStart2pTextTheme().apply(
bodyColor: const Color(0xff184e77),
displayColor: const Color(0xff184e77),
),
),
home: Scaffold(
body: Container(
decoration: const BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Color(0xffa9d6e5),
Color(0xfff2e8cf),
],
),
),
child: SafeArea(
child: Padding(
padding: const EdgeInsets.all(16),
child: Center(
child: Column(
children: [
ScoreCard(score: game.score),
Expanded(
child: FittedBox(
child: SizedBox(
width: gameWidth,
height: gameHeight,
child: GameWidget(
game: game,
overlayBuilderMap: {
PlayState.welcome.name: (context, game) =>
const OverlayScreen(
title: 'TAP TO PLAY',
subtitle: 'Use arrow keys or swipe',
),
PlayState.gameOver.name: (context, game) =>
const OverlayScreen(
title: 'G A M E O V E R',
subtitle: 'Tap to Play Again',
),
PlayState.won.name: (context, game) =>
const OverlayScreen(
title: 'Y O U W O N ! ! !',
subtitle: 'Tap to Play Again',
),
},
),
),
),
),
],
),
),
),
),
),
),
);
}
}
| codelabs/brick_breaker/step_10/lib/src/widgets/game_app.dart/0 | {'file_path': 'codelabs/brick_breaker/step_10/lib/src/widgets/game_app.dart', 'repo_id': 'codelabs', 'token_count': 1788} |
// ignore_for_file: prefer_const_constructors
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: Center(
child: CustomButton(
backgroundColor: Colors.cyan,
child: Text("Tap me!"),
// onTap: Set the tap callback function here.
// onLongPress: Set the long press callback function here.
//
// As a bonus, create two unique buttons.
),
),
),
),
);
}
class CustomButton extends StatelessWidget {
const CustomButton({
super.key,
required this.child,
this.backgroundColor = Colors.blue,
// Add constructor parameters for onTap and onLongPress.
});
final Color backgroundColor;
final Widget child;
// Define two new `VoidCallback` instance variables: onTap and onLongPress.
@override
Widget build(BuildContext context) {
return GestureDetector(
// Replace onTap with the `onTap` instance variable.
onTap: () {
print('Handle Tap/Click');
},
// Replace onLongPress with the `onLongPress` instance variable.
onLongPress: () {
print('Handle LongPress');
},
child: Container(
padding: EdgeInsets.all(10),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(10),
),
child: child,
),
);
}
}
| codelabs/dartpad_codelabs/src/custom_button/step_04/snippet.dart/0 | {'file_path': 'codelabs/dartpad_codelabs/src/custom_button/step_04/snippet.dart', 'repo_id': 'codelabs', 'token_count': 595} |
// ignore_for_file: prefer_const_constructors, use_key_in_widget_constructors
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
home: Scaffold(
body: BlueBox(), // Replace the BlueBox with some Rows and Columns.
),
),
);
}
class BlueBox extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SizedBox(
width: 50,
height: 50,
child: DecoratedBox(
decoration: BoxDecoration(
color: Colors.blue,
border: Border.all(),
),
),
);
}
}
| codelabs/dartpad_codelabs/src/layouts/row_column/snippet.dart/0 | {'file_path': 'codelabs/dartpad_codelabs/src/layouts/row_column/snippet.dart', 'repo_id': 'codelabs', 'token_count': 251} |
// ignore_for_file: prefer_const_constructors, use_key_in_widget_constructors, avoid_print
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
title: 'My App',
home: HomePage(),
),
);
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey.shade300,
appBar: AppBar(
backgroundColor: Colors.green,
title: Text('Home Page Title'),
),
// Replace the Container with a Column that contains three Material Design
// buttons: TextButton, OutlinedButton, ElevatedButton
body: Container(
padding: EdgeInsets.all(20),
child: Material(
elevation: 10,
shadowColor: Colors.green,
textStyle: TextStyle(color: Colors.blue),
child: Center(child: Text('Home Page Content')),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('FloatingActionButton Pressed')),
),
child: Icon(Icons.send),
),
);
}
}
| codelabs/dartpad_codelabs/src/material_widgets/buttons/snippet.dart/0 | {'file_path': 'codelabs/dartpad_codelabs/src/material_widgets/buttons/snippet.dart', 'repo_id': 'codelabs', 'token_count': 476} |
name: Material Widgets
type: flutter
steps:
- name: MaterialApp
directory: material_app
has_solution: true
- name: Material Widget
directory: material_widget
has_solution: true
- name: Scaffold and AppBar
directory: scaffold
has_solution: true
- name: FloatingActionButton
directory: floating_action_button
has_solution: true
- name: Snackbar
directory: snackbar
has_solution: true
- name: Buttons
directory: buttons
has_solution: true
- name: Input
directory: input
has_solution: true
- name: Progress Indicators
directory: progress_indicators
has_solution: true
- name: Conclusion
directory: conclusion
has_solution: false | codelabs/dartpad_codelabs/src/material_widgets/meta.yaml/0 | {'file_path': 'codelabs/dartpad_codelabs/src/material_widgets/meta.yaml', 'repo_id': 'codelabs', 'token_count': 248} |
// TODO: Remove the following line
// ignore_for_file: invalid_assignment, unchecked_use_of_nullable_value
int? couldReturnNullButDoesnt() => -3;
void main() {
int? couldBeNullButIsnt = 1;
List<int?> listThatCouldHoldNulls = [2, null, 4];
int a = couldBeNullButIsnt;
int b = listThatCouldHoldNulls.first; // first item in the list
int c = couldReturnNullButDoesnt().abs(); // absolute value
print('a is $a.');
print('b is $b.');
print('c is $c.');
}
| codelabs/dartpad_codelabs/src/null_safety_workshop/step_04/snippet.dart/0 | {'file_path': 'codelabs/dartpad_codelabs/src/null_safety_workshop/step_04/snippet.dart', 'repo_id': 'codelabs', 'token_count': 168} |
import 'dart:math';
class RandomStringProvider {
String? get value => Random().nextBool() ? 'A String!' : null;
}
void printString(String str) => print(str);
void main() {
final provider = RandomStringProvider();
final str = provider.value;
if (str == null) {
print('The value is null.');
} else {
print('The value is not null, so print it!');
printString(str);
}
}
| codelabs/dartpad_codelabs/src/null_safety_workshop/step_09/solution.dart/0 | {'file_path': 'codelabs/dartpad_codelabs/src/null_safety_workshop/step_09/solution.dart', 'repo_id': 'codelabs', 'token_count': 133} |
// Copyright 2017, 2020, 2022 The Flutter team. 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:ffigen_app/ffigen_app.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
import 'duktape_message.dart';
void main() {
runApp(const ProviderScope(child: DuktapeApp()));
}
final duktapeMessagesProvider =
StateNotifierProvider<DuktapeMessageNotifier, List<DuktapeMessage>>((ref) {
return DuktapeMessageNotifier(messages: <DuktapeMessage>[]);
});
class DuktapeMessageNotifier extends StateNotifier<List<DuktapeMessage>> {
DuktapeMessageNotifier({required List<DuktapeMessage> messages})
: duktape = Duktape(),
super(messages);
final Duktape duktape;
void eval(String code) {
state = [
DuktapeMessage.evaluate(code),
...state,
];
try {
final response = duktape.evalString(code);
state = [
DuktapeMessage.response(response),
...state,
];
} catch (e) {
state = [
DuktapeMessage.error('$e'),
...state,
];
}
}
}
class DuktapeApp extends StatelessWidget {
const DuktapeApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: 'Duktape App',
home: DuktapeRepl(),
);
}
}
class DuktapeRepl extends ConsumerStatefulWidget {
const DuktapeRepl({
super.key,
});
@override
ConsumerState<DuktapeRepl> createState() => _DuktapeReplState();
}
class _DuktapeReplState extends ConsumerState<DuktapeRepl> {
final _controller = TextEditingController();
final _focusNode = FocusNode();
var _isComposing = false;
void _handleSubmitted(String text) {
_controller.clear();
setState(() {
_isComposing = false;
});
setState(() {
ref.read(duktapeMessagesProvider.notifier).eval(text);
});
_focusNode.requestFocus();
}
@override
Widget build(BuildContext context) {
final messages = ref.watch(duktapeMessagesProvider);
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
title: const Text('Duktape REPL'),
elevation: Theme.of(context).platform == TargetPlatform.iOS ? 0.0 : 4.0,
),
body: Column(
children: [
Flexible(
child: Ink(
color: Theme.of(context).scaffoldBackgroundColor,
child: SafeArea(
bottom: false,
child: ListView.builder(
padding: const EdgeInsets.all(8.0),
reverse: true,
itemBuilder: (context, idx) => messages[idx].when(
evaluate: (str) => Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Text(
'> $str',
style: GoogleFonts.firaCode(
textStyle: Theme.of(context).textTheme.titleMedium,
),
),
),
response: (str) => Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Text(
'= $str',
style: GoogleFonts.firaCode(
textStyle: Theme.of(context).textTheme.titleMedium,
color: Colors.blue[800],
),
),
),
error: (str) => Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Text(
str,
style: GoogleFonts.firaCode(
textStyle: Theme.of(context).textTheme.titleSmall,
color: Colors.red[800],
fontWeight: FontWeight.bold,
),
),
),
),
itemCount: messages.length,
),
),
),
),
const Divider(height: 1.0),
SafeArea(
top: false,
child: Container(
decoration: BoxDecoration(color: Theme.of(context).cardColor),
child: _buildTextComposer(),
),
),
],
),
);
}
Widget _buildTextComposer() {
return IconTheme(
data: IconThemeData(color: Theme.of(context).colorScheme.secondary),
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 8.0),
child: Row(
children: [
Text('>', style: Theme.of(context).textTheme.titleMedium),
const SizedBox(width: 4),
Flexible(
child: TextField(
controller: _controller,
decoration: const InputDecoration(
border: InputBorder.none,
),
onChanged: (text) {
setState(() {
_isComposing = text.isNotEmpty;
});
},
onSubmitted: _isComposing ? _handleSubmitted : null,
focusNode: _focusNode,
),
),
Container(
margin: const EdgeInsets.symmetric(horizontal: 4.0),
child: IconButton(
icon: const Icon(Icons.send),
onPressed: _isComposing
? () => _handleSubmitted(_controller.text)
: null,
),
),
],
),
),
);
}
}
| codelabs/ffigen_codelab/step_07/example/lib/main.dart/0 | {'file_path': 'codelabs/ffigen_codelab/step_07/example/lib/main.dart', 'repo_id': 'codelabs', 'token_count': 3020} |
import 'package:flutter/material.dart';
import 'auth_gate.dart';
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const AuthGate(),
);
}
}
| codelabs/firebase-auth-flutterfire-ui/start/lib/app.dart/0 | {'file_path': 'codelabs/firebase-auth-flutterfire-ui/start/lib/app.dart', 'repo_id': 'codelabs', 'token_count': 151} |
// 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 'package:flutter/material.dart';
import 'app_state.dart';
import 'src/widgets.dart';
class YesNoSelection extends StatelessWidget {
const YesNoSelection({
super.key,
required this.state,
required this.onSelection,
});
final Attending state;
final void Function(Attending selection) onSelection;
@override
Widget build(BuildContext context) {
switch (state) {
case Attending.yes:
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
FilledButton(
onPressed: () => onSelection(Attending.yes),
child: const Text('YES'),
),
const SizedBox(width: 8),
TextButton(
onPressed: () => onSelection(Attending.no),
child: const Text('NO'),
),
],
),
);
case Attending.no:
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
TextButton(
onPressed: () => onSelection(Attending.yes),
child: const Text('YES'),
),
const SizedBox(width: 8),
FilledButton(
onPressed: () => onSelection(Attending.no),
child: const Text('NO'),
),
],
),
);
default:
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
StyledButton(
onPressed: () => onSelection(Attending.yes),
child: const Text('YES'),
),
const SizedBox(width: 8),
StyledButton(
onPressed: () => onSelection(Attending.no),
child: const Text('NO'),
),
],
),
);
}
}
}
| codelabs/firebase-get-to-know-flutter/step_09/lib/yes_no_selection.dart/0 | {'file_path': 'codelabs/firebase-get-to-know-flutter/step_09/lib/yes_no_selection.dart', 'repo_id': 'codelabs', 'token_count': 1096} |
# Copyright 2020 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.
name: window_to_front
description: "A new Flutter plugin project."
version: 0.0.1
homepage:
environment:
sdk: '>=3.2.3 <4.0.0'
flutter: '>=3.3.0'
dependencies:
flutter:
sdk: flutter
plugin_platform_interface: ^2.0.2
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^3.0.1
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# This section identifies this Flutter project as a plugin project.
# The 'pluginClass' specifies the class (in Java, Kotlin, Swift, Objective-C, etc.)
# which should be registered in the plugin registry. This is required for
# using method channels.
# The Android 'package' specifies package in which the registered class is.
# This is required for using method channels on Android.
# The 'ffiPlugin' specifies that native code should be built and bundled.
# This is required for using `dart:ffi`.
# All these are used by the tooling to maintain consistency when
# adding or updating assets for this project.
plugin:
platforms:
linux:
pluginClass: WindowToFrontPlugin
macos:
pluginClass: WindowToFrontPlugin
windows:
pluginClass: WindowToFrontPluginCApi
# To add assets to your plugin package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.dev/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware
# To add custom fonts to your plugin package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.dev/custom-fonts/#from-packages
| codelabs/github-client/window_to_front/pubspec.yaml/0 | {'file_path': 'codelabs/github-client/window_to_front/pubspec.yaml', 'repo_id': 'codelabs', 'token_count': 982} |
/*
* 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:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late GoogleMapController mapController;
final LatLng _center = const LatLng(45.521563, -122.677433);
void _onMapCreated(GoogleMapController controller) {
mapController = controller;
}
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
useMaterial3: true,
colorSchemeSeed: Colors.green[700],
),
home: Scaffold(
appBar: AppBar(
title: const Text('Maps Sample App'),
elevation: 2,
),
body: GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: _center,
zoom: 11.0,
),
),
),
);
}
}
| codelabs/google-maps-in-flutter/step_4/lib/main.dart/0 | {'file_path': 'codelabs/google-maps-in-flutter/step_4/lib/main.dart', 'repo_id': 'codelabs', 'token_count': 588} |
// Copyright (c) 2022, 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:firebase_backend_dart/helpers.dart';
import 'package:shelf_router/shelf_router.dart';
Future<void> main() async {
final router = Router();
// Start service
await serveHandler(router.call);
}
| codelabs/in_app_purchases/step_00/dart-backend/bin/server.dart/0 | {'file_path': 'codelabs/in_app_purchases/step_00/dart-backend/bin/server.dart', 'repo_id': 'codelabs', 'token_count': 130} |
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:convert';
import 'dart:io';
import 'package:firebase_backend_dart/app_store_purchase_handler.dart';
import 'package:firebase_backend_dart/google_play_purchase_handler.dart';
import 'package:firebase_backend_dart/helpers.dart';
import 'package:firebase_backend_dart/iap_repository.dart';
import 'package:firebase_backend_dart/products.dart';
import 'package:firebase_backend_dart/purchase_handler.dart';
import 'package:googleapis/androidpublisher/v3.dart' as ap;
import 'package:googleapis/firestore/v1.dart' as fs;
import 'package:googleapis_auth/auth_io.dart' as auth;
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
/// Creates the Google Play and Apple Store [PurchaseHandler]
/// and their dependencies
Future<Map<String, PurchaseHandler>> _createPurchaseHandlers() async {
// Configure Android Publisher API access
final serviceAccountGooglePlay =
File('assets/service-account-google-play.json').readAsStringSync();
final clientCredentialsGooglePlay =
auth.ServiceAccountCredentials.fromJson(serviceAccountGooglePlay);
final clientGooglePlay =
await auth.clientViaServiceAccount(clientCredentialsGooglePlay, [
ap.AndroidPublisherApi.androidpublisherScope,
]);
final androidPublisher = ap.AndroidPublisherApi(clientGooglePlay);
// Configure Firestore API access
final serviceAccountFirebase =
File('assets/service-account-firebase.json').readAsStringSync();
final clientCredentialsFirebase =
auth.ServiceAccountCredentials.fromJson(serviceAccountFirebase);
final clientFirebase =
await auth.clientViaServiceAccount(clientCredentialsFirebase, [
fs.FirestoreApi.cloudPlatformScope,
]);
final firestoreApi = fs.FirestoreApi(clientFirebase);
final dynamic json = jsonDecode(serviceAccountFirebase);
final projectId = json['project_id'] as String;
final iapRepository = IapRepository(firestoreApi, projectId);
return {
'google_play': GooglePlayPurchaseHandler(
androidPublisher,
iapRepository,
),
'app_store': AppStorePurchaseHandler(
iapRepository,
),
};
}
Future<void> main() async {
final router = Router();
final purchaseHandlers = await _createPurchaseHandlers();
/// Warning: This endpoint has no security
/// and does not implement user authentication.
/// Production applications should implement authentication.
// ignore: avoid_types_on_closure_parameters
router.post('/verifypurchase', (Request request) async {
final dynamic payload = json.decode(await request.readAsString());
// NOTE: userId should be obtained using authentication methods.
// source from PurchaseDetails.verificationData.source
// productData product data based on the productId
// token from PurchaseDetails.verificationData.serverVerificationData
final (:userId, :source, :productData, :token) = getPurchaseData(payload);
// Will call to verifyPurchase on
// [GooglePlayPurchaseHandler] or [AppleStorePurchaseHandler]
final result = await purchaseHandlers[source]!.verifyPurchase(
userId: userId,
productData: productData,
token: token,
);
if (result) {
// Note: Better success response recommended
return Response.ok('all good!');
} else {
// Note: Better error handling recommended
return Response.internalServerError();
}
});
// Start service
await serveHandler(router.call);
}
({
String userId,
String source,
ProductData productData,
String token,
}) getPurchaseData(dynamic payload) {
if (payload
case {
'userId': String userId,
'source': String source,
'productId': String productId,
'verificationData': String token,
}) {
return (
userId: userId,
source: source,
productData: productDataMap[productId]!,
token: token,
);
} else {
throw const FormatException('Unexpected JSON');
}
}
| codelabs/in_app_purchases/step_09/dart-backend/bin/server.dart/0 | {'file_path': 'codelabs/in_app_purchases/step_09/dart-backend/bin/server.dart', 'repo_id': 'codelabs', 'token_count': 1349} |
// 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:extra_alignments/extra_alignments.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import '../assets.dart';
import '../common/ui_scaler.dart';
import '../styles.dart';
class TitleScreenUi extends StatelessWidget {
const TitleScreenUi({
super.key,
});
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: 40, horizontal: 50),
child: Stack(
children: [
/// Title Text
TopLeft(
child: UiScaler(
alignment: Alignment.topLeft,
child: _TitleText(),
),
),
],
),
);
}
}
class _TitleText extends StatelessWidget {
const _TitleText();
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Gap(20),
Row(
mainAxisSize: MainAxisSize.min,
children: [
Transform.translate(
offset: Offset(-(TextStyles.h1.letterSpacing! * .5), 0),
child: Text('OUTPOST', style: TextStyles.h1),
),
Image.asset(AssetPaths.titleSelectedLeft, height: 65),
Text('57', style: TextStyles.h2),
Image.asset(AssetPaths.titleSelectedRight, height: 65),
],
),
Text('INTO THE UNKNOWN', style: TextStyles.h3),
],
);
}
}
| codelabs/next-gen-ui/step_03_a/lib/title_screen/title_screen_ui.dart/0 | {'file_path': 'codelabs/next-gen-ui/step_03_a/lib/title_screen/title_screen_ui.dart', 'repo_id': 'codelabs', 'token_count': 749} |
import 'package:flutter_test/flutter_test.dart';
import 'package:tfserving_flutter/main.dart';
void main() {
testWidgets(' smoke test', (tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const TFServingDemo());
// Verify that our counter starts at 0.
expect(find.text('Classify'), findsOneWidget);
expect(find.text('Reset'), findsOneWidget);
});
}
| codelabs/tfserving-flutter/codelab2/starter/test/widget_test.dart/0 | {'file_path': 'codelabs/tfserving-flutter/codelab2/starter/test/widget_test.dart', 'repo_id': 'codelabs', 'token_count': 140} |
include: ../../analysis_options.yaml
| codelabs/webview_flutter/step_11/analysis_options.yaml/0 | {'file_path': 'codelabs/webview_flutter/step_11/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 12} |
import 'dart:async';
import 'package:meta/meta.dart';
import 'models/models.dart';
class WeatherRepository {
Future<Weather> getWeather({@required String city}) async {
await Future.delayed(Duration(seconds: 1));
return Weather(
temperature: 30,
condition: Condition.sunny,
);
}
}
| codemagic_bloc_unit_tests/weather_repository/lib/src/weather_repository.dart/0 | {'file_path': 'codemagic_bloc_unit_tests/weather_repository/lib/src/weather_repository.dart', 'repo_id': 'codemagic_bloc_unit_tests', 'token_count': 110} |
import 'package:meta/meta.dart';
/// {@template transition}
/// A [Transition] represents the change from one [State] to another.
/// A [Transition] consists of the [currentState] and [nextState].
/// {@endtemplate}
@immutable
class Transition<State> {
/// {@macro transition}
const Transition({@required this.currentState, @required this.nextState});
/// The current [State] at the time of the [Transition].
final State currentState;
/// The next [State] at the time of the [Transition].
final State nextState;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Transition<State> &&
runtimeType == other.runtimeType &&
currentState == other.currentState &&
nextState == other.nextState;
@override
int get hashCode => currentState.hashCode ^ nextState.hashCode;
@override
String toString() {
return 'Transition { currentState: $currentState, nextState: $nextState }';
}
}
| cubit/packages/cubit/lib/src/transition.dart/0 | {'file_path': 'cubit/packages/cubit/lib/src/transition.dart', 'repo_id': 'cubit', 'token_count': 311} |
library cubit_test;
export 'src/cubit_test.dart';
export 'src/mock_cubit.dart';
export 'src/when_listen.dart';
| cubit/packages/cubit_test/lib/cubit_test.dart/0 | {'file_path': 'cubit/packages/cubit_test/lib/cubit_test.dart', 'repo_id': 'cubit', 'token_count': 50} |
import 'package:flutter/widgets.dart';
import 'package:provider/provider.dart';
import 'cubit_listener.dart';
/// {@template multi_cubit_listener}
/// Merges multiple [CubitListener] widgets into one widget tree.
///
/// [MultiCubitListener] improves the readability and eliminates the need
/// to nest multiple [CubitListener]s.
///
/// By using [MultiCubitListener] we can go from:
///
/// ```dart
/// CubitListener<CubitA, CubitAState>(
/// listener: (context, state) {},
/// child: CubitListener<CubitB, CubitBState>(
/// listener: (context, state) {},
/// child: CubitListener<CubitC, CubitCState>(
/// listener: (context, state) {},
/// child: ChildA(),
/// ),
/// ),
/// )
/// ```
///
/// to:
///
/// ```dart
/// MultiCubitListener(
/// listeners: [
/// CubitListener<CubitA, CubitAState>(
/// listener: (context, state) {},
/// ),
/// CubitListener<CubitB, CubitBState>(
/// listener: (context, state) {},
/// ),
/// CubitListener<CubitC, CubitCState>(
/// listener: (context, state) {},
/// ),
/// ],
/// child: ChildA(),
/// )
/// ```
///
/// [MultiCubitListener] converts the [CubitListener] list into a tree of nested
/// [CubitListener] widgets.
/// As a result, the only advantage of using [MultiCubitListener] is improved
/// readability due to the reduction in nesting and boilerplate.
/// {@endtemplate}
class MultiCubitListener extends MultiProvider {
/// {@macro multi_cubit_listener}
MultiCubitListener({
Key key,
@required List<CubitListenerSingleChildWidget> listeners,
@required Widget child,
}) : assert(listeners != null),
assert(child != null),
super(key: key, providers: listeners, child: child);
}
| cubit/packages/flutter_cubit/lib/src/multi_cubit_listener.dart/0 | {'file_path': 'cubit/packages/flutter_cubit/lib/src/multi_cubit_listener.dart', 'repo_id': 'cubit', 'token_count': 627} |
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:hive/hive.dart';
import 'package:path/path.dart' as p;
// ignore: implementation_imports
import 'package:hive/src/hive_impl.dart';
void main() {
group('Hive interference', () {
test('odd singleton interference', () async {
final cwd = Directory.current.absolute.path;
final impl1 = Hive..init(cwd);
var box1 = await impl1.openBox<dynamic>('impl1');
final impl2 = Hive..init(cwd);
var box2 = await impl2.openBox<dynamic>('impl2');
await impl1.close();
expect(box1.isOpen, true);
expect(box2.isOpen, false);
await box1.deleteFromDisk();
await Hive.deleteBoxFromDisk('impl2');
});
test('two hive impls beside same directory', () async {
final cwd = Directory.current.absolute.path;
final impl1 = Hive..init(cwd);
var box1 = await impl1.openBox<dynamic>('impl1');
final impl2 = HiveImpl()..init(cwd);
var box2 = await impl2.openBox<dynamic>('impl2');
await box1.put('instance', 'impl1');
await box2.put('instance', 'impl2');
await impl1.close();
await impl2.close();
box1 = await impl1.openBox<dynamic>('impl1');
box2 = await impl2.openBox<dynamic>('impl2');
expect(box1.get('instance'), 'impl1');
expect(box2.get('instance'), 'impl2');
await impl1.deleteFromDisk();
expect(box1.isOpen, false);
expect(box2.isOpen, true);
expect(box2.get('instance'), 'impl2');
await impl2.deleteFromDisk();
expect(box2.isOpen, false);
});
test('two hive impls reside distinct directories', () async {
final cwd1 = p.join(Directory.current.absolute.path, 'cwd1');
final cwd2 = p.join(Directory.current.absolute.path, 'cwd2');
final impl1 = Hive..init(cwd1);
var box1 = await impl1.openBox<dynamic>('impl1');
final impl2 = HiveImpl()..init(cwd2);
var box2 = await impl2.openBox<dynamic>('impl2');
await box1.put('instance', 'impl1');
await box2.put('instance', 'impl2');
await impl1.close();
await impl2.close();
box1 = await impl1.openBox<dynamic>('impl1');
box2 = await impl2.openBox<dynamic>('impl2');
expect(box1.get('instance'), 'impl1');
expect(box2.get('instance'), 'impl2');
await impl1.deleteFromDisk();
expect(box1.isOpen, false);
expect(box2.isOpen, true);
expect(box2.get('instance'), 'impl2');
await impl2.deleteFromDisk();
expect(box2.isOpen, false);
await Directory(cwd1).delete();
await Directory(cwd2).delete();
});
});
}
| cubit/packages/hydrated_cubit/test/hive_interference_test.dart/0 | {'file_path': 'cubit/packages/hydrated_cubit/test/hive_interference_test.dart', 'repo_id': 'cubit', 'token_count': 1094} |
void main(List<String> args) {}
| dart-for-beginners-course/001_hello_world/main.dart/0 | {'file_path': 'dart-for-beginners-course/001_hello_world/main.dart', 'repo_id': 'dart-for-beginners-course', 'token_count': 11} |
name: dummylib
version: 1.0.0
environment:
sdk: ">=3.0.0 <4.0.0" | dart-hotreloader/example/dummylib_v1/pubspec.yaml/0 | {'file_path': 'dart-hotreloader/example/dummylib_v1/pubspec.yaml', 'repo_id': 'dart-hotreloader', 'token_count': 36} |
// 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:convert';
import 'package:convert/convert.dart' show IdentityCodec;
import 'package:logging/logging.dart';
import 'package:retry/retry.dart';
import 'cache_provider.dart';
import 'src/providers/inmemory.dart';
import 'src/providers/redis.dart';
final _logger = Logger('neat_cache');
/// Cache for objects of type [T], wrapping a [CacheProvider] to provide a
/// high-level interface.
///
/// Cache entries are accessed using the indexing operator `[]`, this returns a
/// [Entry<T>] wrapper that can be used to get/set data cached at given key.
///
/// **Example**
/// ```dart
/// final Cache<List<int>> cache = Cache.inMemoryCache(4096);
///
/// // Write data to cache
/// await cache['cached-zeros'].set([0, 0, 0, 0]);
///
/// // Read data from cache
/// var r = await cache['cached-zeros'].get();
/// expect(r, equals([0, 0, 0, 0]));
/// ```
///
/// A [Cache] can be _fused_ with a [Codec] using [withCodec] to get a cache
/// that stores a different kind of objects. It is also possible to create
/// a chuild cache using [withPrefix], such that all entries in the child
/// cache have a given prefix.
abstract class Cache<T> {
/// Get [Entry] wrapping data cached at [key].
Entry<T> operator [](String key);
/// Get a [Cache] wrapping of this cache with given [prefix].
Cache<T> withPrefix(String prefix);
/// Get a [Cache] wrapping of this cache by encoding objects of type [S] as
/// [T] using the given [codec].
Cache<S> withCodec<S>(Codec<S, T> codec);
/// Get a [Cache] wrapping of this cache with given [ttl] as default for all
/// entries being set using [Entry.set].
///
/// This only specifies a different default [ttl], to be used when [Entry.set]
/// is called without a [ttl] parameter.
Cache<T> withTTL(Duration ttl);
/// Create a [Cache] wrapping a [CacheProvider].
factory Cache(CacheProvider<T> provider) {
return _Cache<T, T>(provider, '', IdentityCodec());
}
/// Create an in-memory [CacheProvider] holding a maximum of [maxSize] cache
/// entries.
static CacheProvider<List<int>> inMemoryCacheProvider(int maxSize) {
return InMemoryCacheProvider(maxSize);
}
/// Create a redis [CacheProvider] by connecting using a [connectionString] on
/// the form `redis://<host>:<port>`.
static CacheProvider<List<int>> redisCacheProvider(Uri connectionString) {
return RedisCacheProvider(connectionString);
}
}
/// Pointer to a location in the cache.
///
/// This simply wraps a cache key, such that you don't need to supply a cache
/// key for [get], [set] and [purge] operations.
abstract class Entry<T> {
/// Get value stored in this cache entry.
///
/// If used without [create], this function simply gets the value or `null` if
/// no value is stored.
///
/// If used with [create], this function becomes an upsert, returning the
/// value stored if any, otherwise creating a new value and storing it with
/// optional [ttl]. If multiple callers are using the same cache this is an
/// inherently racy operation, that is multiple instances of the value may
/// be created.
///
/// The [get] method is a best-effort method. In case of intermittent failures
/// from the underlying [CacheProvider] the [get] method will ignore failures
/// and return `null` (or result from [create] if specified).
Future<T?> get([Future<T?> Function() create, Duration ttl]);
/// Set the value stored in this cache entry.
///
/// If given [ttl] specifies the time-to-live. Notice that this is advisatory,
/// the underlying [CacheProvider] may choose to evit cache entries at any
/// time. However, it can be assumed that entries will not live far past
/// their [ttl].
///
/// The [set] method is a best-effort method. In case of intermittent failures
/// from the underlying [CacheProvider] the [set] method will ignore failures.
///
/// To ensure that cache entries are purged, use the [purge] method with
/// `retries` not set to zero.
Future<T?> set(T? value, [Duration ttl]);
/// Clear the value stored in this cache entry.
///
/// If [retries] is `0` (default), this is a best-effort method, which will
/// ignore intermittent failures. If [retries] is non-zero the operation will
/// be retried with exponential back-off, and [IntermittentCacheException]
/// will be thrown if all retries fails.
Future purge({int retries = 0});
}
class _Cache<T, V> implements Cache<T> {
final CacheProvider<V> _provider;
final String _prefix;
final Codec<T, V> _codec;
final Duration? _ttl;
_Cache(this._provider, this._prefix, this._codec, [this._ttl]);
@override
Entry<T> operator [](String key) => _Entry(this, _prefix + key);
@override
Cache<T> withPrefix(String prefix) =>
_Cache(_provider, _prefix + prefix, _codec, _ttl);
@override
Cache<S> withCodec<S>(Codec<S, T> codec) =>
_Cache(_provider, _prefix, codec.fuse(_codec), _ttl);
@override
Cache<T> withTTL(Duration ttl) => _Cache(_provider, _prefix, _codec, ttl);
}
class _Entry<T, V> implements Entry<T> {
final _Cache<T, V> _owner;
final String _key;
_Entry(this._owner, this._key);
@override
Future<T?> get([Future<T?> Function()? create, Duration? ttl]) async {
V? value;
try {
_logger.finest(() => 'reading cache entry for "$_key"');
value = await _owner._provider.get(_key);
} on IntermittentCacheException {
_logger.fine(
// embedding [intermittent-cache-failure] to allow for easy log metrics
'[intermittent-cache-failure], failed to get cache entry for "$_key"',
);
value = null;
}
if (value == null) {
if (create == null) {
return null;
}
final created = await create();
if (created != null) {
// Calling `set(null)` is equivalent to `purge()`, we can skip that here
await set(created, ttl);
}
return created;
}
return _owner._codec.decode(value);
}
@override
Future<T?> set(T? value, [Duration? ttl]) async {
if (value == null) {
await purge();
return null;
}
ttl ??= _owner._ttl;
final raw = _owner._codec.encode(value);
try {
await _owner._provider.set(_key, raw, ttl);
} on IntermittentCacheException {
_logger.fine(
// embedding [intermittent-cache-failure] to allow for easy log metrics
'[intermittent-cache-failure], failed to set cache entry for "$_key"',
);
}
return value;
}
@override
Future<void> purge({int retries = 0}) async {
// Common path is that we have no retries
if (retries == 0) {
try {
await _owner._provider.purge(_key);
} on IntermittentCacheException {
_logger.fine(
// embedding [intermittent-cache-failure] to allow for easy log metrics
'[intermittent-cache-failure], failed to purge cache entry for "$_key"',
);
}
return;
}
// Test that we have a positive number of retries.
if (retries < 0) {
ArgumentError.value(retries, 'retries', 'retries < 0 is not allowed');
}
return await retry(
() => _owner._provider.purge(_key),
retryIf: (e) => e is IntermittentCacheException,
maxAttempts: 1 + retries,
);
}
}
| dart-neats/neat_cache/lib/neat_cache.dart/0 | {'file_path': 'dart-neats/neat_cache/lib/neat_cache.dart', 'repo_id': 'dart-neats', 'token_count': 2650} |
include: package:lints/recommended.yaml
| dart-neats/sanitize_html/analysis_options.yaml/0 | {'file_path': 'dart-neats/sanitize_html/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:collection' show UnmodifiableMapView;
import 'dart:convert';
import 'package:http_methods/http_methods.dart';
import 'package:meta/meta.dart' show sealed;
import 'package:shelf/shelf.dart';
import 'package:shelf_router/src/router_entry.dart' show RouterEntry;
/// Get a URL parameter captured by the [Router].
@Deprecated('Use Request.params instead')
String params(Request request, String name) {
final value = request.params[name];
if (value == null) {
throw Exception('no such parameter $name');
}
return value;
}
final _emptyParams = UnmodifiableMapView(<String, String>{});
extension RouterParams on Request {
/// Get URL parameters captured by the [Router].
///
/// **Example**
/// ```dart
/// final app = Router();
///
/// app.get('/hello/<name>', (Request request) {
/// final name = request.params['name'];
/// return Response.ok('Hello $name');
/// });
/// ```
///
/// If no parameters are captured this returns an empty map.
///
/// The returned map is unmodifiable.
Map<String, String> get params {
final p = context['shelf_router/params'];
if (p is Map<String, String>) {
return UnmodifiableMapView(p);
}
return _emptyParams;
}
}
/// Middleware to remove body from request.
final _removeBody = createMiddleware(responseHandler: (r) {
if (r.headers.containsKey('content-length')) {
r = r.change(headers: {'content-length': '0'});
}
return r.change(body: <int>[]);
});
/// A shelf [Router] routes requests to handlers based on HTTP verb and route
/// pattern.
///
/// ```dart
/// import 'package:shelf_router/shelf_router.dart';
/// import 'package:shelf/shelf.dart';
/// import 'package:shelf/shelf_io.dart' as io;
///
/// var app = Router();
///
/// // Route pattern parameters can be specified <paramName>
/// app.get('/users/<userName>/whoami', (Request request) async {
/// // The matched values can be read with params(request, param)
/// var userName = request.params['userName'];
/// return Response.ok('You are ${userName}');
/// });
///
/// // The matched value can also be taken as parameter, if the handler given
/// // doesn't implement Handler, it's assumed to take all parameters in the
/// // order they appear in the route pattern.
/// app.get('/users/<userName>/say-hello', (Request request, String userName) async {
/// assert(userName == request.params['userName']);
/// return Response.ok('Hello ${userName}');
/// });
///
/// // It is possible to have multiple parameters, and if desired a custom
/// // regular expression can be specified with <paramName|REGEXP>, where
/// // REGEXP is a regular expression (leaving out ^ and $).
/// // If no regular expression is specified `[^/]+` will be used.
/// app.get('/users/<userName>/messages/<msgId|\d+>', (Request request) async {
/// var msgId = int.parse(request.params['msgId']!);
/// return Response.ok(message.getById(msgId));
/// });
///
/// var server = await io.serve(app, 'localhost', 8080);
/// ```
///
/// If multiple routes match the same request, the handler for the first
/// route is called.
/// If no route matches a request, a [Response.notFound] will be returned
/// instead. The default matcher can be overridden with the `notFoundHandler`
/// constructor parameter.
@sealed
class Router {
final List<RouterEntry> _routes = [];
final Handler _notFoundHandler;
/// Creates a new [Router] routing requests to handlers.
///
/// The [notFoundHandler] will be invoked for requests where no matching route
/// was found. By default, a simple [Response.notFound] will be used instead.
Router({Handler notFoundHandler = _defaultNotFound})
: _notFoundHandler = notFoundHandler;
/// Add [handler] for [verb] requests to [route].
///
/// If [verb] is `GET` the [handler] will also be called for `HEAD` requests
/// matching [route]. This is because handling `GET` requests without handling
/// `HEAD` is always wrong. To explicitely implement a `HEAD` handler it must
/// be registered before the `GET` handler.
void add(String verb, String route, Function handler) {
if (!isHttpMethod(verb)) {
throw ArgumentError.value(verb, 'verb', 'expected a valid HTTP method');
}
verb = verb.toUpperCase();
if (verb == 'GET') {
// Handling in a 'GET' request without handling a 'HEAD' request is always
// wrong, thus, we add a default implementation that discards the body.
_routes.add(RouterEntry('HEAD', route, handler, middleware: _removeBody));
}
_routes.add(RouterEntry(verb, route, handler));
}
/// Handle all request to [route] using [handler].
void all(String route, Function handler) {
_routes.add(RouterEntry('ALL', route, handler));
}
/// Mount a handler below a prefix.
///
/// In this case prefix may not contain any parameters, nor
void mount(String prefix, Handler handler) {
if (!prefix.startsWith('/')) {
throw ArgumentError.value(prefix, 'prefix', 'must start with a slash');
}
// first slash is always in request.handlerPath
final path = prefix.substring(1);
if (prefix.endsWith('/')) {
all(prefix + '<path|[^]*>', (Request request) {
return handler(request.change(path: path));
});
} else {
all(prefix, (Request request) {
return handler(request.change(path: path));
});
all(prefix + '/<path|[^]*>', (Request request) {
return handler(request.change(path: path + '/'));
});
}
}
/// Route incoming requests to registered handlers.
///
/// This method allows a Router instance to be a [Handler].
Future<Response> call(Request request) async {
// Note: this is a great place to optimize the implementation by building
// a trie for faster matching... left as an exercise for the reader :)
for (var route in _routes) {
if (route.verb != request.method.toUpperCase() && route.verb != 'ALL') {
continue;
}
var params = route.match('/' + request.url.path);
if (params != null) {
final response = await route.invoke(request, params);
if (response != routeNotFound) {
return response;
}
}
}
return _notFoundHandler(request);
}
// Handlers for all methods
/// Handle `GET` request to [route] using [handler].
///
/// If no matching handler for `HEAD` requests is registered, such requests
/// will also be routed to the [handler] registered here.
void get(String route, Function handler) => add('GET', route, handler);
/// Handle `HEAD` request to [route] using [handler].
void head(String route, Function handler) => add('HEAD', route, handler);
/// Handle `POST` request to [route] using [handler].
void post(String route, Function handler) => add('POST', route, handler);
/// Handle `PUT` request to [route] using [handler].
void put(String route, Function handler) => add('PUT', route, handler);
/// Handle `DELETE` request to [route] using [handler].
void delete(String route, Function handler) => add('DELETE', route, handler);
/// Handle `CONNECT` request to [route] using [handler].
void connect(String route, Function handler) =>
add('CONNECT', route, handler);
/// Handle `OPTIONS` request to [route] using [handler].
void options(String route, Function handler) =>
add('OPTIONS', route, handler);
/// Handle `TRACE` request to [route] using [handler].
void trace(String route, Function handler) => add('TRACE', route, handler);
/// Handle `PATCH` request to [route] using [handler].
void patch(String route, Function handler) => add('PATCH', route, handler);
static Response _defaultNotFound(Request request) => routeNotFound;
/// Sentinel [Response] object indicating that no matching route was found.
///
/// This is the default response value from a [Router] created without a
/// `notFoundHandler`, when no routes matches the incoming request.
///
/// If the [routeNotFound] object is returned from a [Handler] the [Router]
/// will consider the route _not matched_, and attempt to match other routes.
/// This is useful when mounting nested routers, or when matching a route
/// is conditioned on properties beyond the path of the URL.
///
/// **Example**
/// ```dart
/// final app = Router();
///
/// // The pattern for this route will match '/search' and '/search?q=...',
/// // but if request does not have `?q=...', then the handler will return
/// // [Router.routeNotFound] causing the router to attempt further routes.
/// app.get('/search', (Request request) async {
/// if (!request.uri.queryParameters.containsKey('q')) {
/// return Router.routeNotFound;
/// }
/// return Response.ok('TODO: make search results');
/// });
///
/// // Same pattern as above
/// app.get('/search', (Request request) async {
/// return Response.ok('TODO: return search form');
/// });
///
/// // Create a single nested router we can mount for handling API requests.
/// final api = Router();
///
/// api.get('/version', (Request request) => Response.ok('1'));
///
/// // Mounting router under '/api'
/// app.mount('/api', api);
///
/// // If a request matches `/api/...` then the routes in the [api] router
/// // will be attempted. However, for a request like `/api/hello` there is
/// // no matching route in the [api] router. Thus, the router will return
/// // [Router.routeNotFound], which will cause matching to continue.
/// // Hence, the catch-all route below will be matched, causing a custom 404
/// // response with message 'nothing found'.
///
/// // In the pattern below `<anything|.*>` is on the form `<name|regex>`,
/// // thus, this simply creates a URL parameter called `anything` which
/// // matches anything.
/// app.all('/<anything|.*>', (Request request) {
/// return Response.notFound('nothing found');
/// });
/// ```
static final Response routeNotFound = _RouteNotFoundResponse();
}
/// Extends [Response] to allow it to be used multiple times in the
/// actual content being served.
class _RouteNotFoundResponse extends Response {
static const _message = 'Route not found';
static final _messageBytes = utf8.encode(_message);
_RouteNotFoundResponse() : super.notFound(_message);
@override
Stream<List<int>> read() => Stream<List<int>>.value(_messageBytes);
@override
Response change({
Map<String, /* String | List<String> */ Object?>? headers,
Map<String, Object?>? context,
body,
}) {
return super.change(
headers: headers,
context: context,
body: body ?? _message,
);
}
}
| dart-neats/shelf_router/lib/src/router.dart/0 | {'file_path': 'dart-neats/shelf_router/lib/src/router.dart', 'repo_id': 'dart-neats', 'token_count': 3472} |
name: shelf_router_generator
version: 1.0.2
description: >-
A package:build compatible builder for generating request routers for the
shelf web-framework based on source annotations.
homepage: https://github.com/google/dart-neats/tree/master/shelf_router_generator
repository: https://github.com/google/dart-neats.git
issue_tracker: https://github.com/google/dart-neats/labels/pkg:shelf_router_generator
dependencies:
analyzer: '>=2.0.0 <4.0.0'
build: ^2.0.0
build_config: ^1.0.0
code_builder: ^4.0.0
http_methods: ^1.0.0
shelf: ^1.1.0
shelf_router: ^1.0.0
source_gen: ^1.0.0
dev_dependencies:
build_runner: ^2.0.0
build_verify: ^3.0.0
http: ^0.13.0
lints: ^1.0.0
test: ^1.5.3
environment:
sdk: '>=2.12.0 <3.0.0'
| dart-neats/shelf_router_generator/pubspec.yaml/0 | {'file_path': 'dart-neats/shelf_router_generator/pubspec.yaml', 'repo_id': 'dart-neats', 'token_count': 325} |
// Copyright 2022 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:meta/meta.dart' show sealed;
import 'package:pub_semver/pub_semver.dart' show Version;
import 'package:vendor/src/action/import_rewrite.dart' show ImportRewriteAction;
import 'package:vendor/src/action/fetch_package.dart' show FetchPackageAction;
import 'package:vendor/src/action/remove_folder.dart' show RemoveFolderAction;
import 'package:vendor/src/action/write_file.dart' show WriteFileAction;
import 'package:vendor/src/context.dart' show Context;
export 'package:vendor/src/context.dart' show Context;
/// An [Action] is a step that can be planned for execution when vendoring.
///
/// This allows for steps to first be planned and then executed. Thus, we can
/// a dry-run that only creates actions and displays them, but doesn't actually
/// execute the actions.
@sealed
abstract class Action {
/// Short single-line humand readable description of this action.
String get summary;
/// Long-form human readable description of what this action entails.
///
/// Usually a single line summary, followed by a few lines of details.
String get description => summary;
/// Execute this action in the given [ctx].
Future<void> apply(Context ctx);
/// Rewrite import/export statements pointing to [from] in [folder], such that
/// they now point to [to].
static Action rewriteImportPath({
required Uri folder,
required Uri from,
required Uri to,
}) =>
ImportRewriteAction(
folder: folder,
from: from,
to: to,
);
/// Fetch [package] [version] from [hostedUrl] into [folder].
///
/// Only includes files that match a `package:glob` pattern from [include].
static Action fetchPackage(
Uri folder,
String package,
Version version,
Uri hostedUrl,
Set<String> include,
) =>
FetchPackageAction(
folder: folder,
package: package,
version: version,
hostedUrl: hostedUrl,
include: include,
);
/// Remove [folder].
static Action removeFolder(
Uri folder,
) =>
RemoveFolderAction(folder);
/// Write [contents] to [file].
static Action writeFile(
Uri file,
String contents,
) =>
WriteFileAction(file, contents);
}
| dart-neats/vendor/lib/src/action/action.dart/0 | {'file_path': 'dart-neats/vendor/lib/src/action/action.dart', 'repo_id': 'dart-neats', 'token_count': 869} |
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
library dartpad.actions;
import 'dart:html';
import 'dialogs.dart';
import 'elements/elements.dart';
import 'sharing/gists.dart';
/// An action that creates a new pad when clicked.
class NewPadAction {
final DButton _button;
final GistController _gistController;
NewPadAction(ButtonElement element, this._gistController)
: _button = DButton(element) {
_button.onClick.listen((e) => _handleButtonPress());
}
void _handleButtonPress() {
OkCancelDialog('Create New Pad', 'Discard changes to the current pad?',
_gistController.createNewGist,
okText: 'Discard')
.show();
}
}
| dart-pad/lib/actions.dart/0 | {'file_path': 'dart-pad/lib/actions.dart', 'repo_id': 'dart-pad', 'token_count': 288} |
// 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 'dart:html';
import 'package:dart_pad/elements/elements.dart';
typedef ConsoleFilter = String Function(String line);
class Console {
// The duration to wait before adding DOM elements to the document.
final Duration bufferDuration;
/// The element to append messages to.
final DElement element;
/// A filter function to apply to all messages.
final ConsoleFilter filter;
/// The CSS class name to apply to error messages.
final String errorClass;
final _bufferedOutput = <SpanElement>[];
Console(
this.element, {
this.bufferDuration = const Duration(milliseconds: 32),
this.filter,
this.errorClass = 'error-output',
});
/// Displays console output. Does not clear the console.
void showOutput(String message, {bool error = false}) {
if (filter != null) {
message = filter(message);
}
var span = SpanElement()..text = '$message\n';
span.classes.add(error ? errorClass : 'normal');
// Buffer the console output so that heavy writing to stdout does not starve
// the DOM thread.
_bufferedOutput.add(span);
if (_bufferedOutput.length == 1) {
Timer(bufferDuration, () {
element.element.children.addAll(_bufferedOutput);
// Using scrollIntoView(ScrollAlignment.BOTTOM) causes the parent page
// to scroll, so set the scrollTop instead.
var last = element.element.children.last;
element.element.scrollTop = last.offsetTop;
_bufferedOutput.clear();
});
}
}
void clear() {
element.text = '';
}
}
| dart-pad/lib/elements/console.dart/0 | {'file_path': 'dart-pad/lib/elements/console.dart', 'repo_id': 'dart-pad', 'token_count': 582} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.