|
| 1 | +// Copyright (c) 2025, the Dart project authors. Please see the AUTHORS file |
| 2 | +// for details. All rights reserved. Use of this source code is governed by a |
| 3 | +// BSD-style license that can be found in the LICENSE file. |
| 4 | + |
| 5 | +import 'dart:convert'; |
| 6 | +import 'dart:io'; |
| 7 | + |
| 8 | +import 'package:path/path.dart' as p; |
| 9 | + |
| 10 | +import '../command.dart'; |
| 11 | +import '../command_runner.dart'; |
| 12 | +import '../io.dart'; |
| 13 | +import '../log.dart' as log; |
| 14 | +import '../package_config.dart'; |
| 15 | +import '../utils.dart'; |
| 16 | + |
| 17 | +class CacheGcCommand extends PubCommand { |
| 18 | + @override |
| 19 | + String get name => 'gc'; |
| 20 | + @override |
| 21 | + String get description => 'Prunes unused packages from the system cache.'; |
| 22 | + @override |
| 23 | + bool get takesArguments => false; |
| 24 | + |
| 25 | + final dontRemoveFilesOlderThan = const Duration(hours: 2); |
| 26 | + |
| 27 | + CacheGcCommand() { |
| 28 | + argParser.addFlag( |
| 29 | + 'force', |
| 30 | + abbr: 'f', |
| 31 | + help: 'Prune cache without confirmation', |
| 32 | + hideNegatedUsage: true, |
| 33 | + ); |
| 34 | + argParser.addFlag( |
| 35 | + 'collect-recent', |
| 36 | + help: 'Also delete recent files', |
| 37 | + hideNegatedUsage: true, |
| 38 | + ); |
| 39 | + argParser.addFlag( |
| 40 | + 'dry-run', |
| 41 | + help: 'Print list of files that would be deleted', |
| 42 | + hideNegatedUsage: true, |
| 43 | + ); |
| 44 | + } |
| 45 | + |
| 46 | + @override |
| 47 | + Future<void> runProtected() async { |
| 48 | + final dryRun = argResults.flag('dry-run'); |
| 49 | + final activeRoots = cache.activeRoots(); |
| 50 | + // All the `activeRoots` that we could read and parse a |
| 51 | + // .dart_tool/packageConfig.json from. |
| 52 | + final validActiveRoots = <String>[]; |
| 53 | + // All the rootUri paths to cached packages included from |
| 54 | + // `validActiveRoots`. |
| 55 | + final paths = <String>{}; |
| 56 | + for (final packageConfigPath in activeRoots) { |
| 57 | + late final PackageConfig packageConfig; |
| 58 | + try { |
| 59 | + packageConfig = PackageConfig.fromJson( |
| 60 | + json.decode(readTextFile(packageConfigPath)), |
| 61 | + ); |
| 62 | + } on IOException catch (e) { |
| 63 | + // Failed to read file - probably got deleted. |
| 64 | + log.fine('Failed to read packageConfig $packageConfigPath: $e'); |
| 65 | + continue; |
| 66 | + } on FormatException catch (e) { |
| 67 | + log.warning( |
| 68 | + 'Failed to decode packageConfig $packageConfigPath: $e.\n' |
| 69 | + 'It could be corrupted', |
| 70 | + ); |
| 71 | + // Failed to decode - probably corrupted. |
| 72 | + continue; |
| 73 | + } |
| 74 | + for (final package in packageConfig.packages) { |
| 75 | + final rootUri = p.canonicalize( |
| 76 | + package.resolvedRootDir(packageConfigPath), |
| 77 | + ); |
| 78 | + if (p.isWithin(cache.rootDir, rootUri)) { |
| 79 | + paths.add(rootUri); |
| 80 | + } |
| 81 | + } |
| 82 | + validActiveRoots.add(packageConfigPath); |
| 83 | + } |
| 84 | + final now = DateTime.now(); |
| 85 | + final allPathsToGC = |
| 86 | + [ |
| 87 | + for (final source in cache.cachedSources) |
| 88 | + ...await source.entriesToGc( |
| 89 | + cache, |
| 90 | + paths |
| 91 | + .where( |
| 92 | + (path) => p.isWithin( |
| 93 | + p.canonicalize(cache.rootDirForSource(source)), |
| 94 | + path, |
| 95 | + ), |
| 96 | + ) |
| 97 | + .toSet(), |
| 98 | + ), |
| 99 | + ].where((path) { |
| 100 | + // Only clear cache entries older than 2 hours to avoid race |
| 101 | + // conditions with ongoing `pub get` processes. |
| 102 | + final s = statPath(path); |
| 103 | + if (s.type == FileSystemEntityType.notFound) return false; |
| 104 | + if (argResults.flag('collect-recent')) return true; |
| 105 | + return now.difference(s.modified) > dontRemoveFilesOlderThan; |
| 106 | + }).toList(); |
| 107 | + if (validActiveRoots.isEmpty) { |
| 108 | + log.message('Found no active projects.'); |
| 109 | + } else { |
| 110 | + final s = validActiveRoots.length == 1 ? '' : 's'; |
| 111 | + log.message('Found ${validActiveRoots.length} active project$s:'); |
| 112 | + for (final packageConfigPath in validActiveRoots) { |
| 113 | + final parts = p.split(packageConfigPath); |
| 114 | + var projectDir = packageConfigPath; |
| 115 | + if (parts[parts.length - 2] == '.dart_tool' && |
| 116 | + parts[parts.length - 1] == 'package_config.json') { |
| 117 | + projectDir = p.joinAll(parts.sublist(0, parts.length - 2)); |
| 118 | + } |
| 119 | + log.message('* $projectDir'); |
| 120 | + } |
| 121 | + } |
| 122 | + var sum = 0; |
| 123 | + for (final entry in allPathsToGC) { |
| 124 | + if (dirExists(entry)) { |
| 125 | + for (final file in listDir( |
| 126 | + entry, |
| 127 | + recursive: true, |
| 128 | + includeHidden: true, |
| 129 | + includeDirs: false, |
| 130 | + )) { |
| 131 | + sum += tryStatFile(file)?.size ?? 0; |
| 132 | + } |
| 133 | + } else { |
| 134 | + sum += tryStatFile(entry)?.size ?? 0; |
| 135 | + } |
| 136 | + } |
| 137 | + if (sum == 0) { |
| 138 | + log.message('No unused cache entries found.'); |
| 139 | + return; |
| 140 | + } |
| 141 | + log.message(''); |
| 142 | + log.message( |
| 143 | + ''' |
| 144 | +All other projects ${dryRun ? 'would' : 'will'} need to run `$topLevelProgram pub get` again to work correctly.''', |
| 145 | + ); |
| 146 | + log.message( |
| 147 | + '${dryRun ? 'Would' : 'Will'} recover ${readableFileSize(sum)}.', |
| 148 | + ); |
| 149 | + if (dryRun) { |
| 150 | + log.message('Would delete:'); |
| 151 | + for (final path in allPathsToGC..sort()) { |
| 152 | + log.message(path); |
| 153 | + } |
| 154 | + } else if (argResults.flag('force') || |
| 155 | + await confirm('Are you sure you want to continue?')) { |
| 156 | + await log.progress('Deleting unused cache entries', () async { |
| 157 | + for (final path in allPathsToGC..sort()) { |
| 158 | + tryDeleteEntry(path); |
| 159 | + } |
| 160 | + }); |
| 161 | + } |
| 162 | + } |
| 163 | +} |
0 commit comments