migrate_manifest.dart 9.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173
// Copyright 2014 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:yaml/yaml.dart';

import '../base/file_system.dart';
import '../base/logger.dart';
import '../base/terminal.dart';
import 'migrate_result.dart';
import 'migrate_utils.dart';

const String _kMergedFilesKey = 'merged_files';
const String _kConflictFilesKey = 'conflict_files';
const String _kAddedFilesKey = 'added_files';
const String _kDeletedFilesKey = 'deleted_files';

/// Represents the manifest file that tracks the contents of the current
/// migration working directory.
///
/// This manifest file is created with the MigrateResult of a computeMigration run.
class MigrateManifest {
  /// Creates a new manifest from a MigrateResult.
  MigrateManifest({
    required this.migrateRootDir,
    required this.migrateResult,
  });

  /// Parses an existing migrate manifest.
  MigrateManifest.fromFile(File manifestFile) : migrateResult = MigrateResult.empty(), migrateRootDir = manifestFile.parent {
    final Object? yamlContents = loadYaml(manifestFile.readAsStringSync());
    if (yamlContents is! YamlMap) {
      throw Exception('Invalid .migrate_manifest file in the migrate working directory. File is not a Yaml map.');
    }
    final YamlMap map = yamlContents;
    bool valid = map.containsKey(_kMergedFilesKey) && map.containsKey(_kConflictFilesKey) && map.containsKey(_kAddedFilesKey) && map.containsKey(_kDeletedFilesKey);
    if (!valid) {
      throw Exception('Invalid .migrate_manifest file in the migrate working directory. File is missing an entry.');
    }
    final Object? mergedFilesYaml = map[_kMergedFilesKey];
    final Object? conflictFilesYaml = map[_kConflictFilesKey];
    final Object? addedFilesYaml = map[_kAddedFilesKey];
    final Object? deletedFilesYaml = map[_kDeletedFilesKey];
    valid = valid && (mergedFilesYaml is YamlList || mergedFilesYaml == null);
    valid = valid && (conflictFilesYaml is YamlList || conflictFilesYaml == null);
    valid = valid && (addedFilesYaml is YamlList || addedFilesYaml == null);
    valid = valid && (deletedFilesYaml is YamlList || deletedFilesYaml == null);
    if (!valid) {
      throw Exception('Invalid .migrate_manifest file in the migrate working directory. Entry is not a Yaml list.');
    }
    if (mergedFilesYaml != null) {
      for (final Object? localPath in mergedFilesYaml as YamlList) {
        if (localPath is String) {
          // We can fill the maps with partially dummy data as not all properties are used by the manifest.
          migrateResult.mergeResults.add(StringMergeResult.explicit(mergedString: '', hasConflict: false, exitCode: 0, localPath: localPath));
        }
      }
    }
    if (conflictFilesYaml != null) {
      for (final Object? localPath in conflictFilesYaml as YamlList) {
        if (localPath is String) {
          migrateResult.mergeResults.add(StringMergeResult.explicit(mergedString: '', hasConflict: true, exitCode: 1, localPath: localPath));
        }
      }
    }
    if (addedFilesYaml != null) {
      for (final Object? localPath in addedFilesYaml as YamlList) {
        if (localPath is String) {
          migrateResult.addedFiles.add(FilePendingMigration(localPath, migrateRootDir.childFile(localPath)));
        }
      }
    }
    if (deletedFilesYaml != null) {
      for (final Object? localPath in deletedFilesYaml as YamlList) {
        if (localPath is String) {
          migrateResult.deletedFiles.add(FilePendingMigration(localPath, migrateRootDir.childFile(localPath)));
        }
      }
    }
  }

  final Directory migrateRootDir;
  final MigrateResult migrateResult;

  /// A list of local paths of files that require conflict resolution.
  List<String> get conflictFiles {
    final List<String> output = <String>[];
    for (final MergeResult result in migrateResult.mergeResults) {
      if (result.hasConflict) {
        output.add(result.localPath);
      }
    }
    return output;
  }

  /// A list of local paths of files that require conflict resolution.
  List<String> remainingConflictFiles(Directory workingDir) {
    final List<String> output = <String>[];
    for (final String localPath in conflictFiles) {
      if (!_conflictsResolved(workingDir.childFile(localPath).readAsStringSync())) {
        output.add(localPath);
      }
    }
    return output;
  }

  // A list of local paths of files that had conflicts and are now fully resolved.
  List<String> resolvedConflictFiles(Directory workingDir) {
    final List<String> output = <String>[];
    for (final String localPath in conflictFiles) {
      if (_conflictsResolved(workingDir.childFile(localPath).readAsStringSync())) {
        output.add(localPath);
      }
    }
    return output;
  }

  /// A list of local paths of files that were automatically merged.
  List<String> get mergedFiles {
    final List<String> output = <String>[];
    for (final MergeResult result in migrateResult.mergeResults) {
      if (!result.hasConflict) {
        output.add(result.localPath);
      }
    }
    return output;
  }

  /// A list of local paths of files that were newly added.
  List<String> get addedFiles {
    final List<String> output = <String>[];
    for (final FilePendingMigration file in migrateResult.addedFiles) {
      output.add(file.localPath);
    }
    return output;
  }

  /// A list of local paths of files that are marked for deletion.
  List<String> get deletedFiles {
    final List<String> output = <String>[];
    for (final FilePendingMigration file in migrateResult.deletedFiles) {
      output.add(file.localPath);
    }
    return output;
  }

  /// Returns the manifest file given a migration workind directory.
  static File getManifestFileFromDirectory(Directory workingDir) {
    return workingDir.childFile('.migrate_manifest');
  }

  /// Writes the manifest yaml file in the working directory.
  void writeFile() {
    final StringBuffer mergedFileManifestContents = StringBuffer();
    final StringBuffer conflictFilesManifestContents = StringBuffer();
    for (final MergeResult result in migrateResult.mergeResults) {
      if (result.hasConflict) {
        conflictFilesManifestContents.write('  - ${result.localPath}\n');
      } else {
        mergedFileManifestContents.write('  - ${result.localPath}\n');
      }
    }

    final StringBuffer newFileManifestContents = StringBuffer();
    for (final String localPath in addedFiles) {
      newFileManifestContents.write('  - $localPath\n)');
    }

    final StringBuffer deletedFileManifestContents = StringBuffer();
    for (final String localPath in deletedFiles) {
      deletedFileManifestContents.write('  - $localPath\n');
    }

174
    final String migrateManifestContents = 'merged_files:\n${mergedFileManifestContents}conflict_files:\n${conflictFilesManifestContents}added_files:\n${newFileManifestContents}deleted_files:\n$deletedFileManifestContents';
175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
    final File migrateManifest = getManifestFileFromDirectory(migrateRootDir);
    migrateManifest.createSync(recursive: true);
    migrateManifest.writeAsStringSync(migrateManifestContents, flush: true);
  }
}

/// Returns true if the file does not contain any git conflict markers.
bool _conflictsResolved(String contents) {
  if (contents.contains('>>>>>>>') && contents.contains('=======') && contents.contains('<<<<<<<')) {
    return false;
  }
  return true;
}

/// Returns true if the migration working directory has all conflicts resolved and prints the migration status.
///
/// The migration status printout lists all added, deleted, merged, and conflicted files.
bool checkAndPrintMigrateStatus(MigrateManifest manifest, Directory workingDir, {bool warnConflict = false, Logger? logger}) {
  final StringBuffer printout = StringBuffer();
  final StringBuffer redPrintout = StringBuffer();
  bool result = true;
  final List<String> remainingConflicts = <String>[];
  final List<String> mergedFiles = <String>[];
  for (final String localPath in manifest.conflictFiles) {
    if (!_conflictsResolved(workingDir.childFile(localPath).readAsStringSync())) {
      remainingConflicts.add(localPath);
    } else {
      mergedFiles.add(localPath);
    }
  }

  mergedFiles.addAll(manifest.mergedFiles);
  if (manifest.addedFiles.isNotEmpty) {
    printout.write('Added files:\n');
    for (final String localPath in manifest.addedFiles) {
      printout.write('  - $localPath\n');
    }
  }
  if (manifest.deletedFiles.isNotEmpty) {
    printout.write('Deleted files:\n');
    for (final String localPath in manifest.deletedFiles) {
      printout.write('  - $localPath\n');
    }
  }
  if (mergedFiles.isNotEmpty) {
    printout.write('Modified files:\n');
    for (final String localPath in mergedFiles) {
      printout.write('  - $localPath\n');
    }
  }
  if (remainingConflicts.isNotEmpty) {
    if (warnConflict) {
      printout.write('Unable to apply migration. The following files in the migration working directory still have unresolved conflicts:');
    } else {
      printout.write('Merge conflicted files:');
    }
    for (final String localPath in remainingConflicts) {
      redPrintout.write('  - $localPath\n');
    }
    result = false;
  }
  if (logger != null) {
    logger.printStatus(printout.toString());
    logger.printStatus(redPrintout.toString(), color: TerminalColor.red, newline: false);
  }
  return result;
}