|
| 1 | +// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +library cli_util; |
| 6 | + |
| 7 | +import 'dart:io'; |
| 8 | + |
| 9 | +import 'package:which/which.dart'; |
| 10 | + |
| 11 | +/// Return the path to the current Dart SDK. This will return `null` if we are |
| 12 | +/// unable to locate the Dart SDK. |
| 13 | +Directory getSdkDir([List<String> cliArgs]) { |
| 14 | + // Look for --dart-sdk on the command line. |
| 15 | + if (cliArgs != null) { |
| 16 | + int index = cliArgs.indexOf('--dart-sdk'); |
| 17 | + |
| 18 | + if (index != -1 && (index + 1 < cliArgs.length)) { |
| 19 | + return new Directory(cliArgs[index + 1]); |
| 20 | + } |
| 21 | + |
| 22 | + for (String arg in cliArgs) { |
| 23 | + if (arg.startsWith('--dart-sdk=')) { |
| 24 | + return new Directory(arg.substring('--dart-sdk='.length)); |
| 25 | + } |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + // Look in env['DART_SDK'] |
| 30 | + if (Platform.environment['DART_SDK'] != null) { |
| 31 | + return new Directory(Platform.environment['DART_SDK']); |
| 32 | + } |
| 33 | + |
| 34 | + // Look relative to the dart executable. |
| 35 | + Directory sdkDirectory = new File(Platform.executable).parent.parent; |
| 36 | + if (_isSdkDir(sdkDirectory)) return sdkDirectory; |
| 37 | + |
| 38 | + // Try and locate the VM using 'which'. |
| 39 | + String executable = whichSync('dart', orElse: () => null); |
| 40 | + |
| 41 | + // In case Dart is symlinked (e.g. homebrew on Mac) follow symbolic links. |
| 42 | + Link link = new Link(executable); |
| 43 | + if (link.existsSync()) { |
| 44 | + executable = link.resolveSymbolicLinksSync(); |
| 45 | + } |
| 46 | + |
| 47 | + File dartVm = new File(executable); |
| 48 | + Directory dir = dartVm.parent.parent; |
| 49 | + if (_isSdkDir(dir)) return dir; |
| 50 | + |
| 51 | + return null; |
| 52 | +} |
| 53 | + |
| 54 | +bool _isSdkDir(Directory dir) => _joinFile(dir, ['version']).existsSync(); |
| 55 | + |
| 56 | +File _joinFile(Directory dir, List<String> files) { |
| 57 | + String pathFragment = files.join(Platform.pathSeparator); |
| 58 | + return new File("${dir.path}${Platform.pathSeparator}${pathFragment}"); |
| 59 | +} |
0 commit comments