Skip to content

Commit

Permalink
Misc Dart services cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
parlough committed Dec 15, 2023
1 parent 0ed1acc commit 9102ada
Show file tree
Hide file tree
Showing 12 changed files with 65 additions and 74 deletions.
8 changes: 5 additions & 3 deletions pkgs/dart_services/lib/server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,15 @@ Future<void> main(List<String> args) async {

final sdk = Sdk();

var port = 8080;
final int port;

// Read port from args; fall back to using an env. variable.
if (results.wasParsed('port')) {
port = int.parse(results['port'] as String);
} else if (Platform.environment.containsKey('PORT')) {
port = int.parse(Platform.environment['PORT']!);
} else if (Platform.environment['PORT'] case final environmentPath?) {
port = int.parse(environmentPath);
} else {
port = 8080;
}

Logger.root.level = Level.FINER;
Expand Down
18 changes: 7 additions & 11 deletions pkgs/dart_services/lib/src/analysis.dart
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ class AnalysisServerWrapper {
String get mainPath => _getPathFromName(kMainDart);

Future<void> init() async {
final serverArgs = <String>['--client-id=DartPad'];
const serverArgs = <String>['--client-id=DartPad'];
_logger.info('Starting analysis server '
'(sdk: ${path.relative(sdkPath)}, args: ${serverArgs.join(' ')})');

Expand Down Expand Up @@ -231,11 +231,11 @@ class AnalysisServerWrapper {
}

Future<api.DocumentResponse> dartdoc(String src, int offset) async {
final sourcepath = _getPathFromName(kMainDart);
final sourcePath = _getPathFromName(kMainDart);

await _loadSources(_getOverlayMapWithPaths({kMainDart: src}));

final result = await analysisServer.analysis.getHover(sourcepath, offset);
final result = await analysisServer.analysis.getHover(sourcePath, offset);

if (result.hovers.isEmpty) {
return api.DocumentResponse();
Expand All @@ -260,9 +260,9 @@ class AnalysisServerWrapper {
final errors = <AnalysisError>[];

// Loop over all files and collect errors.
for (final sourcepath in sources.keys) {
for (final sourcePath in sources.keys) {
errors
.addAll((await analysisServer.analysis.getErrors(sourcepath)).errors);
.addAll((await analysisServer.analysis.getErrors(sourcePath)).errors);
}

final issues = errors.map((error) {
Expand Down Expand Up @@ -310,18 +310,16 @@ class AnalysisServerWrapper {
final imports = getAllImportsFor(source);
final importIssues = <api.AnalysisIssue>[];

late final lines = Lines(source);

for (final import in imports) {
final start = import.firstTokenAfterCommentAndMetadata;
final end = import.endToken;

Lines? lines;

if (import.dartImport) {
// ignore dart: imports.
} else if (import.packageImport) {
if (!isSupportedPackage(import.packageName)) {
lines ??= Lines(source);

importIssues.add(api.AnalysisIssue(
kind: 'warning',
message: "Unsupported package: 'package:${import.packageName}'.",
Expand All @@ -334,8 +332,6 @@ class AnalysisServerWrapper {
));
}
} else {
lines ??= Lines(source);

importIssues.add(api.AnalysisIssue(
kind: 'error',
message: 'Import type not supported.',
Expand Down
6 changes: 3 additions & 3 deletions pkgs/dart_services/lib/src/caching.dart
Original file line number Diff line number Diff line change
Expand Up @@ -173,16 +173,16 @@ class RedisCache implements ServerCache {
}

@override
Future<dynamic> remove(String key) async {
Future<void> remove(String key) async {
key = _genKey(key);
if (!_isConnected()) {
log.warning('$_logPrefix: no cache available when removing key $key');
return null;
return;
}

final commands = RespCommandsTier2(redisClient!);
try {
return commands.del([key]).timeout(cacheOperationTimeout,
await commands.del([key]).timeout(cacheOperationTimeout,
onTimeout: () async {
log.warning('$_logPrefix: timeout on remove operation for key $key');
await _connection?.close();
Expand Down
5 changes: 3 additions & 2 deletions pkgs/dart_services/lib/src/common_server.dart
Original file line number Diff line number Diff line change
Expand Up @@ -228,10 +228,11 @@ class CommonServerApi {
final packageVersions = getPackageVersions();

final packages = [
for (final packageName in packageVersions.keys)
for (final MapEntry(key: packageName, value: packageVersion)
in packageVersions.entries)
api.PackageInfo(
name: packageName,
version: packageVersions[packageName]!,
version: packageVersion,
supported: isSupportedPackage(packageName),
),
];
Expand Down
8 changes: 2 additions & 6 deletions pkgs/dart_services/lib/src/compiling.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import 'project_templates.dart';
import 'pub.dart';
import 'sdk.dart';

Logger _logger = Logger('compiler');
final Logger _logger = Logger('compiler');

/// An interface to the dart2js compiler. A compiler object can process one
/// compile at a time.
Expand All @@ -41,10 +41,6 @@ class Compiler {
maxWorkers: 1),
_projectTemplates = ProjectTemplates.projectTemplates;

Future<CompilationResults> warmup() async {
return compile('void main() => print("hello");');
}

/// Compile the given string and return the resulting [CompilationResults].
Future<CompilationResults> compile(
String source, {
Expand Down Expand Up @@ -162,7 +158,7 @@ class Compiler {
_logger.fine('About to exec dartdevc worker: ${arguments.join(' ')}"');

final response =
await _ddcDriver.doWork(WorkRequest()..arguments.addAll(arguments));
await _ddcDriver.doWork(WorkRequest(arguments: arguments));

if (response.exitCode != 0) {
return DDCCompilationResults.failed([
Expand Down
14 changes: 10 additions & 4 deletions pkgs/dart_services/lib/src/logging.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,17 @@ final _wsRegex = RegExp(r' \s+');
void emitLogsToStdout() {
Logger.root.onRecord.listen((LogRecord record) {
if (verboseLogging || record.level >= Level.INFO) {
var stackTrace = '';
if (record.stackTrace != null) {
var lines = record.stackTrace!.toString().split('\n').take(5).join(' ');
lines = lines.replaceAll(_wsRegex, ' ');
final String stackTrace;
if (record.stackTrace case final recordStackTrace?) {
final lines = recordStackTrace
.toString()
.split('\n')
.take(5)
.join(' ')
.replaceAll(_wsRegex, ' ');
stackTrace = ' $lines';
} else {
stackTrace = '';
}

print(
Expand Down
4 changes: 1 addition & 3 deletions pkgs/dart_services/lib/src/pub.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,7 @@ import 'package:yaml/yaml.dart';
import 'project_templates.dart' as project;

/// Extract all imports from [dartSource] source code.
List<ImportDirective> getAllImportsFor(String? dartSource) {
if (dartSource == null) return [];

List<ImportDirective> getAllImportsFor(String dartSource) {
final unit = parseString(content: dartSource, throwIfDiagnostics: false).unit;
return unit.directives.whereType<ImportDirective>().toList();
}
Expand Down
14 changes: 7 additions & 7 deletions pkgs/dart_services/lib/src/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,7 @@ Future<Process> runWithLogging(
}

class TaskScheduler {
final Queue<_SchedulerTask<dynamic>> _taskQueue =
Queue<_SchedulerTask<dynamic>>();
final Queue<_SchedulerTask<Object?>> _taskQueue = Queue();
bool _isActive = false;

int get queueCount => _taskQueue.length;
Expand Down Expand Up @@ -112,16 +111,17 @@ class _SchedulerTask<T> {

// Public working data structure.
abstract class SchedulerTask<T> {
late Duration timeoutDuration;
final Duration timeoutDuration;

SchedulerTask({required this.timeoutDuration});

Future<T> perform();
}

class ClosureTask<T> extends SchedulerTask<T> {
final Future<T> Function() _closure;

ClosureTask(this._closure, {required Duration timeoutDuration}) {
this.timeoutDuration = timeoutDuration;
}
ClosureTask(this._closure, {required super.timeoutDuration});

@override
Future<T> perform() {
Expand All @@ -136,7 +136,7 @@ class ClosureTask<T> extends SchedulerTask<T> {
final _possiblePathPattern = RegExp(r'[a-zA-Z:]*\/\S*');

class Lines {
final _starts = <int>[];
final List<int> _starts = [];

Lines(String source) {
final units = source.codeUnits;
Expand Down
52 changes: 26 additions & 26 deletions pkgs/dart_services/pubspec.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit 9102ada

Please sign in to comment.