gradle.dart 5.83 KB
Newer Older
1 2 3 4 5 6 7 8
// Copyright 2016 The Chromium 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:path/path.dart' as path;

9
import '../base/common.dart';
10
import '../base/file_system.dart';
11 12 13 14 15 16 17 18 19 20 21 22 23
import '../base/logger.dart';
import '../base/os.dart';
import '../base/process.dart';
import '../base/utils.dart';
import '../build_info.dart';
import '../cache.dart';
import '../globals.dart';
import 'android_sdk.dart';

const String gradleManifestPath = 'android/app/src/main/AndroidManifest.xml';
const String gradleAppOut = 'android/app/build/outputs/apk/app-debug.apk';

bool isProjectUsingGradle() {
24
  return fs.isFileSync('android/build.gradle');
25 26 27 28 29
}

String locateSystemGradle({ bool ensureExecutable: true }) {
  String gradle = _locateSystemGradle();
  if (ensureExecutable && gradle != null) {
30
    File file = fs.file(gradle);
31 32 33 34 35 36 37 38 39 40
    if (file.existsSync())
      os.makeExecutable(file);
  }
  return gradle;
}

String _locateSystemGradle() {
  // See if the user has explicitly configured gradle-dir.
  String gradleDir = config.getValue('gradle-dir');
  if (gradleDir != null) {
41
    if (fs.isFileSync(gradleDir))
42 43 44 45 46 47 48 49 50
      return gradleDir;
    return path.join(gradleDir, 'bin', 'gradle');
  }

  // Look relative to Android Studio.
  String studioPath = config.getValue('android-studio-dir');

  if (studioPath == null && os.isMacOS) {
    final String kDefaultMacPath = '/Applications/Android Studio.app';
51
    if (fs.isDirectorySync(kDefaultMacPath))
52 53 54 55 56 57 58 59
      studioPath = kDefaultMacPath;
  }

  if (studioPath != null) {
    // '/Applications/Android Studio.app/Contents/gradle/gradle-2.10/bin/gradle'
    if (os.isMacOS && !studioPath.endsWith('Contents'))
      studioPath = path.join(studioPath, 'Contents');

60
    Directory dir = fs.directory(path.join(studioPath, 'gradle'));
61 62 63 64 65
    if (dir.existsSync()) {
      // We find the first valid gradle directory.
      for (FileSystemEntity entity in dir.listSync()) {
        if (entity is Directory && path.basename(entity.path).startsWith('gradle-')) {
          String executable = path.join(entity.path, 'bin', 'gradle');
66
          if (fs.isFileSync(executable))
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
            return executable;
        }
      }
    }
  }

  // Use 'which'.
  File file = os.which('gradle');
  if (file != null)
    return file.path;

  // We couldn't locate gradle.
  return null;
}

String locateProjectGradlew({ bool ensureExecutable: true }) {
  final String path = 'android/gradlew';

85
  if (fs.isFileSync(path)) {
86
    if (ensureExecutable)
87
      os.makeExecutable(fs.file(path));
88 89 90 91 92 93
    return path;
  } else {
    return null;
  }
}

94
Future<Null> buildGradleProject(BuildMode buildMode) async {
95
  // Create android/local.properties.
96
  File localProperties = fs.file('android/local.properties');
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
  if (!localProperties.existsSync()) {
    localProperties.writeAsStringSync(
      'sdk.dir=${androidSdk.directory}\n'
      'flutter.sdk=${Cache.flutterRoot}\n'
    );
  }

  // Update the local.settings file with the build mode.
  // TODO(devoncarew): It would be nicer if we could pass this information in via a cli flag.
  SettingsFile settings = new SettingsFile.parseFromFile(localProperties);
  settings.values['flutter.buildMode'] = getModeName(buildMode);
  settings.writeContents(localProperties);

  String gradlew = locateProjectGradlew();

  if (gradlew == null) {
    String gradle = locateSystemGradle();
    if (gradle == null) {
115
      throwToolExit(
116
        'Unable to locate gradle. Please configure the path to gradle using \'flutter config --gradle-dir\'.'
117 118 119 120 121 122
      );
    } else {
      printTrace('Using gradle from $gradle.');
    }

    // Stamp the android/app/build.gradle file with the current android sdk and build tools version.
123
    File appGradleFile = fs.file('android/app/build.gradle');
124 125 126 127 128 129 130 131 132
    if (appGradleFile.existsSync()) {
      _GradleFile gradleFile = new _GradleFile.parse(appGradleFile);
      AndroidSdkVersion sdkVersion = androidSdk.latestVersion;
      gradleFile.replace('compileSdkVersion', "${sdkVersion.sdkLevel}");
      gradleFile.replace('buildToolsVersion', "'${sdkVersion.buildToolsVersionName}'");
      gradleFile.writeContents(appGradleFile);
    }

    // Run 'gradle wrapper'.
133 134 135 136 137 138 139
    try {
      Status status = logger.startProgress('Running \'gradle wrapper\'...');
      int exitcode = await runCommandAndStreamOutput(
        <String>[gradle, 'wrapper'],
        workingDirectory: 'android',
        allowReentrantFlutter: true
      );
Devon Carew's avatar
Devon Carew committed
140
      status.stop();
141
      if (exitcode != 0)
142
        throwToolExit('Gradle failed: $exitcode', exitCode: exitcode);
143
    } catch (error) {
144
      throwToolExit('$error');
145
    }
146 147

    gradlew = locateProjectGradlew();
148 149
    if (gradlew == null)
      throwToolExit('Unable to build android/gradlew.');
150 151 152 153 154
  }

  // Run 'gradlew build'.
  Status status = logger.startProgress('Running \'gradlew build\'...');
  int exitcode = await runCommandAndStreamOutput(
155
    <String>[fs.file('android/gradlew').absolute.path, 'build'],
156 157 158
    workingDirectory: 'android',
    allowReentrantFlutter: true
  );
Devon Carew's avatar
Devon Carew committed
159
  status.stop();
160

161 162
  if (exitcode != 0)
    throwToolExit('Gradlew failed: $exitcode', exitCode: exitcode);
163

164
  File apkFile = fs.file(gradleAppOut);
165
  printStatus('Built $gradleAppOut (${getSizeAsMB(apkFile.lengthSync())}).');
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
}

class _GradleFile {
  _GradleFile.parse(File file) {
    contents = file.readAsStringSync();
  }

  String contents;

  void replace(String key, String newValue) {
    // Replace 'ws key ws value' with the new value.
    final RegExp regex = new RegExp('\\s+$key\\s+(\\S+)', multiLine: true);
    Match match = regex.firstMatch(contents);
    if (match != null) {
      String oldValue = match.group(1);
      int offset = match.end - oldValue.length;
      contents = contents.substring(0, offset) + newValue + contents.substring(match.end);
    }
  }

  void writeContents(File file) {
    file.writeAsStringSync(contents);
  }
}