[go: nahoru, domu]

Skip to content
This repository has been archived by the owner on Feb 22, 2023. It is now read-only.

[ci] Remove repo tooling #7172

Merged
merged 10 commits into from
Feb 14, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Re-add a minimal stub
  • Loading branch information
stuartmorgan committed Feb 13, 2023
commit 431bb74d879dd7309b9fb243f5d377996daa6557
662 changes: 662 additions & 0 deletions script/tool/CHANGELOG.md

Large diffs are not rendered by default.

25 changes: 25 additions & 0 deletions script/tool/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
Copyright 2013 The Flutter Authors. All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
13 changes: 13 additions & 0 deletions script/tool/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Removed

See https://github.com/flutter/packages/blob/main/script/tool/README.md for the
current location of this tooling.

## Temporary shim

This is a temporary, minimal version of the tools sufficient to keep the
following scripts running until the repository merge is complete and they are
updated to use flutter/packages instead:

- [dart-lang analysis](https://github.com/dart-lang/sdk/blob/main/tools/bots/flutter/analyze_flutter_plugins.sh)
- [flutter/flutter analysis](https://github.com/flutter/flutter/blob/master/dev/bots/test.dart)
5 changes: 5 additions & 0 deletions script/tool/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
include: ../../analysis_options.yaml

linter:
rules:
avoid_print: false # The tool is a CLI, so printing is normal
5 changes: 5 additions & 0 deletions script/tool/bin/flutter_plugin_tools.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Copyright 2013 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.

export 'package:flutter_plugin_tools/src/main.dart';
144 changes: 144 additions & 0 deletions script/tool/lib/src/analyze_command.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// Copyright 2013 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 'dart:async';

import 'package:file/file.dart';
import 'package:platform/platform.dart';
import 'package:yaml/yaml.dart';

import 'common/core.dart';
import 'common/package_looping_command.dart';
import 'common/process_runner.dart';
import 'common/repository_package.dart';

/// A command to run Dart analysis on packages.
class AnalyzeCommand extends PackageLoopingCommand {
/// Creates a analysis command instance.
AnalyzeCommand(
Directory packagesDir, {
ProcessRunner processRunner = const ProcessRunner(),
Platform platform = const LocalPlatform(),
}) : super(packagesDir, processRunner: processRunner, platform: platform) {
argParser.addMultiOption(_customAnalysisFlag,
help:
'Directories (comma separated) that are allowed to have their own '
'analysis options.\n\n'
'Alternately, a list of one or more YAML files that contain a list '
'of allowed directories.',
defaultsTo: <String>[]);
argParser.addOption(_analysisSdk,
valueHelp: 'dart-sdk',
help: 'An optional path to a Dart SDK; this is used to override the '
'SDK used to provide analysis.');
}

static const String _customAnalysisFlag = 'custom-analysis';
static const String _analysisSdk = 'analysis-sdk';

late String _dartBinaryPath;

Set<String> _allowedCustomAnalysisDirectories = const <String>{};

@override
final String name = 'analyze';

@override
final String description = 'Analyzes all packages using dart analyze.\n\n'
'This command requires "dart" and "flutter" to be in your path.';

@override
final bool hasLongOutput = false;

/// Checks that there are no unexpected analysis_options.yaml files.
bool _hasUnexpecetdAnalysisOptions(RepositoryPackage package) {
final List<FileSystemEntity> files =
package.directory.listSync(recursive: true);
for (final FileSystemEntity file in files) {
if (file.basename != 'analysis_options.yaml' &&
file.basename != '.analysis_options') {
continue;
}

final bool allowed = _allowedCustomAnalysisDirectories.any(
(String directory) =>
directory.isNotEmpty &&
path.isWithin(
packagesDir.childDirectory(directory).path, file.path));
if (allowed) {
continue;
}

printError(
'Found an extra analysis_options.yaml at ${file.absolute.path}.');
printError(
'If this was deliberate, pass the package to the analyze command '
'with the --$_customAnalysisFlag flag and try again.');
return true;
}
return false;
}

@override
Future<void> initializeRun() async {
_allowedCustomAnalysisDirectories =
getStringListArg(_customAnalysisFlag).expand<String>((String item) {
if (item.endsWith('.yaml')) {
final File file = packagesDir.fileSystem.file(item);
final Object? yaml = loadYaml(file.readAsStringSync());
if (yaml == null) {
return <String>[];
}
return (yaml as YamlList).toList().cast<String>();
}
return <String>[item];
}).toSet();

// Use the Dart SDK override if one was passed in.
final String? dartSdk = argResults![_analysisSdk] as String?;
_dartBinaryPath =
dartSdk == null ? 'dart' : path.join(dartSdk, 'bin', 'dart');
}

@override
Future<PackageResult> runForPackage(RepositoryPackage package) async {
// Analysis runs over the package and all subpackages (unless only lib/ is
// being analyzed), so all of them need `flutter pub get` run before
// analyzing. `example` packages can be skipped since 'flutter packages get'
// automatically runs `pub get` in examples as part of handling the parent
// directory.
final List<RepositoryPackage> packagesToGet = <RepositoryPackage>[
package,
...await getSubpackages(package).toList(),
];
for (final RepositoryPackage packageToGet in packagesToGet) {
if (packageToGet.directory.basename != 'example' ||
!RepositoryPackage(packageToGet.directory.parent)
.pubspecFile
.existsSync()) {
if (!await _runPubCommand(packageToGet, 'get')) {
return PackageResult.fail(<String>['Unable to get dependencies']);
}
}
}

if (_hasUnexpecetdAnalysisOptions(package)) {
return PackageResult.fail(<String>['Unexpected local analysis options']);
}
final int exitCode = await processRunner.runAndStream(
_dartBinaryPath, <String>['analyze', '--fatal-infos'],
workingDir: package.directory);
if (exitCode != 0) {
return PackageResult.fail();
}
return PackageResult.success();
}

Future<bool> _runPubCommand(RepositoryPackage package, String command) async {
final int exitCode = await processRunner.runAndStream(
flutterCommand, <String>['pub', command],
workingDir: package.directory);
return exitCode == 0;
}
}
82 changes: 82 additions & 0 deletions script/tool/lib/src/common/core.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// Copyright 2013 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:colorize/colorize.dart';
import 'package:file/file.dart';

/// The signature for a print handler for commands that allow overriding the
/// print destination.
typedef Print = void Function(Object? object);

/// Key for APK (Android) platform.
const String platformAndroid = 'android';

/// Key for IPA (iOS) platform.
const String platformIOS = 'ios';

/// Key for linux platform.
const String platformLinux = 'linux';

/// Key for macos platform.
const String platformMacOS = 'macos';

/// Key for Web platform.
const String platformWeb = 'web';

/// Key for windows platform.
const String platformWindows = 'windows';

/// Key for enable experiment.
const String kEnableExperiment = 'enable-experiment';

/// Target platforms supported by Flutter.
// ignore: public_member_api_docs
enum FlutterPlatform { android, ios, linux, macos, web, windows }

/// Returns whether the given directory is a Dart package.
bool isPackage(FileSystemEntity entity) {
if (entity is! Directory) {
return false;
}
// According to
// https://dart.dev/guides/libraries/create-library-packages#what-makes-a-library-package
// a package must also have a `lib/` directory, but in practice that's not
// always true. flutter/plugins has some special cases (espresso, some
// federated implementation packages) that don't have any source, so this
// deliberately doesn't check that there's a lib directory.
return entity.childFile('pubspec.yaml').existsSync();
}

/// Prints `successMessage` in green.
void printSuccess(String successMessage) {
print(Colorize(successMessage)..green());
}

/// Prints `errorMessage` in red.
void printError(String errorMessage) {
print(Colorize(errorMessage)..red());
}

/// Error thrown when a command needs to exit with a non-zero exit code.
///
/// While there is no specific definition of the meaning of different non-zero
/// exit codes for this tool, commands should follow the general convention:
/// 1: The command ran correctly, but found errors.
/// 2: The command failed to run because the arguments were invalid.
/// >2: The command failed to run correctly for some other reason. Ideally,
/// each such failure should have a unique exit code within the context of
/// that command.
class ToolExit extends Error {
/// Creates a tool exit with the given [exitCode].
ToolExit(this.exitCode);

/// The code that the process should exit with.
final int exitCode;
}

/// A exit code for [ToolExit] for a successful run that found errors.
const int exitCommandFoundErrors = 1;

/// A exit code for [ToolExit] for a failure to run due to invalid arguments.
const int exitInvalidArguments = 2;
116 changes: 116 additions & 0 deletions script/tool/lib/src/common/git_version_finder.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
// Copyright 2013 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 'dart:io' as io;

import 'package:git/git.dart';
import 'package:pub_semver/pub_semver.dart';
import 'package:yaml/yaml.dart';

/// Finding diffs based on `baseGitDir` and `baseSha`.
class GitVersionFinder {
/// Constructor
GitVersionFinder(this.baseGitDir, String? baseSha) : _baseSha = baseSha;

/// The top level directory of the git repo.
///
/// That is where the .git/ folder exists.
final GitDir baseGitDir;

/// The base sha used to get diff.
String? _baseSha;

static bool _isPubspec(String file) {
return file.trim().endsWith('pubspec.yaml');
}

/// Get a list of all the pubspec.yaml file that is changed.
Future<List<String>> getChangedPubSpecs() async {
return (await getChangedFiles()).where(_isPubspec).toList();
}

/// Get a list of all the changed files.
Future<List<String>> getChangedFiles(
{bool includeUncommitted = false}) async {
final String baseSha = await getBaseSha();
final io.ProcessResult changedFilesCommand = await baseGitDir
.runCommand(<String>[
'diff',
'--name-only',
baseSha,
if (!includeUncommitted) 'HEAD'
]);
final String changedFilesStdout = changedFilesCommand.stdout.toString();
if (changedFilesStdout.isEmpty) {
return <String>[];
}
final List<String> changedFiles = changedFilesStdout.split('\n')
..removeWhere((String element) => element.isEmpty);
return changedFiles.toList();
}

/// Get a list of all the changed files.
Future<List<String>> getDiffContents({
String? targetPath,
bool includeUncommitted = false,
}) async {
final String baseSha = await getBaseSha();
final io.ProcessResult diffCommand = await baseGitDir.runCommand(<String>[
'diff',
baseSha,
if (!includeUncommitted) 'HEAD',
if (targetPath != null) ...<String>['--', targetPath],
]);
final String diffStdout = diffCommand.stdout.toString();
if (diffStdout.isEmpty) {
return <String>[];
}
final List<String> changedFiles = diffStdout.split('\n')
..removeWhere((String element) => element.isEmpty);
return changedFiles.toList();
}

/// Get the package version specified in the pubspec file in `pubspecPath` and
/// at the revision of `gitRef` (defaulting to the base if not provided).
Future<Version?> getPackageVersion(String pubspecPath,
{String? gitRef}) async {
final String ref = gitRef ?? (await getBaseSha());

io.ProcessResult gitShow;
try {
gitShow =
await baseGitDir.runCommand(<String>['show', '$ref:$pubspecPath']);
} on io.ProcessException {
return null;
}
final String fileContent = gitShow.stdout as String;
if (fileContent.trim().isEmpty) {
return null;
}
final YamlMap fileYaml = loadYaml(fileContent) as YamlMap;
final String? versionString = fileYaml['version'] as String?;
return versionString == null ? null : Version.parse(versionString);
}

/// Returns the base used to diff against.
Future<String> getBaseSha() async {
String? baseSha = _baseSha;
if (baseSha != null && baseSha.isNotEmpty) {
return baseSha;
}

io.ProcessResult baseShaFromMergeBase = await baseGitDir.runCommand(
<String>['merge-base', '--fork-point', 'FETCH_HEAD', 'HEAD'],
throwOnError: false);
final String stdout = (baseShaFromMergeBase.stdout as String? ?? '').trim();
final String stderr = (baseShaFromMergeBase.stderr as String? ?? '').trim();
if (stderr.isNotEmpty || stdout.isEmpty) {
baseShaFromMergeBase = await baseGitDir
.runCommand(<String>['merge-base', 'FETCH_HEAD', 'HEAD']);
}
baseSha = (baseShaFromMergeBase.stdout as String).trim();
_baseSha = baseSha;
return baseSha;
}
}
Loading