version_test.dart 38.8 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:convert';

7 8
import 'package:file/file.dart';
import 'package:file/memory.dart';
9
import 'package:flutter_tools/src/base/logger.dart';
10
import 'package:flutter_tools/src/base/platform.dart';
11
import 'package:flutter_tools/src/base/process.dart';
12
import 'package:flutter_tools/src/base/time.dart';
13 14
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/version.dart';
15
import 'package:test/fake.dart';
16

17 18
import '../src/common.dart';
import '../src/context.dart';
19
import '../src/fake_process_manager.dart';
20
import '../src/fakes.dart' show FakeFlutterVersion;
21

22
final SystemClock _testClock = SystemClock.fixed(DateTime.utc(2015));
23 24
final DateTime _stampUpToDate = _testClock.ago(VersionFreshnessValidator.checkAgeConsideredUpToDate ~/ 2);
final DateTime _stampOutOfDate = _testClock.ago(VersionFreshnessValidator.checkAgeConsideredUpToDate * 2);
25 26

void main() {
27 28
  late FakeCache cache;
  late FakeProcessManager processManager;
29 30

  setUp(() {
31
    processManager = FakeProcessManager.empty();
32
    cache = FakeCache();
33
  });
34

35 36 37 38 39 40 41 42 43
  testUsingContext('Channel enum and string transform to each other', () {
    for (final Channel channel in Channel.values) {
      expect(getNameForChannel(channel), kOfficialChannels.toList()[channel.index]);
    }
    expect(kOfficialChannels.toList().map((String str) => getChannelForName(str)).toList(),
      Channel.values);
  });

  for (final String channel in kOfficialChannels) {
44
    DateTime getChannelUpToDateVersion() {
45
      return _testClock.ago(VersionFreshnessValidator.versionAgeConsideredUpToDate(channel) ~/ 2);
46
    }
47

48
    DateTime getChannelOutOfDateVersion() {
49
      return _testClock.ago(VersionFreshnessValidator.versionAgeConsideredUpToDate(channel) * 2);
50
    }
51

52
    group('$FlutterVersion for $channel', () {
53 54 55
      late FileSystem fs;
      const String flutterRoot = '/path/to/flutter';

56
      setUpAll(() {
57
        fs = MemoryFileSystem.test();
58
        Cache.disableLocking();
59
        VersionFreshnessValidator.timeToPauseToLetUserReadTheMessage = Duration.zero;
60
      });
61

62
      testUsingContext('prints nothing when Flutter installation looks fresh', () async {
63
        const String flutterUpstreamUrl = 'https://github.com/flutter/flutter.git';
64
        processManager.addCommands(<FakeCommand>[
65 66 67 68 69 70 71 72 73 74 75
          const FakeCommand(
            command: <String>['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%H'],
            stdout: '1234abcd',
          ),
          const FakeCommand(
            command: <String>['git', 'tag', '--points-at', '1234abcd'],
          ),
          const FakeCommand(
            command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'],
            stdout: '0.1.2-3-1234abcd',
          ),
76 77 78 79
          FakeCommand(
            command: const <String>['git', 'symbolic-ref', '--short', 'HEAD'],
            stdout: channel,
          ),
80
          FakeCommand(
81
            command: const <String>['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{upstream}'],
82 83 84 85 86 87 88
            stdout: 'origin/$channel',
          ),
          const FakeCommand(
            command: <String>['git', 'ls-remote', '--get-url', 'origin'],
            stdout: flutterUpstreamUrl,
          ),
          FakeCommand(
89
            command: const <String>['git', '-c', 'log.showSignature=false', 'log', 'HEAD', '-n', '1', '--pretty=format:%ad', '--date=iso'],
90 91 92
            stdout: getChannelUpToDateVersion().toString(),
          ),
          const FakeCommand(
93
            command: <String>['git', 'fetch', '--tags'],
94 95
          ),
          FakeCommand(
96
            command: const <String>['git', '-c', 'log.showSignature=false', 'log', '@{upstream}', '-n', '1', '--pretty=format:%ad', '--date=iso'],
97 98
            stdout: getChannelOutOfDateVersion().toString(),
          ),
99 100 101 102 103
          const FakeCommand(
            command: <String>['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%ar'],
            stdout: '1 second ago',
          ),
          FakeCommand(
104
            command: const <String>['git', '-c', 'log.showSignature=false', 'log', 'HEAD', '-n', '1', '--pretty=format:%ad', '--date=iso'],
105 106 107 108
            stdout: getChannelUpToDateVersion().toString(),
          ),
        ]);

109
        final FlutterVersion flutterVersion = FlutterVersion(clock: _testClock, fs: fs, flutterRoot: flutterRoot);
110 111
        await flutterVersion.checkFlutterVersionFreshness();
        expect(flutterVersion.channel, channel);
112
        expect(flutterVersion.repositoryUrl, flutterUpstreamUrl);
113 114 115 116 117
        expect(flutterVersion.frameworkRevision, '1234abcd');
        expect(flutterVersion.frameworkRevisionShort, '1234abcd');
        expect(flutterVersion.frameworkVersion, '0.0.0-unknown');
        expect(
          flutterVersion.toString(),
118
          'Flutter • channel $channel$flutterUpstreamUrl\n'
119
          'Framework • revision 1234abcd (1 second ago) • ${getChannelUpToDateVersion()}\n'
120
          'Engine • revision abcdefg\n'
121
          'Tools • Dart 2.12.0 • DevTools 2.8.0',
122 123 124 125 126 127 128
        );
        expect(flutterVersion.frameworkAge, '1 second ago');
        expect(flutterVersion.getVersionString(), '$channel/1234abcd');
        expect(flutterVersion.getBranchName(), channel);
        expect(flutterVersion.getVersionString(redactUnknownBranches: true), '$channel/1234abcd');
        expect(flutterVersion.getBranchName(redactUnknownBranches: true), channel);

129
        expect(testLogger.statusText, isEmpty);
130
        expect(processManager, hasNoRemainingExpectations);
131
      }, overrides: <Type, Generator>{
132
        ProcessManager: () => processManager,
133
        Cache: () => cache,
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 174 175 176 177 178 179
      testUsingContext('does not crash when git log outputs malformed output', () async {
        const String flutterUpstreamUrl = 'https://github.com/flutter/flutter.git';

        final String malformedGitLogOutput = '${getChannelUpToDateVersion()}[0x7FF9E2A75000] ANOMALY: meaningless REX prefix used';
        processManager.addCommands(<FakeCommand>[
          const FakeCommand(
            command: <String>['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%H'],
            stdout: '1234abcd',
          ),
          const FakeCommand(
            command: <String>['git', 'tag', '--points-at', '1234abcd'],
          ),
          const FakeCommand(
            command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'],
            stdout: '0.1.2-3-1234abcd',
          ),
          FakeCommand(
            command: const <String>['git', 'symbolic-ref', '--short', 'HEAD'],
            stdout: channel,
          ),
          FakeCommand(
            command: const <String>['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{upstream}'],
            stdout: 'origin/$channel',
          ),
          const FakeCommand(
            command: <String>['git', 'ls-remote', '--get-url', 'origin'],
            stdout: flutterUpstreamUrl,
          ),
          FakeCommand(
            command: const <String>['git', '-c', 'log.showSignature=false', 'log', 'HEAD', '-n', '1', '--pretty=format:%ad', '--date=iso'],
            stdout: malformedGitLogOutput,
          ),
        ]);

        final FlutterVersion flutterVersion = FlutterVersion(clock: _testClock, fs: fs, flutterRoot: flutterRoot);
        await flutterVersion.checkFlutterVersionFreshness();

        expect(testLogger.statusText, isEmpty);
        expect(processManager, hasNoRemainingExpectations);
      }, overrides: <Type, Generator>{
        ProcessManager: () => processManager,
        Cache: () => cache,
      });

180
      testWithoutContext('prints nothing when Flutter installation looks out-of-date but is actually up-to-date', () async {
181
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel);
182 183 184 185
        final BufferLogger logger = BufferLogger.test();
        final VersionCheckStamp stamp = VersionCheckStamp(
          lastTimeVersionWasChecked: _stampOutOfDate,
          lastKnownRemoteVersion: getChannelOutOfDateVersion(),
186
        );
187
        cache.versionStamp = json.encode(stamp);
188

189 190
        await VersionFreshnessValidator(
          version: flutterVersion,
191
          cache: cache,
192 193 194 195
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
          latestFlutterCommitDate: getChannelOutOfDateVersion(),
196
        ).run();
197

198
        expect(logger.statusText, isEmpty);
199 200
      });

201
      testWithoutContext('does not ping server when version stamp is up-to-date', () async {
202
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel);
203 204 205 206
        final BufferLogger logger = BufferLogger.test();
        final VersionCheckStamp stamp = VersionCheckStamp(
          lastTimeVersionWasChecked: _stampUpToDate,
          lastKnownRemoteVersion: getChannelUpToDateVersion(),
207
        );
208
        cache.versionStamp = json.encode(stamp);
209

210 211
        await VersionFreshnessValidator(
          version: flutterVersion,
212
          cache: cache,
213 214 215 216
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
          latestFlutterCommitDate: getChannelUpToDateVersion(),
217
        ).run();
218

219
        expect(logger.statusText, contains('A new version of Flutter is available!'));
220
        expect(cache.setVersionStamp, true);
221 222
      });

223
      testWithoutContext('does not print warning if printed recently', () async {
224
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel);
225 226 227 228 229
        final BufferLogger logger = BufferLogger.test();
        final VersionCheckStamp stamp = VersionCheckStamp(
          lastTimeVersionWasChecked: _stampUpToDate,
          lastKnownRemoteVersion: getChannelUpToDateVersion(),
          lastTimeWarningWasPrinted: _testClock.now(),
230
        );
231
        cache.versionStamp = json.encode(stamp);
232

233 234
        await VersionFreshnessValidator(
          version: flutterVersion,
235
          cache: cache,
236 237 238 239
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
          latestFlutterCommitDate: getChannelUpToDateVersion(),
240
        ).run();
241

242
        expect(logger.statusText, isEmpty);
243 244
      });

245
      testWithoutContext('pings server when version stamp is missing', () async {
246
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel);
247
        final BufferLogger logger = BufferLogger.test();
248
        cache.versionStamp = '{}';
249

250 251
        await VersionFreshnessValidator(
          version: flutterVersion,
252
          cache: cache,
253 254 255 256
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
          latestFlutterCommitDate: getChannelUpToDateVersion(),
257
        ).run();
258

259
        expect(logger.statusText, contains('A new version of Flutter is available!'));
260
        expect(cache.setVersionStamp, true);
261
      });
262

263
      testWithoutContext('pings server when version stamp is out-of-date', () async {
264
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel);
265 266
        final BufferLogger logger = BufferLogger.test();
        final VersionCheckStamp stamp = VersionCheckStamp(
267 268 269 270
          lastTimeVersionWasChecked: _stampOutOfDate,
          lastKnownRemoteVersion: _testClock.ago(const Duration(days: 2)),
        );
        cache.versionStamp = json.encode(stamp);
271

272 273
        await VersionFreshnessValidator(
          version: flutterVersion,
274
          cache: cache,
275 276 277 278
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
          latestFlutterCommitDate: getChannelUpToDateVersion(),
279
        ).run();
280

281
        expect(logger.statusText, contains('A new version of Flutter is available!'));
282 283
      });

284
      testWithoutContext('does not print warning when unable to connect to server if not out of date', () async {
285
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel);
286
        final BufferLogger logger = BufferLogger.test();
287
        cache.versionStamp = '{}';
288

289 290
        await VersionFreshnessValidator(
          version: flutterVersion,
291
          cache: cache,
292 293 294
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelUpToDateVersion(),
295 296
          // latestFlutterCommitDate defaults to null because we failed to get remote version
        ).run();
297

298
        expect(logger.statusText, isEmpty);
299 300
      });

301
      testWithoutContext('prints warning when unable to connect to server if really out of date', () async {
302
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(branch: channel);
303
        final BufferLogger logger = BufferLogger.test();
304
        final VersionCheckStamp stamp = VersionCheckStamp(
305 306 307 308
          lastTimeVersionWasChecked: _stampOutOfDate,
          lastKnownRemoteVersion: _testClock.ago(const Duration(days: 2)),
        );
        cache.versionStamp = json.encode(stamp);
309

310 311
        await VersionFreshnessValidator(
          version: flutterVersion,
312
          cache: cache,
313 314 315
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
316 317
          // latestFlutterCommitDate defaults to null because we failed to get remote version
        ).run();
318

319 320
        final Duration frameworkAge = _testClock.now().difference(getChannelOutOfDateVersion());
        expect(logger.statusText, contains('WARNING: your installation of Flutter is ${frameworkAge.inDays} days old.'));
321 322
      });

323
      group('$VersionCheckStamp for $channel', () {
324
        void expectDefault(VersionCheckStamp stamp) {
325 326 327 328 329 330
          expect(stamp.lastKnownRemoteVersion, isNull);
          expect(stamp.lastTimeVersionWasChecked, isNull);
          expect(stamp.lastTimeWarningWasPrinted, isNull);
        }

        testWithoutContext('loads blank when stamp file missing', () async {
331
          cache.versionStamp = null;
332

333
          expectDefault(await VersionCheckStamp.load(cache, BufferLogger.test()));
334 335 336
        });

        testWithoutContext('loads blank when stamp file is malformed JSON', () async {
337
          cache.versionStamp = '<';
338

339
          expectDefault(await VersionCheckStamp.load(cache, BufferLogger.test()));
340 341 342
        });

        testWithoutContext('loads blank when stamp file is well-formed but invalid JSON', () async {
343
          cache.versionStamp = '[]';
344

345
          expectDefault(await VersionCheckStamp.load(cache, BufferLogger.test()));
346 347 348 349 350 351 352 353 354 355
        });

        testWithoutContext('loads valid JSON', () async {
          final String value = '''
        {
          "lastKnownRemoteVersion": "${_testClock.ago(const Duration(days: 1))}",
          "lastTimeVersionWasChecked": "${_testClock.ago(const Duration(days: 2))}",
          "lastTimeWarningWasPrinted": "${_testClock.now()}"
        }
        ''';
356
          cache.versionStamp = value;
357

358
          final VersionCheckStamp stamp = await VersionCheckStamp.load(cache, BufferLogger.test());
359 360 361 362 363

          expect(stamp.lastKnownRemoteVersion, _testClock.ago(const Duration(days: 1)));
          expect(stamp.lastTimeVersionWasChecked, _testClock.ago(const Duration(days: 2)));
          expect(stamp.lastTimeWarningWasPrinted, _testClock.now());
        });
364
      });
365
    });
366
  }
367

368 369 370 371
    group('VersionUpstreamValidator', () {
      const String flutterStandardUrlDotGit = 'https://github.com/flutter/flutter.git';
      const String flutterNonStandardUrlDotGit = 'https://githubmirror.com/flutter/flutter.git';
      const String flutterStandardSshUrlDotGit = 'git@github.com:flutter/flutter.git';
372
      const String flutterFullSshUrlDotGit = 'ssh://git@github.com/flutter/flutter.git';
373

374 375 376
      VersionCheckError? runUpstreamValidator({
        String? versionUpstreamUrl,
        String? flutterGitUrl,
377 378 379 380 381
      }){
        final Platform testPlatform = FakePlatform(environment: <String, String> {
          if (flutterGitUrl != null) 'FLUTTER_GIT_URL': flutterGitUrl,
        });
        return VersionUpstreamValidator(
382
          version: FakeFlutterVersion(repositoryUrl: versionUpstreamUrl),
383 384 385 386 387 388 389
          platform: testPlatform,
        ).run();
      }

      testWithoutContext('returns error if repository url is null', () {
        final VersionCheckError error = runUpstreamValidator(
          // repositoryUrl is null by default
390
        )!;
391 392 393 394 395 396 397 398 399 400 401 402
        expect(error, isNotNull);
        expect(
          error.message,
          contains('The tool could not determine the remote upstream which is being tracked by the SDK.'),
        );
      });

      testWithoutContext('does not return error at standard remote url with FLUTTER_GIT_URL unset', () {
        expect(runUpstreamValidator(versionUpstreamUrl: flutterStandardUrlDotGit), isNull);
      });

      testWithoutContext('returns error at non-standard remote url with FLUTTER_GIT_URL unset', () {
403
        final VersionCheckError error = runUpstreamValidator(versionUpstreamUrl: flutterNonStandardUrlDotGit)!;
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
        expect(error, isNotNull);
        expect(
          error.message,
          contains(
            'The Flutter SDK is tracking a non-standard remote "$flutterNonStandardUrlDotGit".\n'
            'Set the environment variable "FLUTTER_GIT_URL" to "$flutterNonStandardUrlDotGit". '
            'If this is intentional, it is recommended to use "git" directly to manage the SDK.'
          ),
        );
      });

      testWithoutContext('does not return error at non-standard remote url with FLUTTER_GIT_URL set', () {
        expect(runUpstreamValidator(
          versionUpstreamUrl: flutterNonStandardUrlDotGit,
          flutterGitUrl: flutterNonStandardUrlDotGit,
        ), isNull);
      });

422
      testWithoutContext('respects FLUTTER_GIT_URL even if upstream remote url is standard', () {
423
        final VersionCheckError error = runUpstreamValidator(
424 425
            versionUpstreamUrl: flutterStandardUrlDotGit,
            flutterGitUrl: flutterNonStandardUrlDotGit,
426
        )!;
427 428 429 430
        expect(error, isNotNull);
        expect(
          error.message,
          contains(
431 432
            'The Flutter SDK is tracking "$flutterStandardUrlDotGit" but "FLUTTER_GIT_URL" is set to "$flutterNonStandardUrlDotGit".\n'
            'Either remove "FLUTTER_GIT_URL" from the environment or set it to "$flutterStandardUrlDotGit". '
433 434 435 436 437 438 439 440 441
            'If this is intentional, it is recommended to use "git" directly to manage the SDK.'
          ),
        );
      });

      testWithoutContext('does not return error at standard ssh url with FLUTTER_GIT_URL unset', () {
        expect(runUpstreamValidator(versionUpstreamUrl: flutterStandardSshUrlDotGit), isNull);
      });

442 443 444 445
      testWithoutContext('does not return error at full ssh url with FLUTTER_GIT_URL unset', () {
        expect(runUpstreamValidator(versionUpstreamUrl: flutterFullSshUrlDotGit), isNull);
      });

446 447 448 449 450 451 452 453 454 455
      testWithoutContext('stripDotGit removes ".git" suffix if any', () {
        expect(VersionUpstreamValidator.stripDotGit('https://github.com/flutter/flutter.git'), 'https://github.com/flutter/flutter');
        expect(VersionUpstreamValidator.stripDotGit('https://github.com/flutter/flutter'), 'https://github.com/flutter/flutter');
        expect(VersionUpstreamValidator.stripDotGit('git@github.com:flutter/flutter.git'), 'git@github.com:flutter/flutter');
        expect(VersionUpstreamValidator.stripDotGit('git@github.com:flutter/flutter'), 'git@github.com:flutter/flutter');
        expect(VersionUpstreamValidator.stripDotGit('https://githubmirror.com/flutter/flutter.git.git'), 'https://githubmirror.com/flutter/flutter.git');
        expect(VersionUpstreamValidator.stripDotGit('https://githubmirror.com/flutter/flutter.gitgit'), 'https://githubmirror.com/flutter/flutter.gitgit');
      });
    });

456 457 458 459 460 461 462 463 464 465 466 467 468 469
  testUsingContext('version handles unknown branch', () async {
    processManager.addCommands(<FakeCommand>[
      const FakeCommand(
        command: <String>['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%H'],
        stdout: '1234abcd',
      ),
      const FakeCommand(
        command: <String>['git', 'tag', '--points-at', '1234abcd'],
      ),
      const FakeCommand(
        command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'],
        stdout: '0.1.2-3-1234abcd',
      ),
      const FakeCommand(
470
        command: <String>['git', 'symbolic-ref', '--short', 'HEAD'],
471 472 473 474
        stdout: 'feature-branch',
      ),
    ]);

475 476 477 478 479 480
    final MemoryFileSystem fs = MemoryFileSystem.test();
    final FlutterVersion flutterVersion = FlutterVersion(
      clock: _testClock,
      fs: fs,
      flutterRoot: '/path/to/flutter',
    );
481
    expect(flutterVersion.channel, '[user-branch]');
482 483 484 485
    expect(flutterVersion.getVersionString(), 'feature-branch/1234abcd');
    expect(flutterVersion.getBranchName(), 'feature-branch');
    expect(flutterVersion.getVersionString(redactUnknownBranches: true), '[user-branch]/1234abcd');
    expect(flutterVersion.getBranchName(redactUnknownBranches: true), '[user-branch]');
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600

    expect(processManager, hasNoRemainingExpectations);
  }, overrides: <Type, Generator>{
    ProcessManager: () => processManager,
    Cache: () => cache,
  });

  testUsingContext('ensureVersionFile() writes version information to disk', () async {
    processManager.addCommands(<FakeCommand>[
      const FakeCommand(
        command: <String>['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%H'],
        stdout: '1234abcd',
      ),
      const FakeCommand(
        command: <String>['git', 'tag', '--points-at', '1234abcd'],
      ),
      const FakeCommand(
        command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'],
        stdout: '0.1.2-3-1234abcd',
      ),
      const FakeCommand(
        command: <String>['git', 'symbolic-ref', '--short', 'HEAD'],
        stdout: 'feature-branch',
      ),
      const FakeCommand(
        command: <String>['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{upstream}'],
      ),
      FakeCommand(
        command: const <String>[
          'git',
          '-c',
          'log.showSignature=false',
          'log',
          'HEAD',
          '-n',
          '1',
          '--pretty=format:%ad',
          '--date=iso',
        ],
        stdout: _testClock.ago(VersionFreshnessValidator.versionAgeConsideredUpToDate('stable') ~/ 2).toString(),
      ),
    ]);

    final MemoryFileSystem fs = MemoryFileSystem.test();
    final Directory flutterRoot = fs.directory('/path/to/flutter');
    flutterRoot.childDirectory('bin').childDirectory('cache').createSync(recursive: true);
    final FlutterVersion flutterVersion = FlutterVersion(
      clock: _testClock,
      fs: fs,
      flutterRoot: flutterRoot.path,
    );

    final File versionFile = fs.file('/path/to/flutter/bin/cache/flutter.version.json');
    expect(versionFile.existsSync(), isFalse);

    flutterVersion.ensureVersionFile();
    expect(versionFile.existsSync(), isTrue);
    expect(versionFile.readAsStringSync(), '''
{
  "frameworkVersion": "0.0.0-unknown",
  "channel": "[user-branch]",
  "repositoryUrl": "unknown source",
  "frameworkRevision": "1234abcd",
  "frameworkCommitDate": "2014-10-02 00:00:00.000Z",
  "engineRevision": "abcdefg",
  "dartSdkVersion": "2.12.0",
  "devToolsVersion": "2.8.0",
  "flutterVersion": "0.0.0-unknown"
}''');
    expect(processManager, hasNoRemainingExpectations);
  }, overrides: <Type, Generator>{
    ProcessManager: () => processManager,
    Cache: () => cache,
  });

  testUsingContext('version does not call git if a .version.json file exists', () async {
    final MemoryFileSystem fs = MemoryFileSystem.test();
    final Directory flutterRoot = fs.directory('/path/to/flutter');
    final Directory cacheDir = flutterRoot
        .childDirectory('bin')
        .childDirectory('cache')
        ..createSync(recursive: true);
    const String devToolsVersion = '0000000';
    const Map<String, Object> versionJson = <String, Object>{
      'channel': 'stable',
      'frameworkVersion': '1.2.3',
      'repositoryUrl': 'https://github.com/flutter/flutter.git',
      'frameworkRevision': '1234abcd',
      'frameworkCommitDate': '2023-04-28 12:34:56 -0400',
      'engineRevision': 'deadbeef',
      'dartSdkVersion': 'deadbeef2',
      'devToolsVersion': devToolsVersion,
      'flutterVersion': 'foo',
    };
    cacheDir.childFile('flutter.version.json').writeAsStringSync(
      jsonEncode(versionJson),
    );
    final FlutterVersion flutterVersion = FlutterVersion(
      clock: _testClock,
      fs: fs,
      flutterRoot: flutterRoot.path,
    );
    expect(flutterVersion.channel, 'stable');
    expect(flutterVersion.getVersionString(), 'stable/1.2.3');
    expect(flutterVersion.getBranchName(), 'stable');
    expect(flutterVersion.dartSdkVersion, 'deadbeef2');
    expect(flutterVersion.devToolsVersion, devToolsVersion);
    expect(flutterVersion.engineRevision, 'deadbeef');

    expect(processManager, hasNoRemainingExpectations);
  }, overrides: <Type, Generator>{
    ProcessManager: () => processManager,
    Cache: () => cache,
  });

601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637
  testUsingContext('_FlutterVersionFromFile.ensureVersionFile ensures legacy version file exists', () async {
    final MemoryFileSystem fs = MemoryFileSystem.test();
    final Directory flutterRoot = fs.directory('/path/to/flutter');
    final Directory cacheDir = flutterRoot
        .childDirectory('bin')
        .childDirectory('cache')
        ..createSync(recursive: true);
    const String devToolsVersion = '0000000';
    final File legacyVersionFile = flutterRoot.childFile('version');
    const Map<String, Object> versionJson = <String, Object>{
      'channel': 'stable',
      'frameworkVersion': '1.2.3',
      'repositoryUrl': 'https://github.com/flutter/flutter.git',
      'frameworkRevision': '1234abcd',
      'frameworkCommitDate': '2023-04-28 12:34:56 -0400',
      'engineRevision': 'deadbeef',
      'dartSdkVersion': 'deadbeef2',
      'devToolsVersion': devToolsVersion,
      'flutterVersion': 'foo',
    };
    cacheDir.childFile('flutter.version.json').writeAsStringSync(
      jsonEncode(versionJson),
    );
    expect(legacyVersionFile.existsSync(), isFalse);
    final FlutterVersion flutterVersion = FlutterVersion(
      clock: _testClock,
      fs: fs,
      flutterRoot: flutterRoot.path,
    );
    flutterVersion.ensureVersionFile();
    expect(legacyVersionFile.existsSync(), isTrue);
    expect(legacyVersionFile.readAsStringSync(), '1.2.3');
  }, overrides: <Type, Generator>{
    ProcessManager: () => processManager,
    Cache: () => cache,
  });

638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698
  testUsingContext('FlutterVersion() falls back to git if .version.json is malformed', () async {
    final MemoryFileSystem fs = MemoryFileSystem.test();
    final Directory flutterRoot = fs.directory(fs.path.join('path', 'to', 'flutter'));
    final Directory cacheDir = flutterRoot
        .childDirectory('bin')
        .childDirectory('cache')
        ..createSync(recursive: true);
    final File legacyVersionFile = flutterRoot.childFile('version');
    final File versionFile = cacheDir.childFile('flutter.version.json')..writeAsStringSync(
      '{',
    );

    processManager.addCommands(<FakeCommand>[
      const FakeCommand(
        command: <String>['git', '-c', 'log.showSignature=false', 'log', '-n', '1', '--pretty=format:%H'],
        stdout: '1234abcd',
      ),
      const FakeCommand(
        command: <String>['git', 'tag', '--points-at', '1234abcd'],
      ),
      const FakeCommand(
        command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', '1234abcd'],
        stdout: '0.1.2-3-1234abcd',
      ),
      const FakeCommand(
        command: <String>['git', 'symbolic-ref', '--short', 'HEAD'],
        stdout: 'feature-branch',
      ),
      const FakeCommand(
        command: <String>['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{upstream}'],
        stdout: 'feature-branch',
      ),
      FakeCommand(
        command: const <String>[
          'git',
          '-c',
          'log.showSignature=false',
          'log',
          'HEAD',
          '-n',
          '1',
          '--pretty=format:%ad',
          '--date=iso',
        ],
        stdout: _testClock.ago(VersionFreshnessValidator.versionAgeConsideredUpToDate('stable') ~/ 2).toString(),
      ),
    ]);

    // version file exists in a malformed state
    expect(versionFile.existsSync(), isTrue);
    final FlutterVersion flutterVersion = FlutterVersion(
      clock: _testClock,
      fs: fs,
      flutterRoot: flutterRoot.path,
    );

    // version file was deleted because it couldn't be parsed
    expect(versionFile.existsSync(), isFalse);
    expect(legacyVersionFile.existsSync(), isFalse);
    // version file was written to disk
    flutterVersion.ensureVersionFile();
699
    expect(processManager, hasNoRemainingExpectations);
700 701
    expect(versionFile.existsSync(), isTrue);
    expect(legacyVersionFile.existsSync(), isTrue);
702 703
  }, overrides: <Type, Generator>{
    ProcessManager: () => processManager,
704
    Cache: () => cache,
705 706
  });

707 708
  testUsingContext('GitTagVersion', () {
    const String hash = 'abcdef';
709 710
    GitTagVersion gitTagVersion;

711
    // Master channel
712 713 714
    gitTagVersion = GitTagVersion.parse('1.2.0-4.5.pre-13-g$hash');
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.0-5.0.pre.13');
    expect(gitTagVersion.gitTag, '1.2.0-4.5.pre');
715 716 717
    expect(gitTagVersion.devVersion, 4);
    expect(gitTagVersion.devPatch, 5);

718 719 720 721 722 723 724 725 726
    // Stable channel
    gitTagVersion = GitTagVersion.parse('1.2.3');
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.3');
    expect(gitTagVersion.x, 1);
    expect(gitTagVersion.y, 2);
    expect(gitTagVersion.z, 3);
    expect(gitTagVersion.devVersion, null);
    expect(gitTagVersion.devPatch, null);

727
    // Beta channel
728 729
    gitTagVersion = GitTagVersion.parse('1.2.3-4.5.pre');
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.3-4.5.pre');
730 731 732 733 734
    expect(gitTagVersion.gitTag, '1.2.3-4.5.pre');
    expect(gitTagVersion.devVersion, 4);
    expect(gitTagVersion.devPatch, 5);

    gitTagVersion = GitTagVersion.parse('1.2.3-13-g$hash');
735
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.4-0.0.pre.13');
736
    expect(gitTagVersion.gitTag, '1.2.3');
737 738 739
    expect(gitTagVersion.devVersion, null);
    expect(gitTagVersion.devPatch, null);

740
    // new tag release format, beta channel
741 742 743
    gitTagVersion = GitTagVersion.parse('1.2.3-4.5.pre-0-g$hash');
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.3-4.5.pre');
    expect(gitTagVersion.gitTag, '1.2.3-4.5.pre');
744 745 746
    expect(gitTagVersion.devVersion, 4);
    expect(gitTagVersion.devPatch, 5);

747
    // new tag release format, stable channel
748
    gitTagVersion = GitTagVersion.parse('1.2.3-13-g$hash');
749
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.4-0.0.pre.13');
750
    expect(gitTagVersion.gitTag, '1.2.3');
751 752 753
    expect(gitTagVersion.devVersion, null);
    expect(gitTagVersion.devPatch, null);

754
    expect(GitTagVersion.parse('98.76.54-32-g$hash').frameworkVersionFor(hash), '98.76.55-0.0.pre.32');
755
    expect(GitTagVersion.parse('10.20.30-0-g$hash').frameworkVersionFor(hash), '10.20.30');
756
    expect(testLogger.traceText, '');
757
    expect(GitTagVersion.parse('v1.2.3+hotfix.1-4-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
758
    expect(GitTagVersion.parse('x1.2.3-4-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
759
    expect(GitTagVersion.parse('1.0.0-unknown-0-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
760
    expect(GitTagVersion.parse('beta-1-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
761
    expect(GitTagVersion.parse('1.2.3-4-gx$hash').frameworkVersionFor(hash), '0.0.0-unknown');
762 763
    expect(testLogger.statusText, '');
    expect(testLogger.errorText, '');
764 765
    expect(
      testLogger.traceText,
766
      'Could not interpret results of "git describe": v1.2.3+hotfix.1-4-gabcdef\n'
767
      'Could not interpret results of "git describe": x1.2.3-4-gabcdef\n'
768
      'Could not interpret results of "git describe": 1.0.0-unknown-0-gabcdef\n'
769
      'Could not interpret results of "git describe": beta-1-gabcdef\n'
770
      'Could not interpret results of "git describe": 1.2.3-4-gxabcdef\n',
771 772
    );
  });
773

774 775 776 777 778 779 780 781 782 783 784 785 786 787
  testUsingContext('determine reports correct stable version if HEAD is at a tag', () {
    const String stableTag = '1.2.3';
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(
      <FakeCommand>[
        const FakeCommand(
          command: <String>['git', 'tag', '--points-at', 'HEAD'],
          stdout: stableTag,
        ),
      ],
    );
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
788 789
    final FakePlatform platform = FakePlatform();
    final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, platform, workingDirectory: '.');
790 791 792
    expect(gitTagVersion.frameworkVersionFor('abcd1234'), stableTag);
  });

793
  testUsingContext('determine favors stable tag over beta tag if both identify HEAD', () {
794 795 796 797 798
    const String stableTag = '1.2.3';
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(
      <FakeCommand>[
        const FakeCommand(
          command: <String>['git', 'tag', '--points-at', 'HEAD'],
799
          // This tests the unlikely edge case where a beta release made it to stable without any cherry picks
800 801 802 803 804 805 806 807
          stdout: '1.2.3-6.0.pre\n$stableTag',
        ),
      ],
    );
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
808 809 810
    final FakePlatform platform = FakePlatform();

    final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, platform, workingDirectory: '.');
811 812 813 814
    expect(gitTagVersion.frameworkVersionFor('abcd1234'), stableTag);
  });

  testUsingContext('determine reports correct git describe version if HEAD is not at a tag', () {
815
    const String devTag = '1.2.0-2.0.pre';
816 817 818 819 820 821
    const String headRevision = 'abcd1234';
    const String commitsAhead = '12';
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(
      <FakeCommand>[
        const FakeCommand(
          command: <String>['git', 'tag', '--points-at', 'HEAD'],
822
          // no output, since there's no tag
823 824
        ),
        const FakeCommand(
825
          command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
826 827 828 829 830 831 832 833
          stdout: '$devTag-$commitsAhead-g$headRevision',
        ),
      ],
    );
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
834 835 836
    final FakePlatform platform = FakePlatform();

    final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, platform, workingDirectory: '.');
837 838
    // reported version should increment the m
    expect(gitTagVersion.frameworkVersionFor(headRevision), '1.2.0-3.0.pre.12');
839 840
  });

841
  testUsingContext('determine does not call fetch --tags', () {
842 843 844 845 846 847 848 849 850 851 852 853 854
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(
        command: <String>['git', 'tag', '--points-at', 'HEAD'],
      ),
      const FakeCommand(
        command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
        stdout: 'v0.1.2-3-1234abcd',
      ),
    ]);
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
855
    final FakePlatform platform = FakePlatform();
856

857
    GitTagVersion.determine(processUtils, platform, workingDirectory: '.');
858
    expect(fakeProcessManager, hasNoRemainingExpectations);
859 860
  });

861
  testUsingContext('determine does not fetch tags on beta', () {
862 863
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(
864 865
        command: <String>['git', 'symbolic-ref', '--short', 'HEAD'],
        stdout: 'beta',
866 867 868 869 870 871 872 873 874 875 876 877 878
      ),
      const FakeCommand(
        command: <String>['git', 'tag', '--points-at', 'HEAD'],
      ),
      const FakeCommand(
        command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
        stdout: 'v0.1.2-3-1234abcd',
      ),
    ]);
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
879
    final FakePlatform platform = FakePlatform();
880

881
    GitTagVersion.determine(processUtils, platform, workingDirectory: '.', fetchTags: true);
882
    expect(fakeProcessManager, hasNoRemainingExpectations);
883 884 885
  });

  testUsingContext('determine calls fetch --tags on master', () {
886 887
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(
888
        command: <String>['git', 'symbolic-ref', '--short', 'HEAD'],
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905
        stdout: 'master',
      ),
      const FakeCommand(
        command: <String>['git', 'fetch', 'https://github.com/flutter/flutter.git', '--tags', '-f'],
      ),
      const FakeCommand(
        command: <String>['git', 'tag', '--points-at', 'HEAD'],
      ),
      const FakeCommand(
        command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
        stdout: 'v0.1.2-3-1234abcd',
      ),
    ]);
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
906
    final FakePlatform platform = FakePlatform();
907

908
    GitTagVersion.determine(processUtils, platform, workingDirectory: '.', fetchTags: true);
909
    expect(fakeProcessManager, hasNoRemainingExpectations);
910
  });
911 912

  testUsingContext('determine uses overridden git url', () {
913 914
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(
915
        command: <String>['git', 'symbolic-ref', '--short', 'HEAD'],
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932
        stdout: 'master',
      ),
      const FakeCommand(
        command: <String>['git', 'fetch', 'https://githubmirror.com/flutter.git', '--tags', '-f'],
      ),
      const FakeCommand(
        command: <String>['git', 'tag', '--points-at', 'HEAD'],
      ),
      const FakeCommand(
        command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
        stdout: 'v0.1.2-3-1234abcd',
      ),
    ]);
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
933 934 935
    final FakePlatform platform = FakePlatform(
      environment: <String, String> {'FLUTTER_GIT_URL': 'https://githubmirror.com/flutter.git'},
    );
936

937
    GitTagVersion.determine(processUtils, platform, workingDirectory: '.', fetchTags: true);
938
    expect(fakeProcessManager, hasNoRemainingExpectations);
939
  });
940 941
}

942
class FakeCache extends Fake implements Cache {
943
  String? versionStamp;
944 945 946 947 948
  bool setVersionStamp = false;

  @override
  String get engineRevision => 'abcdefg';

949 950 951
  @override
  String get devToolsVersion => '2.8.0';

952 953 954 955 956 957 958
  @override
  String get dartSdkVersion => '2.12.0';

  @override
  void checkLockAcquired() { }

  @override
959
  String? getStampFor(String artifactName) {
960 961 962 963 964 965 966 967 968 969 970 971 972
    if (artifactName == VersionCheckStamp.flutterVersionCheckStampFile) {
      return versionStamp;
    }
    return null;
  }

  @override
  void setStampFor(String artifactName, String version) {
    if (artifactName == VersionCheckStamp.flutterVersionCheckStampFile) {
      setVersionStamp = true;
    }
  }
}