version_test.dart 29.1 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
import 'package:flutter_tools/src/base/logger.dart';
8
import 'package:flutter_tools/src/base/platform.dart';
9
import 'package:flutter_tools/src/base/process.dart';
10
import 'package:flutter_tools/src/base/time.dart';
11
import 'package:flutter_tools/src/cache.dart';
12
import 'package:flutter_tools/src/globals.dart' as globals;
13
import 'package:flutter_tools/src/version.dart';
14
import 'package:test/fake.dart';
15

16 17
import '../src/common.dart';
import '../src/context.dart';
18
import '../src/fake_process_manager.dart';
19

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

void main() {
25 26
  late FakeCache cache;
  late FakeProcessManager processManager;
27 28

  setUp(() {
29
    processManager = FakeProcessManager.empty();
30
    cache = FakeCache();
31
  });
32

33 34 35 36 37 38 39 40 41
  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) {
42
    DateTime getChannelUpToDateVersion() {
43
      return _testClock.ago(VersionFreshnessValidator.versionAgeConsideredUpToDate(channel) ~/ 2);
44
    }
45

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

50 51 52
    group('$FlutterVersion for $channel', () {
      setUpAll(() {
        Cache.disableLocking();
53
        VersionFreshnessValidator.timeToPauseToLetUserReadTheMessage = Duration.zero;
54
      });
55

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

        final FlutterVersion flutterVersion = globals.flutterVersion;
        await flutterVersion.checkFlutterVersionFreshness();
        expect(flutterVersion.channel, channel);
106
        expect(flutterVersion.repositoryUrl, flutterUpstreamUrl);
107 108 109 110 111
        expect(flutterVersion.frameworkRevision, '1234abcd');
        expect(flutterVersion.frameworkRevisionShort, '1234abcd');
        expect(flutterVersion.frameworkVersion, '0.0.0-unknown');
        expect(
          flutterVersion.toString(),
112
          'Flutter • channel $channel$flutterUpstreamUrl\n'
113
          'Framework • revision 1234abcd (1 second ago) • ${getChannelUpToDateVersion()}\n'
114
          'Engine • revision abcdefg\n'
115
          'Tools • Dart 2.12.0 • DevTools 2.8.0',
116 117 118 119 120 121 122
        );
        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);

123
        expect(testLogger.statusText, isEmpty);
124
        expect(processManager.hasRemainingExpectations, isFalse);
125
      }, overrides: <Type, Generator>{
126
        FlutterVersion: () => FlutterVersion(clock: _testClock),
127
        ProcessManager: () => processManager,
128
        Cache: () => cache,
129 130
      });

131
      testWithoutContext('prints nothing when Flutter installation looks out-of-date but is actually up-to-date', () async {
132
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(channel: channel);
133 134 135 136
        final BufferLogger logger = BufferLogger.test();
        final VersionCheckStamp stamp = VersionCheckStamp(
          lastTimeVersionWasChecked: _stampOutOfDate,
          lastKnownRemoteVersion: getChannelOutOfDateVersion(),
137
        );
138
        cache.versionStamp = json.encode(stamp);
139

140 141
        await VersionFreshnessValidator(
          version: flutterVersion,
142
          cache: cache,
143 144 145 146
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
          latestFlutterCommitDate: getChannelOutOfDateVersion(),
147
        ).run();
148

149
        expect(logger.statusText, isEmpty);
150 151
      });

152
      testWithoutContext('does not ping server when version stamp is up-to-date', () async {
153
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(channel: channel);
154 155 156 157
        final BufferLogger logger = BufferLogger.test();
        final VersionCheckStamp stamp = VersionCheckStamp(
          lastTimeVersionWasChecked: _stampUpToDate,
          lastKnownRemoteVersion: getChannelUpToDateVersion(),
158
        );
159
        cache.versionStamp = json.encode(stamp);
160

161 162
        await VersionFreshnessValidator(
          version: flutterVersion,
163
          cache: cache,
164 165 166 167
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
          latestFlutterCommitDate: getChannelUpToDateVersion(),
168
        ).run();
169

170
        expect(logger.statusText, contains('A new version of Flutter is available!'));
171
        expect(cache.setVersionStamp, true);
172 173
      });

174
      testWithoutContext('does not print warning if printed recently', () async {
175
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(channel: channel);
176 177 178 179 180
        final BufferLogger logger = BufferLogger.test();
        final VersionCheckStamp stamp = VersionCheckStamp(
          lastTimeVersionWasChecked: _stampUpToDate,
          lastKnownRemoteVersion: getChannelUpToDateVersion(),
          lastTimeWarningWasPrinted: _testClock.now(),
181
        );
182
        cache.versionStamp = json.encode(stamp);
183

184 185
        await VersionFreshnessValidator(
          version: flutterVersion,
186
          cache: cache,
187 188 189 190
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
          latestFlutterCommitDate: getChannelUpToDateVersion(),
191
        ).run();
192

193
        expect(logger.statusText, isEmpty);
194 195
      });

196
      testWithoutContext('pings server when version stamp is missing', () async {
197
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(channel: channel);
198
        final BufferLogger logger = BufferLogger.test();
199
        cache.versionStamp = '{}';
200

201 202
        await VersionFreshnessValidator(
          version: flutterVersion,
203
          cache: cache,
204 205 206 207
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
          latestFlutterCommitDate: getChannelUpToDateVersion(),
208
        ).run();
209

210
        expect(logger.statusText, contains('A new version of Flutter is available!'));
211
        expect(cache.setVersionStamp, true);
212
      });
213

214
      testWithoutContext('pings server when version stamp is out-of-date', () async {
215
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(channel: channel);
216 217
        final BufferLogger logger = BufferLogger.test();
        final VersionCheckStamp stamp = VersionCheckStamp(
218 219 220 221
          lastTimeVersionWasChecked: _stampOutOfDate,
          lastKnownRemoteVersion: _testClock.ago(const Duration(days: 2)),
        );
        cache.versionStamp = json.encode(stamp);
222

223 224
        await VersionFreshnessValidator(
          version: flutterVersion,
225
          cache: cache,
226 227 228 229
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
          latestFlutterCommitDate: getChannelUpToDateVersion(),
230
        ).run();
231

232
        expect(logger.statusText, contains('A new version of Flutter is available!'));
233 234
      });

235
      testWithoutContext('does not print warning when unable to connect to server if not out of date', () async {
236
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(channel: channel);
237
        final BufferLogger logger = BufferLogger.test();
238
        cache.versionStamp = '{}';
239

240 241
        await VersionFreshnessValidator(
          version: flutterVersion,
242
          cache: cache,
243 244 245
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelUpToDateVersion(),
246 247
          // latestFlutterCommitDate defaults to null because we failed to get remote version
        ).run();
248

249
        expect(logger.statusText, isEmpty);
250 251
      });

252
      testWithoutContext('prints warning when unable to connect to server if really out of date', () async {
253
        final FakeFlutterVersion flutterVersion = FakeFlutterVersion(channel: channel);
254
        final BufferLogger logger = BufferLogger.test();
255
        final VersionCheckStamp stamp = VersionCheckStamp(
256 257 258 259
          lastTimeVersionWasChecked: _stampOutOfDate,
          lastKnownRemoteVersion: _testClock.ago(const Duration(days: 2)),
        );
        cache.versionStamp = json.encode(stamp);
260

261 262
        await VersionFreshnessValidator(
          version: flutterVersion,
263
          cache: cache,
264 265 266
          clock: _testClock,
          logger: logger,
          localFrameworkCommitDate: getChannelOutOfDateVersion(),
267 268
          // latestFlutterCommitDate defaults to null because we failed to get remote version
        ).run();
269

270 271
        final Duration frameworkAge = _testClock.now().difference(getChannelOutOfDateVersion());
        expect(logger.statusText, contains('WARNING: your installation of Flutter is ${frameworkAge.inDays} days old.'));
272 273
      });

274
      group('$VersionCheckStamp for $channel', () {
275
        void expectDefault(VersionCheckStamp stamp) {
276 277 278 279 280 281
          expect(stamp.lastKnownRemoteVersion, isNull);
          expect(stamp.lastTimeVersionWasChecked, isNull);
          expect(stamp.lastTimeWarningWasPrinted, isNull);
        }

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

284
          expectDefault(await VersionCheckStamp.load(cache, BufferLogger.test()));
285 286 287
        });

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

290
          expectDefault(await VersionCheckStamp.load(cache, BufferLogger.test()));
291 292 293
        });

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

296
          expectDefault(await VersionCheckStamp.load(cache, BufferLogger.test()));
297 298 299 300 301 302 303 304 305 306
        });

        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()}"
        }
        ''';
307
          cache.versionStamp = value;
308

309
          final VersionCheckStamp stamp = await VersionCheckStamp.load(cache, BufferLogger.test());
310 311 312 313 314

          expect(stamp.lastKnownRemoteVersion, _testClock.ago(const Duration(days: 1)));
          expect(stamp.lastTimeVersionWasChecked, _testClock.ago(const Duration(days: 2)));
          expect(stamp.lastTimeWarningWasPrinted, _testClock.now());
        });
315
      });
316
    });
317
  }
318

319 320 321 322 323
    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';

324 325 326
      VersionCheckError? runUpstreamValidator({
        String? versionUpstreamUrl,
        String? flutterGitUrl,
327 328 329 330 331
      }){
        final Platform testPlatform = FakePlatform(environment: <String, String> {
          if (flutterGitUrl != null) 'FLUTTER_GIT_URL': flutterGitUrl,
        });
        return VersionUpstreamValidator(
332
          version: FakeFlutterVersion(repositoryUrl: versionUpstreamUrl, channel: 'master'),
333 334 335 336 337 338 339
          platform: testPlatform,
        ).run();
      }

      testWithoutContext('returns error if repository url is null', () {
        final VersionCheckError error = runUpstreamValidator(
          // repositoryUrl is null by default
340
        )!;
341 342 343 344 345 346 347 348 349 350 351 352
        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', () {
353
        final VersionCheckError error = runUpstreamValidator(versionUpstreamUrl: flutterNonStandardUrlDotGit)!;
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
        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);
      });

372
      testWithoutContext('respects FLUTTER_GIT_URL even if upstream remote url is standard', () {
373
        final VersionCheckError error = runUpstreamValidator(
374 375
            versionUpstreamUrl: flutterStandardUrlDotGit,
            flutterGitUrl: flutterNonStandardUrlDotGit,
376
        )!;
377 378 379 380
        expect(error, isNotNull);
        expect(
          error.message,
          contains(
381 382
            '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". '
383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
            '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);
      });

      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');
      });
    });

402 403 404 405 406 407 408 409 410 411 412 413 414 415
  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(
416
        command: <String>['git', 'rev-parse', '--abbrev-ref', '--symbolic', '@{upstream}'],
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434
        stdout: 'feature-branch',
      ),
      const FakeCommand(
        command: <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
        stdout: 'feature-branch',
      ),
    ]);

    final FlutterVersion flutterVersion = globals.flutterVersion;
    expect(flutterVersion.channel, 'feature-branch');
    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]');
    expect(processManager.hasRemainingExpectations, isFalse);
  }, overrides: <Type, Generator>{
    FlutterVersion: () => FlutterVersion(clock: _testClock),
    ProcessManager: () => processManager,
435
    Cache: () => cache,
436 437
  });

438 439
  testUsingContext('GitTagVersion', () {
    const String hash = 'abcdef';
440 441
    GitTagVersion gitTagVersion;

442 443
    // Master channel
    gitTagVersion = GitTagVersion.parse('1.2.3-4.5.pre-13-g$hash');
444
    expect(gitTagVersion.frameworkVersionFor(hash), '1.3.0-0.0.pre.13');
445
    expect(gitTagVersion.gitTag, '1.2.3-4.5.pre');
446 447 448
    expect(gitTagVersion.devVersion, 4);
    expect(gitTagVersion.devPatch, 5);

449 450 451 452 453 454 455 456 457 458 459 460
    // 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);

    // Dev channel
    gitTagVersion = GitTagVersion.parse('1.2.3-4.5.pre');
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.3-4.5.pre');
461 462 463 464 465
    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');
466
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.4-0.0.pre.13');
467
    expect(gitTagVersion.gitTag, '1.2.3');
468 469 470
    expect(gitTagVersion.devVersion, null);
    expect(gitTagVersion.devPatch, null);

471 472 473 474
    // new tag release format, dev channel
    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');
475 476 477
    expect(gitTagVersion.devVersion, 4);
    expect(gitTagVersion.devPatch, 5);

478
    // new tag release format, stable channel
479
    gitTagVersion = GitTagVersion.parse('1.2.3-13-g$hash');
480
    expect(gitTagVersion.frameworkVersionFor(hash), '1.2.4-0.0.pre.13');
481
    expect(gitTagVersion.gitTag, '1.2.3');
482 483 484
    expect(gitTagVersion.devVersion, null);
    expect(gitTagVersion.devPatch, null);

485
    expect(GitTagVersion.parse('98.76.54-32-g$hash').frameworkVersionFor(hash), '98.76.55-0.0.pre.32');
486
    expect(GitTagVersion.parse('10.20.30-0-g$hash').frameworkVersionFor(hash), '10.20.30');
487
    expect(testLogger.traceText, '');
488
    expect(GitTagVersion.parse('v1.2.3+hotfix.1-4-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
489
    expect(GitTagVersion.parse('x1.2.3-4-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
490
    expect(GitTagVersion.parse('1.0.0-unknown-0-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
491
    expect(GitTagVersion.parse('beta-1-g$hash').frameworkVersionFor(hash), '0.0.0-unknown');
492
    expect(GitTagVersion.parse('1.2.3-4-gx$hash').frameworkVersionFor(hash), '0.0.0-unknown');
493 494
    expect(testLogger.statusText, '');
    expect(testLogger.errorText, '');
495 496
    expect(
      testLogger.traceText,
497
      'Could not interpret results of "git describe": v1.2.3+hotfix.1-4-gabcdef\n'
498
      'Could not interpret results of "git describe": x1.2.3-4-gabcdef\n'
499
      'Could not interpret results of "git describe": 1.0.0-unknown-0-gabcdef\n'
500
      'Could not interpret results of "git describe": beta-1-gabcdef\n'
501
      'Could not interpret results of "git describe": 1.2.3-4-gxabcdef\n',
502 503
    );
  });
504

505 506 507 508 509 510 511 512 513 514 515 516 517 518
  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(),
    );
519 520
    final FakePlatform platform = FakePlatform();
    final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, platform, workingDirectory: '.');
521 522 523
    expect(gitTagVersion.frameworkVersionFor('abcd1234'), stableTag);
  });

524
  testUsingContext('determine favors stable tag over dev tag if both identify HEAD', () {
525 526 527 528 529 530 531 532 533 534 535 536 537 538
    const String stableTag = '1.2.3';
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(
      <FakeCommand>[
        const FakeCommand(
          command: <String>['git', 'tag', '--points-at', 'HEAD'],
          // This tests the unlikely edge case where a dev release made it to stable without any cherry picks
          stdout: '1.2.3-6.0.pre\n$stableTag',
        ),
      ],
    );
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
539 540 541
    final FakePlatform platform = FakePlatform();

    final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, platform, workingDirectory: '.');
542 543 544 545 546 547 548 549 550 551 552
    expect(gitTagVersion.frameworkVersionFor('abcd1234'), stableTag);
  });

  testUsingContext('determine reports correct git describe version if HEAD is not at a tag', () {
    const String devTag = '1.2.3-2.0.pre';
    const String headRevision = 'abcd1234';
    const String commitsAhead = '12';
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(
      <FakeCommand>[
        const FakeCommand(
          command: <String>['git', 'tag', '--points-at', 'HEAD'],
553
          // no output, since there's no tag
554 555
        ),
        const FakeCommand(
556
          command: <String>['git', 'describe', '--match', '*.*.*', '--long', '--tags', 'HEAD'],
557 558 559 560 561 562 563 564
          stdout: '$devTag-$commitsAhead-g$headRevision',
        ),
      ],
    );
    final ProcessUtils processUtils = ProcessUtils(
      processManager: fakeProcessManager,
      logger: BufferLogger.test(),
    );
565 566 567
    final FakePlatform platform = FakePlatform();

    final GitTagVersion gitTagVersion = GitTagVersion.determine(processUtils, platform, workingDirectory: '.');
568 569
    // reported version should increment the y
    expect(gitTagVersion.frameworkVersionFor(headRevision), '1.3.0-0.0.pre.12');
570 571
  });

572
  testUsingContext('determine does not call fetch --tags', () {
573 574 575 576 577 578 579 580 581 582 583 584 585
    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(),
    );
586
    final FakePlatform platform = FakePlatform();
587

588
    GitTagVersion.determine(processUtils, platform, workingDirectory: '.');
589
    expect(fakeProcessManager, hasNoRemainingExpectations);
590 591
  });

592
  testUsingContext('determine does not fetch tags on dev/stable/beta', () {
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(
        command: <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
        stdout: 'dev',
      ),
      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(),
    );
610
    final FakePlatform platform = FakePlatform();
611

612
    GitTagVersion.determine(processUtils, platform, workingDirectory: '.', fetchTags: true);
613
    expect(fakeProcessManager, hasNoRemainingExpectations);
614 615 616
  });

  testUsingContext('determine calls fetch --tags on master', () {
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(
        command: <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
        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(),
    );
637
    final FakePlatform platform = FakePlatform();
638

639
    GitTagVersion.determine(processUtils, platform, workingDirectory: '.', fetchTags: true);
640
    expect(fakeProcessManager, hasNoRemainingExpectations);
641
  });
642 643

  testUsingContext('determine uses overridden git url', () {
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
    final FakeProcessManager fakeProcessManager = FakeProcessManager.list(<FakeCommand>[
      const FakeCommand(
        command: <String>['git', 'rev-parse', '--abbrev-ref', 'HEAD'],
        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(),
    );
664 665 666
    final FakePlatform platform = FakePlatform(
      environment: <String, String> {'FLUTTER_GIT_URL': 'https://githubmirror.com/flutter.git'},
    );
667

668
    GitTagVersion.determine(processUtils, platform, workingDirectory: '.', fetchTags: true);
669
    expect(fakeProcessManager, hasNoRemainingExpectations);
670
  });
671 672
}

673
class FakeCache extends Fake implements Cache {
674
  String? versionStamp;
675 676 677 678 679
  bool setVersionStamp = false;

  @override
  String get engineRevision => 'abcdefg';

680 681 682
  @override
  String get devToolsVersion => '2.8.0';

683 684 685 686 687 688 689
  @override
  String get dartSdkVersion => '2.12.0';

  @override
  void checkLockAcquired() { }

  @override
690
  String? getStampFor(String artifactName) {
691 692 693 694 695 696 697 698 699 700 701 702 703
    if (artifactName == VersionCheckStamp.flutterVersionCheckStampFile) {
      return versionStamp;
    }
    return null;
  }

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

705
class FakeFlutterVersion extends Fake implements FlutterVersion {
706
  FakeFlutterVersion({required this.channel, this.repositoryUrl});
707

708 709
  @override
  final String channel;
710 711

  @override
712
  final String? repositoryUrl;
713
}