code
stringlengths
8
3.25M
repository
stringlengths
15
175
metadata
stringlengths
66
249
// 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:test/test.dart'; void main() { group('MultiplexingBuilder', () { test('Only passes matching inputs', () async { final builder = MultiplexingBuilder([ TestBuilder(buildExtensions: replaceExtension('.foo', '.copy')), TestBuilder(buildExtensions: replaceExtension('.bar', '.copy')), ]); await testBuilder(builder, {'a|lib/a1.foo': 'a1', 'a|lib/a2.bar': 'a2'}, outputs: {'a|lib/a1.copy': 'a1', 'a|lib/a2.copy': 'a2'}); }); test('merges non-overlapping extension maps', () { final builder = MultiplexingBuilder([ TestBuilder(buildExtensions: replaceExtension('.foo', '.copy')), TestBuilder(buildExtensions: replaceExtension('.bar', '.copy')), ]); expect(builder.buildExtensions, { '.foo': ['.copy'], '.bar': ['.copy'] }); }); test('merges overlapping extension maps', () { final builder = MultiplexingBuilder([ TestBuilder(buildExtensions: { '.foo': ['.copy.0', '.copy.1'] }), TestBuilder(buildExtensions: replaceExtension('.foo', '.new')), ]); expect(builder.buildExtensions, { '.foo': ['.copy.0', '.copy.1', '.new'] }); }); }); }
build/build/test/builder/multiplexing_builder_test.dart/0
{'file_path': 'build/build/test/builder/multiplexing_builder_test.dart', 'repo_id': 'build', 'token_count': 609}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'builder_definition.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** BuilderDefinition _$BuilderDefinitionFromJson(Map json) => $checkedCreate( 'BuilderDefinition', json, ($checkedConvert) { $checkKeys( json, allowedKeys: const [ 'builder_factories', 'import', 'build_extensions', 'target', 'auto_apply', 'required_inputs', 'runs_before', 'applies_builders', 'is_optional', 'build_to', 'defaults' ], requiredKeys: const [ 'builder_factories', 'import', 'build_extensions' ], disallowNullValues: const [ 'builder_factories', 'import', 'build_extensions' ], ); final val = BuilderDefinition( builderFactories: $checkedConvert('builder_factories', (v) => (v as List<dynamic>).map((e) => e as String).toList()), buildExtensions: $checkedConvert( 'build_extensions', (v) => (v as Map).map( (k, e) => MapEntry(k as String, (e as List<dynamic>).map((e) => e as String).toList()), )), import: $checkedConvert('import', (v) => v as String), target: $checkedConvert('target', (v) => v as String?), autoApply: $checkedConvert( 'auto_apply', (v) => $enumDecodeNullable(_$AutoApplyEnumMap, v)), requiredInputs: $checkedConvert('required_inputs', (v) => (v as List<dynamic>?)?.map((e) => e as String)), runsBefore: $checkedConvert('runs_before', (v) => (v as List<dynamic>?)?.map((e) => e as String)), appliesBuilders: $checkedConvert('applies_builders', (v) => (v as List<dynamic>?)?.map((e) => e as String)), isOptional: $checkedConvert('is_optional', (v) => v as bool?), buildTo: $checkedConvert( 'build_to', (v) => $enumDecodeNullable(_$BuildToEnumMap, v)), defaults: $checkedConvert( 'defaults', (v) => v == null ? null : TargetBuilderConfigDefaults.fromJson(v as Map)), ); return val; }, fieldKeyMap: const { 'builderFactories': 'builder_factories', 'buildExtensions': 'build_extensions', 'autoApply': 'auto_apply', 'requiredInputs': 'required_inputs', 'runsBefore': 'runs_before', 'appliesBuilders': 'applies_builders', 'isOptional': 'is_optional', 'buildTo': 'build_to' }, ); const _$AutoApplyEnumMap = { AutoApply.none: 'none', AutoApply.dependents: 'dependents', AutoApply.allPackages: 'all_packages', AutoApply.rootPackage: 'root_package', }; const _$BuildToEnumMap = { BuildTo.source: 'source', BuildTo.cache: 'cache', }; PostProcessBuilderDefinition _$PostProcessBuilderDefinitionFromJson(Map json) => $checkedCreate( 'PostProcessBuilderDefinition', json, ($checkedConvert) { $checkKeys( json, allowedKeys: const [ 'builder_factory', 'import', 'input_extensions', 'target', 'defaults' ], requiredKeys: const ['builder_factory', 'import'], disallowNullValues: const ['builder_factory', 'import'], ); final val = PostProcessBuilderDefinition( builderFactory: $checkedConvert('builder_factory', (v) => v as String), import: $checkedConvert('import', (v) => v as String), inputExtensions: $checkedConvert('input_extensions', (v) => (v as List<dynamic>?)?.map((e) => e as String)), target: $checkedConvert('target', (v) => v as String?), defaults: $checkedConvert( 'defaults', (v) => v == null ? null : TargetBuilderConfigDefaults.fromJson(v as Map)), ); return val; }, fieldKeyMap: const { 'builderFactory': 'builder_factory', 'inputExtensions': 'input_extensions' }, ); TargetBuilderConfigDefaults _$TargetBuilderConfigDefaultsFromJson(Map json) => $checkedCreate( 'TargetBuilderConfigDefaults', json, ($checkedConvert) { $checkKeys( json, allowedKeys: const [ 'generate_for', 'options', 'dev_options', 'release_options' ], ); final val = TargetBuilderConfigDefaults( generateFor: $checkedConvert( 'generate_for', (v) => v == null ? null : InputSet.fromJson(v)), options: $checkedConvert( 'options', (v) => (v as Map?)?.map( (k, e) => MapEntry(k as String, e), )), devOptions: $checkedConvert( 'dev_options', (v) => (v as Map?)?.map( (k, e) => MapEntry(k as String, e), )), releaseOptions: $checkedConvert( 'release_options', (v) => (v as Map?)?.map( (k, e) => MapEntry(k as String, e), )), ); return val; }, fieldKeyMap: const { 'generateFor': 'generate_for', 'devOptions': 'dev_options', 'releaseOptions': 'release_options' }, );
build/build_config/lib/src/builder_definition.g.dart/0
{'file_path': 'build/build_config/lib/src/builder_definition.g.dart', 'repo_id': 'build', 'token_count': 2870}
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'package:path/path.dart' as p; const readyToConnectLog = 'READY TO CONNECT'; const versionSkew = 'DIFFERENT RUNNING VERSION'; const optionsSkew = 'DIFFERENT OPTIONS'; const buildModeFlag = 'build-mode'; enum BuildMode { // ignore: constant_identifier_names Manual, // ignore: constant_identifier_names Auto, } /// These are used when serializing log messages over stdout. /// /// Serialized logs must be preceded with the [logStartMarker] on its own line, /// and terminated with a [logEndMarker] also on its own line. /// /// This allows multi-line logs to be sanely serialized via stdout, and mixed /// with other generic messages. const logStartMarker = 'BUILD DAEMON LOG START'; const logEndMarker = 'BUILD DAEMON LOG END'; // TODO(grouma) - use pubspec version when this is open sourced. const currentVersion = '8'; var _username = Platform.environment['USER'] ?? ''; String daemonWorkspace(String workingDirectory) { var segments = [Directory.systemTemp.path]; if (_username.isNotEmpty) segments.add(_username); segments.add(workingDirectory .replaceAll('/', '_') .replaceAll(':', '_') .replaceAll('\\', '_')); return p.joinAll(segments); } /// Used to ensure that only one instance of this daemon is running at a time. String lockFilePath(String workingDirectory) => p.join(daemonWorkspace(workingDirectory), '.dart_build_lock'); /// Used to signal to clients on what port the running daemon is listening. String portFilePath(String workingDirectory) => p.join(daemonWorkspace(workingDirectory), '.dart_build_daemon_port'); /// Used to signal to clients the current version of the build daemon. String versionFilePath(String workingDirectory) => p.join(daemonWorkspace(workingDirectory), '.dart_build_daemon_version'); /// Used to signal to clients the current set of options of the build daemon. String optionsFilePath(String workingDirectory) => p.join(daemonWorkspace(workingDirectory), '.dart_build_daemon_options');
build/build_daemon/lib/constants.dart/0
{'file_path': 'build/build_daemon/lib/constants.dart', 'repo_id': 'build', 'token_count': 664}
# See https://pub.dev/packages/build_config builders: module_library: import: "package:build_modules/builders.dart" builder_factories: - moduleLibraryBuilder build_extensions: .dart: - .module.library auto_apply: all_packages is_optional: True required_inputs: [".dart"] applies_builders: ["|module_cleanup"] post_process_builders: module_cleanup: import: "package:build_modules/builders.dart" builder_factory: "moduleCleanup"
build/build_modules/build.yaml/0
{'file_path': 'build/build_modules/build.yaml', 'repo_id': 'build', 'token_count': 187}
// 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:collection'; import 'package:build/build.dart'; import 'package:collection/collection.dart' show UnmodifiableSetView; import 'package:graphs/graphs.dart'; import 'package:json_annotation/json_annotation.dart'; import 'errors.dart'; import 'module_builder.dart'; import 'module_cache.dart'; import 'platform.dart'; part 'modules.g.dart'; /// A collection of Dart libraries in a strongly connected component of the /// import graph. /// /// Modules track their sources and the other modules they depend on. /// modules they depend on. /// Modules can span pub package boundaries when there are import cycles across /// packages. @_AssetIdConverter() @_DartPlatformConverter() @JsonSerializable() class Module { /// Merge the sources and dependencies from [modules] into a single module. /// /// All modules must have the same [platform]. /// [primarySource] will be the earliest value from the combined [sources] if /// they were sorted. /// [isMissing] will be true if any input module is missing. /// [isSupported] will be true if all input modules are supported. /// [directDependencies] will be merged for all modules, but if any module /// depended on a source from any other they will be filtered out. static Module merge(List<Module> modules) { assert(modules.isNotEmpty); if (modules.length == 1) return modules.single; assert(modules.every((m) => m.platform == modules.first.platform)); final allSources = HashSet.of(modules.expand((m) => m.sources)); final allDependencies = HashSet.of(modules.expand((m) => m.directDependencies)) ..removeAll(allSources); final primarySource = allSources.reduce((a, b) => a.compareTo(b) < 0 ? a : b); final isMissing = modules.any((m) => m.isMissing); final isSupported = modules.every((m) => m.isSupported); return Module(primarySource, allSources, allDependencies, modules.first.platform, isSupported, isMissing: isMissing); } /// The library which will be used to reference any library in [sources]. /// /// The assets which are built once per module, such as DDC compiled output or /// Analyzer summaries, will be named after the primary source and will /// encompass everything in [sources]. @JsonKey(name: 'p') final AssetId primarySource; /// The libraries in the strongly connected import cycle with [primarySource]. /// /// In most cases without cyclic imports this will contain only the primary /// source. For libraries with an import cycle all of the libraries in the /// cycle will be contained in `sources`. For example: /// /// ```dart /// library foo; /// /// import 'bar.dart'; /// ``` /// /// ```dart /// library bar; /// /// import 'foo.dart'; /// ``` /// /// Libraries `foo` and `bar` form an import cycle so they would be grouped in /// the same module. Every Dart library will only be contained in a single /// [Module]. @JsonKey(name: 's', toJson: _toJsonAssetIds) final Set<AssetId> sources; /// The [primarySource]s of the [Module]s which contain any library imported /// from any of the [sources] in this module. @JsonKey(name: 'd', toJson: _toJsonAssetIds) final Set<AssetId> directDependencies; /// Missing modules are created if a module depends on another non-existent /// module. /// /// We want to report these errors lazily to allow for builds to succeed if it /// won't actually impact any apps negatively. @JsonKey(name: 'm') final bool isMissing; /// Whether or not this module is supported for [platform]. /// /// Note that this only indicates support for the [sources] within this /// module, and not its transitive (or direct) dependencies. /// /// Compilers can use this to either silently skip compilation of this module /// or throw early errors or warnings. /// /// Modules are allowed to exist even if they aren't supported, which can help /// with discovering root causes of incompatibility. @JsonKey(name: 'is') final bool isSupported; @JsonKey(name: 'pf') final DartPlatform platform; Module(this.primarySource, Iterable<AssetId> sources, Iterable<AssetId> directDependencies, this.platform, this.isSupported, {this.isMissing = false}) : sources = UnmodifiableSetView(HashSet.of(sources)), directDependencies = UnmodifiableSetView(HashSet.of(directDependencies)); /// Generated factory constructor. factory Module.fromJson(Map<String, dynamic> json) => _$ModuleFromJson(json); Map<String, dynamic> toJson() => _$ModuleToJson(this); /// Returns all [Module]s in the transitive dependencies of this module in /// reverse dependency order. /// /// Throws a [MissingModulesException] if there are any missing modules. This /// typically means that somebody is trying to import a non-existing file. /// /// If [throwIfUnsupported] is `true`, then an [UnsupportedModules] /// will be thrown if there are any modules that are not supported. Future<List<Module>> computeTransitiveDependencies(BuildStep buildStep, {bool throwIfUnsupported = false}) async { final modules = await buildStep.fetchResource(moduleCache); var transitiveDeps = <AssetId, Module>{}; var modulesToCrawl = {primarySource}; var missingModuleSources = <AssetId>{}; var unsupportedModules = <Module>{}; while (modulesToCrawl.isNotEmpty) { var next = modulesToCrawl.last; modulesToCrawl.remove(next); if (transitiveDeps.containsKey(next)) continue; var nextModuleId = next.changeExtension(moduleExtension(platform)); var module = await modules.find(nextModuleId, buildStep); if (module == null || module.isMissing) { missingModuleSources.add(next); continue; } if (throwIfUnsupported && !module.isSupported) { unsupportedModules.add(module); } // Don't include the root module in the transitive deps. if (next != primarySource) transitiveDeps[next] = module; modulesToCrawl.addAll(module.directDependencies); } if (missingModuleSources.isNotEmpty) { throw await MissingModulesException.create(missingModuleSources, transitiveDeps.values.toList()..add(this), buildStep); } if (throwIfUnsupported && unsupportedModules.isNotEmpty) { throw UnsupportedModules(unsupportedModules); } var orderedModules = stronglyConnectedComponents<Module>( transitiveDeps.values, (m) => m.directDependencies.map((s) => transitiveDeps[s]!), equals: (a, b) => a.primarySource == b.primarySource, hashCode: (m) => m.primarySource.hashCode); return orderedModules.map((c) => c.single).toList(); } } class _AssetIdConverter implements JsonConverter<AssetId, List> { const _AssetIdConverter(); @override AssetId fromJson(List json) => AssetId.deserialize(json); @override List toJson(AssetId object) => object.serialize() as List; } class _DartPlatformConverter implements JsonConverter<DartPlatform, String> { const _DartPlatformConverter(); @override DartPlatform fromJson(String json) => DartPlatform.byName(json); @override String toJson(DartPlatform object) => object.name; } /// Ensure sets of asset IDs are sorted before writing them for a consistent /// output. List<List> _toJsonAssetIds(Set<AssetId> ids) => (ids.toList()..sort()).map((i) => i.serialize() as List).toList();
build/build_modules/lib/src/modules.dart/0
{'file_path': 'build/build_modules/lib/src/modules.dart', 'repo_id': 'build', 'token_count': 2450}
part of a_imports_b_no_cycle;
build/build_modules/test/fixtures/a/lib/a_part_library_name.dart/0
{'file_path': 'build/build_modules/test/fixtures/a/lib/a_part_library_name.dart', 'repo_id': 'build', 'token_count': 14}
// Copyright (c) 2020, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:build/build.dart'; import 'package:build_modules/build_modules.dart'; import 'package:build_test/build_test.dart'; import 'package:test/test.dart'; void main() { test('can pass dart2js arguments with spaces', () async { await testBuilder( TestBuilder( build: (BuildStep buildStep, _) async { var resource = await buildStep.fetchResource(dart2JsWorkerResource); await scratchSpace.ensureAssets([buildStep.inputId], buildStep); var result = await resource .compile(['web/foo bar.dart', '-o', 'web/foo bar.dart.js']); expect(result.succeeded, true, reason: result.output); await scratchSpace.copyOutput( buildStep.inputId.changeExtension('.dart.js'), buildStep); expect(result.output, contains('web/foo%20bar.dart.js')); }, buildExtensions: { '.dart': ['.dart.js'] }), { 'a|web/foo bar.dart': 'main() {}', }, outputs: { 'a|web/foo bar.dart.js': decodedMatches( contains('//# sourceMappingURL=foo%20bar.dart.js.map')), }); }); }
build/build_modules/test/worker_test.dart/0
{'file_path': 'build/build_modules/test/worker_test.dart', 'repo_id': 'build', 'token_count': 652}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:build_runner/src/build_script_generate/bootstrap.dart'; import 'package:build_runner/src/entrypoint/options.dart'; import 'package:build_runner/src/entrypoint/runner.dart'; import 'package:build_runner/src/logging/std_io_logging.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:io/ansi.dart'; import 'package:io/io.dart'; import 'package:logging/logging.dart'; import 'src/commands/clean.dart'; import 'src/commands/generate_build_script.dart'; Future<void> main(List<String> args) async { // Use the actual command runner to parse the args and immediately print the // usage information if there is no command provided or the help command was // explicitly invoked. var commandRunner = BuildCommandRunner([], await PackageGraph.forThisPackage()); var localCommands = [CleanCommand(), GenerateBuildScript()]; var localCommandNames = localCommands.map((c) => c.name).toSet(); for (var command in localCommands) { commandRunner.addCommand(command); // This flag is added to each command individually and not the top level. command.argParser.addFlag(verboseOption, abbr: 'v', defaultsTo: false, negatable: false, help: 'Enables verbose logging.'); } ArgResults parsedArgs; try { parsedArgs = commandRunner.parse(args); } on UsageException catch (e) { print(red.wrap(e.message)); print(''); print(e.usage); exitCode = ExitCode.usage.code; return; } var commandName = parsedArgs.command?.name; if (parsedArgs.rest.isNotEmpty) { print( yellow.wrap('Could not find a command named "${parsedArgs.rest[0]}".')); print(''); print(commandRunner.usageWithoutDescription); exitCode = ExitCode.usage.code; return; } if (commandName == 'help' || parsedArgs.wasParsed('help') || (parsedArgs.command?.wasParsed('help') ?? false)) { await commandRunner.runCommand(parsedArgs); return; } if (commandName == null) { commandRunner.printUsage(); exitCode = ExitCode.usage.code; return; } StreamSubscription logListener; if (commandName == 'daemon') { // Simple logs only in daemon mode. These get converted into info or // severe logs by the client. logListener = Logger.root.onRecord.listen((record) { if (record.level >= Level.SEVERE) { var buffer = StringBuffer(record.message); if (record.error != null) buffer.writeln(record.error); if (record.stackTrace != null) buffer.writeln(record.stackTrace); stderr.writeln(buffer); } else { stdout.writeln(record.message); } }); } else { var verbose = parsedArgs.command!['verbose'] as bool? ?? false; if (verbose) Logger.root.level = Level.ALL; logListener = Logger.root.onRecord.listen(stdIOLogListener(verbose: verbose)); } if (localCommandNames.contains(commandName)) { exitCode = await commandRunner.runCommand(parsedArgs) ?? 1; } else { while ((exitCode = await generateAndRun(args)) == ExitCode.tempFail.code) {} } await logListener.cancel(); }
build/build_runner/bin/build_runner.dart/0
{'file_path': 'build/build_runner/bin/build_runner.dart', 'repo_id': 'build', 'token_count': 1229}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:logging/logging.dart'; import 'options.dart'; import 'runner.dart'; final lineLength = stdout.hasTerminal ? stdout.terminalColumns : 80; abstract class BuildRunnerCommand extends Command<int> { Logger get logger => Logger(name); List<BuilderApplication> get builderApplications => (runner as BuildCommandRunner).builderApplications; PackageGraph get packageGraph => (runner as BuildCommandRunner).packageGraph; BuildRunnerCommand({bool symlinksDefault = false}) { _addBaseFlags(symlinksDefault); } @override final argParser = ArgParser(usageLineLength: lineLength); void _addBaseFlags(bool symlinksDefault) { argParser ..addFlag(deleteFilesByDefaultOption, help: 'By default, the user will be prompted to delete any files which ' 'already exist but were not known to be generated by this ' 'specific build script.\n\n' 'Enabling this option skips the prompt and deletes the files. ' 'This should typically be used in continues integration servers ' 'and tests, but not otherwise.', negatable: false, defaultsTo: false) ..addFlag(lowResourcesModeOption, help: 'Reduce the amount of memory consumed by the build process. ' 'This will slow down builds but allow them to progress in ' 'resource constrained environments.', negatable: false, defaultsTo: false) ..addOption(configOption, help: 'Read `build.<name>.yaml` instead of the default `build.yaml`', abbr: 'c') ..addFlag('fail-on-severe', help: 'Deprecated argument - always enabled', negatable: true, defaultsTo: true, hide: true) ..addFlag(trackPerformanceOption, help: r'Enables performance tracking and the /$perf page.', negatable: true, defaultsTo: false) ..addOption(logPerformanceOption, help: 'A directory to write performance logs to, must be in the ' 'current package. Implies `--track-performance`.') ..addFlag(skipBuildScriptCheckOption, help: r'Skip validation for the digests of files imported by the ' 'build script.', hide: true, defaultsTo: false) ..addMultiOption(outputOption, help: 'A directory to copy the fully built package to. Or a mapping ' 'from a top-level directory in the package to the directory to ' 'write a filtered build output to. For example "web:deploy".', abbr: 'o') ..addFlag(verboseOption, abbr: 'v', defaultsTo: false, negatable: false, help: 'Enables verbose logging.') ..addFlag(releaseOption, abbr: 'r', defaultsTo: false, negatable: true, help: 'Build with release mode defaults for builders.') ..addMultiOption(defineOption, splitCommas: false, help: 'Sets the global `options` config for a builder by key.') ..addFlag(symlinkOption, defaultsTo: symlinksDefault, negatable: true, help: 'Symlink files in the output directories, instead of copying.') ..addMultiOption(buildFilterOption, help: 'An explicit filter of files to build. Relative paths and ' '`package:` uris are supported, including glob syntax for paths ' 'portions (but not package names).\n\n' 'If multiple filters are applied then outputs matching any filter ' 'will be built (they do not need to match all filters).') ..addMultiOption(enableExperimentOption, help: 'A list of dart language experiments to enable.'); } /// Must be called inside [run] so that [argResults] is non-null. /// /// You may override this to return more specific options if desired, but they /// must extend [SharedOptions]. SharedOptions readOptions() { return SharedOptions.fromParsedArgs( argResults!, argResults!.rest, packageGraph.root.name, this); } }
build/build_runner/lib/src/entrypoint/base_command.dart/0
{'file_path': 'build/build_runner/lib/src/entrypoint/base_command.dart', 'repo_id': 'build', 'token_count': 1721}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'dart:io'; import 'package:io/ansi.dart'; import 'package:logging/logging.dart'; import 'package:stack_trace/stack_trace.dart'; void Function(LogRecord) stdIOLogListener({bool? assumeTty, bool? verbose}) => (record) => overrideAnsiOutput(assumeTty == true || ansiOutputEnabled, () { _stdIOLogListener(record, verbose: verbose ?? false); }); StringBuffer colorLog(LogRecord record, {required bool verbose}) { AnsiCode color; if (record.level < Level.WARNING) { color = cyan; } else if (record.level < Level.SEVERE) { color = yellow; } else { color = red; } final level = color.wrap('[${record.level}]'); final eraseLine = ansiOutputEnabled && !verbose ? '\x1b[2K\r' : ''; var lines = <Object>[ '$eraseLine$level ${_recordHeader(record, verbose)}${record.message}' ]; if (record.error != null) { lines.add(record.error!); } if (record.stackTrace != null && verbose) { var trace = Trace.from(record.stackTrace!); const buildSystem = {'build_runner', 'build_runner_core', 'build'}; if (trace.frames.isNotEmpty && !buildSystem.contains(trace.frames.first.package)) { trace = trace.foldFrames((f) => buildSystem.contains(f.package), terse: true); } lines.add(trace); } var message = StringBuffer(lines.join('\n')); // We always add an extra newline at the end of each message, so it // isn't multiline unless we see > 2 lines. var multiLine = LineSplitter.split(message.toString()).length > 2; if (record.level > Level.INFO || !ansiOutputEnabled || multiLine || verbose) { // Add an extra line to the output so the last line isn't written over. message.writeln(''); } return message; } void _stdIOLogListener(LogRecord record, {required bool verbose}) => stdout.write(colorLog(record, verbose: verbose)); /// Filter out the Logger names which aren't coming from specific builders and /// splits the header for levels >= WARNING. String _recordHeader(LogRecord record, bool verbose) { var maybeSplit = record.level >= Level.WARNING ? '\n' : ''; return verbose || record.loggerName.contains(' ') ? '${record.loggerName}:$maybeSplit' : ''; }
build/build_runner/lib/src/logging/std_io_logging.dart/0
{'file_path': 'build/build_runner/lib/src/logging/std_io_logging.dart', 'repo_id': 'build', 'token_count': 850}
// 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. @Tags(['integration']) import 'package:build_test/build_test.dart'; import 'package:test/test.dart'; import 'package:test_descriptor/test_descriptor.dart' as d; import 'utils/build_descriptor.dart'; // test-package-start ######################################################### final alwaysThrow = TestBuilder( buildExtensions: { '.txt': ['.txt.copy'], }, build: (_, __) { throw StateError('Build action failure'); }); // test-package-end ########################################################### void main() { final builders = [ builder('alwaysThrow', alwaysThrow), ]; late BuildTool buildTool; setUpAll(() async { buildTool = await packageWithBuildScript(builders, contents: [ d.dir('web', [d.file('a.txt', 'a')]) ]); }); group('build', () { test('replays errors on builds with no change', () async { final firstBuild = await buildTool.build(expectExitCode: 1); await expectLater( firstBuild, emitsThrough(contains('Build action failure'))); // Run another build, no action should run but the failure will be logged // again final nextBuild = await buildTool.build(expectExitCode: 1); await expectLater( nextBuild, emitsThrough(contains('Build action failure'))); }); }); }
build/build_runner/test/integration_tests/errors_test.dart/0
{'file_path': 'build/build_runner/test/integration_tests/errors_test.dart', 'repo_id': 'build', 'token_count': 501}
// 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:io'; import 'package:build/build.dart'; import 'package:collection/collection.dart'; import 'package:logging/logging.dart'; import 'package:path/path.dart' as p; import 'package:pool/pool.dart'; import '../asset/reader.dart'; import '../environment/build_environment.dart'; import '../generate/build_directory.dart'; import '../generate/finalized_assets_view.dart'; import '../logging/logging.dart'; import '../package_graph/package_graph.dart'; /// Pool for async file operations, we don't want to use too many file handles. final _descriptorPool = Pool(32); final _logger = Logger('CreateOutputDir'); const _manifestName = '.build.manifest'; const _manifestSeparator = '\n'; /// Creates merged output directories for each [OutputLocation]. /// /// Returns whether it succeeded or not. Future<bool> createMergedOutputDirectories( Set<BuildDirectory> buildDirs, PackageGraph packageGraph, BuildEnvironment environment, AssetReader reader, FinalizedAssetsView finalizedAssetsView, bool outputSymlinksOnly) async { if (outputSymlinksOnly && reader is! PathProvidingAssetReader) { _logger.severe( 'The current environment does not support symlinks, but symlinks were ' 'requested.'); return false; } var conflictingOutputs = _conflicts(buildDirs); if (conflictingOutputs.isNotEmpty) { _logger.severe('Unable to create merged directory. ' 'Conflicting outputs for $conflictingOutputs'); return false; } for (var target in buildDirs) { var outputLocation = target.outputLocation; if (outputLocation != null) { if (!await _createMergedOutputDir( outputLocation.path, target.directory, packageGraph, environment, reader, finalizedAssetsView, // TODO(grouma) - retrieve symlink information from target only. outputSymlinksOnly || outputLocation.useSymlinks, outputLocation.hoist)) { _logger.severe( 'Unable to create merged directory for ${outputLocation.path}.'); return false; } } } return true; } Set<String> _conflicts(Set<BuildDirectory> buildDirs) { final seen = <String>{}; final conflicts = <String>{}; var outputLocations = buildDirs.map((d) => d.outputLocation?.path).whereNotNull(); for (var location in outputLocations) { if (!seen.add(location)) conflicts.add(location); } return conflicts; } Future<bool> _createMergedOutputDir( String outputPath, String? root, PackageGraph packageGraph, BuildEnvironment environment, AssetReader reader, FinalizedAssetsView finalizedOutputsView, bool symlinkOnly, bool hoist) async { try { if (root == null) return false; var absoluteRoot = p.join(packageGraph.root.path, root); if (absoluteRoot != packageGraph.root.path && !p.isWithin(packageGraph.root.path, absoluteRoot)) { _logger.severe( 'Invalid dir to build `$root`, must be within the package root.'); return false; } var outputDir = Directory(outputPath); var outputDirExists = await outputDir.exists(); if (outputDirExists) { if (!await _cleanUpOutputDir(outputDir, environment)) return false; } var builtAssets = finalizedOutputsView.allAssets(rootDir: root).toList(); if (root != '' && !builtAssets .where((id) => id.package == packageGraph.root.name) .any((id) => p.isWithin(root, id.path))) { _logger.severe('No assets exist in $root, skipping output'); return false; } var outputAssets = <AssetId>[]; await logTimedAsync(_logger, 'Creating merged output dir `$outputPath`', () async { if (!outputDirExists) { await outputDir.create(recursive: true); } outputAssets.addAll(await Future.wait([ for (var id in builtAssets) _writeAsset( id, outputDir, root, packageGraph, reader, symlinkOnly, hoist), _writeCustomPackagesFile(packageGraph, outputDir), if (await reader.canRead(_packageConfigId(packageGraph.root.name))) _writeModifiedPackageConfig( packageGraph.root.name, reader, outputDir), ])); if (!hoist) { for (var dir in _findRootDirs(builtAssets, outputPath)) { var link = Link(p.join(outputDir.path, dir, 'packages')); if (!link.existsSync()) { link.createSync(p.join('..', 'packages'), recursive: true); } } } }); await logTimedAsync(_logger, 'Writing asset manifest', () async { var paths = outputAssets.map((id) => id.path).toList()..sort(); var content = paths.join(_manifestSeparator); await _writeAsString( outputDir, AssetId(packageGraph.root.name, _manifestName), content); }); return true; } on FileSystemException catch (e) { if (e.osError?.errorCode != 1314) rethrow; var devModeLink = 'https://docs.microsoft.com/en-us/windows/uwp/get-started/' 'enable-your-device-for-development'; _logger.severe('Unable to create symlink ${e.path}. Note that to create ' 'symlinks on windows you need to either run in a console with admin ' 'privileges or enable developer mode (see $devModeLink).'); return false; } } /// Creates a custom `.packages` file in [outputDir] containing all the /// packages in [packageGraph]. /// /// All package root uris are of the form `packages/<package>/`. Future<AssetId> _writeCustomPackagesFile( PackageGraph packageGraph, Directory outputDir) async { var packagesFileContent = packageGraph.allPackages.keys.map((p) => '$p:packages/$p/').join('\r\n'); var packagesAsset = AssetId(packageGraph.root.name, '.packages'); await _writeAsString(outputDir, packagesAsset, packagesFileContent); return packagesAsset; } AssetId _packageConfigId(String rootPackage) => AssetId(rootPackage, '.dart_tool/package_config.json'); /// Creates a modified `.dart_tool/package_config.json` file in [outputDir] /// based on the current one but with modified root and package uris. /// /// All `rootUri`s are of the form `packages/<package>` and the `packageUri` /// is always the empty string. This is because only the lib directory is /// exposed when using a `packages` directory layout so the root uri and /// package uri are equivalent. /// /// All other fields are left as is. Future<AssetId> _writeModifiedPackageConfig( String rootPackage, AssetReader reader, Directory outputDir) async { var packageConfigAsset = _packageConfigId(rootPackage); var packageConfig = jsonDecode(await reader.readAsString(packageConfigAsset)) as Map<String, dynamic>; var version = packageConfig['configVersion'] as int; if (version != 2) { throw UnsupportedError( 'Unsupported package_config.json version, got $version but only ' 'version 2 is supported.'); } var packages = (packageConfig['packages'] as List).cast<Map<String, dynamic>>(); for (var package in packages) { final name = package['name'] as String; if (name == rootPackage) { package['rootUri'] = '../'; package['packageUri'] = 'packages/${package['name']}'; } else { package['rootUri'] = '../packages/${package['name']}'; package['packageUri'] = ''; } } await _writeAsString( outputDir, packageConfigAsset, jsonEncode(packageConfig)); return packageConfigAsset; } Set<String> _findRootDirs(Iterable<AssetId> allAssets, String outputPath) { var rootDirs = <String>{}; for (var id in allAssets) { var parts = p.url.split(id.path); if (parts.length == 1) continue; var dir = parts.first; if (dir == outputPath || dir == 'lib') continue; rootDirs.add(parts.first); } return rootDirs; } Future<AssetId> _writeAsset( AssetId id, Directory outputDir, String root, PackageGraph packageGraph, AssetReader reader, bool symlinkOnly, bool hoist) { return _descriptorPool.withResource(() async { String assetPath; if (id.path.startsWith('lib/')) { assetPath = p.url.join('packages', id.package, id.path.substring('lib/'.length)); } else { assetPath = id.path; assert(id.package == packageGraph.root.name); if (hoist && p.isWithin(root, id.path)) { assetPath = p.relative(id.path, from: root); } } var outputId = AssetId(packageGraph.root.name, assetPath); try { if (symlinkOnly) { await Link(_filePathFor(outputDir, outputId)).create( // We assert at the top of `createMergedOutputDirectories` that the // reader implements this type when requesting symlinks. (reader as PathProvidingAssetReader).pathTo(id), recursive: true); } else { await _writeAsBytes(outputDir, outputId, await reader.readAsBytes(id)); } } on AssetNotFoundException catch (e) { if (p.basename(id.path).startsWith('.')) { _logger.fine('Skipping missing hidden file ${id.path}'); } else { _logger.severe( 'Missing asset ${e.assetId}, it may have been deleted during the ' 'build. Please try rebuilding and if you continue to see the ' 'error then file a bug at ' 'https://github.com/dart-lang/build/issues/new.'); rethrow; } } return outputId; }); } Future<void> _writeAsBytes(Directory outputDir, AssetId id, List<int> bytes) => _fileFor(outputDir, id).then((file) => file.writeAsBytes(bytes)); Future<void> _writeAsString(Directory outputDir, AssetId id, String contents) => _fileFor(outputDir, id).then((file) => file.writeAsString(contents)); Future<File> _fileFor(Directory outputDir, AssetId id) { return File(_filePathFor(outputDir, id)).create(recursive: true); } String _filePathFor(Directory outputDir, AssetId id) { String relativePath; if (id.path.startsWith('lib')) { relativePath = p.join('packages', id.package, p.joinAll(p.url.split(id.path).skip(1))); } else { relativePath = id.path; } return p.join(outputDir.path, relativePath); } /// Checks for a manifest file in [outputDir] and deletes all referenced files. /// /// Prompts the user with a few options if no manifest file is found. /// /// Returns whether or not the directory was successfully cleaned up. Future<bool> _cleanUpOutputDir( Directory outputDir, BuildEnvironment environment) async { var outputPath = outputDir.path; var manifestFile = File(p.join(outputPath, _manifestName)); if (!manifestFile.existsSync()) { if (outputDir.listSync(recursive: false).isNotEmpty) { var choices = [ 'Leave the directory unchanged and skip writing the build output', 'Delete the directory and all contents', 'Leave the directory in place and write over any existing files', ]; int choice; try { choice = await environment.prompt( 'Found existing directory `$outputPath` but no manifest file.\n' 'Please choose one of the following options:', choices); } on NonInteractiveBuildException catch (_) { _logger.severe('Unable to create merged directory at $outputPath.\n' 'Choose a different directory or delete the contents of that ' 'directory.'); return false; } switch (choice) { case 0: _logger.severe('Skipped creation of the merged output directory.'); return false; case 1: try { outputDir.deleteSync(recursive: true); } catch (e) { _logger.severe( 'Failed to delete output dir at `$outputPath` with error:\n\n' '$e'); return false; } // Actually recreate the directory, but as an empty one. outputDir.createSync(); break; case 2: // Just do nothing here, we overwrite files by default. break; } } } else { var previousOutputs = logTimedSync( _logger, 'Reading manifest at ${manifestFile.path}', () => manifestFile.readAsStringSync().split(_manifestSeparator)); logTimedSync(_logger, 'Deleting previous outputs in `$outputPath`', () { for (var path in previousOutputs) { var file = File(p.join(outputPath, path)); if (file.existsSync()) file.deleteSync(); } _cleanEmptyDirectories(outputPath, previousOutputs); }); } return true; } /// Deletes all the directories which used to contain any path in /// [removedFilePaths] if that directory is now empty. void _cleanEmptyDirectories( String outputPath, Iterable<String> removedFilePaths) { for (var directory in removedFilePaths .map((path) => p.join(outputPath, p.dirname(path))) .toSet()) { _deleteUp(directory, outputPath); } } /// Deletes the directory at [from] and and any parent directories which are /// subdirectories of [to] if they are empty. void _deleteUp(String from, String to) { var directoryPath = from; while (p.isWithin(to, directoryPath)) { var directory = Directory(directoryPath); if (!directory.existsSync() || directory.listSync().isNotEmpty) return; directory.deleteSync(); directoryPath = p.dirname(directoryPath); } }
build/build_runner_core/lib/src/environment/create_merged_dir.dart/0
{'file_path': 'build/build_runner_core/lib/src/environment/create_merged_dir.dart', 'repo_id': 'build', 'token_count': 5082}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:logging/logging.dart'; import 'failure_reporter.dart'; /// A delegating [Logger] that records if any logs of level >= [Level.SEVERE] /// were seen. class BuildForInputLogger implements Logger { final Logger _delegate; final errorsSeen = <ErrorReport>[]; BuildForInputLogger(this._delegate); @override Level get level => _delegate.level; @override set level(Level? level) => _delegate.level = level; @override Map<String, Logger> get children => _delegate.children; @override void clearListeners() => _delegate.clearListeners(); @override void config(Object? message, [Object? error, StackTrace? stackTrace]) => _delegate.config(message, error, stackTrace); @override void fine(Object? message, [Object? error, StackTrace? stackTrace]) => _delegate.fine(message, error, stackTrace); @override void finer(Object? message, [Object? error, StackTrace? stackTrace]) => _delegate.finer(message, error, stackTrace); @override void finest(Object? message, [Object? error, StackTrace? stackTrace]) => _delegate.finest(message, error, stackTrace); @override String get fullName => _delegate.fullName; @override void info(Object? message, [Object? error, StackTrace? stackTrace]) => _delegate.info(message, error, stackTrace); @override bool isLoggable(Level value) => _delegate.isLoggable(value); @override void log(Level logLevel, Object? message, [Object? error, StackTrace? stackTrace, Zone? zone]) { if (logLevel >= Level.SEVERE) { errorsSeen.add(ErrorReport('$message', '${error ?? ''}', stackTrace)); } _delegate.log(logLevel, message, error, stackTrace, zone); } @override String get name => _delegate.name; @override Stream<LogRecord> get onRecord => _delegate.onRecord; @override Logger? get parent => _delegate.parent; @override void severe(Object? message, [Object? error, StackTrace? stackTrace]) { errorsSeen.add(ErrorReport('$message', '${error ?? ''}', stackTrace)); _delegate.severe(message, error, stackTrace); } @override void shout(Object? message, [Object? error, StackTrace? stackTrace]) { errorsSeen.add(ErrorReport('$message', '${error ?? ''}', stackTrace)); _delegate.shout(message, error, stackTrace); } @override void warning(Object? message, [Object? error, StackTrace? stackTrace]) => _delegate.warning(message, error, stackTrace); }
build/build_runner_core/lib/src/logging/build_for_input_logger.dart/0
{'file_path': 'build/build_runner_core/lib/src/logging/build_for_input_logger.dart', 'repo_id': 'build', 'token_count': 921}
// 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:_test_common/common.dart'; import 'package:build/build.dart'; import 'package:build_runner_core/src/asset/cache.dart'; import 'package:test/test.dart'; void main() { var fooTxt = AssetId('a', 'foo.txt'); var missingTxt = AssetId('a', 'missing.txt'); var fooContent = 'bar'; var fooutf8Bytes = decodedMatches('bar'); var assets = <AssetId, dynamic>{ fooTxt: 'bar', }; late InMemoryRunnerAssetReader delegate; late CachingAssetReader reader; setUp(() { delegate = InMemoryRunnerAssetReader(assets); reader = CachingAssetReader(delegate); }); group('canRead', () { test('should read from the delegate', () async { expect(await reader.canRead(fooTxt), isTrue); expect(await reader.canRead(missingTxt), isFalse); expect(delegate.assetsRead, [fooTxt, missingTxt]); }); test('should not re-read from the delegate', () async { expect(await reader.canRead(fooTxt), isTrue); delegate.assetsRead.clear(); expect(await reader.canRead(fooTxt), isTrue); expect(delegate.assetsRead, isEmpty); }); test('can be invalidated with invalidate', () async { expect(await reader.canRead(fooTxt), isTrue); delegate.assetsRead.clear(); expect(delegate.assetsRead, isEmpty); reader.invalidate([fooTxt]); expect(await reader.canRead(fooTxt), isTrue); expect(delegate.assetsRead, [fooTxt]); }); }); group('readAsBytes', () { test('should read from the delegate', () async { expect(await reader.readAsBytes(fooTxt), fooutf8Bytes); expect(delegate.assetsRead, [fooTxt]); }); test('should not re-read from the delegate', () async { expect(await reader.readAsBytes(fooTxt), fooutf8Bytes); delegate.assetsRead.clear(); expect(await reader.readAsBytes(fooTxt), fooutf8Bytes); expect(delegate.assetsRead, isEmpty); }); test('can be invalidated with invalidate', () async { expect(await reader.readAsBytes(fooTxt), fooutf8Bytes); delegate.assetsRead.clear(); expect(delegate.assetsRead, isEmpty); reader.invalidate([fooTxt]); expect(await reader.readAsBytes(fooTxt), fooutf8Bytes); expect(delegate.assetsRead, [fooTxt]); }); test('should not cache bytes during readAsString calls', () async { expect(await reader.readAsString(fooTxt), fooContent); expect(delegate.assetsRead, [fooTxt]); delegate.assetsRead.clear(); expect(await reader.readAsBytes(fooTxt), fooutf8Bytes); expect(delegate.assetsRead, [fooTxt]); }); }); group('readAsString', () { test('should read from the delegate', () async { expect(await reader.readAsString(fooTxt), fooContent); expect(delegate.assetsRead, [fooTxt]); }); test('should not re-read from the delegate', () async { expect(await reader.readAsString(fooTxt), fooContent); delegate.assetsRead.clear(); expect(await reader.readAsString(fooTxt), fooContent); expect(delegate.assetsRead, isEmpty); }); test('can be invalidated with invalidate', () async { expect(await reader.readAsString(fooTxt), fooContent); delegate.assetsRead.clear(); expect(delegate.assetsRead, isEmpty); reader.invalidate([fooTxt]); expect(await reader.readAsString(fooTxt), fooContent); expect(delegate.assetsRead, [fooTxt]); }); test('uses cached bytes if available', () async { expect(await reader.readAsBytes(fooTxt), fooutf8Bytes); expect(delegate.assetsRead, [fooTxt]); delegate.assetsRead.clear(); expect(await reader.readAsString(fooTxt), fooContent); expect(delegate.assetsRead, isEmpty); }); }); group('digest', () { test('should read from the delegate', () async { expect(await reader.digest(fooTxt), isNotNull); expect(delegate.assetsRead, [fooTxt]); }); test('should re-read from the delegate (no cache)', () async { expect(await reader.digest(fooTxt), isNotNull); delegate.assetsRead.clear(); expect(await reader.digest(fooTxt), isNotNull); expect(delegate.assetsRead, [fooTxt]); }); }); }
build/build_runner_core/test/asset/cache_test.dart/0
{'file_path': 'build/build_runner_core/test/asset/cache_test.dart', 'repo_id': 'build', 'token_count': 1642}
name: c version: 4.0.0 dependencies: basic_pkg: ^1.0.0
build/build_runner_core/test/fixtures/basic_pkg/pkg/c/pubspec.yaml/0
{'file_path': 'build/build_runner_core/test/fixtures/basic_pkg/pkg/c/pubspec.yaml', 'repo_id': 'build', 'token_count': 28}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:_test_common/build_configs.dart'; import 'package:_test_common/common.dart'; import 'package:build/build.dart'; import 'package:build_runner_core/build_runner_core.dart'; import 'package:test/test.dart'; void main() { test('uses builder options', () async { Builder copyBuilder(BuilderOptions options) => TestBuilder( buildExtensions: replaceExtension( options.config['inputExtension'] as String, '.copy')); final buildConfigs = parseBuildConfigs({ 'a': { 'targets': { 'a': { 'builders': { 'a:optioned_builder': { 'options': {'inputExtension': '.matches'} } } } } } }); await testBuilders( [ apply('a:optioned_builder', [copyBuilder], toRoot(), hideOutput: false), ], { 'a|lib/file.nomatch': 'a', 'a|lib/file.matches': 'b', }, overrideBuildConfig: buildConfigs, outputs: { 'a|lib/file.copy': 'b', }); }); test('isRoot is applied correctly', () async { Builder copyBuilder(BuilderOptions options) => TestBuilder( buildExtensions: replaceExtension( '.txt', options.isRoot ? '.root.copy' : '.dep.copy')); var packageGraph = buildPackageGraph({ rootPackage('a'): ['b'], package('b'): [], }); await testBuilders([ apply('a:optioned_builder', [copyBuilder], toAllPackages(), hideOutput: true), ], { 'a|lib/a.txt': 'a', 'b|lib/b.txt': 'b', }, outputs: { r'$$a|lib/a.root.copy': 'a', r'$$b|lib/b.dep.copy': 'b', }, packageGraph: packageGraph); }); }
build/build_runner_core/test/generate/build_configuration_test.dart/0
{'file_path': 'build/build_runner_core/test/generate/build_configuration_test.dart', 'repo_id': 'build', 'token_count': 868}
// 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. export 'package:build/src/builder/logging.dart' show scopeLogAsync; export 'src/assets.dart'; export 'src/builder.dart'; export 'src/fake_watcher.dart'; export 'src/globbing_builder.dart'; export 'src/in_memory_reader.dart'; export 'src/in_memory_writer.dart'; export 'src/matchers.dart'; export 'src/multi_asset_reader.dart' show MultiAssetReader; export 'src/package_reader.dart' show PackageAssetReader; export 'src/record_logs.dart'; export 'src/resolve_source.dart' show useAssetReader, resolveSource, resolveSources, resolveAsset; export 'src/stub_reader.dart'; export 'src/stub_writer.dart'; export 'src/test_builder.dart'; export 'src/written_asset_reader.dart';
build/build_test/lib/build_test.dart/0
{'file_path': 'build/build_test/lib/build_test.dart', 'repo_id': 'build', 'token_count': 299}
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'package:build/build.dart'; import 'package:crypto/crypto.dart'; import 'package:path/path.dart' as p; // ignore: deprecated_member_use import 'package:test_core/backend.dart'; /// A [Builder] that injects bootstrapping code used by the test runner to run /// tests in --precompiled mode. /// /// This doesn't modify existing code at all, it just adds wrapper files that /// can be used to load isolates or iframes. class TestBootstrapBuilder extends Builder { @override final buildExtensions = const { '_test.dart': [ '_test.dart.vm_test.dart', '_test.dart.browser_test.dart', '_test.dart.node_test.dart', ] }; TestBootstrapBuilder(); @override Future<void> build(BuildStep buildStep) async { var id = buildStep.inputId; var contents = await buildStep.readAsString(id); var assetPath = id.pathSegments.first == 'lib' ? p.url.join('packages', id.package, id.path) : id.path; var vmRuntimes = [Runtime.vm]; var browserRuntimes = Runtime.builtIn.where((r) => r.isBrowser == true).toList(); var nodeRuntimes = [Runtime.nodeJS]; var config = await _ConfigLoader.instance.load(id.package, buildStep); if (config != null) { for (var customRuntime in config.defineRuntimes.values) { var parent = customRuntime.parent; if (vmRuntimes.any((r) => r.identifier == parent)) { var runtime = vmRuntimes.firstWhere((r) => r.identifier == parent); vmRuntimes.add( runtime.extend(customRuntime.name, customRuntime.identifier)); } else if (browserRuntimes.any((r) => r.identifier == parent)) { var runtime = browserRuntimes.firstWhere((r) => r.identifier == parent); browserRuntimes.add( runtime.extend(customRuntime.name, customRuntime.identifier)); } else if (nodeRuntimes.any((r) => r.identifier == parent)) { var runtime = nodeRuntimes.firstWhere((r) => r.identifier == parent); nodeRuntimes.add( runtime.extend(customRuntime.name, customRuntime.identifier)); } } } var metadata = parseMetadata( assetPath, contents, vmRuntimes .followedBy(browserRuntimes) .followedBy(nodeRuntimes) .map((r) => r.identifier) .toSet()); if (vmRuntimes.any((r) => metadata.testOn.evaluate(SuitePlatform(r)))) { await buildStep.writeAsString(id.addExtension('.vm_test.dart'), ''' ${metadata.languageVersionComment ?? ''} import "dart:isolate"; import "package:test/bootstrap/vm.dart"; import "${p.url.basename(id.path)}" as test; void main(_, SendPort message) { internalBootstrapVmTest(() => test.main, message); } '''); } if (browserRuntimes .any((r) => metadata.testOn.evaluate(SuitePlatform(r)))) { await buildStep.writeAsString(id.addExtension('.browser_test.dart'), ''' ${metadata.languageVersionComment ?? ''} import "package:test/bootstrap/browser.dart"; import "${p.url.basename(id.path)}" as test; void main() { if (Uri.base.queryParameters['directRun'] == 'true') { test.main(); } else { internalBootstrapBrowserTest(() => test.main); } } '''); } if (nodeRuntimes.any((r) => metadata.testOn.evaluate(SuitePlatform(r)))) { await buildStep.writeAsString(id.addExtension('.node_test.dart'), ''' ${metadata.languageVersionComment ?? ''} import "package:test/bootstrap/node.dart"; import "${p.url.basename(id.path)}" as test; void main() { internalBootstrapNodeTest(() => test.main); } '''); } } } /// Manages a cache of [Configuration] per package, to avoid duplicating work /// across build steps. /// /// Can safely be used across the build as configuration is invalidated by its /// digest. class _ConfigLoader { _ConfigLoader._(); static final instance = _ConfigLoader._(); final _configByPackage = <String, Future<Configuration>>{}; final _configDigestByPackage = <String, Digest>{}; Future<Configuration?> load(String package, AssetReader reader) async { var customConfigId = AssetId(package, 'dart_test.yaml'); if (!await reader.canRead(customConfigId)) return null; var digest = await reader.digest(customConfigId); if (_configDigestByPackage[package] == digest) { assert(_configByPackage[package] != null); return _configByPackage[package]; } _configDigestByPackage[package] = digest; return _configByPackage[package] = () async { var content = await reader.readAsString(customConfigId); return Configuration.loadFromString(content, sourceUrl: customConfigId.uri); }(); } }
build/build_test/lib/src/test_bootstrap_builder.dart/0
{'file_path': 'build/build_test/lib/src/test_bootstrap_builder.dart', 'repo_id': 'build', 'token_count': 2076}
// 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 'package:analyzer/dart/analysis/results.dart'; import 'package:analyzer/dart/element/element.dart'; import 'package:analyzer/dart/element/type.dart'; import 'package:build/build.dart'; import 'package:build_test/build_test.dart'; import 'package:package_config/package_config.dart'; import 'package:test/test.dart'; void main() { group('resolveSource can resolve', () { test('a simple dart file', () async { var libExample = await resolveSource(r''' library example; class Foo {} ''', (resolver) => resolver.findLibraryNotNull('example')); expect(libExample.getClass('Foo'), isNotNull); }); test('a simple dart file with dart: dependencies', () async { var libExample = await resolveSource(r''' library example; import 'dart:collection'; abstract class Foo implements LinkedHashMap {} ''', (resolver) => resolver.findLibraryNotNull('example')); var classFoo = libExample.getClass('Foo')!; expect( classFoo.allSupertypes.map(_toStringId), contains('dart:collection#LinkedHashMap'), ); }); test('a simple dart file package: dependencies', () async { var libExample = await resolveSource(r''' library example; import 'package:collection/collection.dart'; abstract class Foo implements Equality {} ''', (resolver) => resolver.findLibraryNotNull('example')); var classFoo = libExample.getClass('Foo')!; expect( classFoo.allSupertypes.map(_toStringId), contains(endsWith(':collection#Equality')), ); }); test('multiple assets, some mock, some on disk', () async { final real = 'build_test|test/_files/example_lib.dart'; final mock = 'build_test|test/_files/not_really_here.dart'; final library = await resolveSources( { real: useAssetReader, mock: r''' // This is a fake library that we're mocking. library example; // This is a real on-disk library we are using. import 'example_lib.dart'; class ExamplePrime extends Example {} ''', }, (resolver) => resolver.findLibraryNotNull('example'), resolverFor: mock, ); final type = library.getClass('ExamplePrime'); expect(type, isNotNull); expect(type!.supertype!.element2.name, 'Example'); }); test('waits for tearDown', () async { var resolverDone = Completer<void>(); var resolver = await resolveSource(r''' library example; import 'package:collection/collection.dart'; abstract class Foo implements Equality {} ''', (resolver) => resolver, tearDown: resolverDone.future); expect( await resolver.libraries.any((library) => library.name == 'example'), true); var libExample = await resolver.findLibraryNotNull('example'); resolverDone.complete(); var classFoo = libExample.getClass('Foo')!; expect( classFoo.allSupertypes.map(_toStringId), contains(endsWith(':collection#Equality')), ); }); test('can do expects inside the action', () async { await resolveSource(r''' library example; import 'package:collection/collection.dart'; abstract class Foo implements Equality {} ''', (resolver) async { var libExample = await resolver.findLibraryNotNull('example'); var classFoo = libExample.getClass('Foo')!; expect(classFoo.allSupertypes.map(_toStringId), contains(endsWith(':collection#Equality'))); }); }); test('with specified language versions from a PackageConfig', () async { var packageConfig = PackageConfig([ Package('a', Uri.file('/a/'), packageUriRoot: Uri.file('/a/lib/'), languageVersion: LanguageVersion(2, 3)) ]); var libExample = await resolveSource(r''' library example; extension _Foo on int {} ''', (resolver) => resolver.findLibraryNotNull('example'), packageConfig: packageConfig, inputId: AssetId('a', 'invalid.dart')); var errors = await libExample.session .getErrors(libExample.source.fullName) as ErrorsResult; expect( errors.errors.map((e) => e.message), contains(contains( 'This requires the \'extension-methods\' language feature to be ' 'enabled.'))); }); }); group('should resolveAsset', () { test('asset:build_test/test/_files/example_lib.dart', () async { var asset = AssetId('build_test', 'test/_files/example_lib.dart'); var libExample = await resolveAsset( asset, (resolver) => resolver.findLibraryNotNull('example_lib')); expect(libExample.getClass('Example'), isNotNull); }); }); group('error handling', () { test('getting the library for a part file', () async { var partAsset = AssetId('build_test', 'test/_files/example_part.dart'); await resolveAsset(partAsset, (resolver) async { expect( () => resolver.libraryFor(partAsset), throwsA(isA<NonLibraryAssetException>() .having((e) => e.assetId, 'assetId', partAsset))); }); }); }); } String _toStringId(InterfaceType t) => '${t.element2.source.uri.toString().split('/').first}#${t.element2.name}'; extension on Resolver { Future<LibraryElement> findLibraryNotNull(String name) async { return (await findLibraryByName(name))!; } }
build/build_test/test/resolve_source_test.dart/0
{'file_path': 'build/build_test/test/resolve_source_test.dart', 'repo_id': 'build', 'token_count': 2267}
// 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/build.dart'; import 'package:path/path.dart' as p; import 'common.dart'; /// Copies the require.js file from the sdk itself, into the /// build_web_compilers package at `lib/require.js`. class SdkJsCopyBuilder implements Builder { @override final buildExtensions = { r'$package$': ['lib/src/dev_compiler/require.js'] }; /// Path to the require.js file that should be used for all ddc web apps. final _sdkRequireJsLocation = p.join(sdkDir, 'lib', 'dev_compiler', 'kernel', 'amd', 'require.js'); @override FutureOr<void> build(BuildStep buildStep) async { if (buildStep.inputId.package != 'build_web_compilers') { throw StateError('This builder should only be applied to the ' 'build_web_compilers package'); } await buildStep.writeAsBytes( AssetId('build_web_compilers', 'lib/src/dev_compiler/require.js'), await File(_sdkRequireJsLocation).readAsBytes()); } }
build/build_web_compilers/lib/src/sdk_js_copy_builder.dart/0
{'file_path': 'build/build_web_compilers/lib/src/sdk_js_copy_builder.dart', 'repo_id': 'build', 'token_count': 419}
name: b environment: sdk: ">=1.0.0 <3.0.0" dependencies: a: path: ../a
build/build_web_compilers/test/fixtures/b/pubspec.yaml/0
{'file_path': 'build/build_web_compilers/test/fixtures/b/pubspec.yaml', 'repo_id': 'build', 'token_count': 46}
import 'package:meta/meta.dart'; /// Alias for vm:prefer-inline @internal const preferInline = pragma('vm:prefer-inline');
build_runner_bug/packages/custom_lint_core/lib/src/pragrams.dart/0
{'file_path': 'build_runner_bug/packages/custom_lint_core/lib/src/pragrams.dart', 'repo_id': 'build_runner_bug', 'token_count': 43}
# Defines a default set of lint rules enforced for # projects at Google. For details and rationale, # see https://github.com/dart-lang/pedantic#enabled-lints. include: package:pedantic/analysis_options.yaml analyzer: strong-mode: implicit-dynamic: false errors: unused_import: error unused_local_variable: error dead_code: error # Lint rules and documentation, see http://dart-lang.github.io/linter/lints linter: rules: - annotate_overrides - avoid_unused_constructor_parameters - await_only_futures - camel_case_types - cancel_subscriptions - directives_ordering - empty_catches - empty_statements - hash_and_equals - iterable_contains_unrelated_type - list_remove_unrelated_type - no_adjacent_strings_in_list - no_duplicate_case_values - non_constant_identifier_names - only_throw_errors - overridden_fields - prefer_collection_literals - prefer_conditional_assignment - prefer_contains - prefer_final_fields - prefer_final_locals - prefer_initializing_formals - prefer_interpolation_to_compose_strings - prefer_is_empty - prefer_is_not_empty - prefer_typing_uninitialized_variables - recursive_getters - slash_for_doc_comments - test_types_in_equals - throw_in_finally - type_init_formals - unawaited_futures - unnecessary_brace_in_string_interps - unnecessary_getters_setters - unnecessary_lambdas - unnecessary_new - unnecessary_null_aware_assignments - unnecessary_statements - unnecessary_this - unrelated_type_equality_checks - use_rethrow_when_possible - valid_regexps
bunq.dart/analysis_options.yaml/0
{'file_path': 'bunq.dart/analysis_options.yaml', 'repo_id': 'bunq.dart', 'token_count': 630}
import 'package:cached_value/cached_value.dart'; import 'package:meta/meta.dart'; import 'package:test/test.dart'; class TestBed { String name = "Elon Bezos"; // Married name late final firstNameCache = CachedValue( () => name.split(" ").first, ).withDependency( () => name, ); } @isTest void testComputedCachedValue( String description, dynamic Function(TestBed testBed) body, ) { final testBed = TestBed(); test(description, () => body(testBed)); } void main() { testComputedCachedValue( "cached value should be computed and cached", (testBed) { final cachedValueAtStart = testBed.firstNameCache.value; // update value testBed.name = "Joseph climber"; final cachedValueAfterUpdate = testBed.firstNameCache.value; expect(cachedValueAtStart, equals('Elon')); expect(cachedValueAfterUpdate, equals('Joseph')); }, ); testComputedCachedValue( 'dependency change should update cached value on next access', (testBed) { final cachedValueAtStart = testBed.firstNameCache.value; final validAfterFirstAccess = testBed.firstNameCache.isValid; // update value testBed.name = "Joseph climber"; final validAfterUpdate = testBed.firstNameCache.isValid; final cachedValueAfterUpdate = testBed.firstNameCache.value; final validAfterUpdateAccess = testBed.firstNameCache.isValid; expect(cachedValueAtStart, equals('Elon')); expect(cachedValueAfterUpdate, equals('Joseph')); expect(validAfterFirstAccess, isTrue); expect(validAfterUpdate, isFalse); expect(validAfterUpdateAccess, isTrue); }, ); testComputedCachedValue( 'invalidate should update cached value on next access', (testBed) { // first access final cachedValueStart = testBed.firstNameCache.value; final validAfterFirstAccess = testBed.firstNameCache.isValid; // invalidate testBed.firstNameCache.invalidate(); final validAfterInvalidate = testBed.firstNameCache.isValid; // second access final cachedValueAfterInvalidate = testBed.firstNameCache.value; final validAfterInvalidateAccess = testBed.firstNameCache.isValid; expect(cachedValueStart, equals('Elon')); expect(cachedValueAfterInvalidate, equals('Elon')); expect(validAfterFirstAccess, isTrue); expect(validAfterInvalidate, isFalse); expect(validAfterInvalidateAccess, isTrue); }, ); testComputedCachedValue('refresh should update cached value immediately', (testBed) { // first access final cachedValueStart = testBed.firstNameCache.value; final validAfterFirstAccess = testBed.firstNameCache.isValid; // update value testBed.name = "Joseph climber"; final validAfterUpdate = testBed.firstNameCache.isValid; // refresh testBed.firstNameCache.refresh(); final validAfterRefresh = testBed.firstNameCache.isValid; // second access final cachedValueAfterUpdate = testBed.firstNameCache.value; expect(cachedValueStart, equals('Elon')); expect(cachedValueAfterUpdate, equals('Joseph')); expect(validAfterFirstAccess, isTrue); expect(validAfterUpdate, isFalse); expect(validAfterRefresh, isTrue); }); }
cached_value/test/src/dependent_cached_value_test.dart/0
{'file_path': 'cached_value/test/src/dependent_cached_value_test.dart', 'repo_id': 'cached_value', 'token_count': 1121}
import 'dart:ui'; import 'canvas_command.dart'; /// canvas.drawRect() class RectCommand extends CanvasCommand { RectCommand(this.rect, this.paint); final Rect rect; final Paint? paint; @override bool equals(RectCommand other) { return eq(rect, other.rect) && eq(paint, other.paint); } @override String toString() { return 'drawRect(${repr(rect)}, ${repr(paint)})'; } }
canvas_test/lib/src/canvas_commands/rect_command.dart/0
{'file_path': 'canvas_test/lib/src/canvas_commands/rect_command.dart', 'repo_id': 'canvas_test', 'token_count': 147}
// Copyright (c) 2022, Very Good Ventures // https://verygood.ventures // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. @Tags(['version-verify']) import 'package:build_verify/build_verify.dart'; import 'package:test/test.dart'; void main() { test('ensure_build', expectBuildClean); }
chance-dart-cli/test/ensure_build_test.dart/0
{'file_path': 'chance-dart-cli/test/ensure_build_test.dart', 'repo_id': 'chance-dart-cli', 'token_count': 126}
import 'dart:math'; enum Casing { lower, upper } const String _lowerCaseChars = 'abcdefghijklmnopqrstuvwxyz'; const String _upperCaseChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; const String _symbols = '!@#\$%^&*()'; const String _numbers = '0123456789'; const String _chars = '$_lowerCaseChars$_upperCaseChars$_numbers$_symbols'; /// Return a random character. // => 'c' /// Usage /// ```character()``` /// ```character({ pool: 'abcde' })``` /// ```chance.character({ alpha: true })``` /// ```chance.character({ numeric: true })``` /// ```chance.character({ casing: 'lower' })``` /// ```chance.character({ symbols: true })``` /// String character({ bool? alpha, /// Optionally specify a pool and the character will be generated with /// characters only from that pool. /// By default it will return a string with random character from the /// following pool. /// [_chars] String? pool, /// Optionally specify numeric for a numeric character. bool? numeric, /// Default includes both upper and lower case. It's possible to specify /// one or the other. Casing? casing, /// Optionally return only symbols bool? symbols, }) { assert(alpha == true && numeric == true); assert(casing != null && symbols == true); if (alpha == null && pool == null && numeric == null && casing == null && symbols == null) { return _getRandomString(); } else if (alpha == true) { return _getRandomString(_upperCaseChars); } else if (pool != null) { return _getRandomString(pool); } else if (casing != null) { if (casing == Casing.lower) { return _getRandomString(_lowerCaseChars); } return _getRandomString(_upperCaseChars); } else if (symbols != null) { return _getRandomString(_symbols); } return _getRandomString(); } String _getRandomString([String? chars]) => String.fromCharCodes( Iterable.generate( 1, (_) => chars?.codeUnitAt( Random().nextInt(chars.length), ) ?? _chars.codeUnitAt( Random().nextInt(_chars.length), ), ), );
chance-dart/packages/chance_dart/lib/core/basics/src/character.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/basics/src/character.dart', 'repo_id': 'chance-dart', 'token_count': 784}
import '../../core.dart'; /// It returns a random number between the min and max values, with a fixed /// number of decimal places /// /// Args: /// max (int): The maximum value of the number. /// min (int): The minimum value of the number. /// fixed (int): The number of decimal places to return. /// /// Returns: /// A string with a random number between 0 and /// ```max``` String cedi({ int? max, int? min, int? fixed, }) { num value = floating( fixed: fixed, max: max, min: min, ); return '₵$value'; }
chance-dart/packages/chance_dart/lib/core/finance/src/cedi.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/finance/src/cedi.dart', 'repo_id': 'chance-dart', 'token_count': 185}
import 'dart:convert'; import 'dart:math'; import 'package:chance_dart/core/location/models/address.dart'; import '../constants/addresses.dart'; /// It takes the addresses string, decodes it, parses it into a map, /// converts the map into a list of /// addresses, and returns a random address from that list /// /// Returns: /// A random address from the list of addresses. Address address() { final decodedAddress = base64Decode(addresses); final addressList = (jsonDecode( String.fromCharCodes(decodedAddress), )['addresses'] as List) .map( (addressMap) => Address.fromMap(addressMap as Map<String, dynamic>), ) .toList(); return addressList[Random().nextInt(addressList.length)]; }
chance-dart/packages/chance_dart/lib/core/location/src/address.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/location/src/address.dart', 'repo_id': 'chance-dart', 'token_count': 242}
import '../../core.dart'; /// Return a randomly generated address street. /// /// Returns: /// The street from the randomly generated address. String street() { final randomAddress = address(); if (randomAddress.address1 == null) { return street(); } return randomAddress.address1!; }
chance-dart/packages/chance_dart/lib/core/location/src/street.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/location/src/street.dart', 'repo_id': 'chance-dart', 'token_count': 86}
import 'dart:math'; /// Generates a UUID. /// /// Returns: /// A string of 36 characters. String generateUUID() { final microSecond = DateTime.now().microsecond; /// Generating a random UUID. final uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' .split('') .map( (value) => value .replaceAll( 'x', _replacer('x', microSecond + Random().nextInt(10)), ) .replaceAll( 'y', _replacer('y', microSecond), ), ) .join(); return uuid; } /// `(microSecond + Random().nextInt(99999999) * 16) % 16 | 0` /// /// The above function is a bitwise operation that returns a random number /// between 0 and 15 /// /// Args: /// c (String): The character to be replaced. /// microSecond (int): The current time in microseconds. /// /// Returns: /// A random hexadecimal number. String _replacer(String c, int microSecond) { num sec = microSecond; final random = (microSecond + Random().nextInt(99999999) * 16) % 16 | 0; sec = (sec / 16); return (c == 'x' ? random : (random & 0x3 | 0x8)).toString()[0]; }
chance-dart/packages/chance_dart/lib/core/mobile/src/uuid.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/mobile/src/uuid.dart', 'repo_id': 'chance-dart', 'token_count': 476}
import 'package:chance_dart/chance_dart.dart'; /// Returns a random integer between 0 and 60. /// /// Returns: /// A random integer between 0 and 60. int minute() { return integer(max: 60); }
chance-dart/packages/chance_dart/lib/core/time/src/minute.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/core/time/src/minute.dart', 'repo_id': 'chance-dart', 'token_count': 64}
import 'package:chance_dart/chance_dart.dart'; /// It takes in a [ChanceAlias] and a [Map] of arguments and returns a dynamic value /// /// Args: /// alias (ChanceAlias): The alias of the function to call. /// args (Map<String, dynamic>): The arguments passed to the function. Defaults to const {} /// extraValue (dynamic): This is the value that will be returned if the alias is not found. /// /// Returns: /// A function that takes a [ChanceAlias] and returns a dynamic value. dynamic aliasToFunction( ChanceAlias alias, [ Map<String, dynamic> args = const {}, dynamic extraValue, ]) { final fixed = args['fixed']; /// final max = args['max']; /// final min = args['min']; /// final casing = args['casing']; /// final alpha = args['alpha']; /// final length = args['length']; /// final pool = args['pool']; /// final symbols = args['symbols']; /// final template = args['template']; /// final ccType = args['cc_type'] ?? args['ccType']; /// final count = args['count']; /// final currencyKeyToRemove = args['currencyKeyToRemove'] ?? args['currency_key_to_remove']; /// final future = args['future']; /// final lineBreak = args['lineBreak'] ?? args['line_break']; /// final sentences = args['sentences']; switch (alias) { case ChanceAlias.falsy: return falsy(); case ChanceAlias.boolean: return boolean(); case ChanceAlias.character: return character( alpha: alpha, ); case ChanceAlias.floating: return floating( fixed: fixed, max: max, min: min, ); case ChanceAlias.integer: return integer( max: max, ); case ChanceAlias.letter: return letter( casing: casing, ); case ChanceAlias.natural: return natural( max: max, ); case ChanceAlias.prime: return prime( max: max, ); case ChanceAlias.string: return string( alpha: alpha, casing: casing, length: length, max: max, pool: pool, symbols: symbols, ); case ChanceAlias.template: return template( template, ); case ChanceAlias.ccType: return ccType(); case ChanceAlias.cc: return cc( ccType: ccType, ); case ChanceAlias.cedi: return cedi( fixed: fixed, max: max, min: min, ); case ChanceAlias.currenyPair: return currencyPair(); case ChanceAlias.currency: return currency( currencyKeyToRemove: currencyKeyToRemove, ); case ChanceAlias.dollar: return dollar( fixed: fixed, max: max, min: min, ); case ChanceAlias.euro: return euro( fixed: fixed, max: max, min: min, ); case ChanceAlias.expMonth: return expMonth( future: future, ); case ChanceAlias.expYear: return expYear(); case ChanceAlias.exp: return exp(); case ChanceAlias.naira: return naira( fixed: fixed, max: max, min: min, ); case ChanceAlias.address: return address(); case ChanceAlias.altitude: return ''; case ChanceAlias.areaCode: return areaCode(); case ChanceAlias.city: return city(); case ChanceAlias.coordinates: return coordinates(); case ChanceAlias.country: return country(); case ChanceAlias.depth: return 0; case ChanceAlias.geohash: return geohash(); case ChanceAlias.latitude: return latitude(); case ChanceAlias.locale: return locale(); case ChanceAlias.longitude: return longitude(); case ChanceAlias.phone: return phone(); case ChanceAlias.postal: return postal(); case ChanceAlias.postCode: return postCode(); case ChanceAlias.province: return ''; case ChanceAlias.state: return state(); case ChanceAlias.street: return street(); case ChanceAlias.age: return age( max: max, ); case ChanceAlias.birthday: return birthday(); case ChanceAlias.firstName: return firstName(); case ChanceAlias.fullName: return fullName(); case ChanceAlias.gender: return gender(); case ChanceAlias.lastName: return lastName(); case ChanceAlias.personTitle: return personTitle(); case ChanceAlias.ssn: return ssn(); case ChanceAlias.zip: return 0; case ChanceAlias.paragraph: return paragraph( lineBreak: lineBreak, sentences: sentences, ); case ChanceAlias.sentence: return sentence(); case ChanceAlias.syllable: return syllable(count); case ChanceAlias.animal: return animal(); case ChanceAlias.amPm: return amPm(); case ChanceAlias.date: return date(); case ChanceAlias.hour: return hour(); case ChanceAlias.millisecond: return millisecond(); case ChanceAlias.minute: return minute(); case ChanceAlias.month: return month(); case ChanceAlias.second: return second(); case ChanceAlias.timestamp: return timeStamp(); case ChanceAlias.timezone: return ''; case ChanceAlias.weekday: return weekday(); case ChanceAlias.year: return year( max: max, min: min, ); } }
chance-dart/packages/chance_dart/lib/src/helper.dart/0
{'file_path': 'chance-dart/packages/chance_dart/lib/src/helper.dart', 'repo_id': 'chance-dart', 'token_count': 2226}
extension StringExtension on String { String unCapitalize() { return '${this[0].toLowerCase()}${substring(1).toUpperCase()}'; } }
chance-dart/packages/chance_generator/lib/src/extensions/string_extensions.dart/0
{'file_path': 'chance-dart/packages/chance_generator/lib/src/extensions/string_extensions.dart', 'repo_id': 'chance-dart', 'token_count': 51}
include: package:very_good_analysis/analysis_options.5.1.0.yaml linter: rules: public_member_api_docs: false
cli_completion/example/analysis_options.yaml/0
{'file_path': 'cli_completion/example/analysis_options.yaml', 'repo_id': 'cli_completion', 'token_count': 44}
/// Contains the classes and functions related to the creation of suggestions /// for the completion of commands. library parser; export 'src/parser/completion_level.dart'; export 'src/parser/completion_result.dart'; export 'src/parser/completion_state.dart'; export 'src/parser/parser.dart'; export 'src/system_shell.dart';
cli_completion/lib/parser.dart/0
{'file_path': 'cli_completion/lib/parser.dart', 'repo_id': 'cli_completion', 'token_count': 95}
import 'package:args/args.dart'; import 'package:cli_completion/parser.dart'; import 'package:cli_completion/src/parser/arg_parser_extension.dart'; /// {@template completion_parser} /// The workhorse of the completion system. /// /// Responsible for discovering the possible completions given a /// [CompletionLevel] /// {@endtemplate} class CompletionParser { /// {@macro completion_parser} CompletionParser({ required this.completionLevel, }); /// The [CompletionLevel] to parse. final CompletionLevel completionLevel; /// Parse the given [CompletionState] into a [CompletionResult] given the /// structure of commands and options declared by the CLIs [ArgParser]. List<CompletionResult> parse() => _parse().toList(); Iterable<CompletionResult> _parse() sync* { final rawArgs = completionLevel.rawArgs; final visibleSubcommands = completionLevel.visibleSubcommands; final nonEmptyArgs = rawArgs.where((element) => element.isNotEmpty); if (nonEmptyArgs.isEmpty) { // There is nothing in the user prompt between the last known command and // the cursor // e.g. `my_cli commandName|` yield AllOptionsAndCommandsCompletionResult( completionLevel: completionLevel, ); return; } final argOnCursor = rawArgs.last; if (argOnCursor.isEmpty) { // Check if the last given argument, if it is an option, // complete with the known allowed values. // e.g. `my_cli commandName --option |` or `my_cli commandName -o |` final lastNonEmpty = nonEmptyArgs.last; final suggestionForValues = _getOptionValues(lastNonEmpty); if (suggestionForValues != null) { yield suggestionForValues; return; } // User pressed space before tab (not currently writing any arg ot the // arg is a flag) // e.g. `my_cli commandName something |` yield AllOptionsAndCommandsCompletionResult( completionLevel: completionLevel, ); return; } // Check if the user has started to type the value of an // option with "allowed" values // e.g. `my_cli --option valueNam|` or `my_cli -o valueNam|` if (nonEmptyArgs.length > 1) { final secondLastNonEmpty = nonEmptyArgs.elementAt(nonEmptyArgs.length - 2); final resultForValues = _getOptionValues(secondLastNonEmpty, argOnCursor); if (resultForValues != null) { yield resultForValues; return; } } // Further code cover the case where the user is in the middle of writing a // word. // From now on, avoid early returns since completions may include commands // and options alike // Check if the user has started to type a sub command and pressed tab // e.g. `my_cli commandNam|` if (visibleSubcommands.isNotEmpty) { yield MatchingCommandsCompletionResult( completionLevel: completionLevel, pattern: argOnCursor, ); } // Check if the user has started to type an option // e.g. `my_cli commandName --optionNam|` if (isOption(argOnCursor)) { yield MatchingOptionsCompletionResult( completionLevel: completionLevel, pattern: argOnCursor.substring(2), ); } // Abbreviation cases if (isAbbr(argOnCursor)) { // Check if the user typed only a dash if (argOnCursor.length == 1) { yield AllAbbrOptionsCompletionResult(completionLevel: completionLevel); } else { // The user has started to type the value of an // option with "allowed" in an abbreviated form or just the abbreviation // e.g. `my_cli commandName -a|` or `my_cli commandName -avalueNam|` final abbrName = argOnCursor.substring(1, 2); final abbrValue = argOnCursor.substring(2); yield OptionValuesCompletionResult.abbr( abbrName: abbrName, completionLevel: completionLevel, pattern: abbrValue, includeAbbrName: true, ); } } } CompletionResult? _getOptionValues(String value, [String? valuePattern]) { if (isOption(value)) { final optionName = value.substring(2); final option = completionLevel.grammar.findByNameOrAlias(optionName); final receivesValue = option != null && !option.isFlag; if (receivesValue) { return OptionValuesCompletionResult( optionName: optionName, completionLevel: completionLevel, pattern: valuePattern, ); } } else if (isAbbr(value) && value.length > 1) { final abbrName = value.substring(1, 2); final option = completionLevel.grammar.findByAbbreviation(abbrName); final receivesValue = option != null && !option.isFlag; if (receivesValue) { return OptionValuesCompletionResult.abbr( abbrName: abbrName, completionLevel: completionLevel, pattern: valuePattern, ); } } return null; } }
cli_completion/lib/src/parser/parser.dart/0
{'file_path': 'cli_completion/lib/src/parser/parser.dart', 'repo_id': 'cli_completion', 'token_count': 1852}
import 'package:args/args.dart'; import 'package:args/command_runner.dart'; import 'package:cli_completion/parser.dart'; import 'package:test/test.dart'; class _TestCommand extends Command<void> { _TestCommand({ required this.name, required this.description, }); @override final String description; @override final String name; } void main() { group('CompletionParser', () { test('can be instantiated', () { expect( () => CompletionParser( completionLevel: CompletionLevel( grammar: ArgParser(), rawArgs: const [], visibleOptions: const [], visibleSubcommands: const [], ), ), returnsNormally, ); }); group('parse', () { final visibleSubcommands = [ _TestCommand(name: 'command1', description: 'yay command 1'), _TestCommand(name: 'command2', description: 'yay command 2'), ]; final testArgParser = ArgParser() ..addOption('option') ..addOption('optionAllowed', abbr: 'a', allowed: ['allowed', 'another']) ..addFlag('flag'); group('when there is zero non empty args', () { test('returns all options', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: ' '.split(' '), visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 1); expect( result.first, isA<AllOptionsAndCommandsCompletionResult>(), ); }); }); group('when there is a space before the cursor', () { group('and last given arg is an option', () { group('an option without allowed values', () { test('returns OptionValuesCompletionResult', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const ['', 'command1', '--option', ''], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 1); expect( result.first, isA<OptionValuesCompletionResult>() .having((r) => r.optionName, 'option name', 'option') .having((r) => r.pattern, 'pattern', null) .having((r) => r.isAbbr, 'is abbr', false), ); }); }); group('an option with allowed values', () { test('returns option values', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const ['', 'command1', '--optionAllowed', ''], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 1); expect( result.first, isA<OptionValuesCompletionResult>() .having((r) => r.optionName, 'name', 'optionAllowed') .having((r) => r.pattern, 'pattern', null) .having((r) => r.isAbbr, 'is abbr', false), ); }); }); group('an option with allowed values (abbr)', () { test('returns option values', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const ['', 'command1', '-a', ''], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 1); expect( result.first, isA<OptionValuesCompletionResult>() .having((r) => r.optionName, 'option name', 'a') .having((r) => r.pattern, 'pattern', null) .having((r) => r.isAbbr, 'is abbr', true) .having((r) => r.includeAbbrName, 'include abbr', false), ); }); }); group('a flag', () { test('returns all options', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const ['', 'command1', '--flag', ''], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 1); expect( result.first, isA<AllOptionsAndCommandsCompletionResult>(), ); }); }); }); test('returns all options', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const ['', 'command1', 'rest', ''], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 1); expect( result.first, isA<AllOptionsAndCommandsCompletionResult>(), ); }); }); group( 'when the user started to type something after writing ' 'an option', () { group('an option without allowed values', () { test('returns OptionValuesCompletionResults', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const ['', 'command1', '--option', 'something'], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 1); expect( result.first, isA<OptionValuesCompletionResult>() .having((r) => r.optionName, 'option name', 'option') .having((r) => r.pattern, 'pattern', 'something') .having((r) => r.isAbbr, 'is abbr', false), ); }); }); group('an option with allowed values', () { test('returns OptionValuesCompletionResults', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const [ '', 'command1', '--optionAllowed', 'something', ], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 1); expect( result.first, isA<OptionValuesCompletionResult>() .having((r) => r.optionName, ' name', 'optionAllowed') .having((r) => r.pattern, 'pattern', 'something') .having((r) => r.isAbbr, 'is abbr', false), ); }); }); group('an option with allowed values (abbr)', () { test('returns OptionValuesCompletionResults', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const [ '', 'command1', '-a', 'something', ], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 1); expect( result.first, isA<OptionValuesCompletionResult>() .having((r) => r.optionName, 'option name', 'a') .having((r) => r.pattern, 'pattern', 'something') .having((r) => r.isAbbr, 'is abbr', true) .having((r) => r.includeAbbrName, 'include abbr name', false), ); }); }); group('a flag', () { test('returns all options', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const ['', 'command1', '--flag', ''], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 1); expect(result.first, isA<AllOptionsAndCommandsCompletionResult>()); }); }); }); group('when the user started to type a sub command', () { test('returns all matching command', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const ['', 'command'], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 1); expect( result.first, isA<MatchingCommandsCompletionResult>() .having((res) => res.pattern, 'commands pattern', 'command'), ); }); }); group('when the user started to type an option', () { test('returns all matching options', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const ['', '--option'], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 2); expect( result.first, isA<MatchingCommandsCompletionResult>() .having((res) => res.pattern, 'commands pattern', '--option'), ); expect( result.last, isA<MatchingOptionsCompletionResult>() .having((res) => res.pattern, 'option pattern', 'option'), ); }); }); group('when the user just typed a dash', () { test('returns all matching abbreviated options', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const ['', '-'], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 2); expect( result.first, isA<MatchingCommandsCompletionResult>().having( (res) => res.pattern, 'commands pattern', '-', ), ); expect(result.last, isA<AllAbbrOptionsCompletionResult>()); }); }); group('when the user typed an abbreviated option with value', () { test('returns OptionValuesCompletionResults', () { final parser = CompletionParser( completionLevel: CompletionLevel( grammar: testArgParser, rawArgs: const ['', '-asomething'], visibleSubcommands: visibleSubcommands, visibleOptions: testArgParser.options.values.toList(), ), ); final result = parser.parse(); expect(result.length, 2); expect(result.first, isA<MatchingCommandsCompletionResult>()); expect( result.last, isA<OptionValuesCompletionResult>() .having((r) => r.optionName, 'option name', 'a') .having((r) => r.pattern, 'pattern', 'something') .having((r) => r.isAbbr, 'is abbr', true) .having((r) => r.includeAbbrName, 'include abbr name', true), ); }); }); }); }); }
cli_completion/test/src/parser/parser_test.dart/0
{'file_path': 'cli_completion/test/src/parser/parser_test.dart', 'repo_id': 'cli_completion', 'token_count': 6622}
export 'background.dart'; export 'ball.dart'; export 'palette.dart'; export 'slide.dart';
clock/canvas_clock/lib/components/style/style.dart/0
{'file_path': 'clock/canvas_clock/lib/components/style/style.dart', 'repo_id': 'clock', 'token_count': 34}
export 'composition.dart';
clock/canvas_clock/lib/rendering/rendering.dart/0
{'file_path': 'clock/canvas_clock/lib/rendering/rendering.dart', 'repo_id': 'clock', 'token_count': 9}
import 'package:cloud9/src/connectors/src/cloud9_connector.dart'; /// An implementation of the `Cloud9Connector` abstract class for Google Drive. class GoogleDriveConnector implements Cloud9Connector { @override Future<void> connect() async { // Connect to Google Drive here. } }
cloud9/lib/src/connectors/src/implementation/googledrive_connector.dart/0
{'file_path': 'cloud9/lib/src/connectors/src/implementation/googledrive_connector.dart', 'repo_id': 'cloud9', 'token_count': 83}
# Specify analysis options for all of flutter/cocoon # # Until there are meta linter rules, each desired lint must be explicitly enabled. # See: https://github.com/dart-lang/linter/issues/288 # # For a list of lints, see: http://dart-lang.github.io/linter/lints/ # See the configuration guide for more # https://github.com/dart-lang/sdk/tree/master/pkg/analyzer#configuring-the-analyzer # # There are other similar analysis options files in the flutter repos, # which should be kept in sync with this file: # # - analysis_options.yaml (this file) # - packages/flutter/lib/analysis_options_user.yaml # - https://github.com/flutter/packages/blob/main/analysis_options.yaml # - https://github.com/flutter/engine/blob/main/analysis_options.yaml # # This file contains the analysis options used by Flutter tools, such as IntelliJ, # Android Studio, and the `flutter analyze` command. include: package:flutter_lints/flutter.yaml analyzer: language: strict-casts: false strict-raw-types: true errors: # treat missing required parameters as a warning (not a hint) missing_required_param: warning # allow having TODOs in the code todo: ignore exclude: - ".dart_tool/**" - "**/*.g.dart" - "**/*.pb.dart" - "**/*.pbjson.dart" - "**/*.pbgrpc.dart" - "**/*.pbserver.dart" - "**/*.pbenum.dart" - "lib/generated_plugin_registrant.dart" - "test/**/mocks.mocks.dart" linter: rules: use_super_parameters: true prefer_final_fields: true prefer_final_locals: true prefer_single_quotes: true require_trailing_commas: true unawaited_futures: true unnecessary_await_in_return: true
cocoon/analysis_options.yaml/0
{'file_path': 'cocoon/analysis_options.yaml', 'repo_id': 'cocoon', 'token_count': 620}
# Provide instructions for google Cloud Build to auto-build flutter # dashboard to flutter-dashboard project. Auto-build will be triggered # by daily schedule on `main` branch. # # The auto-build will be skipped if no new commits since last deployment. steps: # Get recently pushed docker image and associated provenance, along with the # correct docker digest url, including the hash. - name: gcr.io/cloud-builders/gcloud entrypoint: '/bin/bash' args: - '-c' - |- cloud_build/get_docker_image_provenance.sh \ us-docker.pkg.dev/$PROJECT_ID/appengine/default.version-$SHORT_SHA:latest \ unverified_provenance.json # Verify provenance is valid before proceeding with deployment. - name: 'golang:1.20' entrypoint: '/bin/bash' args: - '-c' - |- cloud_build/verify_provenance.sh unverified_provenance.json # Deploy a new version to google cloud. - name: gcr.io/cloud-builders/gcloud entrypoint: '/bin/bash' args: - '-c' - |- gcloud config set project $PROJECT_ID latest_version=$(gcloud app versions list --hide-no-traffic --format 'value(version.id)') if [ "$latest_version" = "version-$SHORT_SHA" ]; then echo "No updates since last deployment." else bash cloud_build/deploy_app_dart.sh $PROJECT_ID $SHORT_SHA fi timeout: 1200s
cocoon/app_dart/cloudbuild_app_dart_deploy.yaml/0
{'file_path': 'cocoon/app_dart/cloudbuild_app_dart_deploy.yaml', 'repo_id': 'cocoon', 'token_count': 535}
// 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:gcloud/db.dart'; /// Class that represents a non-Google account that has been allowlisted to /// make API requests to the Flutter dashboard. /// /// By default, only App Engine cronjobs, and users /// authenticated as "@google.com" accounts are allowed to make API requests /// to the Cocooon backend. This class represents instances where non-Google /// users have been explicitly allowlisted to make such requests. @Kind(name: 'AllowedAccount') class AllowedAccount extends Model<int> { /// Creates a new [AllowedAccount]. AllowedAccount({ Key<int>? key, required this.email, }) { parentKey = key?.parent; id = key?.id; } /// The email address of the account that has been allowlisted. @StringProperty(propertyName: 'Email', required: true) String email; @override String toString() { final StringBuffer buf = StringBuffer() ..write('$runtimeType(') ..write('id: $id') ..write(', parentKey: ${parentKey?.id}') ..write(', key: ${parentKey == null ? null : key.id}') ..write(', email: $email') ..write(')'); return buf.toString(); } }
cocoon/app_dart/lib/src/model/appengine/allowed_account.dart/0
{'file_path': 'cocoon/app_dart/lib/src/model/appengine/allowed_account.dart', 'repo_id': 'cocoon', 'token_count': 409}
// GENERATED CODE - DO NOT MODIFY BY HAND // ignore_for_file: always_specify_types, implicit_dynamic_parameter part of 'service_account_info.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** ServiceAccountInfo _$ServiceAccountInfoFromJson(Map<String, dynamic> json) => ServiceAccountInfo( type: json['type'] as String?, projectId: json['project_id'] as String?, privateKeyId: json['private_key_id'] as String?, privateKey: json['private_key'] as String?, email: json['client_email'] as String?, clientId: json['client_id'] as String?, authUrl: json['auth_uri'] as String?, tokenUrl: json['token_uri'] as String?, authCertUrl: json['auth_provider_x509_cert_url'] as String?, clientCertUrl: json['client_x509_cert_url'] as String?, ); Map<String, dynamic> _$ServiceAccountInfoToJson(ServiceAccountInfo instance) => <String, dynamic>{ 'type': instance.type, 'project_id': instance.projectId, 'private_key_id': instance.privateKeyId, 'private_key': instance.privateKey, 'client_email': instance.email, 'client_id': instance.clientId, 'auth_uri': instance.authUrl, 'token_uri': instance.tokenUrl, 'auth_provider_x509_cert_url': instance.authCertUrl, 'client_x509_cert_url': instance.clientCertUrl, };
cocoon/app_dart/lib/src/model/appengine/service_account_info.g.dart/0
{'file_path': 'cocoon/app_dart/lib/src/model/appengine/service_account_info.g.dart', 'repo_id': 'cocoon', 'token_count': 507}
// 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. class ConfigurationException implements Exception { /// Create a custom exception for Autosubmit Configuration Errors. ConfigurationException(this.cause); final String cause; @override String toString() => cause; }
cocoon/auto_submit/lib/exception/configuration_exception.dart/0
{'file_path': 'cocoon/auto_submit/lib/exception/configuration_exception.dart', 'repo_id': 'cocoon', 'token_count': 96}
// 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:async'; import 'dart:convert'; import 'package:auto_submit/requests/check_request.dart'; import 'package:auto_submit/service/approver_service.dart'; import 'package:auto_submit/service/log.dart'; import 'package:auto_submit/service/pull_request_validation_service.dart'; import 'package:github/github.dart'; import 'package:googleapis/pubsub/v1.dart' as pub; import 'package:shelf/shelf.dart'; import '../request_handling/pubsub.dart'; /// Handler for processing pull requests with 'autosubmit' label. /// /// For pull requests where an 'autosubmit' label was added in pubsub, /// check if the pull request is mergable. class CheckPullRequest extends CheckRequest { const CheckPullRequest({ required super.config, required super.cronAuthProvider, super.approverProvider = ApproverService.defaultProvider, super.pubsub = const PubSub(), }); @override Future<Response> get() async { return process( config.pubsubPullRequestSubscription, config.kPubsubPullNumber, config.kPullMesssageBatchSize, ); } ///TODO refactor this method out into the base class. /// Process pull request messages from Pubsub. Future<Response> process( String pubSubSubscription, int pubSubPulls, int pubSubBatchSize, ) async { final Set<int> processingLog = <int>{}; final List<pub.ReceivedMessage> messageList = await pullMessages( pubSubSubscription, pubSubPulls, pubSubBatchSize, ); if (messageList.isEmpty) { log.info('No messages are pulled.'); return Response.ok('No messages are pulled.'); } log.info('Processing ${messageList.length} messages'); final PullRequestValidationService validationService = PullRequestValidationService(config); final List<Future<void>> futures = <Future<void>>[]; for (pub.ReceivedMessage message in messageList) { log.info(message.toJson()); assert(message.message != null); assert(message.message!.data != null); final String messageData = message.message!.data!; final Map<String, dynamic> rawBody = json.decode(String.fromCharCodes(base64.decode(messageData))) as Map<String, dynamic>; log.info('request raw body = $rawBody'); final PullRequest pullRequest = PullRequest.fromJson(rawBody); log.info('Processing message ackId: ${message.ackId}'); log.info('Processing mesageId: ${message.message!.messageId}'); log.info('Processing PR: $rawBody'); if (processingLog.contains(pullRequest.number)) { // Ack duplicate. log.info('Ack the duplicated message : ${message.ackId!}.'); await pubsub.acknowledge( pubSubSubscription, message.ackId!, ); continue; } else { final ApproverService approver = approverProvider(config); log.info('Checking auto approval of pull request: $rawBody'); await approver.autoApproval(pullRequest); processingLog.add(pullRequest.number!); } futures.add( validationService.processMessage(pullRequest, message.ackId!, pubsub), ); } await Future.wait(futures); return Response.ok('Finished processing changes'); } }
cocoon/auto_submit/lib/requests/check_pull_request.dart/0
{'file_path': 'cocoon/auto_submit/lib/requests/check_pull_request.dart', 'repo_id': 'cocoon', 'token_count': 1203}
// 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:auto_submit/service/log.dart'; import 'package:gql/ast.dart'; import 'package:graphql/client.dart'; import '../requests/exceptions.dart'; /// Service class used to execute GraphQL queries. class GraphQlService { /// Runs a GraphQL query using [slug], [prNumber] and a [GraphQL] client. Future<Map<String, dynamic>> queryGraphQL({ required DocumentNode documentNode, required Map<String, dynamic> variables, required GraphQLClient client, }) async { final QueryResult queryResult = await client.query( QueryOptions( document: documentNode, fetchPolicy: FetchPolicy.noCache, variables: variables, ), ); if (queryResult.hasException) { log.severe(queryResult.exception.toString()); throw const BadRequestException('GraphQL query failed'); } return queryResult.data!; } Future<Map<String, dynamic>> mutateGraphQL({ required DocumentNode documentNode, required Map<String, dynamic> variables, required GraphQLClient client, }) async { final QueryResult queryResult = await client.mutate( MutationOptions( document: documentNode, fetchPolicy: FetchPolicy.noCache, variables: variables, ), ); if (queryResult.hasException) { log.severe(queryResult.exception.toString()); throw const BadRequestException('GraphQL mutate failed'); } return queryResult.data!; } }
cocoon/auto_submit/lib/service/graphql_service.dart/0
{'file_path': 'cocoon/auto_submit/lib/service/graphql_service.dart', 'repo_id': 'cocoon', 'token_count': 546}
// 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. const String sampleConfigNoOverride = ''' default_branch: main allow_config_override: false auto_approval_accounts: - dependabot[bot] - dependabot - DartDevtoolWorkflowBot approving_reviews: 2 approval_group: flutter-hackers run_ci: true support_no_review_revert: true required_checkruns_on_revert: - ci.yaml validation '''; const String sampleConfigRevertReviewRequired = ''' default_branch: main allow_config_override: false auto_approval_accounts: - dependabot[bot] - dependabot - DartDevtoolWorkflowBot approving_reviews: 2 approval_group: flutter-hackers run_ci: true support_no_review_revert: false required_checkruns_on_revert: - ci.yaml validation '''; const String sampleConfigWithOverride = ''' default_branch: main allow_config_override: true auto_approval_accounts: - dependabot[bot] - dependabot - DartDevtoolWorkflowBot approving_reviews: 2 approval_group: flutter-hackers run_ci: true support_no_review_revert: true required_checkruns_on_revert: - ci.yaml validation ''';
cocoon/auto_submit/test/configuration/repository_configuration_data.dart/0
{'file_path': 'cocoon/auto_submit/test/configuration/repository_configuration_data.dart', 'repo_id': 'cocoon', 'token_count': 444}
// Copyright 2023 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:auto_submit/validations/validation.dart'; import 'package:auto_submit/validations/validation_filter.dart'; class FakeValidationFilter implements ValidationFilter { final Set<Validation> validations = {}; void registerValidation(Validation newValidation) { validations.add(newValidation); } @override Set<Validation> getValidations() { return validations; } }
cocoon/auto_submit/test/src/validations/fake_validation_filter.dart/0
{'file_path': 'cocoon/auto_submit/test/src/validations/fake_validation_filter.dart', 'repo_id': 'cocoon', 'token_count': 166}
// Copyright 2019 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:io' as io; import 'package:codesign/verify.dart'; import 'package:logging/logging.dart'; Future<void> main(List<String> args) async { final Logger logger = Logger('root'); logger.onRecord.listen((LogRecord record) { io.stdout.writeln(record.message); }); if (args.length != 1) { logger.info('Usage: dart verify.dart [FILE]'); io.exit(1); } if (!io.Platform.isMacOS) { logger.severe('This tool must be run from macOS.'); io.exit(1); } final inputFile = args[0]; final VerificationResult result = await VerificationService( binaryPath: inputFile, logger: logger, ).run(); io.exit(result == VerificationResult.codesignedAndNotarized ? 0 : 1); }
cocoon/cipd_packages/codesign/bin/verify.dart/0
{'file_path': 'cocoon/cipd_packages/codesign/bin/verify.dart', 'repo_id': 'cocoon', 'token_count': 301}
// 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/foundation.dart'; typedef BrookCallback<T> = void Function(T event); /// A source of events of type T. /// /// This is a light-weight stream, hence the name of the class. /// /// Listeners cannot be registered multiple times simultaneously. class Brook<T> { Brook(); final Set<BrookCallback<T>> _listeners = <BrookCallback<T>>{}; void addListener(BrookCallback<T> listener) { assert(!_listeners.contains(listener)); _listeners.add(listener); } void removeListener(BrookCallback<T> listener) { assert(_listeners.contains(listener)); _listeners.remove(listener); } } /// A place to send events of type T. /// /// Instances of this class can be given to consumers, as the type [Brook]. /// This allows consumers to register for events without being able to send /// events. class BrookSink<T> extends Brook<T> { BrookSink(); void send(T event) { final List<BrookCallback<T>> frozenListeners = _listeners.toList(); for (final BrookCallback<T> listener in frozenListeners) { try { if (_listeners.contains(listener)) { listener(event); } } catch (exception, stack) { FlutterError.reportError( FlutterErrorDetails( exception: exception, stack: stack, library: 'Flutter Dashboard', context: ErrorDescription('while sending event'), informationCollector: () sync* { yield DiagnosticsProperty<BrookSink<T>>( 'The $runtimeType sending the event was', this, style: DiagnosticsTreeStyle.errorProperty, ); yield DiagnosticsProperty<T>( 'The $T event was', event, style: DiagnosticsTreeStyle.errorProperty, ); }, ), ); } } } } class ErrorSink extends BrookSink<String> { ErrorSink(); @override void send(String event) { // TODO(ianh): log errors to a service as well, https://github.com/flutter/flutter/issues/52697 debugPrint(event); // to allow for copy/paste super.send(event); } }
cocoon/dashboard/lib/logic/brooks.dart/0
{'file_path': 'cocoon/dashboard/lib/logic/brooks.dart', 'repo_id': 'cocoon', 'token_count': 917}
// 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:flutter/widgets.dart'; /// An inherited widget that reports the current time and /// ticks once per second. class Now extends InheritedNotifier<ValueNotifier<DateTime?>> { /// For production. Now({ super.key, required super.child, }) : super( notifier: _Clock(), ); /// For tests. Now.fixed({ super.key, required DateTime dateTime, required super.child, }) : super( notifier: ValueNotifier<DateTime>(dateTime), ); static DateTime? of(BuildContext context) { final Now now = context.dependOnInheritedWidgetOfExactType<Now>()!; return now.notifier!.value; } } class _Clock extends ValueNotifier<DateTime?> { _Clock() : super(null); Timer? _timer; @override void addListener(VoidCallback listener) { if (!hasListeners) { assert(_timer == null); value = DateTime.now(); _scheduleTick(); } super.addListener(listener); } @override void removeListener(VoidCallback listener) { super.removeListener(listener); if (!hasListeners && _timer != null) { _timer!.cancel(); _timer = null; value = null; } } void _tick() { value = DateTime.now(); _scheduleTick(); notifyListeners(); } void _scheduleTick() { // To make the application appear responsive, we try to tick at the start of each second // (as opposed to just anywhere within a second, each second). To do that, each tick, we // set up a new timer to fire just as the time on the device reaches a new second, right // when the milliseconds component of the time is zero. // // To compute the time until the next second, we take the current time, ignore all parts // except the milliseconds, and subtract that from one second. (We have to take care and // never wait for zero milliseconds; if the milliseconds part is zero, then we must wait // a full second.) // // By scheduling a new tick each time, we also ensure that we skip past any seconds that // we were too busy to service without increasing the load on the device. _timer = Timer(Duration(milliseconds: 1000 - (value!.millisecondsSinceEpoch % 1000)), _tick); } }
cocoon/dashboard/lib/widgets/now.dart/0
{'file_path': 'cocoon/dashboard/lib/widgets/now.dart', 'repo_id': 'cocoon', 'token_count': 802}
// 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_dashboard/service/cocoon.dart'; import 'package:flutter_dashboard/service/google_authentication.dart'; import 'package:flutter_dashboard/state/build.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:http/http.dart'; import 'package:mockito/annotations.dart'; export 'mocks.mocks.dart'; @GenerateMocks( <Type>[ Client, CocoonService, BuildState, GoogleSignIn, GoogleSignInService, ], ) void main() {}
cocoon/dashboard/test/utils/mocks.dart/0
{'file_path': 'cocoon/dashboard/test/utils/mocks.dart', 'repo_id': 'cocoon', 'token_count': 222}
linter: rules: - always_declare_return_types - always_put_control_body_on_new_line - always_put_required_named_parameters_first - always_specify_types # - always_use_package_imports - annotate_overrides - avoid_annotating_with_dynamic - avoid_bool_literals_in_conditional_expressions - avoid_catches_without_on_clauses - avoid_catching_errors - avoid_classes_with_only_static_members - avoid_double_and_int_checks - avoid_dynamic_calls - avoid_empty_else - avoid_equals_and_hash_code_on_mutable_classes # - avoid_escaping_inner_quotes - avoid_field_initializers_in_const_classes # - avoid_final_parameters - avoid_function_literals_in_foreach_calls - avoid_implementing_value_types - avoid_init_to_null - avoid_js_rounded_ints - avoid_multiple_declarations_per_line - avoid_null_checks_in_equality_operators - avoid_positional_boolean_parameters # - avoid_print - avoid_private_typedef_functions - avoid_redundant_argument_values - avoid_relative_lib_imports - avoid_renaming_method_parameters - avoid_return_types_on_setters - avoid_returning_null_for_void - avoid_returning_this - avoid_setters_without_getters - avoid_shadowing_type_parameters - avoid_single_cascade_in_expression_statements # - avoid_slow_async_io - avoid_type_to_string # - avoid_types_as_parameter_names # - avoid_types_on_closure_parameters - avoid_unnecessary_containers - avoid_unused_constructor_parameters - avoid_void_async - avoid_web_libraries_in_flutter - await_only_futures - camel_case_extensions - camel_case_types - cancel_subscriptions - cascade_invocations - cast_nullable_to_non_nullable - close_sinks - collection_methods_unrelated_type - combinators_ordering - comment_references - conditional_uri_does_not_exist - constant_identifier_names - control_flow_in_finally - curly_braces_in_flow_control_structures - dangling_library_doc_comments - depend_on_referenced_packages - deprecated_consistency - diagnostic_describe_all_properties - directives_ordering - discarded_futures - do_not_use_environment - empty_catches - empty_constructor_bodies - empty_statements - eol_at_end_of_file - exhaustive_cases - file_names - flutter_style_todos - hash_and_equals - implementation_imports - implicit_call_tearoffs - invalid_case_patterns - join_return_with_assignment - leading_newlines_in_multiline_strings - library_annotations - library_names - library_prefixes - library_private_types_in_public_api # - lines_longer_than_80_chars - literal_only_boolean_expressions - missing_whitespace_between_adjacent_strings - no_adjacent_strings_in_list - no_default_cases - no_duplicate_case_values - no_leading_underscores_for_library_prefixes - no_leading_underscores_for_local_identifiers - no_logic_in_create_state - no_runtimeType_toString - non_constant_identifier_names - noop_primitive_operations - null_check_on_nullable_type_parameter - null_closures # - omit_local_variable_types - one_member_abstracts - only_throw_errors - overridden_fields - package_api_docs - package_names - package_prefixed_library_names - parameter_assignments - prefer_adjacent_string_concatenation - prefer_asserts_in_initializer_lists - prefer_asserts_with_message - prefer_collection_literals - prefer_conditional_assignment - prefer_const_constructors - prefer_const_constructors_in_immutables - prefer_const_declarations - prefer_const_literals_to_create_immutables - prefer_constructors_over_static_methods - prefer_contains # - prefer_double_quotes # - prefer_expression_function_bodies - prefer_final_fields - prefer_final_in_for_each - prefer_final_locals - prefer_final_parameters - prefer_for_elements_to_map_fromIterable - prefer_foreach - prefer_function_declarations_over_variables - prefer_generic_function_type_aliases - prefer_if_elements_to_conditional_expressions - prefer_if_null_operators - prefer_initializing_formals - prefer_inlined_adds - prefer_int_literals - prefer_interpolation_to_compose_strings - prefer_is_empty - prefer_is_not_empty - prefer_is_not_operator - prefer_iterable_whereType - prefer_mixin - prefer_null_aware_method_calls - prefer_null_aware_operators - prefer_relative_imports - prefer_single_quotes - prefer_spread_collections - prefer_typing_uninitialized_variables - prefer_void_to_null - provide_deprecation_message # - public_member_api_docs - recursive_getters - require_trailing_commas - secure_pubspec_urls - sized_box_for_whitespace - sized_box_shrink_expand - slash_for_doc_comments - sort_child_properties_last - sort_constructors_first - sort_pub_dependencies - sort_unnamed_constructors_first - test_types_in_equals - throw_in_finally - tighten_type_of_initializing_formals - type_annotate_public_apis - type_init_formals - unawaited_futures - unnecessary_await_in_return - unnecessary_brace_in_string_interps - unnecessary_breaks - unnecessary_const - unnecessary_constructor_name # - unnecessary_final - unnecessary_getters_setters - unnecessary_lambdas - unnecessary_late - unnecessary_library_directive - unnecessary_new - unnecessary_null_aware_assignments - unnecessary_null_aware_operator_on_extension_on_nullable - unnecessary_null_checks - unnecessary_null_in_if_null_operators - unnecessary_nullable_for_final_variable_declarations - unnecessary_overrides - unnecessary_parenthesis - unnecessary_raw_strings - unnecessary_statements - unnecessary_string_escapes - unnecessary_string_interpolations - unnecessary_this - unnecessary_to_list_in_spreads - unreachable_from_main - unrelated_type_equality_checks - unsafe_html - use_build_context_synchronously - use_colored_box - use_decorated_box - use_enums - use_full_hex_values_for_flutter_colors - use_function_type_syntax_for_parameters - use_if_null_to_convert_nulls_to_bools - use_is_even_rather_than_modulo - use_key_in_widget_constructors - use_late_for_private_fields_and_variables - use_named_constants - use_raw_strings - use_rethrow_when_possible - use_setters_to_change_properties - use_string_buffers - use_string_in_part_of_directives - use_super_parameters - use_test_throws_matchers - use_to_and_as_if_applicable - valid_regexps - void_checks
cocoon/dev/githubanalysis/analysis_options.yaml/0
{'file_path': 'cocoon/dev/githubanalysis/analysis_options.yaml', 'repo_id': 'cocoon', 'token_count': 2698}
// // Generated code. Do not modify. // source: go.chromium.org/luci/buildbucket/proto/common.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 import 'dart:core' as $core; import 'package:protobuf/protobuf.dart' as $pb; class Status extends $pb.ProtobufEnum { static const Status STATUS_UNSPECIFIED = Status._(0, _omitEnumNames ? '' : 'STATUS_UNSPECIFIED'); static const Status SCHEDULED = Status._(1, _omitEnumNames ? '' : 'SCHEDULED'); static const Status STARTED = Status._(2, _omitEnumNames ? '' : 'STARTED'); static const Status ENDED_MASK = Status._(4, _omitEnumNames ? '' : 'ENDED_MASK'); static const Status SUCCESS = Status._(12, _omitEnumNames ? '' : 'SUCCESS'); static const Status FAILURE = Status._(20, _omitEnumNames ? '' : 'FAILURE'); static const Status INFRA_FAILURE = Status._(36, _omitEnumNames ? '' : 'INFRA_FAILURE'); static const Status CANCELED = Status._(68, _omitEnumNames ? '' : 'CANCELED'); static const $core.List<Status> values = <Status>[ STATUS_UNSPECIFIED, SCHEDULED, STARTED, ENDED_MASK, SUCCESS, FAILURE, INFRA_FAILURE, CANCELED, ]; static final $core.Map<$core.int, Status> _byValue = $pb.ProtobufEnum.initByValue(values); static Status? valueOf($core.int value) => _byValue[value]; const Status._($core.int v, $core.String n) : super(v, n); } class Trinary extends $pb.ProtobufEnum { static const Trinary UNSET = Trinary._(0, _omitEnumNames ? '' : 'UNSET'); static const Trinary YES = Trinary._(1, _omitEnumNames ? '' : 'YES'); static const Trinary NO = Trinary._(2, _omitEnumNames ? '' : 'NO'); static const $core.List<Trinary> values = <Trinary>[ UNSET, YES, NO, ]; static final $core.Map<$core.int, Trinary> _byValue = $pb.ProtobufEnum.initByValue(values); static Trinary? valueOf($core.int value) => _byValue[value]; const Trinary._($core.int v, $core.String n) : super(v, n); } class Compression extends $pb.ProtobufEnum { static const Compression ZLIB = Compression._(0, _omitEnumNames ? '' : 'ZLIB'); static const Compression ZSTD = Compression._(1, _omitEnumNames ? '' : 'ZSTD'); static const $core.List<Compression> values = <Compression>[ ZLIB, ZSTD, ]; static final $core.Map<$core.int, Compression> _byValue = $pb.ProtobufEnum.initByValue(values); static Compression? valueOf($core.int value) => _byValue[value]; const Compression._($core.int v, $core.String n) : super(v, n); } const _omitEnumNames = $core.bool.fromEnvironment('protobuf.omit_enum_names');
cocoon/packages/buildbucket-dart/lib/src/generated/go.chromium.org/luci/buildbucket/proto/common.pbenum.dart/0
{'file_path': 'cocoon/packages/buildbucket-dart/lib/src/generated/go.chromium.org/luci/buildbucket/proto/common.pbenum.dart', 'repo_id': 'cocoon', 'token_count': 1035}
// 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:test/test.dart'; import 'package:triage_bot/utils.dart'; void main() { test('hex', () { expect(hex(-1), '-1'); expect(hex(0), '00'); expect(hex(1), '01'); expect(hex(15), '0f'); expect(hex(16), '10'); expect(hex(256), '100'); }); test('s', () { expect(s(-1), 's'); expect(s(0), 's'); expect(s(1), ''); expect(s(15), 's'); expect(s(16), 's'); expect(s(256), 's'); }); }
cocoon/triage_bot/test/utils_test.dart/0
{'file_path': 'cocoon/triage_bot/test/utils_test.dart', 'repo_id': 'cocoon', 'token_count': 256}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'code.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 _$Block extends Block { @override final BuiltList<Code> statements; factory _$Block([void updates(BlockBuilder b)]) => (new BlockBuilder()..update(updates)).build() as _$Block; _$Block._({this.statements}) : super._() { if (statements == null) throw new BuiltValueNullFieldError('Block', 'statements'); } @override Block rebuild(void updates(BlockBuilder b)) => (toBuilder()..update(updates)).build(); @override _$BlockBuilder toBuilder() => new _$BlockBuilder()..replace(this); @override bool operator ==(dynamic other) { if (identical(other, this)) return true; if (other is! Block) return false; return statements == other.statements; } @override int get hashCode { return $jf($jc(0, statements.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('Block')..add('statements', statements)) .toString(); } } class _$BlockBuilder extends BlockBuilder { _$Block _$v; @override ListBuilder<Code> get statements { _$this; return super.statements ??= new ListBuilder<Code>(); } @override set statements(ListBuilder<Code> statements) { _$this; super.statements = statements; } _$BlockBuilder() : super._(); BlockBuilder get _$this { if (_$v != null) { super.statements = _$v.statements?.toBuilder(); _$v = null; } return this; } @override void replace(Block other) { if (other == null) throw new ArgumentError.notNull('other'); _$v = other as _$Block; } @override void update(void updates(BlockBuilder b)) { if (updates != null) updates(this); } @override _$Block build() { _$Block _$result; try { _$result = _$v ?? new _$Block._(statements: statements.build()); } catch (_) { String _$failedField; try { _$failedField = 'statements'; statements.build(); } catch (e) { throw new BuiltValueNestedFieldError( 'Block', _$failedField, e.toString()); } rethrow; } replace(_$result); return _$result; } }
code_builder/lib/src/specs/code.g.dart/0
{'file_path': 'code_builder/lib/src/specs/code.g.dart', 'repo_id': 'code_builder', 'token_count': 1003}
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'method.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 _$Method extends Method { @override final BuiltList<Expression> annotations; @override final BuiltList<String> docs; @override final BuiltList<Reference> types; @override final BuiltList<Parameter> optionalParameters; @override final BuiltList<Parameter> requiredParameters; @override final Code body; @override final bool external; @override final bool lambda; @override final bool static; @override final String name; @override final MethodType type; @override final MethodModifier modifier; @override final Reference returns; factory _$Method([void updates(MethodBuilder b)]) => (new MethodBuilder()..update(updates)).build() as _$Method; _$Method._( {this.annotations, this.docs, this.types, this.optionalParameters, this.requiredParameters, this.body, this.external, this.lambda, this.static, this.name, this.type, this.modifier, this.returns}) : super._() { if (annotations == null) throw new BuiltValueNullFieldError('Method', 'annotations'); if (docs == null) throw new BuiltValueNullFieldError('Method', 'docs'); if (types == null) throw new BuiltValueNullFieldError('Method', 'types'); if (optionalParameters == null) throw new BuiltValueNullFieldError('Method', 'optionalParameters'); if (requiredParameters == null) throw new BuiltValueNullFieldError('Method', 'requiredParameters'); if (external == null) throw new BuiltValueNullFieldError('Method', 'external'); if (static == null) throw new BuiltValueNullFieldError('Method', 'static'); } @override Method rebuild(void updates(MethodBuilder b)) => (toBuilder()..update(updates)).build(); @override _$MethodBuilder toBuilder() => new _$MethodBuilder()..replace(this); @override bool operator ==(dynamic other) { if (identical(other, this)) return true; if (other is! Method) return false; return annotations == other.annotations && docs == other.docs && types == other.types && optionalParameters == other.optionalParameters && requiredParameters == other.requiredParameters && body == other.body && external == other.external && lambda == other.lambda && static == other.static && name == other.name && type == other.type && modifier == other.modifier && returns == other.returns; } @override int get hashCode { return $jf($jc( $jc( $jc( $jc( $jc( $jc( $jc( $jc( $jc( $jc( $jc( $jc( $jc(0, annotations.hashCode), docs.hashCode), types.hashCode), optionalParameters.hashCode), requiredParameters.hashCode), body.hashCode), external.hashCode), lambda.hashCode), static.hashCode), name.hashCode), type.hashCode), modifier.hashCode), returns.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('Method') ..add('annotations', annotations) ..add('docs', docs) ..add('types', types) ..add('optionalParameters', optionalParameters) ..add('requiredParameters', requiredParameters) ..add('body', body) ..add('external', external) ..add('lambda', lambda) ..add('static', static) ..add('name', name) ..add('type', type) ..add('modifier', modifier) ..add('returns', returns)) .toString(); } } class _$MethodBuilder extends MethodBuilder { _$Method _$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 ListBuilder<Reference> get types { _$this; return super.types ??= new ListBuilder<Reference>(); } @override set types(ListBuilder<Reference> types) { _$this; super.types = types; } @override ListBuilder<Parameter> get optionalParameters { _$this; return super.optionalParameters ??= new ListBuilder<Parameter>(); } @override set optionalParameters(ListBuilder<Parameter> optionalParameters) { _$this; super.optionalParameters = optionalParameters; } @override ListBuilder<Parameter> get requiredParameters { _$this; return super.requiredParameters ??= new ListBuilder<Parameter>(); } @override set requiredParameters(ListBuilder<Parameter> requiredParameters) { _$this; super.requiredParameters = requiredParameters; } @override Code get body { _$this; return super.body; } @override set body(Code body) { _$this; super.body = body; } @override bool get external { _$this; return super.external; } @override set external(bool external) { _$this; super.external = external; } @override bool get lambda { _$this; return super.lambda; } @override set lambda(bool lambda) { _$this; super.lambda = lambda; } @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 MethodType get type { _$this; return super.type; } @override set type(MethodType type) { _$this; super.type = type; } @override MethodModifier get modifier { _$this; return super.modifier; } @override set modifier(MethodModifier modifier) { _$this; super.modifier = modifier; } @override Reference get returns { _$this; return super.returns; } @override set returns(Reference returns) { _$this; super.returns = returns; } _$MethodBuilder() : super._(); MethodBuilder get _$this { if (_$v != null) { super.annotations = _$v.annotations?.toBuilder(); super.docs = _$v.docs?.toBuilder(); super.types = _$v.types?.toBuilder(); super.optionalParameters = _$v.optionalParameters?.toBuilder(); super.requiredParameters = _$v.requiredParameters?.toBuilder(); super.body = _$v.body; super.external = _$v.external; super.lambda = _$v.lambda; super.static = _$v.static; super.name = _$v.name; super.type = _$v.type; super.modifier = _$v.modifier; super.returns = _$v.returns; _$v = null; } return this; } @override void replace(Method other) { if (other == null) throw new ArgumentError.notNull('other'); _$v = other as _$Method; } @override void update(void updates(MethodBuilder b)) { if (updates != null) updates(this); } @override _$Method build() { _$Method _$result; try { _$result = _$v ?? new _$Method._( annotations: annotations.build(), docs: docs.build(), types: types.build(), optionalParameters: optionalParameters.build(), requiredParameters: requiredParameters.build(), body: body, external: external, lambda: lambda, static: static, name: name, type: type, modifier: modifier, returns: returns); } catch (_) { String _$failedField; try { _$failedField = 'annotations'; annotations.build(); _$failedField = 'docs'; docs.build(); _$failedField = 'types'; types.build(); _$failedField = 'optionalParameters'; optionalParameters.build(); _$failedField = 'requiredParameters'; requiredParameters.build(); } catch (e) { throw new BuiltValueNestedFieldError( 'Method', _$failedField, e.toString()); } rethrow; } replace(_$result); return _$result; } } class _$Parameter extends Parameter { @override final Code defaultTo; @override final String name; @override final bool named; @override final bool toThis; @override final BuiltList<Expression> annotations; @override final BuiltList<String> docs; @override final BuiltList<Reference> types; @override final Reference type; factory _$Parameter([void updates(ParameterBuilder b)]) => (new ParameterBuilder()..update(updates)).build() as _$Parameter; _$Parameter._( {this.defaultTo, this.name, this.named, this.toThis, this.annotations, this.docs, this.types, this.type}) : super._() { if (name == null) throw new BuiltValueNullFieldError('Parameter', 'name'); if (named == null) throw new BuiltValueNullFieldError('Parameter', 'named'); if (toThis == null) throw new BuiltValueNullFieldError('Parameter', 'toThis'); if (annotations == null) throw new BuiltValueNullFieldError('Parameter', 'annotations'); if (docs == null) throw new BuiltValueNullFieldError('Parameter', 'docs'); if (types == null) throw new BuiltValueNullFieldError('Parameter', 'types'); } @override Parameter rebuild(void updates(ParameterBuilder b)) => (toBuilder()..update(updates)).build(); @override _$ParameterBuilder toBuilder() => new _$ParameterBuilder()..replace(this); @override bool operator ==(dynamic other) { if (identical(other, this)) return true; if (other is! Parameter) return false; return defaultTo == other.defaultTo && name == other.name && named == other.named && toThis == other.toThis && annotations == other.annotations && docs == other.docs && types == other.types && type == other.type; } @override int get hashCode { return $jf($jc( $jc( $jc( $jc( $jc( $jc($jc($jc(0, defaultTo.hashCode), name.hashCode), named.hashCode), toThis.hashCode), annotations.hashCode), docs.hashCode), types.hashCode), type.hashCode)); } @override String toString() { return (newBuiltValueToStringHelper('Parameter') ..add('defaultTo', defaultTo) ..add('name', name) ..add('named', named) ..add('toThis', toThis) ..add('annotations', annotations) ..add('docs', docs) ..add('types', types) ..add('type', type)) .toString(); } } class _$ParameterBuilder extends ParameterBuilder { _$Parameter _$v; @override Code get defaultTo { _$this; return super.defaultTo; } @override set defaultTo(Code defaultTo) { _$this; super.defaultTo = defaultTo; } @override String get name { _$this; return super.name; } @override set name(String name) { _$this; super.name = name; } @override bool get named { _$this; return super.named; } @override set named(bool named) { _$this; super.named = named; } @override bool get toThis { _$this; return super.toThis; } @override set toThis(bool toThis) { _$this; super.toThis = toThis; } @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 ListBuilder<Reference> get types { _$this; return super.types ??= new ListBuilder<Reference>(); } @override set types(ListBuilder<Reference> types) { _$this; super.types = types; } @override Reference get type { _$this; return super.type; } @override set type(Reference type) { _$this; super.type = type; } _$ParameterBuilder() : super._(); ParameterBuilder get _$this { if (_$v != null) { super.defaultTo = _$v.defaultTo; super.name = _$v.name; super.named = _$v.named; super.toThis = _$v.toThis; super.annotations = _$v.annotations?.toBuilder(); super.docs = _$v.docs?.toBuilder(); super.types = _$v.types?.toBuilder(); super.type = _$v.type; _$v = null; } return this; } @override void replace(Parameter other) { if (other == null) throw new ArgumentError.notNull('other'); _$v = other as _$Parameter; } @override void update(void updates(ParameterBuilder b)) { if (updates != null) updates(this); } @override _$Parameter build() { _$Parameter _$result; try { _$result = _$v ?? new _$Parameter._( defaultTo: defaultTo, name: name, named: named, toThis: toThis, annotations: annotations.build(), docs: docs.build(), types: types.build(), type: type); } catch (_) { String _$failedField; try { _$failedField = 'annotations'; annotations.build(); _$failedField = 'docs'; docs.build(); _$failedField = 'types'; types.build(); } catch (e) { throw new BuiltValueNestedFieldError( 'Parameter', _$failedField, e.toString()); } rethrow; } replace(_$result); return _$result; } }
code_builder/lib/src/specs/method.g.dart/0
{'file_path': 'code_builder/lib/src/specs/method.g.dart', 'repo_id': 'code_builder', 'token_count': 6621}
// Copyright (c) 2017, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:code_builder/code_builder.dart'; import 'package:test/test.dart'; import '../common.dart'; void main() { useDartfmt(); test('should create a method', () { expect( Method((b) => b..name = 'foo'), equalsDart(r''' foo(); '''), ); }); test('should create an async method', () { expect( Method((b) => b ..name = 'foo' ..modifier = MethodModifier.async ..body = literalNull.code), equalsDart(r''' foo() async => null '''), ); }); test('should create an async* method', () { expect( Method((b) => b ..name = 'foo' ..modifier = MethodModifier.asyncStar ..body = literalNull.code), equalsDart(r''' foo() async* => null '''), ); }); test('should create an sync* method', () { expect( Method((b) => b ..name = 'foo' ..modifier = MethodModifier.syncStar ..body = literalNull.code), equalsDart(r''' foo() sync* => null '''), ); }); test('should create a lambda method implicitly', () { expect( Method((b) => b ..name = 'returnsTrue' ..returns = refer('bool') ..body = literalTrue.code), equalsDart(r''' bool returnsTrue() => true '''), ); }); test('should create a normal method implicitly', () { expect( Method.returnsVoid((b) => b ..name = 'assignTrue' ..body = refer('topLevelFoo').assign(literalTrue).statement), equalsDart(r''' void assignTrue() { topLevelFoo = true; } '''), ); }); test('should create a getter', () { expect( Method((b) => b ..name = 'foo' ..external = true ..type = MethodType.getter), equalsDart(r''' external get foo; '''), ); }); test('should create a setter', () { expect( Method((b) => b ..name = 'foo' ..external = true ..requiredParameters.add((Parameter((b) => b..name = 'foo'))) ..type = MethodType.setter), equalsDart(r''' external set foo(foo); '''), ); }); test('should create a method with a return type', () { expect( Method((b) => b ..name = 'foo' ..returns = refer('String')), equalsDart(r''' String foo(); '''), ); }); test('should create a method with a void return type', () { expect( Method.returnsVoid((b) => b..name = 'foo'), equalsDart(r''' void foo(); '''), ); }); test('should create a method with a function type return type', () { expect( Method((b) => b ..name = 'foo' ..returns = FunctionType((b) => b ..returnType = refer('String') ..requiredParameters.addAll([ refer('int'), ]))), equalsDart(r''' String Function(int) foo(); '''), ); }); test('should create a method with a nested function type return type', () { expect( Method((b) => b ..name = 'foo' ..returns = FunctionType((b) => b ..returnType = FunctionType((b) => b ..returnType = refer('String') ..requiredParameters.add(refer('String'))) ..requiredParameters.addAll([ refer('int'), ]))), equalsDart(r''' String Function(String) Function(int) foo(); '''), ); }); test('should create a method with a function type argument', () { expect( Method((b) => b ..name = 'foo' ..requiredParameters.add(Parameter((b) => b ..type = FunctionType((b) => b ..returnType = refer('String') ..requiredParameters.add(refer('int'))) ..name = 'argument'))), equalsDart(r''' foo(String Function(int) argument); ''')); }); test('should create a method with a nested function type argument', () { expect( Method((b) => b ..name = 'foo' ..requiredParameters.add(Parameter((b) => b ..type = FunctionType((b) => b ..returnType = FunctionType((b) => b ..returnType = refer('String') ..requiredParameters.add(refer('String'))) ..requiredParameters.add(refer('int'))) ..name = 'argument'))), equalsDart(r''' foo(String Function(String) Function(int) argument); ''')); }); test('should create a method with generic types', () { expect( Method((b) => b ..name = 'foo' ..types.add(refer('T'))), equalsDart(r''' foo<T>(); '''), ); }); test('should create an external method', () { expect( Method((b) => b ..name = 'foo' ..external = true), equalsDart(r''' external foo(); '''), ); }); test('should create a method with a body', () { expect( Method((b) => b ..name = 'foo' ..body = const Code('return 1+ 2;')), equalsDart(r''' foo() { return 1 + 2; } '''), ); }); test('should create a lambda method (explicitly)', () { expect( Method((b) => b ..name = 'foo' ..lambda = true ..body = const Code('1 + 2')), equalsDart(r''' foo() => 1 + 2 '''), ); }); test('should create a method with a body with references', () { final $LinkedHashMap = refer('LinkedHashMap', 'dart:collection'); expect( Method((b) => b ..name = 'foo' ..body = Code.scope( (a) => 'return new ${a($LinkedHashMap)}();', )), equalsDart(r''' foo() { return new LinkedHashMap(); } '''), ); }); test('should create a method with a paremter', () { expect( Method( (b) => b ..name = 'fib' ..requiredParameters.add( Parameter((b) => b.name = 'i'), ), ), equalsDart(r''' fib(i); '''), ); }); test('should create a method with an annotated parameter', () { expect( Method( (b) => b ..name = 'fib' ..requiredParameters.add( Parameter((b) => b ..name = 'i' ..annotations.add(refer('deprecated'))), ), ), equalsDart(r''' fib(@deprecated i); '''), ); }); test('should create a method with a parameter with a type', () { expect( Method( (b) => b ..name = 'fib' ..requiredParameters.add( Parameter( (b) => b ..name = 'i' ..type = refer('int').type, ), ), ), equalsDart(r''' fib(int i); '''), ); }); test('should create a method with a parameter with a generic type', () { expect( Method( (b) => b ..name = 'foo' ..types.add(TypeReference((b) => b ..symbol = 'T' ..bound = refer('Iterable'))) ..requiredParameters.addAll([ Parameter( (b) => b ..name = 't' ..type = refer('T'), ), Parameter((b) => b ..name = 'x' ..type = TypeReference((b) => b ..symbol = 'X' ..types.add(refer('T')))), ]), ), equalsDart(r''' foo<T extends Iterable>(T t, X<T> x); '''), ); }); test('should create a method with an optional parameter', () { expect( Method( (b) => b ..name = 'fib' ..optionalParameters.add( Parameter((b) => b.name = 'i'), ), ), equalsDart(r''' fib([i]); '''), ); }); test('should create a method with multiple optional parameters', () { expect( Method( (b) => b ..name = 'foo' ..optionalParameters.addAll([ Parameter((b) => b.name = 'a'), Parameter((b) => b.name = 'b'), ]), ), equalsDart(r''' foo([a, b]); '''), ); }); test('should create a method with an optional parameter with a value', () { expect( Method( (b) => b ..name = 'fib' ..optionalParameters.add( Parameter((b) => b ..name = 'i' ..defaultTo = const Code('0')), ), ), equalsDart(r''' fib([i = 0]); '''), ); }); test('should create a method with a named optional parameter', () { expect( Method( (b) => b ..name = 'fib' ..optionalParameters.add( Parameter((b) => b ..named = true ..name = 'i'), ), ), equalsDart(r''' fib({i}); '''), ); }); test('should create a method with a named optional parameter with value', () { expect( Method( (b) => b ..name = 'fib' ..optionalParameters.add( Parameter((b) => b ..named = true ..name = 'i' ..defaultTo = const Code('0')), ), ), equalsDart(r''' fib({i: 0}); '''), ); }); test('should create a method with a mix of parameters', () { expect( Method( (b) => b ..name = 'foo' ..requiredParameters.add( Parameter((b) => b..name = 'a'), ) ..optionalParameters.add( Parameter((b) => b ..named = true ..name = 'b'), ), ), equalsDart(r''' foo(a, {b}); '''), ); }); }
code_builder/test/specs/method_test.dart/0
{'file_path': 'code_builder/test/specs/method_test.dart', 'repo_id': 'code_builder', 'token_count': 5049}
name: No Response # Both `issue_comment` and `scheduled` event types are required for this Action # to work properly. on: issue_comment: types: [created] schedule: # Schedule for five minutes after the hour, every hour - cron: '5 * * * *' # By specifying the access of one of the scopes, all of those that are not # specified are set to 'none'. permissions: issues: write jobs: noResponse: runs-on: ubuntu-latest steps: - uses: lee-dohm/no-response@9bb0a4b5e6a45046f00353d5de7d90fb8bd773bb with: token: ${{ github.token }} # Comment to post when closing an Issue for lack of response. Set to `false` to disable closeComment: > Without additional information we're not able to resolve this issue, so it will be closed at this time. You're still free to add more info and respond to any questions above, though. We'll reopen the case if you do. Thanks for your contribution! # Number of days of inactivity before an issue is closed for lack of response. daysUntilClose: 21 # Label requiring a response. responseRequiredLabel: "waiting for customer response"
codelabs/.github/workflows/no-response.yaml/0
{'file_path': 'codelabs/.github/workflows/no-response.yaml', 'repo_id': 'codelabs', 'token_count': 446}
// 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 '../models/models.dart'; class SearchBar extends StatelessWidget { const SearchBar({ super.key, required this.currentUser, }); final User currentUser; @override Widget build(BuildContext context) { return SizedBox( height: 56, child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.circular(100), color: Colors.white, ), padding: const EdgeInsets.fromLTRB(31, 12, 12, 12), child: Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ const Icon(Icons.search), const SizedBox(width: 23.5), Expanded( child: TextField( maxLines: 1, decoration: InputDecoration( isDense: true, border: InputBorder.none, hintText: 'Search replies', hintStyle: Theme.of(context).textTheme.bodyMedium, ), ), ), CircleAvatar( backgroundImage: AssetImage(currentUser.avatarUrl), ), ], ), ), ); } }
codelabs/animated-responsive-layout/step_04/lib/widgets/search_bar.dart/0
{'file_path': 'codelabs/animated-responsive-layout/step_04/lib/widgets/search_bar.dart', 'repo_id': 'codelabs', 'token_count': 661}
include: ../../analysis_options.yaml
codelabs/animated-responsive-layout/step_07/analysis_options.yaml/0
{'file_path': 'codelabs/animated-responsive-layout/step_07/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 12}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; class StarButton extends StatefulWidget { const StarButton({super.key}); @override State<StarButton> createState() => _StarButtonState(); } class _StarButtonState extends State<StarButton> { bool state = false; late final ColorScheme _colorScheme = Theme.of(context).colorScheme; Icon get icon { final IconData iconData = state ? Icons.star : Icons.star_outline; return Icon( iconData, color: Colors.grey, size: 20, ); } void _toggle() { setState(() { state = !state; }); } double get turns => state ? 1 : 0; @override Widget build(BuildContext context) { return AnimatedRotation( turns: turns, curve: Curves.decelerate, duration: const Duration(milliseconds: 300), child: FloatingActionButton( elevation: 0, shape: const CircleBorder(), backgroundColor: _colorScheme.surface, onPressed: () => _toggle(), child: Padding( padding: const EdgeInsets.all(10.0), child: icon, ), ), ); } }
codelabs/animated-responsive-layout/step_07/lib/widgets/star_button.dart/0
{'file_path': 'codelabs/animated-responsive-layout/step_07/lib/widgets/star_button.dart', 'repo_id': 'codelabs', 'token_count': 481}
// 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 '../animations.dart'; import '../destinations.dart'; import '../transitions/nav_rail_transition.dart'; import 'animated_floating_action_button.dart'; class DisappearingNavigationRail extends StatelessWidget { const DisappearingNavigationRail({ super.key, required this.railAnimation, required this.railFabAnimation, required this.backgroundColor, required this.selectedIndex, this.onDestinationSelected, }); final RailAnimation railAnimation; final RailFabAnimation railFabAnimation; final Color backgroundColor; final int selectedIndex; final ValueChanged<int>? onDestinationSelected; @override Widget build(BuildContext context) { return NavRailTransition( animation: railAnimation, backgroundColor: backgroundColor, child: NavigationRail( selectedIndex: selectedIndex, backgroundColor: backgroundColor, onDestinationSelected: onDestinationSelected, leading: Column( children: [ IconButton( onPressed: () {}, icon: const Icon(Icons.menu), ), const SizedBox(height: 8), AnimatedFloatingActionButton( animation: railFabAnimation, elevation: 0, onPressed: () {}, child: const Icon(Icons.add), ), ], ), groupAlignment: -0.85, destinations: destinations.map((d) { return NavigationRailDestination( icon: Icon(d.icon), label: Text(d.label), ); }).toList(), ), ); } }
codelabs/animated-responsive-layout/step_08/lib/widgets/disappearing_navigation_rail.dart/0
{'file_path': 'codelabs/animated-responsive-layout/step_08/lib/widgets/disappearing_navigation_rail.dart', 'repo_id': 'codelabs', 'token_count': 734}
// 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 'package:go_router/go_router.dart'; import '../../../shared/classes/playlist.dart'; import '../../../shared/extensions.dart'; import '../../../shared/views/clickable.dart'; import '../../../shared/views/image_clipper.dart'; import '../../../shared/views/outlined_card.dart'; class HomeRecent extends StatelessWidget { const HomeRecent( {super.key, required this.playlists, this.axis = Axis.horizontal}); final List<Playlist> playlists; final Axis axis; @override Widget build(BuildContext context) { if (axis == Axis.horizontal) { return SizedBox( height: 295, child: ListView.builder( scrollDirection: axis, padding: const EdgeInsets.only(left: 10), itemCount: playlists.length, itemBuilder: (context, index) { final playlist = playlists[index]; return Clickable( child: Padding( padding: const EdgeInsets.only(right: 25), child: OutlinedCard( child: SizedBox( width: 200, child: Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: [ Row( children: [ Expanded( child: Image.asset(playlist.cover.image, fit: BoxFit.cover), ), ], ), Padding( padding: const EdgeInsets.fromLTRB(5, 10, 5, 0), child: buildDetails(context, playlist), ), ], ), ), ), ), onTap: () => GoRouter.of(context).go('/playlists/${playlist.id}'), ); }, ), ); } return ListView.builder( scrollDirection: axis, itemCount: playlists.length, itemBuilder: (context, index) { final playlist = playlists[index]; return Padding( padding: const EdgeInsets.all(8.0), child: Clickable( onTap: () => GoRouter.of(context).go('/playlists/${playlist.id}'), child: SizedBox( height: 200, child: Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, mainAxisSize: MainAxisSize.max, children: [ ClippedImage( playlist.cover.image, height: 200, ), Expanded( child: Center( child: Padding( padding: const EdgeInsets.all(20), child: buildDetails(context, playlist), ), ), ), ], ), ), ), ); }, ); } Widget buildDetails(BuildContext context, Playlist playlist) { return Column( children: [ Padding( padding: const EdgeInsets.fromLTRB(10, 5, 10, 5), child: Text( playlist.title, style: context.titleSmall!.copyWith( fontWeight: FontWeight.bold, ), overflow: TextOverflow.ellipsis, maxLines: 1, textAlign: TextAlign.center, )), Padding( padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 10), child: Text(playlist.description, overflow: TextOverflow.ellipsis, style: context.labelSmall, maxLines: 2, textAlign: TextAlign.center), ), ], ); } }
codelabs/boring_to_beautiful/final/lib/src/features/home/view/home_recent.dart/0
{'file_path': 'codelabs/boring_to_beautiful/final/lib/src/features/home/view/home_recent.dart', 'repo_id': 'codelabs', 'token_count': 2352}
// 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 './classes.dart'; class Song { final Artist artist; final String title; final Duration length; final MyArtistImage image; const Song(this.title, this.artist, this.length, this.image); }
codelabs/boring_to_beautiful/final/lib/src/shared/classes/song.dart/0
{'file_path': 'codelabs/boring_to_beautiful/final/lib/src/shared/classes/song.dart', 'repo_id': 'codelabs', 'token_count': 105}
// 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'; class ArticleContent extends StatelessWidget { const ArticleContent({ super.key, required this.child, this.maxWidth = 960, }); final double maxWidth; final Widget child; @override Widget build(BuildContext context) { return Container( alignment: Alignment.topCenter, child: ConstrainedBox( constraints: BoxConstraints( maxWidth: maxWidth, ), child: Padding( padding: const EdgeInsets.all(15), child: child, ), ), ); } }
codelabs/boring_to_beautiful/final/lib/src/shared/views/article_content.dart/0
{'file_path': 'codelabs/boring_to_beautiful/final/lib/src/shared/views/article_content.dart', 'repo_id': 'codelabs', 'token_count': 280}
// 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 'package:flutter_bloc/flutter_bloc.dart'; import '../../../shared/classes/classes.dart'; import '../../../shared/extensions.dart'; import '../../../shared/playback/bloc/bloc.dart'; import '../../../shared/views/image_clipper.dart'; import '../../../shared/views/views.dart'; class ArtistRankedSongs extends StatelessWidget { const ArtistRankedSongs({super.key, required this.artist}); final Artist artist; @override Widget build(BuildContext context) { return AdaptiveTable<RankedSong>( items: artist.songs, breakpoint: 450, itemBuilder: (song, index) { return ListTile( leading: ClippedImage(song.image.image), title: Text(song.title), subtitle: Text(song.length.toHumanizedString()), trailing: Text(song.ranking.toString()), onTap: () => BlocProvider.of<PlaybackBloc>(context).add( PlaybackEvent.changeSong(song), ), ); }, columns: const [ DataColumn( label: Text( 'Ranking', ), numeric: true, ), DataColumn( label: Text( 'Title', ), ), DataColumn( label: Text( 'Length', ), ), ], rowBuilder: (song, index) => DataRow.byIndex(index: index, cells: [ DataCell( HoverableSongPlayButton( song: song, child: Center( child: Text(song.ranking.toString()), ), ), ), DataCell( Row(children: [ Padding( padding: const EdgeInsets.all(2), child: ClippedImage(song.image.image), ), const SizedBox(width: 5.0), Expanded(child: Text(song.title)), ]), ), DataCell( Text(song.length.toHumanizedString()), ), ]), ); } }
codelabs/boring_to_beautiful/step_01/lib/src/features/artists/view/artist_ranked_songs.dart/0
{'file_path': 'codelabs/boring_to_beautiful/step_01/lib/src/features/artists/view/artist_ranked_songs.dart', 'repo_id': 'codelabs', 'token_count': 1026}
// 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:dynamic_color/dynamic_color.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'playback/bloc/bloc.dart'; import 'providers/theme.dart'; import 'router.dart'; import 'views/views.dart'; class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { final settings = ValueNotifier(ThemeSettings( sourceColor: Colors.pink, // Replace this color themeMode: ThemeMode.system, )); @override Widget build(BuildContext context) { return BlocProvider<PlaybackBloc>( create: (context) => PlaybackBloc(), child: DynamicColorBuilder( builder: (lightDynamic, darkDynamic) => ThemeProvider( lightDynamic: lightDynamic, darkDynamic: darkDynamic, settings: settings, child: NotificationListener<ThemeSettingChange>( onNotification: (notification) { settings.value = notification.settings; return true; }, child: ValueListenableBuilder<ThemeSettings>( valueListenable: settings, builder: (context, value, _) { // Create theme instance return MaterialApp.router( debugShowCheckedModeBanner: false, title: 'Flutter Demo', // Add theme // Add dark theme // Add theme mode routeInformationParser: appRouter.routeInformationParser, routeInformationProvider: appRouter.routeInformationProvider, routerDelegate: appRouter.routerDelegate, builder: (context, child) { return PlayPauseListener(child: child!); }, ); }, ), )), ), ); } }
codelabs/boring_to_beautiful/step_01/lib/src/shared/app.dart/0
{'file_path': 'codelabs/boring_to_beautiful/step_01/lib/src/shared/app.dart', 'repo_id': 'codelabs', 'token_count': 1004}
// 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:math'; import 'package:collection/collection.dart'; import 'package:english_words/english_words.dart'; import '../classes/classes.dart'; import '../extensions.dart'; import 'providers.dart'; class PlaylistsProvider { List<Playlist> get playlists => _randomPlaylists; Playlist get newReleases => randomPlaylist(numSongs: 10); Playlist get topSongs => randomPlaylist(numSongs: 10); static List<MyArtistImage> images() { return [ const MyArtistImage( image: 'assets/images/playlists/favorite.jpg', sourceLink: 'https://unsplash.com/photos/60GsdOMRFGc', sourceName: 'Karsten Winegeart'), const MyArtistImage( image: 'assets/images/playlists/austin.jpg', sourceLink: 'https://unsplash.com/photos/AlBgcDfDG_s', sourceName: 'Carlos Alfonso'), const MyArtistImage( image: 'assets/images/playlists/reading.jpg', sourceLink: 'https://unsplash.com/photos/wkgv7I2VTzM', sourceName: 'Alexandra Fuller'), const MyArtistImage( image: 'assets/images/playlists/workout.jpg', sourceLink: 'https://unsplash.com/photos/CnEEF5eJemQ', sourceName: 'Karsten Winegeart'), const MyArtistImage( image: 'assets/images/playlists/calm.jpg', sourceLink: 'https://unsplash.com/photos/NTyBbu66_SI', sourceName: 'Jared Rice'), const MyArtistImage( image: 'assets/images/playlists/coffee.jpg', sourceLink: 'https://unsplash.com/photos/XOhI_kW_TaM', sourceName: 'Nathan Dumlao'), const MyArtistImage( image: 'assets/images/playlists/piano.jpg', sourceLink: 'https://unsplash.com/photos/BhfE1IgcsA8', sourceName: 'Jordan Whitfield'), const MyArtistImage( image: 'assets/images/playlists/studying.jpg', sourceLink: 'https://unsplash.com/photos/-moT-Deiw1M', sourceName: 'Humble Lamb'), const MyArtistImage( image: 'assets/images/playlists/jazz.jpg', sourceLink: 'https://unsplash.com/photos/BY_KyTwTKq4', sourceName: 'dimitri.photography'), ]; } Playlist? getPlaylist(String id) { return playlists.firstWhereOrNull((playlist) => playlist.id == id); } static Playlist randomPlaylist({int numSongs = 15}) { return Playlist( id: randomId(), title: generateRandomString(max(2, Random().nextInt(4))), description: generateRandomString(Random().nextInt(25)), songs: List.generate(numSongs, (index) => randomSong()), cover: images()[Random().nextInt(images().length - 1)], ); } static Playlist randomLengthPlaylist({int maxSongs = 15}) { final int songCount = Random().nextInt(maxSongs) + 1; return PlaylistsProvider.randomPlaylist(numSongs: songCount); } static Song randomSong() { return Song( generateRandomString(2), ArtistsProvider.shared.randomArtist, generateRandomSongLength(), images()[Random().nextInt(images().length)], ); } static final List<Playlist> _randomPlaylists = List.generate(10, (index) => randomLengthPlaylist()); } String randomId() { return Random().nextInt(1000000).toString(); } String generateRandomString(int wordCount) { final randomWords = generateWordPairs().take((wordCount).floor()); return randomWords.join(' '); } Duration generateRandomSongLength() { Random rand = Random(); int minute = rand.nextInt(5); int second = rand.nextInt(60); String secondStr = second.toString(); if (second < 10) { secondStr = secondStr.padLeft(2, '0'); } return '$minute : $secondStr'.toDuration(); }
codelabs/boring_to_beautiful/step_01/lib/src/shared/providers/playlists.dart/0
{'file_path': 'codelabs/boring_to_beautiful/step_01/lib/src/shared/providers/playlists.dart', 'repo_id': 'codelabs', 'token_count': 1505}
// 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 '../../shared/extensions.dart'; import 'outlined_card.dart'; class ImageCard extends StatelessWidget { const ImageCard( {super.key, required this.title, required this.details, required this.image, this.subtitle, this.clickable = false}); final String title; final String? subtitle; final String details; final String image; final bool clickable; @override Widget build(BuildContext context) { const padding = EdgeInsets.all(8.0); return OutlinedCard( clickable: clickable, child: Padding( padding: const EdgeInsets.all(8.0), child: LayoutBuilder(builder: (context, constraints) { return Row( children: [ if (constraints.maxWidth > 600) SizedBox( width: 170, height: 170, child: Image.asset( image, fit: BoxFit.cover, ), ), Expanded( child: Padding( padding: padding, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Padding( padding: const EdgeInsets.only(bottom: 5), child: Text( title, style: context.titleLarge! .copyWith(fontWeight: FontWeight.bold), ), ), if (subtitle != null) Padding( padding: const EdgeInsets.only(bottom: 10), child: Text( subtitle!, style: context.labelMedium, ), ), Text( details, style: context.labelMedium?.copyWith( fontSize: 16, height: 1.25, ), ), ], ), ), ), ], ); }), ), ); } }
codelabs/boring_to_beautiful/step_01/lib/src/shared/views/image_card.dart/0
{'file_path': 'codelabs/boring_to_beautiful/step_01/lib/src/shared/views/image_card.dart', 'repo_id': 'codelabs', 'token_count': 1470}
import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:flutter/material.dart'; import '../brick_breaker.dart'; import 'play_area.dart'; class Ball extends CircleComponent with CollisionCallbacks, HasGameReference<BrickBreaker> { 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, children: [CircleHitbox()]); final Vector2 velocity; @override void update(double dt) { super.update(dt); position += velocity * dt; } @override void onCollisionStart( Set<Vector2> intersectionPoints, PositionComponent other) { super.onCollisionStart(intersectionPoints, other); if (other is PlayArea) { if (intersectionPoints.first.y <= 0) { velocity.y = -velocity.y; } else if (intersectionPoints.first.x <= 0) { velocity.x = -velocity.x; } else if (intersectionPoints.first.x >= game.width) { velocity.x = -velocity.x; } else if (intersectionPoints.first.y >= game.height) { removeFromParent(); } } else { debugPrint('collision with $other'); } } }
codelabs/brick_breaker/step_06/lib/src/components/ball.dart/0
{'file_path': 'codelabs/brick_breaker/step_06/lib/src/components/ball.dart', 'repo_id': 'codelabs', 'token_count': 545}
import 'package:flame/collisions.dart'; import 'package:flame/components.dart'; import 'package:flame/effects.dart'; import 'package:flame/events.dart'; import 'package:flutter/material.dart'; import '../brick_breaker.dart'; class Bat extends PositionComponent with DragCallbacks, HasGameReference<BrickBreaker> { Bat({ required this.cornerRadius, required super.position, required super.size, }) : super( anchor: Anchor.center, children: [RectangleHitbox()], ); final Radius cornerRadius; final _paint = Paint() ..color = const Color(0xff1e6091) ..style = PaintingStyle.fill; @override void render(Canvas canvas) { super.render(canvas); canvas.drawRRect( RRect.fromRectAndRadius( Offset.zero & size.toSize(), cornerRadius, ), _paint); } @override void onDragUpdate(DragUpdateEvent event) { super.onDragUpdate(event); position.x = (position.x + event.localDelta.x) .clamp(width / 2, game.width - width / 2); } void moveBy(double dx) { add(MoveToEffect( Vector2( (position.x + dx).clamp(width / 2, game.width - width / 2), position.y, ), EffectController(duration: 0.1), )); } }
codelabs/brick_breaker/step_09/lib/src/components/bat.dart/0
{'file_path': 'codelabs/brick_breaker/step_09/lib/src/components/bat.dart', 'repo_id': 'codelabs', 'token_count': 524}
// Copyright 2023 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'dart:convert'; class Document { final Map<String, Object?> _json; Document() : _json = jsonDecode(documentJson); (String, {DateTime modified}) get metadata { if (_json case { 'metadata': { 'title': String title, 'modified': String localModified, } }) { return (title, modified: DateTime.parse(localModified)); } else { throw const FormatException('Unexpected JSON'); } } } const documentJson = ''' { "metadata": { "title": "My Document", "modified": "2023-05-10" }, "blocks": [ { "type": "h1", "text": "Chapter 1" }, { "type": "p", "text": "Lorem ipsum dolor sit amet, consectetur adipiscing elit." }, { "type": "checkbox", "checked": false, "text": "Learn Dart 3" } ] } ''';
codelabs/dart-patterns-and-records/step_07_b/lib/data.dart/0
{'file_path': 'codelabs/dart-patterns-and-records/step_07_b/lib/data.dart', 'repo_id': 'codelabs', 'token_count': 439}
// ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: Scaffold( body: Center( child: CustomButton( color: Colors.cyan, child: Text("Button 1"), onTap: () => print('Button 1: Handle Tap/Click'), onLongPress: () => print('Button 1: Handle LongPress'), ), ), ), ), ); } // CustomButton converted into a StatefulWidget class CustomButton extends StatefulWidget { const CustomButton({ super.key, required this.child, required this.onTap, required this.onLongPress, this.color = Colors.blue, }); final Color color; final Widget child; final VoidCallback onTap; final VoidCallback onLongPress; @override State<CustomButton> createState() => _CustomButtonState(); } class _CustomButtonState extends State<CustomButton> { // Variable to keep track of whether the user is hovering over the button or // not. Use this information to update the background color. bool _hovering = false; @override Widget build(BuildContext context) { // Use the MouseRegion to set the cursor return MouseRegion( cursor: SystemMouseCursors.click, // Update the _hovering instance variable when a user starts and stops // hovering over the button onEnter: (_) => setState(() => _hovering = true), onExit: (_) => setState(() => _hovering = false), child: GestureDetector( onTap: widget.onTap, onLongPress: widget.onLongPress, child: Container( padding: EdgeInsets.all(10), decoration: BoxDecoration( // If the user is hovering over the button, change the background // color! color: _hovering ? widget.color.withOpacity(0.8) : widget.color, borderRadius: BorderRadius.circular(10), ), child: widget.child, ), ), ); } }
codelabs/dartpad_codelabs/src/custom_button/step_05/solution.dart/0
{'file_path': 'codelabs/dartpad_codelabs/src/custom_button/step_05/solution.dart', 'repo_id': 'codelabs', 'token_count': 777}
import 'package:flutter/material.dart'; final GlobalKey<ShoppingCartIconState> shoppingCart = GlobalKey<ShoppingCartIconState>(); final GlobalKey<ProductListWidgetState> productList = GlobalKey<ProductListWidgetState>(); void main() { runApp( const AppStateWidget( child: MaterialApp( debugShowCheckedModeBanner: false, title: 'Store', home: MyStorePage(), ), ), ); } class AppState { AppState({ required this.productList, this.itemsInCart = const <String>{}, }); final List<String> productList; final Set<String> itemsInCart; AppState copyWith({ List<String>? productList, Set<String>? itemsInCart, }) { return AppState( productList: productList ?? this.productList, itemsInCart: itemsInCart ?? this.itemsInCart, ); } } class AppStateScope extends InheritedWidget { const AppStateScope(this.data, {super.key, required super.child}); final AppState data; static AppState of(BuildContext context) { return context.dependOnInheritedWidgetOfExactType<AppStateScope>()!.data; } @override bool updateShouldNotify(AppStateScope oldWidget) { return data != oldWidget.data; } } class AppStateWidget extends StatefulWidget { const AppStateWidget({required this.child, super.key}); final Widget child; static AppStateWidgetState of(BuildContext context) { return context.findAncestorStateOfType<AppStateWidgetState>()!; } @override AppStateWidgetState createState() => AppStateWidgetState(); } class AppStateWidgetState extends State<AppStateWidget> { AppState _data = AppState( productList: Server.getProductList(), ); void setProductList(List<String> newProductList) { if (newProductList != _data.productList) { setState(() { _data = _data.copyWith( productList: newProductList, ); }); } } void addToCart(String id) { if (!_data.itemsInCart.contains(id)) { final Set<String> newItemsInCart = Set<String>.from(_data.itemsInCart); newItemsInCart.add(id); setState(() { _data = _data.copyWith( itemsInCart: newItemsInCart, ); }); } } void removeFromCart(String id) { if (_data.itemsInCart.contains(id)) { final Set<String> newItemsInCart = Set<String>.from(_data.itemsInCart); newItemsInCart.remove(id); setState(() { _data = _data.copyWith( itemsInCart: newItemsInCart, ); }); } } @override Widget build(BuildContext context) { return AppStateScope( _data, child: widget.child, ); } } class MyStorePage extends StatefulWidget { const MyStorePage({super.key}); @override MyStorePageState createState() => MyStorePageState(); } class MyStorePageState extends State<MyStorePage> { bool _inSearch = false; final TextEditingController _controller = TextEditingController(); final FocusNode _focusNode = FocusNode(); void _toggleSearch() { setState(() { _inSearch = !_inSearch; }); _controller.clear(); productList.currentState!.productList = Server.getProductList(); } void _handleSearch() { _focusNode.unfocus(); final String filter = _controller.text; productList.currentState!.productList = Server.getProductList(filter: filter); } @override Widget build(BuildContext context) { return Scaffold( body: CustomScrollView( slivers: [ SliverAppBar( leading: Padding( padding: const EdgeInsets.all(16.0), child: Image.network('$baseAssetURL/google-logo.png'), ), title: _inSearch ? TextField( autofocus: true, focusNode: _focusNode, controller: _controller, onSubmitted: (_) => _handleSearch(), decoration: InputDecoration( hintText: 'Search Google Store', prefixIcon: IconButton( icon: const Icon(Icons.search), onPressed: _handleSearch, ), suffixIcon: IconButton( icon: const Icon(Icons.close), onPressed: _toggleSearch, ), ), ) : null, actions: [ if (!_inSearch) IconButton( onPressed: _toggleSearch, icon: const Icon(Icons.search, color: Colors.black), ), ShoppingCartIcon(key: shoppingCart), ], backgroundColor: Colors.white, pinned: true, ), SliverToBoxAdapter( child: ProductListWidget(key: productList), ), ], ), ); } } class ShoppingCartIcon extends StatefulWidget { const ShoppingCartIcon({super.key}); @override ShoppingCartIconState createState() => ShoppingCartIconState(); } class ShoppingCartIconState extends State<ShoppingCartIcon> { Set<String> get itemsInCart => _itemsInCart; Set<String> _itemsInCart = <String>{}; set itemsInCart(Set<String> value) { setState(() { _itemsInCart = value; }); } @override Widget build(BuildContext context) { final bool hasPurchase = itemsInCart.isNotEmpty; return Stack( alignment: Alignment.center, children: [ Padding( padding: EdgeInsets.only(right: hasPurchase ? 17.0 : 10.0), child: const Icon( Icons.shopping_cart, color: Colors.black, ), ), if (hasPurchase) Padding( padding: const EdgeInsets.only(left: 17.0), child: CircleAvatar( radius: 8.0, backgroundColor: Colors.lightBlue, foregroundColor: Colors.white, child: Text( itemsInCart.length.toString(), style: const TextStyle( fontWeight: FontWeight.bold, fontSize: 12.0, ), ), ), ), ], ); } } class ProductListWidget extends StatefulWidget { const ProductListWidget({super.key}); @override ProductListWidgetState createState() => ProductListWidgetState(); } class ProductListWidgetState extends State<ProductListWidget> { List<String> get productList => _productList; List<String> _productList = Server.getProductList(); set productList(List<String> value) { setState(() { _productList = value; }); } Set<String> get itemsInCart => _itemsInCart; Set<String> _itemsInCart = <String>{}; set itemsInCart(Set<String> value) { setState(() { _itemsInCart = value; }); } void _handleAddToCart(String id) { itemsInCart = _itemsInCart..add(id); shoppingCart.currentState!.itemsInCart = itemsInCart; } void _handleRemoveFromCart(String id) { itemsInCart = _itemsInCart..remove(id); shoppingCart.currentState!.itemsInCart = itemsInCart; } Widget _buildProductTile(String id) { return ProductTile( product: Server.getProductById(id), purchased: itemsInCart.contains(id), onAddToCart: () => _handleAddToCart(id), onRemoveFromCart: () => _handleRemoveFromCart(id), ); } @override Widget build(BuildContext context) { return Column( children: productList.map(_buildProductTile).toList(), ); } } class ProductTile extends StatelessWidget { const ProductTile({ super.key, required this.product, required this.purchased, required this.onAddToCart, required this.onRemoveFromCart, }); final Product product; final bool purchased; final VoidCallback onAddToCart; final VoidCallback onRemoveFromCart; @override Widget build(BuildContext context) { Color getButtonColor(Set<MaterialState> states) { return purchased ? Colors.grey : Colors.black; } BorderSide getButtonSide(Set<MaterialState> states) { return BorderSide( color: purchased ? Colors.grey : Colors.black, ); } return Container( margin: const EdgeInsets.symmetric( vertical: 15, horizontal: 40, ), color: const Color(0xfff8f8f8), child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Padding( padding: const EdgeInsets.all(20), child: Text(product.title), ), Text.rich( product.description, textAlign: TextAlign.center, style: const TextStyle( fontSize: 20, fontWeight: FontWeight.bold, ), ), Padding( padding: const EdgeInsets.all(20), child: OutlinedButton( style: ButtonStyle( foregroundColor: MaterialStateProperty.resolveWith(getButtonColor), side: MaterialStateProperty.resolveWith(getButtonSide), ), onPressed: purchased ? onRemoveFromCart : onAddToCart, child: purchased ? const Text('Remove from cart') : const Text('Add to cart'), ), ), Image.network(product.pictureURL), ], ), ); } } // The code below is for the dummy server, and you should not need to modify it // in this workshop. const String baseAssetURL = 'https://dartpad-workshops-io2021.web.app/inherited_widget/assets'; const Map<String, Product> kDummyData = { '0': Product( id: '0', title: 'Explore Pixel phones', description: TextSpan(children: <TextSpan>[ TextSpan( text: 'Capture the details.\n', style: TextStyle(color: Colors.black), ), TextSpan( text: 'Capture your world.', style: TextStyle(color: Colors.blue), ), ]), pictureURL: '$baseAssetURL/pixels.png', ), '1': Product( id: '1', title: 'Nest Audio', description: TextSpan(children: <TextSpan>[ TextSpan(text: 'Amazing sound.\n', style: TextStyle(color: Colors.green)), TextSpan(text: 'At your command.', style: TextStyle(color: Colors.black)), ]), pictureURL: '$baseAssetURL/nest.png', ), '2': Product( id: '2', title: 'Nest Audio Entertainment packages', description: TextSpan(children: <TextSpan>[ TextSpan( text: 'Built for music.\n', style: TextStyle(color: Colors.orange), ), TextSpan( text: 'Made for you.', style: TextStyle(color: Colors.black), ), ]), pictureURL: '$baseAssetURL/nest-audio-packages.png', ), '3': Product( id: '3', title: 'Nest Home Security packages', description: TextSpan(children: <TextSpan>[ TextSpan(text: 'Your home,\n', style: TextStyle(color: Colors.black)), TextSpan(text: 'safe and sound.', style: TextStyle(color: Colors.red)), ]), pictureURL: '$baseAssetURL/nest-home-packages.png', ), }; class Server { static Product getProductById(String id) { return kDummyData[id]!; } static List<String> getProductList({String? filter}) { if (filter == null) return kDummyData.keys.toList(); final List<String> ids = <String>[]; for (final Product product in kDummyData.values) { if (product.title.toLowerCase().contains(filter.toLowerCase())) { ids.add(product.id); } } return ids; } } class Product { const Product({ required this.id, required this.pictureURL, required this.title, required this.description, }); final String id; final String pictureURL; final String title; final TextSpan description; }
codelabs/dartpad_codelabs/src/inherited_widget/step_04/solution.dart/0
{'file_path': 'codelabs/dartpad_codelabs/src/inherited_widget/step_04/solution.dart', 'repo_id': 'codelabs', 'token_count': 5115}
// ignore_for_file: prefer_const_constructors, use_key_in_widget_constructors import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: Scaffold( body: ListView.separated( itemCount: 500, padding: EdgeInsets.all(10), // Use the ListItem widget in place of Column code. itemBuilder: (context, index) => ListItem(index: index), separatorBuilder: (context, index) => SizedBox(height: 10), ), ), ), ); } // A reusable widget that contains all of the code to lay out each item. class ListItem extends StatelessWidget { const ListItem({ super.key, // Accept the index as part of the constructor required this.index, }); // Use an instance variable to store the index final int index; @override Widget build(BuildContext context) { // Move the Column code from the itemBuilder function into this build method return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ // Use the stored index to display the correct Text widget Text( 'Item $index', style: TextStyle(fontWeight: FontWeight.bold), ), Text('Subtitle', style: TextStyle(color: Colors.grey)) ], ); } }
codelabs/dartpad_codelabs/src/introduction_to_lists/extract_widget/solution.dart/0
{'file_path': 'codelabs/dartpad_codelabs/src/introduction_to_lists/extract_widget/solution.dart', 'repo_id': 'codelabs', 'token_count': 491}
name: Lists of Content type: flutter # Optional steps: - name: ListView directory: list_view has_solution: true - name: Long Lists directory: long_lists has_solution: true - name: Separators directory: separators has_solution: true - name: Extract Widget directory: extract_widget has_solution: true - name: Material Widgets directory: material_widgets has_solution: true - name: GridView directory: grid_view has_solution: true - name: Long GridViews directory: long_grid_view has_solution: true - name: Conclusion directory: conclusion has_solution: false
codelabs/dartpad_codelabs/src/introduction_to_lists/meta.yaml/0
{'file_path': 'codelabs/dartpad_codelabs/src/introduction_to_lists/meta.yaml', 'repo_id': 'codelabs', 'token_count': 227}
// ignore_for_file: prefer_const_constructors, use_key_in_widget_constructors import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( home: Scaffold( body: DecoratedBox( decoration: BoxDecoration(color: Colors.grey), child: Row( children: [ BlueBox(), Expanded(child: BlueBox()), Expanded(child: BlueBox()), ], ), ), ), ), ); } class BlueBox extends StatelessWidget { @override Widget build(BuildContext context) { return SizedBox( width: 100, height: 100, child: DecoratedBox( decoration: BoxDecoration( color: Colors.blue, border: Border.all(), ), ), ); } }
codelabs/dartpad_codelabs/src/layouts/expanded/solution.dart/0
{'file_path': 'codelabs/dartpad_codelabs/src/layouts/expanded/solution.dart', 'repo_id': 'codelabs', 'token_count': 387}
int addThreeValues({ required int first, required int second, required int third, }) { return first + second + third; } void main() { final sum = addThreeValues( first: 2, second: 5, third: 3, ); print(sum); }
codelabs/dartpad_codelabs/src/null_safety_workshop/step_05/solution.dart/0
{'file_path': 'codelabs/dartpad_codelabs/src/null_safety_workshop/step_05/solution.dart', 'repo_id': 'codelabs', 'token_count': 88}
name: ffigen_app description: "A new Flutter FFI plugin project." version: 0.0.1 homepage: environment: sdk: '>=3.2.3 <4.0.0' flutter: '>=3.3.0' dependencies: ffi: ^2.1.0 flutter: sdk: flutter path: ^1.8.3 plugin_platform_interface: ^2.0.2 dev_dependencies: ffigen: ^11.0.0 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. # # Please refer to README.md for a detailed explanation. plugin: platforms: android: ffiPlugin: true ios: ffiPlugin: true linux: ffiPlugin: true macos: ffiPlugin: true windows: ffiPlugin: true # 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/ffigen_codelab/step_07/pubspec.yaml/0
{'file_path': 'codelabs/ffigen_codelab/step_07/pubspec.yaml', 'repo_id': 'codelabs', 'token_count': 921}
import 'package:firebase_ui_auth/firebase_ui_auth.dart'; import 'package:flutter/material.dart'; class HomeScreen extends StatelessWidget { const HomeScreen({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( actions: [ IconButton( icon: const Icon(Icons.person), onPressed: () { Navigator.push( context, MaterialPageRoute<ProfileScreen>( builder: (context) => ProfileScreen( appBar: AppBar( title: const Text('User Profile'), ), actions: [ SignedOutAction((context) { Navigator.of(context).pop(); }) ], children: [ const Divider(), Padding( padding: const EdgeInsets.all(2), child: AspectRatio( aspectRatio: 1, child: Image.asset('flutterfire_300x.png'), ), ), ], ), ), ); }, ) ], automaticallyImplyLeading: false, ), body: Center( child: Column( children: [ Image.asset('dash.png'), Text( 'Welcome!', style: Theme.of(context).textTheme.displaySmall, ), const SignOutButton(), ], ), ), ); } }
codelabs/firebase-auth-flutterfire-ui/complete/lib/home.dart/0
{'file_path': 'codelabs/firebase-auth-flutterfire-ui/complete/lib/home.dart', 'repo_id': 'codelabs', 'token_count': 1022}
name: complete description: "A new Flutter project." publish_to: 'none' version: 0.1.0 environment: sdk: '>=3.2.3 <4.0.0' dependencies: firebase_auth: ^4.16.0 firebase_core: ^2.24.2 firebase_ui_auth: ^1.12.0 firebase_ui_oauth_google: ^1.2.16 flutter: sdk: flutter google_sign_in: ^6.2.1 dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^3.0.1 flutter: uses-material-design: true assets: - assets/
codelabs/firebase-auth-flutterfire-ui/complete/pubspec.yaml/0
{'file_path': 'codelabs/firebase-auth-flutterfire-ui/complete/pubspec.yaml', 'repo_id': 'codelabs', 'token_count': 207}
import 'package:flutter/material.dart'; import 'app.dart'; // TODO(codelab user): Get API key const clientId = 'YOUR_CLIENT_ID'; void main() async { runApp(const MyApp()); }
codelabs/firebase-auth-flutterfire-ui/start/lib/main.dart/0
{'file_path': 'codelabs/firebase-auth-flutterfire-ui/start/lib/main.dart', 'repo_id': 'codelabs', 'token_count': 68}
include: ../../analysis_options.yaml
codelabs/firebase-get-to-know-flutter/step_02/analysis_options.yaml/0
{'file_path': 'codelabs/firebase-get-to-know-flutter/step_02/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 12}
// Copyright 2022 The Flutter Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import 'package:flutter/material.dart'; class Header extends StatelessWidget { const Header(this.heading, {super.key}); final String heading; @override Widget build(BuildContext context) => Padding( padding: const EdgeInsets.all(8.0), child: Text( heading, style: const TextStyle(fontSize: 24), ), ); } class Paragraph extends StatelessWidget { const Paragraph(this.content, {super.key}); final String content; @override Widget build(BuildContext context) => Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), child: Text( content, style: const TextStyle(fontSize: 18), ), ); } class IconAndDetail extends StatelessWidget { const IconAndDetail(this.icon, this.detail, {super.key}); final IconData icon; final String detail; @override Widget build(BuildContext context) => Padding( padding: const EdgeInsets.all(8.0), child: Row( children: [ Icon(icon), const SizedBox(width: 8), Text( detail, style: const TextStyle(fontSize: 18), ) ], ), ); } class StyledButton extends StatelessWidget { const StyledButton({required this.child, required this.onPressed, super.key}); final Widget child; final void Function() onPressed; @override Widget build(BuildContext context) => OutlinedButton( style: OutlinedButton.styleFrom( side: const BorderSide(color: Colors.deepPurple)), onPressed: onPressed, child: child, ); }
codelabs/firebase-get-to-know-flutter/step_02/lib/src/widgets.dart/0
{'file_path': 'codelabs/firebase-get-to-know-flutter/step_02/lib/src/widgets.dart', 'repo_id': 'codelabs', 'token_count': 724}
// 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:firebase_auth/firebase_auth.dart' hide EmailAuthProvider, PhoneAuthProvider; import 'package:firebase_core/firebase_core.dart'; import 'package:firebase_ui_auth/firebase_ui_auth.dart'; import 'package:flutter/material.dart'; import 'firebase_options.dart'; class ApplicationState extends ChangeNotifier { ApplicationState() { init(); } bool _loggedIn = false; bool get loggedIn => _loggedIn; Future<void> init() async { await Firebase.initializeApp( options: DefaultFirebaseOptions.currentPlatform); FirebaseUIAuth.configureProviders([ EmailAuthProvider(), ]); FirebaseAuth.instance.userChanges().listen((user) { if (user != null) { _loggedIn = true; } else { _loggedIn = false; } notifyListeners(); }); } }
codelabs/firebase-get-to-know-flutter/step_05/lib/app_state.dart/0
{'file_path': 'codelabs/firebase-get-to-know-flutter/step_05/lib/app_state.dart', 'repo_id': 'codelabs', 'token_count': 354}
// 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 'package:go_router/go_router.dart'; import 'widgets.dart'; class AuthFunc extends StatelessWidget { const AuthFunc({ super.key, required this.loggedIn, required this.signOut, }); final bool loggedIn; final void Function() signOut; @override Widget build(BuildContext context) { return Row( children: [ Padding( padding: const EdgeInsets.only(left: 24, bottom: 8), child: StyledButton( onPressed: () { !loggedIn ? context.push('/sign-in') : signOut(); }, child: !loggedIn ? const Text('RSVP') : const Text('Logout')), ), Visibility( visible: loggedIn, child: Padding( padding: const EdgeInsets.only(left: 24, bottom: 8), child: StyledButton( onPressed: () { context.push('/profile'); }, child: const Text('Profile')), )) ], ); } }
codelabs/firebase-get-to-know-flutter/step_06/lib/src/authentication.dart/0
{'file_path': 'codelabs/firebase-get-to-know-flutter/step_06/lib/src/authentication.dart', 'repo_id': 'codelabs', 'token_count': 570}
// 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_test/flutter_test.dart'; import 'package:gtk_flutter/app_state.dart'; import 'package:gtk_flutter/main.dart'; import 'package:provider/provider.dart'; void main() { testWidgets('Basic rendering', (tester) async { // Build our app and trigger a frame. await tester.pumpWidget( ChangeNotifierProvider( create: (context) => ApplicationState(), builder: (context, _) => const App(), ), ); // Verify that our counter starts at 0. expect(find.text('Firebase Meetup'), findsOneWidget); expect(find.text('January 1st'), findsNothing); }); }
codelabs/firebase-get-to-know-flutter/step_06/test/widget_test.dart/0
{'file_path': 'codelabs/firebase-get-to-know-flutter/step_06/test/widget_test.dart', 'repo_id': 'codelabs', 'token_count': 268}
include: ../../analysis_options.yaml analyzer: exclude: - lib/src/*.g.dart
codelabs/google-maps-in-flutter/step_4/analysis_options.yaml/0
{'file_path': 'codelabs/google-maps-in-flutter/step_4/analysis_options.yaml', 'repo_id': 'codelabs', 'token_count': 36}
import 'package:flutter/material.dart'; import 'shimmer_gradient.dart'; import 'shimmer_loading.dart'; class ShimmerLoadingAnim extends StatelessWidget { const ShimmerLoadingAnim( {super.key, required this.child, this.isLoading = false}); final Widget child; final bool isLoading; @override Widget build(BuildContext context) { return Shimmer( linearGradient: shimmerGradient, child: ShimmerLoading( isLoading: isLoading, child: child, ), ); } }
codelabs/haiku_generator/step0/lib/widgets/shimmer_loading_anim.dart/0
{'file_path': 'codelabs/haiku_generator/step0/lib/widgets/shimmer_loading_anim.dart', 'repo_id': 'codelabs', 'token_count': 186}
import '../../domain/repositories/abstract/poem_repository.dart'; // ignore: unused_import import 'dart:convert'; // ignore: unused_import import 'package:http/http.dart' as http; class PoemRepositoryImpl implements PoemRepository { PoemRepositoryImpl(); @override Future<String> getPoems(String productName) async { return ""; } }
codelabs/haiku_generator/step1/lib/data/repositories/poem_repository_impl.dart/0
{'file_path': 'codelabs/haiku_generator/step1/lib/data/repositories/poem_repository_impl.dart', 'repo_id': 'codelabs', 'token_count': 118}
import 'package:flutter/material.dart'; import 'home_screen.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); runApp(const MyApp()); } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( theme: ThemeData( useMaterial3: true, appBarTheme: AppBarTheme( backgroundColor: ColorScheme.fromSeed(seedColor: Colors.deepPurple) .primaryContainer, ), textTheme: const TextTheme( titleMedium: TextStyle( fontFamily: 'Chewy', fontSize: 20, ), ), ), home: const MyHomePage(), ); } }
codelabs/homescreen_codelab/step_05/lib/main.dart/0
{'file_path': 'codelabs/homescreen_codelab/step_05/lib/main.dart', 'repo_id': 'codelabs', 'token_count': 314}
name: dashclicker description: A codelab for in-app purchases publish_to: "none" version: 1.0.0+1 environment: sdk: ^3.2.0 dependencies: cloud_firestore: ^4.0.3 cloud_functions: ^4.0.3 cupertino_icons: ^1.0.2 firebase_auth: ^4.2.2 firebase_core: ^2.5.0 flutter: sdk: flutter google_sign_in: ^6.0.1 http: ^1.0.0 in_app_purchase: ^3.0.1 in_app_purchase_platform_interface: ^1.3.1 intl: ^0.18.0 provider: ^6.0.2 dev_dependencies: flutter_lints: ^3.0.0 flutter_test: sdk: flutter flutter: uses-material-design: true assets: - assets/
codelabs/in_app_purchases/complete/app/pubspec.yaml/0
{'file_path': 'codelabs/in_app_purchases/complete/app/pubspec.yaml', 'repo_id': 'codelabs', 'token_count': 278}
name: firebase_backend_dart description: A sample command-line application. version: 1.0.0 # homepage: https://www.example.com environment: sdk: ^3.2.0 dependencies: googleapis: ^11.0.0 googleapis_auth: ^1.3.0 http: ^1.1.0 shelf: ^1.3.0 shelf_router: ^1.1.2 app_store_server_sdk: ^1.2.5 dev_dependencies: lints: ^3.0.0 test: ^1.16.0
codelabs/in_app_purchases/complete/dart-backend/pubspec.yaml/0
{'file_path': 'codelabs/in_app_purchases/complete/dart-backend/pubspec.yaml', 'repo_id': 'codelabs', 'token_count': 164}
import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:provider/provider.dart'; import '../logic/dash_counter.dart'; import '../logic/dash_purchases.dart'; import '../logic/dash_upgrades.dart'; class HomePage extends StatelessWidget { const HomePage({super.key}); @override Widget build(BuildContext context) { return const Column( children: [ Expanded( flex: 2, child: DashClickerWidget(), ), Expanded(child: UpgradeList()), ], ); } } class DashClickerWidget extends StatelessWidget { const DashClickerWidget({super.key}); @override Widget build(BuildContext context) { return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ const CounterStateWidget(), InkWell( // Don't listen as we don't need a rebuild when the count changes onTap: Provider.of<DashCounter>(context, listen: false).increment, child: Image.asset(context.read<DashPurchases>().beautifiedDash ? 'assets/dash.png' : 'assets/dash_old.png'), ) ], ), ); } } class CounterStateWidget extends StatelessWidget { const CounterStateWidget({super.key}); @override Widget build(BuildContext context) { // This widget is the only widget that directly listens to the counter // and is thus updated almost every frame. Keep this as small as possible. var counter = context.watch<DashCounter>(); return RichText( text: TextSpan( text: 'You have tapped Dash ', style: DefaultTextStyle.of(context).style, children: <TextSpan>[ TextSpan( text: counter.countString, style: const TextStyle(fontWeight: FontWeight.bold)), const TextSpan(text: ' times!'), ], ), ); } } class UpgradeList extends StatelessWidget { const UpgradeList({super.key}); @override Widget build(BuildContext context) { var upgrades = context.watch<DashUpgrades>(); return ListView(children: [ _UpgradeWidget( upgrade: upgrades.tim, title: 'Tim Sneath', onPressed: upgrades.addTim, ), ]); } } class _UpgradeWidget extends StatelessWidget { final Upgrade upgrade; final String title; final VoidCallback onPressed; const _UpgradeWidget({ required this.upgrade, required this.title, required this.onPressed, }); @override Widget build(BuildContext context) { return InkWell( onTap: onPressed, child: ListTile( leading: Center( widthFactor: 1, child: Text( upgrade.count.toString(), ), ), title: Text( title, style: !upgrade.purchasable ? const TextStyle(color: Colors.redAccent) : null, ), subtitle: Text('Produces ${upgrade.work} dashes per second'), trailing: Text( '${NumberFormat.compact().format(upgrade.cost)} dashes', ), )); } }
codelabs/in_app_purchases/step_00/app/lib/pages/home_page.dart/0
{'file_path': 'codelabs/in_app_purchases/step_00/app/lib/pages/home_page.dart', 'repo_id': 'codelabs', 'token_count': 1351}
class ProductData { final String productId; final ProductType type; const ProductData(this.productId, this.type); } enum ProductType { subscription, nonSubscription, } const productDataMap = { 'dash_consumable_2k': ProductData( 'dash_consumable_2k', ProductType.nonSubscription, ), 'dash_upgrade_3d': ProductData( 'dash_upgrade_3d', ProductType.nonSubscription, ), 'dash_subscription_doubler': ProductData( 'dash_subscription_doubler', ProductType.subscription, ), };
codelabs/in_app_purchases/step_00/dart-backend/lib/products.dart/0
{'file_path': 'codelabs/in_app_purchases/step_00/dart-backend/lib/products.dart', 'repo_id': 'codelabs', 'token_count': 190}
// 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:async'; import 'dart:io'; import 'package:shelf/shelf.dart'; import 'package:shelf/shelf_io.dart'; /// Serves [handler] on [InternetAddress.anyIPv4] using the port returned by /// [listenPort]. /// /// The returned [Future] will complete using [terminateRequestFuture] after /// closing the server. Future<void> serveHandler(Handler handler) async { final port = listenPort(); final server = await serve( handler, InternetAddress.anyIPv4, // Allows external connections port, ); print('Serving at http://${server.address.host}:${server.port}'); await terminateRequestFuture(); await server.close(); } /// Returns the port to listen on from environment variable or uses the default /// `8080`. /// /// See https://cloud.google.com/run/docs/reference/container-contract#port int listenPort() => int.parse(Platform.environment['PORT'] ?? '8080'); /// Returns a [Future] that completes when the process receives a /// [ProcessSignal] requesting a shutdown. /// /// [ProcessSignal.sigint] is listened to on all platforms. /// /// [ProcessSignal.sigterm] is listened to on all platforms except Windows. Future<void> terminateRequestFuture() { final completer = Completer<bool>.sync(); // sigIntSub is copied below to avoid a race condition - ignoring this lint // ignore: cancel_subscriptions StreamSubscription? sigIntSub, sigTermSub; Future<void> signalHandler(ProcessSignal signal) async { print('Received signal $signal - closing'); final subCopy = sigIntSub; if (subCopy != null) { sigIntSub = null; await subCopy.cancel(); sigIntSub = null; if (sigTermSub != null) { await sigTermSub!.cancel(); sigTermSub = null; } completer.complete(true); } } sigIntSub = ProcessSignal.sigint.watch().listen(signalHandler); // SIGTERM is not supported on Windows. Attempting to register a SIGTERM // handler raises an exception. if (!Platform.isWindows) { sigTermSub = ProcessSignal.sigterm.watch().listen(signalHandler); } return completer.future; }
codelabs/in_app_purchases/step_09/dart-backend/lib/helpers.dart/0
{'file_path': 'codelabs/in_app_purchases/step_09/dart-backend/lib/helpers.dart', 'repo_id': 'codelabs', 'token_count': 723}
import 'package:flutter/widgets.dart'; import '../constants.dart'; enum PurchaseType { subscriptionPurchase, nonSubscriptionPurchase, } enum Store { googlePlay, appStore, } enum Status { pending, completed, active, expired, } @immutable class PastPurchase { final PurchaseType type; final Store store; final String orderId; final String productId; final DateTime purchaseDate; final DateTime? expiryDate; final Status status; String get title { return switch (productId) { storeKeyConsumable => 'Consumable', storeKeySubscription => 'Subscription', _ => productId }; } PastPurchase.fromJson(Map<String, dynamic> json) : type = _typeFromString(json['type'] as String), store = _storeFromString(json['iapSource'] as String), orderId = json['orderId'] as String, productId = json['productId'] as String, purchaseDate = DateTime.now(), expiryDate = null, status = _statusFromString(json['status'] as String); } PurchaseType _typeFromString(String type) { return switch (type) { 'nonSubscription' => PurchaseType.subscriptionPurchase, 'subscription' => PurchaseType.nonSubscriptionPurchase, _ => throw ArgumentError.value(type, '$type is not a supported type') }; } Store _storeFromString(String store) { return switch (store) { 'googleplay' => Store.googlePlay, 'appstore' => Store.appStore, _ => throw ArgumentError.value(store, '$store is not a supported store') }; } Status _statusFromString(String status) { return switch (status) { 'pending' => Status.pending, 'completed' => Status.completed, 'active' => Status.active, 'expired' => Status.expired, _ => throw ArgumentError.value(status, '$status is not a supported status') }; }
codelabs/in_app_purchases/step_10/app/lib/model/past_purchase.dart/0
{'file_path': 'codelabs/in_app_purchases/step_10/app/lib/model/past_purchase.dart', 'repo_id': 'codelabs', 'token_count': 628}