Skip to content

Commit

Permalink
refactor: Run analyzer and fix lint issues, possible perf improvements (
Browse files Browse the repository at this point in the history
#128)

* refactor: Run analyzer and fix linting issues, might see perf improvements
  • Loading branch information
j4qfrost committed Oct 30, 2022
1 parent 9d1e953 commit 0675a4e
Show file tree
Hide file tree
Showing 166 changed files with 2,429 additions and 2,318 deletions.
13 changes: 1 addition & 12 deletions packages/codable/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -1,12 +1 @@
include: package:lint/analysis_options.yaml

# # Lint rules and documentation, see http://dart-lang.github.io/linter/lints
# linter:
# rules:
# - cancel_subscriptions
# - hash_and_equals
# - iterable_contains_unrelated_type
# - list_remove_unrelated_type
# - test_types_in_equals
# - unrelated_type_equality_checks
# - valid_regexps
include: package:lint/analysis_options.yaml
1 change: 0 additions & 1 deletion packages/common_test/analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ linter:
- file_names
- hash_and_equals
- implementation_imports
- invariant_booleans
- iterable_contains_unrelated_type
- join_return_with_assignment
- library_names
Expand Down
5 changes: 2 additions & 3 deletions packages/conduit/analysis_options.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,6 @@ linter:
- file_names
- hash_and_equals
- implementation_imports
- invariant_booleans
- iterable_contains_unrelated_type
- join_return_with_assignment
- library_names
Expand All @@ -66,8 +65,8 @@ linter:
- prefer_constructors_over_static_methods
- prefer_contains
- prefer_equal_for_default_values
# - prefer_final_fields
# - prefer_final_locals
- prefer_final_fields
- prefer_final_locals
- prefer_foreach
- prefer_generic_function_type_aliases
- prefer_interpolation_to_compose_strings
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ class AuthRedirectController extends ResourceController {
];
}

static Response _unsupportedResponseTypeResponse = Response.badRequest(
static final Response _unsupportedResponseTypeResponse = Response.badRequest(
body: "<h1>Error</h1><p>unsupported_response_type</p>")
..contentType = ContentType.html;

Expand Down
42 changes: 19 additions & 23 deletions packages/conduit/lib/src/cli/command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -112,13 +112,12 @@ abstract class CLICommand {
T decode<T extends Object>(
String key,
) {
T? val = decodeOptional(key);
final T? val = decodeOptional(key);

if (val == null) {
throw CLIException('The required argument "$key" was not passed.');
if (val != null) {
return val;
}

return val;
throw CLIException('The required argument "$key" was not passed.');
}

/// Use this method to extract an optional value for the command line argument for [key].
Expand All @@ -143,12 +142,11 @@ abstract class CLICommand {
}

if (T == int && val is String) {
var t = int.tryParse(val);
if (t == null) {
throw CLIException(
'Invalid integer value "$val" for argument "$key".');
} else
final t = int.tryParse(val);
if (t != null) {
return t as T;
}
throw CLIException('Invalid integer value "$val" for argument "$key".');
}
return RuntimeContext.current.coerce<T>(val);
} on TypeCoercionException catch (_) {
Expand All @@ -158,10 +156,7 @@ abstract class CLICommand {
}

T? _orElse<T>(T? Function()? orElse) {
if (orElse != null)
return orElse();
else
return null;
return (orElse != null) ? orElse() : null;
}

void registerCommand(CLICommand cmd) {
Expand Down Expand Up @@ -236,12 +231,12 @@ abstract class CLICommand {

Future determineToolVersion() async {
try {
var toolLibraryFilePath = (await Isolate.resolvePackageUri(
final toolLibraryFilePath = (await Isolate.resolvePackageUri(
currentMirrorSystem().findLibrary(#conduit).uri))!
.toFilePath(windows: Platform.isWindows);
var conduitDirectory = Directory(FileSystemEntity.parentOf(
final conduitDirectory = Directory(FileSystemEntity.parentOf(
FileSystemEntity.parentOf(toolLibraryFilePath)));
var toolPubspecFile =
final toolPubspecFile =
File.fromUri(conduitDirectory.absolute.uri.resolve("pubspec.yaml"));

final toolPubspecContents =
Expand Down Expand Up @@ -287,7 +282,7 @@ abstract class CLICommand {
String get detailedDescription => "";

String get usage {
var buf = StringBuffer(name);
final buf = StringBuffer(name);
if (_commandMap.isNotEmpty) {
buf.write(" <command>");
}
Expand Down Expand Up @@ -331,19 +326,20 @@ abstract class CLICommand {
if (options.commands.isNotEmpty) {
print("Available sub-commands:");

var commandNames = options.commands.keys.toList();
final commandNames = options.commands.keys.toList();
commandNames.sort((a, b) => b.length.compareTo(a.length));
var length = commandNames.first.length + 3;
final length = commandNames.first.length + 3;
commandNames.forEach((command) {
var desc = _commandMap[command]?.description;
final desc = _commandMap[command]?.description;
print(" ${command.padRight(length, " ")}$desc");
});
}
}

bool isExecutableInShellPath(String name) {
String locator = Platform.isWindows ? "where" : "which";
ProcessResult results = Process.runSync(locator, [name], runInShell: true);
final String locator = Platform.isWindows ? "where" : "which";
final ProcessResult results =
Process.runSync(locator, [name], runInShell: true);

return results.exitCode == 0;
}
Expand Down
8 changes: 4 additions & 4 deletions packages/conduit/lib/src/cli/commands/auth_add_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ class CLIAuthAddClient extends CLICommand
"A space-delimited list of allowed scopes. Omit if application does not support scopes.",
defaultsTo: "")
List<String>? get allowedScopes {
String v = decode<String>("allowed-scopes");
final String v = decode<String>("allowed-scopes");
if (v.isEmpty) {
return null;
}
Expand All @@ -80,17 +80,17 @@ class CLIAuthAddClient extends CLICommand
return 1;
}

var dataModel = ManagedDataModel.fromCurrentMirrorSystem();
final dataModel = ManagedDataModel.fromCurrentMirrorSystem();
context = ManagedContext(dataModel, persistentStore);

var credentials = AuthUtility.generateAPICredentialPair(clientID, secret,
final credentials = AuthUtility.generateAPICredentialPair(clientID, secret,
redirectURI: redirectUri,
hashLength: hashLength,
hashRounds: hashRounds,
hashFunction: hashFunction)
..allowedScopes = allowedScopes?.map((s) => AuthScope(s)).toList();

var managedCredentials = ManagedAuthClient.fromClient(credentials);
final managedCredentials = ManagedAuthClient.fromClient(credentials);

final query = Query<ManagedAuthClient>(context!)
..values = managedCredentials;
Expand Down
12 changes: 6 additions & 6 deletions packages/conduit/lib/src/cli/commands/auth_scope.dart
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ class CLIAuthScopeClient extends CLICommand
"A space-delimited list of allowed scopes. Omit if application does not support scopes.",
defaultsTo: "")
List<String>? get scopes {
String? v = decode("scopes");
if (v.isEmpty) {
final String? v = decode("scopes");
if (v!.isEmpty) {
return null;
}
return v.split(" ").toList();
Expand All @@ -41,18 +41,18 @@ class CLIAuthScopeClient extends CLICommand
return 1;
}

var dataModel = ManagedDataModel.fromCurrentMirrorSystem();
final dataModel = ManagedDataModel.fromCurrentMirrorSystem();
context = ManagedContext(dataModel, persistentStore);

var scopingClient = AuthClient.public(clientID!,
final scopingClient = AuthClient.public(clientID!,
allowedScopes: scopes?.map((s) => AuthScope(s)).toList());

var query = Query<ManagedAuthClient>(context)
final query = Query<ManagedAuthClient>(context)
..where((o) => o.id).equalTo(clientID)
..values.allowedScope =
scopingClient.allowedScopes?.map((s) => s.toString()).join(" ");

var result = await query.updateOne();
final result = await query.updateOne();
if (result == null) {
displayError("Client ID '$clientID' does not exist.");
return 1;
Expand Down
39 changes: 20 additions & 19 deletions packages/conduit/lib/src/cli/commands/create.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class CLITemplateCreator extends CLICommand with CLIConduitGlobal {
return 1;
}

var destDirectory = destinationDirectoryFromPath(projectName!);
final destDirectory = destinationDirectoryFromPath(projectName!);
if (destDirectory.existsSync()) {
displayError("${destDirectory.path} already exists, stopping.");
return 1;
Expand Down Expand Up @@ -111,7 +111,7 @@ class CLITemplateCreator extends CLICommand with CLIConduitGlobal {
}

bool shouldIncludeItem(FileSystemEntity entity) {
var ignoreFiles = [
final ignoreFiles = [
"packages",
"pubspec.lock",
"Dart_Packages.xml",
Expand All @@ -120,7 +120,7 @@ class CLITemplateCreator extends CLICommand with CLIConduitGlobal {
"vcs.xml",
];

var hiddenFilesToKeep = [
final hiddenFilesToKeep = [
".gitignore",
".travis.yml",
"analysis_options.yaml"
Expand Down Expand Up @@ -157,9 +157,9 @@ class CLITemplateCreator extends CLICommand with CLIConduitGlobal {

void copyDirectory(String? projectName, Directory destinationParentDirectory,
Directory sourceDirectory) {
var sourceDirectoryName = sourceDirectory
final sourceDirectoryName = sourceDirectory
.uri.pathSegments[sourceDirectory.uri.pathSegments.length - 2];
var destDir = Directory(
final destDir = Directory(
path_lib.join(destinationParentDirectory.path, sourceDirectoryName));

destDir.createSync();
Expand All @@ -171,15 +171,15 @@ class CLITemplateCreator extends CLICommand with CLIConduitGlobal {

void copyFile(
String projectName, Directory destinationDirectory, File sourceFile) {
var path = path_lib.join(
final path = path_lib.join(
destinationDirectory.path, fileNameForFile(projectName, sourceFile));
var contents = sourceFile.readAsStringSync();

contents = contents.replaceAll("wildfire", projectName);
contents =
contents.replaceAll("Wildfire", camelCaseFromSnakeCase(projectName));

var outputFile = File(path);
final outputFile = File(path);
outputFile.createSync();
outputFile.writeAsStringSync(contents);
}
Expand All @@ -193,29 +193,30 @@ class CLITemplateCreator extends CLICommand with CLIConduitGlobal {
if (pathString.startsWith("/")) {
return Directory(pathString);
}
var currentDirPath = join(Directory.current.path, pathString);
final currentDirPath = join(Directory.current.path, pathString);

return Directory(currentDirPath);
}

void createProjectSpecificFiles(String directoryPath) {
displayProgress("Generating config.yaml from config.src.yaml.");
var configSrcPath = File(path_lib.join(directoryPath, "config.src.yaml"));
final configSrcPath = File(path_lib.join(directoryPath, "config.src.yaml"));
configSrcPath
.copySync(File(path_lib.join(directoryPath, "config.yaml")).path);
}

bool addDependencyOverridesToPackage(
String packageDirectoryPath, Map<String, Uri> overrides) {
var pubspecFile = File(path_lib.join(packageDirectoryPath, "pubspec.yaml"));
var contents = pubspecFile.readAsStringSync();
final pubspecFile =
File(path_lib.join(packageDirectoryPath, "pubspec.yaml"));
final contents = pubspecFile.readAsStringSync();

bool valid = true;

final overrideBuffer = StringBuffer();
overrideBuffer.writeln("dependency_overrides:");
overrides.forEach((packageName, location) {
var path = location.toFilePath(windows: Platform.isWindows);
final path = location.toFilePath(windows: Platform.isWindows);

valid &= _testPackagePath(path, packageName);
overrideBuffer.writeln(" $packageName:");
Expand Down Expand Up @@ -247,28 +248,28 @@ class CLITemplateCreator extends CLICommand with CLIConduitGlobal {
}

bool isSnakeCase(String string) {
var expr = RegExp("^[a-z][a-z0-9_]*\$");
final expr = RegExp("^[a-z][a-z0-9_]*\$");
return expr.hasMatch(string);
}

String camelCaseFromSnakeCase(String string) {
return string.split("_").map((str) {
var firstChar = str.substring(0, 1);
var remainingString = str.substring(1, str.length);
final firstChar = str.substring(0, 1);
final remainingString = str.substring(1, str.length);
return firstChar.toUpperCase() + remainingString;
}).join("");
}

Future<int> fetchProjectDependencies(Directory workingDirectory,
{bool offline = false}) async {
var args = ["pub", "get"];
final args = ["pub", "get"];
if (offline) {
args.add("--offline");
}

try {
const cmd = "dart";
var process = await Process.start(cmd, args,
final process = await Process.start(cmd, args,
workingDirectory: workingDirectory.absolute.path,
runInShell: true)
.timeout(const Duration(seconds: 60));
Expand Down Expand Up @@ -323,7 +324,7 @@ class CLITemplateCreator extends CLICommand with CLIConduitGlobal {

/// test if the given package dir exists in the test path
bool _testPackagePath(String testPath, String packageName) {
String packagePath = _truepath(testPath);
final String packagePath = _truepath(testPath);
if (!_exists(packagePath)) {
displayError(
"The source for path '$packageName' doesn't exists. Expected to find it at '$packagePath'");
Expand Down Expand Up @@ -380,7 +381,7 @@ class CLIConduitGlobal {
PubCache pub = PubCache();

PackageRef? get conduitPackageRef {
var apps = pub.getGlobalApplications();
final apps = pub.getGlobalApplications();
if (apps.isEmpty) {
return null;
}
Expand Down
2 changes: 1 addition & 1 deletion packages/conduit/lib/src/cli/commands/db_generate.dart
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class CLIDatabaseGenerate extends CLICommand

@override
Future<int> handle() async {
var existingMigrations = projectMigrations;
final existingMigrations = projectMigrations;

var newMigrationFile = File.fromUri(migrationDirectory!.uri.resolve(
"00000001_${migrationName != "unnamed" ? migrationName : "initial"}.migration.dart"));
Expand Down
2 changes: 1 addition & 1 deletion packages/conduit/lib/src/cli/commands/db_schema.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class CLIDatabaseSchema extends CLICommand
with CLIDatabaseManagingCommand, CLIProject {
@override
Future<int> handle() async {
var map = (await getProjectSchema(this)).asMap();
final map = (await getProjectSchema(this)).asMap();
if (isMachineOutput) {
outputSink.write("${json.encode(map)}");
} else {
Expand Down
4 changes: 2 additions & 2 deletions packages/conduit/lib/src/cli/commands/db_show_migrations.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ class CLIDatabaseShowMigrations extends CLICommand
with CLIDatabaseManagingCommand, CLIProject, CLIDatabaseConnectingCommand {
@override
Future<int> handle() async {
var files = projectMigrations.map((mig) {
var versionString = "${mig.versionNumber}".padLeft(8, "0");
final files = projectMigrations.map((mig) {
final versionString = "${mig.versionNumber}".padLeft(8, "0");
return " $versionString | ${mig.uri!.pathSegments.last}";
}).join("\n");

Expand Down
2 changes: 1 addition & 1 deletion packages/conduit/lib/src/cli/commands/db_upgrade.dart
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ class CLIDatabaseUpgrade extends CLICommand
}

DBInfo? get _storeConnectionInfo {
var s = persistentStore;
final s = persistentStore;
if (s is PostgreSQLPersistentStore) {
return DBInfo("postgres", s.username, s.password, s.host, s.port,
s.databaseName, s.timeZone,
Expand Down
Loading

0 comments on commit 0675a4e

Please sign in to comment.