|
| 1 | +// Copyright (c) 2022, 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 | +import 'dart:io'; |
| 6 | + |
| 7 | +void main() async { |
| 8 | + _updateManifestJson(); |
| 9 | +} |
| 10 | + |
| 11 | +/// Adds the Googler extension key. |
| 12 | +Future<void> _updateManifestJson() async { |
| 13 | + final manifestJson = File('compiled/manifest.json'); |
| 14 | + final extensionKeyTxt = File('extension_key.txt'); |
| 15 | + final extensionKey = await extensionKeyTxt.exists() |
| 16 | + ? await extensionKeyTxt.readAsString() |
| 17 | + : null; |
| 18 | + _transformDevFile(manifestJson, (line) { |
| 19 | + if (_matchesKey(line: line, key: 'name')) { |
| 20 | + return [ |
| 21 | + line, |
| 22 | + if (extensionKey != null) |
| 23 | + _newKeyValue( |
| 24 | + oldLine: line, |
| 25 | + newKey: 'key', |
| 26 | + newValue: extensionKey, |
| 27 | + ), |
| 28 | + ]; |
| 29 | + } else { |
| 30 | + return [line]; |
| 31 | + } |
| 32 | + }); |
| 33 | +} |
| 34 | + |
| 35 | +Future<void> _transformDevFile( |
| 36 | + File devFile, List<String> Function(String) transformLine) async { |
| 37 | + final lines = devFile.readAsLinesSync(); |
| 38 | + final newLines = <String>[]; |
| 39 | + for (final line in lines) { |
| 40 | + newLines.addAll(transformLine(line)); |
| 41 | + } |
| 42 | + final content = newLines.joinWithNewLine(); |
| 43 | + return devFile.writeAsStringSync(content); |
| 44 | +} |
| 45 | + |
| 46 | +bool _matchesKey({required String line, required String key}) { |
| 47 | + return line.trimLeft().startsWith('"$key":'); |
| 48 | +} |
| 49 | + |
| 50 | +String _newKeyValue({ |
| 51 | + required String oldLine, |
| 52 | + String? newKey, |
| 53 | + String? newValue, |
| 54 | +}) { |
| 55 | + final lineStart = oldLine.leftPadding(); |
| 56 | + final key = newKey != null ? '"$newKey": ' : ''; |
| 57 | + final value = newValue != null ? '"$newValue"' : ''; |
| 58 | + final lineEnd = oldLine.trim().endsWith(',') ? ',' : ''; |
| 59 | + return '$lineStart$key$value$lineEnd'; |
| 60 | +} |
| 61 | + |
| 62 | +extension LeftPaddingExtension on String { |
| 63 | + String leftPadding() { |
| 64 | + String padding = ''; |
| 65 | + int idx = 0; |
| 66 | + while (idx < length && this[idx] == ' ') { |
| 67 | + padding += ' '; |
| 68 | + idx++; |
| 69 | + } |
| 70 | + return padding; |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +extension JoinExtension on List<String> { |
| 75 | + String joinWithNewLine() { |
| 76 | + return '${join('\n')}\n'; |
| 77 | + } |
| 78 | +} |
0 commit comments