diff --git a/packages/melos/lib/src/common/intellij_project.dart b/packages/melos/lib/src/common/intellij_project.dart index caf713415..96ea7a08f 100644 --- a/packages/melos/lib/src/common/intellij_project.dart +++ b/packages/melos/lib/src/common/intellij_project.dart @@ -3,16 +3,14 @@ import 'dart:io'; import 'package:path/path.dart' as p; import 'package:xml/xml.dart' as xml; -import '../common/utils.dart' as utils; import '../package.dart'; import '../workspace.dart'; +import 'intellij_templates.g.dart'; import 'io.dart'; import 'platform.dart'; const String kRunConfigurationPrefix = 'melos_'; -const String _kTemplatesDirName = 'templates'; -const String _kIntellijDirName = 'intellij'; const String _kDotIdeaDirName = '.idea'; const String _kTmplExtension = '.tmpl'; @@ -24,25 +22,6 @@ class IntellijProject { final MelosWorkspace _workspace; - final Map _cacheTemplates = {}; - - Future? _pathTemplates; - - /// Fully qualified path to the intellij templates shipped as part of Melos. - Future get pathTemplates => - _pathTemplates ??= _resolvePathTemplates(); - - Future _resolvePathTemplates() async { - // For a globally-activated Melos with a custom PUB_CACHE, the - // isolate-resolved root can point into the default pub-cache even though - // the templates live in PUB_CACHE (see invertase/melos#749). - final melosRoot = utils.applyPubCacheOverride( - await utils.getMelosRoot(), - probeSubdirectory: _kTemplatesDirName, - ); - return p.join(melosRoot, _kTemplatesDirName, _kIntellijDirName); - } - Directory get runConfigurationsDir => Directory(p.join(dotIdeaDir.path, 'runConfigurations')); @@ -89,10 +68,6 @@ class IntellijProject { return p.join(package.path, '${packageModuleName(package)}.iml'); } - Future pathTemplatesForDirectory(String directory) async { - return p.join(await pathTemplates, directory); - } - String injectTemplateVariable({ required String template, required String variableName, @@ -116,29 +91,24 @@ class IntellijProject { return updatedTemplate; } - /// Reads a file template from the templates directory. - /// - /// Additionally keeps a cache to reduce reads. + /// Reads a bundled file template. Future readFileTemplate( String fileName, { String? templateCategory, }) async { - if (_cacheTemplates[fileName] != null) { - return _cacheTemplates[fileName]!; - } - - String templatesRootPath; - if (templateCategory != null) { - templatesRootPath = await pathTemplatesForDirectory(templateCategory); - } else { - templatesRootPath = await pathTemplates; + final templateKey = templateCategory != null + ? '$templateCategory/$fileName$_kTmplExtension' + : '$fileName$_kTmplExtension'; + + final template = intellijTemplates[templateKey]; + if (template == null) { + throw ArgumentError.value( + templateKey, + 'fileName', + 'Unknown IntelliJ template', + ); } - final templateFile = p.join(templatesRootPath, '$fileName$_kTmplExtension'); - final template = await readTextFileAsync(templateFile); - - _cacheTemplates[fileName] = template; - return template; } diff --git a/packages/melos/lib/src/common/intellij_templates.g.dart b/packages/melos/lib/src/common/intellij_templates.g.dart new file mode 100644 index 000000000..cb28e18e3 --- /dev/null +++ b/packages/melos/lib/src/common/intellij_templates.g.dart @@ -0,0 +1,227 @@ +// This file is generated. Do not manually edit. +// Run `dart run scripts/generate_templates.dart` to regenerate. +// ignore_for_file: lines_longer_than_80_chars + +const Map intellijTemplates = { + 'modules.xml.tmpl': ''' + + + + +{{#modules}} + + +''', + 'modules/dart_package_module.iml.tmpl': r''' + + + + + + + + + + + + + + + +''', + 'modules/flutter_app_android_java_module.iml.tmpl': r''' + + + + + + + + + + + + + + + + + + + +''', + 'modules/flutter_app_module.iml.tmpl': r''' + + + + + + + + + + + + + + + + + + + + + + + + + + +''', + 'modules/flutter_plugin_android_java_module.iml.tmpl': r''' + + + + + + + + + + + + + + + + + + + +''', + 'modules/flutter_plugin_module.iml.tmpl': r''' + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +''', + 'modules/workspace_root_module.iml.tmpl': r''' + + + + + + + + + + + + +''', + 'runConfigurations/dart_run.xml.tmpl': ''' + + + + + +''', + 'runConfigurations/dart_test.xml.tmpl': ''' + + + + + +''', + 'runConfigurations/flutter_run.xml.tmpl': r''' + + + +''', + 'runConfigurations/flutter_run_with_args.xml.tmpl': r''' + + + +''', + 'runConfigurations/flutter_test.xml.tmpl': ''' + + + + + +''', + 'runConfigurations/shell_script.xml.tmpl': r''' + + + + + +''', + 'vcs.xml.tmpl': ''' + + + + + +''', +}; diff --git a/packages/melos/lib/src/common/utils.dart b/packages/melos/lib/src/common/utils.dart index 7bfd8f3c8..3d1bd007d 100644 --- a/packages/melos/lib/src/common/utils.dart +++ b/packages/melos/lib/src/common/utils.dart @@ -15,7 +15,6 @@ import '../logging.dart'; import '../workspace.dart'; import 'environment_variable_key.dart'; import 'exception.dart'; -import 'io.dart' show dirExists; import 'platform.dart'; import 'process_output_cancel_token.dart'; @@ -319,105 +318,22 @@ String addToPathEnvVar({ } } -/// Default pub cache locations when [EnvironmentVariableKey.pubCache] is -/// unset. -/// -/// Windows can have a cache under Local *and* Roaming, and -/// `Isolate.resolvePackageUri` may report either, so remapping has to try -/// both. Returns an empty list when no default location can be determined. -List _defaultPubCacheDirectories() { - if (currentPlatform.isWindows) { - final dirs = []; - final localAppData = currentPlatform.environment['LOCALAPPDATA']; - if (localAppData != null && localAppData.isNotEmpty) { - dirs.add(p.join(localAppData, 'Pub', 'Cache')); - } - final appData = currentPlatform.environment['APPDATA']; - if (appData != null && appData.isNotEmpty) { - dirs.add(p.join(appData, 'Pub', 'Cache')); - } - if (dirs.isNotEmpty) { - return dirs; - } - } - final home = - currentPlatform.environment['HOME'] ?? - currentPlatform.environment['USERPROFILE'] ?? - ''; - if (home.isEmpty) { - return const []; - } - return [p.join(home, '.pub-cache')]; -} - -/// Rewrites [resolvedRoot] from a default pub-cache location into the cache -/// pointed to by [EnvironmentVariableKey.pubCache]. -/// -/// The rewrite only happens when [probeSubdirectory] is missing under -/// [resolvedRoot], [resolvedRoot] is inside a default pub-cache location, and -/// the rewritten root does contain [probeSubdirectory]; in every other case -/// [resolvedRoot] is returned unchanged. -/// -/// This covers globally-activated Melos when `Isolate.resolvePackageUri` -/// still reports `$HOME/.pub-cache` while the packages actually live in a -/// custom `PUB_CACHE` (see invertase/melos#749). -String applyPubCacheOverride( - String resolvedRoot, { - required String probeSubdirectory, -}) { - final pubCacheEnv = - currentPlatform.environment[EnvironmentVariableKey.pubCache]; - if (pubCacheEnv == null || pubCacheEnv.isEmpty) { - return resolvedRoot; - } - // Pub resolves a relative PUB_CACHE against the working directory. - final pubCache = p.normalize(p.absolute(pubCacheEnv)); - - final resolved = p.normalize(resolvedRoot); - if (p.equals(pubCache, resolved) || p.isWithin(pubCache, resolved)) { - return resolvedRoot; - } - if (_probeDirExists(p.join(resolved, probeSubdirectory))) { - return resolvedRoot; - } - - for (final defaultCache in _defaultPubCacheDirectories().map(p.normalize)) { - if (!p.equals(defaultCache, resolved) && - !p.isWithin(defaultCache, resolved)) { - continue; - } - final rewritten = p.equals(defaultCache, resolved) - ? pubCache - : p.normalize( - p.join(pubCache, p.relative(resolved, from: defaultCache)), - ); - if (_probeDirExists(p.join(rewritten, probeSubdirectory))) { - return rewritten; - } - } - return resolvedRoot; -} - -/// [dirExists] variant that treats unreadable paths as missing, since the -/// probed locations may not be stat-able by the current user (for example -/// `/root/.pub-cache` when running as a regular user). -bool _probeDirExists(String path) { - try { - return dirExists(path); - } on FileSystemException { - return false; - } -} - Future? _melosRoot; Future getMelosRoot() => _melosRoot ??= _resolveMelosRoot(); Future _resolveMelosRoot() async { final melosPackageFileUri = await Isolate.resolvePackageUri(melosPackageUri); + if (melosPackageFileUri == null) { + throw StateError( + 'Could not resolve package root for $melosPackageUri. ' + 'Package URI resolution is unavailable when running as a ' + 'compiled executable.', + ); + } // Get from lib/melos.dart to the package root - return p.normalize('${melosPackageFileUri!.toFilePath()}/../..'); + return p.normalize('${melosPackageFileUri.toFilePath()}/../..'); } String melosStatePathForDirectory(String directory) => diff --git a/packages/melos/test/common/intellij_project_test.dart b/packages/melos/test/common/intellij_project_test.dart index bcaf1e440..f858d2bd3 100644 --- a/packages/melos/test/common/intellij_project_test.dart +++ b/packages/melos/test/common/intellij_project_test.dart @@ -2,7 +2,9 @@ import 'dart:io'; import 'package:melos/src/common/environment_variable_key.dart'; import 'package:melos/src/common/intellij_project.dart'; +import 'package:melos/src/common/intellij_templates.g.dart'; import 'package:melos/src/common/io.dart'; +import 'package:melos/src/common/utils.dart' as utils; import 'package:path/path.dart' as p; import 'package:platform/platform.dart' show FakePlatform; import 'package:pubspec_parse/pubspec_parse.dart'; @@ -988,4 +990,86 @@ $runArguments ), ); }); + + group('bundled IntelliJ templates', () { + test( + 'match every template file under templates/intellij on disk', + () async { + final melosRoot = await utils.getMelosRoot(); + final templatesDir = Directory( + p.join(melosRoot, 'templates', 'intellij'), + ); + final diskTemplates = {}; + for (final entity in templatesDir.listSync(recursive: true)) { + if (entity is! File || !entity.path.endsWith('.tmpl')) { + continue; + } + final key = p.posix.joinAll( + p.split(p.relative(entity.path, from: templatesDir.path)), + ); + diskTemplates[key] = entity.readAsStringSync().replaceAll( + '\r\n', + '\n', + ); + } + + expect( + intellijTemplates.keys.toSet(), + diskTemplates.keys.toSet(), + reason: + 'Embedded IntelliJ templates are out of sync with ' + 'templates/intellij/. Run ' + '"dart run scripts/generate_templates.dart" to regenerate.', + ); + + for (final entry in diskTemplates.entries) { + expect( + intellijTemplates[entry.key], + entry.value, + reason: + 'Embedded template "${entry.key}" differs from disk. ' + 'Run "dart run scripts/generate_templates.dart" to regenerate.', + ); + } + }, + ); + + test( + 'readFileTemplate returns bundled templates and rejects unknown names', + () async { + final tempDir = createTestTempDir(); + final workspace = VirtualWorkspaceBuilder( + path: tempDir.path, + ''' + packages: + - . + ''', + ).build(); + final project = IntellijProject.fromWorkspace(workspace); + + expect( + await project.readFileTemplate('modules.xml'), + intellijTemplates['modules.xml.tmpl'], + ); + expect( + await project.readFileTemplate( + 'dart_package_module.iml', + templateCategory: 'modules', + ), + intellijTemplates['modules/dart_package_module.iml.tmpl'], + ); + expect( + await project.readFileTemplate( + 'dart_run.xml', + templateCategory: 'runConfigurations', + ), + intellijTemplates['runConfigurations/dart_run.xml.tmpl'], + ); + await expectLater( + project.readFileTemplate('nonexistent.xml'), + throwsArgumentError, + ); + }, + ); + }); } diff --git a/packages/melos/test/utils_test.dart b/packages/melos/test/utils_test.dart index 201922e05..0af9d6379 100644 --- a/packages/melos/test/utils_test.dart +++ b/packages/melos/test/utils_test.dart @@ -312,177 +312,6 @@ void main() { }); }); - group('applyPubCacheOverride', () { - String packagePath(String cache) => - p.join(cache, 'hosted', 'pub.dev', 'melos-6.1.0'); - - test('rewrites a stale default pub-cache path into PUB_CACHE', () async { - final pubCacheDir = createTestTempDir(); - final rewrittenRoot = packagePath(pubCacheDir.path); - Directory(p.join(rewrittenRoot, 'templates')).createSync(recursive: true); - - await withMockPlatform( - () { - expect( - applyPubCacheOverride( - packagePath(p.join('/root', '.pub-cache')), - probeSubdirectory: 'templates', - ), - p.normalize(rewrittenRoot), - ); - }, - platform: FakePlatform( - operatingSystem: 'linux', - environment: { - EnvironmentVariableKey.pubCache: pubCacheDir.path, - 'HOME': '/root', - }, - ), - )(); - }); - - test('keeps a resolved path that still contains the probe', () async { - final defaultCacheDir = createTestTempDir(); - final resolvedRoot = packagePath(defaultCacheDir.path); - Directory(p.join(resolvedRoot, 'templates')).createSync(recursive: true); - final pubCacheDir = createTestTempDir(); - - await withMockPlatform( - () { - expect( - applyPubCacheOverride(resolvedRoot, probeSubdirectory: 'templates'), - resolvedRoot, - ); - }, - platform: FakePlatform( - operatingSystem: 'linux', - environment: { - EnvironmentVariableKey.pubCache: pubCacheDir.path, - 'HOME': '/root', - }, - ), - )(); - }); - - test( - 'keeps the isolate-resolved path when PUB_CACHE is unset', - withMockPlatform( - () { - final resolved = packagePath(p.join('/root', '.pub-cache')); - expect( - applyPubCacheOverride(resolved, probeSubdirectory: 'templates'), - resolved, - ); - }, - platform: FakePlatform( - operatingSystem: 'linux', - environment: const {'HOME': '/root'}, - ), - ), - ); - - test('keeps a path that is not under the default pub-cache', () async { - final pubCacheDir = createTestTempDir(); - Directory( - p.join(packagePath(pubCacheDir.path), 'templates'), - ).createSync(recursive: true); - - await withMockPlatform( - () { - const resolved = '/src/melos/packages/melos'; - expect( - applyPubCacheOverride(resolved, probeSubdirectory: 'templates'), - resolved, - ); - }, - platform: FakePlatform( - operatingSystem: 'linux', - environment: { - EnvironmentVariableKey.pubCache: pubCacheDir.path, - 'HOME': '/root', - }, - ), - )(); - }); - - test('keeps the resolved path when PUB_CACHE lacks the probe', () async { - final pubCacheDir = createTestTempDir(); - - await withMockPlatform( - () { - final resolved = packagePath(p.join('/root', '.pub-cache')); - expect( - applyPubCacheOverride(resolved, probeSubdirectory: 'templates'), - resolved, - ); - }, - platform: FakePlatform( - operatingSystem: 'linux', - environment: { - EnvironmentVariableKey.pubCache: pubCacheDir.path, - 'HOME': '/root', - }, - ), - )(); - }); - - test( - 'keeps a resolved path that is already inside a nested PUB_CACHE', - () async { - final homeDir = createTestTempDir(); - final pubCache = p.join(homeDir.path, '.pub-cache', 'ci'); - final resolved = packagePath(pubCache); - - await withMockPlatform( - () { - expect( - applyPubCacheOverride(resolved, probeSubdirectory: 'templates'), - resolved, - ); - }, - platform: FakePlatform( - operatingSystem: 'linux', - environment: { - EnvironmentVariableKey.pubCache: pubCache, - 'HOME': homeDir.path, - }, - ), - )(); - }, - ); - - test( - 'rewrites a Windows Roaming cache path even when Local is set', - () async { - final localDir = createTestTempDir(); - final roamingDir = createTestTempDir(); - final pubCacheDir = createTestTempDir(); - final rewrittenRoot = packagePath(pubCacheDir.path); - Directory( - p.join(rewrittenRoot, 'templates'), - ).createSync(recursive: true); - final resolved = packagePath(p.join(roamingDir.path, 'Pub', 'Cache')); - - await withMockPlatform( - () { - expect( - applyPubCacheOverride(resolved, probeSubdirectory: 'templates'), - p.normalize(rewrittenRoot), - ); - }, - platform: FakePlatform( - operatingSystem: 'windows', - environment: { - EnvironmentVariableKey.pubCache: pubCacheDir.path, - 'LOCALAPPDATA': localDir.path, - 'APPDATA': roamingDir.path, - }, - ), - )(); - }, - ); - }); - group('mergeYaml', () { test('correctly handles value overriding', () { final base = { diff --git a/scripts/generate_templates.dart b/scripts/generate_templates.dart new file mode 100644 index 000000000..2fd520928 --- /dev/null +++ b/scripts/generate_templates.dart @@ -0,0 +1,70 @@ +// ignore_for_file: avoid_print + +import 'dart:io' show Directory, File; + +import 'package:path/path.dart' as p; + +Future main() async { + final templatesDir = Directory( + p.joinAll([ + Directory.current.path, + 'packages', + 'melos', + 'templates', + 'intellij', + ]), + ); + final outputPath = p.joinAll([ + Directory.current.path, + 'packages', + 'melos', + 'lib', + 'src', + 'common', + 'intellij_templates.g.dart', + ]); + + final templateEntries = >[]; + for (final entity in templatesDir.listSync(recursive: true)) { + if (entity is! File || !entity.path.endsWith('.tmpl')) { + continue; + } + final relativePath = p.posix.joinAll( + p.split(p.relative(entity.path, from: templatesDir.path)), + ); + final contents = entity.readAsStringSync().replaceAll('\r\n', '\n'); + if (contents.contains("'''") || contents.endsWith("'")) { + throw StateError( + 'Template "$relativePath" cannot be encoded as a triple-single-quoted ' + 'Dart string literal.', + ); + } + templateEntries.add(MapEntry(relativePath, contents)); + } + templateEntries.sort((a, b) => a.key.compareTo(b.key)); + + final buffer = StringBuffer() + ..writeln('// This file is generated. Do not manually edit.') + ..writeln( + '// Run `dart run scripts/generate_templates.dart` to regenerate.', + ) + ..writeln('// ignore_for_file: lines_longer_than_80_chars') + ..writeln() + ..writeln('const Map intellijTemplates = {'); + + for (final entry in templateEntries) { + final isRaw = entry.value.contains(r'$') || entry.value.contains(r'\'); + final openQuote = isRaw ? "r'''" : "'''"; + buffer + ..writeln(" '${entry.key}': $openQuote") + ..write(entry.value) + ..writeln("''',"); + } + + buffer.writeln('};'); + + await File(outputPath).writeAsString(buffer.toString()); + print( + 'Generated $outputPath with ${templateEntries.length} IntelliJ templates.', + ); +}